diff --git a/.gitattributes b/.gitattributes
index a6344aac8c09253b3b630fb776ae94478aa0275b..f15a0a525a6bd37feeb63f861913a8888ce061a6 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
+examples/desi.mp4 filter=lfs diff=lfs merge=lfs -text
+examples/desi.png filter=lfs diff=lfs merge=lfs -text
+examples/man.png filter=lfs diff=lfs merge=lfs -text
+examples/paul.mp4 filter=lfs diff=lfs merge=lfs -text
diff --git a/INSTALL.md b/INSTALL.md
new file mode 100644
index 0000000000000000000000000000000000000000..e75b461705350dc890d2e2c53cf60f2f3965ecb3
--- /dev/null
+++ b/INSTALL.md
@@ -0,0 +1,55 @@
+# Installation Guide
+
+## Install with pip
+
+```bash
+pip install .
+pip install .[dev] # Installe aussi les outils de dev
+```
+
+## Install with Poetry
+
+Ensure you have [Poetry](https://python-poetry.org/docs/#installation) installed on your system.
+
+To install all dependencies:
+
+```bash
+poetry install
+```
+
+### Handling `flash-attn` Installation Issues
+
+If `flash-attn` fails due to **PEP 517 build issues**, you can try one of the following fixes.
+
+#### No-Build-Isolation Installation (Recommended)
+```bash
+poetry run pip install --upgrade pip setuptools wheel
+poetry run pip install flash-attn --no-build-isolation
+poetry install
+```
+
+#### Install from Git (Alternative)
+```bash
+poetry run pip install git+https://github.com/Dao-AILab/flash-attention.git
+```
+
+---
+
+### Running the Model
+
+Once the installation is complete, you can run **Wan2.2** using:
+
+```bash
+poetry run python generate.py --task t2v-A14B --size '1280*720' --ckpt_dir ./Wan2.2-T2V-A14B --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
+```
+
+#### Test
+```bash
+bash tests/test.sh
+```
+
+#### Format
+```bash
+black .
+isort .
+```
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..29f81d812f3e768fa89638d1f72920dbfd1413a8
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..60ba7641abe459e699ec86e224ed07f04385b34e
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,5 @@
+.PHONY: format
+
+format:
+ isort generate.py wan
+ yapf -i -r *.py generate.py wan
diff --git a/README.md b/README.md
index d9f33c7ccd88a5f868b2418640b21dec1308e610..823129d3930a9418ad340e3de9ba475f2d48552e 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,12 @@
----
-title: Wan2.2 Animate ZEROGPU
-emoji: 😻
-colorFrom: indigo
-colorTo: purple
-sdk: gradio
-sdk_version: 5.49.1
-app_file: app.py
-pinned: false
----
-
-Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
+---
+title: Wan2.2 Animate [Local]
+emoji: 🔥
+colorFrom: pink
+colorTo: yellow
+sdk: gradio
+sdk_version: 5.49.1
+app_file: app.py
+pinned: false
+---
+
+Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
diff --git a/app.py b/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ae47f5f0fa18bbf568edb5b77c3d90668c4f450
--- /dev/null
+++ b/app.py
@@ -0,0 +1,546 @@
+import spaces
+from huggingface_hub import snapshot_download, hf_hub_download
+import os
+import subprocess
+import importlib, site
+from PIL import Image
+import uuid
+import shutil
+import time
+import cv2
+from generate import generate, load_model
+import json
+
+# Re-discover all .pth/.egg-link files
+for sitedir in site.getsitepackages():
+ site.addsitedir(sitedir)
+
+# Clear caches so importlib will pick up new modules
+importlib.invalidate_caches()
+
+def sh(cmd): subprocess.check_call(cmd, shell=True)
+
+try:
+ print("Attempting to download and build sam2...")
+
+ print("download sam")
+ sam_dir = snapshot_download(repo_id="alexnasa/sam2")
+
+ @spaces.GPU(duration=450)
+ def install_sam():
+ os.environ["TORCH_CUDA_ARCH_LIST"] = "9.0"
+ sh(f"cd {sam_dir} && python setup.py build_ext --inplace && pip install -e .")
+
+ print("install sam")
+ install_sam()
+
+ # tell Python to re-scan site-packages now that the egg-link exists
+ import importlib, site; site.addsitedir(site.getsitepackages()[0]); importlib.invalidate_caches()
+
+ flash_attention_installed = True
+ print("sam2 installed successfully.")
+
+except Exception as e:
+ print(f"⚠️ Could not install sam2: {e}")
+ print("Continuing without sam2...")
+
+import torch
+print(f"Torch version: {torch.__version__}")
+
+os.environ["PROCESSED_RESULTS"] = f"{os.getcwd()}/processed_results"
+
+import gradio as gr
+
+
+snapshot_download(repo_id="Wan-AI/Wan2.2-Animate-14B", local_dir="./Wan2.2-Animate-14B")
+wan_animate = load_model(True)
+
+
+rc_mapping = {
+ "Video → Ref Image" : False,
+ "Video ← Ref Image" : True
+}
+
+
+def preprocess_video(input_video_path, session_id=None):
+
+ if session_id is None:
+ session_id = uuid.uuid4().hex
+
+ output_dir = os.path.join(os.environ["PROCESSED_RESULTS"], session_id)
+ os.makedirs(output_dir, exist_ok=True)
+
+ process_video_path = os.path.join(output_dir, 'input_video.mp4')
+
+ convert_video_to_30fps_and_clip(input_video_path, process_video_path, crop_width=720, crop_height=1280)
+
+ return process_video_path
+
+def extract_audio_from_video_ffmpeg(video_path, output_wav_path, sample_rate=None):
+ """
+ Extracts the audio track from a video file and saves it as a WAV file.
+
+ Args:
+ video_path (str): Path to the input video file.
+ output_wav_path (str): Path to save the extracted WAV file.
+ sample_rate (int, optional): Output sample rate (e.g., 16000).
+ If None, keep the original.
+ """
+ cmd = [
+ 'ffmpeg',
+ '-i', video_path, # Input video
+ '-vn', # Disable video
+ '-acodec', 'pcm_s16le', # 16-bit PCM (WAV format)
+ '-ac', '1', # Mono channel (use '2' for stereo)
+ '-y', # Overwrite output
+ '-loglevel', 'error' # Cleaner output
+ ]
+
+ # Only add the sample rate option if explicitly specified
+ if sample_rate is not None:
+ cmd.extend(['-ar', str(sample_rate)])
+
+ cmd.append(output_wav_path)
+
+ try:
+ subprocess.run(cmd, check=True, capture_output=True, text=True)
+ except subprocess.CalledProcessError as e:
+ raise RuntimeError(f"ffmpeg failed ({e.returncode}): {e.stderr.strip()}")
+
+
+def combine_video_and_audio_ffmpeg(video_path, audio_path, output_video_path):
+ """
+ Combines a silent MP4 video with a WAV audio file into a single MP4 with sound.
+
+ Args:
+ video_path (str): Path to the silent video file.
+ audio_path (str): Path to the WAV audio file.
+ output_video_path (str): Path to save the output MP4 with audio.
+ """
+ cmd = [
+ 'ffmpeg',
+ '-i', video_path, # Input video
+ '-i', audio_path, # Input audio
+ '-c:v', 'copy', # Copy video without re-encoding
+ '-c:a', 'aac', # Encode audio as AAC (MP4-compatible)
+ '-shortest', # Stop when the shortest stream ends
+ '-y', # Overwrite output
+ '-loglevel', 'error',
+ output_video_path
+ ]
+
+ try:
+ subprocess.run(cmd, check=True, capture_output=True, text=True)
+ except subprocess.CalledProcessError as e:
+ raise RuntimeError(f"ffmpeg failed ({e.returncode}): {e.stderr.strip()}")
+
+
+def convert_video_to_30fps_and_clip(
+ input_video_path,
+ output_video_path,
+ duration_s=2,
+ target_fps=30,
+ crop_width=None,
+ crop_height=None
+):
+ # Get input video dimensions using ffprobe
+ if crop_width and crop_height:
+ probe_cmd = [
+ 'ffprobe', '-v', 'error', '-select_streams', 'v:0',
+ '-show_entries', 'stream=width,height',
+ '-of', 'json', input_video_path
+ ]
+ probe_result = subprocess.run(probe_cmd, capture_output=True, text=True, check=True)
+ video_info = json.loads(probe_result.stdout)
+ w = video_info['streams'][0]['width']
+ h = video_info['streams'][0]['height']
+
+ # Clamp crop size to not exceed actual dimensions
+ crop_width = min(crop_width, w)
+ crop_height = min(crop_height, h)
+
+ # Center crop offsets
+ crop_x = max((w - crop_width) // 2, 0)
+ crop_y = max((h - crop_height) // 2, 0)
+ crop_filter = f"crop={crop_width}:{crop_height}:{crop_x}:{crop_y}"
+ else:
+ crop_filter = None
+
+ cmd = [
+ 'ffmpeg',
+ '-i', input_video_path,
+ '-r', str(target_fps),
+ '-t', str(duration_s),
+ ]
+
+ if crop_filter:
+ cmd += ['-vf', crop_filter]
+
+ cmd += [
+ '-c:v', 'libx264',
+ '-c:a', 'aac',
+ '-strict', 'experimental',
+ '-y',
+ '-loglevel', 'error',
+ output_video_path
+ ]
+
+ try:
+ subprocess.run(cmd, check=True, capture_output=True, text=True)
+ except subprocess.CalledProcessError as e:
+ raise RuntimeError(f"ffmpeg failed ({e.returncode}): {e.stderr.strip()}")
+
+def get_frames_count(video_file):
+
+ # Get video information
+ cap = cv2.VideoCapture(video_file)
+ if not cap.isOpened():
+ error_msg = "Cannot open video file"
+ gr.Warning(error_msg)
+
+ orig_frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+ orig_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
+ orig_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
+
+ cap.release()
+
+ return orig_frame_count
+
+def calculate_time_required(input_video, rc_bool):
+
+ frames_count = get_frames_count(input_video)
+
+ chunks = frames_count // 77 + 1
+
+
+ if rc_bool:
+ pose2d_tracking_duration_s = 75
+ iteration_per_step_s = 13
+ else:
+ pose2d_tracking_duration_s = 50
+ iteration_per_step_s = 12
+
+ time_required = pose2d_tracking_duration_s + iteration_per_step_s * 20 * chunks
+ print(f'for frames_count:{frames_count} doing {chunks} chunks the time_required is {time_required}')
+ return time_required
+
+def update_time_required(input_video, rc_str):
+
+ if input_video is None:
+ return gr.update(value="⌚ Zero GPU Required: --")
+
+ rc_bool = rc_mapping[rc_str]
+
+ duration_s = calculate_time_required(input_video, rc_bool)
+ duration_m = duration_s / 60
+
+ return gr.update(value=f"⌚ Zero GPU Required: ~{duration_s}.0s ({duration_m:.1f} mins)")
+
+def get_duration(input_video, edited_frame, rc_bool, session_id, progress):
+
+ return calculate_time_required(input_video, rc_bool)
+
+
+@spaces.GPU(duration=get_duration)
+def _animate(input_video, edited_frame, rc_bool, session_id = None, progress=gr.Progress(track_tqdm=True),):
+
+ if session_id is None:
+ session_id = uuid.uuid4().hex
+
+ output_dir = os.path.join(os.environ["PROCESSED_RESULTS"], session_id)
+ os.makedirs(output_dir, exist_ok=True)
+
+ preprocess_dir = os.path.join(output_dir, "preprocess_dir")
+ os.makedirs(preprocess_dir, exist_ok=True)
+
+ output_video_path = os.path.join(output_dir, 'result.mp4')
+
+ # --- Measure preprocess time ---
+ start_preprocess = time.time()
+
+ # w = 720
+ # h = 480
+
+ # w = 720
+ # h = 1280
+
+ w = 480
+ h = 832
+
+ # w = 480
+ # h = 720
+
+ tag_string = "retarget_flag"
+
+ if rc_bool:
+ tag_string = "replace_flag"
+
+ sh("python ./wan/modules/animate/preprocess/preprocess_data.py "
+ "--ckpt_path ./Wan2.2-Animate-14B/process_checkpoint "
+ f"--video_path {input_video} "
+ f"--refer_path {edited_frame} "
+ f"--save_path {preprocess_dir} "
+ f"--resolution_area {w} {h} --{tag_string} "
+ )
+
+ preprocess_time = time.time() - start_preprocess
+ print(f"Preprocess took {preprocess_time:.2f} seconds")
+
+ # --- Measure generate time ---
+ start_generate = time.time()
+
+ generate(wan_animate, preprocess_dir, output_video_path, rc_bool)
+
+ generate_time = time.time() - start_generate
+ print(f"Generate took {generate_time:.2f} seconds")
+
+ # --- Optional total time ---
+ total_time = preprocess_time + generate_time
+ print(f"Total time: {total_time:.2f} seconds")
+
+ return output_video_path
+
+def animate_scene(input_video, edited_frame, rc_str, session_id = None, progress=gr.Progress(track_tqdm=True),):
+
+ if not input_video:
+ raise gr.Error("Please provide an video")
+
+ if not edited_frame:
+ raise gr.Error("Please provide an image")
+
+ if session_id is None:
+ session_id = uuid.uuid4().hex
+
+ rc_bool = rc_mapping[rc_str]
+
+ output_dir = os.path.join(os.environ["PROCESSED_RESULTS"], session_id)
+ os.makedirs(output_dir, exist_ok=True)
+
+ input_audio_path = os.path.join(output_dir, 'input_audio.wav')
+
+ extract_audio_from_video_ffmpeg(input_video, input_audio_path)
+
+ output_video_path = _animate(input_video, edited_frame, rc_bool, session_id, progress)
+
+ final_video_path = os.path.join(output_dir, 'final_result.mp4')
+
+ preprocess_dir = os.path.join(output_dir, "preprocess_dir")
+ pose_video = os.path.join(preprocess_dir, 'src_pose.mp4')
+
+ if rc_bool:
+ mask_video = os.path.join(preprocess_dir, 'src_mask.mp4')
+ bg_video = os.path.join(preprocess_dir, 'src_bg.mp4')
+ face_video = os.path.join(preprocess_dir, 'src_face.mp4')
+ else:
+ mask_video = os.path.join(preprocess_dir, 'src_pose.mp4')
+ bg_video = os.path.join(preprocess_dir, 'src_pose.mp4')
+ face_video = os.path.join(preprocess_dir, 'src_pose.mp4')
+
+ combine_video_and_audio_ffmpeg(output_video_path, input_audio_path, final_video_path)
+
+ return final_video_path, pose_video, bg_video, mask_video, face_video
+
+css = """
+ #col-container {
+ margin: 0 auto;
+ max-width: 1600px;
+ }
+
+ #step-column {
+ padding: 20px;
+ border-radius: 8px;
+ box-shadow: var(--card-shadow);
+ margin: 10px;
+ }
+
+ #col-showcase {
+ margin: 0 auto;
+ max-width: 1100px;
+ }
+
+ .button-gradient {
+ background: linear-gradient(45deg, rgb(255, 65, 108), rgb(255, 75, 43), rgb(255, 155, 0), rgb(255, 65, 108)) 0% 0% / 400% 400%;
+ border: none;
+ padding: 14px 28px;
+ font-size: 16px;
+ font-weight: bold;
+ color: white;
+ border-radius: 10px;
+ cursor: pointer;
+ transition: 0.3s ease-in-out;
+ animation: 2s linear 0s infinite normal none running gradientAnimation;
+ box-shadow: rgba(255, 65, 108, 0.6) 0px 4px 10px;
+ }
+
+ .toggle-container {
+ display: inline-flex;
+ background-color: #ffd6ff; /* light pink background */
+ border-radius: 9999px;
+ padding: 4px;
+ position: relative;
+ width: fit-content;
+ font-family: sans-serif;
+ }
+
+ .toggle-container input[type="radio"] {
+ display: none;
+ }
+
+ .toggle-container label {
+ position: relative;
+ z-index: 2;
+ flex: 1;
+ text-align: center;
+ font-weight: 700;
+ color: #4b2ab5; /* dark purple text for unselected */
+ padding: 6px 22px;
+ border-radius: 9999px;
+ cursor: pointer;
+ transition: color 0.25s ease;
+ }
+
+ /* Moving highlight */
+ .toggle-highlight {
+ position: absolute;
+ top: 4px;
+ left: 4px;
+ width: calc(50% - 4px);
+ height: calc(100% - 8px);
+ background-color: #4b2ab5; /* dark purple background */
+ border-radius: 9999px;
+ transition: transform 0.25s ease;
+ z-index: 1;
+ }
+
+ /* When "True" is checked */
+ #true:checked ~ label[for="true"] {
+ color: #ffd6ff; /* light pink text */
+ }
+
+ /* When "False" is checked */
+ #false:checked ~ label[for="false"] {
+ color: #ffd6ff; /* light pink text */
+ }
+
+ /* Move highlight to right side when False is checked */
+ #false:checked ~ .toggle-highlight {
+ transform: translateX(100%);
+ }
+ """
+def start_session(request: gr.Request):
+
+ return request.session_hash
+
+def cleanup(request: gr.Request):
+
+ sid = request.session_hash
+
+ if sid:
+ d1 = os.path.join(os.environ["PROCESSED_RESULTS"], sid)
+ shutil.rmtree(d1, ignore_errors=True)
+
+with gr.Blocks(css=css, title="Wan 2.2 Animate --replace", theme=gr.themes.Ocean()) as demo:
+
+ session_state = gr.State()
+ demo.load(start_session, outputs=[session_state])
+
+ with gr.Column(elem_id="col-container"):
+ with gr.Row():
+ gr.HTML(
+ """
+
+
+ Wan2.2-Animate-14B
+
+
+ [Model]
+
+
+
+ HF Space By:
+
+
+
+
+
+ """
+ )
+ with gr.Row():
+ with gr.Column(elem_id="step-column"):
+ gr.HTML("""
+
+ 1. Upload a Video
+
+ """)
+ input_video = gr.Video(label="Input Video", height=512)
+
+
+ with gr.Column(elem_id="step-column"):
+ gr.HTML("""
+
+ 2. Upload a Ref Image
+
+ """)
+ edited_frame = gr.Image(label="Ref Image", type="filepath", height=512)
+ gr.HTML("""
+
+ 3. Choose Mode
+
+ """)
+ replace_character_string = gr.Radio(
+ ["Video → Ref Image", "Video ← Ref Image"], value="Video → Ref Image", show_label=False
+ )
+
+ with gr.Column(elem_id="step-column"):
+ gr.HTML("""
+
+ 4. Wan Animate it!
+
+ """)
+ output_video = gr.Video(label="Edited Video", height=512)
+
+ time_required = gr.Text(value="⌚ Zero GPU Required: --", show_label=False)
+ action_button = gr.Button("Wan Animate 🦆", variant='primary', elem_classes="button-gradient")
+
+ with gr.Accordion("Preprocessed Data", open=False, visible=False):
+ pose_video = gr.Video(label="Pose Video", height=512)
+ bg_video = gr.Video(label="Background Video", height=512)
+ face_video = gr.Video(label="Face Video", height=512)
+ mask_video = gr.Video(label="Mask Video", height=512)
+
+ with gr.Row():
+ with gr.Column(elem_id="col-showcase"):
+
+ gr.Examples(
+ examples=[
+
+ [
+ "./examples/desi.mp4",
+ "./examples/desi.png",
+ "Video ← Ref Image"
+ ],
+
+ [
+ "./examples/paul.mp4",
+ "./examples/man.png",
+ "Video → Ref Image"
+ ],
+
+
+ ],
+ inputs=[input_video, edited_frame, replace_character_string],
+ outputs=[output_video, pose_video, bg_video, mask_video, face_video],
+ fn=animate_scene,
+ cache_examples=True,
+ )
+
+ action_button.click(fn=animate_scene, inputs=[input_video, edited_frame, replace_character_string, session_state], outputs=[output_video, pose_video, bg_video, mask_video, face_video])
+
+ input_video.upload(preprocess_video, inputs=[input_video, session_state], outputs=[input_video]).then(update_time_required, inputs=[input_video, replace_character_string], outputs=[time_required])
+ replace_character_string.change(update_time_required, inputs=[input_video, replace_character_string], outputs=[time_required])
+
+if __name__ == "__main__":
+ demo.queue()
+ demo.unload(cleanup)
+ demo.launch(ssr_mode=False, share=True)
+
\ No newline at end of file
diff --git a/examples/desi.mp4 b/examples/desi.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..afa1422fcd6e029478f8950e3954aefa8d1d59d1
--- /dev/null
+++ b/examples/desi.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e02e84151e5625fb3863ebdf65dfab06940afac5fbd471db3b46a4ebd84b248d
+size 551595
diff --git a/examples/desi.png b/examples/desi.png
new file mode 100644
index 0000000000000000000000000000000000000000..c463facd3e16f1b2180248ac5a05a0ab92d0c908
--- /dev/null
+++ b/examples/desi.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3f1a6ac41049380ddb43dcfb9efe1a0b6c561c4bb4132332fe07a82df263df66
+size 477051
diff --git a/examples/man.png b/examples/man.png
new file mode 100644
index 0000000000000000000000000000000000000000..cbd90f73cf8f8be263bc2ebbc3ebb3d9346acdba
--- /dev/null
+++ b/examples/man.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6dc2c61f01a0290a8478fe3b494cf69ca054b2502b00b0be8c68a42ac544d5b5
+size 2502316
diff --git a/examples/paul.mp4 b/examples/paul.mp4
new file mode 100644
index 0000000000000000000000000000000000000000..3b0696eb31f1ec7a3930d99ecc6a1ea950dff0f4
--- /dev/null
+++ b/examples/paul.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fb065c2d24bff8a49955389f94c05c80d39638410dad8082f7e0eb7f2dc5c672
+size 1029922
diff --git a/generate.py b/generate.py
new file mode 100644
index 0000000000000000000000000000000000000000..200e0bb6d8cba8367d50c10aa316dc70d209103a
--- /dev/null
+++ b/generate.py
@@ -0,0 +1,236 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import argparse
+import logging
+import os
+import sys
+import warnings
+from datetime import datetime
+
+warnings.filterwarnings('ignore')
+
+import random
+
+import torch
+import torch.distributed as dist
+from PIL import Image
+
+import wan
+from wan.configs import MAX_AREA_CONFIGS, SIZE_CONFIGS, SUPPORTED_SIZES, WAN_CONFIGS
+from wan.distributed.util import init_distributed_group
+from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
+from wan.utils.utils import merge_video_audio, save_video, str2bool
+
+
+EXAMPLE_PROMPT = {
+ "t2v-A14B": {
+ "prompt":
+ "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
+ },
+ "i2v-A14B": {
+ "prompt":
+ "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside.",
+ "image":
+ "examples/i2v_input.JPG",
+ },
+ "ti2v-5B": {
+ "prompt":
+ "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
+ },
+ "animate-14B": {
+ "prompt": "视频中的人在做动作",
+ "video": "",
+ "pose": "",
+ "mask": "",
+ },
+ "s2v-14B": {
+ "prompt":
+ "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside.",
+ "image":
+ "examples/i2v_input.JPG",
+ "audio":
+ "examples/talk.wav",
+ "tts_prompt_audio":
+ "examples/zero_shot_prompt.wav",
+ "tts_prompt_text":
+ "希望你以后能够做的比我还好呦。",
+ "tts_text":
+ "收到好友从远方寄来的生日礼物,那份意外的惊喜与深深的祝福让我心中充满了甜蜜的快乐,笑容如花儿般绽放。"
+ },
+}
+
+
+def _validate_args(args):
+ # Basic check
+ assert args.ckpt_dir is not None, "Please specify the checkpoint directory."
+ assert args.task in WAN_CONFIGS, f"Unsupport task: {args.task}"
+ assert args.task in EXAMPLE_PROMPT, f"Unsupport task: {args.task}"
+
+ if args.prompt is None:
+ args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
+ if args.image is None and "image" in EXAMPLE_PROMPT[args.task]:
+ args.image = EXAMPLE_PROMPT[args.task]["image"]
+ if args.audio is None and args.enable_tts is False and "audio" in EXAMPLE_PROMPT[args.task]:
+ args.audio = EXAMPLE_PROMPT[args.task]["audio"]
+ if (args.tts_prompt_audio is None or args.tts_text is None) and args.enable_tts is True and "audio" in EXAMPLE_PROMPT[args.task]:
+ args.tts_prompt_audio = EXAMPLE_PROMPT[args.task]["tts_prompt_audio"]
+ args.tts_prompt_text = EXAMPLE_PROMPT[args.task]["tts_prompt_text"]
+ args.tts_text = EXAMPLE_PROMPT[args.task]["tts_text"]
+
+ if args.task == "i2v-A14B":
+ assert args.image is not None, "Please specify the image path for i2v."
+
+ cfg = WAN_CONFIGS[args.task]
+
+ if args.sample_steps is None:
+ args.sample_steps = cfg.sample_steps
+
+ if args.sample_shift is None:
+ args.sample_shift = cfg.sample_shift
+
+ if args.sample_guide_scale is None:
+ args.sample_guide_scale = cfg.sample_guide_scale
+
+ if args.frame_num is None:
+ args.frame_num = cfg.frame_num
+
+ args.base_seed = args.base_seed if args.base_seed >= 0 else random.randint(
+ 0, sys.maxsize)
+ # Size check
+ if not 's2v' in args.task:
+ assert args.size in SUPPORTED_SIZES[
+ args.
+ task], f"Unsupport size {args.size} for task {args.task}, supported sizes are: {', '.join(SUPPORTED_SIZES[args.task])}"
+
+
+class _Args:
+ pass
+
+def _parse_args():
+ args = _Args()
+
+ # core generation options
+ args.task = "animate-14B"
+ # args.size = "1280*720"
+ args.size = "720*1280"
+ args.frame_num = None
+ args.ckpt_dir = "./Wan2.2-Animate-14B/"
+ args.offload_model = True
+ args.ulysses_size = 1
+ args.t5_fsdp = False
+ args.t5_cpu = False
+ args.dit_fsdp = False
+ args.prompt = None
+ args.use_prompt_extend = False
+ args.prompt_extend_method = "local_qwen" # ["dashscope", "local_qwen"]
+ args.prompt_extend_model = None
+ args.prompt_extend_target_lang = "zh" # ["zh", "en"]
+ args.base_seed = 0
+ args.image = None
+ args.sample_solver = "unipc" # ['unipc', 'dpm++']
+ args.sample_steps = None
+ args.sample_shift = None
+ args.sample_guide_scale = None
+ args.convert_model_dtype = False
+
+ # animate
+ args.refert_num = 1
+
+ # s2v-only
+ args.num_clip = None
+ args.audio = None
+ args.enable_tts = False
+ args.tts_prompt_audio = None
+ args.tts_prompt_text = None
+ args.tts_text = None
+ args.pose_video = None
+ args.start_from_ref = False
+ args.infer_frames = 80
+
+ _validate_args(args)
+ return args
+
+
+
+def _init_logging(rank):
+ # logging
+ if rank == 0:
+ # set format
+ logging.basicConfig(
+ level=logging.INFO,
+ format="[%(asctime)s] %(levelname)s: %(message)s",
+ handlers=[logging.StreamHandler(stream=sys.stdout)])
+ else:
+ logging.basicConfig(level=logging.ERROR)
+
+def load_model(use_relighting_lora = False):
+
+ cfg = WAN_CONFIGS["animate-14B"]
+
+ return wan.WanAnimate(
+ config=cfg,
+ checkpoint_dir="./Wan2.2-Animate-14B/",
+ device_id=0,
+ rank=0,
+ t5_fsdp=False,
+ dit_fsdp=False,
+ use_sp=False,
+ t5_cpu=False,
+ convert_model_dtype=False,
+ use_relighting_lora=use_relighting_lora
+ )
+
+def generate(wan_animate, preprocess_dir, save_file, replace_flag = False):
+ args = _parse_args()
+ rank = int(os.getenv("RANK", 0))
+ world_size = int(os.getenv("WORLD_SIZE", 1))
+ local_rank = int(os.getenv("LOCAL_RANK", 0))
+ device = local_rank
+ _init_logging(rank)
+
+ cfg = WAN_CONFIGS[args.task]
+
+ logging.info(f"Input prompt: {args.prompt}")
+ img = None
+ if args.image is not None:
+ img = Image.open(args.image).convert("RGB")
+ logging.info(f"Input image: {args.image}")
+
+ print(f'rank:{rank}')
+
+
+
+ logging.info(f"Generating video ...")
+ video = wan_animate.generate(
+ src_root_path=preprocess_dir,
+ replace_flag=replace_flag,
+ refert_num = args.refert_num,
+ clip_len=args.frame_num,
+ shift=args.sample_shift,
+ sample_solver=args.sample_solver,
+ sampling_steps=args.sample_steps,
+ guide_scale=args.sample_guide_scale,
+ seed=args.base_seed,
+ offload_model=args.offload_model)
+ if rank == 0:
+
+ save_video(
+ tensor=video[None],
+ save_file=save_file,
+ fps=cfg.sample_fps,
+ nrow=1,
+ normalize=True,
+ value_range=(-1, 1))
+ # if "s2v" in args.task:
+ # if args.enable_tts is False:
+ # merge_video_audio(video_path=args.save_file, audio_path=args.audio)
+ # else:
+ # merge_video_audio(video_path=args.save_file, audio_path="tts.wav")
+ del video
+
+ torch.cuda.synchronize()
+ if dist.is_initialized():
+ dist.barrier()
+ dist.destroy_process_group()
+
+ logging.info("Finished.")
+
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..4dbda7fa31305d581e6f9b501499d784013af455
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,66 @@
+[build-system]
+requires = ["setuptools>=61.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "wan"
+version = "2.2.0"
+description = "Wan: Open and Advanced Large-Scale Video Generative Models"
+authors = [
+ { name = "Wan Team", email = "wan.ai@alibabacloud.com" }
+]
+license = { file = "LICENSE.txt" }
+readme = "README.md"
+requires-python = ">=3.10,<4.0"
+dependencies = [
+ "torch>=2.4.0",
+ "torchvision>=0.19.0",
+ "opencv-python>=4.9.0.80",
+ "diffusers>=0.31.0",
+ "transformers>=4.49.0",
+ "tokenizers>=0.20.3",
+ "accelerate>=1.1.1",
+ "tqdm",
+ "imageio",
+ "easydict",
+ "ftfy",
+ "dashscope",
+ "imageio-ffmpeg",
+ "flash_attn",
+ "numpy>=1.23.5,<2"
+]
+
+[project.optional-dependencies]
+dev = [
+ "pytest",
+ "black",
+ "flake8",
+ "isort",
+ "mypy",
+ "huggingface-hub[cli]"
+]
+
+[project.urls]
+homepage = "https://wanxai.com"
+documentation = "https://github.com/Wan-Video/Wan2.2"
+repository = "https://github.com/Wan-Video/Wan2.2"
+huggingface = "https://huggingface.co/Wan-AI/"
+modelscope = "https://modelscope.cn/organization/Wan-AI"
+discord = "https://discord.gg/p5XbdQV7"
+
+[tool.setuptools]
+packages = ["wan"]
+
+[tool.setuptools.package-data]
+"wan" = ["**/*.py"]
+
+[tool.black]
+line-length = 88
+
+[tool.isort]
+profile = "black"
+
+[tool.mypy]
+strict = true
+
+
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..023d8bf01fef097c23e629a1e0946c3de14e4fc7
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,31 @@
+torch==2.8.0
+decord
+peft
+pandas
+matplotlib
+loguru
+sentencepiece
+dashscope
+ftfy
+diffusers
+opencv-python
+moviepy
+torchvision
+torchaudio
+transformers
+tokenizers
+accelerate
+tqdm
+imageio[ffmpeg]
+easydict
+imageio-ffmpeg
+numpy>=1.23.5,<2
+hydra-core
+iopath
+pytest
+pillow
+fvcore
+librosa
+flash-attn
+onnxruntime-gpu
+flash-attn-3 @ https://huggingface.co/alexnasa/flash-attn-3/resolve/main/128/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl
\ No newline at end of file
diff --git a/wan/__init__.py b/wan/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..70ad365272f0e03608d9e8a7765f1a9ba2b34942
--- /dev/null
+++ b/wan/__init__.py
@@ -0,0 +1,7 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from . import configs, distributed, modules
+from .image2video import WanI2V
+from .speech2video import WanS2V
+from .text2video import WanT2V
+from .textimage2video import WanTI2V
+from .animate import WanAnimate
\ No newline at end of file
diff --git a/wan/animate.py b/wan/animate.py
new file mode 100644
index 0000000000000000000000000000000000000000..510fd2d7ffc059aa3304335d8174cb34058633a3
--- /dev/null
+++ b/wan/animate.py
@@ -0,0 +1,653 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import logging
+import math
+import os
+import cv2
+import types
+from copy import deepcopy
+from functools import partial
+from einops import rearrange
+import numpy as np
+import torch
+
+import torch.distributed as dist
+from peft import set_peft_model_state_dict
+from decord import VideoReader
+from tqdm import tqdm
+import torch.nn.functional as F
+from .distributed.fsdp import shard_model
+from .distributed.sequence_parallel import sp_attn_forward, sp_dit_forward
+from .distributed.util import get_world_size
+
+from .modules.animate import WanAnimateModel
+from .modules.animate import CLIPModel
+from .modules.t5 import T5EncoderModel
+from .modules.vae2_1 import Wan2_1_VAE
+from .modules.animate.animate_utils import TensorList, get_loraconfig
+from .utils.fm_solvers import (
+ FlowDPMSolverMultistepScheduler,
+ get_sampling_sigmas,
+ retrieve_timesteps,
+)
+from .utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
+
+
+
+class WanAnimate:
+
+ def __init__(
+ self,
+ config,
+ checkpoint_dir,
+ device_id=0,
+ rank=0,
+ t5_fsdp=False,
+ dit_fsdp=False,
+ use_sp=False,
+ t5_cpu=False,
+ init_on_cpu=True,
+ convert_model_dtype=False,
+ use_relighting_lora=False
+ ):
+ r"""
+ Initializes the generation model components.
+
+ Args:
+ config (EasyDict):
+ Object containing model parameters initialized from config.py
+ checkpoint_dir (`str`):
+ Path to directory containing model checkpoints
+ device_id (`int`, *optional*, defaults to 0):
+ Id of target GPU device
+ rank (`int`, *optional*, defaults to 0):
+ Process rank for distributed training
+ t5_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for T5 model
+ dit_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for DiT model
+ use_sp (`bool`, *optional*, defaults to False):
+ Enable distribution strategy of sequence parallel.
+ t5_cpu (`bool`, *optional*, defaults to False):
+ Whether to place T5 model on CPU. Only works without t5_fsdp.
+ init_on_cpu (`bool`, *optional*, defaults to True):
+ Enable initializing Transformer Model on CPU. Only works without FSDP or USP.
+ convert_model_dtype (`bool`, *optional*, defaults to False):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+ use_relighting_lora (`bool`, *optional*, defaults to False):
+ Whether to use relighting lora for character replacement.
+ """
+ self.device = torch.device(f"cuda:{device_id}")
+ self.config = config
+ self.rank = rank
+ self.t5_cpu = t5_cpu
+ self.init_on_cpu = init_on_cpu
+
+ self.num_train_timesteps = config.num_train_timesteps
+ self.param_dtype = config.param_dtype
+
+ if t5_fsdp or dit_fsdp or use_sp:
+ self.init_on_cpu = False
+
+ shard_fn = partial(shard_model, device_id=device_id)
+ self.text_encoder = T5EncoderModel(
+ text_len=config.text_len,
+ dtype=config.t5_dtype,
+ device=torch.device('cpu'),
+ checkpoint_path=os.path.join(checkpoint_dir, config.t5_checkpoint),
+ tokenizer_path=os.path.join(checkpoint_dir, config.t5_tokenizer),
+ shard_fn=shard_fn if t5_fsdp else None,
+ )
+
+ self.clip = CLIPModel(
+ dtype=torch.float16,
+ device=self.device,
+ checkpoint_path=os.path.join(checkpoint_dir,
+ config.clip_checkpoint),
+ tokenizer_path=os.path.join(checkpoint_dir, config.clip_tokenizer))
+
+ self.vae = Wan2_1_VAE(
+ vae_pth=os.path.join(checkpoint_dir, config.vae_checkpoint),
+ device=self.device)
+
+ logging.info(f"Creating WanAnimate from {checkpoint_dir}")
+
+ if not dit_fsdp:
+ self.noise_model = WanAnimateModel.from_pretrained(
+ checkpoint_dir,
+ torch_dtype=self.param_dtype,
+ device_map=self.device)
+ else:
+ self.noise_model = WanAnimateModel.from_pretrained(
+ checkpoint_dir, torch_dtype=self.param_dtype)
+
+ self.noise_model = self._configure_model(
+ model=self.noise_model,
+ use_sp=use_sp,
+ dit_fsdp=dit_fsdp,
+ shard_fn=shard_fn,
+ convert_model_dtype=convert_model_dtype,
+ use_lora=use_relighting_lora,
+ checkpoint_dir=checkpoint_dir,
+ config=config
+ )
+
+ if use_sp:
+ self.sp_size = get_world_size()
+ else:
+ self.sp_size = 1
+
+ self.sample_neg_prompt = config.sample_neg_prompt
+ self.sample_prompt = config.prompt
+
+
+ def _configure_model(self, model, use_sp, dit_fsdp, shard_fn,
+ convert_model_dtype, use_lora, checkpoint_dir, config):
+ """
+ Configures a model object. This includes setting evaluation modes,
+ applying distributed parallel strategy, and handling device placement.
+
+ Args:
+ model (torch.nn.Module):
+ The model instance to configure.
+ use_sp (`bool`):
+ Enable distribution strategy of sequence parallel.
+ dit_fsdp (`bool`):
+ Enable FSDP sharding for DiT model.
+ shard_fn (callable):
+ The function to apply FSDP sharding.
+ convert_model_dtype (`bool`):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+
+ Returns:
+ torch.nn.Module:
+ The configured model.
+ """
+ model.eval().requires_grad_(False)
+
+ if use_sp:
+ for block in model.blocks:
+ block.self_attn.forward = types.MethodType(
+ sp_attn_forward, block.self_attn)
+
+ model.use_context_parallel = True
+
+ if dist.is_initialized():
+ dist.barrier()
+
+ if use_lora:
+ logging.info("Loading Relighting Lora. ")
+ lora_config = get_loraconfig(
+ transformer=model,
+ rank=128,
+ alpha=128
+ )
+ model.add_adapter(lora_config)
+ lora_path = os.path.join(checkpoint_dir, config.lora_checkpoint)
+ peft_state_dict = torch.load(lora_path)["state_dict"]
+ set_peft_model_state_dict(model, peft_state_dict)
+
+ if dit_fsdp:
+ model = shard_fn(model, use_lora=use_lora)
+ else:
+ if convert_model_dtype:
+ model.to(self.param_dtype)
+ if not self.init_on_cpu:
+ model.to(self.device)
+
+ return model
+
+ def inputs_padding(self, array, target_len):
+ idx = 0
+ flip = False
+ target_array = []
+ while len(target_array) < target_len:
+ target_array.append(deepcopy(array[idx]))
+ if flip:
+ idx -= 1
+ else:
+ idx += 1
+ if idx == 0 or idx == len(array) - 1:
+ flip = not flip
+ return target_array[:target_len]
+
+ def get_valid_len(self, real_len, clip_len=81, overlap=1):
+ real_clip_len = clip_len - overlap
+ last_clip_num = (real_len - overlap) % real_clip_len
+ if last_clip_num == 0:
+ extra = 0
+ else:
+ extra = real_clip_len - last_clip_num
+ target_len = real_len + extra
+ return target_len
+
+
+ def get_i2v_mask(self, lat_t, lat_h, lat_w, mask_len=1, mask_pixel_values=None, device="cuda"):
+ if mask_pixel_values is None:
+ msk = torch.zeros(1, (lat_t-1) * 4 + 1, lat_h, lat_w, device=device)
+ else:
+ msk = mask_pixel_values.clone()
+ msk[:, :mask_len] = 1
+ msk = torch.concat([torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]], dim=1)
+ msk = msk.view(1, msk.shape[1] // 4, 4, lat_h, lat_w)
+ msk = msk.transpose(1, 2)[0]
+ return msk
+
+ def padding_resize(self, img_ori, height=512, width=512, padding_color=(0, 0, 0), interpolation=cv2.INTER_LINEAR):
+ ori_height = img_ori.shape[0]
+ ori_width = img_ori.shape[1]
+ channel = img_ori.shape[2]
+
+ img_pad = np.zeros((height, width, channel))
+ if channel == 1:
+ img_pad[:, :, 0] = padding_color[0]
+ else:
+ img_pad[:, :, 0] = padding_color[0]
+ img_pad[:, :, 1] = padding_color[1]
+ img_pad[:, :, 2] = padding_color[2]
+
+ if (ori_height / ori_width) > (height / width):
+ new_width = int(height / ori_height * ori_width)
+ img = cv2.resize(img_ori, (new_width, height), interpolation=interpolation)
+ padding = int((width - new_width) / 2)
+ if len(img.shape) == 2:
+ img = img[:, :, np.newaxis]
+ img_pad[:, padding: padding + new_width, :] = img
+ else:
+ new_height = int(width / ori_width * ori_height)
+ img = cv2.resize(img_ori, (width, new_height), interpolation=interpolation)
+ padding = int((height - new_height) / 2)
+ if len(img.shape) == 2:
+ img = img[:, :, np.newaxis]
+ img_pad[padding: padding + new_height, :, :] = img
+
+ img_pad = np.uint8(img_pad)
+
+ return img_pad
+
+ def prepare_source(self, src_pose_path, src_face_path, src_ref_path):
+ pose_video_reader = VideoReader(src_pose_path)
+ pose_len = len(pose_video_reader)
+ pose_idxs = list(range(pose_len))
+ cond_images = pose_video_reader.get_batch(pose_idxs).asnumpy()
+
+ face_video_reader = VideoReader(src_face_path)
+ face_len = len(face_video_reader)
+ face_idxs = list(range(face_len))
+ face_images = face_video_reader.get_batch(face_idxs).asnumpy()
+ height, width = cond_images[0].shape[:2]
+ refer_images = cv2.imread(src_ref_path)[..., ::-1]
+ refer_images = self.padding_resize(refer_images, height=height, width=width)
+ return cond_images, face_images, refer_images
+
+ def prepare_source_for_replace(self, src_bg_path, src_mask_path):
+ bg_video_reader = VideoReader(src_bg_path)
+ bg_len = len(bg_video_reader)
+ bg_idxs = list(range(bg_len))
+ bg_images = bg_video_reader.get_batch(bg_idxs).asnumpy()
+
+ mask_video_reader = VideoReader(src_mask_path)
+ mask_len = len(mask_video_reader)
+ mask_idxs = list(range(mask_len))
+ mask_images = mask_video_reader.get_batch(mask_idxs).asnumpy()
+ mask_images = mask_images[:, :, :, 0] / 255
+ return bg_images, mask_images
+
+ def generate(
+ self,
+ src_root_path,
+ replace_flag=False,
+ clip_len=77,
+ refert_num=1,
+ shift=5.0,
+ sample_solver='dpm++',
+ sampling_steps=20,
+ guide_scale=1,
+ input_prompt="",
+ n_prompt="",
+ seed=-1,
+ offload_model=True,
+ ):
+ r"""
+ Generates video frames from input image using diffusion process.
+
+ Args:
+ src_root_path ('str'):
+ Process output path
+ replace_flag (`bool`, *optional*, defaults to False):
+ Whether to use character replace.
+ clip_len (`int`, *optional*, defaults to 77):
+ How many frames to generate per clips. The number should be 4n+1
+ refert_num (`int`, *optional*, defaults to 1):
+ How many frames used for temporal guidance. Recommended to be 1 or 5.
+ shift (`float`, *optional*, defaults to 5.0):
+ Noise schedule shift parameter.
+ sample_solver (`str`, *optional*, defaults to 'dpm++'):
+ Solver used to sample the video.
+ sampling_steps (`int`, *optional*, defaults to 20):
+ Number of diffusion sampling steps. Higher values improve quality but slow generation
+ guide_scale (`float` or tuple[`float`], *optional*, defaults 1.0):
+ Classifier-free guidance scale. We only use it for expression control.
+ In most cases, it's not necessary and faster generation can be achieved without it.
+ When expression adjustments are needed, you may consider using this feature.
+ input_prompt (`str`):
+ Text prompt for content generation. We don't recommend custom prompts (although they work)
+ n_prompt (`str`, *optional*, defaults to ""):
+ Negative prompt for content exclusion. If not given, use `config.sample_neg_prompt`
+ seed (`int`, *optional*, defaults to -1):
+ Random seed for noise generation. If -1, use random seed
+ offload_model (`bool`, *optional*, defaults to True):
+ If True, offloads models to CPU during generation to save VRAM
+
+ Returns:
+ torch.Tensor:
+ Generated video frames tensor. Dimensions: (C, N, H, W) where:
+ - C: Color channels (3 for RGB)
+ - N: Number of frames
+ - H: Frame height
+ - W: Frame width
+ """
+ assert refert_num == 1 or refert_num == 5, "refert_num should be 1 or 5."
+
+ seed_g = torch.Generator(device=self.device)
+ seed_g.manual_seed(seed)
+
+
+ if n_prompt == "":
+ n_prompt = self.sample_neg_prompt
+
+ if input_prompt == "":
+ input_prompt = self.sample_prompt
+
+ src_pose_path = os.path.join(src_root_path, "src_pose.mp4")
+ src_face_path = os.path.join(src_root_path, "src_face.mp4")
+ src_ref_path = os.path.join(src_root_path, "src_ref.png")
+
+ cond_images, face_images, refer_images = self.prepare_source(src_pose_path=src_pose_path, src_face_path=src_face_path, src_ref_path=src_ref_path)
+
+ if not self.t5_cpu:
+ self.text_encoder.model.to(self.device)
+ context = self.text_encoder([input_prompt], self.device)
+ context_null = self.text_encoder([n_prompt], self.device)
+ if offload_model:
+ self.text_encoder.model.cpu()
+ else:
+ context = self.text_encoder([input_prompt], torch.device('cpu'))
+ context_null = self.text_encoder([n_prompt], torch.device('cpu'))
+ context = [t.to(self.device) for t in context]
+ context_null = [t.to(self.device) for t in context_null]
+
+ real_frame_len = len(cond_images)
+ target_len = self.get_valid_len(real_frame_len, clip_len, overlap=refert_num)
+ logging.info('real frames: {} target frames: {}'.format(real_frame_len, target_len))
+ cond_images = self.inputs_padding(cond_images, target_len)
+ face_images = self.inputs_padding(face_images, target_len)
+
+ if replace_flag:
+ src_bg_path = os.path.join(src_root_path, "src_bg.mp4")
+ src_mask_path = os.path.join(src_root_path, "src_mask.mp4")
+ bg_images, mask_images = self.prepare_source_for_replace(src_bg_path, src_mask_path)
+ bg_images = self.inputs_padding(bg_images, target_len)
+ mask_images = self.inputs_padding(mask_images, target_len)
+ self.noise_model.disable_adapters()
+ else:
+ self.noise_model.disable_adapters()
+
+
+ height, width = refer_images.shape[:2]
+ start = 0
+ end = clip_len
+ all_out_frames = []
+ while True:
+ if start + refert_num >= len(cond_images):
+ break
+
+ if start == 0:
+ mask_reft_len = 0
+ else:
+ mask_reft_len = refert_num
+
+ batch = {
+ "conditioning_pixel_values": torch.zeros(1, 3, clip_len, height, width),
+ "bg_pixel_values": torch.zeros(1, 3, clip_len, height, width),
+ "mask_pixel_values": torch.zeros(1, 1, clip_len, height, width),
+ "face_pixel_values": torch.zeros(1, 3, clip_len, 512, 512),
+ "refer_pixel_values": torch.zeros(1, 3, height, width),
+ "refer_t_pixel_values": torch.zeros(refert_num, 3, height, width)
+ }
+
+ batch["conditioning_pixel_values"] = rearrange(
+ torch.tensor(np.stack(cond_images[start:end]) / 127.5 - 1),
+ "t h w c -> 1 c t h w",
+ )
+ batch["face_pixel_values"] = rearrange(
+ torch.tensor(np.stack(face_images[start:end]) / 127.5 - 1),
+ "t h w c -> 1 c t h w",
+ )
+
+ batch["refer_pixel_values"] = rearrange(
+ torch.tensor(refer_images / 127.5 - 1), "h w c -> 1 c h w"
+ )
+
+ if start > 0:
+ batch["refer_t_pixel_values"] = rearrange(
+ out_frames[0, :, -refert_num:].clone().detach(),
+ "c t h w -> t c h w",
+ )
+
+ batch["refer_t_pixel_values"] = rearrange(batch["refer_t_pixel_values"],
+ "t c h w -> 1 c t h w",
+ )
+
+ if replace_flag:
+ batch["bg_pixel_values"] = rearrange(
+ torch.tensor(np.stack(bg_images[start:end]) / 127.5 - 1),
+ "t h w c -> 1 c t h w",
+ )
+
+ batch["mask_pixel_values"] = rearrange(
+ torch.tensor(np.stack(mask_images[start:end])[:, :, :, None]),
+ "t h w c -> 1 t c h w",
+ )
+
+
+ for key, value in batch.items():
+ if isinstance(value, torch.Tensor):
+ batch[key] = value.to(device=self.device, dtype=torch.bfloat16)
+
+ ref_pixel_values = batch["refer_pixel_values"]
+ refer_t_pixel_values = batch["refer_t_pixel_values"]
+ conditioning_pixel_values = batch["conditioning_pixel_values"]
+ face_pixel_values = batch["face_pixel_values"]
+
+ B, _, H, W = ref_pixel_values.shape
+ T = clip_len
+ lat_h = H // 8
+ lat_w = W // 8
+ lat_t = T // 4 + 1
+ target_shape = [lat_t + 1, lat_h, lat_w]
+ noise = [
+ torch.randn(
+ 16,
+ target_shape[0],
+ target_shape[1],
+ target_shape[2],
+ dtype=torch.float32,
+ device=self.device,
+ generator=seed_g,
+ )
+ ]
+
+ max_seq_len = int(math.ceil(np.prod(target_shape) // 4 / self.sp_size)) * self.sp_size
+ if max_seq_len % self.sp_size != 0:
+ raise ValueError(f"max_seq_len {max_seq_len} is not divisible by sp_size {self.sp_size}")
+
+ with (
+ torch.autocast(device_type=str(self.device), dtype=torch.bfloat16, enabled=True),
+ torch.no_grad()
+ ):
+ if sample_solver == 'unipc':
+ sample_scheduler = FlowUniPCMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sample_scheduler.set_timesteps(
+ sampling_steps, device=self.device, shift=shift)
+ timesteps = sample_scheduler.timesteps
+ elif sample_solver == 'dpm++':
+ sample_scheduler = FlowDPMSolverMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sampling_sigmas = get_sampling_sigmas(sampling_steps, shift)
+ timesteps, _ = retrieve_timesteps(
+ sample_scheduler,
+ device=self.device,
+ sigmas=sampling_sigmas)
+ else:
+ raise NotImplementedError("Unsupported solver.")
+
+ latents = noise
+
+ pose_latents_no_ref = self.vae.encode(conditioning_pixel_values.to(torch.bfloat16))
+ pose_latents_no_ref = torch.stack(pose_latents_no_ref)
+ pose_latents = torch.cat([pose_latents_no_ref], dim=2)
+
+ ref_pixel_values = rearrange(ref_pixel_values, "t c h w -> 1 c t h w")
+ ref_latents = self.vae.encode(ref_pixel_values.to(torch.bfloat16))
+ ref_latents = torch.stack(ref_latents)
+
+ mask_ref = self.get_i2v_mask(1, lat_h, lat_w, 1, device=self.device)
+ y_ref = torch.concat([mask_ref, ref_latents[0]]).to(dtype=torch.bfloat16, device=self.device)
+
+ img = ref_pixel_values[0, :, 0]
+ clip_context = self.clip.visual([img[:, None, :, :]]).to(dtype=torch.bfloat16, device=self.device)
+
+ if mask_reft_len > 0:
+ if replace_flag:
+ bg_pixel_values = batch["bg_pixel_values"]
+ y_reft = self.vae.encode(
+ [
+ torch.concat([refer_t_pixel_values[0, :, :mask_reft_len], bg_pixel_values[0, :, mask_reft_len:]], dim=1).to(self.device)
+ ]
+ )[0]
+ mask_pixel_values = 1 - batch["mask_pixel_values"]
+ mask_pixel_values = rearrange(mask_pixel_values, "b t c h w -> (b t) c h w")
+ mask_pixel_values = F.interpolate(mask_pixel_values, size=(H//8, W//8), mode='nearest')
+ mask_pixel_values = rearrange(mask_pixel_values, "(b t) c h w -> b t c h w", b=1)[:,:,0]
+ msk_reft = self.get_i2v_mask(lat_t, lat_h, lat_w, mask_reft_len, mask_pixel_values=mask_pixel_values, device=self.device)
+ else:
+ y_reft = self.vae.encode(
+ [
+ torch.concat(
+ [
+ torch.nn.functional.interpolate(refer_t_pixel_values[0, :, :mask_reft_len].cpu(),
+ size=(H, W), mode="bicubic"),
+ torch.zeros(3, T - mask_reft_len, H, W),
+ ],
+ dim=1,
+ ).to(self.device)
+ ]
+ )[0]
+ msk_reft = self.get_i2v_mask(lat_t, lat_h, lat_w, mask_reft_len, device=self.device)
+ else:
+ if replace_flag:
+ bg_pixel_values = batch["bg_pixel_values"]
+ mask_pixel_values = 1 - batch["mask_pixel_values"]
+ mask_pixel_values = rearrange(mask_pixel_values, "b t c h w -> (b t) c h w")
+ mask_pixel_values = F.interpolate(mask_pixel_values, size=(H//8, W//8), mode='nearest')
+ mask_pixel_values = rearrange(mask_pixel_values, "(b t) c h w -> b t c h w", b=1)[:,:,0]
+ y_reft = self.vae.encode(
+ [
+ torch.concat(
+ [
+ bg_pixel_values[0],
+ ],
+ dim=1,
+ ).to(self.device)
+ ]
+ )[0]
+ msk_reft = self.get_i2v_mask(lat_t, lat_h, lat_w, mask_reft_len, mask_pixel_values=mask_pixel_values, device=self.device)
+ else:
+ y_reft = self.vae.encode(
+ [
+ torch.concat(
+ [
+ torch.zeros(3, T - mask_reft_len, H, W),
+ ],
+ dim=1,
+ ).to(self.device)
+ ]
+ )[0]
+ msk_reft = self.get_i2v_mask(lat_t, lat_h, lat_w, mask_reft_len, device=self.device)
+
+ y_reft = torch.concat([msk_reft, y_reft]).to(dtype=torch.bfloat16, device=self.device)
+ y = torch.concat([y_ref, y_reft], dim=1)
+
+ arg_c = {
+ "context": context,
+ "seq_len": max_seq_len,
+ "clip_fea": clip_context.to(dtype=torch.bfloat16, device=self.device),
+ "y": [y],
+ "pose_latents": pose_latents,
+ "face_pixel_values": face_pixel_values,
+ }
+
+ if guide_scale > 1:
+ face_pixel_values_uncond = face_pixel_values * 0 - 1
+ arg_null = {
+ "context": context_null,
+ "seq_len": max_seq_len,
+ "clip_fea": clip_context.to(dtype=torch.bfloat16, device=self.device),
+ "y": [y],
+ "pose_latents": pose_latents,
+ "face_pixel_values": face_pixel_values_uncond,
+ }
+
+ for i, t in enumerate(tqdm(timesteps)):
+ latent_model_input = latents
+ timestep = [t]
+
+ timestep = torch.stack(timestep)
+
+ noise_pred_cond = TensorList(
+ self.noise_model(TensorList(latent_model_input), t=timestep, **arg_c)
+ )
+
+ if guide_scale > 1:
+ noise_pred_uncond = TensorList(
+ self.noise_model(
+ TensorList(latent_model_input), t=timestep, **arg_null
+ )
+ )
+ noise_pred = noise_pred_uncond + guide_scale * (
+ noise_pred_cond - noise_pred_uncond
+ )
+ else:
+ noise_pred = noise_pred_cond
+
+ temp_x0 = sample_scheduler.step(
+ noise_pred[0].unsqueeze(0),
+ t,
+ latents[0].unsqueeze(0),
+ return_dict=False,
+ generator=seed_g,
+ )[0]
+ latents[0] = temp_x0.squeeze(0)
+
+ x0 = latents
+
+ x0 = [x.to(dtype=torch.float32) for x in x0]
+ out_frames = torch.stack(self.vae.decode([x0[0][:, 1:]]))
+
+ if start != 0:
+ out_frames = out_frames[:, :, refert_num:]
+
+ all_out_frames.append(out_frames.cpu())
+
+ start += clip_len - refert_num
+ end += clip_len - refert_num
+
+ videos = torch.cat(all_out_frames, dim=2)[:, :, :real_frame_len]
+ return videos[0] if self.rank == 0 else None
diff --git a/wan/configs/__init__.py b/wan/configs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b99916cc862d61897e5975b019bcd7cf8dc42277
--- /dev/null
+++ b/wan/configs/__init__.py
@@ -0,0 +1,50 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import copy
+import os
+
+os.environ['TOKENIZERS_PARALLELISM'] = 'false'
+
+from .wan_i2v_A14B import i2v_A14B
+from .wan_s2v_14B import s2v_14B
+from .wan_t2v_A14B import t2v_A14B
+from .wan_ti2v_5B import ti2v_5B
+from .wan_animate_14B import animate_14B
+
+WAN_CONFIGS = {
+ 't2v-A14B': t2v_A14B,
+ 'i2v-A14B': i2v_A14B,
+ 'ti2v-5B': ti2v_5B,
+ 'animate-14B': animate_14B,
+ 's2v-14B': s2v_14B,
+}
+
+SIZE_CONFIGS = {
+ '720*1280': (720, 1280),
+ '1280*720': (1280, 720),
+ '480*832': (480, 832),
+ '832*480': (832, 480),
+ '704*1280': (704, 1280),
+ '1280*704': (1280, 704),
+ '1024*704': (1024, 704),
+ '704*1024': (704, 1024),
+}
+
+MAX_AREA_CONFIGS = {
+ '720*1280': 720 * 1280,
+ '1280*720': 1280 * 720,
+ '480*832': 480 * 832,
+ '832*480': 832 * 480,
+ '704*1280': 704 * 1280,
+ '1280*704': 1280 * 704,
+ '1024*704': 1024 * 704,
+ '704*1024': 704 * 1024,
+}
+
+SUPPORTED_SIZES = {
+ 't2v-A14B': ('720*1280', '1280*720', '480*832', '832*480'),
+ 'i2v-A14B': ('720*1280', '1280*720', '480*832', '832*480'),
+ 'ti2v-5B': ('704*1280', '1280*704'),
+ 's2v-14B': ('720*1280', '1280*720', '480*832', '832*480', '1024*704',
+ '704*1024', '704*1280', '1280*704'),
+ 'animate-14B': ('720*1280', '1280*720')
+}
diff --git a/wan/configs/shared_config.py b/wan/configs/shared_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..70b6457ca93df74ab38423031ae88812ed3eab6c
--- /dev/null
+++ b/wan/configs/shared_config.py
@@ -0,0 +1,20 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import torch
+from easydict import EasyDict
+
+#------------------------ Wan shared config ------------------------#
+wan_shared_cfg = EasyDict()
+
+# t5
+wan_shared_cfg.t5_model = 'umt5_xxl'
+wan_shared_cfg.t5_dtype = torch.bfloat16
+wan_shared_cfg.text_len = 512
+
+# transformer
+wan_shared_cfg.param_dtype = torch.bfloat16
+
+# inference
+wan_shared_cfg.num_train_timesteps = 1000
+wan_shared_cfg.sample_fps = 16
+wan_shared_cfg.sample_neg_prompt = '色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走'
+wan_shared_cfg.frame_num = 81
diff --git a/wan/configs/wan_animate_14B.py b/wan/configs/wan_animate_14B.py
new file mode 100644
index 0000000000000000000000000000000000000000..370ddceaa27aa958f0411e12a6c439e677121c0c
--- /dev/null
+++ b/wan/configs/wan_animate_14B.py
@@ -0,0 +1,40 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from easydict import EasyDict
+
+from .shared_config import wan_shared_cfg
+
+#------------------------ Wan animate 14B ------------------------#
+animate_14B = EasyDict(__name__='Config: Wan animate 14B')
+animate_14B.update(wan_shared_cfg)
+
+animate_14B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
+animate_14B.t5_tokenizer = 'google/umt5-xxl'
+
+animate_14B.clip_checkpoint = 'models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth'
+animate_14B.clip_tokenizer = 'xlm-roberta-large'
+animate_14B.lora_checkpoint = 'relighting_lora.ckpt'
+# vae
+animate_14B.vae_checkpoint = 'Wan2.1_VAE.pth'
+animate_14B.vae_stride = (4, 8, 8)
+
+# transformer
+animate_14B.patch_size = (1, 2, 2)
+animate_14B.dim = 5120
+animate_14B.ffn_dim = 13824
+animate_14B.freq_dim = 256
+animate_14B.num_heads = 40
+animate_14B.num_layers = 40
+animate_14B.window_size = (-1, -1)
+animate_14B.qk_norm = True
+animate_14B.cross_attn_norm = True
+animate_14B.eps = 1e-6
+animate_14B.use_face_encoder = True
+animate_14B.motion_encoder_dim = 512
+
+# inference
+animate_14B.sample_shift = 5.0
+animate_14B.sample_steps = 20
+animate_14B.sample_guide_scale = 1.0
+animate_14B.frame_num = 77
+animate_14B.sample_fps = 30
+animate_14B.prompt = '视频中的人在做动作'
diff --git a/wan/configs/wan_i2v_A14B.py b/wan/configs/wan_i2v_A14B.py
new file mode 100644
index 0000000000000000000000000000000000000000..b30a173fd3334fa9093b4ad85f335aa052aea4e5
--- /dev/null
+++ b/wan/configs/wan_i2v_A14B.py
@@ -0,0 +1,37 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import torch
+from easydict import EasyDict
+
+from .shared_config import wan_shared_cfg
+
+#------------------------ Wan I2V A14B ------------------------#
+
+i2v_A14B = EasyDict(__name__='Config: Wan I2V A14B')
+i2v_A14B.update(wan_shared_cfg)
+
+i2v_A14B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
+i2v_A14B.t5_tokenizer = 'google/umt5-xxl'
+
+# vae
+i2v_A14B.vae_checkpoint = 'Wan2.1_VAE.pth'
+i2v_A14B.vae_stride = (4, 8, 8)
+
+# transformer
+i2v_A14B.patch_size = (1, 2, 2)
+i2v_A14B.dim = 5120
+i2v_A14B.ffn_dim = 13824
+i2v_A14B.freq_dim = 256
+i2v_A14B.num_heads = 40
+i2v_A14B.num_layers = 40
+i2v_A14B.window_size = (-1, -1)
+i2v_A14B.qk_norm = True
+i2v_A14B.cross_attn_norm = True
+i2v_A14B.eps = 1e-6
+i2v_A14B.low_noise_checkpoint = 'low_noise_model'
+i2v_A14B.high_noise_checkpoint = 'high_noise_model'
+
+# inference
+i2v_A14B.sample_shift = 5.0
+i2v_A14B.sample_steps = 40
+i2v_A14B.boundary = 0.900
+i2v_A14B.sample_guide_scale = (3.5, 3.5) # low noise, high noise
diff --git a/wan/configs/wan_s2v_14B.py b/wan/configs/wan_s2v_14B.py
new file mode 100644
index 0000000000000000000000000000000000000000..aab207bfcd4309aeeb4a762eb7163811bc176378
--- /dev/null
+++ b/wan/configs/wan_s2v_14B.py
@@ -0,0 +1,59 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from easydict import EasyDict
+
+from .shared_config import wan_shared_cfg
+
+#------------------------ Wan S2V 14B ------------------------#
+
+s2v_14B = EasyDict(__name__='Config: Wan S2V 14B')
+s2v_14B.update(wan_shared_cfg)
+
+# t5
+s2v_14B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
+s2v_14B.t5_tokenizer = 'google/umt5-xxl'
+
+# vae
+s2v_14B.vae_checkpoint = 'Wan2.1_VAE.pth'
+s2v_14B.vae_stride = (4, 8, 8)
+
+# wav2vec
+s2v_14B.wav2vec = "wav2vec2-large-xlsr-53-english"
+
+s2v_14B.num_heads = 40
+# transformer
+s2v_14B.transformer = EasyDict(
+ __name__="Config: Transformer config for WanModel_S2V")
+s2v_14B.transformer.patch_size = (1, 2, 2)
+s2v_14B.transformer.dim = 5120
+s2v_14B.transformer.ffn_dim = 13824
+s2v_14B.transformer.freq_dim = 256
+s2v_14B.transformer.num_heads = 40
+s2v_14B.transformer.num_layers = 40
+s2v_14B.transformer.window_size = (-1, -1)
+s2v_14B.transformer.qk_norm = True
+s2v_14B.transformer.cross_attn_norm = True
+s2v_14B.transformer.eps = 1e-6
+s2v_14B.transformer.enable_adain = True
+s2v_14B.transformer.adain_mode = "attn_norm"
+s2v_14B.transformer.audio_inject_layers = [
+ 0, 4, 8, 12, 16, 20, 24, 27, 30, 33, 36, 39
+]
+s2v_14B.transformer.zero_init = True
+s2v_14B.transformer.zero_timestep = True
+s2v_14B.transformer.enable_motioner = False
+s2v_14B.transformer.add_last_motion = True
+s2v_14B.transformer.trainable_token = False
+s2v_14B.transformer.enable_tsm = False
+s2v_14B.transformer.enable_framepack = True
+s2v_14B.transformer.framepack_drop_mode = 'padd'
+s2v_14B.transformer.audio_dim = 1024
+
+s2v_14B.transformer.motion_frames = 73
+s2v_14B.transformer.cond_dim = 16
+
+# inference
+s2v_14B.sample_neg_prompt = "画面模糊,最差质量,画面模糊,细节模糊不清,情绪激动剧烈,手快速抖动,字幕,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
+s2v_14B.drop_first_motion = True
+s2v_14B.sample_shift = 3
+s2v_14B.sample_steps = 40
+s2v_14B.sample_guide_scale = 4.5
diff --git a/wan/configs/wan_t2v_A14B.py b/wan/configs/wan_t2v_A14B.py
new file mode 100644
index 0000000000000000000000000000000000000000..e079548b2618f36309ee4b10c33e6f1b48f11e72
--- /dev/null
+++ b/wan/configs/wan_t2v_A14B.py
@@ -0,0 +1,37 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from easydict import EasyDict
+
+from .shared_config import wan_shared_cfg
+
+#------------------------ Wan T2V A14B ------------------------#
+
+t2v_A14B = EasyDict(__name__='Config: Wan T2V A14B')
+t2v_A14B.update(wan_shared_cfg)
+
+# t5
+t2v_A14B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
+t2v_A14B.t5_tokenizer = 'google/umt5-xxl'
+
+# vae
+t2v_A14B.vae_checkpoint = 'Wan2.1_VAE.pth'
+t2v_A14B.vae_stride = (4, 8, 8)
+
+# transformer
+t2v_A14B.patch_size = (1, 2, 2)
+t2v_A14B.dim = 5120
+t2v_A14B.ffn_dim = 13824
+t2v_A14B.freq_dim = 256
+t2v_A14B.num_heads = 40
+t2v_A14B.num_layers = 40
+t2v_A14B.window_size = (-1, -1)
+t2v_A14B.qk_norm = True
+t2v_A14B.cross_attn_norm = True
+t2v_A14B.eps = 1e-6
+t2v_A14B.low_noise_checkpoint = 'low_noise_model'
+t2v_A14B.high_noise_checkpoint = 'high_noise_model'
+
+# inference
+t2v_A14B.sample_shift = 12.0
+t2v_A14B.sample_steps = 40
+t2v_A14B.boundary = 0.875
+t2v_A14B.sample_guide_scale = (3.0, 4.0) # low noise, high noise
diff --git a/wan/configs/wan_ti2v_5B.py b/wan/configs/wan_ti2v_5B.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcbdc2fe663306c44567e06e29ab9805682226de
--- /dev/null
+++ b/wan/configs/wan_ti2v_5B.py
@@ -0,0 +1,36 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from easydict import EasyDict
+
+from .shared_config import wan_shared_cfg
+
+#------------------------ Wan TI2V 5B ------------------------#
+
+ti2v_5B = EasyDict(__name__='Config: Wan TI2V 5B')
+ti2v_5B.update(wan_shared_cfg)
+
+# t5
+ti2v_5B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
+ti2v_5B.t5_tokenizer = 'google/umt5-xxl'
+
+# vae
+ti2v_5B.vae_checkpoint = 'Wan2.2_VAE.pth'
+ti2v_5B.vae_stride = (4, 16, 16)
+
+# transformer
+ti2v_5B.patch_size = (1, 2, 2)
+ti2v_5B.dim = 3072
+ti2v_5B.ffn_dim = 14336
+ti2v_5B.freq_dim = 256
+ti2v_5B.num_heads = 24
+ti2v_5B.num_layers = 30
+ti2v_5B.window_size = (-1, -1)
+ti2v_5B.qk_norm = True
+ti2v_5B.cross_attn_norm = True
+ti2v_5B.eps = 1e-6
+
+# inference
+ti2v_5B.sample_fps = 24
+ti2v_5B.sample_shift = 5.0
+ti2v_5B.sample_steps = 50
+ti2v_5B.sample_guide_scale = 5.0
+ti2v_5B.frame_num = 121
diff --git a/wan/distributed/__init__.py b/wan/distributed/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d80865c6458d1a3903c0437adf3bce4975ce571f
--- /dev/null
+++ b/wan/distributed/__init__.py
@@ -0,0 +1 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
diff --git a/wan/distributed/fsdp.py b/wan/distributed/fsdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..aec73a3ac13456f3d517e99a89b8f448c2ee7e54
--- /dev/null
+++ b/wan/distributed/fsdp.py
@@ -0,0 +1,45 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import gc
+from functools import partial
+
+import torch
+from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
+from torch.distributed.fsdp import MixedPrecision, ShardingStrategy
+from torch.distributed.fsdp.wrap import lambda_auto_wrap_policy
+from torch.distributed.utils import _free_storage
+
+
+def shard_model(
+ model,
+ device_id,
+ param_dtype=torch.bfloat16,
+ reduce_dtype=torch.float32,
+ buffer_dtype=torch.float32,
+ process_group=None,
+ sharding_strategy=ShardingStrategy.FULL_SHARD,
+ sync_module_states=True,
+ use_lora=False
+):
+ model = FSDP(
+ module=model,
+ process_group=process_group,
+ sharding_strategy=sharding_strategy,
+ auto_wrap_policy=partial(
+ lambda_auto_wrap_policy, lambda_fn=lambda m: m in model.blocks),
+ mixed_precision=MixedPrecision(
+ param_dtype=param_dtype,
+ reduce_dtype=reduce_dtype,
+ buffer_dtype=buffer_dtype),
+ device_id=device_id,
+ sync_module_states=sync_module_states,
+ use_orig_params=True if use_lora else False)
+ return model
+
+
+def free_model(model):
+ for m in model.modules():
+ if isinstance(m, FSDP):
+ _free_storage(m._handle.flat_param.data)
+ del model
+ gc.collect()
+ torch.cuda.empty_cache()
diff --git a/wan/distributed/sequence_parallel.py b/wan/distributed/sequence_parallel.py
new file mode 100644
index 0000000000000000000000000000000000000000..2579463b7510ff2f6e57e5f7eb1b5b9eee28d0fb
--- /dev/null
+++ b/wan/distributed/sequence_parallel.py
@@ -0,0 +1,176 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import torch
+import torch.cuda.amp as amp
+
+from ..modules.model import sinusoidal_embedding_1d
+from .ulysses import distributed_attention
+from .util import gather_forward, get_rank, get_world_size
+
+
+def pad_freqs(original_tensor, target_len):
+ seq_len, s1, s2 = original_tensor.shape
+ pad_size = target_len - seq_len
+ padding_tensor = torch.ones(
+ pad_size,
+ s1,
+ s2,
+ dtype=original_tensor.dtype,
+ device=original_tensor.device)
+ padded_tensor = torch.cat([original_tensor, padding_tensor], dim=0)
+ return padded_tensor
+
+
+@torch.amp.autocast('cuda', enabled=False)
+def rope_apply(x, grid_sizes, freqs):
+ """
+ x: [B, L, N, C].
+ grid_sizes: [B, 3].
+ freqs: [M, C // 2].
+ """
+ s, n, c = x.size(1), x.size(2), x.size(3) // 2
+ # split freqs
+ freqs = freqs.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
+
+ # loop over samples
+ output = []
+ for i, (f, h, w) in enumerate(grid_sizes.tolist()):
+ seq_len = f * h * w
+
+ # precompute multipliers
+ x_i = torch.view_as_complex(x[i, :s].to(torch.float64).reshape(
+ s, n, -1, 2))
+ freqs_i = torch.cat([
+ freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
+ freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
+ freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
+ ],
+ dim=-1).reshape(seq_len, 1, -1)
+
+ # apply rotary embedding
+ sp_size = get_world_size()
+ sp_rank = get_rank()
+ freqs_i = pad_freqs(freqs_i, s * sp_size)
+ s_per_rank = s
+ freqs_i_rank = freqs_i[(sp_rank * s_per_rank):((sp_rank + 1) *
+ s_per_rank), :, :]
+ x_i = torch.view_as_real(x_i * freqs_i_rank).flatten(2)
+ x_i = torch.cat([x_i, x[i, s:]])
+
+ # append to collection
+ output.append(x_i)
+ return torch.stack(output).float()
+
+
+def sp_dit_forward(
+ self,
+ x,
+ t,
+ context,
+ seq_len,
+ y=None,
+):
+ """
+ x: A list of videos each with shape [C, T, H, W].
+ t: [B].
+ context: A list of text embeddings each with shape [L, C].
+ """
+ if self.model_type == 'i2v':
+ assert y is not None
+ # params
+ device = self.patch_embedding.weight.device
+ if self.freqs.device != device:
+ self.freqs = self.freqs.to(device)
+
+ if y is not None:
+ x = [torch.cat([u, v], dim=0) for u, v in zip(x, y)]
+
+ # embeddings
+ x = [self.patch_embedding(u.unsqueeze(0)) for u in x]
+ grid_sizes = torch.stack(
+ [torch.tensor(u.shape[2:], dtype=torch.long) for u in x])
+ x = [u.flatten(2).transpose(1, 2) for u in x]
+ seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long)
+ assert seq_lens.max() <= seq_len
+ x = torch.cat([
+ torch.cat([u, u.new_zeros(1, seq_len - u.size(1), u.size(2))], dim=1)
+ for u in x
+ ])
+
+ # time embeddings
+ if t.dim() == 1:
+ t = t.expand(t.size(0), seq_len)
+ with torch.amp.autocast('cuda', dtype=torch.float32):
+ bt = t.size(0)
+ t = t.flatten()
+ e = self.time_embedding(
+ sinusoidal_embedding_1d(self.freq_dim,
+ t).unflatten(0, (bt, seq_len)).float())
+ e0 = self.time_projection(e).unflatten(2, (6, self.dim))
+ assert e.dtype == torch.float32 and e0.dtype == torch.float32
+
+ # context
+ context_lens = None
+ context = self.text_embedding(
+ torch.stack([
+ torch.cat([u, u.new_zeros(self.text_len - u.size(0), u.size(1))])
+ for u in context
+ ]))
+
+ # Context Parallel
+ x = torch.chunk(x, get_world_size(), dim=1)[get_rank()]
+ e = torch.chunk(e, get_world_size(), dim=1)[get_rank()]
+ e0 = torch.chunk(e0, get_world_size(), dim=1)[get_rank()]
+
+ # arguments
+ kwargs = dict(
+ e=e0,
+ seq_lens=seq_lens,
+ grid_sizes=grid_sizes,
+ freqs=self.freqs,
+ context=context,
+ context_lens=context_lens)
+
+ for block in self.blocks:
+ x = block(x, **kwargs)
+
+ # head
+ x = self.head(x, e)
+
+ # Context Parallel
+ x = gather_forward(x, dim=1)
+
+ # unpatchify
+ x = self.unpatchify(x, grid_sizes)
+ return [u.float() for u in x]
+
+
+def sp_attn_forward(self, x, seq_lens, grid_sizes, freqs, dtype=torch.bfloat16):
+ b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
+ half_dtypes = (torch.float16, torch.bfloat16)
+
+ def half(x):
+ return x if x.dtype in half_dtypes else x.to(dtype)
+
+ # query, key, value function
+ def qkv_fn(x):
+ q = self.norm_q(self.q(x)).view(b, s, n, d)
+ k = self.norm_k(self.k(x)).view(b, s, n, d)
+ v = self.v(x).view(b, s, n, d)
+ return q, k, v
+
+ q, k, v = qkv_fn(x)
+ q = rope_apply(q, grid_sizes, freqs)
+ k = rope_apply(k, grid_sizes, freqs)
+
+ x = distributed_attention(
+ half(q),
+ half(k),
+ half(v),
+ seq_lens,
+ window_size=self.window_size,
+ )
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
diff --git a/wan/distributed/ulysses.py b/wan/distributed/ulysses.py
new file mode 100644
index 0000000000000000000000000000000000000000..8515a07ea4c4ae009fe44151d4f695e7466928fa
--- /dev/null
+++ b/wan/distributed/ulysses.py
@@ -0,0 +1,47 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import torch
+import torch.distributed as dist
+
+from ..modules.attention import flash_attention
+from .util import all_to_all
+
+
+def distributed_attention(
+ q,
+ k,
+ v,
+ seq_lens,
+ window_size=(-1, -1),
+):
+ """
+ Performs distributed attention based on DeepSpeed Ulysses attention mechanism.
+ please refer to https://arxiv.org/pdf/2309.14509
+
+ Args:
+ q: [B, Lq // p, Nq, C1].
+ k: [B, Lk // p, Nk, C1].
+ v: [B, Lk // p, Nk, C2]. Nq must be divisible by Nk.
+ seq_lens: [B], length of each sequence in batch
+ window_size: (left right). If not (-1, -1), apply sliding window local attention.
+ """
+ if not dist.is_initialized():
+ raise ValueError("distributed group should be initialized.")
+ b = q.shape[0]
+
+ # gather q/k/v sequence
+ q = all_to_all(q, scatter_dim=2, gather_dim=1)
+ k = all_to_all(k, scatter_dim=2, gather_dim=1)
+ v = all_to_all(v, scatter_dim=2, gather_dim=1)
+
+ # apply attention
+ x = flash_attention(
+ q,
+ k,
+ v,
+ k_lens=seq_lens,
+ window_size=window_size,
+ )
+
+ # scatter q/k/v sequence
+ x = all_to_all(x, scatter_dim=1, gather_dim=2)
+ return x
diff --git a/wan/distributed/util.py b/wan/distributed/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..464e6ae45a9f7a1aefb735bb29d899a612d35f71
--- /dev/null
+++ b/wan/distributed/util.py
@@ -0,0 +1,51 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import torch
+import torch.distributed as dist
+
+
+def init_distributed_group():
+ """r initialize sequence parallel group.
+ """
+ if not dist.is_initialized():
+ dist.init_process_group(backend='nccl')
+
+
+def get_rank():
+ return dist.get_rank()
+
+
+def get_world_size():
+ return dist.get_world_size()
+
+
+def all_to_all(x, scatter_dim, gather_dim, group=None, **kwargs):
+ """
+ `scatter` along one dimension and `gather` along another.
+ """
+ world_size = get_world_size()
+ if world_size > 1:
+ inputs = [u.contiguous() for u in x.chunk(world_size, dim=scatter_dim)]
+ outputs = [torch.empty_like(u) for u in inputs]
+ dist.all_to_all(outputs, inputs, group=group, **kwargs)
+ x = torch.cat(outputs, dim=gather_dim).contiguous()
+ return x
+
+
+def all_gather(tensor):
+ world_size = dist.get_world_size()
+ if world_size == 1:
+ return [tensor]
+ tensor_list = [torch.empty_like(tensor) for _ in range(world_size)]
+ torch.distributed.all_gather(tensor_list, tensor)
+ return tensor_list
+
+
+def gather_forward(input, dim):
+ # skip if world_size == 1
+ world_size = dist.get_world_size()
+ if world_size == 1:
+ return input
+
+ # gather sequence
+ output = all_gather(input)
+ return torch.cat(output, dim=dim).contiguous()
diff --git a/wan/image2video.py b/wan/image2video.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d1ea3867e7a3421a53f2bc953ce469d16c58756
--- /dev/null
+++ b/wan/image2video.py
@@ -0,0 +1,431 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import gc
+import logging
+import math
+import os
+import random
+import sys
+import types
+from contextlib import contextmanager
+from functools import partial
+
+import numpy as np
+import torch
+import torch.cuda.amp as amp
+import torch.distributed as dist
+import torchvision.transforms.functional as TF
+from tqdm import tqdm
+
+from .distributed.fsdp import shard_model
+from .distributed.sequence_parallel import sp_attn_forward, sp_dit_forward
+from .distributed.util import get_world_size
+from .modules.model import WanModel
+from .modules.t5 import T5EncoderModel
+from .modules.vae2_1 import Wan2_1_VAE
+from .utils.fm_solvers import (
+ FlowDPMSolverMultistepScheduler,
+ get_sampling_sigmas,
+ retrieve_timesteps,
+)
+from .utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
+
+
+class WanI2V:
+
+ def __init__(
+ self,
+ config,
+ checkpoint_dir,
+ device_id=0,
+ rank=0,
+ t5_fsdp=False,
+ dit_fsdp=False,
+ use_sp=False,
+ t5_cpu=False,
+ init_on_cpu=True,
+ convert_model_dtype=False,
+ ):
+ r"""
+ Initializes the image-to-video generation model components.
+
+ Args:
+ config (EasyDict):
+ Object containing model parameters initialized from config.py
+ checkpoint_dir (`str`):
+ Path to directory containing model checkpoints
+ device_id (`int`, *optional*, defaults to 0):
+ Id of target GPU device
+ rank (`int`, *optional*, defaults to 0):
+ Process rank for distributed training
+ t5_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for T5 model
+ dit_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for DiT model
+ use_sp (`bool`, *optional*, defaults to False):
+ Enable distribution strategy of sequence parallel.
+ t5_cpu (`bool`, *optional*, defaults to False):
+ Whether to place T5 model on CPU. Only works without t5_fsdp.
+ init_on_cpu (`bool`, *optional*, defaults to True):
+ Enable initializing Transformer Model on CPU. Only works without FSDP or USP.
+ convert_model_dtype (`bool`, *optional*, defaults to False):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+ """
+ self.device = torch.device(f"cuda:{device_id}")
+ self.config = config
+ self.rank = rank
+ self.t5_cpu = t5_cpu
+ self.init_on_cpu = init_on_cpu
+
+ self.num_train_timesteps = config.num_train_timesteps
+ self.boundary = config.boundary
+ self.param_dtype = config.param_dtype
+
+ if t5_fsdp or dit_fsdp or use_sp:
+ self.init_on_cpu = False
+
+ shard_fn = partial(shard_model, device_id=device_id)
+ self.text_encoder = T5EncoderModel(
+ text_len=config.text_len,
+ dtype=config.t5_dtype,
+ device=torch.device('cpu'),
+ checkpoint_path=os.path.join(checkpoint_dir, config.t5_checkpoint),
+ tokenizer_path=os.path.join(checkpoint_dir, config.t5_tokenizer),
+ shard_fn=shard_fn if t5_fsdp else None,
+ )
+
+ self.vae_stride = config.vae_stride
+ self.patch_size = config.patch_size
+ self.vae = Wan2_1_VAE(
+ vae_pth=os.path.join(checkpoint_dir, config.vae_checkpoint),
+ device=self.device)
+
+ logging.info(f"Creating WanModel from {checkpoint_dir}")
+ self.low_noise_model = WanModel.from_pretrained(
+ checkpoint_dir, subfolder=config.low_noise_checkpoint)
+ self.low_noise_model = self._configure_model(
+ model=self.low_noise_model,
+ use_sp=use_sp,
+ dit_fsdp=dit_fsdp,
+ shard_fn=shard_fn,
+ convert_model_dtype=convert_model_dtype)
+
+ self.high_noise_model = WanModel.from_pretrained(
+ checkpoint_dir, subfolder=config.high_noise_checkpoint)
+ self.high_noise_model = self._configure_model(
+ model=self.high_noise_model,
+ use_sp=use_sp,
+ dit_fsdp=dit_fsdp,
+ shard_fn=shard_fn,
+ convert_model_dtype=convert_model_dtype)
+ if use_sp:
+ self.sp_size = get_world_size()
+ else:
+ self.sp_size = 1
+
+ self.sample_neg_prompt = config.sample_neg_prompt
+
+ def _configure_model(self, model, use_sp, dit_fsdp, shard_fn,
+ convert_model_dtype):
+ """
+ Configures a model object. This includes setting evaluation modes,
+ applying distributed parallel strategy, and handling device placement.
+
+ Args:
+ model (torch.nn.Module):
+ The model instance to configure.
+ use_sp (`bool`):
+ Enable distribution strategy of sequence parallel.
+ dit_fsdp (`bool`):
+ Enable FSDP sharding for DiT model.
+ shard_fn (callable):
+ The function to apply FSDP sharding.
+ convert_model_dtype (`bool`):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+
+ Returns:
+ torch.nn.Module:
+ The configured model.
+ """
+ model.eval().requires_grad_(False)
+
+ if use_sp:
+ for block in model.blocks:
+ block.self_attn.forward = types.MethodType(
+ sp_attn_forward, block.self_attn)
+ model.forward = types.MethodType(sp_dit_forward, model)
+
+ if dist.is_initialized():
+ dist.barrier()
+
+ if dit_fsdp:
+ model = shard_fn(model)
+ else:
+ if convert_model_dtype:
+ model.to(self.param_dtype)
+ if not self.init_on_cpu:
+ model.to(self.device)
+
+ return model
+
+ def _prepare_model_for_timestep(self, t, boundary, offload_model):
+ r"""
+ Prepares and returns the required model for the current timestep.
+
+ Args:
+ t (torch.Tensor):
+ current timestep.
+ boundary (`int`):
+ The timestep threshold. If `t` is at or above this value,
+ the `high_noise_model` is considered as the required model.
+ offload_model (`bool`):
+ A flag intended to control the offloading behavior.
+
+ Returns:
+ torch.nn.Module:
+ The active model on the target device for the current timestep.
+ """
+ if t.item() >= boundary:
+ required_model_name = 'high_noise_model'
+ offload_model_name = 'low_noise_model'
+ else:
+ required_model_name = 'low_noise_model'
+ offload_model_name = 'high_noise_model'
+ if offload_model or self.init_on_cpu:
+ if next(getattr(
+ self,
+ offload_model_name).parameters()).device.type == 'cuda':
+ getattr(self, offload_model_name).to('cpu')
+ if next(getattr(
+ self,
+ required_model_name).parameters()).device.type == 'cpu':
+ getattr(self, required_model_name).to(self.device)
+ return getattr(self, required_model_name)
+
+ def generate(self,
+ input_prompt,
+ img,
+ max_area=720 * 1280,
+ frame_num=81,
+ shift=5.0,
+ sample_solver='unipc',
+ sampling_steps=40,
+ guide_scale=5.0,
+ n_prompt="",
+ seed=-1,
+ offload_model=True):
+ r"""
+ Generates video frames from input image and text prompt using diffusion process.
+
+ Args:
+ input_prompt (`str`):
+ Text prompt for content generation.
+ img (PIL.Image.Image):
+ Input image tensor. Shape: [3, H, W]
+ max_area (`int`, *optional*, defaults to 720*1280):
+ Maximum pixel area for latent space calculation. Controls video resolution scaling
+ frame_num (`int`, *optional*, defaults to 81):
+ How many frames to sample from a video. The number should be 4n+1
+ shift (`float`, *optional*, defaults to 5.0):
+ Noise schedule shift parameter. Affects temporal dynamics
+ [NOTE]: If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
+ sample_solver (`str`, *optional*, defaults to 'unipc'):
+ Solver used to sample the video.
+ sampling_steps (`int`, *optional*, defaults to 40):
+ Number of diffusion sampling steps. Higher values improve quality but slow generation
+ guide_scale (`float` or tuple[`float`], *optional*, defaults 5.0):
+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.
+ If tuple, the first guide_scale will be used for low noise model and
+ the second guide_scale will be used for high noise model.
+ n_prompt (`str`, *optional*, defaults to ""):
+ Negative prompt for content exclusion. If not given, use `config.sample_neg_prompt`
+ seed (`int`, *optional*, defaults to -1):
+ Random seed for noise generation. If -1, use random seed
+ offload_model (`bool`, *optional*, defaults to True):
+ If True, offloads models to CPU during generation to save VRAM
+
+ Returns:
+ torch.Tensor:
+ Generated video frames tensor. Dimensions: (C, N H, W) where:
+ - C: Color channels (3 for RGB)
+ - N: Number of frames (81)
+ - H: Frame height (from max_area)
+ - W: Frame width from max_area)
+ """
+ # preprocess
+ guide_scale = (guide_scale, guide_scale) if isinstance(
+ guide_scale, float) else guide_scale
+ img = TF.to_tensor(img).sub_(0.5).div_(0.5).to(self.device)
+
+ F = frame_num
+ h, w = img.shape[1:]
+ aspect_ratio = h / w
+ lat_h = round(
+ np.sqrt(max_area * aspect_ratio) // self.vae_stride[1] //
+ self.patch_size[1] * self.patch_size[1])
+ lat_w = round(
+ np.sqrt(max_area / aspect_ratio) // self.vae_stride[2] //
+ self.patch_size[2] * self.patch_size[2])
+ h = lat_h * self.vae_stride[1]
+ w = lat_w * self.vae_stride[2]
+
+ max_seq_len = ((F - 1) // self.vae_stride[0] + 1) * lat_h * lat_w // (
+ self.patch_size[1] * self.patch_size[2])
+ max_seq_len = int(math.ceil(max_seq_len / self.sp_size)) * self.sp_size
+
+ seed = seed if seed >= 0 else random.randint(0, sys.maxsize)
+ seed_g = torch.Generator(device=self.device)
+ seed_g.manual_seed(seed)
+ noise = torch.randn(
+ 16,
+ (F - 1) // self.vae_stride[0] + 1,
+ lat_h,
+ lat_w,
+ dtype=torch.float32,
+ generator=seed_g,
+ device=self.device)
+
+ msk = torch.ones(1, F, lat_h, lat_w, device=self.device)
+ msk[:, 1:] = 0
+ msk = torch.concat([
+ torch.repeat_interleave(msk[:, 0:1], repeats=4, dim=1), msk[:, 1:]
+ ],
+ dim=1)
+ msk = msk.view(1, msk.shape[1] // 4, 4, lat_h, lat_w)
+ msk = msk.transpose(1, 2)[0]
+
+ if n_prompt == "":
+ n_prompt = self.sample_neg_prompt
+
+ # preprocess
+ if not self.t5_cpu:
+ self.text_encoder.model.to(self.device)
+ context = self.text_encoder([input_prompt], self.device)
+ context_null = self.text_encoder([n_prompt], self.device)
+ if offload_model:
+ self.text_encoder.model.cpu()
+ else:
+ context = self.text_encoder([input_prompt], torch.device('cpu'))
+ context_null = self.text_encoder([n_prompt], torch.device('cpu'))
+ context = [t.to(self.device) for t in context]
+ context_null = [t.to(self.device) for t in context_null]
+
+ y = self.vae.encode([
+ torch.concat([
+ torch.nn.functional.interpolate(
+ img[None].cpu(), size=(h, w), mode='bicubic').transpose(
+ 0, 1),
+ torch.zeros(3, F - 1, h, w)
+ ],
+ dim=1).to(self.device)
+ ])[0]
+ y = torch.concat([msk, y])
+
+ @contextmanager
+ def noop_no_sync():
+ yield
+
+ no_sync_low_noise = getattr(self.low_noise_model, 'no_sync',
+ noop_no_sync)
+ no_sync_high_noise = getattr(self.high_noise_model, 'no_sync',
+ noop_no_sync)
+
+ # evaluation mode
+ with (
+ torch.amp.autocast('cuda', dtype=self.param_dtype),
+ torch.no_grad(),
+ no_sync_low_noise(),
+ no_sync_high_noise(),
+ ):
+ boundary = self.boundary * self.num_train_timesteps
+
+ if sample_solver == 'unipc':
+ sample_scheduler = FlowUniPCMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sample_scheduler.set_timesteps(
+ sampling_steps, device=self.device, shift=shift)
+ timesteps = sample_scheduler.timesteps
+ elif sample_solver == 'dpm++':
+ sample_scheduler = FlowDPMSolverMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sampling_sigmas = get_sampling_sigmas(sampling_steps, shift)
+ timesteps, _ = retrieve_timesteps(
+ sample_scheduler,
+ device=self.device,
+ sigmas=sampling_sigmas)
+ else:
+ raise NotImplementedError("Unsupported solver.")
+
+ # sample videos
+ latent = noise
+
+ arg_c = {
+ 'context': [context[0]],
+ 'seq_len': max_seq_len,
+ 'y': [y],
+ }
+
+ arg_null = {
+ 'context': context_null,
+ 'seq_len': max_seq_len,
+ 'y': [y],
+ }
+
+ if offload_model:
+ torch.cuda.empty_cache()
+
+ for _, t in enumerate(tqdm(timesteps)):
+ latent_model_input = [latent.to(self.device)]
+ timestep = [t]
+
+ timestep = torch.stack(timestep).to(self.device)
+
+ model = self._prepare_model_for_timestep(
+ t, boundary, offload_model)
+ sample_guide_scale = guide_scale[1] if t.item(
+ ) >= boundary else guide_scale[0]
+
+ noise_pred_cond = model(
+ latent_model_input, t=timestep, **arg_c)[0]
+ if offload_model:
+ torch.cuda.empty_cache()
+ noise_pred_uncond = model(
+ latent_model_input, t=timestep, **arg_null)[0]
+ if offload_model:
+ torch.cuda.empty_cache()
+ noise_pred = noise_pred_uncond + sample_guide_scale * (
+ noise_pred_cond - noise_pred_uncond)
+
+ temp_x0 = sample_scheduler.step(
+ noise_pred.unsqueeze(0),
+ t,
+ latent.unsqueeze(0),
+ return_dict=False,
+ generator=seed_g)[0]
+ latent = temp_x0.squeeze(0)
+
+ x0 = [latent]
+ del latent_model_input, timestep
+
+ if offload_model:
+ self.low_noise_model.cpu()
+ self.high_noise_model.cpu()
+ torch.cuda.empty_cache()
+
+ if self.rank == 0:
+ videos = self.vae.decode(x0)
+
+ del noise, latent, x0
+ del sample_scheduler
+ if offload_model:
+ gc.collect()
+ torch.cuda.synchronize()
+ if dist.is_initialized():
+ dist.barrier()
+
+ return videos[0] if self.rank == 0 else None
diff --git a/wan/modules/__init__.py b/wan/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..db71d3adfd44374fa8c7fda2a51357fe3993c5e7
--- /dev/null
+++ b/wan/modules/__init__.py
@@ -0,0 +1,19 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from .attention import flash_attention
+from .model import WanModel
+from .t5 import T5Decoder, T5Encoder, T5EncoderModel, T5Model
+from .tokenizers import HuggingfaceTokenizer
+from .vae2_1 import Wan2_1_VAE
+from .vae2_2 import Wan2_2_VAE
+
+__all__ = [
+ 'Wan2_1_VAE',
+ 'Wan2_2_VAE',
+ 'WanModel',
+ 'T5Model',
+ 'T5Encoder',
+ 'T5Decoder',
+ 'T5EncoderModel',
+ 'HuggingfaceTokenizer',
+ 'flash_attention',
+]
diff --git a/wan/modules/animate/__init__.py b/wan/modules/animate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b86363f3e70c69393a06641069b00827d559099
--- /dev/null
+++ b/wan/modules/animate/__init__.py
@@ -0,0 +1,4 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from .model_animate import WanAnimateModel
+from .clip import CLIPModel
+__all__ = ['WanAnimateModel', 'CLIPModel']
\ No newline at end of file
diff --git a/wan/modules/animate/animate_utils.py b/wan/modules/animate/animate_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f8d2df78df3fb8c5188b27302bea65b33b012af
--- /dev/null
+++ b/wan/modules/animate/animate_utils.py
@@ -0,0 +1,143 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import torch
+import numbers
+from peft import LoraConfig
+
+
+def get_loraconfig(transformer, rank=128, alpha=128, init_lora_weights="gaussian"):
+ target_modules = []
+ for name, module in transformer.named_modules():
+ if "blocks" in name and "face" not in name and "modulation" not in name and isinstance(module, torch.nn.Linear):
+ target_modules.append(name)
+
+ transformer_lora_config = LoraConfig(
+ r=rank,
+ lora_alpha=alpha,
+ init_lora_weights=init_lora_weights,
+ target_modules=target_modules,
+ )
+ return transformer_lora_config
+
+
+
+class TensorList(object):
+
+ def __init__(self, tensors):
+ """
+ tensors: a list of torch.Tensor objects. No need to have uniform shape.
+ """
+ assert isinstance(tensors, (list, tuple))
+ assert all(isinstance(u, torch.Tensor) for u in tensors)
+ assert len(set([u.ndim for u in tensors])) == 1
+ assert len(set([u.dtype for u in tensors])) == 1
+ assert len(set([u.device for u in tensors])) == 1
+ self.tensors = tensors
+
+ def to(self, *args, **kwargs):
+ return TensorList([u.to(*args, **kwargs) for u in self.tensors])
+
+ def size(self, dim):
+ assert dim == 0, 'only support get the 0th size'
+ return len(self.tensors)
+
+ def pow(self, *args, **kwargs):
+ return TensorList([u.pow(*args, **kwargs) for u in self.tensors])
+
+ def squeeze(self, dim):
+ assert dim != 0
+ if dim > 0:
+ dim -= 1
+ return TensorList([u.squeeze(dim) for u in self.tensors])
+
+ def type(self, *args, **kwargs):
+ return TensorList([u.type(*args, **kwargs) for u in self.tensors])
+
+ def type_as(self, other):
+ assert isinstance(other, (torch.Tensor, TensorList))
+ if isinstance(other, torch.Tensor):
+ return TensorList([u.type_as(other) for u in self.tensors])
+ else:
+ return TensorList([u.type(other.dtype) for u in self.tensors])
+
+ @property
+ def dtype(self):
+ return self.tensors[0].dtype
+
+ @property
+ def device(self):
+ return self.tensors[0].device
+
+ @property
+ def ndim(self):
+ return 1 + self.tensors[0].ndim
+
+ def __getitem__(self, index):
+ return self.tensors[index]
+
+ def __len__(self):
+ return len(self.tensors)
+
+ def __add__(self, other):
+ return self._apply(other, lambda u, v: u + v)
+
+ def __radd__(self, other):
+ return self._apply(other, lambda u, v: v + u)
+
+ def __sub__(self, other):
+ return self._apply(other, lambda u, v: u - v)
+
+ def __rsub__(self, other):
+ return self._apply(other, lambda u, v: v - u)
+
+ def __mul__(self, other):
+ return self._apply(other, lambda u, v: u * v)
+
+ def __rmul__(self, other):
+ return self._apply(other, lambda u, v: v * u)
+
+ def __floordiv__(self, other):
+ return self._apply(other, lambda u, v: u // v)
+
+ def __truediv__(self, other):
+ return self._apply(other, lambda u, v: u / v)
+
+ def __rfloordiv__(self, other):
+ return self._apply(other, lambda u, v: v // u)
+
+ def __rtruediv__(self, other):
+ return self._apply(other, lambda u, v: v / u)
+
+ def __pow__(self, other):
+ return self._apply(other, lambda u, v: u ** v)
+
+ def __rpow__(self, other):
+ return self._apply(other, lambda u, v: v ** u)
+
+ def __neg__(self):
+ return TensorList([-u for u in self.tensors])
+
+ def __iter__(self):
+ for tensor in self.tensors:
+ yield tensor
+
+ def __repr__(self):
+ return 'TensorList: \n' + repr(self.tensors)
+
+ def _apply(self, other, op):
+ if isinstance(other, (list, tuple, TensorList)) or (
+ isinstance(other, torch.Tensor) and (
+ other.numel() > 1 or other.ndim > 1
+ )
+ ):
+ assert len(other) == len(self.tensors)
+ return TensorList([op(u, v) for u, v in zip(self.tensors, other)])
+ elif isinstance(other, numbers.Number) or (
+ isinstance(other, torch.Tensor) and (
+ other.numel() == 1 and other.ndim <= 1
+ )
+ ):
+ return TensorList([op(u, other) for u in self.tensors])
+ else:
+ raise TypeError(
+ f'unsupported operand for *: "TensorList" and "{type(other)}"'
+ )
\ No newline at end of file
diff --git a/wan/modules/animate/clip.py b/wan/modules/animate/clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bfe7cfcd904b407d10cd96a9b186c52909f6b1c
--- /dev/null
+++ b/wan/modules/animate/clip.py
@@ -0,0 +1,542 @@
+# Modified from ``https://github.com/openai/CLIP'' and ``https://github.com/mlfoundations/open_clip''
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import logging
+import math
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torchvision.transforms as T
+
+from ..attention import flash_attention
+from ..tokenizers import HuggingfaceTokenizer
+from .xlm_roberta import XLMRoberta
+
+__all__ = [
+ 'XLMRobertaCLIP',
+ 'clip_xlm_roberta_vit_h_14',
+ 'CLIPModel',
+]
+
+
+def pos_interpolate(pos, seq_len):
+ if pos.size(1) == seq_len:
+ return pos
+ else:
+ src_grid = int(math.sqrt(pos.size(1)))
+ tar_grid = int(math.sqrt(seq_len))
+ n = pos.size(1) - src_grid * src_grid
+ return torch.cat([
+ pos[:, :n],
+ F.interpolate(
+ pos[:, n:].float().reshape(1, src_grid, src_grid, -1).permute(
+ 0, 3, 1, 2),
+ size=(tar_grid, tar_grid),
+ mode='bicubic',
+ align_corners=False).flatten(2).transpose(1, 2)
+ ],
+ dim=1)
+
+
+class QuickGELU(nn.Module):
+
+ def forward(self, x):
+ return x * torch.sigmoid(1.702 * x)
+
+
+class LayerNorm(nn.LayerNorm):
+
+ def forward(self, x):
+ return super().forward(x.float()).type_as(x)
+
+
+class SelfAttention(nn.Module):
+
+ def __init__(self,
+ dim,
+ num_heads,
+ causal=False,
+ attn_dropout=0.0,
+ proj_dropout=0.0):
+ assert dim % num_heads == 0
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.causal = causal
+ self.attn_dropout = attn_dropout
+ self.proj_dropout = proj_dropout
+
+ # layers
+ self.to_qkv = nn.Linear(dim, dim * 3)
+ self.proj = nn.Linear(dim, dim)
+
+ def forward(self, x):
+ """
+ x: [B, L, C].
+ """
+ b, s, c, n, d = *x.size(), self.num_heads, self.head_dim
+
+ # compute query, key, value
+ q, k, v = self.to_qkv(x).view(b, s, 3, n, d).unbind(2)
+
+ # compute attention
+ p = self.attn_dropout if self.training else 0.0
+ x = flash_attention(q, k, v, dropout_p=p, causal=self.causal, version=2)
+ x = x.reshape(b, s, c)
+
+ # output
+ x = self.proj(x)
+ x = F.dropout(x, self.proj_dropout, self.training)
+ return x
+
+
+class SwiGLU(nn.Module):
+
+ def __init__(self, dim, mid_dim):
+ super().__init__()
+ self.dim = dim
+ self.mid_dim = mid_dim
+
+ # layers
+ self.fc1 = nn.Linear(dim, mid_dim)
+ self.fc2 = nn.Linear(dim, mid_dim)
+ self.fc3 = nn.Linear(mid_dim, dim)
+
+ def forward(self, x):
+ x = F.silu(self.fc1(x)) * self.fc2(x)
+ x = self.fc3(x)
+ return x
+
+
+class AttentionBlock(nn.Module):
+
+ def __init__(self,
+ dim,
+ mlp_ratio,
+ num_heads,
+ post_norm=False,
+ causal=False,
+ activation='quick_gelu',
+ attn_dropout=0.0,
+ proj_dropout=0.0,
+ norm_eps=1e-5):
+ assert activation in ['quick_gelu', 'gelu', 'swi_glu']
+ super().__init__()
+ self.dim = dim
+ self.mlp_ratio = mlp_ratio
+ self.num_heads = num_heads
+ self.post_norm = post_norm
+ self.causal = causal
+ self.norm_eps = norm_eps
+
+ # layers
+ self.norm1 = LayerNorm(dim, eps=norm_eps)
+ self.attn = SelfAttention(dim, num_heads, causal, attn_dropout,
+ proj_dropout)
+ self.norm2 = LayerNorm(dim, eps=norm_eps)
+ if activation == 'swi_glu':
+ self.mlp = SwiGLU(dim, int(dim * mlp_ratio))
+ else:
+ self.mlp = nn.Sequential(
+ nn.Linear(dim, int(dim * mlp_ratio)),
+ QuickGELU() if activation == 'quick_gelu' else nn.GELU(),
+ nn.Linear(int(dim * mlp_ratio), dim), nn.Dropout(proj_dropout))
+
+ def forward(self, x):
+ if self.post_norm:
+ x = x + self.norm1(self.attn(x))
+ x = x + self.norm2(self.mlp(x))
+ else:
+ x = x + self.attn(self.norm1(x))
+ x = x + self.mlp(self.norm2(x))
+ return x
+
+
+class AttentionPool(nn.Module):
+
+ def __init__(self,
+ dim,
+ mlp_ratio,
+ num_heads,
+ activation='gelu',
+ proj_dropout=0.0,
+ norm_eps=1e-5):
+ assert dim % num_heads == 0
+ super().__init__()
+ self.dim = dim
+ self.mlp_ratio = mlp_ratio
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.proj_dropout = proj_dropout
+ self.norm_eps = norm_eps
+
+ # layers
+ gain = 1.0 / math.sqrt(dim)
+ self.cls_embedding = nn.Parameter(gain * torch.randn(1, 1, dim))
+ self.to_q = nn.Linear(dim, dim)
+ self.to_kv = nn.Linear(dim, dim * 2)
+ self.proj = nn.Linear(dim, dim)
+ self.norm = LayerNorm(dim, eps=norm_eps)
+ self.mlp = nn.Sequential(
+ nn.Linear(dim, int(dim * mlp_ratio)),
+ QuickGELU() if activation == 'quick_gelu' else nn.GELU(),
+ nn.Linear(int(dim * mlp_ratio), dim), nn.Dropout(proj_dropout))
+
+ def forward(self, x):
+ """
+ x: [B, L, C].
+ """
+ b, s, c, n, d = *x.size(), self.num_heads, self.head_dim
+
+ # compute query, key, value
+ q = self.to_q(self.cls_embedding).view(1, 1, n, d).expand(b, -1, -1, -1)
+ k, v = self.to_kv(x).view(b, s, 2, n, d).unbind(2)
+
+ # compute attention
+ x = flash_attention(q, k, v, version=2)
+ x = x.reshape(b, 1, c)
+
+ # output
+ x = self.proj(x)
+ x = F.dropout(x, self.proj_dropout, self.training)
+
+ # mlp
+ x = x + self.mlp(self.norm(x))
+ return x[:, 0]
+
+
+class VisionTransformer(nn.Module):
+
+ def __init__(self,
+ image_size=224,
+ patch_size=16,
+ dim=768,
+ mlp_ratio=4,
+ out_dim=512,
+ num_heads=12,
+ num_layers=12,
+ pool_type='token',
+ pre_norm=True,
+ post_norm=False,
+ activation='quick_gelu',
+ attn_dropout=0.0,
+ proj_dropout=0.0,
+ embedding_dropout=0.0,
+ norm_eps=1e-5):
+ if image_size % patch_size != 0:
+ print(
+ '[WARNING] image_size is not divisible by patch_size',
+ flush=True)
+ assert pool_type in ('token', 'token_fc', 'attn_pool')
+ out_dim = out_dim or dim
+ super().__init__()
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_patches = (image_size // patch_size)**2
+ self.dim = dim
+ self.mlp_ratio = mlp_ratio
+ self.out_dim = out_dim
+ self.num_heads = num_heads
+ self.num_layers = num_layers
+ self.pool_type = pool_type
+ self.post_norm = post_norm
+ self.norm_eps = norm_eps
+
+ # embeddings
+ gain = 1.0 / math.sqrt(dim)
+ self.patch_embedding = nn.Conv2d(
+ 3,
+ dim,
+ kernel_size=patch_size,
+ stride=patch_size,
+ bias=not pre_norm)
+ if pool_type in ('token', 'token_fc'):
+ self.cls_embedding = nn.Parameter(gain * torch.randn(1, 1, dim))
+ self.pos_embedding = nn.Parameter(gain * torch.randn(
+ 1, self.num_patches +
+ (1 if pool_type in ('token', 'token_fc') else 0), dim))
+ self.dropout = nn.Dropout(embedding_dropout)
+
+ # transformer
+ self.pre_norm = LayerNorm(dim, eps=norm_eps) if pre_norm else None
+ self.transformer = nn.Sequential(*[
+ AttentionBlock(dim, mlp_ratio, num_heads, post_norm, False,
+ activation, attn_dropout, proj_dropout, norm_eps)
+ for _ in range(num_layers)
+ ])
+ self.post_norm = LayerNorm(dim, eps=norm_eps)
+
+ # head
+ if pool_type == 'token':
+ self.head = nn.Parameter(gain * torch.randn(dim, out_dim))
+ elif pool_type == 'token_fc':
+ self.head = nn.Linear(dim, out_dim)
+ elif pool_type == 'attn_pool':
+ self.head = AttentionPool(dim, mlp_ratio, num_heads, activation,
+ proj_dropout, norm_eps)
+
+ def forward(self, x, interpolation=False, use_31_block=False):
+ b = x.size(0)
+
+ # embeddings
+ x = self.patch_embedding(x).flatten(2).permute(0, 2, 1)
+ if self.pool_type in ('token', 'token_fc'):
+ x = torch.cat([self.cls_embedding.expand(b, -1, -1), x], dim=1)
+ if interpolation:
+ e = pos_interpolate(self.pos_embedding, x.size(1))
+ else:
+ e = self.pos_embedding
+ x = self.dropout(x + e)
+ if self.pre_norm is not None:
+ x = self.pre_norm(x)
+
+ # transformer
+ if use_31_block:
+ x = self.transformer[:-1](x)
+ return x
+ else:
+ x = self.transformer(x)
+ return x
+
+
+class XLMRobertaWithHead(XLMRoberta):
+
+ def __init__(self, **kwargs):
+ self.out_dim = kwargs.pop('out_dim')
+ super().__init__(**kwargs)
+
+ # head
+ mid_dim = (self.dim + self.out_dim) // 2
+ self.head = nn.Sequential(
+ nn.Linear(self.dim, mid_dim, bias=False), nn.GELU(),
+ nn.Linear(mid_dim, self.out_dim, bias=False))
+
+ def forward(self, ids):
+ # xlm-roberta
+ x = super().forward(ids)
+
+ # average pooling
+ mask = ids.ne(self.pad_id).unsqueeze(-1).to(x)
+ x = (x * mask).sum(dim=1) / mask.sum(dim=1)
+
+ # head
+ x = self.head(x)
+ return x
+
+
+class XLMRobertaCLIP(nn.Module):
+
+ def __init__(self,
+ embed_dim=1024,
+ image_size=224,
+ patch_size=14,
+ vision_dim=1280,
+ vision_mlp_ratio=4,
+ vision_heads=16,
+ vision_layers=32,
+ vision_pool='token',
+ vision_pre_norm=True,
+ vision_post_norm=False,
+ activation='gelu',
+ vocab_size=250002,
+ max_text_len=514,
+ type_size=1,
+ pad_id=1,
+ text_dim=1024,
+ text_heads=16,
+ text_layers=24,
+ text_post_norm=True,
+ text_dropout=0.1,
+ attn_dropout=0.0,
+ proj_dropout=0.0,
+ embedding_dropout=0.0,
+ norm_eps=1e-5):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.vision_dim = vision_dim
+ self.vision_mlp_ratio = vision_mlp_ratio
+ self.vision_heads = vision_heads
+ self.vision_layers = vision_layers
+ self.vision_pre_norm = vision_pre_norm
+ self.vision_post_norm = vision_post_norm
+ self.activation = activation
+ self.vocab_size = vocab_size
+ self.max_text_len = max_text_len
+ self.type_size = type_size
+ self.pad_id = pad_id
+ self.text_dim = text_dim
+ self.text_heads = text_heads
+ self.text_layers = text_layers
+ self.text_post_norm = text_post_norm
+ self.norm_eps = norm_eps
+
+ # models
+ self.visual = VisionTransformer(
+ image_size=image_size,
+ patch_size=patch_size,
+ dim=vision_dim,
+ mlp_ratio=vision_mlp_ratio,
+ out_dim=embed_dim,
+ num_heads=vision_heads,
+ num_layers=vision_layers,
+ pool_type=vision_pool,
+ pre_norm=vision_pre_norm,
+ post_norm=vision_post_norm,
+ activation=activation,
+ attn_dropout=attn_dropout,
+ proj_dropout=proj_dropout,
+ embedding_dropout=embedding_dropout,
+ norm_eps=norm_eps)
+ self.textual = XLMRobertaWithHead(
+ vocab_size=vocab_size,
+ max_seq_len=max_text_len,
+ type_size=type_size,
+ pad_id=pad_id,
+ dim=text_dim,
+ out_dim=embed_dim,
+ num_heads=text_heads,
+ num_layers=text_layers,
+ post_norm=text_post_norm,
+ dropout=text_dropout)
+ self.log_scale = nn.Parameter(math.log(1 / 0.07) * torch.ones([]))
+
+ def forward(self, imgs, txt_ids):
+ """
+ imgs: [B, 3, H, W] of torch.float32.
+ - mean: [0.48145466, 0.4578275, 0.40821073]
+ - std: [0.26862954, 0.26130258, 0.27577711]
+ txt_ids: [B, L] of torch.long.
+ Encoded by data.CLIPTokenizer.
+ """
+ xi = self.visual(imgs)
+ xt = self.textual(txt_ids)
+ return xi, xt
+
+ def param_groups(self):
+ groups = [{
+ 'params': [
+ p for n, p in self.named_parameters()
+ if 'norm' in n or n.endswith('bias')
+ ],
+ 'weight_decay': 0.0
+ }, {
+ 'params': [
+ p for n, p in self.named_parameters()
+ if not ('norm' in n or n.endswith('bias'))
+ ]
+ }]
+ return groups
+
+
+def _clip(pretrained=False,
+ pretrained_name=None,
+ model_cls=XLMRobertaCLIP,
+ return_transforms=False,
+ return_tokenizer=False,
+ tokenizer_padding='eos',
+ dtype=torch.float32,
+ device='cpu',
+ **kwargs):
+ # init a model on device
+ with torch.device(device):
+ model = model_cls(**kwargs)
+
+ # set device
+ model = model.to(dtype=dtype, device=device)
+ output = (model,)
+
+ # init transforms
+ if return_transforms:
+ # mean and std
+ if 'siglip' in pretrained_name.lower():
+ mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
+ else:
+ mean = [0.48145466, 0.4578275, 0.40821073]
+ std = [0.26862954, 0.26130258, 0.27577711]
+
+ # transforms
+ transforms = T.Compose([
+ T.Resize((model.image_size, model.image_size),
+ interpolation=T.InterpolationMode.BICUBIC),
+ T.ToTensor(),
+ T.Normalize(mean=mean, std=std)
+ ])
+ output += (transforms,)
+ return output[0] if len(output) == 1 else output
+
+
+def clip_xlm_roberta_vit_h_14(
+ pretrained=False,
+ pretrained_name='open-clip-xlm-roberta-large-vit-huge-14',
+ **kwargs):
+ cfg = dict(
+ embed_dim=1024,
+ image_size=224,
+ patch_size=14,
+ vision_dim=1280,
+ vision_mlp_ratio=4,
+ vision_heads=16,
+ vision_layers=32,
+ vision_pool='token',
+ activation='gelu',
+ vocab_size=250002,
+ max_text_len=514,
+ type_size=1,
+ pad_id=1,
+ text_dim=1024,
+ text_heads=16,
+ text_layers=24,
+ text_post_norm=True,
+ text_dropout=0.1,
+ attn_dropout=0.0,
+ proj_dropout=0.0,
+ embedding_dropout=0.0)
+ cfg.update(**kwargs)
+ return _clip(pretrained, pretrained_name, XLMRobertaCLIP, **cfg)
+
+
+class CLIPModel:
+
+ def __init__(self, dtype, device, checkpoint_path, tokenizer_path):
+ self.dtype = dtype
+ self.device = device
+ self.checkpoint_path = checkpoint_path
+ self.tokenizer_path = tokenizer_path
+
+ # init model
+ self.model, self.transforms = clip_xlm_roberta_vit_h_14(
+ pretrained=False,
+ return_transforms=True,
+ return_tokenizer=False,
+ dtype=dtype,
+ device=device)
+ self.model = self.model.eval().requires_grad_(False)
+ logging.info(f'loading {checkpoint_path}')
+ self.model.load_state_dict(
+ torch.load(checkpoint_path, map_location='cpu'))
+
+ # init tokenizer
+ self.tokenizer = HuggingfaceTokenizer(
+ name=tokenizer_path,
+ seq_len=self.model.max_text_len - 2,
+ clean='whitespace')
+
+ def visual(self, videos):
+ # preprocess
+ size = (self.model.image_size,) * 2
+ videos = torch.cat([
+ F.interpolate(
+ u.transpose(0, 1),
+ size=size,
+ mode='bicubic',
+ align_corners=False) for u in videos
+ ])
+ videos = self.transforms.transforms[-1](videos.mul_(0.5).add_(0.5))
+
+ # forward
+ with torch.cuda.amp.autocast(dtype=self.dtype):
+ out = self.model.visual(videos, use_31_block=True)
+ return out
\ No newline at end of file
diff --git a/wan/modules/animate/face_blocks.py b/wan/modules/animate/face_blocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..527d94a1bbc58f92420a0015827fc4fb3340ea12
--- /dev/null
+++ b/wan/modules/animate/face_blocks.py
@@ -0,0 +1,383 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from torch import nn
+import torch
+from typing import Tuple, Optional
+from einops import rearrange
+import torch.nn.functional as F
+import math
+from ...distributed.util import gather_forward, get_rank, get_world_size
+
+
+try:
+ from flash_attn import flash_attn_qkvpacked_func, flash_attn_func
+except ImportError:
+ flash_attn_func = None
+
+MEMORY_LAYOUT = {
+ "flash": (
+ lambda x: x.view(x.shape[0] * x.shape[1], *x.shape[2:]),
+ lambda x: x,
+ ),
+ "torch": (
+ lambda x: x.transpose(1, 2),
+ lambda x: x.transpose(1, 2),
+ ),
+ "vanilla": (
+ lambda x: x.transpose(1, 2),
+ lambda x: x.transpose(1, 2),
+ ),
+}
+
+
+def attention(
+ q,
+ k,
+ v,
+ mode="flash",
+ drop_rate=0,
+ attn_mask=None,
+ causal=False,
+ max_seqlen_q=None,
+ batch_size=1,
+):
+ """
+ Perform QKV self attention.
+
+ Args:
+ q (torch.Tensor): Query tensor with shape [b, s, a, d], where a is the number of heads.
+ k (torch.Tensor): Key tensor with shape [b, s1, a, d]
+ v (torch.Tensor): Value tensor with shape [b, s1, a, d]
+ mode (str): Attention mode. Choose from 'self_flash', 'cross_flash', 'torch', and 'vanilla'.
+ drop_rate (float): Dropout rate in attention map. (default: 0)
+ attn_mask (torch.Tensor): Attention mask with shape [b, s1] (cross_attn), or [b, a, s, s1] (torch or vanilla).
+ (default: None)
+ causal (bool): Whether to use causal attention. (default: False)
+ cu_seqlens_q (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
+ used to index into q.
+ cu_seqlens_kv (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
+ used to index into kv.
+ max_seqlen_q (int): The maximum sequence length in the batch of q.
+ max_seqlen_kv (int): The maximum sequence length in the batch of k and v.
+
+ Returns:
+ torch.Tensor: Output tensor after self attention with shape [b, s, ad]
+ """
+ pre_attn_layout, post_attn_layout = MEMORY_LAYOUT[mode]
+
+ if mode == "torch":
+ if attn_mask is not None and attn_mask.dtype != torch.bool:
+ attn_mask = attn_mask.to(q.dtype)
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal)
+
+ elif mode == "flash":
+ x = flash_attn_func(
+ q,
+ k,
+ v,
+ )
+ x = x.view(batch_size, max_seqlen_q, x.shape[-2], x.shape[-1]) # reshape x to [b, s, a, d]
+ elif mode == "vanilla":
+ scale_factor = 1 / math.sqrt(q.size(-1))
+
+ b, a, s, _ = q.shape
+ s1 = k.size(2)
+ attn_bias = torch.zeros(b, a, s, s1, dtype=q.dtype, device=q.device)
+ if causal:
+ # Only applied to self attention
+ assert attn_mask is None, "Causal mask and attn_mask cannot be used together"
+ temp_mask = torch.ones(b, a, s, s, dtype=torch.bool, device=q.device).tril(diagonal=0)
+ attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
+ attn_bias.to(q.dtype)
+
+ if attn_mask is not None:
+ if attn_mask.dtype == torch.bool:
+ attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
+ else:
+ attn_bias += attn_mask
+
+ attn = (q @ k.transpose(-2, -1)) * scale_factor
+ attn += attn_bias
+ attn = attn.softmax(dim=-1)
+ attn = torch.dropout(attn, p=drop_rate, train=True)
+ x = attn @ v
+ else:
+ raise NotImplementedError(f"Unsupported attention mode: {mode}")
+
+ x = post_attn_layout(x)
+ b, s, a, d = x.shape
+ out = x.reshape(b, s, -1)
+ return out
+
+
+class CausalConv1d(nn.Module):
+
+ def __init__(self, chan_in, chan_out, kernel_size=3, stride=1, dilation=1, pad_mode="replicate", **kwargs):
+ super().__init__()
+
+ self.pad_mode = pad_mode
+ padding = (kernel_size - 1, 0) # T
+ self.time_causal_padding = padding
+
+ self.conv = nn.Conv1d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs)
+
+ def forward(self, x):
+ x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)
+ return self.conv(x)
+
+
+
+class FaceEncoder(nn.Module):
+ def __init__(self, in_dim: int, hidden_dim: int, num_heads=int, dtype=None, device=None):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+
+ self.num_heads = num_heads
+ self.conv1_local = CausalConv1d(in_dim, 1024 * num_heads, 3, stride=1)
+ self.norm1 = nn.LayerNorm(hidden_dim // 8, elementwise_affine=False, eps=1e-6, **factory_kwargs)
+ self.act = nn.SiLU()
+ self.conv2 = CausalConv1d(1024, 1024, 3, stride=2)
+ self.conv3 = CausalConv1d(1024, 1024, 3, stride=2)
+
+ self.out_proj = nn.Linear(1024, hidden_dim)
+ self.norm1 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs)
+
+ self.norm2 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs)
+
+ self.norm3 = nn.LayerNorm(1024, elementwise_affine=False, eps=1e-6, **factory_kwargs)
+
+ self.padding_tokens = nn.Parameter(torch.zeros(1, 1, 1, hidden_dim))
+
+ def forward(self, x):
+
+ x = rearrange(x, "b t c -> b c t")
+ b, c, t = x.shape
+
+ x = self.conv1_local(x)
+ x = rearrange(x, "b (n c) t -> (b n) t c", n=self.num_heads)
+
+ x = self.norm1(x)
+ x = self.act(x)
+ x = rearrange(x, "b t c -> b c t")
+ x = self.conv2(x)
+ x = rearrange(x, "b c t -> b t c")
+ x = self.norm2(x)
+ x = self.act(x)
+ x = rearrange(x, "b t c -> b c t")
+ x = self.conv3(x)
+ x = rearrange(x, "b c t -> b t c")
+ x = self.norm3(x)
+ x = self.act(x)
+ x = self.out_proj(x)
+ x = rearrange(x, "(b n) t c -> b t n c", b=b)
+ padding = self.padding_tokens.repeat(b, x.shape[1], 1, 1)
+ x = torch.cat([x, padding], dim=-2)
+ x_local = x.clone()
+
+ return x_local
+
+
+
+class RMSNorm(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ elementwise_affine=True,
+ eps: float = 1e-6,
+ device=None,
+ dtype=None,
+ ):
+ """
+ Initialize the RMSNorm normalization layer.
+
+ Args:
+ dim (int): The dimension of the input tensor.
+ eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
+
+ Attributes:
+ eps (float): A small value added to the denominator for numerical stability.
+ weight (nn.Parameter): Learnable scaling parameter.
+
+ """
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.eps = eps
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim, **factory_kwargs))
+
+ def _norm(self, x):
+ """
+ Apply the RMSNorm normalization to the input tensor.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The normalized tensor.
+
+ """
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
+
+ def forward(self, x):
+ """
+ Forward pass through the RMSNorm layer.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The output tensor after applying RMSNorm.
+
+ """
+ output = self._norm(x.float()).type_as(x)
+ if hasattr(self, "weight"):
+ output = output * self.weight
+ return output
+
+
+def get_norm_layer(norm_layer):
+ """
+ Get the normalization layer.
+
+ Args:
+ norm_layer (str): The type of normalization layer.
+
+ Returns:
+ norm_layer (nn.Module): The normalization layer.
+ """
+ if norm_layer == "layer":
+ return nn.LayerNorm
+ elif norm_layer == "rms":
+ return RMSNorm
+ else:
+ raise NotImplementedError(f"Norm layer {norm_layer} is not implemented")
+
+
+class FaceAdapter(nn.Module):
+ def __init__(
+ self,
+ hidden_dim: int,
+ heads_num: int,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ num_adapter_layers: int = 1,
+ dtype=None,
+ device=None,
+ ):
+
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ self.hidden_size = hidden_dim
+ self.heads_num = heads_num
+ self.fuser_blocks = nn.ModuleList(
+ [
+ FaceBlock(
+ self.hidden_size,
+ self.heads_num,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(num_adapter_layers)
+ ]
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ motion_embed: torch.Tensor,
+ idx: int,
+ freqs_cis_q: Tuple[torch.Tensor, torch.Tensor] = None,
+ freqs_cis_k: Tuple[torch.Tensor, torch.Tensor] = None,
+ ) -> torch.Tensor:
+
+ return self.fuser_blocks[idx](x, motion_embed, freqs_cis_q, freqs_cis_k)
+
+
+
+class FaceBlock(nn.Module):
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ self.scale = qk_scale or head_dim**-0.5
+
+ self.linear1_kv = nn.Linear(hidden_size, hidden_size * 2, **factory_kwargs)
+ self.linear1_q = nn.Linear(hidden_size, hidden_size, **factory_kwargs)
+
+ self.linear2 = nn.Linear(hidden_size, hidden_size, **factory_kwargs)
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity()
+ )
+
+ self.pre_norm_feat = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs)
+
+ self.pre_norm_motion = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ motion_vec: torch.Tensor,
+ motion_mask: Optional[torch.Tensor] = None,
+ use_context_parallel=False,
+ ) -> torch.Tensor:
+
+ B, T, N, C = motion_vec.shape
+ T_comp = T
+
+ x_motion = self.pre_norm_motion(motion_vec)
+ x_feat = self.pre_norm_feat(x)
+
+ kv = self.linear1_kv(x_motion)
+ q = self.linear1_q(x_feat)
+
+ k, v = rearrange(kv, "B L N (K H D) -> K B L N H D", K=2, H=self.heads_num)
+ q = rearrange(q, "B S (H D) -> B S H D", H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ k = rearrange(k, "B L N H D -> (B L) N H D")
+ v = rearrange(v, "B L N H D -> (B L) N H D")
+
+ if use_context_parallel:
+ q = gather_forward(q, dim=1)
+
+ q = rearrange(q, "B (L S) H D -> (B L) S H D", L=T_comp)
+ # Compute attention.
+ attn = attention(
+ q,
+ k,
+ v,
+ max_seqlen_q=q.shape[1],
+ batch_size=q.shape[0],
+ )
+
+ attn = rearrange(attn, "(B L) S C -> B (L S) C", L=T_comp)
+ if use_context_parallel:
+ attn = torch.chunk(attn, get_world_size(), dim=1)[get_rank()]
+
+ output = self.linear2(attn)
+
+ if motion_mask is not None:
+ output = output * rearrange(motion_mask, "B T H W -> B (T H W)").unsqueeze(-1)
+
+ return output
\ No newline at end of file
diff --git a/wan/modules/animate/model_animate.py b/wan/modules/animate/model_animate.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b4eebd165b2698e5916c10124d8e5db8e58cb24
--- /dev/null
+++ b/wan/modules/animate/model_animate.py
@@ -0,0 +1,500 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import math
+import types
+from copy import deepcopy
+from einops import rearrange
+from typing import List
+import numpy as np
+import torch
+import torch.cuda.amp as amp
+import torch.nn as nn
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.loaders import PeftAdapterMixin
+
+from ...distributed.sequence_parallel import (
+ distributed_attention,
+ gather_forward,
+ get_rank,
+ get_world_size,
+)
+
+
+from ..model import (
+ Head,
+ WanAttentionBlock,
+ WanLayerNorm,
+ WanRMSNorm,
+ WanModel,
+ WanSelfAttention,
+ flash_attention,
+ rope_params,
+ sinusoidal_embedding_1d,
+ rope_apply
+)
+
+from .face_blocks import FaceEncoder, FaceAdapter
+from .motion_encoder import Generator
+
+class HeadAnimate(Head):
+
+ def forward(self, x, e):
+ """
+ Args:
+ x(Tensor): Shape [B, L1, C]
+ e(Tensor): Shape [B, L1, C]
+ """
+ assert e.dtype == torch.float32
+ with amp.autocast(dtype=torch.float32):
+ e = (self.modulation + e.unsqueeze(1)).chunk(2, dim=1)
+ x = (self.head(self.norm(x) * (1 + e[1]) + e[0]))
+ return x
+
+
+class WanAnimateSelfAttention(WanSelfAttention):
+
+ def forward(self, x, seq_lens, grid_sizes, freqs):
+ """
+ Args:
+ x(Tensor): Shape [B, L, num_heads, C / num_heads]
+ seq_lens(Tensor): Shape [B]
+ grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)
+ freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]
+ """
+ b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
+
+ # query, key, value function
+ def qkv_fn(x):
+ q = self.norm_q(self.q(x)).view(b, s, n, d)
+ k = self.norm_k(self.k(x)).view(b, s, n, d)
+ v = self.v(x).view(b, s, n, d)
+ return q, k, v
+
+ q, k, v = qkv_fn(x)
+
+ x = flash_attention(
+ q=rope_apply(q, grid_sizes, freqs),
+ k=rope_apply(k, grid_sizes, freqs),
+ v=v,
+ k_lens=seq_lens,
+ window_size=self.window_size)
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
+
+
+class WanAnimateCrossAttention(WanSelfAttention):
+ def __init__(
+ self,
+ dim,
+ num_heads,
+ window_size=(-1, -1),
+ qk_norm=True,
+ eps=1e-6,
+ use_img_emb=True
+ ):
+ super().__init__(
+ dim,
+ num_heads,
+ window_size,
+ qk_norm,
+ eps
+ )
+ self.use_img_emb = use_img_emb
+
+ if use_img_emb:
+ self.k_img = nn.Linear(dim, dim)
+ self.v_img = nn.Linear(dim, dim)
+ self.norm_k_img = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
+
+ def forward(self, x, context, context_lens):
+ """
+ x: [B, L1, C].
+ context: [B, L2, C].
+ context_lens: [B].
+ """
+ if self.use_img_emb:
+ context_img = context[:, :257]
+ context = context[:, 257:]
+ else:
+ context = context
+
+ b, n, d = x.size(0), self.num_heads, self.head_dim
+
+ # compute query, key, value
+ q = self.norm_q(self.q(x)).view(b, -1, n, d)
+ k = self.norm_k(self.k(context)).view(b, -1, n, d)
+ v = self.v(context).view(b, -1, n, d)
+
+ if self.use_img_emb:
+ k_img = self.norm_k_img(self.k_img(context_img)).view(b, -1, n, d)
+ v_img = self.v_img(context_img).view(b, -1, n, d)
+ img_x = flash_attention(q, k_img, v_img, k_lens=None)
+ # compute attention
+ x = flash_attention(q, k, v, k_lens=context_lens)
+
+ # output
+ x = x.flatten(2)
+
+ if self.use_img_emb:
+ img_x = img_x.flatten(2)
+ x = x + img_x
+
+ x = self.o(x)
+ return x
+
+
+class WanAnimateAttentionBlock(nn.Module):
+ def __init__(self,
+ dim,
+ ffn_dim,
+ num_heads,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=True,
+ eps=1e-6,
+ use_img_emb=True):
+
+ super().__init__()
+ self.dim = dim
+ self.ffn_dim = ffn_dim
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.cross_attn_norm = cross_attn_norm
+ self.eps = eps
+
+ # layers
+ self.norm1 = WanLayerNorm(dim, eps)
+ self.self_attn = WanAnimateSelfAttention(dim, num_heads, window_size, qk_norm, eps)
+
+ self.norm3 = WanLayerNorm(
+ dim, eps, elementwise_affine=True
+ ) if cross_attn_norm else nn.Identity()
+
+ self.cross_attn = WanAnimateCrossAttention(dim, num_heads, (-1, -1), qk_norm, eps, use_img_emb=use_img_emb)
+ self.norm2 = WanLayerNorm(dim, eps)
+ self.ffn = nn.Sequential(
+ nn.Linear(dim, ffn_dim),
+ nn.GELU(approximate='tanh'),
+ nn.Linear(ffn_dim, dim)
+ )
+
+ # modulation
+ self.modulation = nn.Parameter(torch.randn(1, 6, dim) / dim ** 0.5)
+
+ def forward(
+ self,
+ x,
+ e,
+ seq_lens,
+ grid_sizes,
+ freqs,
+ context,
+ context_lens,
+ ):
+ """
+ Args:
+ x(Tensor): Shape [B, L, C]
+ e(Tensor): Shape [B, L1, 6, C]
+ seq_lens(Tensor): Shape [B], length of each sequence in batch
+ grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)
+ freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]
+ """
+ assert e.dtype == torch.float32
+ with amp.autocast(dtype=torch.float32):
+ e = (self.modulation + e).chunk(6, dim=1)
+ assert e[0].dtype == torch.float32
+
+ # self-attention
+ y = self.self_attn(
+ self.norm1(x).float() * (1 + e[1]) + e[0], seq_lens, grid_sizes, freqs
+ )
+ with amp.autocast(dtype=torch.float32):
+ x = x + y * e[2]
+
+ # cross-attention & ffn function
+ def cross_attn_ffn(x, context, context_lens, e):
+ x = x + self.cross_attn(self.norm3(x), context, context_lens)
+ y = self.ffn(self.norm2(x).float() * (1 + e[4]) + e[3])
+ with amp.autocast(dtype=torch.float32):
+ x = x + y * e[5]
+ return x
+
+ x = cross_attn_ffn(x, context, context_lens, e)
+ return x
+
+
+class MLPProj(torch.nn.Module):
+ def __init__(self, in_dim, out_dim):
+ super().__init__()
+
+ self.proj = torch.nn.Sequential(
+ torch.nn.LayerNorm(in_dim),
+ torch.nn.Linear(in_dim, in_dim),
+ torch.nn.GELU(),
+ torch.nn.Linear(in_dim, out_dim),
+ torch.nn.LayerNorm(out_dim),
+ )
+
+ def forward(self, image_embeds):
+ clip_extra_context_tokens = self.proj(image_embeds)
+ return clip_extra_context_tokens
+
+class WanAnimateModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ _no_split_modules = ['WanAttentionBlock']
+
+ @register_to_config
+ def __init__(self,
+ patch_size=(1, 2, 2),
+ text_len=512,
+ in_dim=36,
+ dim=5120,
+ ffn_dim=13824,
+ freq_dim=256,
+ text_dim=4096,
+ out_dim=16,
+ num_heads=40,
+ num_layers=40,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=True,
+ eps=1e-6,
+ motion_encoder_dim=512,
+ use_context_parallel=False,
+ use_img_emb=True):
+
+ super().__init__()
+ self.patch_size = patch_size
+ self.text_len = text_len
+ self.in_dim = in_dim
+ self.dim = dim
+ self.ffn_dim = ffn_dim
+ self.freq_dim = freq_dim
+ self.text_dim = text_dim
+ self.out_dim = out_dim
+ self.num_heads = num_heads
+ self.num_layers = num_layers
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.cross_attn_norm = cross_attn_norm
+ self.eps = eps
+ self.motion_encoder_dim = motion_encoder_dim
+ self.use_context_parallel = use_context_parallel
+ self.use_img_emb = use_img_emb
+
+ # embeddings
+ self.patch_embedding = nn.Conv3d(
+ in_dim, dim, kernel_size=patch_size, stride=patch_size)
+
+ self.pose_patch_embedding = nn.Conv3d(
+ 16, dim, kernel_size=patch_size, stride=patch_size
+ )
+
+ self.text_embedding = nn.Sequential(
+ nn.Linear(text_dim, dim), nn.GELU(approximate='tanh'),
+ nn.Linear(dim, dim))
+
+ self.time_embedding = nn.Sequential(
+ nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
+ self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6))
+
+ # blocks
+ self.blocks = nn.ModuleList([
+ WanAnimateAttentionBlock(dim, ffn_dim, num_heads, window_size, qk_norm,
+ cross_attn_norm, eps, use_img_emb) for _ in range(num_layers)
+ ])
+
+ # head
+ self.head = HeadAnimate(dim, out_dim, patch_size, eps)
+
+ # buffers (don't use register_buffer otherwise dtype will be changed in to())
+ assert (dim % num_heads) == 0 and (dim // num_heads) % 2 == 0
+ d = dim // num_heads
+ self.freqs = torch.cat([
+ rope_params(1024, d - 4 * (d // 6)),
+ rope_params(1024, 2 * (d // 6)),
+ rope_params(1024, 2 * (d // 6))
+ ], dim=1)
+
+ self.img_emb = MLPProj(1280, dim)
+
+ # initialize weights
+ self.init_weights()
+
+ self.motion_encoder = Generator(size=512, style_dim=512, motion_dim=20)
+ self.face_adapter = FaceAdapter(
+ heads_num=self.num_heads,
+ hidden_dim=self.dim,
+ num_adapter_layers=self.num_layers // 5,
+ )
+
+ self.face_encoder = FaceEncoder(
+ in_dim=motion_encoder_dim,
+ hidden_dim=self.dim,
+ num_heads=4,
+ )
+
+ def after_patch_embedding(self, x: List[torch.Tensor], pose_latents, face_pixel_values):
+ pose_latents = [self.pose_patch_embedding(u.unsqueeze(0)) for u in pose_latents]
+ for x_, pose_latents_ in zip(x, pose_latents):
+ x_[:, :, 1:] += pose_latents_
+
+ b,c,T,h,w = face_pixel_values.shape
+ face_pixel_values = rearrange(face_pixel_values, "b c t h w -> (b t) c h w")
+
+ encode_bs = 8
+ face_pixel_values_tmp = []
+ for i in range(math.ceil(face_pixel_values.shape[0]/encode_bs)):
+ face_pixel_values_tmp.append(self.motion_encoder.get_motion(face_pixel_values[i*encode_bs:(i+1)*encode_bs]))
+
+ motion_vec = torch.cat(face_pixel_values_tmp)
+
+ motion_vec = rearrange(motion_vec, "(b t) c -> b t c", t=T)
+ motion_vec = self.face_encoder(motion_vec)
+
+ B, L, H, C = motion_vec.shape
+ pad_face = torch.zeros(B, 1, H, C).type_as(motion_vec)
+ motion_vec = torch.cat([pad_face, motion_vec], dim=1)
+ return x, motion_vec
+
+
+ def after_transformer_block(self, block_idx, x, motion_vec, motion_masks=None):
+ if block_idx % 5 == 0:
+ adapter_args = [x, motion_vec, motion_masks, self.use_context_parallel]
+ residual_out = self.face_adapter.fuser_blocks[block_idx // 5](*adapter_args)
+ x = residual_out + x
+ return x
+
+
+ def forward(
+ self,
+ x,
+ t,
+ clip_fea,
+ context,
+ seq_len,
+ y=None,
+ pose_latents=None,
+ face_pixel_values=None
+ ):
+ # params
+ device = self.patch_embedding.weight.device
+ if self.freqs.device != device:
+ self.freqs = self.freqs.to(device)
+
+ if y is not None:
+ x = [torch.cat([u, v], dim=0) for u, v in zip(x, y)]
+
+ # embeddings
+ x = [self.patch_embedding(u.unsqueeze(0)) for u in x]
+ x, motion_vec = self.after_patch_embedding(x, pose_latents, face_pixel_values)
+
+ grid_sizes = torch.stack(
+ [torch.tensor(u.shape[2:], dtype=torch.long) for u in x])
+ x = [u.flatten(2).transpose(1, 2) for u in x]
+ seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long)
+ assert seq_lens.max() <= seq_len
+ x = torch.cat([
+ torch.cat([u, u.new_zeros(1, seq_len - u.size(1), u.size(2))],
+ dim=1) for u in x
+ ])
+
+ # time embeddings
+ with amp.autocast(dtype=torch.float32):
+ e = self.time_embedding(
+ sinusoidal_embedding_1d(self.freq_dim, t).float()
+ )
+ e0 = self.time_projection(e).unflatten(1, (6, self.dim))
+ assert e.dtype == torch.float32 and e0.dtype == torch.float32
+
+ # context
+ context_lens = None
+ context = self.text_embedding(
+ torch.stack([
+ torch.cat(
+ [u, u.new_zeros(self.text_len - u.size(0), u.size(1))])
+ for u in context
+ ]))
+
+ if self.use_img_emb:
+ context_clip = self.img_emb(clip_fea) # bs x 257 x dim
+ context = torch.concat([context_clip, context], dim=1)
+
+ # arguments
+ kwargs = dict(
+ e=e0,
+ seq_lens=seq_lens,
+ grid_sizes=grid_sizes,
+ freqs=self.freqs,
+ context=context,
+ context_lens=context_lens)
+
+ if self.use_context_parallel:
+ x = torch.chunk(x, get_world_size(), dim=1)[get_rank()]
+
+ for idx, block in enumerate(self.blocks):
+ x = block(x, **kwargs)
+ x = self.after_transformer_block(idx, x, motion_vec)
+
+ # head
+ x = self.head(x, e)
+
+ if self.use_context_parallel:
+ x = gather_forward(x, dim=1)
+
+ # unpatchify
+ x = self.unpatchify(x, grid_sizes)
+ return [u.float() for u in x]
+
+
+ def unpatchify(self, x, grid_sizes):
+ r"""
+ Reconstruct video tensors from patch embeddings.
+
+ Args:
+ x (List[Tensor]):
+ List of patchified features, each with shape [L, C_out * prod(patch_size)]
+ grid_sizes (Tensor):
+ Original spatial-temporal grid dimensions before patching,
+ shape [B, 3] (3 dimensions correspond to F_patches, H_patches, W_patches)
+
+ Returns:
+ List[Tensor]:
+ Reconstructed video tensors with shape [C_out, F, H / 8, W / 8]
+ """
+
+ c = self.out_dim
+ out = []
+ for u, v in zip(x, grid_sizes.tolist()):
+ u = u[:math.prod(v)].view(*v, *self.patch_size, c)
+ u = torch.einsum('fhwpqrc->cfphqwr', u)
+ u = u.reshape(c, *[i * j for i, j in zip(v, self.patch_size)])
+ out.append(u)
+ return out
+
+ def init_weights(self):
+ r"""
+ Initialize model parameters using Xavier initialization.
+ """
+
+ # basic init
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.xavier_uniform_(m.weight)
+ if m.bias is not None:
+ nn.init.zeros_(m.bias)
+
+ # init embeddings
+ nn.init.xavier_uniform_(self.patch_embedding.weight.flatten(1))
+ for m in self.text_embedding.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.normal_(m.weight, std=.02)
+ for m in self.time_embedding.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.normal_(m.weight, std=.02)
+
+ # init output layer
+ nn.init.zeros_(self.head.head.weight)
diff --git a/wan/modules/animate/motion_encoder.py b/wan/modules/animate/motion_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d11a7062b9c94ede349e9a1f86fd68baef30b8b
--- /dev/null
+++ b/wan/modules/animate/motion_encoder.py
@@ -0,0 +1,307 @@
+# Modified from ``https://github.com/wyhsirius/LIA``
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import torch
+import torch.nn as nn
+from torch.nn import functional as F
+import math
+
+def custom_qr(input_tensor):
+ original_dtype = input_tensor.dtype
+ if original_dtype == torch.bfloat16:
+ q, r = torch.linalg.qr(input_tensor.to(torch.float32))
+ return q.to(original_dtype), r.to(original_dtype)
+ return torch.linalg.qr(input_tensor)
+
+def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5):
+ return F.leaky_relu(input + bias, negative_slope) * scale
+
+
+def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1):
+ _, minor, in_h, in_w = input.shape
+ kernel_h, kernel_w = kernel.shape
+
+ out = input.view(-1, minor, in_h, 1, in_w, 1)
+ out = F.pad(out, [0, up_x - 1, 0, 0, 0, up_y - 1, 0, 0])
+ out = out.view(-1, minor, in_h * up_y, in_w * up_x)
+
+ out = F.pad(out, [max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)])
+ out = out[:, :, max(-pad_y0, 0): out.shape[2] - max(-pad_y1, 0),
+ max(-pad_x0, 0): out.shape[3] - max(-pad_x1, 0), ]
+
+ out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1])
+ w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
+ out = F.conv2d(out, w)
+ out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1,
+ in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1, )
+ return out[:, :, ::down_y, ::down_x]
+
+
+def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
+ return upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1])
+
+
+def make_kernel(k):
+ k = torch.tensor(k, dtype=torch.float32)
+ if k.ndim == 1:
+ k = k[None, :] * k[:, None]
+ k /= k.sum()
+ return k
+
+
+class FusedLeakyReLU(nn.Module):
+ def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5):
+ super().__init__()
+ self.bias = nn.Parameter(torch.zeros(1, channel, 1, 1))
+ self.negative_slope = negative_slope
+ self.scale = scale
+
+ def forward(self, input):
+ out = fused_leaky_relu(input, self.bias, self.negative_slope, self.scale)
+ return out
+
+
+class Blur(nn.Module):
+ def __init__(self, kernel, pad, upsample_factor=1):
+ super().__init__()
+
+ kernel = make_kernel(kernel)
+
+ if upsample_factor > 1:
+ kernel = kernel * (upsample_factor ** 2)
+
+ self.register_buffer('kernel', kernel)
+
+ self.pad = pad
+
+ def forward(self, input):
+ return upfirdn2d(input, self.kernel, pad=self.pad)
+
+
+class ScaledLeakyReLU(nn.Module):
+ def __init__(self, negative_slope=0.2):
+ super().__init__()
+
+ self.negative_slope = negative_slope
+
+ def forward(self, input):
+ return F.leaky_relu(input, negative_slope=self.negative_slope)
+
+
+class EqualConv2d(nn.Module):
+ def __init__(self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True):
+ super().__init__()
+
+ self.weight = nn.Parameter(torch.randn(out_channel, in_channel, kernel_size, kernel_size))
+ self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2)
+
+ self.stride = stride
+ self.padding = padding
+
+ if bias:
+ self.bias = nn.Parameter(torch.zeros(out_channel))
+ else:
+ self.bias = None
+
+ def forward(self, input):
+
+ return F.conv2d(input, self.weight * self.scale, bias=self.bias, stride=self.stride, padding=self.padding)
+
+ def __repr__(self):
+ return (
+ f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},'
+ f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})'
+ )
+
+
+class EqualLinear(nn.Module):
+ def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None):
+ super().__init__()
+
+ self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul))
+
+ if bias:
+ self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init))
+ else:
+ self.bias = None
+
+ self.activation = activation
+
+ self.scale = (1 / math.sqrt(in_dim)) * lr_mul
+ self.lr_mul = lr_mul
+
+ def forward(self, input):
+
+ if self.activation:
+ out = F.linear(input, self.weight * self.scale)
+ out = fused_leaky_relu(out, self.bias * self.lr_mul)
+ else:
+ out = F.linear(input, self.weight * self.scale, bias=self.bias * self.lr_mul)
+
+ return out
+
+ def __repr__(self):
+ return (f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})')
+
+
+class ConvLayer(nn.Sequential):
+ def __init__(
+ self,
+ in_channel,
+ out_channel,
+ kernel_size,
+ downsample=False,
+ blur_kernel=[1, 3, 3, 1],
+ bias=True,
+ activate=True,
+ ):
+ layers = []
+
+ if downsample:
+ factor = 2
+ p = (len(blur_kernel) - factor) + (kernel_size - 1)
+ pad0 = (p + 1) // 2
+ pad1 = p // 2
+
+ layers.append(Blur(blur_kernel, pad=(pad0, pad1)))
+
+ stride = 2
+ self.padding = 0
+
+ else:
+ stride = 1
+ self.padding = kernel_size // 2
+
+ layers.append(EqualConv2d(in_channel, out_channel, kernel_size, padding=self.padding, stride=stride,
+ bias=bias and not activate))
+
+ if activate:
+ if bias:
+ layers.append(FusedLeakyReLU(out_channel))
+ else:
+ layers.append(ScaledLeakyReLU(0.2))
+
+ super().__init__(*layers)
+
+
+class ResBlock(nn.Module):
+ def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]):
+ super().__init__()
+
+ self.conv1 = ConvLayer(in_channel, in_channel, 3)
+ self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True)
+
+ self.skip = ConvLayer(in_channel, out_channel, 1, downsample=True, activate=False, bias=False)
+
+ def forward(self, input):
+ out = self.conv1(input)
+ out = self.conv2(out)
+
+ skip = self.skip(input)
+ out = (out + skip) / math.sqrt(2)
+
+ return out
+
+
+class EncoderApp(nn.Module):
+ def __init__(self, size, w_dim=512):
+ super(EncoderApp, self).__init__()
+
+ channels = {
+ 4: 512,
+ 8: 512,
+ 16: 512,
+ 32: 512,
+ 64: 256,
+ 128: 128,
+ 256: 64,
+ 512: 32,
+ 1024: 16
+ }
+
+ self.w_dim = w_dim
+ log_size = int(math.log(size, 2))
+
+ self.convs = nn.ModuleList()
+ self.convs.append(ConvLayer(3, channels[size], 1))
+
+ in_channel = channels[size]
+ for i in range(log_size, 2, -1):
+ out_channel = channels[2 ** (i - 1)]
+ self.convs.append(ResBlock(in_channel, out_channel))
+ in_channel = out_channel
+
+ self.convs.append(EqualConv2d(in_channel, self.w_dim, 4, padding=0, bias=False))
+
+ def forward(self, x):
+
+ res = []
+ h = x
+ for conv in self.convs:
+ h = conv(h)
+ res.append(h)
+
+ return res[-1].squeeze(-1).squeeze(-1), res[::-1][2:]
+
+
+class Encoder(nn.Module):
+ def __init__(self, size, dim=512, dim_motion=20):
+ super(Encoder, self).__init__()
+
+ # appearance netmork
+ self.net_app = EncoderApp(size, dim)
+
+ # motion network
+ fc = [EqualLinear(dim, dim)]
+ for i in range(3):
+ fc.append(EqualLinear(dim, dim))
+
+ fc.append(EqualLinear(dim, dim_motion))
+ self.fc = nn.Sequential(*fc)
+
+ def enc_app(self, x):
+ h_source = self.net_app(x)
+ return h_source
+
+ def enc_motion(self, x):
+ h, _ = self.net_app(x)
+ h_motion = self.fc(h)
+ return h_motion
+
+
+class Direction(nn.Module):
+ def __init__(self, motion_dim):
+ super(Direction, self).__init__()
+ self.weight = nn.Parameter(torch.randn(512, motion_dim))
+
+ def forward(self, input):
+
+ weight = self.weight + 1e-8
+ Q, R = custom_qr(weight)
+ if input is None:
+ return Q
+ else:
+ input_diag = torch.diag_embed(input) # alpha, diagonal matrix
+ out = torch.matmul(input_diag, Q.T)
+ out = torch.sum(out, dim=1)
+ return out
+
+
+class Synthesis(nn.Module):
+ def __init__(self, motion_dim):
+ super(Synthesis, self).__init__()
+ self.direction = Direction(motion_dim)
+
+
+class Generator(nn.Module):
+ def __init__(self, size, style_dim=512, motion_dim=20):
+ super().__init__()
+
+ self.enc = Encoder(size, style_dim, motion_dim)
+ self.dec = Synthesis(motion_dim)
+
+ def get_motion(self, img):
+ #motion_feat = self.enc.enc_motion(img)
+ motion_feat = torch.utils.checkpoint.checkpoint((self.enc.enc_motion), img, use_reentrant=True)
+ with torch.cuda.amp.autocast(dtype=torch.float32):
+ motion = self.dec.direction(motion_feat)
+ return motion
\ No newline at end of file
diff --git a/wan/modules/animate/preprocess/UserGuider.md b/wan/modules/animate/preprocess/UserGuider.md
new file mode 100644
index 0000000000000000000000000000000000000000..bbf11006b750eb3f8c418a812b98a1ac30f42154
--- /dev/null
+++ b/wan/modules/animate/preprocess/UserGuider.md
@@ -0,0 +1,70 @@
+# Wan-animate Preprocessing User Guider
+
+## 1. Introductions
+
+
+Wan-animate offers two generation modes: `animation` and `replacement`. While both modes extract the skeleton from the reference video, they each have a distinct preprocessing pipeline.
+
+### 1.1 Animation Mode
+
+In this mode, it is highly recommended to enable pose retargeting, especially if the body proportions of the reference and driving characters are dissimilar.
+
+ - A simplified version of pose retargeting pipeline is provided to help developers quickly implement this functionality.
+
+ - **NOTE:** Due to the potential complexity of input data, the results from this simplified retargeting version are NOT guaranteed to be perfect. It is strongly advised to verify the preprocessing results before proceeding.
+
+ - Community contributions to improve on this feature are welcome.
+
+### 1.2 Replacement Mode
+
+ - Pose retargeting is DISABLED by default in this mode. This is a deliberate choice to account for potential spatial interactions between the character and the environment.
+
+ - **WARNING**: If there is a significant mismatch in body proportions between the reference and driving characters, artifacts or deformations may appear in the final output.
+
+ - A simplified version for extracting the character's mask is also provided.
+ - **WARNING:** This mask extraction process is designed for **single-person videos ONLY** and may produce incorrect results or fail in multi-person videos (incorrect pose tracking). For multi-person video, users are required to either develop their own solution or integrate a suitable open-source tool.
+
+---
+
+## 2. Preprocessing Instructions and Recommendations
+
+### 2.1 Basic Usage
+
+- The preprocessing process requires some additional models, including pose detection (mandatory), and mask extraction and image editing models (optional, as needed). Place them according to the following directory structure:
+```
+ /path/to/your/ckpt_path/
+ ├── det/
+ │ └── yolov10m.onnx
+ ├── pose2d/
+ │ └── vitpose_h_wholebody.onnx
+ ├── sam2/
+ │ └── sam2_hiera_large.pt
+ └── FLUX.1-Kontext-dev/
+```
+- `video_path`, `refer_path`, and `save_path` correspond to the paths for the input driving video, the character image, and the preprocessed results.
+
+- When using `animation` mode, two videos, `src_face.mp4` and `src_pose.mp4`, will be generated in `save_path`. When using `replacement` mode, two additional videos, `src_bg.mp4` and `src_mask.mp4`, will also be generated.
+
+- The `resolution_area` parameter determines the resolution for both preprocessing and the generation model. Its size is determined by pixel area.
+
+- The `fps` parameter can specify the frame rate for video processing. A lower frame rate can improve generation efficiency, but may cause stuttering or choppiness.
+
+---
+
+### 2.2 Animation Mode
+
+- We support three forms: not using pose retargeting, using basic pose retargeting, and using enhanced pose retargeting based on the `FLUX.1-Kontext-dev` image editing model. These are specified via the `retarget_flag` and `use_flux` parameters.
+
+- Specifying `retarget_flag` to use basic pose retargeting requires ensuring that both the reference character and the character in the first frame of the driving video are in a front-facing, stretched pose.
+
+- Other than that, we recommend using enhanced pose retargeting by specifying both `retarget_flag` and `use_flux`. **NOTE:** Due to the limited capabilities of `FLUX.1-Kontext-dev`, it is NOT guaranteed to produce the expected results (e.g., consistency is not maintained, the pose is incorrect, etc.). It is recommended to check the intermediate results as well as the finally generated pose video; both are stored in `save_path`. Of course, users can also use a better image editing model, or explore the prompts for Flux on their own.
+
+---
+
+### 2.3 Replacement Mode
+
+- Specifying `replace_flag` to enable data preprocessing for this mode. The preprocessing will additionally process a mask for the character in the video, and its size and shape can be adjusted by specifying some parameters.
+- `iterations` and `k` can make the mask larger, covering more area.
+- `w_len` and `h_len` can adjust the mask's shape. Smaller values will make the outline coarser, while larger values will make it finer.
+
+- A smaller, finer-contoured mask can allow for more of the original background to be preserved, but may potentially limit the character's generation area (considering potential appearance differences, this can lead to some shape leakage). A larger, coarser mask can allow the character generation to be more flexible and consistent, but because it includes more of the background, it might affect the background's consistency. We recommend users to adjust the relevant parameters based on their specific input data.
\ No newline at end of file
diff --git a/wan/modules/animate/preprocess/__init__.py b/wan/modules/animate/preprocess/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae2d9a2769b6606dcd807edfd162091fe52d965d
--- /dev/null
+++ b/wan/modules/animate/preprocess/__init__.py
@@ -0,0 +1,3 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from .process_pipepline import ProcessPipeline
+from .video_predictor import SAM2VideoPredictor
\ No newline at end of file
diff --git a/wan/modules/animate/preprocess/human_visualization.py b/wan/modules/animate/preprocess/human_visualization.py
new file mode 100644
index 0000000000000000000000000000000000000000..740a48734a9f35ccb8fc9c786ffdb7d171952236
--- /dev/null
+++ b/wan/modules/animate/preprocess/human_visualization.py
@@ -0,0 +1,1357 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import os
+import cv2
+import time
+import math
+import matplotlib
+import matplotlib.pyplot as plt
+import numpy as np
+from typing import Dict, List
+import random
+from pose2d_utils import AAPoseMeta
+
+
+def draw_handpose(canvas, keypoints, hand_score_th=0.6):
+ """
+ Draw keypoints and connections representing hand pose on a given canvas.
+
+ Args:
+ canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the hand pose.
+ keypoints (List[Keypoint]| None): A list of Keypoint objects representing the hand keypoints to be drawn
+ or None if no keypoints are present.
+
+ Returns:
+ np.ndarray: A 3D numpy array representing the modified canvas with the drawn hand pose.
+
+ Note:
+ The function expects the x and y coordinates of the keypoints to be normalized between 0 and 1.
+ """
+ eps = 0.01
+
+ H, W, C = canvas.shape
+ stickwidth = max(int(min(H, W) / 200), 1)
+
+ edges = [
+ [0, 1],
+ [1, 2],
+ [2, 3],
+ [3, 4],
+ [0, 5],
+ [5, 6],
+ [6, 7],
+ [7, 8],
+ [0, 9],
+ [9, 10],
+ [10, 11],
+ [11, 12],
+ [0, 13],
+ [13, 14],
+ [14, 15],
+ [15, 16],
+ [0, 17],
+ [17, 18],
+ [18, 19],
+ [19, 20],
+ ]
+
+ for ie, (e1, e2) in enumerate(edges):
+ k1 = keypoints[e1]
+ k2 = keypoints[e2]
+ if k1 is None or k2 is None:
+ continue
+ if k1[2] < hand_score_th or k2[2] < hand_score_th:
+ continue
+
+ x1 = int(k1[0])
+ y1 = int(k1[1])
+ x2 = int(k2[0])
+ y2 = int(k2[1])
+ if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
+ cv2.line(
+ canvas,
+ (x1, y1),
+ (x2, y2),
+ matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * 255,
+ thickness=stickwidth,
+ )
+
+ for keypoint in keypoints:
+
+ if keypoint is None:
+ continue
+ if keypoint[2] < hand_score_th:
+ continue
+
+ x, y = keypoint[0], keypoint[1]
+ x = int(x)
+ y = int(y)
+ if x > eps and y > eps:
+ cv2.circle(canvas, (x, y), stickwidth, (0, 0, 255), thickness=-1)
+ return canvas
+
+
+def draw_handpose_new(canvas, keypoints, stickwidth_type='v2', hand_score_th=0.6):
+ """
+ Draw keypoints and connections representing hand pose on a given canvas.
+
+ Args:
+ canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the hand pose.
+ keypoints (List[Keypoint]| None): A list of Keypoint objects representing the hand keypoints to be drawn
+ or None if no keypoints are present.
+
+ Returns:
+ np.ndarray: A 3D numpy array representing the modified canvas with the drawn hand pose.
+
+ Note:
+ The function expects the x and y coordinates of the keypoints to be normalized between 0 and 1.
+ """
+ eps = 0.01
+
+ H, W, C = canvas.shape
+ if stickwidth_type == 'v1':
+ stickwidth = max(int(min(H, W) / 200), 1)
+ elif stickwidth_type == 'v2':
+ stickwidth = max(max(int(min(H, W) / 200) - 1, 1) // 2, 1)
+
+ edges = [
+ [0, 1],
+ [1, 2],
+ [2, 3],
+ [3, 4],
+ [0, 5],
+ [5, 6],
+ [6, 7],
+ [7, 8],
+ [0, 9],
+ [9, 10],
+ [10, 11],
+ [11, 12],
+ [0, 13],
+ [13, 14],
+ [14, 15],
+ [15, 16],
+ [0, 17],
+ [17, 18],
+ [18, 19],
+ [19, 20],
+ ]
+
+ for ie, (e1, e2) in enumerate(edges):
+ k1 = keypoints[e1]
+ k2 = keypoints[e2]
+ if k1 is None or k2 is None:
+ continue
+ if k1[2] < hand_score_th or k2[2] < hand_score_th:
+ continue
+
+ x1 = int(k1[0])
+ y1 = int(k1[1])
+ x2 = int(k2[0])
+ y2 = int(k2[1])
+ if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
+ cv2.line(
+ canvas,
+ (x1, y1),
+ (x2, y2),
+ matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * 255,
+ thickness=stickwidth,
+ )
+
+ for keypoint in keypoints:
+
+ if keypoint is None:
+ continue
+ if keypoint[2] < hand_score_th:
+ continue
+
+ x, y = keypoint[0], keypoint[1]
+ x = int(x)
+ y = int(y)
+ if x > eps and y > eps:
+ cv2.circle(canvas, (x, y), stickwidth, (0, 0, 255), thickness=-1)
+ return canvas
+
+
+def draw_ellipse_by_2kp(img, keypoint1, keypoint2, color, threshold=0.6):
+ H, W, C = img.shape
+ stickwidth = max(int(min(H, W) / 200), 1)
+
+ if keypoint1[-1] < threshold or keypoint2[-1] < threshold:
+ return img
+
+ Y = np.array([keypoint1[0], keypoint2[0]])
+ X = np.array([keypoint1[1], keypoint2[1]])
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(img, polygon, [int(float(c) * 0.6) for c in color])
+ return img
+
+
+def split_pose2d_kps_to_aa(kp2ds: np.ndarray) -> List[np.ndarray]:
+ """Convert the 133 keypoints from pose2d to body and hands keypoints.
+
+ Args:
+ kp2ds (np.ndarray): [133, 2]
+
+ Returns:
+ List[np.ndarray]: _description_
+ """
+ kp2ds_body = (
+ kp2ds[[0, 6, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 17, 20]]
+ + kp2ds[[0, 5, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 18, 21]]
+ ) / 2
+ kp2ds_lhand = kp2ds[91:112]
+ kp2ds_rhand = kp2ds[112:133]
+ return kp2ds_body.copy(), kp2ds_lhand.copy(), kp2ds_rhand.copy()
+
+
+def draw_aapose_by_meta(img, meta: AAPoseMeta, threshold=0.5, stick_width_norm=200, draw_hand=True, draw_head=True):
+ kp2ds = np.concatenate([meta.kps_body, meta.kps_body_p[:, None]], axis=1)
+ kp2ds_lhand = np.concatenate([meta.kps_lhand, meta.kps_lhand_p[:, None]], axis=1)
+ kp2ds_rhand = np.concatenate([meta.kps_rhand, meta.kps_rhand_p[:, None]], axis=1)
+ pose_img = draw_aapose(img, kp2ds, threshold, kp2ds_lhand=kp2ds_lhand, kp2ds_rhand=kp2ds_rhand, stick_width_norm=stick_width_norm, draw_hand=draw_hand, draw_head=draw_head)
+ return pose_img
+
+def draw_aapose_by_meta_new(img, meta: AAPoseMeta, threshold=0.5, stickwidth_type='v2', draw_hand=True, draw_head=True):
+ kp2ds = np.concatenate([meta.kps_body, meta.kps_body_p[:, None]], axis=1)
+ kp2ds_lhand = np.concatenate([meta.kps_lhand, meta.kps_lhand_p[:, None]], axis=1)
+ kp2ds_rhand = np.concatenate([meta.kps_rhand, meta.kps_rhand_p[:, None]], axis=1)
+ pose_img = draw_aapose_new(img, kp2ds, threshold, kp2ds_lhand=kp2ds_lhand, kp2ds_rhand=kp2ds_rhand,
+ stickwidth_type=stickwidth_type, draw_hand=draw_hand, draw_head=draw_head)
+ return pose_img
+
+def draw_hand_by_meta(img, meta: AAPoseMeta, threshold=0.5, stick_width_norm=200):
+ kp2ds = np.concatenate([meta.kps_body, meta.kps_body_p[:, None] * 0], axis=1)
+ kp2ds_lhand = np.concatenate([meta.kps_lhand, meta.kps_lhand_p[:, None]], axis=1)
+ kp2ds_rhand = np.concatenate([meta.kps_rhand, meta.kps_rhand_p[:, None]], axis=1)
+ pose_img = draw_aapose(img, kp2ds, threshold, kp2ds_lhand=kp2ds_lhand, kp2ds_rhand=kp2ds_rhand, stick_width_norm=stick_width_norm, draw_hand=True, draw_head=False)
+ return pose_img
+
+
+def draw_aaface_by_meta(img, meta: AAPoseMeta, threshold=0.5, stick_width_norm=200, draw_hand=False, draw_head=True):
+ kp2ds = np.concatenate([meta.kps_body, meta.kps_body_p[:, None]], axis=1)
+ # kp2ds_lhand = np.concatenate([meta.kps_lhand, meta.kps_lhand_p[:, None]], axis=1)
+ # kp2ds_rhand = np.concatenate([meta.kps_rhand, meta.kps_rhand_p[:, None]], axis=1)
+ pose_img = draw_M(img, kp2ds, threshold, kp2ds_lhand=None, kp2ds_rhand=None, stick_width_norm=stick_width_norm, draw_hand=draw_hand, draw_head=draw_head)
+ return pose_img
+
+
+def draw_aanose_by_meta(img, meta: AAPoseMeta, threshold=0.5, stick_width_norm=100, draw_hand=False):
+ kp2ds = np.concatenate([meta.kps_body, meta.kps_body_p[:, None]], axis=1)
+ # kp2ds_lhand = np.concatenate([meta.kps_lhand, meta.kps_lhand_p[:, None]], axis=1)
+ # kp2ds_rhand = np.concatenate([meta.kps_rhand, meta.kps_rhand_p[:, None]], axis=1)
+ pose_img = draw_nose(img, kp2ds, threshold, kp2ds_lhand=None, kp2ds_rhand=None, stick_width_norm=stick_width_norm, draw_hand=draw_hand)
+ return pose_img
+
+
+def gen_face_motion_seq(img, metas: List[AAPoseMeta], threshold=0.5, stick_width_norm=200):
+
+ return
+
+
+def draw_M(
+ img,
+ kp2ds,
+ threshold=0.6,
+ data_to_json=None,
+ idx=-1,
+ kp2ds_lhand=None,
+ kp2ds_rhand=None,
+ draw_hand=False,
+ stick_width_norm=200,
+ draw_head=True
+):
+ """
+ Draw keypoints and connections representing hand pose on a given canvas.
+
+ Args:
+ canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the hand pose.
+ keypoints (List[Keypoint]| None): A list of Keypoint objects representing the hand keypoints to be drawn
+ or None if no keypoints are present.
+
+ Returns:
+ np.ndarray: A 3D numpy array representing the modified canvas with the drawn hand pose.
+
+ Note:
+ The function expects the x and y coordinates of the keypoints to be normalized between 0 and 1.
+ """
+
+ new_kep_list = [
+ "Nose",
+ "Neck",
+ "RShoulder",
+ "RElbow",
+ "RWrist", # No.4
+ "LShoulder",
+ "LElbow",
+ "LWrist", # No.7
+ "RHip",
+ "RKnee",
+ "RAnkle", # No.10
+ "LHip",
+ "LKnee",
+ "LAnkle", # No.13
+ "REye",
+ "LEye",
+ "REar",
+ "LEar",
+ "LToe",
+ "RToe",
+ ]
+ # kp2ds_body = (kp2ds.copy()[[0, 6, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 17, 20]] + \
+ # kp2ds.copy()[[0, 5, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 18, 21]]) / 2
+ kp2ds = kp2ds.copy()
+ # import ipdb; ipdb.set_trace()
+ kp2ds[[1,2,3,4,5,6,7,8,9,10,11,12,13,18,19], 2] = 0
+ if not draw_head:
+ kp2ds[[0,14,15,16,17], 2] = 0
+ kp2ds_body = kp2ds
+ # kp2ds_body = kp2ds_body[:18]
+
+ # kp2ds_lhand = kp2ds.copy()[91:112]
+ # kp2ds_rhand = kp2ds.copy()[112:133]
+
+ limbSeq = [
+ # [2, 3],
+ # [2, 6], # shoulders
+ # [3, 4],
+ # [4, 5], # left arm
+ # [6, 7],
+ # [7, 8], # right arm
+ # [2, 9],
+ # [9, 10],
+ # [10, 11], # right leg
+ # [2, 12],
+ # [12, 13],
+ # [13, 14], # left leg
+ # [2, 1],
+ [1, 15],
+ [15, 17],
+ [1, 16],
+ [16, 18], # face (nose, eyes, ears)
+ # [14, 19],
+ # [11, 20], # foot
+ ]
+
+ colors = [
+ # [255, 0, 0],
+ # [255, 85, 0],
+ # [255, 170, 0],
+ # [255, 255, 0],
+ # [170, 255, 0],
+ # [85, 255, 0],
+ # [0, 255, 0],
+ # [0, 255, 85],
+ # [0, 255, 170],
+ # [0, 255, 255],
+ # [0, 170, 255],
+ # [0, 85, 255],
+ # [0, 0, 255],
+ # [85, 0, 255],
+ [170, 0, 255],
+ [255, 0, 255],
+ [255, 0, 170],
+ [255, 0, 85],
+ # foot
+ # [200, 200, 0],
+ # [100, 100, 0],
+ ]
+
+ H, W, C = img.shape
+ stickwidth = max(int(min(H, W) / stick_width_norm), 1)
+
+ for _idx, ((k1_index, k2_index), color) in enumerate(zip(limbSeq, colors)):
+ keypoint1 = kp2ds_body[k1_index - 1]
+ keypoint2 = kp2ds_body[k2_index - 1]
+
+ if keypoint1[-1] < threshold or keypoint2[-1] < threshold:
+ continue
+
+ Y = np.array([keypoint1[0], keypoint2[0]])
+ X = np.array([keypoint1[1], keypoint2[1]])
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(img, polygon, [int(float(c) * 0.6) for c in color])
+
+ for _idx, (keypoint, color) in enumerate(zip(kp2ds_body, colors)):
+ if keypoint[-1] < threshold:
+ continue
+ x, y = keypoint[0], keypoint[1]
+ # cv2.circle(canvas, (int(x), int(y)), 4, color, thickness=-1)
+ cv2.circle(img, (int(x), int(y)), stickwidth, color, thickness=-1)
+
+ if draw_hand:
+ img = draw_handpose(img, kp2ds_lhand, hand_score_th=threshold)
+ img = draw_handpose(img, kp2ds_rhand, hand_score_th=threshold)
+
+ kp2ds_body[:, 0] /= W
+ kp2ds_body[:, 1] /= H
+
+ if data_to_json is not None:
+ if idx == -1:
+ data_to_json.append(
+ {
+ "image_id": "frame_{:05d}.jpg".format(len(data_to_json) + 1),
+ "height": H,
+ "width": W,
+ "category_id": 1,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ }
+ )
+ else:
+ data_to_json[idx] = {
+ "image_id": "frame_{:05d}.jpg".format(idx + 1),
+ "height": H,
+ "width": W,
+ "category_id": 1,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ }
+ return img
+
+
+def draw_nose(
+ img,
+ kp2ds,
+ threshold=0.6,
+ data_to_json=None,
+ idx=-1,
+ kp2ds_lhand=None,
+ kp2ds_rhand=None,
+ draw_hand=False,
+ stick_width_norm=200,
+):
+ """
+ Draw keypoints and connections representing hand pose on a given canvas.
+
+ Args:
+ canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the hand pose.
+ keypoints (List[Keypoint]| None): A list of Keypoint objects representing the hand keypoints to be drawn
+ or None if no keypoints are present.
+
+ Returns:
+ np.ndarray: A 3D numpy array representing the modified canvas with the drawn hand pose.
+
+ Note:
+ The function expects the x and y coordinates of the keypoints to be normalized between 0 and 1.
+ """
+
+ new_kep_list = [
+ "Nose",
+ "Neck",
+ "RShoulder",
+ "RElbow",
+ "RWrist", # No.4
+ "LShoulder",
+ "LElbow",
+ "LWrist", # No.7
+ "RHip",
+ "RKnee",
+ "RAnkle", # No.10
+ "LHip",
+ "LKnee",
+ "LAnkle", # No.13
+ "REye",
+ "LEye",
+ "REar",
+ "LEar",
+ "LToe",
+ "RToe",
+ ]
+ # kp2ds_body = (kp2ds.copy()[[0, 6, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 17, 20]] + \
+ # kp2ds.copy()[[0, 5, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 18, 21]]) / 2
+ kp2ds = kp2ds.copy()
+ kp2ds[1:, 2] = 0
+ # kp2ds[0, 2] = 1
+ kp2ds_body = kp2ds
+ # kp2ds_body = kp2ds_body[:18]
+
+ # kp2ds_lhand = kp2ds.copy()[91:112]
+ # kp2ds_rhand = kp2ds.copy()[112:133]
+
+ limbSeq = [
+ # [2, 3],
+ # [2, 6], # shoulders
+ # [3, 4],
+ # [4, 5], # left arm
+ # [6, 7],
+ # [7, 8], # right arm
+ # [2, 9],
+ # [9, 10],
+ # [10, 11], # right leg
+ # [2, 12],
+ # [12, 13],
+ # [13, 14], # left leg
+ # [2, 1],
+ [1, 15],
+ [15, 17],
+ [1, 16],
+ [16, 18], # face (nose, eyes, ears)
+ # [14, 19],
+ # [11, 20], # foot
+ ]
+
+ colors = [
+ # [255, 0, 0],
+ # [255, 85, 0],
+ # [255, 170, 0],
+ # [255, 255, 0],
+ # [170, 255, 0],
+ # [85, 255, 0],
+ # [0, 255, 0],
+ # [0, 255, 85],
+ # [0, 255, 170],
+ # [0, 255, 255],
+ # [0, 170, 255],
+ # [0, 85, 255],
+ # [0, 0, 255],
+ # [85, 0, 255],
+ [170, 0, 255],
+ # [255, 0, 255],
+ # [255, 0, 170],
+ # [255, 0, 85],
+ # foot
+ # [200, 200, 0],
+ # [100, 100, 0],
+ ]
+
+ H, W, C = img.shape
+ stickwidth = max(int(min(H, W) / stick_width_norm), 1)
+
+ # for _idx, ((k1_index, k2_index), color) in enumerate(zip(limbSeq, colors)):
+ # keypoint1 = kp2ds_body[k1_index - 1]
+ # keypoint2 = kp2ds_body[k2_index - 1]
+
+ # if keypoint1[-1] < threshold or keypoint2[-1] < threshold:
+ # continue
+
+ # Y = np.array([keypoint1[0], keypoint2[0]])
+ # X = np.array([keypoint1[1], keypoint2[1]])
+ # mX = np.mean(X)
+ # mY = np.mean(Y)
+ # length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ # angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ # polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
+ # cv2.fillConvexPoly(img, polygon, [int(float(c) * 0.6) for c in color])
+
+ for _idx, (keypoint, color) in enumerate(zip(kp2ds_body, colors)):
+ if keypoint[-1] < threshold:
+ continue
+ x, y = keypoint[0], keypoint[1]
+ # cv2.circle(canvas, (int(x), int(y)), 4, color, thickness=-1)
+ cv2.circle(img, (int(x), int(y)), stickwidth, color, thickness=-1)
+
+ if draw_hand:
+ img = draw_handpose(img, kp2ds_lhand, hand_score_th=threshold)
+ img = draw_handpose(img, kp2ds_rhand, hand_score_th=threshold)
+
+ kp2ds_body[:, 0] /= W
+ kp2ds_body[:, 1] /= H
+
+ if data_to_json is not None:
+ if idx == -1:
+ data_to_json.append(
+ {
+ "image_id": "frame_{:05d}.jpg".format(len(data_to_json) + 1),
+ "height": H,
+ "width": W,
+ "category_id": 1,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ }
+ )
+ else:
+ data_to_json[idx] = {
+ "image_id": "frame_{:05d}.jpg".format(idx + 1),
+ "height": H,
+ "width": W,
+ "category_id": 1,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ }
+ return img
+
+
+def draw_aapose(
+ img,
+ kp2ds,
+ threshold=0.6,
+ data_to_json=None,
+ idx=-1,
+ kp2ds_lhand=None,
+ kp2ds_rhand=None,
+ draw_hand=False,
+ stick_width_norm=200,
+ draw_head=True
+):
+ """
+ Draw keypoints and connections representing hand pose on a given canvas.
+
+ Args:
+ canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the hand pose.
+ keypoints (List[Keypoint]| None): A list of Keypoint objects representing the hand keypoints to be drawn
+ or None if no keypoints are present.
+
+ Returns:
+ np.ndarray: A 3D numpy array representing the modified canvas with the drawn hand pose.
+
+ Note:
+ The function expects the x and y coordinates of the keypoints to be normalized between 0 and 1.
+ """
+
+ new_kep_list = [
+ "Nose",
+ "Neck",
+ "RShoulder",
+ "RElbow",
+ "RWrist", # No.4
+ "LShoulder",
+ "LElbow",
+ "LWrist", # No.7
+ "RHip",
+ "RKnee",
+ "RAnkle", # No.10
+ "LHip",
+ "LKnee",
+ "LAnkle", # No.13
+ "REye",
+ "LEye",
+ "REar",
+ "LEar",
+ "LToe",
+ "RToe",
+ ]
+ # kp2ds_body = (kp2ds.copy()[[0, 6, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 17, 20]] + \
+ # kp2ds.copy()[[0, 5, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 18, 21]]) / 2
+ kp2ds = kp2ds.copy()
+ if not draw_head:
+ kp2ds[[0,14,15,16,17], 2] = 0
+ kp2ds_body = kp2ds
+
+ # kp2ds_lhand = kp2ds.copy()[91:112]
+ # kp2ds_rhand = kp2ds.copy()[112:133]
+
+ limbSeq = [
+ [2, 3],
+ [2, 6], # shoulders
+ [3, 4],
+ [4, 5], # left arm
+ [6, 7],
+ [7, 8], # right arm
+ [2, 9],
+ [9, 10],
+ [10, 11], # right leg
+ [2, 12],
+ [12, 13],
+ [13, 14], # left leg
+ [2, 1],
+ [1, 15],
+ [15, 17],
+ [1, 16],
+ [16, 18], # face (nose, eyes, ears)
+ [14, 19],
+ [11, 20], # foot
+ ]
+
+ colors = [
+ [255, 0, 0],
+ [255, 85, 0],
+ [255, 170, 0],
+ [255, 255, 0],
+ [170, 255, 0],
+ [85, 255, 0],
+ [0, 255, 0],
+ [0, 255, 85],
+ [0, 255, 170],
+ [0, 255, 255],
+ [0, 170, 255],
+ [0, 85, 255],
+ [0, 0, 255],
+ [85, 0, 255],
+ [170, 0, 255],
+ [255, 0, 255],
+ [255, 0, 170],
+ [255, 0, 85],
+ # foot
+ [200, 200, 0],
+ [100, 100, 0],
+ ]
+
+ H, W, C = img.shape
+ stickwidth = max(int(min(H, W) / stick_width_norm), 1)
+
+ for _idx, ((k1_index, k2_index), color) in enumerate(zip(limbSeq, colors)):
+ keypoint1 = kp2ds_body[k1_index - 1]
+ keypoint2 = kp2ds_body[k2_index - 1]
+
+ if keypoint1[-1] < threshold or keypoint2[-1] < threshold:
+ continue
+
+ Y = np.array([keypoint1[0], keypoint2[0]])
+ X = np.array([keypoint1[1], keypoint2[1]])
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(img, polygon, [int(float(c) * 0.6) for c in color])
+
+ for _idx, (keypoint, color) in enumerate(zip(kp2ds_body, colors)):
+ if keypoint[-1] < threshold:
+ continue
+ x, y = keypoint[0], keypoint[1]
+ # cv2.circle(canvas, (int(x), int(y)), 4, color, thickness=-1)
+ cv2.circle(img, (int(x), int(y)), stickwidth, color, thickness=-1)
+
+ if draw_hand:
+ img = draw_handpose(img, kp2ds_lhand, hand_score_th=threshold)
+ img = draw_handpose(img, kp2ds_rhand, hand_score_th=threshold)
+
+ kp2ds_body[:, 0] /= W
+ kp2ds_body[:, 1] /= H
+
+ if data_to_json is not None:
+ if idx == -1:
+ data_to_json.append(
+ {
+ "image_id": "frame_{:05d}.jpg".format(len(data_to_json) + 1),
+ "height": H,
+ "width": W,
+ "category_id": 1,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ }
+ )
+ else:
+ data_to_json[idx] = {
+ "image_id": "frame_{:05d}.jpg".format(idx + 1),
+ "height": H,
+ "width": W,
+ "category_id": 1,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ }
+ return img
+
+
+def draw_aapose_new(
+ img,
+ kp2ds,
+ threshold=0.6,
+ data_to_json=None,
+ idx=-1,
+ kp2ds_lhand=None,
+ kp2ds_rhand=None,
+ draw_hand=False,
+ stickwidth_type='v2',
+ draw_head=True
+):
+ """
+ Draw keypoints and connections representing hand pose on a given canvas.
+
+ Args:
+ canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the hand pose.
+ keypoints (List[Keypoint]| None): A list of Keypoint objects representing the hand keypoints to be drawn
+ or None if no keypoints are present.
+
+ Returns:
+ np.ndarray: A 3D numpy array representing the modified canvas with the drawn hand pose.
+
+ Note:
+ The function expects the x and y coordinates of the keypoints to be normalized between 0 and 1.
+ """
+
+ new_kep_list = [
+ "Nose",
+ "Neck",
+ "RShoulder",
+ "RElbow",
+ "RWrist", # No.4
+ "LShoulder",
+ "LElbow",
+ "LWrist", # No.7
+ "RHip",
+ "RKnee",
+ "RAnkle", # No.10
+ "LHip",
+ "LKnee",
+ "LAnkle", # No.13
+ "REye",
+ "LEye",
+ "REar",
+ "LEar",
+ "LToe",
+ "RToe",
+ ]
+ # kp2ds_body = (kp2ds.copy()[[0, 6, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 17, 20]] + \
+ # kp2ds.copy()[[0, 5, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 18, 21]]) / 2
+ kp2ds = kp2ds.copy()
+ if not draw_head:
+ kp2ds[[0,14,15,16,17], 2] = 0
+ kp2ds_body = kp2ds
+
+ # kp2ds_lhand = kp2ds.copy()[91:112]
+ # kp2ds_rhand = kp2ds.copy()[112:133]
+
+ limbSeq = [
+ [2, 3],
+ [2, 6], # shoulders
+ [3, 4],
+ [4, 5], # left arm
+ [6, 7],
+ [7, 8], # right arm
+ [2, 9],
+ [9, 10],
+ [10, 11], # right leg
+ [2, 12],
+ [12, 13],
+ [13, 14], # left leg
+ [2, 1],
+ [1, 15],
+ [15, 17],
+ [1, 16],
+ [16, 18], # face (nose, eyes, ears)
+ [14, 19],
+ [11, 20], # foot
+ ]
+
+ colors = [
+ [255, 0, 0],
+ [255, 85, 0],
+ [255, 170, 0],
+ [255, 255, 0],
+ [170, 255, 0],
+ [85, 255, 0],
+ [0, 255, 0],
+ [0, 255, 85],
+ [0, 255, 170],
+ [0, 255, 255],
+ [0, 170, 255],
+ [0, 85, 255],
+ [0, 0, 255],
+ [85, 0, 255],
+ [170, 0, 255],
+ [255, 0, 255],
+ [255, 0, 170],
+ [255, 0, 85],
+ # foot
+ [200, 200, 0],
+ [100, 100, 0],
+ ]
+
+ H, W, C = img.shape
+ H, W, C = img.shape
+
+ if stickwidth_type == 'v1':
+ stickwidth = max(int(min(H, W) / 200), 1)
+ elif stickwidth_type == 'v2':
+ stickwidth = max(int(min(H, W) / 200) - 1, 1)
+ else:
+ raise
+
+ for _idx, ((k1_index, k2_index), color) in enumerate(zip(limbSeq, colors)):
+ keypoint1 = kp2ds_body[k1_index - 1]
+ keypoint2 = kp2ds_body[k2_index - 1]
+
+ if keypoint1[-1] < threshold or keypoint2[-1] < threshold:
+ continue
+
+ Y = np.array([keypoint1[0], keypoint2[0]])
+ X = np.array([keypoint1[1], keypoint2[1]])
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(img, polygon, [int(float(c) * 0.6) for c in color])
+
+ for _idx, (keypoint, color) in enumerate(zip(kp2ds_body, colors)):
+ if keypoint[-1] < threshold:
+ continue
+ x, y = keypoint[0], keypoint[1]
+ # cv2.circle(canvas, (int(x), int(y)), 4, color, thickness=-1)
+ cv2.circle(img, (int(x), int(y)), stickwidth, color, thickness=-1)
+
+ if draw_hand:
+ img = draw_handpose_new(img, kp2ds_lhand, stickwidth_type=stickwidth_type, hand_score_th=threshold)
+ img = draw_handpose_new(img, kp2ds_rhand, stickwidth_type=stickwidth_type, hand_score_th=threshold)
+
+ kp2ds_body[:, 0] /= W
+ kp2ds_body[:, 1] /= H
+
+ if data_to_json is not None:
+ if idx == -1:
+ data_to_json.append(
+ {
+ "image_id": "frame_{:05d}.jpg".format(len(data_to_json) + 1),
+ "height": H,
+ "width": W,
+ "category_id": 1,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ }
+ )
+ else:
+ data_to_json[idx] = {
+ "image_id": "frame_{:05d}.jpg".format(idx + 1),
+ "height": H,
+ "width": W,
+ "category_id": 1,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ }
+ return img
+
+
+def draw_bbox(img, bbox, color=(255, 0, 0)):
+ img = load_image(img)
+ bbox = [int(bbox_tmp) for bbox_tmp in bbox]
+ cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color, 2)
+ return img
+
+
+def draw_kp2ds(img, kp2ds, threshold=0, color=(255, 0, 0), skeleton=None, reverse=False):
+ img = load_image(img, reverse)
+
+ if skeleton is not None:
+ if skeleton == "coco17":
+ skeleton_list = [
+ [6, 8],
+ [8, 10],
+ [5, 7],
+ [7, 9],
+ [11, 13],
+ [13, 15],
+ [12, 14],
+ [14, 16],
+ [5, 6],
+ [6, 12],
+ [12, 11],
+ [11, 5],
+ ]
+ color_list = [
+ (255, 0, 0),
+ (0, 255, 0),
+ (0, 0, 255),
+ (255, 255, 0),
+ (255, 0, 255),
+ (0, 255, 255),
+ ]
+ elif skeleton == "cocowholebody":
+ skeleton_list = [
+ [6, 8],
+ [8, 10],
+ [5, 7],
+ [7, 9],
+ [11, 13],
+ [13, 15],
+ [12, 14],
+ [14, 16],
+ [5, 6],
+ [6, 12],
+ [12, 11],
+ [11, 5],
+ [15, 17],
+ [15, 18],
+ [15, 19],
+ [16, 20],
+ [16, 21],
+ [16, 22],
+ [91, 92, 93, 94, 95],
+ [91, 96, 97, 98, 99],
+ [91, 100, 101, 102, 103],
+ [91, 104, 105, 106, 107],
+ [91, 108, 109, 110, 111],
+ [112, 113, 114, 115, 116],
+ [112, 117, 118, 119, 120],
+ [112, 121, 122, 123, 124],
+ [112, 125, 126, 127, 128],
+ [112, 129, 130, 131, 132],
+ ]
+ color_list = [
+ (255, 0, 0),
+ (0, 255, 0),
+ (0, 0, 255),
+ (255, 255, 0),
+ (255, 0, 255),
+ (0, 255, 255),
+ ]
+ else:
+ color_list = [color]
+ for _idx, _skeleton in enumerate(skeleton_list):
+ for i in range(len(_skeleton) - 1):
+ cv2.line(
+ img,
+ (int(kp2ds[_skeleton[i], 0]), int(kp2ds[_skeleton[i], 1])),
+ (int(kp2ds[_skeleton[i + 1], 0]), int(kp2ds[_skeleton[i + 1], 1])),
+ color_list[_idx % len(color_list)],
+ 3,
+ )
+
+ for _idx, kp2d in enumerate(kp2ds):
+ if kp2d[2] > threshold:
+ cv2.circle(img, (int(kp2d[0]), int(kp2d[1])), 3, color, -1)
+ # cv2.putText(img,
+ # str(_idx),
+ # (int(kp2d[0, i, 0])*1,
+ # int(kp2d[0, i, 1])*1),
+ # cv2.FONT_HERSHEY_SIMPLEX,
+ # 0.75,
+ # color,
+ # 2
+ # )
+
+ return img
+
+
+def draw_mask(img, mask, background=0, return_rgba=False):
+ img = load_image(img)
+ h, w, _ = img.shape
+ if type(background) == int:
+ background = np.ones((h, w, 3)).astype(np.uint8) * 255 * background
+ backgournd = cv2.resize(background, (w, h))
+ img_rgba = np.concatenate([img, mask], -1)
+ return alphaMerge(img_rgba, background, 0, 0, return_rgba=True)
+
+
+def draw_pcd(pcd_list, save_path=None):
+ fig = plt.figure()
+ ax = fig.add_subplot(111, projection="3d")
+
+ color_list = ["r", "g", "b", "y", "p"]
+
+ for _idx, _pcd in enumerate(pcd_list):
+ ax.scatter(_pcd[:, 0], _pcd[:, 1], _pcd[:, 2], c=color_list[_idx], marker="o")
+
+ ax.set_xlabel("X")
+ ax.set_ylabel("Y")
+ ax.set_zlabel("Z")
+
+ if save_path is not None:
+ plt.savefig(save_path)
+ else:
+ plt.savefig("tmp.png")
+
+
+def load_image(img, reverse=False):
+ if type(img) == str:
+ img = cv2.imread(img)
+ if reverse:
+ img = img.astype(np.float32)
+ img = img[:, :, ::-1]
+ img = img.astype(np.uint8)
+ return img
+
+
+def draw_skeleten(meta):
+ kps = []
+ for i, kp in enumerate(meta["keypoints_body"]):
+ if kp is None:
+ # if kp is None:
+ kps.append([0, 0, 0])
+ else:
+ kps.append([*kp, 1])
+ kps = np.array(kps)
+
+ kps[:, 0] *= meta["width"]
+ kps[:, 1] *= meta["height"]
+ pose_img = np.zeros([meta["height"], meta["width"], 3], dtype=np.uint8)
+
+ pose_img = draw_aapose(
+ pose_img,
+ kps,
+ draw_hand=True,
+ kp2ds_lhand=meta["keypoints_left_hand"],
+ kp2ds_rhand=meta["keypoints_right_hand"],
+ )
+ return pose_img
+
+
+def draw_skeleten_with_pncc(pncc: np.ndarray, meta: Dict) -> np.ndarray:
+ """
+ Args:
+ pncc: [H,W,3]
+ meta: required keys: keypoints_body: [N, 3] keypoints_left_hand, keypoints_right_hand
+ Return:
+ np.ndarray [H, W, 3]
+ """
+ # preprocess keypoints
+ kps = []
+ for i, kp in enumerate(meta["keypoints_body"]):
+ if kp is None:
+ # if kp is None:
+ kps.append([0, 0, 0])
+ elif i in [14, 15, 16, 17]:
+ kps.append([0, 0, 0])
+ else:
+ kps.append([*kp])
+ kps = np.stack(kps)
+
+ kps[:, 0] *= pncc.shape[1]
+ kps[:, 1] *= pncc.shape[0]
+
+ # draw neck
+ canvas = np.zeros_like(pncc)
+ if kps[0][2] > 0.6 and kps[1][2] > 0.6:
+ canvas = draw_ellipse_by_2kp(canvas, kps[0], kps[1], [0, 0, 255])
+
+ # draw pncc
+ mask = (pncc > 0).max(axis=2)
+ canvas[mask] = pncc[mask]
+ pncc = canvas
+
+ # draw other skeleten
+ kps[0] = 0
+
+ meta["keypoints_left_hand"][:, 0] *= meta["width"]
+ meta["keypoints_left_hand"][:, 1] *= meta["height"]
+
+ meta["keypoints_right_hand"][:, 0] *= meta["width"]
+ meta["keypoints_right_hand"][:, 1] *= meta["height"]
+ pose_img = draw_aapose(
+ pncc,
+ kps,
+ draw_hand=True,
+ kp2ds_lhand=meta["keypoints_left_hand"],
+ kp2ds_rhand=meta["keypoints_right_hand"],
+ )
+ return pose_img
+
+
+FACE_CUSTOM_STYLE = {
+ "eyeball": {"indexs": [68, 69], "color": [255, 255, 255], "connect": False},
+ "left_eyebrow": {"indexs": [17, 18, 19, 20, 21], "color": [0, 255, 0]},
+ "right_eyebrow": {"indexs": [22, 23, 24, 25, 26], "color": [0, 0, 255]},
+ "left_eye": {"indexs": [36, 37, 38, 39, 40, 41], "color": [255, 255, 0], "close": True},
+ "right_eye": {"indexs": [42, 43, 44, 45, 46, 47], "color": [255, 0, 255], "close": True},
+ "mouth_outside": {"indexs": list(range(48, 60)), "color": [100, 255, 50], "close": True},
+ "mouth_inside": {"indexs": [60, 61, 62, 63, 64, 65, 66, 67], "color": [255, 100, 50], "close": True},
+}
+
+
+def draw_face_kp(img, kps, thickness=2, style=FACE_CUSTOM_STYLE):
+ """
+ Args:
+ img: [H, W, 3]
+ kps: [70, 2]
+ """
+ img = img.copy()
+ for key, item in style.items():
+ pts = np.array(kps[item["indexs"]]).astype(np.int32)
+ connect = item.get("connect", True)
+ color = item["color"]
+ close = item.get("close", False)
+ if connect:
+ cv2.polylines(img, [pts], close, color, thickness=thickness)
+ else:
+ for kp in pts:
+ kp = np.array(kp).astype(np.int32)
+ cv2.circle(img, kp, thickness * 2, color=color, thickness=-1)
+ return img
+
+
+def draw_traj(metas: List[AAPoseMeta], threshold=0.6):
+
+ colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
+ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85], [100, 255, 50], [255, 100, 50],
+ # foot
+ [200, 200, 0],
+ [100, 100, 0]
+ ]
+ limbSeq = [
+ [1, 2], [1, 5], # shoulders
+ [2, 3], [3, 4], # left arm
+ [5, 6], [6, 7], # right arm
+ [1, 8], [8, 9], [9, 10], # right leg
+ [1, 11], [11, 12], [12, 13], # left leg
+ # face (nose, eyes, ears)
+ [13, 18], [10, 19] # foot
+ ]
+
+ face_seq = [[1, 0], [0, 14], [14, 16], [0, 15], [15, 17]]
+ kp_body = np.array([meta.kps_body for meta in metas])
+ kp_body_p = np.array([meta.kps_body_p for meta in metas])
+
+
+ face_seq = random.sample(face_seq, 2)
+
+ kp_lh = np.array([meta.kps_lhand for meta in metas])
+ kp_rh = np.array([meta.kps_rhand for meta in metas])
+
+ kp_lh_p = np.array([meta.kps_lhand_p for meta in metas])
+ kp_rh_p = np.array([meta.kps_rhand_p for meta in metas])
+
+ # kp_lh = np.concatenate([kp_lh, kp_lh_p], axis=-1)
+ # kp_rh = np.concatenate([kp_rh, kp_rh_p], axis=-1)
+
+ new_limbSeq = []
+ key_point_list = []
+ for _idx, ((k1_index, k2_index)) in enumerate(limbSeq):
+
+ vis = (kp_body_p[:, k1_index] > threshold) * (kp_body_p[:, k2_index] > threshold) * 1
+ if vis.sum() * 1.0 / vis.shape[0] > 0.4:
+ new_limbSeq.append([k1_index, k2_index])
+
+ for _idx, ((k1_index, k2_index)) in enumerate(limbSeq):
+
+ keypoint1 = kp_body[:, k1_index - 1]
+ keypoint2 = kp_body[:, k2_index - 1]
+ interleave = random.randint(4, 7)
+ randind = random.randint(0, interleave - 1)
+ # randind = random.rand(range(interleave), sampling_num)
+
+ Y = np.array([keypoint1[:, 0], keypoint2[:, 0]])
+ X = np.array([keypoint1[:, 1], keypoint2[:, 1]])
+
+ vis = (keypoint1[:, -1] > threshold) * (keypoint2[:, -1] > threshold) * 1
+
+ # for randidx in randind:
+ t = randind / interleave
+ x = (1-t)*Y[0, :] + t*Y[1, :]
+ y = (1-t)*X[0, :] + t*X[1, :]
+
+ # np.array([1])
+ x = x.astype(int)
+ y = y.astype(int)
+
+ new_array = np.array([x, y, vis]).T
+
+ key_point_list.append(new_array)
+
+ indx_lh = random.randint(0, kp_lh.shape[1] - 1)
+ lh = kp_lh[:, indx_lh, :]
+ lh_p = kp_lh_p[:, indx_lh:indx_lh+1]
+ lh = np.concatenate([lh, lh_p], axis=-1)
+
+ indx_rh = random.randint(0, kp_rh.shape[1] - 1)
+ rh = kp_rh[:, random.randint(0, kp_rh.shape[1] - 1), :]
+ rh_p = kp_rh_p[:, indx_rh:indx_rh+1]
+ rh = np.concatenate([rh, rh_p], axis=-1)
+
+
+
+ lh[-1, :] = (lh[-1, :] > threshold) * 1
+ rh[-1, :] = (rh[-1, :] > threshold) * 1
+
+ # print(rh.shape, new_array.shape)
+ # exit()
+ key_point_list.append(lh.astype(int))
+ key_point_list.append(rh.astype(int))
+
+
+ key_points_list = np.stack(key_point_list)
+ num_points = len(key_points_list)
+ sample_colors = random.sample(colors, num_points)
+
+ stickwidth = max(int(min(metas[0].width, metas[0].height) / 150), 2)
+
+ image_list_ori = []
+ for i in range(key_points_list.shape[-2]):
+ _image_vis = np.zeros((metas[0].width, metas[0].height, 3))
+ points = key_points_list[:, i, :]
+ for idx, point in enumerate(points):
+ x, y, vis = point
+ if vis == 1:
+ cv2.circle(_image_vis, (x, y), stickwidth, sample_colors[idx], thickness=-1)
+
+ image_list_ori.append(_image_vis)
+
+ return image_list_ori
+
+ return [np.zeros([meta.width, meta.height, 3], dtype=np.uint8) for meta in metas]
+
+
+if __name__ == "__main__":
+ meta = {
+ "image_id": "00472.jpg",
+ "height": 540,
+ "width": 414,
+ "category_id": 1,
+ "keypoints_body": [
+ [0.5084776947463768, 0.11350188078703703],
+ [0.504467655495169, 0.20419560185185184],
+ [0.3982016153381642, 0.198046875],
+ [0.3841664779589372, 0.34869068287037036],
+ [0.3901815368357488, 0.4670536747685185],
+ [0.610733695652174, 0.2103443287037037],
+ [0.6167487545289855, 0.3517650462962963],
+ [0.6448190292874396, 0.4762767650462963],
+ [0.4523371452294686, 0.47320240162037036],
+ [0.4503321256038647, 0.6776475694444445],
+ [0.47639738073671495, 0.8544234664351852],
+ [0.5766483620169082, 0.47320240162037036],
+ [0.5666232638888888, 0.6761103877314815],
+ [0.534542949879227, 0.863646556712963],
+ [0.4864224788647343, 0.09505570023148148],
+ [0.5285278910024155, 0.09351851851851851],
+ [0.46236224335748793, 0.10581597222222222],
+ [0.5586031853864735, 0.10274160879629629],
+ [0.4994551064311594, 0.9405056423611111],
+ [0.4152442821557971, 0.9312825520833333],
+ ],
+ "keypoints_left_hand": [
+ [267.78515625, 263.830078125, 1.2840936183929443],
+ [265.294921875, 269.640625, 1.2546794414520264],
+ [263.634765625, 277.111328125, 1.2863062620162964],
+ [262.8046875, 285.412109375, 1.267038345336914],
+ [261.14453125, 292.8828125, 1.280144453048706],
+ [273.595703125, 281.26171875, 1.2592815160751343],
+ [271.10546875, 291.22265625, 1.3256099224090576],
+ [265.294921875, 294.54296875, 1.2368024587631226],
+ [261.14453125, 294.54296875, 0.9771889448165894],
+ [274.42578125, 282.091796875, 1.250044584274292],
+ [269.4453125, 291.22265625, 1.2571144104003906],
+ [264.46484375, 292.8828125, 1.177802324295044],
+ [260.314453125, 292.052734375, 0.9283463358879089],
+ [273.595703125, 282.091796875, 1.1834490299224854],
+ [269.4453125, 290.392578125, 1.188171625137329],
+ [265.294921875, 290.392578125, 1.192609429359436],
+ [261.974609375, 289.5625, 0.9366656541824341],
+ [271.935546875, 281.26171875, 1.0946396589279175],
+ [268.615234375, 287.072265625, 0.9906131029129028],
+ [265.294921875, 287.90234375, 1.0219476222991943],
+ [262.8046875, 287.072265625, 0.9240120053291321],
+ ],
+ "keypoints_right_hand": [
+ [161.53515625, 258.849609375, 1.2069408893585205],
+ [168.17578125, 263.0, 1.1846840381622314],
+ [173.986328125, 269.640625, 1.1435924768447876],
+ [173.986328125, 277.94140625, 1.1802611351013184],
+ [173.986328125, 286.2421875, 1.2599592208862305],
+ [165.685546875, 275.451171875, 1.0633569955825806],
+ [167.345703125, 286.2421875, 1.1693341732025146],
+ [169.8359375, 291.22265625, 1.2698509693145752],
+ [170.666015625, 294.54296875, 1.0619274377822876],
+ [160.705078125, 276.28125, 1.0995020866394043],
+ [163.1953125, 287.90234375, 1.2735884189605713],
+ [166.515625, 291.22265625, 1.339503526687622],
+ [169.005859375, 294.54296875, 1.0835273265838623],
+ [157.384765625, 277.111328125, 1.0866981744766235],
+ [161.53515625, 287.072265625, 1.2468621730804443],
+ [164.025390625, 289.5625, 1.2817761898040771],
+ [166.515625, 292.052734375, 1.099466323852539],
+ [155.724609375, 277.111328125, 1.1065717935562134],
+ [159.044921875, 285.412109375, 1.1924479007720947],
+ [160.705078125, 287.072265625, 1.1304771900177002],
+ [162.365234375, 287.90234375, 1.0040509700775146],
+ ],
+ }
+ demo_meta = AAPoseMeta(meta)
+ res = draw_traj([demo_meta]*5)
+ cv2.imwrite("traj.png", res[0][..., ::-1])
diff --git a/wan/modules/animate/preprocess/pose2d.py b/wan/modules/animate/preprocess/pose2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..00b728c686e6247ab081e43594f8383307ae6d74
--- /dev/null
+++ b/wan/modules/animate/preprocess/pose2d.py
@@ -0,0 +1,430 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import os
+import cv2
+from typing import Union, List
+
+import numpy as np
+import torch
+import onnxruntime
+
+from pose2d_utils import (
+ read_img,
+ box_convert_simple,
+ bbox_from_detector,
+ crop,
+ keypoints_from_heatmaps,
+ load_pose_metas_from_kp2ds_seq
+)
+
+
+class SimpleOnnxInference(object):
+ def __init__(self, checkpoint, device='cuda', reverse_input=False, **kwargs):
+ if isinstance(device, str):
+ device = torch.device(device)
+ if device.type == 'cuda':
+ device = '{}:{}'.format(device.type, device.index)
+ providers = [("CUDAExecutionProvider", {"device_id": device[-1:] if device[-1] in [str(_i) for _i in range(10)] else "0"}), "CPUExecutionProvider"]
+ else:
+ providers = ["CPUExecutionProvider"]
+ self.device = device
+ if not os.path.exists(checkpoint):
+ raise RuntimeError("{} is not existed!".format(checkpoint))
+
+ if os.path.isdir(checkpoint):
+ checkpoint = os.path.join(checkpoint, 'end2end.onnx')
+
+ self.session = onnxruntime.InferenceSession(checkpoint,
+ providers=providers
+ )
+ self.input_name = self.session.get_inputs()[0].name
+ self.output_name = self.session.get_outputs()[0].name
+ self.input_resolution = self.session.get_inputs()[0].shape[2:] if not reverse_input else self.session.get_inputs()[0].shape[2:][::-1]
+ self.input_resolution = np.array(self.input_resolution)
+
+
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+
+ def get_output_names(self):
+ output_names = []
+ for node in self.session.get_outputs():
+ output_names.append(node.name)
+ return output_names
+
+
+ def set_device(self, device):
+ if isinstance(device, str):
+ device = torch.device(device)
+ if device.type == 'cuda':
+ device = '{}:{}'.format(device.type, device.index)
+ providers = [("CUDAExecutionProvider", {"device_id": device[-1:] if device[-1] in [str(_i) for _i in range(10)] else "0"}), "CPUExecutionProvider"]
+ else:
+ providers = ["CPUExecutionProvider"]
+ self.session.set_providers(["CUDAExecutionProvider"])
+ self.device = device
+
+
+class Yolo(SimpleOnnxInference):
+ def __init__(self, checkpoint, device='cuda', threshold_conf=0.05, threshold_multi_persons=0.1, input_resolution=(640, 640), threshold_iou=0.5, threshold_bbox_shape_ratio=0.4, cat_id=[1], select_type='max', strict=True, sorted_func=None, **kwargs):
+ super(Yolo, self).__init__(checkpoint, device=device, **kwargs)
+ self.session.set_providers(["CUDAExecutionProvider"])
+ model_inputs = self.session.get_inputs()
+ input_shape = model_inputs[0].shape
+
+ self.input_width = 640
+ self.input_height = 640
+
+ self.threshold_multi_persons = threshold_multi_persons
+ self.threshold_conf = threshold_conf
+ self.threshold_iou = threshold_iou
+ self.threshold_bbox_shape_ratio = threshold_bbox_shape_ratio
+ self.input_resolution = input_resolution
+ self.cat_id = cat_id
+ self.select_type = select_type
+ self.strict = strict
+ self.sorted_func = sorted_func
+
+
+ def preprocess(self, input_image):
+ """
+ Preprocesses the input image before performing inference.
+
+ Returns:
+ image_data: Preprocessed image data ready for inference.
+ """
+ img = read_img(input_image)
+ # Get the height and width of the input image
+ img_height, img_width = img.shape[:2]
+ # Resize the image to match the input shape
+ img = cv2.resize(img, (self.input_resolution[1], self.input_resolution[0]))
+ # Normalize the image data by dividing it by 255.0
+ image_data = np.array(img) / 255.0
+ # Transpose the image to have the channel dimension as the first dimension
+ image_data = np.transpose(image_data, (2, 0, 1)) # Channel first
+ # Expand the dimensions of the image data to match the expected input shape
+ # image_data = np.expand_dims(image_data, axis=0).astype(np.float32)
+ image_data = image_data.astype(np.float32)
+ # Return the preprocessed image data
+ return image_data, np.array([img_height, img_width])
+
+
+ def postprocess(self, output, shape_raw, cat_id=[1]):
+ """
+ Performs post-processing on the model's output to extract bounding boxes, scores, and class IDs.
+
+ Args:
+ input_image (numpy.ndarray): The input image.
+ output (numpy.ndarray): The output of the model.
+
+ Returns:
+ numpy.ndarray: The input image with detections drawn on it.
+ """
+ # Transpose and squeeze the output to match the expected shape
+
+ outputs = np.squeeze(output)
+ if len(outputs.shape) == 1:
+ outputs = outputs[None]
+ if output.shape[-1] != 6 and output.shape[1] == 84:
+ outputs = np.transpose(outputs)
+
+ # Get the number of rows in the outputs array
+ rows = outputs.shape[0]
+
+ # Calculate the scaling factors for the bounding box coordinates
+ x_factor = shape_raw[1] / self.input_width
+ y_factor = shape_raw[0] / self.input_height
+
+ # Lists to store the bounding boxes, scores, and class IDs of the detections
+ boxes = []
+ scores = []
+ class_ids = []
+
+ if outputs.shape[-1] == 6:
+ max_scores = outputs[:, 4]
+ classid = outputs[:, -1]
+
+ threshold_conf_masks = max_scores >= self.threshold_conf
+ classid_masks = classid[threshold_conf_masks] != 3.14159
+
+ max_scores = max_scores[threshold_conf_masks][classid_masks]
+ classid = classid[threshold_conf_masks][classid_masks]
+
+ boxes = outputs[:, :4][threshold_conf_masks][classid_masks]
+ boxes[:, [0, 2]] *= x_factor
+ boxes[:, [1, 3]] *= y_factor
+ boxes[:, 2] = boxes[:, 2] - boxes[:, 0]
+ boxes[:, 3] = boxes[:, 3] - boxes[:, 1]
+ boxes = boxes.astype(np.int32)
+
+ else:
+ classes_scores = outputs[:, 4:]
+ max_scores = np.amax(classes_scores, -1)
+ threshold_conf_masks = max_scores >= self.threshold_conf
+
+ classid = np.argmax(classes_scores[threshold_conf_masks], -1)
+
+ classid_masks = classid!=3.14159
+
+ classes_scores = classes_scores[threshold_conf_masks][classid_masks]
+ max_scores = max_scores[threshold_conf_masks][classid_masks]
+ classid = classid[classid_masks]
+
+ xywh = outputs[:, :4][threshold_conf_masks][classid_masks]
+
+ x = xywh[:, 0:1]
+ y = xywh[:, 1:2]
+ w = xywh[:, 2:3]
+ h = xywh[:, 3:4]
+
+ left = ((x - w / 2) * x_factor)
+ top = ((y - h / 2) * y_factor)
+ width = (w * x_factor)
+ height = (h * y_factor)
+ boxes = np.concatenate([left, top, width, height], axis=-1).astype(np.int32)
+
+ boxes = boxes.tolist()
+ scores = max_scores.tolist()
+ class_ids = classid.tolist()
+
+ # Apply non-maximum suppression to filter out overlapping bounding boxes
+ indices = cv2.dnn.NMSBoxes(boxes, scores, self.threshold_conf, self.threshold_iou)
+ # Iterate over the selected indices after non-maximum suppression
+
+ results = []
+ for i in indices:
+ # Get the box, score, and class ID corresponding to the index
+ box = box_convert_simple(boxes[i], 'xywh2xyxy')
+ score = scores[i]
+ class_id = class_ids[i]
+ results.append(box + [score] + [class_id])
+ # # Draw the detection on the input image
+
+ # Return the modified input image
+ return np.array(results)
+
+
+ def process_results(self, results, shape_raw, cat_id=[1], single_person=True):
+ if isinstance(results, tuple):
+ det_results = results[0]
+ else:
+ det_results = results
+
+ person_results = []
+ person_count = 0
+ if len(results):
+ max_idx = -1
+ max_bbox_size = shape_raw[0] * shape_raw[1] * -10
+ max_bbox_shape = -1
+
+ bboxes = []
+ idx_list = []
+ for i in range(results.shape[0]):
+ bbox = results[i]
+ if (bbox[-1] + 1 in cat_id) and (bbox[-2] > self.threshold_conf):
+ idx_list.append(i)
+ bbox_shape = max((bbox[2] - bbox[0]), ((bbox[3] - bbox[1])))
+ if bbox_shape > max_bbox_shape:
+ max_bbox_shape = bbox_shape
+
+ results = results[idx_list]
+
+ for i in range(results.shape[0]):
+ bbox = results[i]
+ bboxes.append(bbox)
+ if self.select_type == 'max':
+ bbox_size = (bbox[2] - bbox[0]) * ((bbox[3] - bbox[1]))
+ elif self.select_type == 'center':
+ bbox_size = (abs((bbox[2] + bbox[0]) / 2 - shape_raw[1]/2)) * -1
+ bbox_shape = max((bbox[2] - bbox[0]), ((bbox[3] - bbox[1])))
+ if bbox_size > max_bbox_size:
+ if (self.strict or max_idx != -1) and bbox_shape < max_bbox_shape * self.threshold_bbox_shape_ratio:
+ continue
+ max_bbox_size = bbox_size
+ max_bbox_shape = bbox_shape
+ max_idx = i
+
+ if self.sorted_func is not None and len(bboxes) > 0:
+ max_idx = self.sorted_func(bboxes, shape_raw)
+ bbox = bboxes[max_idx]
+ if self.select_type == 'max':
+ max_bbox_size = (bbox[2] - bbox[0]) * ((bbox[3] - bbox[1]))
+ elif self.select_type == 'center':
+ max_bbox_size = (abs((bbox[2] + bbox[0]) / 2 - shape_raw[1]/2)) * -1
+
+ if max_idx != -1:
+ person_count = 1
+
+ if max_idx != -1:
+ person = {}
+ person['bbox'] = results[max_idx, :5]
+ person['track_id'] = int(0)
+ person_results.append(person)
+
+ for i in range(results.shape[0]):
+ bbox = results[i]
+ if (bbox[-1] + 1 in cat_id) and (bbox[-2] > self.threshold_conf):
+ if self.select_type == 'max':
+ bbox_size = (bbox[2] - bbox[0]) * ((bbox[3] - bbox[1]))
+ elif self.select_type == 'center':
+ bbox_size = (abs((bbox[2] + bbox[0]) / 2 - shape_raw[1]/2)) * -1
+ if i != max_idx and bbox_size > max_bbox_size * self.threshold_multi_persons and bbox_size < max_bbox_size:
+ person_count += 1
+ if not single_person:
+ person = {}
+ person['bbox'] = results[i, :5]
+ person['track_id'] = int(person_count - 1)
+ person_results.append(person)
+ return person_results
+ else:
+ return None
+
+
+ def postprocess_threading(self, outputs, shape_raw, person_results, i, single_person=True, **kwargs):
+ result = self.postprocess(outputs[i], shape_raw[i], cat_id=self.cat_id)
+ result = self.process_results(result, shape_raw[i], cat_id=self.cat_id, single_person=single_person)
+ if result is not None and len(result) != 0:
+ person_results[i] = result
+
+
+ def forward(self, img, shape_raw, **kwargs):
+ """
+ Performs inference using an ONNX model and returns the output image with drawn detections.
+
+ Returns:
+ output_img: The output image with drawn detections.
+ """
+ if isinstance(img, torch.Tensor):
+ img = img.cpu().numpy()
+ shape_raw = shape_raw.cpu().numpy()
+
+ outputs = self.session.run(None, {self.session.get_inputs()[0].name: img})[0]
+ person_results = [[{'bbox': np.array([0., 0., 1.*shape_raw[i][1], 1.*shape_raw[i][0], -1]), 'track_id': -1}] for i in range(len(outputs))]
+
+ for i in range(len(outputs)):
+ self.postprocess_threading(outputs, shape_raw, person_results, i, **kwargs)
+ return person_results
+
+
+class ViTPose(SimpleOnnxInference):
+ def __init__(self, checkpoint, device='cuda', **kwargs):
+ super(ViTPose, self).__init__(checkpoint, device=device)
+ self.session.set_providers(["CUDAExecutionProvider"])
+
+ def forward(self, img, center, scale, **kwargs):
+ heatmaps = self.session.run([], {self.session.get_inputs()[0].name: img})[0]
+ points, prob = keypoints_from_heatmaps(heatmaps=heatmaps,
+ center=center,
+ scale=scale*200,
+ unbiased=True,
+ use_udp=False)
+ return np.concatenate([points, prob], axis=2)
+
+
+ @staticmethod
+ def preprocess(img, bbox=None, input_resolution=(256, 192), rescale=1.25, mask=None, **kwargs):
+ if bbox is None or bbox[-1] <= 0 or (bbox[2] - bbox[0]) < 10 or (bbox[3] - bbox[1]) < 10:
+ bbox = np.array([0, 0, img.shape[1], img.shape[0]])
+
+ bbox_xywh = bbox
+ if mask is not None:
+ img = np.where(mask>128, img, mask)
+
+ if isinstance(input_resolution, int):
+ center, scale = bbox_from_detector(bbox_xywh, (input_resolution, input_resolution), rescale=rescale)
+ img, new_shape, old_xy, new_xy = crop(img, center, scale, (input_resolution, input_resolution))
+ else:
+ center, scale = bbox_from_detector(bbox_xywh, input_resolution, rescale=rescale)
+ img, new_shape, old_xy, new_xy = crop(img, center, scale, (input_resolution[0], input_resolution[1]))
+
+ IMG_NORM_MEAN = np.array([0.485, 0.456, 0.406])
+ IMG_NORM_STD = np.array([0.229, 0.224, 0.225])
+ img_norm = (img / 255. - IMG_NORM_MEAN) / IMG_NORM_STD
+ img_norm = img_norm.transpose(2, 0, 1).astype(np.float32)
+ return img_norm, np.array(center), np.array(scale)
+
+
+class Pose2d:
+ def __init__(self, checkpoint, detector_checkpoint=None, device='cuda', **kwargs):
+
+ if detector_checkpoint is not None:
+ self.detector = Yolo(detector_checkpoint, device)
+ else:
+ self.detector = None
+
+ self.model = ViTPose(checkpoint, device)
+ self.device = device
+
+ def load_images(self, inputs):
+ """
+ Load images from various input types.
+
+ Args:
+ inputs (Union[str, np.ndarray, List[np.ndarray]]): Input can be file path,
+ single image array, or list of image arrays
+
+ Returns:
+ List[np.ndarray]: List of RGB image arrays
+
+ Raises:
+ ValueError: If file format is unsupported or image cannot be read
+ """
+ if isinstance(inputs, str):
+ if inputs.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
+ cap = cv2.VideoCapture(inputs)
+ frames = []
+ while True:
+ ret, frame = cap.read()
+ if not ret:
+ break
+ frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
+ cap.release()
+ images = frames
+ elif inputs.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
+ img = cv2.cvtColor(cv2.imread(inputs), cv2.COLOR_BGR2RGB)
+ if img is None:
+ raise ValueError(f"Cannot read image: {inputs}")
+ images = [img]
+ else:
+ raise ValueError(f"Unsupported file format: {inputs}")
+
+ elif isinstance(inputs, np.ndarray):
+ images = [cv2.cvtColor(image, cv2.COLOR_BGR2RGB) for image in inputs]
+ elif isinstance(inputs, list):
+ images = [cv2.cvtColor(image, cv2.COLOR_BGR2RGB) for image in inputs]
+ return images
+
+ def __call__(
+ self,
+ inputs: Union[str, np.ndarray, List[np.ndarray]],
+ return_image: bool = False,
+ **kwargs
+ ):
+ """
+ Process input and estimate 2D keypoints.
+
+ Args:
+ inputs (Union[str, np.ndarray, List[np.ndarray]]): Input can be file path,
+ single image array, or list of image arrays
+ **kwargs: Additional arguments for processing
+
+ Returns:
+ np.ndarray: Array of detected 2D keypoints for all input images
+ """
+ images = self.load_images(inputs)
+ H, W = images[0].shape[:2]
+ if self.detector is not None:
+ bboxes = []
+ for _image in images:
+ img, shape = self.detector.preprocess(_image)
+ bboxes.append(self.detector(img[None], shape[None])[0][0]["bbox"])
+ else:
+ bboxes = [None] * len(images)
+
+ kp2ds = []
+ for _image, _bbox in zip(images, bboxes):
+ img, center, scale = self.model.preprocess(_image, _bbox)
+ kp2ds.append(self.model(img[None], center[None], scale[None]))
+ kp2ds = np.concatenate(kp2ds, 0)
+ metas = load_pose_metas_from_kp2ds_seq(kp2ds, width=W, height=H)
+ return metas
\ No newline at end of file
diff --git a/wan/modules/animate/preprocess/pose2d_utils.py b/wan/modules/animate/preprocess/pose2d_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b496e211faa4e30cf4a81352752c13b179d14fd9
--- /dev/null
+++ b/wan/modules/animate/preprocess/pose2d_utils.py
@@ -0,0 +1,1159 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import warnings
+import cv2
+import numpy as np
+from typing import List
+from PIL import Image
+
+
+def box_convert_simple(box, convert_type='xyxy2xywh'):
+ if convert_type == 'xyxy2xywh':
+ return [box[0], box[1], box[2] - box[0], box[3] - box[1]]
+ elif convert_type == 'xywh2xyxy':
+ return [box[0], box[1], box[2] + box[0], box[3] + box[1]]
+ elif convert_type == 'xyxy2ctwh':
+ return [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2, box[2] - box[0], box[3] - box[1]]
+ elif convert_type == 'ctwh2xyxy':
+ return [box[0] - box[2] // 2, box[1] - box[3] // 2, box[0] + (box[2] - box[2] // 2), box[1] + (box[3] - box[3] // 2)]
+
+def read_img(image, convert='RGB', check_exist=False):
+ if isinstance(image, str):
+ if check_exist and not osp.exists(image):
+ return None
+ try:
+ img = Image.open(image)
+ if convert:
+ img = img.convert(convert)
+ except:
+ raise IOError('File error: ', image)
+ return np.asarray(img)
+ else:
+ if isinstance(image, np.ndarray):
+ if convert:
+ return image[..., ::-1]
+ else:
+ if convert:
+ img = img.convert(convert)
+ return np.asarray(img)
+
+class AAPoseMeta:
+ def __init__(self, meta=None, kp2ds=None):
+ self.image_id = ""
+ self.height = 0
+ self.width = 0
+
+ self.kps_body: np.ndarray = None
+ self.kps_lhand: np.ndarray = None
+ self.kps_rhand: np.ndarray = None
+ self.kps_face: np.ndarray = None
+ self.kps_body_p: np.ndarray = None
+ self.kps_lhand_p: np.ndarray = None
+ self.kps_rhand_p: np.ndarray = None
+ self.kps_face_p: np.ndarray = None
+
+
+ if meta is not None:
+ self.load_from_meta(meta)
+ elif kp2ds is not None:
+ self.load_from_kp2ds(kp2ds)
+
+ def is_valid(self, kp, p, threshold):
+ x, y = kp
+ if x < 0 or y < 0 or x > self.width or y > self.height or p < threshold:
+ return False
+ else:
+ return True
+
+ def get_bbox(self, kp, kp_p, threshold=0.5):
+ kps = kp[kp_p > threshold]
+ if kps.size == 0:
+ return 0, 0, 0, 0
+ x0, y0 = kps.min(axis=0)
+ x1, y1 = kps.max(axis=0)
+ return x0, y0, x1, y1
+
+ def crop(self, x0, y0, x1, y1):
+ all_kps = [self.kps_body, self.kps_lhand, self.kps_rhand, self.kps_face]
+ for kps in all_kps:
+ if kps is not None:
+ kps[:, 0] -= x0
+ kps[:, 1] -= y0
+ self.width = x1 - x0
+ self.height = y1 - y0
+ return self
+
+ def resize(self, width, height):
+ scale_x = width / self.width
+ scale_y = height / self.height
+ all_kps = [self.kps_body, self.kps_lhand, self.kps_rhand, self.kps_face]
+ for kps in all_kps:
+ if kps is not None:
+ kps[:, 0] *= scale_x
+ kps[:, 1] *= scale_y
+ self.width = width
+ self.height = height
+ return self
+
+
+ def get_kps_body_with_p(self, normalize=False):
+ kps_body = self.kps_body.copy()
+ if normalize:
+ kps_body = kps_body / np.array([self.width, self.height])
+
+ return np.concatenate([kps_body, self.kps_body_p[:, None]])
+
+ @staticmethod
+ def from_kps_face(kps_face: np.ndarray, height: int, width: int):
+
+ pose_meta = AAPoseMeta()
+ pose_meta.kps_face = kps_face[:, :2]
+ if kps_face.shape[1] == 3:
+ pose_meta.kps_face_p = kps_face[:, 2]
+ else:
+ pose_meta.kps_face_p = kps_face[:, 0] * 0 + 1
+ pose_meta.height = height
+ pose_meta.width = width
+ return pose_meta
+
+ @staticmethod
+ def from_kps_body(kps_body: np.ndarray, height: int, width: int):
+
+ pose_meta = AAPoseMeta()
+ pose_meta.kps_body = kps_body[:, :2]
+ pose_meta.kps_body_p = kps_body[:, 2]
+ pose_meta.height = height
+ pose_meta.width = width
+ return pose_meta
+ @staticmethod
+ def from_humanapi_meta(meta):
+ pose_meta = AAPoseMeta()
+ width, height = meta["width"], meta["height"]
+ pose_meta.width = width
+ pose_meta.height = height
+ pose_meta.kps_body = meta["keypoints_body"][:, :2] * (width, height)
+ pose_meta.kps_body_p = meta["keypoints_body"][:, 2]
+ pose_meta.kps_lhand = meta["keypoints_left_hand"][:, :2] * (width, height)
+ pose_meta.kps_lhand_p = meta["keypoints_left_hand"][:, 2]
+ pose_meta.kps_rhand = meta["keypoints_right_hand"][:, :2] * (width, height)
+ pose_meta.kps_rhand_p = meta["keypoints_right_hand"][:, 2]
+ if 'keypoints_face' in meta:
+ pose_meta.kps_face = meta["keypoints_face"][:, :2] * (width, height)
+ pose_meta.kps_face_p = meta["keypoints_face"][:, 2]
+ return pose_meta
+
+ def load_from_meta(self, meta, norm_body=True, norm_hand=False):
+
+ self.image_id = meta.get("image_id", "00000.png")
+ self.height = meta["height"]
+ self.width = meta["width"]
+ kps_body_p = []
+ kps_body = []
+ for kp in meta["keypoints_body"]:
+ if kp is None:
+ kps_body.append([0, 0])
+ kps_body_p.append(0)
+ else:
+ kps_body.append(kp)
+ kps_body_p.append(1)
+
+ self.kps_body = np.array(kps_body)
+ self.kps_body[:, 0] *= self.width
+ self.kps_body[:, 1] *= self.height
+ self.kps_body_p = np.array(kps_body_p)
+
+ self.kps_lhand = np.array(meta["keypoints_left_hand"])[:, :2]
+ self.kps_lhand_p = np.array(meta["keypoints_left_hand"])[:, 2]
+ self.kps_rhand = np.array(meta["keypoints_right_hand"])[:, :2]
+ self.kps_rhand_p = np.array(meta["keypoints_right_hand"])[:, 2]
+
+ @staticmethod
+ def load_from_kp2ds(kp2ds: List[np.ndarray], width: int, height: int):
+ """input 133x3 numpy keypoints and output AAPoseMeta
+
+ Args:
+ kp2ds (List[np.ndarray]): _description_
+ width (int): _description_
+ height (int): _description_
+
+ Returns:
+ _type_: _description_
+ """
+ pose_meta = AAPoseMeta()
+ pose_meta.width = width
+ pose_meta.height = height
+ kps_body = (kp2ds[[0, 6, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 17, 20]] + kp2ds[[0, 5, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 18, 21]]) / 2
+ kps_lhand = kp2ds[91:112]
+ kps_rhand = kp2ds[112:133]
+ kps_face = np.concatenate([kp2ds[23:23+68], kp2ds[1:3]], axis=0)
+ pose_meta.kps_body = kps_body[:, :2]
+ pose_meta.kps_body_p = kps_body[:, 2]
+ pose_meta.kps_lhand = kps_lhand[:, :2]
+ pose_meta.kps_lhand_p = kps_lhand[:, 2]
+ pose_meta.kps_rhand = kps_rhand[:, :2]
+ pose_meta.kps_rhand_p = kps_rhand[:, 2]
+ pose_meta.kps_face = kps_face[:, :2]
+ pose_meta.kps_face_p = kps_face[:, 2]
+ return pose_meta
+
+ @staticmethod
+ def from_dwpose(dwpose_det_res, height, width):
+ pose_meta = AAPoseMeta()
+ pose_meta.kps_body = dwpose_det_res["bodies"]["candidate"]
+ pose_meta.kps_body_p = dwpose_det_res["bodies"]["score"]
+ pose_meta.kps_body[:, 0] *= width
+ pose_meta.kps_body[:, 1] *= height
+
+ pose_meta.kps_lhand, pose_meta.kps_rhand = dwpose_det_res["hands"]
+ pose_meta.kps_lhand[:, 0] *= width
+ pose_meta.kps_lhand[:, 1] *= height
+ pose_meta.kps_rhand[:, 0] *= width
+ pose_meta.kps_rhand[:, 1] *= height
+ pose_meta.kps_lhand_p, pose_meta.kps_rhand_p = dwpose_det_res["hands_score"]
+
+ pose_meta.kps_face = dwpose_det_res["faces"][0]
+ pose_meta.kps_face[:, 0] *= width
+ pose_meta.kps_face[:, 1] *= height
+ pose_meta.kps_face_p = dwpose_det_res["faces_score"][0]
+ return pose_meta
+
+ def save_json(self):
+ pass
+
+ def draw_aapose(self, img, threshold=0.5, stick_width_norm=200, draw_hand=True, draw_head=True):
+ from .human_visualization import draw_aapose_by_meta
+ return draw_aapose_by_meta(img, self, threshold, stick_width_norm, draw_hand, draw_head)
+
+
+ def translate(self, x0, y0):
+ all_kps = [self.kps_body, self.kps_lhand, self.kps_rhand, self.kps_face]
+ for kps in all_kps:
+ if kps is not None:
+ kps[:, 0] -= x0
+ kps[:, 1] -= y0
+
+ def scale(self, sx, sy):
+ all_kps = [self.kps_body, self.kps_lhand, self.kps_rhand, self.kps_face]
+ for kps in all_kps:
+ if kps is not None:
+ kps[:, 0] *= sx
+ kps[:, 1] *= sy
+
+ def padding_resize2(self, height=512, width=512):
+ """kps will be changed inplace
+
+ """
+
+ all_kps = [self.kps_body, self.kps_lhand, self.kps_rhand, self.kps_face]
+
+ ori_height, ori_width = self.height, self.width
+
+ if (ori_height / ori_width) > (height / width):
+ new_width = int(height / ori_height * ori_width)
+ padding = int((width - new_width) / 2)
+ padding_width = padding
+ padding_height = 0
+ scale = height / ori_height
+
+ for kps in all_kps:
+ if kps is not None:
+ kps[:, 0] = kps[:, 0] * scale + padding
+ kps[:, 1] = kps[:, 1] * scale
+
+ else:
+ new_height = int(width / ori_width * ori_height)
+ padding = int((height - new_height) / 2)
+ padding_width = 0
+ padding_height = padding
+ scale = width / ori_width
+ for kps in all_kps:
+ if kps is not None:
+ kps[:, 1] = kps[:, 1] * scale + padding
+ kps[:, 0] = kps[:, 0] * scale
+
+
+ self.width = width
+ self.height = height
+ return self
+
+
+def transform_preds(coords, center, scale, output_size, use_udp=False):
+ """Get final keypoint predictions from heatmaps and apply scaling and
+ translation to map them back to the image.
+
+ Note:
+ num_keypoints: K
+
+ Args:
+ coords (np.ndarray[K, ndims]):
+
+ * If ndims=2, corrds are predicted keypoint location.
+ * If ndims=4, corrds are composed of (x, y, scores, tags)
+ * If ndims=5, corrds are composed of (x, y, scores, tags,
+ flipped_tags)
+
+ center (np.ndarray[2, ]): Center of the bounding box (x, y).
+ scale (np.ndarray[2, ]): Scale of the bounding box
+ wrt [width, height].
+ output_size (np.ndarray[2, ] | list(2,)): Size of the
+ destination heatmaps.
+ use_udp (bool): Use unbiased data processing
+
+ Returns:
+ np.ndarray: Predicted coordinates in the images.
+ """
+ assert coords.shape[1] in (2, 4, 5)
+ assert len(center) == 2
+ assert len(scale) == 2
+ assert len(output_size) == 2
+
+ # Recover the scale which is normalized by a factor of 200.
+ # scale = scale * 200.0
+
+ if use_udp:
+ scale_x = scale[0] / (output_size[0] - 1.0)
+ scale_y = scale[1] / (output_size[1] - 1.0)
+ else:
+ scale_x = scale[0] / output_size[0]
+ scale_y = scale[1] / output_size[1]
+
+ target_coords = np.ones_like(coords)
+ target_coords[:, 0] = coords[:, 0] * scale_x + center[0] - scale[0] * 0.5
+ target_coords[:, 1] = coords[:, 1] * scale_y + center[1] - scale[1] * 0.5
+
+ return target_coords
+
+
+def _calc_distances(preds, targets, mask, normalize):
+ """Calculate the normalized distances between preds and target.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ dimension of keypoints: D (normally, D=2 or D=3)
+
+ Args:
+ preds (np.ndarray[N, K, D]): Predicted keypoint location.
+ targets (np.ndarray[N, K, D]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ normalize (np.ndarray[N, D]): Typical value is heatmap_size
+
+ Returns:
+ np.ndarray[K, N]: The normalized distances. \
+ If target keypoints are missing, the distance is -1.
+ """
+ N, K, _ = preds.shape
+ # set mask=0 when normalize==0
+ _mask = mask.copy()
+ _mask[np.where((normalize == 0).sum(1))[0], :] = False
+ distances = np.full((N, K), -1, dtype=np.float32)
+ # handle invalid values
+ normalize[np.where(normalize <= 0)] = 1e6
+ distances[_mask] = np.linalg.norm(
+ ((preds - targets) / normalize[:, None, :])[_mask], axis=-1)
+ return distances.T
+
+
+def _distance_acc(distances, thr=0.5):
+ """Return the percentage below the distance threshold, while ignoring
+ distances values with -1.
+
+ Note:
+ batch_size: N
+ Args:
+ distances (np.ndarray[N, ]): The normalized distances.
+ thr (float): Threshold of the distances.
+
+ Returns:
+ float: Percentage of distances below the threshold. \
+ If all target keypoints are missing, return -1.
+ """
+ distance_valid = distances != -1
+ num_distance_valid = distance_valid.sum()
+ if num_distance_valid > 0:
+ return (distances[distance_valid] < thr).sum() / num_distance_valid
+ return -1
+
+
+def _get_max_preds(heatmaps):
+ """Get keypoint predictions from score maps.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ heatmap height: H
+ heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.
+
+ Returns:
+ tuple: A tuple containing aggregated results.
+
+ - preds (np.ndarray[N, K, 2]): Predicted keypoint location.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ assert isinstance(heatmaps,
+ np.ndarray), ('heatmaps should be numpy.ndarray')
+ assert heatmaps.ndim == 4, 'batch_images should be 4-ndim'
+
+ N, K, _, W = heatmaps.shape
+ heatmaps_reshaped = heatmaps.reshape((N, K, -1))
+ idx = np.argmax(heatmaps_reshaped, 2).reshape((N, K, 1))
+ maxvals = np.amax(heatmaps_reshaped, 2).reshape((N, K, 1))
+
+ preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
+ preds[:, :, 0] = preds[:, :, 0] % W
+ preds[:, :, 1] = preds[:, :, 1] // W
+
+ preds = np.where(np.tile(maxvals, (1, 1, 2)) > 0.0, preds, -1)
+ return preds, maxvals
+
+
+def _get_max_preds_3d(heatmaps):
+ """Get keypoint predictions from 3D score maps.
+
+ Note:
+ batch size: N
+ num keypoints: K
+ heatmap depth size: D
+ heatmap height: H
+ heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, D, H, W]): model predicted heatmaps.
+
+ Returns:
+ tuple: A tuple containing aggregated results.
+
+ - preds (np.ndarray[N, K, 3]): Predicted keypoint location.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ assert isinstance(heatmaps, np.ndarray), \
+ ('heatmaps should be numpy.ndarray')
+ assert heatmaps.ndim == 5, 'heatmaps should be 5-ndim'
+
+ N, K, D, H, W = heatmaps.shape
+ heatmaps_reshaped = heatmaps.reshape((N, K, -1))
+ idx = np.argmax(heatmaps_reshaped, 2).reshape((N, K, 1))
+ maxvals = np.amax(heatmaps_reshaped, 2).reshape((N, K, 1))
+
+ preds = np.zeros((N, K, 3), dtype=np.float32)
+ _idx = idx[..., 0]
+ preds[..., 2] = _idx // (H * W)
+ preds[..., 1] = (_idx // W) % H
+ preds[..., 0] = _idx % W
+
+ preds = np.where(maxvals > 0.0, preds, -1)
+ return preds, maxvals
+
+
+def pose_pck_accuracy(output, target, mask, thr=0.05, normalize=None):
+ """Calculate the pose accuracy of PCK for each individual keypoint and the
+ averaged accuracy across all keypoints from heatmaps.
+
+ Note:
+ PCK metric measures accuracy of the localization of the body joints.
+ The distances between predicted positions and the ground-truth ones
+ are typically normalized by the bounding box size.
+ The threshold (thr) of the normalized distance is commonly set
+ as 0.05, 0.1 or 0.2 etc.
+
+ - batch_size: N
+ - num_keypoints: K
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ output (np.ndarray[N, K, H, W]): Model output heatmaps.
+ target (np.ndarray[N, K, H, W]): Groundtruth heatmaps.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ thr (float): Threshold of PCK calculation. Default 0.05.
+ normalize (np.ndarray[N, 2]): Normalization factor for H&W.
+
+ Returns:
+ tuple: A tuple containing keypoint accuracy.
+
+ - np.ndarray[K]: Accuracy of each keypoint.
+ - float: Averaged accuracy across all keypoints.
+ - int: Number of valid keypoints.
+ """
+ N, K, H, W = output.shape
+ if K == 0:
+ return None, 0, 0
+ if normalize is None:
+ normalize = np.tile(np.array([[H, W]]), (N, 1))
+
+ pred, _ = _get_max_preds(output)
+ gt, _ = _get_max_preds(target)
+ return keypoint_pck_accuracy(pred, gt, mask, thr, normalize)
+
+
+def keypoint_pck_accuracy(pred, gt, mask, thr, normalize):
+ """Calculate the pose accuracy of PCK for each individual keypoint and the
+ averaged accuracy across all keypoints for coordinates.
+
+ Note:
+ PCK metric measures accuracy of the localization of the body joints.
+ The distances between predicted positions and the ground-truth ones
+ are typically normalized by the bounding box size.
+ The threshold (thr) of the normalized distance is commonly set
+ as 0.05, 0.1 or 0.2 etc.
+
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ pred (np.ndarray[N, K, 2]): Predicted keypoint location.
+ gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ thr (float): Threshold of PCK calculation.
+ normalize (np.ndarray[N, 2]): Normalization factor for H&W.
+
+ Returns:
+ tuple: A tuple containing keypoint accuracy.
+
+ - acc (np.ndarray[K]): Accuracy of each keypoint.
+ - avg_acc (float): Averaged accuracy across all keypoints.
+ - cnt (int): Number of valid keypoints.
+ """
+ distances = _calc_distances(pred, gt, mask, normalize)
+
+ acc = np.array([_distance_acc(d, thr) for d in distances])
+ valid_acc = acc[acc >= 0]
+ cnt = len(valid_acc)
+ avg_acc = valid_acc.mean() if cnt > 0 else 0
+ return acc, avg_acc, cnt
+
+
+def keypoint_auc(pred, gt, mask, normalize, num_step=20):
+ """Calculate the pose accuracy of PCK for each individual keypoint and the
+ averaged accuracy across all keypoints for coordinates.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ pred (np.ndarray[N, K, 2]): Predicted keypoint location.
+ gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ normalize (float): Normalization factor.
+
+ Returns:
+ float: Area under curve.
+ """
+ nor = np.tile(np.array([[normalize, normalize]]), (pred.shape[0], 1))
+ x = [1.0 * i / num_step for i in range(num_step)]
+ y = []
+ for thr in x:
+ _, avg_acc, _ = keypoint_pck_accuracy(pred, gt, mask, thr, nor)
+ y.append(avg_acc)
+
+ auc = 0
+ for i in range(num_step):
+ auc += 1.0 / num_step * y[i]
+ return auc
+
+
+def keypoint_nme(pred, gt, mask, normalize_factor):
+ """Calculate the normalized mean error (NME).
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ pred (np.ndarray[N, K, 2]): Predicted keypoint location.
+ gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ normalize_factor (np.ndarray[N, 2]): Normalization factor.
+
+ Returns:
+ float: normalized mean error
+ """
+ distances = _calc_distances(pred, gt, mask, normalize_factor)
+ distance_valid = distances[distances != -1]
+ return distance_valid.sum() / max(1, len(distance_valid))
+
+
+def keypoint_epe(pred, gt, mask):
+ """Calculate the end-point error.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ pred (np.ndarray[N, K, 2]): Predicted keypoint location.
+ gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+
+ Returns:
+ float: Average end-point error.
+ """
+
+ distances = _calc_distances(
+ pred, gt, mask,
+ np.ones((pred.shape[0], pred.shape[2]), dtype=np.float32))
+ distance_valid = distances[distances != -1]
+ return distance_valid.sum() / max(1, len(distance_valid))
+
+
+def _taylor(heatmap, coord):
+ """Distribution aware coordinate decoding method.
+
+ Note:
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ heatmap (np.ndarray[H, W]): Heatmap of a particular joint type.
+ coord (np.ndarray[2,]): Coordinates of the predicted keypoints.
+
+ Returns:
+ np.ndarray[2,]: Updated coordinates.
+ """
+ H, W = heatmap.shape[:2]
+ px, py = int(coord[0]), int(coord[1])
+ if 1 < px < W - 2 and 1 < py < H - 2:
+ dx = 0.5 * (heatmap[py][px + 1] - heatmap[py][px - 1])
+ dy = 0.5 * (heatmap[py + 1][px] - heatmap[py - 1][px])
+ dxx = 0.25 * (
+ heatmap[py][px + 2] - 2 * heatmap[py][px] + heatmap[py][px - 2])
+ dxy = 0.25 * (
+ heatmap[py + 1][px + 1] - heatmap[py - 1][px + 1] -
+ heatmap[py + 1][px - 1] + heatmap[py - 1][px - 1])
+ dyy = 0.25 * (
+ heatmap[py + 2 * 1][px] - 2 * heatmap[py][px] +
+ heatmap[py - 2 * 1][px])
+ derivative = np.array([[dx], [dy]])
+ hessian = np.array([[dxx, dxy], [dxy, dyy]])
+ if dxx * dyy - dxy**2 != 0:
+ hessianinv = np.linalg.inv(hessian)
+ offset = -hessianinv @ derivative
+ offset = np.squeeze(np.array(offset.T), axis=0)
+ coord += offset
+ return coord
+
+
+def post_dark_udp(coords, batch_heatmaps, kernel=3):
+ """DARK post-pocessing. Implemented by udp. Paper ref: Huang et al. The
+ Devil is in the Details: Delving into Unbiased Data Processing for Human
+ Pose Estimation (CVPR 2020). Zhang et al. Distribution-Aware Coordinate
+ Representation for Human Pose Estimation (CVPR 2020).
+
+ Note:
+ - batch size: B
+ - num keypoints: K
+ - num persons: N
+ - height of heatmaps: H
+ - width of heatmaps: W
+
+ B=1 for bottom_up paradigm where all persons share the same heatmap.
+ B=N for top_down paradigm where each person has its own heatmaps.
+
+ Args:
+ coords (np.ndarray[N, K, 2]): Initial coordinates of human pose.
+ batch_heatmaps (np.ndarray[B, K, H, W]): batch_heatmaps
+ kernel (int): Gaussian kernel size (K) for modulation.
+
+ Returns:
+ np.ndarray([N, K, 2]): Refined coordinates.
+ """
+ if not isinstance(batch_heatmaps, np.ndarray):
+ batch_heatmaps = batch_heatmaps.cpu().numpy()
+ B, K, H, W = batch_heatmaps.shape
+ N = coords.shape[0]
+ assert (B == 1 or B == N)
+ for heatmaps in batch_heatmaps:
+ for heatmap in heatmaps:
+ cv2.GaussianBlur(heatmap, (kernel, kernel), 0, heatmap)
+ np.clip(batch_heatmaps, 0.001, 50, batch_heatmaps)
+ np.log(batch_heatmaps, batch_heatmaps)
+
+ batch_heatmaps_pad = np.pad(
+ batch_heatmaps, ((0, 0), (0, 0), (1, 1), (1, 1)),
+ mode='edge').flatten()
+
+ index = coords[..., 0] + 1 + (coords[..., 1] + 1) * (W + 2)
+ index += (W + 2) * (H + 2) * np.arange(0, B * K).reshape(-1, K)
+ index = index.astype(int).reshape(-1, 1)
+ i_ = batch_heatmaps_pad[index]
+ ix1 = batch_heatmaps_pad[index + 1]
+ iy1 = batch_heatmaps_pad[index + W + 2]
+ ix1y1 = batch_heatmaps_pad[index + W + 3]
+ ix1_y1_ = batch_heatmaps_pad[index - W - 3]
+ ix1_ = batch_heatmaps_pad[index - 1]
+ iy1_ = batch_heatmaps_pad[index - 2 - W]
+
+ dx = 0.5 * (ix1 - ix1_)
+ dy = 0.5 * (iy1 - iy1_)
+ derivative = np.concatenate([dx, dy], axis=1)
+ derivative = derivative.reshape(N, K, 2, 1)
+ dxx = ix1 - 2 * i_ + ix1_
+ dyy = iy1 - 2 * i_ + iy1_
+ dxy = 0.5 * (ix1y1 - ix1 - iy1 + i_ + i_ - ix1_ - iy1_ + ix1_y1_)
+ hessian = np.concatenate([dxx, dxy, dxy, dyy], axis=1)
+ hessian = hessian.reshape(N, K, 2, 2)
+ hessian = np.linalg.inv(hessian + np.finfo(np.float32).eps * np.eye(2))
+ coords -= np.einsum('ijmn,ijnk->ijmk', hessian, derivative).squeeze()
+ return coords
+
+
+def _gaussian_blur(heatmaps, kernel=11):
+ """Modulate heatmap distribution with Gaussian.
+ sigma = 0.3*((kernel_size-1)*0.5-1)+0.8
+ sigma~=3 if k=17
+ sigma=2 if k=11;
+ sigma~=1.5 if k=7;
+ sigma~=1 if k=3;
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.
+ kernel (int): Gaussian kernel size (K) for modulation, which should
+ match the heatmap gaussian sigma when training.
+ K=17 for sigma=3 and k=11 for sigma=2.
+
+ Returns:
+ np.ndarray ([N, K, H, W]): Modulated heatmap distribution.
+ """
+ assert kernel % 2 == 1
+
+ border = (kernel - 1) // 2
+ batch_size = heatmaps.shape[0]
+ num_joints = heatmaps.shape[1]
+ height = heatmaps.shape[2]
+ width = heatmaps.shape[3]
+ for i in range(batch_size):
+ for j in range(num_joints):
+ origin_max = np.max(heatmaps[i, j])
+ dr = np.zeros((height + 2 * border, width + 2 * border),
+ dtype=np.float32)
+ dr[border:-border, border:-border] = heatmaps[i, j].copy()
+ dr = cv2.GaussianBlur(dr, (kernel, kernel), 0)
+ heatmaps[i, j] = dr[border:-border, border:-border].copy()
+ heatmaps[i, j] *= origin_max / np.max(heatmaps[i, j])
+ return heatmaps
+
+
+def keypoints_from_regression(regression_preds, center, scale, img_size):
+ """Get final keypoint predictions from regression vectors and transform
+ them back to the image.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ regression_preds (np.ndarray[N, K, 2]): model prediction.
+ center (np.ndarray[N, 2]): Center of the bounding box (x, y).
+ scale (np.ndarray[N, 2]): Scale of the bounding box
+ wrt height/width.
+ img_size (list(img_width, img_height)): model input image size.
+
+ Returns:
+ tuple:
+
+ - preds (np.ndarray[N, K, 2]): Predicted keypoint location in images.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ N, K, _ = regression_preds.shape
+ preds, maxvals = regression_preds, np.ones((N, K, 1), dtype=np.float32)
+
+ preds = preds * img_size
+
+ # Transform back to the image
+ for i in range(N):
+ preds[i] = transform_preds(preds[i], center[i], scale[i], img_size)
+
+ return preds, maxvals
+
+
+def keypoints_from_heatmaps(heatmaps,
+ center,
+ scale,
+ unbiased=False,
+ post_process='default',
+ kernel=11,
+ valid_radius_factor=0.0546875,
+ use_udp=False,
+ target_type='GaussianHeatmap'):
+ """Get final keypoint predictions from heatmaps and transform them back to
+ the image.
+
+ Note:
+ - batch size: N
+ - num keypoints: K
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.
+ center (np.ndarray[N, 2]): Center of the bounding box (x, y).
+ scale (np.ndarray[N, 2]): Scale of the bounding box
+ wrt height/width.
+ post_process (str/None): Choice of methods to post-process
+ heatmaps. Currently supported: None, 'default', 'unbiased',
+ 'megvii'.
+ unbiased (bool): Option to use unbiased decoding. Mutually
+ exclusive with megvii.
+ Note: this arg is deprecated and unbiased=True can be replaced
+ by post_process='unbiased'
+ Paper ref: Zhang et al. Distribution-Aware Coordinate
+ Representation for Human Pose Estimation (CVPR 2020).
+ kernel (int): Gaussian kernel size (K) for modulation, which should
+ match the heatmap gaussian sigma when training.
+ K=17 for sigma=3 and k=11 for sigma=2.
+ valid_radius_factor (float): The radius factor of the positive area
+ in classification heatmap for UDP.
+ use_udp (bool): Use unbiased data processing.
+ target_type (str): 'GaussianHeatmap' or 'CombinedTarget'.
+ GaussianHeatmap: Classification target with gaussian distribution.
+ CombinedTarget: The combination of classification target
+ (response map) and regression target (offset map).
+ Paper ref: Huang et al. The Devil is in the Details: Delving into
+ Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
+
+ Returns:
+ tuple: A tuple containing keypoint predictions and scores.
+
+ - preds (np.ndarray[N, K, 2]): Predicted keypoint location in images.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ # Avoid being affected
+ heatmaps = heatmaps.copy()
+
+ # detect conflicts
+ if unbiased:
+ assert post_process not in [False, None, 'megvii']
+ if post_process in ['megvii', 'unbiased']:
+ assert kernel > 0
+ if use_udp:
+ assert not post_process == 'megvii'
+
+ # normalize configs
+ if post_process is False:
+ warnings.warn(
+ 'post_process=False is deprecated, '
+ 'please use post_process=None instead', DeprecationWarning)
+ post_process = None
+ elif post_process is True:
+ if unbiased is True:
+ warnings.warn(
+ 'post_process=True, unbiased=True is deprecated,'
+ " please use post_process='unbiased' instead",
+ DeprecationWarning)
+ post_process = 'unbiased'
+ else:
+ warnings.warn(
+ 'post_process=True, unbiased=False is deprecated, '
+ "please use post_process='default' instead",
+ DeprecationWarning)
+ post_process = 'default'
+ elif post_process == 'default':
+ if unbiased is True:
+ warnings.warn(
+ 'unbiased=True is deprecated, please use '
+ "post_process='unbiased' instead", DeprecationWarning)
+ post_process = 'unbiased'
+
+ # start processing
+ if post_process == 'megvii':
+ heatmaps = _gaussian_blur(heatmaps, kernel=kernel)
+
+ N, K, H, W = heatmaps.shape
+ if use_udp:
+ if target_type.lower() == 'GaussianHeatMap'.lower():
+ preds, maxvals = _get_max_preds(heatmaps)
+ preds = post_dark_udp(preds, heatmaps, kernel=kernel)
+ elif target_type.lower() == 'CombinedTarget'.lower():
+ for person_heatmaps in heatmaps:
+ for i, heatmap in enumerate(person_heatmaps):
+ kt = 2 * kernel + 1 if i % 3 == 0 else kernel
+ cv2.GaussianBlur(heatmap, (kt, kt), 0, heatmap)
+ # valid radius is in direct proportion to the height of heatmap.
+ valid_radius = valid_radius_factor * H
+ offset_x = heatmaps[:, 1::3, :].flatten() * valid_radius
+ offset_y = heatmaps[:, 2::3, :].flatten() * valid_radius
+ heatmaps = heatmaps[:, ::3, :]
+ preds, maxvals = _get_max_preds(heatmaps)
+ index = preds[..., 0] + preds[..., 1] * W
+ index += W * H * np.arange(0, N * K / 3)
+ index = index.astype(int).reshape(N, K // 3, 1)
+ preds += np.concatenate((offset_x[index], offset_y[index]), axis=2)
+ else:
+ raise ValueError('target_type should be either '
+ "'GaussianHeatmap' or 'CombinedTarget'")
+ else:
+ preds, maxvals = _get_max_preds(heatmaps)
+ if post_process == 'unbiased': # alleviate biased coordinate
+ # apply Gaussian distribution modulation.
+ heatmaps = np.log(
+ np.maximum(_gaussian_blur(heatmaps, kernel), 1e-10))
+ for n in range(N):
+ for k in range(K):
+ preds[n][k] = _taylor(heatmaps[n][k], preds[n][k])
+ elif post_process is not None:
+ # add +/-0.25 shift to the predicted locations for higher acc.
+ for n in range(N):
+ for k in range(K):
+ heatmap = heatmaps[n][k]
+ px = int(preds[n][k][0])
+ py = int(preds[n][k][1])
+ if 1 < px < W - 1 and 1 < py < H - 1:
+ diff = np.array([
+ heatmap[py][px + 1] - heatmap[py][px - 1],
+ heatmap[py + 1][px] - heatmap[py - 1][px]
+ ])
+ preds[n][k] += np.sign(diff) * .25
+ if post_process == 'megvii':
+ preds[n][k] += 0.5
+
+ # Transform back to the image
+ for i in range(N):
+ preds[i] = transform_preds(
+ preds[i], center[i], scale[i], [W, H], use_udp=use_udp)
+
+ if post_process == 'megvii':
+ maxvals = maxvals / 255.0 + 0.5
+
+ return preds, maxvals
+
+
+def keypoints_from_heatmaps3d(heatmaps, center, scale):
+ """Get final keypoint predictions from 3d heatmaps and transform them back
+ to the image.
+
+ Note:
+ - batch size: N
+ - num keypoints: K
+ - heatmap depth size: D
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, D, H, W]): model predicted heatmaps.
+ center (np.ndarray[N, 2]): Center of the bounding box (x, y).
+ scale (np.ndarray[N, 2]): Scale of the bounding box
+ wrt height/width.
+
+ Returns:
+ tuple: A tuple containing keypoint predictions and scores.
+
+ - preds (np.ndarray[N, K, 3]): Predicted 3d keypoint location \
+ in images.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ N, K, D, H, W = heatmaps.shape
+ preds, maxvals = _get_max_preds_3d(heatmaps)
+ # Transform back to the image
+ for i in range(N):
+ preds[i, :, :2] = transform_preds(preds[i, :, :2], center[i], scale[i],
+ [W, H])
+ return preds, maxvals
+
+
+def multilabel_classification_accuracy(pred, gt, mask, thr=0.5):
+ """Get multi-label classification accuracy.
+
+ Note:
+ - batch size: N
+ - label number: L
+
+ Args:
+ pred (np.ndarray[N, L, 2]): model predicted labels.
+ gt (np.ndarray[N, L, 2]): ground-truth labels.
+ mask (np.ndarray[N, 1] or np.ndarray[N, L] ): reliability of
+ ground-truth labels.
+
+ Returns:
+ float: multi-label classification accuracy.
+ """
+ # we only compute accuracy on the samples with ground-truth of all labels.
+ valid = (mask > 0).min(axis=1) if mask.ndim == 2 else (mask > 0)
+ pred, gt = pred[valid], gt[valid]
+
+ if pred.shape[0] == 0:
+ acc = 0.0 # when no sample is with gt labels, set acc to 0.
+ else:
+ # The classification of a sample is regarded as correct
+ # only if it's correct for all labels.
+ acc = (((pred - thr) * (gt - thr)) > 0).all(axis=1).mean()
+ return acc
+
+
+
+def get_transform(center, scale, res, rot=0):
+ """Generate transformation matrix."""
+ # res: (height, width), (rows, cols)
+ crop_aspect_ratio = res[0] / float(res[1])
+ h = 200 * scale
+ w = h / crop_aspect_ratio
+ t = np.zeros((3, 3))
+ t[0, 0] = float(res[1]) / w
+ t[1, 1] = float(res[0]) / h
+ t[0, 2] = res[1] * (-float(center[0]) / w + .5)
+ t[1, 2] = res[0] * (-float(center[1]) / h + .5)
+ t[2, 2] = 1
+ if not rot == 0:
+ rot = -rot # To match direction of rotation from cropping
+ rot_mat = np.zeros((3, 3))
+ rot_rad = rot * np.pi / 180
+ sn, cs = np.sin(rot_rad), np.cos(rot_rad)
+ rot_mat[0, :2] = [cs, -sn]
+ rot_mat[1, :2] = [sn, cs]
+ rot_mat[2, 2] = 1
+ # Need to rotate around center
+ t_mat = np.eye(3)
+ t_mat[0, 2] = -res[1] / 2
+ t_mat[1, 2] = -res[0] / 2
+ t_inv = t_mat.copy()
+ t_inv[:2, 2] *= -1
+ t = np.dot(t_inv, np.dot(rot_mat, np.dot(t_mat, t)))
+ return t
+
+
+def transform(pt, center, scale, res, invert=0, rot=0):
+ """Transform pixel location to different reference."""
+ t = get_transform(center, scale, res, rot=rot)
+ if invert:
+ t = np.linalg.inv(t)
+ new_pt = np.array([pt[0] - 1, pt[1] - 1, 1.]).T
+ new_pt = np.dot(t, new_pt)
+ return np.array([round(new_pt[0]), round(new_pt[1])], dtype=int) + 1
+
+
+def bbox_from_detector(bbox, input_resolution=(224, 224), rescale=1.25):
+ """
+ Get center and scale of bounding box from bounding box.
+ The expected format is [min_x, min_y, max_x, max_y].
+ """
+ CROP_IMG_HEIGHT, CROP_IMG_WIDTH = input_resolution
+ CROP_ASPECT_RATIO = CROP_IMG_HEIGHT / float(CROP_IMG_WIDTH)
+
+ # center
+ center_x = (bbox[0] + bbox[2]) / 2.0
+ center_y = (bbox[1] + bbox[3]) / 2.0
+ center = np.array([center_x, center_y])
+
+ # scale
+ bbox_w = bbox[2] - bbox[0]
+ bbox_h = bbox[3] - bbox[1]
+ bbox_size = max(bbox_w * CROP_ASPECT_RATIO, bbox_h)
+
+ scale = np.array([bbox_size / CROP_ASPECT_RATIO, bbox_size]) / 200.0
+ # scale = bbox_size / 200.0
+ # adjust bounding box tightness
+ scale *= rescale
+ return center, scale
+
+
+def crop(img, center, scale, res):
+ """
+ Crop image according to the supplied bounding box.
+ res: [rows, cols]
+ """
+ # Upper left point
+ ul = np.array(transform([1, 1], center, max(scale), res, invert=1)) - 1
+ # Bottom right point
+ br = np.array(transform([res[1] + 1, res[0] + 1], center, max(scale), res, invert=1)) - 1
+
+ # Padding so that when rotated proper amount of context is included
+ pad = int(np.linalg.norm(br - ul) / 2 - float(br[1] - ul[1]) / 2)
+
+ new_shape = [br[1] - ul[1], br[0] - ul[0]]
+ if len(img.shape) > 2:
+ new_shape += [img.shape[2]]
+ new_img = np.zeros(new_shape, dtype=np.float32)
+
+ # Range to fill new array
+ new_x = max(0, -ul[0]), min(br[0], len(img[0])) - ul[0]
+ new_y = max(0, -ul[1]), min(br[1], len(img)) - ul[1]
+ # Range to sample from original image
+ old_x = max(0, ul[0]), min(len(img[0]), br[0])
+ old_y = max(0, ul[1]), min(len(img), br[1])
+ try:
+ new_img[new_y[0]:new_y[1], new_x[0]:new_x[1]] = img[old_y[0]:old_y[1], old_x[0]:old_x[1]]
+ except Exception as e:
+ print(e)
+
+ new_img = cv2.resize(new_img, (res[1], res[0])) # (cols, rows)
+ return new_img, new_shape, (old_x, old_y), (new_x, new_y) # , ul, br
+
+
+def split_kp2ds_for_aa(kp2ds, ret_face=False):
+ kp2ds_body = (kp2ds[[0, 6, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 17, 20]] + kp2ds[[0, 5, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3, 18, 21]]) / 2
+ kp2ds_lhand = kp2ds[91:112]
+ kp2ds_rhand = kp2ds[112:133]
+ kp2ds_face = kp2ds[22:91]
+ if ret_face:
+ return kp2ds_body.copy(), kp2ds_lhand.copy(), kp2ds_rhand.copy(), kp2ds_face.copy()
+ return kp2ds_body.copy(), kp2ds_lhand.copy(), kp2ds_rhand.copy()
+
+def load_pose_metas_from_kp2ds_seq_list(kp2ds_seq, width, height):
+ metas = []
+ for kps in kp2ds_seq:
+ if len(kps) != 1:
+ return None
+ kps = kps[0].copy()
+ kps[:, 0] /= width
+ kps[:, 1] /= height
+ kp2ds_body, kp2ds_lhand, kp2ds_rhand, kp2ds_face = split_kp2ds_for_aa(kps, ret_face=True)
+
+ if kp2ds_body[:, :2].min(axis=1).max() < 0:
+ kp2ds_body = last_kp2ds_body
+ last_kp2ds_body = kp2ds_body
+
+ meta = {
+ "width": width,
+ "height": height,
+ "keypoints_body": kp2ds_body.tolist(),
+ "keypoints_left_hand": kp2ds_lhand.tolist(),
+ "keypoints_right_hand": kp2ds_rhand.tolist(),
+ "keypoints_face": kp2ds_face.tolist(),
+ }
+ metas.append(meta)
+ return metas
+
+
+def load_pose_metas_from_kp2ds_seq(kp2ds_seq, width, height):
+ metas = []
+ for kps in kp2ds_seq:
+ kps = kps.copy()
+ kps[:, 0] /= width
+ kps[:, 1] /= height
+ kp2ds_body, kp2ds_lhand, kp2ds_rhand, kp2ds_face = split_kp2ds_for_aa(kps, ret_face=True)
+
+ # 排除全部小于0的情况
+ if kp2ds_body[:, :2].min(axis=1).max() < 0:
+ kp2ds_body = last_kp2ds_body
+ last_kp2ds_body = kp2ds_body
+
+ meta = {
+ "width": width,
+ "height": height,
+ "keypoints_body": kp2ds_body,
+ "keypoints_left_hand": kp2ds_lhand,
+ "keypoints_right_hand": kp2ds_rhand,
+ "keypoints_face": kp2ds_face,
+ }
+ metas.append(meta)
+ return metas
\ No newline at end of file
diff --git a/wan/modules/animate/preprocess/preprocess_data.py b/wan/modules/animate/preprocess/preprocess_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..150088ed08203d8a51f257ce33aaf145350768c6
--- /dev/null
+++ b/wan/modules/animate/preprocess/preprocess_data.py
@@ -0,0 +1,121 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import os
+import argparse
+from process_pipepline import ProcessPipeline
+
+
+def _parse_args():
+ parser = argparse.ArgumentParser(
+ description="The preprocessing pipeline for Wan-animate."
+ )
+
+ parser.add_argument(
+ "--ckpt_path",
+ type=str,
+ default=None,
+ help="The path to the preprocessing model's checkpoint directory. ")
+
+ parser.add_argument(
+ "--video_path",
+ type=str,
+ default=None,
+ help="The path to the driving video.")
+ parser.add_argument(
+ "--refer_path",
+ type=str,
+ default=None,
+ help="The path to the refererence image.")
+ parser.add_argument(
+ "--save_path",
+ type=str,
+ default=None,
+ help="The path to save the processed results.")
+
+ parser.add_argument(
+ "--resolution_area",
+ type=int,
+ nargs=2,
+ default=[1280, 720],
+ help="The target resolution for processing, specified as [width, height]. To handle different aspect ratios, the video is resized to have a total area equivalent to width * height, while preserving the original aspect ratio."
+ )
+ parser.add_argument(
+ "--fps",
+ type=int,
+ default=30,
+ help="The target FPS for processing the driving video. Set to -1 to use the video's original FPS."
+ )
+
+ parser.add_argument(
+ "--replace_flag",
+ action="store_true",
+ default=False,
+ help="Whether to use replacement mode.")
+ parser.add_argument(
+ "--retarget_flag",
+ action="store_true",
+ default=False,
+ help="Whether to use pose retargeting. Currently only supported in animation mode")
+ parser.add_argument(
+ "--use_flux",
+ action="store_true",
+ default=False,
+ help="Whether to use image editing in pose retargeting. Recommended if the character in the reference image or the first frame of the driving video is not in a standard, front-facing pose")
+
+ # Parameters for the mask strategy in replacement mode. These control the mask's size and shape. Refer to https://arxiv.org/pdf/2502.06145
+ parser.add_argument(
+ "--iterations",
+ type=int,
+ default=3,
+ help="Number of iterations for mask dilation."
+ )
+ parser.add_argument(
+ "--k",
+ type=int,
+ default=7,
+ help="Number of kernel size for mask dilation."
+ )
+ parser.add_argument(
+ "--w_len",
+ type=int,
+ default=1,
+ help="The number of subdivisions for the grid along the 'w' dimension. A higher value results in a more detailed contour. A value of 1 means no subdivision is performed."
+ )
+ parser.add_argument(
+ "--h_len",
+ type=int,
+ default=1,
+ help="The number of subdivisions for the grid along the 'h' dimension. A higher value results in a more detailed contour. A value of 1 means no subdivision is performed."
+ )
+ args = parser.parse_args()
+
+ return args
+
+
+if __name__ == '__main__':
+ args = _parse_args()
+ args_dict = vars(args)
+ print(args_dict)
+
+ assert len(args.resolution_area) == 2, "resolution_area should be a list of two integers [width, height]"
+ assert not args.use_flux or args.retarget_flag, "Image editing with FLUX can only be used when pose retargeting is enabled."
+
+ pose2d_checkpoint_path = os.path.join(args.ckpt_path, 'pose2d/vitpose_h_wholebody.onnx')
+ det_checkpoint_path = os.path.join(args.ckpt_path, 'det/yolov10m.onnx')
+
+ sam2_checkpoint_path = os.path.join(args.ckpt_path, 'sam2/sam2_hiera_large.pt') if args.replace_flag else None
+ flux_kontext_path = os.path.join(args.ckpt_path, 'FLUX.1-Kontext-dev') if args.use_flux else None
+ process_pipeline = ProcessPipeline(det_checkpoint_path=det_checkpoint_path, pose2d_checkpoint_path=pose2d_checkpoint_path, sam_checkpoint_path=sam2_checkpoint_path, flux_kontext_path=flux_kontext_path)
+ os.makedirs(args.save_path, exist_ok=True)
+ process_pipeline(video_path=args.video_path,
+ refer_image_path=args.refer_path,
+ output_path=args.save_path,
+ resolution_area=args.resolution_area,
+ fps=args.fps,
+ iterations=args.iterations,
+ k=args.k,
+ w_len=args.w_len,
+ h_len=args.h_len,
+ retarget_flag=args.retarget_flag,
+ use_flux=args.use_flux,
+ replace_flag=args.replace_flag)
+
diff --git a/wan/modules/animate/preprocess/process_pipepline.py b/wan/modules/animate/preprocess/process_pipepline.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d4d23cf8c288855e9a909b2b31e8c72f6446b11
--- /dev/null
+++ b/wan/modules/animate/preprocess/process_pipepline.py
@@ -0,0 +1,354 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import os
+import numpy as np
+import shutil
+import torch
+from diffusers import FluxKontextPipeline
+import cv2
+from loguru import logger
+from PIL import Image
+try:
+ import moviepy.editor as mpy
+except:
+ import moviepy as mpy
+
+from decord import VideoReader
+from pose2d import Pose2d
+from pose2d_utils import AAPoseMeta
+from utils import resize_by_area, get_frame_indices, padding_resize, get_face_bboxes, get_aug_mask, get_mask_body_img
+from human_visualization import draw_aapose_by_meta_new
+from retarget_pose import get_retarget_pose
+import sam2.modeling.sam.transformer as transformer
+transformer.USE_FLASH_ATTN = False
+transformer.MATH_KERNEL_ON = True
+transformer.OLD_GPU = True
+from sam_utils import build_sam2_video_predictor
+
+
+class ProcessPipeline():
+ def __init__(self, det_checkpoint_path, pose2d_checkpoint_path, sam_checkpoint_path, flux_kontext_path):
+ self.pose2d = Pose2d(checkpoint=pose2d_checkpoint_path, detector_checkpoint=det_checkpoint_path)
+
+ model_cfg = "sam2_hiera_l.yaml"
+ if sam_checkpoint_path is not None:
+ self.predictor = build_sam2_video_predictor(model_cfg, sam_checkpoint_path)
+ if flux_kontext_path is not None:
+ self.flux_kontext = FluxKontextPipeline.from_pretrained(flux_kontext_path, torch_dtype=torch.bfloat16).to("cuda")
+
+ def __call__(self, video_path, refer_image_path, output_path, resolution_area=[1280, 720], fps=30, iterations=3, k=7, w_len=1, h_len=1, retarget_flag=False, use_flux=False, replace_flag=False):
+ if replace_flag:
+
+ video_reader = VideoReader(video_path)
+ frame_num = len(video_reader)
+ print('frame_num: {}'.format(frame_num))
+
+ video_fps = video_reader.get_avg_fps()
+ print('video_fps: {}'.format(video_fps))
+ print('fps: {}'.format(fps))
+
+ # TODO: Maybe we can switch to PyAV later, which can get accurate frame num
+ duration = video_reader.get_frame_timestamp(-1)[-1]
+ expected_frame_num = int(duration * video_fps + 0.5)
+ ratio = abs((frame_num - expected_frame_num)/frame_num)
+ if ratio > 0.1:
+ print("Warning: The difference between the actual number of frames and the expected number of frames is two large")
+ frame_num = expected_frame_num
+
+ if fps == -1:
+ fps = video_fps
+
+ target_num = int(frame_num / video_fps * fps)
+ print('target_num: {}'.format(target_num))
+ idxs = get_frame_indices(frame_num, video_fps, target_num, fps)
+ frames = video_reader.get_batch(idxs).asnumpy()
+
+ frames = [resize_by_area(frame, resolution_area[0] * resolution_area[1], divisor=16) for frame in frames]
+ height, width = frames[0].shape[:2]
+ logger.info(f"Processing pose meta")
+
+
+ tpl_pose_metas = self.pose2d(frames)
+
+ face_images = []
+ for idx, meta in enumerate(tpl_pose_metas):
+ face_bbox_for_image = get_face_bboxes(meta['keypoints_face'][:, :2], scale=1.3,
+ image_shape=(frames[0].shape[0], frames[0].shape[1]))
+
+ x1, x2, y1, y2 = face_bbox_for_image
+ face_image = frames[idx][y1:y2, x1:x2]
+ face_image = cv2.resize(face_image, (512, 512))
+ face_images.append(face_image)
+
+ logger.info(f"Processing reference image: {refer_image_path}")
+ refer_img = cv2.imread(refer_image_path)
+ src_ref_path = os.path.join(output_path, 'src_ref.png')
+ shutil.copy(refer_image_path, src_ref_path)
+ refer_img = refer_img[..., ::-1]
+
+ refer_img = padding_resize(refer_img, height, width)
+ logger.info(f"Processing template video: {video_path}")
+ tpl_retarget_pose_metas = [AAPoseMeta.from_humanapi_meta(meta) for meta in tpl_pose_metas]
+ cond_images = []
+
+ for idx, meta in enumerate(tpl_retarget_pose_metas):
+ canvas = np.zeros_like(refer_img)
+ conditioning_image = draw_aapose_by_meta_new(canvas, meta)
+ cond_images.append(conditioning_image)
+ masks = self.get_mask(frames, 400, tpl_pose_metas)
+
+ bg_images = []
+ aug_masks = []
+
+ for frame, mask in zip(frames, masks):
+ if iterations > 0:
+ _, each_mask = get_mask_body_img(frame, mask, iterations=iterations, k=k)
+ each_aug_mask = get_aug_mask(each_mask, w_len=w_len, h_len=h_len)
+ else:
+ each_aug_mask = mask
+
+ each_bg_image = frame * (1 - each_aug_mask[:, :, None])
+ bg_images.append(each_bg_image)
+ aug_masks.append(each_aug_mask)
+
+ src_face_path = os.path.join(output_path, 'src_face.mp4')
+ mpy.ImageSequenceClip(face_images, fps=fps).write_videofile(src_face_path)
+
+ src_pose_path = os.path.join(output_path, 'src_pose.mp4')
+ mpy.ImageSequenceClip(cond_images, fps=fps).write_videofile(src_pose_path)
+
+ src_bg_path = os.path.join(output_path, 'src_bg.mp4')
+ mpy.ImageSequenceClip(bg_images, fps=fps).write_videofile(src_bg_path)
+
+ aug_masks_new = [np.stack([mask * 255, mask * 255, mask * 255], axis=2) for mask in aug_masks]
+ src_mask_path = os.path.join(output_path, 'src_mask.mp4')
+ mpy.ImageSequenceClip(aug_masks_new, fps=fps).write_videofile(src_mask_path)
+ return True
+ else:
+ logger.info(f"Processing reference image: {refer_image_path}")
+ refer_img = cv2.imread(refer_image_path)
+ src_ref_path = os.path.join(output_path, 'src_ref.png')
+ shutil.copy(refer_image_path, src_ref_path)
+ refer_img = refer_img[..., ::-1]
+
+ refer_img = resize_by_area(refer_img, resolution_area[0] * resolution_area[1], divisor=16)
+
+ refer_pose_meta = self.pose2d([refer_img])[0]
+
+
+ logger.info(f"Processing template video: {video_path}")
+ video_reader = VideoReader(video_path)
+ frame_num = len(video_reader)
+ print('frame_num: {}'.format(frame_num))
+
+ video_fps = video_reader.get_avg_fps()
+ print('video_fps: {}'.format(video_fps))
+ print('fps: {}'.format(fps))
+
+ # TODO: Maybe we can switch to PyAV later, which can get accurate frame num
+ duration = video_reader.get_frame_timestamp(-1)[-1]
+ expected_frame_num = int(duration * video_fps + 0.5)
+ ratio = abs((frame_num - expected_frame_num)/frame_num)
+ if ratio > 0.1:
+ print("Warning: The difference between the actual number of frames and the expected number of frames is two large")
+ frame_num = expected_frame_num
+
+ if fps == -1:
+ fps = video_fps
+
+ target_num = int(frame_num / video_fps * fps)
+ print('target_num: {}'.format(target_num))
+ idxs = get_frame_indices(frame_num, video_fps, target_num, fps)
+ frames = video_reader.get_batch(idxs).asnumpy()
+
+ logger.info(f"Processing pose meta")
+
+ tpl_pose_meta0 = self.pose2d(frames[:1])[0]
+ tpl_pose_metas = self.pose2d(frames)
+
+ face_images = []
+ for idx, meta in enumerate(tpl_pose_metas):
+ face_bbox_for_image = get_face_bboxes(meta['keypoints_face'][:, :2], scale=1.3,
+ image_shape=(frames[0].shape[0], frames[0].shape[1]))
+
+ x1, x2, y1, y2 = face_bbox_for_image
+ face_image = frames[idx][y1:y2, x1:x2]
+ face_image = cv2.resize(face_image, (512, 512))
+ face_images.append(face_image)
+
+ if retarget_flag:
+ if use_flux:
+ tpl_prompt, refer_prompt = self.get_editing_prompts(tpl_pose_metas, refer_pose_meta)
+ refer_input = Image.fromarray(refer_img)
+ refer_edit = self.flux_kontext(
+ image=refer_input,
+ height=refer_img.shape[0],
+ width=refer_img.shape[1],
+ prompt=refer_prompt,
+ guidance_scale=2.5,
+ num_inference_steps=28,
+ ).images[0]
+
+ refer_edit = Image.fromarray(padding_resize(np.array(refer_edit), refer_img.shape[0], refer_img.shape[1]))
+ refer_edit_path = os.path.join(output_path, 'refer_edit.png')
+ refer_edit.save(refer_edit_path)
+ refer_edit_pose_meta = self.pose2d([np.array(refer_edit)])[0]
+
+ tpl_img = frames[1]
+ tpl_input = Image.fromarray(tpl_img)
+
+ tpl_edit = self.flux_kontext(
+ image=tpl_input,
+ height=tpl_img.shape[0],
+ width=tpl_img.shape[1],
+ prompt=tpl_prompt,
+ guidance_scale=2.5,
+ num_inference_steps=28,
+ ).images[0]
+
+ tpl_edit = Image.fromarray(padding_resize(np.array(tpl_edit), tpl_img.shape[0], tpl_img.shape[1]))
+ tpl_edit_path = os.path.join(output_path, 'tpl_edit.png')
+ tpl_edit.save(tpl_edit_path)
+ tpl_edit_pose_meta0 = self.pose2d([np.array(tpl_edit)])[0]
+ tpl_retarget_pose_metas = get_retarget_pose(tpl_pose_meta0, refer_pose_meta, tpl_pose_metas, tpl_edit_pose_meta0, refer_edit_pose_meta)
+ else:
+ tpl_retarget_pose_metas = get_retarget_pose(tpl_pose_meta0, refer_pose_meta, tpl_pose_metas, None, None)
+ else:
+ tpl_retarget_pose_metas = [AAPoseMeta.from_humanapi_meta(meta) for meta in tpl_pose_metas]
+
+ cond_images = []
+ for idx, meta in enumerate(tpl_retarget_pose_metas):
+ if retarget_flag:
+ canvas = np.zeros_like(refer_img)
+ conditioning_image = draw_aapose_by_meta_new(canvas, meta)
+ else:
+ canvas = np.zeros_like(frames[0])
+ conditioning_image = draw_aapose_by_meta_new(canvas, meta)
+ conditioning_image = padding_resize(conditioning_image, refer_img.shape[0], refer_img.shape[1])
+
+ cond_images.append(conditioning_image)
+
+ src_face_path = os.path.join(output_path, 'src_face.mp4')
+ mpy.ImageSequenceClip(face_images, fps=fps).write_videofile(src_face_path)
+
+ src_pose_path = os.path.join(output_path, 'src_pose.mp4')
+ mpy.ImageSequenceClip(cond_images, fps=fps).write_videofile(src_pose_path)
+ return True
+
+ def get_editing_prompts(self, tpl_pose_metas, refer_pose_meta):
+ arm_visible = False
+ leg_visible = False
+ for tpl_pose_meta in tpl_pose_metas:
+ tpl_keypoints = tpl_pose_meta['keypoints_body']
+ if tpl_keypoints[3].all() != 0 or tpl_keypoints[4].all() != 0 or tpl_keypoints[6].all() != 0 or tpl_keypoints[7].all() != 0:
+ if (tpl_keypoints[3][0] <= 1 and tpl_keypoints[3][1] <= 1 and tpl_keypoints[3][2] >= 0.75) or (tpl_keypoints[4][0] <= 1 and tpl_keypoints[4][1] <= 1 and tpl_keypoints[4][2] >= 0.75) or \
+ (tpl_keypoints[6][0] <= 1 and tpl_keypoints[6][1] <= 1 and tpl_keypoints[6][2] >= 0.75) or (tpl_keypoints[7][0] <= 1 and tpl_keypoints[7][1] <= 1 and tpl_keypoints[7][2] >= 0.75):
+ arm_visible = True
+ if tpl_keypoints[9].all() != 0 or tpl_keypoints[12].all() != 0 or tpl_keypoints[10].all() != 0 or tpl_keypoints[13].all() != 0:
+ if (tpl_keypoints[9][0] <= 1 and tpl_keypoints[9][1] <= 1 and tpl_keypoints[9][2] >= 0.75) or (tpl_keypoints[12][0] <= 1 and tpl_keypoints[12][1] <= 1 and tpl_keypoints[12][2] >= 0.75) or \
+ (tpl_keypoints[10][0] <= 1 and tpl_keypoints[10][1] <= 1 and tpl_keypoints[10][2] >= 0.75) or (tpl_keypoints[13][0] <= 1 and tpl_keypoints[13][1] <= 1 and tpl_keypoints[13][2] >= 0.75):
+ leg_visible = True
+ if arm_visible and leg_visible:
+ break
+
+ if leg_visible:
+ if tpl_pose_meta['width'] > tpl_pose_meta['height']:
+ tpl_prompt = "Change the person to a standard T-pose (facing forward with arms extended). The person is standing. Feet and Hands are visible in the image."
+ else:
+ tpl_prompt = "Change the person to a standard pose with the face oriented forward and arms extending straight down by the sides. The person is standing. Feet and Hands are visible in the image."
+
+ if refer_pose_meta['width'] > refer_pose_meta['height']:
+ refer_prompt = "Change the person to a standard T-pose (facing forward with arms extended). The person is standing. Feet and Hands are visible in the image."
+ else:
+ refer_prompt = "Change the person to a standard pose with the face oriented forward and arms extending straight down by the sides. The person is standing. Feet and Hands are visible in the image."
+ elif arm_visible:
+ if tpl_pose_meta['width'] > tpl_pose_meta['height']:
+ tpl_prompt = "Change the person to a standard T-pose (facing forward with arms extended). Hands are visible in the image."
+ else:
+ tpl_prompt = "Change the person to a standard pose with the face oriented forward and arms extending straight down by the sides. Hands are visible in the image."
+
+ if refer_pose_meta['width'] > refer_pose_meta['height']:
+ refer_prompt = "Change the person to a standard T-pose (facing forward with arms extended). Hands are visible in the image."
+ else:
+ refer_prompt = "Change the person to a standard pose with the face oriented forward and arms extending straight down by the sides. Hands are visible in the image."
+ else:
+ tpl_prompt = "Change the person to face forward."
+ refer_prompt = "Change the person to face forward."
+
+ return tpl_prompt, refer_prompt
+
+
+ def get_mask(self, frames, th_step, kp2ds_all):
+ frame_num = len(frames)
+ if frame_num < th_step:
+ num_step = 1
+ else:
+ num_step = (frame_num + th_step) // th_step
+
+ all_mask = []
+ for index in range(num_step):
+ each_frames = frames[index * th_step:(index + 1) * th_step]
+
+ kp2ds = kp2ds_all[index * th_step:(index + 1) * th_step]
+ if len(each_frames) > 4:
+ key_frame_num = 4
+ elif 4 >= len(each_frames) > 0:
+ key_frame_num = 1
+ else:
+ continue
+
+ key_frame_step = len(kp2ds) // key_frame_num
+ key_frame_index_list = list(range(0, len(kp2ds), key_frame_step))
+
+ key_points_index = [0, 1, 2, 5, 8, 11, 10, 13]
+ key_frame_body_points_list = []
+ for key_frame_index in key_frame_index_list:
+ keypoints_body_list = []
+ body_key_points = kp2ds[key_frame_index]['keypoints_body']
+ for each_index in key_points_index:
+ each_keypoint = body_key_points[each_index]
+ if None is each_keypoint:
+ continue
+ keypoints_body_list.append(each_keypoint)
+
+ keypoints_body = np.array(keypoints_body_list)[:, :2]
+ wh = np.array([[kp2ds[0]['width'], kp2ds[0]['height']]])
+ points = (keypoints_body * wh).astype(np.int32)
+ key_frame_body_points_list.append(points)
+
+ inference_state = self.predictor.init_state_v2(frames=each_frames)
+ self.predictor.reset_state(inference_state)
+ ann_obj_id = 1
+ for ann_frame_idx, points in zip(key_frame_index_list, key_frame_body_points_list):
+ labels = np.array([1] * points.shape[0], np.int32)
+ _, out_obj_ids, out_mask_logits = self.predictor.add_new_points(
+ inference_state=inference_state,
+ frame_idx=ann_frame_idx,
+ obj_id=ann_obj_id,
+ points=points,
+ labels=labels,
+ )
+
+ video_segments = {}
+ for out_frame_idx, out_obj_ids, out_mask_logits in self.predictor.propagate_in_video(inference_state):
+ video_segments[out_frame_idx] = {
+ out_obj_id: (out_mask_logits[i] > 0.0).cpu().numpy()
+ for i, out_obj_id in enumerate(out_obj_ids)
+ }
+
+ for out_frame_idx in range(len(video_segments)):
+ for out_obj_id, out_mask in video_segments[out_frame_idx].items():
+ out_mask = out_mask[0].astype(np.uint8)
+ all_mask.append(out_mask)
+
+ return all_mask
+
+ def convert_list_to_array(self, metas):
+ metas_list = []
+ for meta in metas:
+ for key, value in meta.items():
+ if type(value) is list:
+ value = np.array(value)
+ meta[key] = value
+ metas_list.append(meta)
+ return metas_list
+
diff --git a/wan/modules/animate/preprocess/retarget_pose.py b/wan/modules/animate/preprocess/retarget_pose.py
new file mode 100644
index 0000000000000000000000000000000000000000..75ca5ab02dc6afd5540609993122ca3557dd532f
--- /dev/null
+++ b/wan/modules/animate/preprocess/retarget_pose.py
@@ -0,0 +1,847 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import os
+import cv2
+import numpy as np
+import json
+from tqdm import tqdm
+import math
+from typing import NamedTuple, List
+import copy
+from pose2d_utils import AAPoseMeta
+
+
+# load skeleton name and bone lines
+keypoint_list = [
+ "Nose",
+ "Neck",
+ "RShoulder",
+ "RElbow",
+ "RWrist", # No.4
+ "LShoulder",
+ "LElbow",
+ "LWrist", # No.7
+ "RHip",
+ "RKnee",
+ "RAnkle", # No.10
+ "LHip",
+ "LKnee",
+ "LAnkle", # No.13
+ "REye",
+ "LEye",
+ "REar",
+ "LEar",
+ "LToe",
+ "RToe",
+]
+
+
+limbSeq = [
+ [2, 3], [2, 6], # shoulders
+ [3, 4], [4, 5], # left arm
+ [6, 7], [7, 8], # right arm
+ [2, 9], [9, 10], [10, 11], # right leg
+ [2, 12], [12, 13], [13, 14], # left leg
+ [2, 1], [1, 15], [15, 17], [1, 16], [16, 18], # face (nose, eyes, ears)
+ [14, 19], # left foot
+ [11, 20] # right foot
+]
+
+eps = 0.01
+
+class Keypoint(NamedTuple):
+ x: float
+ y: float
+ score: float = 1.0
+ id: int = -1
+
+
+# for each limb, calculate src & dst bone's length
+# and calculate their ratios
+def get_length(skeleton, limb):
+
+ k1_index, k2_index = limb
+
+ H, W = skeleton['height'], skeleton['width']
+ keypoints = skeleton['keypoints_body']
+ keypoint1 = keypoints[k1_index - 1]
+ keypoint2 = keypoints[k2_index - 1]
+
+ if keypoint1 is None or keypoint2 is None:
+ return None, None, None
+
+ X = np.array([keypoint1[0], keypoint2[0]]) * float(W)
+ Y = np.array([keypoint1[1], keypoint2[1]]) * float(H)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+
+ return X, Y, length
+
+
+
+def get_handpose_meta(keypoints, delta, src_H, src_W):
+
+ new_keypoints = []
+
+ for idx, keypoint in enumerate(keypoints):
+ if keypoint is None:
+ new_keypoints.append(None)
+ continue
+ if keypoint.score == 0:
+ new_keypoints.append(None)
+ continue
+
+ x, y = keypoint.x, keypoint.y
+ x = int(x * src_W + delta[0])
+ y = int(y * src_H + delta[1])
+
+ new_keypoints.append(
+ Keypoint(
+ x=x,
+ y=y,
+ score=keypoint.score,
+ ))
+
+ return new_keypoints
+
+
+def deal_hand_keypoints(hand_res, r_ratio, l_ratio, hand_score_th = 0.5):
+
+ left_hand = []
+ right_hand = []
+
+ left_delta_x = hand_res['left'][0][0] * (l_ratio - 1)
+ left_delta_y = hand_res['left'][0][1] * (l_ratio - 1)
+
+ right_delta_x = hand_res['right'][0][0] * (r_ratio - 1)
+ right_delta_y = hand_res['right'][0][1] * (r_ratio - 1)
+
+ length = len(hand_res['left'])
+
+ for i in range(length):
+ # left hand
+ if hand_res['left'][i][2] < hand_score_th:
+ left_hand.append(
+ Keypoint(
+ x=-1,
+ y=-1,
+ score=0,
+ )
+ )
+ else:
+ left_hand.append(
+ Keypoint(
+ x=hand_res['left'][i][0] * l_ratio - left_delta_x,
+ y=hand_res['left'][i][1] * l_ratio - left_delta_y,
+ score = hand_res['left'][i][2]
+ )
+ )
+
+ # right hand
+ if hand_res['right'][i][2] < hand_score_th:
+ right_hand.append(
+ Keypoint(
+ x=-1,
+ y=-1,
+ score=0,
+ )
+ )
+ else:
+ right_hand.append(
+ Keypoint(
+ x=hand_res['right'][i][0] * r_ratio - right_delta_x,
+ y=hand_res['right'][i][1] * r_ratio - right_delta_y,
+ score = hand_res['right'][i][2]
+ )
+ )
+
+ return right_hand, left_hand
+
+
+def get_scaled_pose(canvas, src_canvas, keypoints, keypoints_hand, bone_ratio_list, delta_ground_x, delta_ground_y,
+ rescaled_src_ground_x, body_flag, id, scale_min, threshold = 0.4):
+
+ H, W = canvas
+ src_H, src_W = src_canvas
+
+ new_length_list = [ ]
+ angle_list = [ ]
+
+ # keypoints from 0-1 to H/W range
+ for idx in range(len(keypoints)):
+ if keypoints[idx] is None or len(keypoints[idx]) == 0:
+ continue
+
+ keypoints[idx] = [keypoints[idx][0] * src_W, keypoints[idx][1] * src_H, keypoints[idx][2]]
+
+ # first traverse, get new_length_list and angle_list
+ for idx, (k1_index, k2_index) in enumerate(limbSeq):
+ keypoint1 = keypoints[k1_index - 1]
+ keypoint2 = keypoints[k2_index - 1]
+
+ if keypoint1 is None or keypoint2 is None or len(keypoint1) == 0 or len(keypoint2) == 0:
+ new_length_list.append(None)
+ angle_list.append(None)
+ continue
+
+ Y = np.array([keypoint1[0], keypoint2[0]]) #* float(W)
+ X = np.array([keypoint1[1], keypoint2[1]]) #* float(H)
+
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+
+ new_length = length * bone_ratio_list[idx]
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+
+ new_length_list.append(new_length)
+ angle_list.append(angle)
+
+ # Keep foot length within 0.5x calf length
+ foot_lower_leg_ratio = 0.5
+ if new_length_list[8] != None and new_length_list[18] != None:
+ if new_length_list[18] > new_length_list[8] * foot_lower_leg_ratio:
+ new_length_list[18] = new_length_list[8] * foot_lower_leg_ratio
+
+ if new_length_list[11] != None and new_length_list[17] != None:
+ if new_length_list[17] > new_length_list[11] * foot_lower_leg_ratio:
+ new_length_list[17] = new_length_list[11] * foot_lower_leg_ratio
+
+ # second traverse, calculate new keypoints
+ rescale_keypoints = keypoints.copy()
+
+ for idx, (k1_index, k2_index) in enumerate(limbSeq):
+ # update dst_keypoints
+ start_keypoint = rescale_keypoints[k1_index - 1]
+ new_length = new_length_list[idx]
+ angle = angle_list[idx]
+
+ if rescale_keypoints[k1_index - 1] is None or rescale_keypoints[k2_index - 1] is None or \
+ len(rescale_keypoints[k1_index - 1]) == 0 or len(rescale_keypoints[k2_index - 1]) == 0:
+ continue
+
+ # calculate end_keypoint
+ delta_x = new_length * math.cos(math.radians(angle))
+ delta_y = new_length * math.sin(math.radians(angle))
+
+ end_keypoint_x = start_keypoint[0] - delta_x
+ end_keypoint_y = start_keypoint[1] - delta_y
+
+ # update keypoints
+ rescale_keypoints[k2_index - 1] = [end_keypoint_x, end_keypoint_y, rescale_keypoints[k2_index - 1][2]]
+
+ if id == 0:
+ if body_flag == 'full_body' and rescale_keypoints[8] != None and rescale_keypoints[11] != None:
+ delta_ground_x_offset_first_frame = (rescale_keypoints[8][0] + rescale_keypoints[11][0]) / 2 - rescaled_src_ground_x
+ delta_ground_x += delta_ground_x_offset_first_frame
+ elif body_flag == 'half_body' and rescale_keypoints[1] != None:
+ delta_ground_x_offset_first_frame = rescale_keypoints[1][0] - rescaled_src_ground_x
+ delta_ground_x += delta_ground_x_offset_first_frame
+
+ # offset all keypoints
+ for idx in range(len(rescale_keypoints)):
+ if rescale_keypoints[idx] is None or len(rescale_keypoints[idx]) == 0 :
+ continue
+ rescale_keypoints[idx][0] -= delta_ground_x
+ rescale_keypoints[idx][1] -= delta_ground_y
+
+ # rescale keypoints to original size
+ rescale_keypoints[idx][0] /= scale_min
+ rescale_keypoints[idx][1] /= scale_min
+
+ # Scale hand proportions based on body skeletal ratios
+ r_ratio = max(bone_ratio_list[0], bone_ratio_list[1]) / scale_min
+ l_ratio = max(bone_ratio_list[0], bone_ratio_list[1]) / scale_min
+ left_hand, right_hand = deal_hand_keypoints(keypoints_hand, r_ratio, l_ratio, hand_score_th = threshold)
+
+ left_hand_new = left_hand.copy()
+ right_hand_new = right_hand.copy()
+
+ if rescale_keypoints[4] == None and rescale_keypoints[7] == None:
+ pass
+
+ elif rescale_keypoints[4] == None and rescale_keypoints[7] != None:
+ right_hand_delta = np.array(rescale_keypoints[7][:2]) - np.array(keypoints[7][:2])
+ right_hand_new = get_handpose_meta(right_hand, right_hand_delta, src_H, src_W)
+
+ elif rescale_keypoints[4] != None and rescale_keypoints[7] == None:
+ left_hand_delta = np.array(rescale_keypoints[4][:2]) - np.array(keypoints[4][:2])
+ left_hand_new = get_handpose_meta(left_hand, left_hand_delta, src_H, src_W)
+
+ else:
+ # get left_hand and right_hand offset
+ left_hand_delta = np.array(rescale_keypoints[4][:2]) - np.array(keypoints[4][:2])
+ right_hand_delta = np.array(rescale_keypoints[7][:2]) - np.array(keypoints[7][:2])
+
+ if keypoints[4][0] != None and left_hand[0].x != -1:
+ left_hand_root_offset = np.array( ( keypoints[4][0] - left_hand[0].x * src_W, keypoints[4][1] - left_hand[0].y * src_H))
+ left_hand_delta += left_hand_root_offset
+
+ if keypoints[7][0] != None and right_hand[0].x != -1:
+ right_hand_root_offset = np.array( ( keypoints[7][0] - right_hand[0].x * src_W, keypoints[7][1] - right_hand[0].y * src_H))
+ right_hand_delta += right_hand_root_offset
+
+ dis_left_hand = ((keypoints[4][0] - left_hand[0].x * src_W) ** 2 + (keypoints[4][1] - left_hand[0].y * src_H) ** 2) ** 0.5
+ dis_right_hand = ((keypoints[7][0] - left_hand[0].x * src_W) ** 2 + (keypoints[7][1] - left_hand[0].y * src_H) ** 2) ** 0.5
+
+ if dis_left_hand > dis_right_hand:
+ right_hand_new = get_handpose_meta(left_hand, right_hand_delta, src_H, src_W)
+ left_hand_new = get_handpose_meta(right_hand, left_hand_delta, src_H, src_W)
+ else:
+ left_hand_new = get_handpose_meta(left_hand, left_hand_delta, src_H, src_W)
+ right_hand_new = get_handpose_meta(right_hand, right_hand_delta, src_H, src_W)
+
+ # get normalized keypoints_body
+ norm_body_keypoints = [ ]
+ for body_keypoint in rescale_keypoints:
+ if body_keypoint != None:
+ norm_body_keypoints.append([body_keypoint[0] / W , body_keypoint[1] / H, body_keypoint[2]])
+ else:
+ norm_body_keypoints.append(None)
+
+ frame_info = {
+ 'height': H,
+ 'width': W,
+ 'keypoints_body': norm_body_keypoints,
+ 'keypoints_left_hand' : left_hand_new,
+ 'keypoints_right_hand' : right_hand_new,
+ }
+
+ return frame_info
+
+
+def rescale_skeleton(H, W, keypoints, bone_ratio_list):
+
+ rescale_keypoints = keypoints.copy()
+
+ new_length_list = [ ]
+ angle_list = [ ]
+
+ # keypoints from 0-1 to H/W range
+ for idx in range(len(rescale_keypoints)):
+ if rescale_keypoints[idx] is None or len(rescale_keypoints[idx]) == 0:
+ continue
+
+ rescale_keypoints[idx] = [rescale_keypoints[idx][0] * W, rescale_keypoints[idx][1] * H]
+
+ # first traverse, get new_length_list and angle_list
+ for idx, (k1_index, k2_index) in enumerate(limbSeq):
+ keypoint1 = rescale_keypoints[k1_index - 1]
+ keypoint2 = rescale_keypoints[k2_index - 1]
+
+ if keypoint1 is None or keypoint2 is None or len(keypoint1) == 0 or len(keypoint2) == 0:
+ new_length_list.append(None)
+ angle_list.append(None)
+ continue
+
+ Y = np.array([keypoint1[0], keypoint2[0]]) #* float(W)
+ X = np.array([keypoint1[1], keypoint2[1]]) #* float(H)
+
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+
+
+ new_length = length * bone_ratio_list[idx]
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+
+ new_length_list.append(new_length)
+ angle_list.append(angle)
+
+ # # second traverse, calculate new keypoints
+ for idx, (k1_index, k2_index) in enumerate(limbSeq):
+ # update dst_keypoints
+ start_keypoint = rescale_keypoints[k1_index - 1]
+ new_length = new_length_list[idx]
+ angle = angle_list[idx]
+
+ if rescale_keypoints[k1_index - 1] is None or rescale_keypoints[k2_index - 1] is None or \
+ len(rescale_keypoints[k1_index - 1]) == 0 or len(rescale_keypoints[k2_index - 1]) == 0:
+ continue
+
+ # calculate end_keypoint
+ delta_x = new_length * math.cos(math.radians(angle))
+ delta_y = new_length * math.sin(math.radians(angle))
+
+ end_keypoint_x = start_keypoint[0] - delta_x
+ end_keypoint_y = start_keypoint[1] - delta_y
+
+ # update keypoints
+ rescale_keypoints[k2_index - 1] = [end_keypoint_x, end_keypoint_y]
+
+ return rescale_keypoints
+
+
+def fix_lack_keypoints_use_sym(skeleton):
+
+ keypoints = skeleton['keypoints_body']
+ H, W = skeleton['height'], skeleton['width']
+
+ limb_points_list = [
+ [3, 4, 5],
+ [6, 7, 8],
+ [12, 13, 14, 19],
+ [9, 10, 11, 20],
+ ]
+
+ for limb_points in limb_points_list:
+ miss_flag = False
+ for point in limb_points:
+ if keypoints[point - 1] is None:
+ miss_flag = True
+ continue
+ if miss_flag:
+ skeleton['keypoints_body'][point - 1] = None
+
+ repair_limb_seq_left = [
+ [3, 4], [4, 5], # left arm
+ [12, 13], [13, 14], # left leg
+ [14, 19] # left foot
+ ]
+
+ repair_limb_seq_right = [
+ [6, 7], [7, 8], # right arm
+ [9, 10], [10, 11], # right leg
+ [11, 20] # right foot
+ ]
+
+ repair_limb_seq = [repair_limb_seq_left, repair_limb_seq_right]
+
+ for idx_part, part in enumerate(repair_limb_seq):
+ for idx, limb in enumerate(part):
+
+ k1_index, k2_index = limb
+ keypoint1 = keypoints[k1_index - 1]
+ keypoint2 = keypoints[k2_index - 1]
+
+ if keypoint1 != None and keypoint2 is None:
+ # reference to symmetric limb
+ sym_limb = repair_limb_seq[1-idx_part][idx]
+ k1_index_sym, k2_index_sym = sym_limb
+ keypoint1_sym = keypoints[k1_index_sym - 1]
+ keypoint2_sym = keypoints[k2_index_sym - 1]
+ ref_length = 0
+
+ if keypoint1_sym != None and keypoint2_sym != None:
+ X = np.array([keypoint1_sym[0], keypoint2_sym[0]]) * float(W)
+ Y = np.array([keypoint1_sym[1], keypoint2_sym[1]]) * float(H)
+ ref_length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ else:
+ ref_length_left, ref_length_right = 0, 0
+ if keypoints[1] != None and keypoints[8] != None:
+ X = np.array([keypoints[1][0], keypoints[8][0]]) * float(W)
+ Y = np.array([keypoints[1][1], keypoints[8][1]]) * float(H)
+ ref_length_left = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ if idx <= 1: # arms
+ ref_length_left /= 2
+
+ if keypoints[1] != None and keypoints[11] != None:
+ X = np.array([keypoints[1][0], keypoints[11][0]]) * float(W)
+ Y = np.array([keypoints[1][1], keypoints[11][1]]) * float(H)
+ ref_length_right = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ if idx <= 1: # arms
+ ref_length_right /= 2
+ elif idx == 4: # foot
+ ref_length_right /= 5
+
+ ref_length = max(ref_length_left, ref_length_right)
+
+ if ref_length != 0:
+ skeleton['keypoints_body'][k2_index - 1] = [0, 0] #init
+ skeleton['keypoints_body'][k2_index - 1][0] = skeleton['keypoints_body'][k1_index - 1][0]
+ skeleton['keypoints_body'][k2_index - 1][1] = skeleton['keypoints_body'][k1_index - 1][1] + ref_length / H
+ return skeleton
+
+
+def rescale_shorten_skeleton(ratio_list, src_length_list, dst_length_list):
+
+ modify_bone_list = [
+ [0, 1],
+ [2, 4],
+ [3, 5],
+ [6, 9],
+ [7, 10],
+ [8, 11],
+ [17, 18]
+ ]
+
+ for modify_bone in modify_bone_list:
+ new_ratio = max(ratio_list[modify_bone[0]], ratio_list[modify_bone[1]])
+ ratio_list[modify_bone[0]] = new_ratio
+ ratio_list[modify_bone[1]] = new_ratio
+
+ if ratio_list[13]!= None and ratio_list[15]!= None:
+ ratio_eye_avg = (ratio_list[13] + ratio_list[15]) / 2
+ ratio_list[13] = ratio_eye_avg
+ ratio_list[15] = ratio_eye_avg
+
+ if ratio_list[14]!= None and ratio_list[16]!= None:
+ ratio_eye_avg = (ratio_list[14] + ratio_list[16]) / 2
+ ratio_list[14] = ratio_eye_avg
+ ratio_list[16] = ratio_eye_avg
+
+ return ratio_list, src_length_list, dst_length_list
+
+
+
+def check_full_body(keypoints, threshold = 0.4):
+
+ body_flag = 'half_body'
+
+ # 1. If ankle points exist, confidence is greater than the threshold, and points do not exceed the frame, return full_body
+ if keypoints[10] != None and keypoints[13] != None and keypoints[8] != None and keypoints[11] != None:
+ if (keypoints[10][1] <= 1 and keypoints[13][1] <= 1) and (keypoints[10][2] >= threshold and keypoints[13][2] >= threshold) and \
+ (keypoints[8][1] <= 1 and keypoints[11][1] <= 1) and (keypoints[8][2] >= threshold and keypoints[11][2] >= threshold):
+ body_flag = 'full_body'
+ return body_flag
+
+ # 2. If hip points exist, return three_quarter_body
+ if (keypoints[8] != None and keypoints[11] != None):
+ if (keypoints[8][1] <= 1 and keypoints[11][1] <= 1) and (keypoints[8][2] >= threshold and keypoints[11][2] >= threshold):
+ body_flag = 'three_quarter_body'
+ return body_flag
+
+ return body_flag
+
+
+def check_full_body_both(flag1, flag2):
+ body_flag_dict = {
+ 'full_body': 2,
+ 'three_quarter_body' : 1,
+ 'half_body': 0
+ }
+
+ body_flag_dict_reverse = {
+ 2: 'full_body',
+ 1: 'three_quarter_body',
+ 0: 'half_body'
+ }
+
+ flag1_num = body_flag_dict[flag1]
+ flag2_num = body_flag_dict[flag2]
+ flag_both_num = min(flag1_num, flag2_num)
+ return body_flag_dict_reverse[flag_both_num]
+
+
+def write_to_poses(data_to_json, none_idx, dst_shape, bone_ratio_list, delta_ground_x, delta_ground_y, rescaled_src_ground_x, body_flag, scale_min):
+ outputs = []
+ length = len(data_to_json)
+ for id in tqdm(range(length)):
+
+ src_height, src_width = data_to_json[id]['height'], data_to_json[id]['width']
+ width, height = dst_shape
+ keypoints = data_to_json[id]['keypoints_body']
+ for idx in range(len(keypoints)):
+ if idx in none_idx:
+ keypoints[idx] = None
+ new_keypoints = keypoints.copy()
+
+ # get hand keypoints
+ keypoints_hand = {'left' : data_to_json[id]['keypoints_left_hand'], 'right' : data_to_json[id]['keypoints_right_hand']}
+ # Normalize hand coordinates to 0-1 range
+ for hand_idx in range(len(data_to_json[id]['keypoints_left_hand'])):
+ data_to_json[id]['keypoints_left_hand'][hand_idx][0] = data_to_json[id]['keypoints_left_hand'][hand_idx][0] / src_width
+ data_to_json[id]['keypoints_left_hand'][hand_idx][1] = data_to_json[id]['keypoints_left_hand'][hand_idx][1] / src_height
+
+ for hand_idx in range(len(data_to_json[id]['keypoints_right_hand'])):
+ data_to_json[id]['keypoints_right_hand'][hand_idx][0] = data_to_json[id]['keypoints_right_hand'][hand_idx][0] / src_width
+ data_to_json[id]['keypoints_right_hand'][hand_idx][1] = data_to_json[id]['keypoints_right_hand'][hand_idx][1] / src_height
+
+
+ frame_info = get_scaled_pose((height, width), (src_height, src_width), new_keypoints, keypoints_hand, bone_ratio_list, delta_ground_x, delta_ground_y, rescaled_src_ground_x, body_flag, id, scale_min)
+ outputs.append(frame_info)
+
+ return outputs
+
+
+def calculate_scale_ratio(skeleton, skeleton_edit, scale_ratio_flag):
+ if scale_ratio_flag:
+
+ headw = max(skeleton['keypoints_body'][0][0], skeleton['keypoints_body'][14][0], skeleton['keypoints_body'][15][0], skeleton['keypoints_body'][16][0], skeleton['keypoints_body'][17][0]) - \
+ min(skeleton['keypoints_body'][0][0], skeleton['keypoints_body'][14][0], skeleton['keypoints_body'][15][0], skeleton['keypoints_body'][16][0], skeleton['keypoints_body'][17][0])
+ headw_edit = max(skeleton_edit['keypoints_body'][0][0], skeleton_edit['keypoints_body'][14][0], skeleton_edit['keypoints_body'][15][0], skeleton_edit['keypoints_body'][16][0], skeleton_edit['keypoints_body'][17][0]) - \
+ min(skeleton_edit['keypoints_body'][0][0], skeleton_edit['keypoints_body'][14][0], skeleton_edit['keypoints_body'][15][0], skeleton_edit['keypoints_body'][16][0], skeleton_edit['keypoints_body'][17][0])
+ headw_ratio = headw / headw_edit
+
+ _, _, shoulder = get_length(skeleton, [6,3])
+ _, _, shoulder_edit = get_length(skeleton_edit, [6,3])
+ shoulder_ratio = shoulder / shoulder_edit
+
+ return max(headw_ratio, shoulder_ratio)
+
+ else:
+ return 1
+
+
+
+def retarget_pose(src_skeleton, dst_skeleton, all_src_skeleton, src_skeleton_edit, dst_skeleton_edit, threshold=0.4):
+
+ if src_skeleton_edit is not None and dst_skeleton_edit is not None:
+ use_edit_for_base = True
+ else:
+ use_edit_for_base = False
+
+ src_skeleton_ori = copy.deepcopy(src_skeleton)
+
+ dst_skeleton_ori_h, dst_skeleton_ori_w = dst_skeleton['height'], dst_skeleton['width']
+ if src_skeleton['keypoints_body'][0] != None and src_skeleton['keypoints_body'][10] != None and src_skeleton['keypoints_body'][13] != None and \
+ dst_skeleton['keypoints_body'][0] != None and dst_skeleton['keypoints_body'][10] != None and dst_skeleton['keypoints_body'][13] != None and \
+ src_skeleton['keypoints_body'][0][2] > 0.5 and src_skeleton['keypoints_body'][10][2] > 0.5 and src_skeleton['keypoints_body'][13][2] > 0.5 and \
+ dst_skeleton['keypoints_body'][0][2] > 0.5 and dst_skeleton['keypoints_body'][10][2] > 0.5 and dst_skeleton['keypoints_body'][13][2] > 0.5:
+
+ src_height = src_skeleton['height'] * abs(
+ (src_skeleton['keypoints_body'][10][1] + src_skeleton['keypoints_body'][13][1]) / 2 -
+ src_skeleton['keypoints_body'][0][1])
+ dst_height = dst_skeleton['height'] * abs(
+ (dst_skeleton['keypoints_body'][10][1] + dst_skeleton['keypoints_body'][13][1]) / 2 -
+ dst_skeleton['keypoints_body'][0][1])
+ scale_min = 1.0 * src_height / dst_height
+ elif src_skeleton['keypoints_body'][0] != None and src_skeleton['keypoints_body'][8] != None and src_skeleton['keypoints_body'][11] != None and \
+ dst_skeleton['keypoints_body'][0] != None and dst_skeleton['keypoints_body'][8] != None and dst_skeleton['keypoints_body'][11] != None and \
+ src_skeleton['keypoints_body'][0][2] > 0.5 and src_skeleton['keypoints_body'][8][2] > 0.5 and src_skeleton['keypoints_body'][11][2] > 0.5 and \
+ dst_skeleton['keypoints_body'][0][2] > 0.5 and dst_skeleton['keypoints_body'][8][2] > 0.5 and dst_skeleton['keypoints_body'][11][2] > 0.5:
+
+ src_height = src_skeleton['height'] * abs(
+ (src_skeleton['keypoints_body'][8][1] + src_skeleton['keypoints_body'][11][1]) / 2 -
+ src_skeleton['keypoints_body'][0][1])
+ dst_height = dst_skeleton['height'] * abs(
+ (dst_skeleton['keypoints_body'][8][1] + dst_skeleton['keypoints_body'][11][1]) / 2 -
+ dst_skeleton['keypoints_body'][0][1])
+ scale_min = 1.0 * src_height / dst_height
+ else:
+ scale_min = np.sqrt(src_skeleton['height'] * src_skeleton['width']) / np.sqrt(dst_skeleton['height'] * dst_skeleton['width'])
+
+ if use_edit_for_base:
+ scale_ratio_flag = False
+ if src_skeleton_edit['keypoints_body'][0] != None and src_skeleton_edit['keypoints_body'][10] != None and src_skeleton_edit['keypoints_body'][13] != None and \
+ dst_skeleton_edit['keypoints_body'][0] != None and dst_skeleton_edit['keypoints_body'][10] != None and dst_skeleton_edit['keypoints_body'][13] != None and \
+ src_skeleton_edit['keypoints_body'][0][2] > 0.5 and src_skeleton_edit['keypoints_body'][10][2] > 0.5 and src_skeleton_edit['keypoints_body'][13][2] > 0.5 and \
+ dst_skeleton_edit['keypoints_body'][0][2] > 0.5 and dst_skeleton_edit['keypoints_body'][10][2] > 0.5 and dst_skeleton_edit['keypoints_body'][13][2] > 0.5:
+
+ src_height_edit = src_skeleton_edit['height'] * abs(
+ (src_skeleton_edit['keypoints_body'][10][1] + src_skeleton_edit['keypoints_body'][13][1]) / 2 -
+ src_skeleton_edit['keypoints_body'][0][1])
+ dst_height_edit = dst_skeleton_edit['height'] * abs(
+ (dst_skeleton_edit['keypoints_body'][10][1] + dst_skeleton_edit['keypoints_body'][13][1]) / 2 -
+ dst_skeleton_edit['keypoints_body'][0][1])
+ scale_min_edit = 1.0 * src_height_edit / dst_height_edit
+ elif src_skeleton_edit['keypoints_body'][0] != None and src_skeleton_edit['keypoints_body'][8] != None and src_skeleton_edit['keypoints_body'][11] != None and \
+ dst_skeleton_edit['keypoints_body'][0] != None and dst_skeleton_edit['keypoints_body'][8] != None and dst_skeleton_edit['keypoints_body'][11] != None and \
+ src_skeleton_edit['keypoints_body'][0][2] > 0.5 and src_skeleton_edit['keypoints_body'][8][2] > 0.5 and src_skeleton_edit['keypoints_body'][11][2] > 0.5 and \
+ dst_skeleton_edit['keypoints_body'][0][2] > 0.5 and dst_skeleton_edit['keypoints_body'][8][2] > 0.5 and dst_skeleton_edit['keypoints_body'][11][2] > 0.5:
+
+ src_height_edit = src_skeleton_edit['height'] * abs(
+ (src_skeleton_edit['keypoints_body'][8][1] + src_skeleton_edit['keypoints_body'][11][1]) / 2 -
+ src_skeleton_edit['keypoints_body'][0][1])
+ dst_height_edit = dst_skeleton_edit['height'] * abs(
+ (dst_skeleton_edit['keypoints_body'][8][1] + dst_skeleton_edit['keypoints_body'][11][1]) / 2 -
+ dst_skeleton_edit['keypoints_body'][0][1])
+ scale_min_edit = 1.0 * src_height_edit / dst_height_edit
+ else:
+ scale_min_edit = np.sqrt(src_skeleton_edit['height'] * src_skeleton_edit['width']) / np.sqrt(dst_skeleton_edit['height'] * dst_skeleton_edit['width'])
+ scale_ratio_flag = True
+
+ # Flux may change the scale, compensate for it here
+ ratio_src = calculate_scale_ratio(src_skeleton, src_skeleton_edit, scale_ratio_flag)
+ ratio_dst = calculate_scale_ratio(dst_skeleton, dst_skeleton_edit, scale_ratio_flag)
+
+ dst_skeleton_edit['height'] = int(dst_skeleton_edit['height'] * scale_min_edit)
+ dst_skeleton_edit['width'] = int(dst_skeleton_edit['width'] * scale_min_edit)
+ for idx in range(len(dst_skeleton_edit['keypoints_left_hand'])):
+ dst_skeleton_edit['keypoints_left_hand'][idx][0] *= scale_min_edit
+ dst_skeleton_edit['keypoints_left_hand'][idx][1] *= scale_min_edit
+ for idx in range(len(dst_skeleton_edit['keypoints_right_hand'])):
+ dst_skeleton_edit['keypoints_right_hand'][idx][0] *= scale_min_edit
+ dst_skeleton_edit['keypoints_right_hand'][idx][1] *= scale_min_edit
+
+
+ dst_skeleton['height'] = int(dst_skeleton['height'] * scale_min)
+ dst_skeleton['width'] = int(dst_skeleton['width'] * scale_min)
+ for idx in range(len(dst_skeleton['keypoints_left_hand'])):
+ dst_skeleton['keypoints_left_hand'][idx][0] *= scale_min
+ dst_skeleton['keypoints_left_hand'][idx][1] *= scale_min
+ for idx in range(len(dst_skeleton['keypoints_right_hand'])):
+ dst_skeleton['keypoints_right_hand'][idx][0] *= scale_min
+ dst_skeleton['keypoints_right_hand'][idx][1] *= scale_min
+
+
+ dst_body_flag = check_full_body(dst_skeleton['keypoints_body'], threshold)
+ src_body_flag = check_full_body(src_skeleton_ori['keypoints_body'], threshold)
+ body_flag = check_full_body_both(dst_body_flag, src_body_flag)
+ #print('body_flag: ', body_flag)
+
+ if use_edit_for_base:
+ src_skeleton_edit = fix_lack_keypoints_use_sym(src_skeleton_edit)
+ dst_skeleton_edit = fix_lack_keypoints_use_sym(dst_skeleton_edit)
+ else:
+ src_skeleton = fix_lack_keypoints_use_sym(src_skeleton)
+ dst_skeleton = fix_lack_keypoints_use_sym(dst_skeleton)
+
+ none_idx = []
+ for idx in range(len(dst_skeleton['keypoints_body'])):
+ if dst_skeleton['keypoints_body'][idx] == None or src_skeleton['keypoints_body'][idx] == None:
+ src_skeleton['keypoints_body'][idx] = None
+ dst_skeleton['keypoints_body'][idx] = None
+ none_idx.append(idx)
+
+ # get bone ratio list
+ ratio_list, src_length_list, dst_length_list = [], [], []
+ for idx, limb in enumerate(limbSeq):
+ if use_edit_for_base:
+ src_X, src_Y, src_length = get_length(src_skeleton_edit, limb)
+ dst_X, dst_Y, dst_length = get_length(dst_skeleton_edit, limb)
+
+ if src_X is None or src_Y is None or dst_X is None or dst_Y is None:
+ ratio = -1
+ else:
+ ratio = 1.0 * dst_length * ratio_dst / src_length / ratio_src
+
+ else:
+ src_X, src_Y, src_length = get_length(src_skeleton, limb)
+ dst_X, dst_Y, dst_length = get_length(dst_skeleton, limb)
+
+ if src_X is None or src_Y is None or dst_X is None or dst_Y is None:
+ ratio = -1
+ else:
+ ratio = 1.0 * dst_length / src_length
+
+ ratio_list.append(ratio)
+ src_length_list.append(src_length)
+ dst_length_list.append(dst_length)
+
+ for idx, ratio in enumerate(ratio_list):
+ if ratio == -1:
+ if ratio_list[0] != -1 and ratio_list[1] != -1:
+ ratio_list[idx] = (ratio_list[0] + ratio_list[1]) / 2
+
+ # Consider adding constraints when Flux fails to correct head pose, causing neck issues.
+ # if ratio_list[12] > (ratio_list[0]+ratio_list[1])/2*1.25:
+ # ratio_list[12] = (ratio_list[0]+ratio_list[1])/2*1.25
+
+ ratio_list, src_length_list, dst_length_list = rescale_shorten_skeleton(ratio_list, src_length_list, dst_length_list)
+
+ rescaled_src_skeleton_ori = rescale_skeleton(src_skeleton_ori['height'], src_skeleton_ori['width'],
+ src_skeleton_ori['keypoints_body'], ratio_list)
+
+ # get global translation offset_x and offset_y
+ if body_flag == 'full_body':
+ #print('use foot mark.')
+ dst_ground_y = max(dst_skeleton['keypoints_body'][10][1], dst_skeleton['keypoints_body'][13][1]) * dst_skeleton[
+ 'height']
+ # The midpoint between toe and ankle
+ if dst_skeleton['keypoints_body'][18] != None and dst_skeleton['keypoints_body'][19] != None:
+ right_foot_mid = (dst_skeleton['keypoints_body'][10][1] + dst_skeleton['keypoints_body'][19][1]) / 2
+ left_foot_mid = (dst_skeleton['keypoints_body'][13][1] + dst_skeleton['keypoints_body'][18][1]) / 2
+ dst_ground_y = max(left_foot_mid, right_foot_mid) * dst_skeleton['height']
+
+ rescaled_src_ground_y = max(rescaled_src_skeleton_ori[10][1], rescaled_src_skeleton_ori[13][1])
+ delta_ground_y = rescaled_src_ground_y - dst_ground_y
+
+ dst_ground_x = (dst_skeleton['keypoints_body'][8][0] + dst_skeleton['keypoints_body'][11][0]) * dst_skeleton[
+ 'width'] / 2
+ rescaled_src_ground_x = (rescaled_src_skeleton_ori[8][0] + rescaled_src_skeleton_ori[11][0]) / 2
+ delta_ground_x = rescaled_src_ground_x - dst_ground_x
+ delta_x, delta_y = delta_ground_x, delta_ground_y
+
+ else:
+ #print('use neck mark.')
+ # use neck keypoint as mark
+ src_neck_y = rescaled_src_skeleton_ori[1][1]
+ dst_neck_y = dst_skeleton['keypoints_body'][1][1]
+ delta_neck_y = src_neck_y - dst_neck_y * dst_skeleton['height']
+
+ src_neck_x = rescaled_src_skeleton_ori[1][0]
+ dst_neck_x = dst_skeleton['keypoints_body'][1][0]
+ delta_neck_x = src_neck_x - dst_neck_x * dst_skeleton['width']
+ delta_x, delta_y = delta_neck_x, delta_neck_y
+ rescaled_src_ground_x = src_neck_x
+
+
+ dst_shape = (dst_skeleton_ori_w, dst_skeleton_ori_h)
+ output = write_to_poses(all_src_skeleton, none_idx, dst_shape, ratio_list, delta_x, delta_y,
+ rescaled_src_ground_x, body_flag, scale_min)
+ return output
+
+
+def get_retarget_pose(tpl_pose_meta0, refer_pose_meta, tpl_pose_metas, tql_edit_pose_meta0, refer_edit_pose_meta):
+
+ for key, value in tpl_pose_meta0.items():
+ if type(value) is np.ndarray:
+ if key in ['keypoints_left_hand', 'keypoints_right_hand']:
+ value = value * np.array([[tpl_pose_meta0["width"], tpl_pose_meta0["height"], 1.0]])
+ if not isinstance(value, list):
+ value = value.tolist()
+ tpl_pose_meta0[key] = value
+
+ for key, value in refer_pose_meta.items():
+ if type(value) is np.ndarray:
+ if key in ['keypoints_left_hand', 'keypoints_right_hand']:
+ value = value * np.array([[refer_pose_meta["width"], refer_pose_meta["height"], 1.0]])
+ if not isinstance(value, list):
+ value = value.tolist()
+ refer_pose_meta[key] = value
+
+ tpl_pose_metas_new = []
+ for meta in tpl_pose_metas:
+ for key, value in meta.items():
+ if type(value) is np.ndarray:
+ if key in ['keypoints_left_hand', 'keypoints_right_hand']:
+ value = value * np.array([[meta["width"], meta["height"], 1.0]])
+ if not isinstance(value, list):
+ value = value.tolist()
+ meta[key] = value
+ tpl_pose_metas_new.append(meta)
+
+ if tql_edit_pose_meta0 is not None:
+ for key, value in tql_edit_pose_meta0.items():
+ if type(value) is np.ndarray:
+ if key in ['keypoints_left_hand', 'keypoints_right_hand']:
+ value = value * np.array([[tql_edit_pose_meta0["width"], tql_edit_pose_meta0["height"], 1.0]])
+ if not isinstance(value, list):
+ value = value.tolist()
+ tql_edit_pose_meta0[key] = value
+
+ if refer_edit_pose_meta is not None:
+ for key, value in refer_edit_pose_meta.items():
+ if type(value) is np.ndarray:
+ if key in ['keypoints_left_hand', 'keypoints_right_hand']:
+ value = value * np.array([[refer_edit_pose_meta["width"], refer_edit_pose_meta["height"], 1.0]])
+ if not isinstance(value, list):
+ value = value.tolist()
+ refer_edit_pose_meta[key] = value
+
+ retarget_tpl_pose_metas = retarget_pose(tpl_pose_meta0, refer_pose_meta, tpl_pose_metas_new, tql_edit_pose_meta0, refer_edit_pose_meta)
+
+ pose_metas = []
+ for meta in retarget_tpl_pose_metas:
+ pose_meta = AAPoseMeta()
+ width, height = meta["width"], meta["height"]
+ pose_meta.width = width
+ pose_meta.height = height
+ pose_meta.kps_body = np.array(meta["keypoints_body"])[:, :2] * (width, height)
+ pose_meta.kps_body_p = np.array(meta["keypoints_body"])[:, 2]
+
+ kps_lhand = []
+ kps_lhand_p = []
+ for each_kps_lhand in meta["keypoints_left_hand"]:
+ if each_kps_lhand is not None:
+ kps_lhand.append([each_kps_lhand.x, each_kps_lhand.y])
+ kps_lhand_p.append(each_kps_lhand.score)
+ else:
+ kps_lhand.append([None, None])
+ kps_lhand_p.append(0.0)
+
+ pose_meta.kps_lhand = np.array(kps_lhand)
+ pose_meta.kps_lhand_p = np.array(kps_lhand_p)
+
+ kps_rhand = []
+ kps_rhand_p = []
+ for each_kps_rhand in meta["keypoints_right_hand"]:
+ if each_kps_rhand is not None:
+ kps_rhand.append([each_kps_rhand.x, each_kps_rhand.y])
+ kps_rhand_p.append(each_kps_rhand.score)
+ else:
+ kps_rhand.append([None, None])
+ kps_rhand_p.append(0.0)
+
+ pose_meta.kps_rhand = np.array(kps_rhand)
+ pose_meta.kps_rhand_p = np.array(kps_rhand_p)
+
+ pose_metas.append(pose_meta)
+
+ return pose_metas
+
diff --git a/wan/modules/animate/preprocess/sam_utils.py b/wan/modules/animate/preprocess/sam_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..282b3eee806d764ad5ca0d0dcf85e8c3209d294c
--- /dev/null
+++ b/wan/modules/animate/preprocess/sam_utils.py
@@ -0,0 +1,155 @@
+# Copyright (c) 2025. Your modifications here.
+# This file wraps and extends sam2.utils.misc for custom modifications.
+
+from sam2.utils import misc as sam2_misc
+from sam2.utils.misc import *
+from PIL import Image
+import numpy as np
+import torch
+from tqdm import tqdm
+import os
+
+import logging
+
+import torch
+from hydra import compose
+from hydra.utils import instantiate
+from omegaconf import OmegaConf
+
+from sam2.utils.misc import AsyncVideoFrameLoader, _load_img_as_tensor
+from sam2.build_sam import _load_checkpoint
+
+
+def _load_img_v2_as_tensor(img, image_size):
+ img_pil = Image.fromarray(img.astype(np.uint8))
+ img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size)))
+ if img_np.dtype == np.uint8: # np.uint8 is expected for JPEG images
+ img_np = img_np / 255.0
+ else:
+ raise RuntimeError(f"Unknown image dtype: {img_np.dtype}")
+ img = torch.from_numpy(img_np).permute(2, 0, 1)
+ video_width, video_height = img_pil.size # the original video size
+ return img, video_height, video_width
+
+def load_video_frames(
+ video_path,
+ image_size,
+ offload_video_to_cpu,
+ img_mean=(0.485, 0.456, 0.406),
+ img_std=(0.229, 0.224, 0.225),
+ async_loading_frames=False,
+ frame_names=None,
+):
+ """
+ Load the video frames from a directory of JPEG files ("
.jpg" format).
+
+ The frames are resized to image_size x image_size and are loaded to GPU if
+ `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`.
+
+ You can load a frame asynchronously by setting `async_loading_frames` to `True`.
+ """
+ if isinstance(video_path, str) and os.path.isdir(video_path):
+ jpg_folder = video_path
+ else:
+ raise NotImplementedError("Only JPEG frames are supported at this moment")
+ if frame_names is None:
+ frame_names = [
+ p
+ for p in os.listdir(jpg_folder)
+ if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG", ".png"]
+ ]
+ frame_names.sort(key=lambda p: int(os.path.splitext(p)[0]))
+
+ num_frames = len(frame_names)
+ if num_frames == 0:
+ raise RuntimeError(f"no images found in {jpg_folder}")
+ img_paths = [os.path.join(jpg_folder, frame_name) for frame_name in frame_names]
+ img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None]
+ img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None]
+
+ if async_loading_frames:
+ lazy_images = AsyncVideoFrameLoader(
+ img_paths, image_size, offload_video_to_cpu, img_mean, img_std
+ )
+ return lazy_images, lazy_images.video_height, lazy_images.video_width
+
+ images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float32)
+ for n, img_path in enumerate(tqdm(img_paths, desc="frame loading (JPEG)")):
+ images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size)
+ if not offload_video_to_cpu:
+ images = images.cuda()
+ img_mean = img_mean.cuda()
+ img_std = img_std.cuda()
+ # normalize by mean and std
+ images -= img_mean
+ images /= img_std
+ return images, video_height, video_width
+
+
+def load_video_frames_v2(
+ frames,
+ image_size,
+ offload_video_to_cpu,
+ img_mean=(0.485, 0.456, 0.406),
+ img_std=(0.229, 0.224, 0.225),
+ async_loading_frames=False,
+ frame_names=None,
+):
+ """
+ Load the video frames from a directory of JPEG files (".jpg" format).
+
+ The frames are resized to image_size x image_size and are loaded to GPU if
+ `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`.
+
+ You can load a frame asynchronously by setting `async_loading_frames` to `True`.
+ """
+ num_frames = len(frames)
+ img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None]
+ img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None]
+
+ images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float32)
+ for n, frame in enumerate(tqdm(frames, desc="video frame")):
+ images[n], video_height, video_width = _load_img_v2_as_tensor(frame, image_size)
+ if not offload_video_to_cpu:
+ images = images.cuda()
+ img_mean = img_mean.cuda()
+ img_std = img_std.cuda()
+ # normalize by mean and std
+ images -= img_mean
+ images /= img_std
+ return images, video_height, video_width
+
+def build_sam2_video_predictor(
+ config_file,
+ ckpt_path=None,
+ device="cuda",
+ mode="eval",
+ hydra_overrides_extra=[],
+ apply_postprocessing=True,
+):
+ hydra_overrides = [
+ "++model._target_=video_predictor.SAM2VideoPredictor",
+ ]
+ if apply_postprocessing:
+ hydra_overrides_extra = hydra_overrides_extra.copy()
+ hydra_overrides_extra += [
+ # dynamically fall back to multi-mask if the single mask is not stable
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
+ # the sigmoid mask logits on interacted frames with clicks in the memory encoder so that the encoded masks are exactly as what users see from clicking
+ "++model.binarize_mask_from_pts_for_mem_enc=true",
+ # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution)
+ "++model.fill_hole_area=8",
+ ]
+
+ hydra_overrides.extend(hydra_overrides_extra)
+ # Read config and init model
+ cfg = compose(config_name=config_file, overrides=hydra_overrides)
+ OmegaConf.resolve(cfg)
+ model = instantiate(cfg.model, _recursive_=True)
+ _load_checkpoint(model, ckpt_path)
+ model = model.to(device)
+ if mode == "eval":
+ model.eval()
+ return model
\ No newline at end of file
diff --git a/wan/modules/animate/preprocess/utils.py b/wan/modules/animate/preprocess/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3932d8e234a09a5fa0351804c7449aafb87cd3c
--- /dev/null
+++ b/wan/modules/animate/preprocess/utils.py
@@ -0,0 +1,226 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import os
+import cv2
+import math
+import random
+import numpy as np
+
+def get_mask_boxes(mask):
+ """
+
+ Args:
+ mask: [h, w]
+ Returns:
+
+ """
+ y_coords, x_coords = np.nonzero(mask)
+ x_min = x_coords.min()
+ x_max = x_coords.max()
+ y_min = y_coords.min()
+ y_max = y_coords.max()
+ bbox = np.array([x_min, y_min, x_max, y_max]).astype(np.int32)
+ return bbox
+
+
+def get_aug_mask(body_mask, w_len=10, h_len=20):
+ body_bbox = get_mask_boxes(body_mask)
+
+ bbox_wh = body_bbox[2:4] - body_bbox[0:2]
+ w_slice = np.int32(bbox_wh[0] / w_len)
+ h_slice = np.int32(bbox_wh[1] / h_len)
+
+ for each_w in range(body_bbox[0], body_bbox[2], w_slice):
+ w_start = min(each_w, body_bbox[2])
+ w_end = min((each_w + w_slice), body_bbox[2])
+ # print(w_start, w_end)
+ for each_h in range(body_bbox[1], body_bbox[3], h_slice):
+ h_start = min(each_h, body_bbox[3])
+ h_end = min((each_h + h_slice), body_bbox[3])
+ if body_mask[h_start:h_end, w_start:w_end].sum() > 0:
+ body_mask[h_start:h_end, w_start:w_end] = 1
+
+ return body_mask
+
+def get_mask_body_img(img_copy, hand_mask, k=7, iterations=1):
+ kernel = np.ones((k, k), np.uint8)
+ dilation = cv2.dilate(hand_mask, kernel, iterations=iterations)
+ mask_hand_img = img_copy * (1 - dilation[:, :, None])
+
+ return mask_hand_img, dilation
+
+
+def get_face_bboxes(kp2ds, scale, image_shape, ratio_aug):
+ h, w = image_shape
+ kp2ds_face = kp2ds.copy()[23:91, :2]
+
+ min_x, min_y = np.min(kp2ds_face, axis=0)
+ max_x, max_y = np.max(kp2ds_face, axis=0)
+
+
+ initial_width = max_x - min_x
+ initial_height = max_y - min_y
+
+ initial_area = initial_width * initial_height
+
+ expanded_area = initial_area * scale
+
+ new_width = np.sqrt(expanded_area * (initial_width / initial_height))
+ new_height = np.sqrt(expanded_area * (initial_height / initial_width))
+
+ delta_width = (new_width - initial_width) / 2
+ delta_height = (new_height - initial_height) / 4
+
+ if ratio_aug:
+ if random.random() > 0.5:
+ delta_width += random.uniform(0, initial_width // 10)
+ else:
+ delta_height += random.uniform(0, initial_height // 10)
+
+ expanded_min_x = max(min_x - delta_width, 0)
+ expanded_max_x = min(max_x + delta_width, w)
+ expanded_min_y = max(min_y - 3 * delta_height, 0)
+ expanded_max_y = min(max_y + delta_height, h)
+
+ return [int(expanded_min_x), int(expanded_max_x), int(expanded_min_y), int(expanded_max_y)]
+
+
+def calculate_new_size(orig_w, orig_h, target_area, divisor=64):
+
+ target_ratio = orig_w / orig_h
+
+ def check_valid(w, h):
+
+ if w <= 0 or h <= 0:
+ return False
+ return (w * h <= target_area and
+ w % divisor == 0 and
+ h % divisor == 0)
+
+ def get_ratio_diff(w, h):
+
+ return abs(w / h - target_ratio)
+
+ def round_to_64(value, round_up=False, divisor=64):
+
+ if round_up:
+ return divisor * ((value + (divisor - 1)) // divisor)
+ return divisor * (value // divisor)
+
+ possible_sizes = []
+
+ max_area_h = int(np.sqrt(target_area / target_ratio))
+ max_area_w = int(max_area_h * target_ratio)
+
+ max_h = round_to_64(max_area_h, round_up=True, divisor=divisor)
+ max_w = round_to_64(max_area_w, round_up=True, divisor=divisor)
+
+ for h in range(divisor, max_h + divisor, divisor):
+ ideal_w = h * target_ratio
+
+ w_down = round_to_64(ideal_w)
+ w_up = round_to_64(ideal_w, round_up=True)
+
+ for w in [w_down, w_up]:
+ if check_valid(w, h, divisor):
+ possible_sizes.append((w, h, get_ratio_diff(w, h)))
+
+ if not possible_sizes:
+ raise ValueError("Can not find suitable size")
+
+ possible_sizes.sort(key=lambda x: (-x[0] * x[1], x[2]))
+
+ best_w, best_h, _ = possible_sizes[0]
+ return int(best_w), int(best_h)
+
+
+def resize_by_area(image, target_area, keep_aspect_ratio=True, divisor=64, padding_color=(0, 0, 0)):
+ h, w = image.shape[:2]
+ try:
+ new_w, new_h = calculate_new_size(w, h, target_area, divisor)
+ except:
+ aspect_ratio = w / h
+
+ if keep_aspect_ratio:
+ new_h = math.sqrt(target_area / aspect_ratio)
+ new_w = target_area / new_h
+ else:
+ new_w = new_h = math.sqrt(target_area)
+
+ new_w, new_h = int((new_w // divisor) * divisor), int((new_h // divisor) * divisor)
+
+ interpolation = cv2.INTER_AREA if (new_w * new_h < w * h) else cv2.INTER_LINEAR
+
+ resized_image = padding_resize(image, height=new_h, width=new_w, padding_color=padding_color,
+ interpolation=interpolation)
+ return resized_image
+
+
+def padding_resize(img_ori, height=512, width=512, padding_color=(0, 0, 0), interpolation=cv2.INTER_LINEAR):
+ ori_height = img_ori.shape[0]
+ ori_width = img_ori.shape[1]
+ channel = img_ori.shape[2]
+
+ img_pad = np.zeros((height, width, channel))
+ if channel == 1:
+ img_pad[:, :, 0] = padding_color[0]
+ else:
+ img_pad[:, :, 0] = padding_color[0]
+ img_pad[:, :, 1] = padding_color[1]
+ img_pad[:, :, 2] = padding_color[2]
+
+ if (ori_height / ori_width) > (height / width):
+ new_width = int(height / ori_height * ori_width)
+ img = cv2.resize(img_ori, (new_width, height), interpolation=interpolation)
+ padding = int((width - new_width) / 2)
+ if len(img.shape) == 2:
+ img = img[:, :, np.newaxis]
+ img_pad[:, padding: padding + new_width, :] = img
+ else:
+ new_height = int(width / ori_width * ori_height)
+ img = cv2.resize(img_ori, (width, new_height), interpolation=interpolation)
+ padding = int((height - new_height) / 2)
+ if len(img.shape) == 2:
+ img = img[:, :, np.newaxis]
+ img_pad[padding: padding + new_height, :, :] = img
+
+ img_pad = np.uint8(img_pad)
+
+ return img_pad
+
+
+def get_frame_indices(frame_num, video_fps, clip_length, train_fps):
+
+ start_frame = 0
+ times = np.arange(0, clip_length) / train_fps
+ frame_indices = start_frame + np.round(times * video_fps).astype(int)
+ frame_indices = np.clip(frame_indices, 0, frame_num - 1)
+
+ return frame_indices.tolist()
+
+
+def get_face_bboxes(kp2ds, scale, image_shape):
+ h, w = image_shape
+ kp2ds_face = kp2ds.copy()[1:] * (w, h)
+
+ min_x, min_y = np.min(kp2ds_face, axis=0)
+ max_x, max_y = np.max(kp2ds_face, axis=0)
+
+ initial_width = max_x - min_x
+ initial_height = max_y - min_y
+
+ initial_area = initial_width * initial_height
+
+ expanded_area = initial_area * scale
+
+ new_width = np.sqrt(expanded_area * (initial_width / initial_height))
+ new_height = np.sqrt(expanded_area * (initial_height / initial_width))
+
+ delta_width = (new_width - initial_width) / 2
+ delta_height = (new_height - initial_height) / 4
+
+ expanded_min_x = max(min_x - delta_width, 0)
+ expanded_max_x = min(max_x + delta_width, w)
+ expanded_min_y = max(min_y - 3 * delta_height, 0)
+ expanded_max_y = min(max_y + delta_height, h)
+
+ return [int(expanded_min_x), int(expanded_max_x), int(expanded_min_y), int(expanded_max_y)]
\ No newline at end of file
diff --git a/wan/modules/animate/preprocess/video_predictor.py b/wan/modules/animate/preprocess/video_predictor.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfe7f1e4c1f3ef6b4bf3adb25a8da7dad76fbd37
--- /dev/null
+++ b/wan/modules/animate/preprocess/video_predictor.py
@@ -0,0 +1,157 @@
+# Copyright (c) 2025. Your modifications here.
+# A wrapper for sam2 functions
+from collections import OrderedDict
+import torch
+from tqdm import tqdm
+
+from sam2.modeling.sam2_base import NO_OBJ_SCORE, SAM2Base
+from sam2.sam2_video_predictor import SAM2VideoPredictor as _SAM2VideoPredictor
+from sam2.utils.misc import concat_points, fill_holes_in_mask_scores
+
+from sam_utils import load_video_frames_v2, load_video_frames
+
+
+class SAM2VideoPredictor(_SAM2VideoPredictor):
+ def __init__(self, *args, **kwargs):
+
+ super().__init__(*args, **kwargs)
+
+ @torch.inference_mode()
+ def init_state(
+ self,
+ video_path,
+ offload_video_to_cpu=False,
+ offload_state_to_cpu=False,
+ async_loading_frames=False,
+ frame_names=None
+ ):
+ """Initialize a inference state."""
+ images, video_height, video_width = load_video_frames(
+ video_path=video_path,
+ image_size=self.image_size,
+ offload_video_to_cpu=offload_video_to_cpu,
+ async_loading_frames=async_loading_frames,
+ frame_names=frame_names
+ )
+ inference_state = {}
+ inference_state["images"] = images
+ inference_state["num_frames"] = len(images)
+ # whether to offload the video frames to CPU memory
+ # turning on this option saves the GPU memory with only a very small overhead
+ inference_state["offload_video_to_cpu"] = offload_video_to_cpu
+ # whether to offload the inference state to CPU memory
+ # turning on this option saves the GPU memory at the cost of a lower tracking fps
+ # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
+ # and from 24 to 21 when tracking two objects)
+ inference_state["offload_state_to_cpu"] = offload_state_to_cpu
+ # the original video height and width, used for resizing final output scores
+ inference_state["video_height"] = video_height
+ inference_state["video_width"] = video_width
+ inference_state["device"] = torch.device("cuda")
+ if offload_state_to_cpu:
+ inference_state["storage_device"] = torch.device("cpu")
+ else:
+ inference_state["storage_device"] = torch.device("cuda")
+ # inputs on each frame
+ inference_state["point_inputs_per_obj"] = {}
+ inference_state["mask_inputs_per_obj"] = {}
+ # visual features on a small number of recently visited frames for quick interactions
+ inference_state["cached_features"] = {}
+ # values that don't change across frames (so we only need to hold one copy of them)
+ inference_state["constants"] = {}
+ # mapping between client-side object id and model-side object index
+ inference_state["obj_id_to_idx"] = OrderedDict()
+ inference_state["obj_idx_to_id"] = OrderedDict()
+ inference_state["obj_ids"] = []
+ # A storage to hold the model's tracking results and states on each frame
+ inference_state["output_dict"] = {
+ "cond_frame_outputs": {}, # dict containing {frame_idx: }
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: }
+ }
+ # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
+ inference_state["output_dict_per_obj"] = {}
+ # A temporary storage to hold new outputs when user interact with a frame
+ # to add clicks or mask (it's merged into "output_dict" before propagation starts)
+ inference_state["temp_output_dict_per_obj"] = {}
+ # Frames that already holds consolidated outputs from click or mask inputs
+ # (we directly use their consolidated outputs during tracking)
+ inference_state["consolidated_frame_inds"] = {
+ "cond_frame_outputs": set(), # set containing frame indices
+ "non_cond_frame_outputs": set(), # set containing frame indices
+ }
+ # metadata for each tracking frame (e.g. which direction it's tracked)
+ inference_state["tracking_has_started"] = False
+ inference_state["frames_already_tracked"] = {}
+ # Warm up the visual backbone and cache the image feature on frame 0
+ self._get_image_feature(inference_state, frame_idx=0, batch_size=1)
+ return inference_state
+
+ @torch.inference_mode()
+ def init_state_v2(
+ self,
+ frames,
+ offload_video_to_cpu=False,
+ offload_state_to_cpu=False,
+ async_loading_frames=False,
+ frame_names=None
+ ):
+ """Initialize a inference state."""
+ images, video_height, video_width = load_video_frames_v2(
+ frames=frames,
+ image_size=self.image_size,
+ offload_video_to_cpu=offload_video_to_cpu,
+ async_loading_frames=async_loading_frames,
+ frame_names=frame_names
+ )
+ inference_state = {}
+ inference_state["images"] = images
+ inference_state["num_frames"] = len(images)
+ # whether to offload the video frames to CPU memory
+ # turning on this option saves the GPU memory with only a very small overhead
+ inference_state["offload_video_to_cpu"] = offload_video_to_cpu
+ # whether to offload the inference state to CPU memory
+ # turning on this option saves the GPU memory at the cost of a lower tracking fps
+ # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
+ # and from 24 to 21 when tracking two objects)
+ inference_state["offload_state_to_cpu"] = offload_state_to_cpu
+ # the original video height and width, used for resizing final output scores
+ inference_state["video_height"] = video_height
+ inference_state["video_width"] = video_width
+ inference_state["device"] = torch.device("cuda")
+ if offload_state_to_cpu:
+ inference_state["storage_device"] = torch.device("cpu")
+ else:
+ inference_state["storage_device"] = torch.device("cuda")
+ # inputs on each frame
+ inference_state["point_inputs_per_obj"] = {}
+ inference_state["mask_inputs_per_obj"] = {}
+ # visual features on a small number of recently visited frames for quick interactions
+ inference_state["cached_features"] = {}
+ # values that don't change across frames (so we only need to hold one copy of them)
+ inference_state["constants"] = {}
+ # mapping between client-side object id and model-side object index
+ inference_state["obj_id_to_idx"] = OrderedDict()
+ inference_state["obj_idx_to_id"] = OrderedDict()
+ inference_state["obj_ids"] = []
+ # A storage to hold the model's tracking results and states on each frame
+ inference_state["output_dict"] = {
+ "cond_frame_outputs": {}, # dict containing {frame_idx: }
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: }
+ }
+ # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
+ inference_state["output_dict_per_obj"] = {}
+ # A temporary storage to hold new outputs when user interact with a frame
+ # to add clicks or mask (it's merged into "output_dict" before propagation starts)
+ inference_state["temp_output_dict_per_obj"] = {}
+ # Frames that already holds consolidated outputs from click or mask inputs
+ # (we directly use their consolidated outputs during tracking)
+ inference_state["consolidated_frame_inds"] = {
+ "cond_frame_outputs": set(), # set containing frame indices
+ "non_cond_frame_outputs": set(), # set containing frame indices
+ }
+ # metadata for each tracking frame (e.g. which direction it's tracked)
+ inference_state["tracking_has_started"] = False
+ inference_state["frames_already_tracked"] = {}
+ # Warm up the visual backbone and cache the image feature on frame 0
+ self._get_image_feature(inference_state, frame_idx=0, batch_size=1)
+ return inference_state
\ No newline at end of file
diff --git a/wan/modules/animate/xlm_roberta.py b/wan/modules/animate/xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..6763f7bde14da16f0716b988e2b0284e695fe914
--- /dev/null
+++ b/wan/modules/animate/xlm_roberta.py
@@ -0,0 +1,170 @@
+# Modified from transformers.models.xlm_roberta.modeling_xlm_roberta
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+__all__ = ['XLMRoberta', 'xlm_roberta_large']
+
+
+class SelfAttention(nn.Module):
+
+ def __init__(self, dim, num_heads, dropout=0.1, eps=1e-5):
+ assert dim % num_heads == 0
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.eps = eps
+
+ # layers
+ self.q = nn.Linear(dim, dim)
+ self.k = nn.Linear(dim, dim)
+ self.v = nn.Linear(dim, dim)
+ self.o = nn.Linear(dim, dim)
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(self, x, mask):
+ """
+ x: [B, L, C].
+ """
+ b, s, c, n, d = *x.size(), self.num_heads, self.head_dim
+
+ # compute query, key, value
+ q = self.q(x).reshape(b, s, n, d).permute(0, 2, 1, 3)
+ k = self.k(x).reshape(b, s, n, d).permute(0, 2, 1, 3)
+ v = self.v(x).reshape(b, s, n, d).permute(0, 2, 1, 3)
+
+ # compute attention
+ p = self.dropout.p if self.training else 0.0
+ x = F.scaled_dot_product_attention(q, k, v, mask, p)
+ x = x.permute(0, 2, 1, 3).reshape(b, s, c)
+
+ # output
+ x = self.o(x)
+ x = self.dropout(x)
+ return x
+
+
+class AttentionBlock(nn.Module):
+
+ def __init__(self, dim, num_heads, post_norm, dropout=0.1, eps=1e-5):
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.post_norm = post_norm
+ self.eps = eps
+
+ # layers
+ self.attn = SelfAttention(dim, num_heads, dropout, eps)
+ self.norm1 = nn.LayerNorm(dim, eps=eps)
+ self.ffn = nn.Sequential(
+ nn.Linear(dim, dim * 4), nn.GELU(), nn.Linear(dim * 4, dim),
+ nn.Dropout(dropout))
+ self.norm2 = nn.LayerNorm(dim, eps=eps)
+
+ def forward(self, x, mask):
+ if self.post_norm:
+ x = self.norm1(x + self.attn(x, mask))
+ x = self.norm2(x + self.ffn(x))
+ else:
+ x = x + self.attn(self.norm1(x), mask)
+ x = x + self.ffn(self.norm2(x))
+ return x
+
+
+class XLMRoberta(nn.Module):
+ """
+ XLMRobertaModel with no pooler and no LM head.
+ """
+
+ def __init__(self,
+ vocab_size=250002,
+ max_seq_len=514,
+ type_size=1,
+ pad_id=1,
+ dim=1024,
+ num_heads=16,
+ num_layers=24,
+ post_norm=True,
+ dropout=0.1,
+ eps=1e-5):
+ super().__init__()
+ self.vocab_size = vocab_size
+ self.max_seq_len = max_seq_len
+ self.type_size = type_size
+ self.pad_id = pad_id
+ self.dim = dim
+ self.num_heads = num_heads
+ self.num_layers = num_layers
+ self.post_norm = post_norm
+ self.eps = eps
+
+ # embeddings
+ self.token_embedding = nn.Embedding(vocab_size, dim, padding_idx=pad_id)
+ self.type_embedding = nn.Embedding(type_size, dim)
+ self.pos_embedding = nn.Embedding(max_seq_len, dim, padding_idx=pad_id)
+ self.dropout = nn.Dropout(dropout)
+
+ # blocks
+ self.blocks = nn.ModuleList([
+ AttentionBlock(dim, num_heads, post_norm, dropout, eps)
+ for _ in range(num_layers)
+ ])
+
+ # norm layer
+ self.norm = nn.LayerNorm(dim, eps=eps)
+
+ def forward(self, ids):
+ """
+ ids: [B, L] of torch.LongTensor.
+ """
+ b, s = ids.shape
+ mask = ids.ne(self.pad_id).long()
+
+ # embeddings
+ x = self.token_embedding(ids) + \
+ self.type_embedding(torch.zeros_like(ids)) + \
+ self.pos_embedding(self.pad_id + torch.cumsum(mask, dim=1) * mask)
+ if self.post_norm:
+ x = self.norm(x)
+ x = self.dropout(x)
+
+ # blocks
+ mask = torch.where(
+ mask.view(b, 1, 1, s).gt(0), 0.0,
+ torch.finfo(x.dtype).min)
+ for block in self.blocks:
+ x = block(x, mask)
+
+ # output
+ if not self.post_norm:
+ x = self.norm(x)
+ return x
+
+
+def xlm_roberta_large(pretrained=False,
+ return_tokenizer=False,
+ device='cpu',
+ **kwargs):
+ """
+ XLMRobertaLarge adapted from Huggingface.
+ """
+ # params
+ cfg = dict(
+ vocab_size=250002,
+ max_seq_len=514,
+ type_size=1,
+ pad_id=1,
+ dim=1024,
+ num_heads=16,
+ num_layers=24,
+ post_norm=True,
+ dropout=0.1,
+ eps=1e-5)
+ cfg.update(**kwargs)
+
+ # init a model on device
+ with torch.device(device):
+ model = XLMRoberta(**cfg)
+ return model
\ No newline at end of file
diff --git a/wan/modules/attention.py b/wan/modules/attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..df3876f4c4db24e64e7b31e26cf37bcc453cb5e2
--- /dev/null
+++ b/wan/modules/attention.py
@@ -0,0 +1,256 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import warnings
+import torch
+from typing import Optional, Tuple
+
+try:
+ import flash_attn_interface
+ FLASH_ATTN_3_AVAILABLE = True
+except ModuleNotFoundError:
+ FLASH_ATTN_3_AVAILABLE = False
+
+try:
+ import flash_attn
+ FLASH_ATTN_2_AVAILABLE = True
+except ModuleNotFoundError:
+ FLASH_ATTN_2_AVAILABLE = False
+
+
+__all__ = [
+ 'flash_attention',
+ 'attention',
+]
+
+
+# ---------------------------
+# Custom op + fake kernel
+# ---------------------------
+from typing import Optional, Sequence # <- add Sequence
+
+# ... imports unchanged ...
+from typing import Optional, Sequence
+
+@torch.library.custom_op("wan::flash_attention", mutates_args=())
+def _wan_flash_attention_op(
+ q: torch.Tensor,
+ k: torch.Tensor,
+ v: torch.Tensor,
+ q_lens: Optional[torch.Tensor] = None,
+ k_lens: Optional[torch.Tensor] = None,
+ dropout_p: float = 0.0,
+ softmax_scale: Optional[float] = None,
+ q_scale: Optional[float] = None,
+ causal: bool = False,
+ # IMPORTANT: schema-friendly default (None), not a tuple
+ window_size: Optional[Sequence[int]] = None,
+ deterministic: bool = False,
+ dtype: torch.dtype = torch.bfloat16,
+ version: Optional[int] = None,
+) -> torch.Tensor:
+ half_dtypes = (torch.float16, torch.bfloat16)
+ assert dtype in half_dtypes
+ assert q.size(-1) <= 256
+
+ # normalize window_size to a 2-tuple for FA2 API
+ if window_size is None:
+ ws = (-1, -1)
+ else:
+ ws = tuple(window_size)
+ if len(ws) != 2:
+ raise ValueError(f"window_size must have length 2; got {window_size!r}")
+
+ b, lq, nheads = q.shape[0], q.shape[1], q.shape[2]
+ lk = k.shape[1]
+ out_dtype = q.dtype
+
+ def half(x: torch.Tensor) -> torch.Tensor:
+ return x if x.dtype in half_dtypes else x.to(dtype)
+
+ # --- preprocess (unchanged) ---
+ if q_lens is None:
+ q_flat = half(q.flatten(0, 1))
+ q_lens = torch.tensor([lq] * b, dtype=torch.int32)
+ else:
+ q_flat = half(torch.cat([u[:v] for u, v in zip(q, q_lens)]))
+
+ if k_lens is None:
+ k_flat = half(k.flatten(0, 1))
+ v_flat = half(v.flatten(0, 1))
+ k_lens = torch.tensor([lk] * b, dtype=torch.int32)
+ else:
+ k_flat = half(torch.cat([u[:v] for u, v in zip(k, k_lens)]))
+ v_flat = half(torch.cat([u[:v] for u, v in zip(v, k_lens)]))
+
+ q_flat = q_flat.to(v_flat.dtype); k_flat = k_flat.to(v_flat.dtype)
+ if q_scale is not None:
+ q_flat = q_flat * q_scale
+
+ if version is not None and version == 3 and not FLASH_ATTN_3_AVAILABLE:
+ warnings.warn('Flash attention 3 is not available, use flash attention 2 instead.')
+
+ if FLASH_ATTN_3_AVAILABLE:
+ ret = flash_attn_interface.flash_attn_varlen_func(
+ q=q_flat,
+ k=k_flat,
+ v=v_flat,
+ cu_seqlens_q=torch.cat([q_lens.new_zeros([1]), q_lens]).cumsum(0, dtype=torch.int32).to(q_flat.device, non_blocking=True),
+ cu_seqlens_k=torch.cat([k_lens.new_zeros([1]), k_lens]).cumsum(0, dtype=torch.int32).to(k_flat.device, non_blocking=True),
+ seqused_q=None,
+ seqused_k=None,
+ max_seqlen_q=lq,
+ max_seqlen_k=lk,
+ softmax_scale=softmax_scale,
+ causal=causal,
+ deterministic=deterministic,
+ )
+ out0 = ret[0] if isinstance(ret, (tuple, list)) else ret
+ total_q = b * lq
+ if out0.dim() != 3:
+ raise RuntimeError(f"Unexpected FA3 output rank {out0.dim()} shape={tuple(out0.shape)}")
+ if out0.shape[0] == total_q:
+ out_flat = out0
+ elif out0.shape[0] == nheads and out0.shape[1] == total_q:
+ out_flat = out0.transpose(0, 1).contiguous()
+ else:
+ raise RuntimeError(f"Unexpected FA3 output shape {tuple(out0.shape)}")
+ out = out_flat.unflatten(0, (b, lq))
+
+ elif FLASH_ATTN_2_AVAILABLE:
+ out = flash_attn.flash_attn_varlen_func(
+ q=q_flat,
+ k=k_flat,
+ v=v_flat,
+ cu_seqlens_q=torch.cat([q_lens.new_zeros([1]), q_lens]).cumsum(0, dtype=torch.int32).to(q_flat.device, non_blocking=True),
+ cu_seqlens_k=torch.cat([k_lens.new_zeros([1]), k_lens]).cumsum(0, dtype=torch.int32).to(q_flat.device, non_blocking=True),
+ max_seqlen_q=lq,
+ max_seqlen_k=lk,
+ dropout_p=dropout_p,
+ softmax_scale=softmax_scale,
+ causal=causal,
+ window_size=ws, # <- pass 2-tuple
+ deterministic=deterministic,
+ ).unflatten(0, (b, lq))
+ else:
+ q_s = q.transpose(1, 2).to(dtype)
+ k_s = k.transpose(1, 2).to(dtype)
+ v_s = v.transpose(1, 2).to(dtype)
+ out = torch.nn.functional.scaled_dot_product_attention(
+ q_s, k_s, v_s, attn_mask=None, is_causal=causal, dropout_p=dropout_p
+ ).transpose(1, 2).contiguous()
+
+ return out.to(out_dtype)
+
+@_wan_flash_attention_op.register_fake
+def _wan_flash_attention_op_fake(
+ q,
+ k,
+ v,
+ q_lens=None,
+ k_lens=None,
+ dropout_p: float = 0.0,
+ softmax_scale=None,
+ q_scale=None,
+ causal: bool = False,
+ window_size: Optional[Sequence[int]] = None,
+ deterministic: bool = False,
+ dtype: torch.dtype = torch.bfloat16,
+ version: Optional[int] = None,
+):
+ # Match output shape: (B, Lq, Nq, Dh_v) and keep the SAME fake device as `q`
+ B, Lq, Nq, _ = q.shape
+ Dh_v = v.shape[-1]
+ return q.new_empty((B, Lq, Nq, Dh_v), dtype=q.dtype)
+
+
+
+# ---------------------------
+# Public API (unchanged signature)
+# ---------------------------
+def flash_attention(
+ q,
+ k,
+ v,
+ q_lens=None,
+ k_lens=None,
+ dropout_p=0.,
+ softmax_scale=None,
+ q_scale=None,
+ causal=False,
+ window_size=(-1, -1),
+ deterministic=False,
+ dtype=torch.bfloat16,
+ version=None,
+):
+ """
+ q: [B, Lq, Nq, C1].
+ k: [B, Lk, Nk, C1].
+ v: [B, Lk, Nk, C2]. Nq must be divisible by Nk.
+ q_lens: [B].
+ k_lens: [B].
+ dropout_p: float. Dropout probability.
+ softmax_scale: float. The scaling of QK^T before applying softmax.
+ causal: bool. Whether to apply causal attention mask.
+ window_size: (left right). If not (-1, -1), apply sliding window local attention.
+ deterministic: bool. If True, slightly slower and uses more memory.
+ dtype: torch.dtype. Apply when dtype of q/k/v is not float16/bfloat16.
+ """
+ # Simply delegate to the custom op so Dynamo/AOT treats it as a single node;
+ # our eager kernel inside _wan_flash_attention_op keeps the original behavior.
+ return _wan_flash_attention_op(
+ q, k, v,
+ q_lens=q_lens,
+ k_lens=k_lens,
+ dropout_p=dropout_p,
+ softmax_scale=softmax_scale,
+ q_scale=q_scale,
+ causal=causal,
+ window_size=window_size,
+ deterministic=deterministic,
+ dtype=dtype,
+ version=version,
+ )
+
+
+def attention(
+ q,
+ k,
+ v,
+ q_lens=None,
+ k_lens=None,
+ dropout_p=0.,
+ softmax_scale=None,
+ q_scale=None,
+ causal=False,
+ window_size=(-1, -1),
+ deterministic=False,
+ dtype=torch.bfloat16,
+ fa_version=None,
+):
+ if FLASH_ATTN_2_AVAILABLE or FLASH_ATTN_3_AVAILABLE:
+ return flash_attention(
+ q=q,
+ k=k,
+ v=v,
+ q_lens=q_lens,
+ k_lens=k_lens,
+ dropout_p=dropout_p,
+ softmax_scale=softmax_scale,
+ q_scale=q_scale,
+ causal=causal,
+ window_size=window_size,
+ deterministic=deterministic,
+ dtype=dtype,
+ version=fa_version,
+ )
+ else:
+ if q_lens is not None or k_lens is not None:
+ warnings.warn(
+ 'Padding mask is disabled when using scaled_dot_product_attention. It can have a significant impact on performance.'
+ )
+ q_ = q.transpose(1, 2).to(dtype)
+ k_ = k.transpose(1, 2).to(dtype)
+ v_ = v.transpose(1, 2).to(dtype)
+ out = torch.nn.functional.scaled_dot_product_attention(
+ q_, k_, v_, attn_mask=None, is_causal=causal, dropout_p=dropout_p
+ )
+ return out.transpose(1, 2).contiguous()
\ No newline at end of file
diff --git a/wan/modules/model.py b/wan/modules/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c7e4707b9f1d1fc26acf6c296d1d6af3f9bde56
--- /dev/null
+++ b/wan/modules/model.py
@@ -0,0 +1,546 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import math
+
+import torch
+import torch.nn as nn
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_utils import ModelMixin
+
+from .attention import flash_attention
+
+__all__ = ['WanModel']
+
+
+def sinusoidal_embedding_1d(dim, position):
+ # preprocess
+ assert dim % 2 == 0
+ half = dim // 2
+ position = position.type(torch.float64)
+
+ # calculation
+ sinusoid = torch.outer(
+ position, torch.pow(10000, -torch.arange(half).to(position).div(half)))
+ x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
+ return x
+
+
+@torch.amp.autocast('cuda', enabled=False)
+def rope_params(max_seq_len, dim, theta=10000):
+ assert dim % 2 == 0
+ freqs = torch.outer(
+ torch.arange(max_seq_len),
+ 1.0 / torch.pow(theta,
+ torch.arange(0, dim, 2).to(torch.float64).div(dim)))
+ freqs = torch.polar(torch.ones_like(freqs), freqs)
+ return freqs
+
+
+@torch.amp.autocast('cuda', enabled=False)
+def rope_apply(x, grid_sizes, freqs):
+ n, c = x.size(2), x.size(3) // 2
+
+ # split freqs
+ freqs = freqs.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
+
+ # loop over samples
+ output = []
+ for i, (f, h, w) in enumerate(grid_sizes.tolist()):
+ seq_len = f * h * w
+
+ # precompute multipliers
+ x_i = torch.view_as_complex(x[i, :seq_len].to(torch.float64).reshape(
+ seq_len, n, -1, 2))
+ freqs_i = torch.cat([
+ freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
+ freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
+ freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
+ ],
+ dim=-1).reshape(seq_len, 1, -1)
+
+ # apply rotary embedding
+ x_i = torch.view_as_real(x_i * freqs_i).flatten(2)
+ x_i = torch.cat([x_i, x[i, seq_len:]])
+
+ # append to collection
+ output.append(x_i)
+ return torch.stack(output).float()
+
+
+class WanRMSNorm(nn.Module):
+
+ def __init__(self, dim, eps=1e-5):
+ super().__init__()
+ self.dim = dim
+ self.eps = eps
+ self.weight = nn.Parameter(torch.ones(dim))
+
+ def forward(self, x):
+ r"""
+ Args:
+ x(Tensor): Shape [B, L, C]
+ """
+ return self._norm(x.float()).type_as(x) * self.weight
+
+ def _norm(self, x):
+ return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
+
+
+class WanLayerNorm(nn.LayerNorm):
+
+ def __init__(self, dim, eps=1e-6, elementwise_affine=False):
+ super().__init__(dim, elementwise_affine=elementwise_affine, eps=eps)
+
+ def forward(self, x):
+ r"""
+ Args:
+ x(Tensor): Shape [B, L, C]
+ """
+ return super().forward(x.float()).type_as(x)
+
+
+class WanSelfAttention(nn.Module):
+
+ def __init__(self,
+ dim,
+ num_heads,
+ window_size=(-1, -1),
+ qk_norm=True,
+ eps=1e-6):
+ assert dim % num_heads == 0
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.eps = eps
+
+ # layers
+ self.q = nn.Linear(dim, dim)
+ self.k = nn.Linear(dim, dim)
+ self.v = nn.Linear(dim, dim)
+ self.o = nn.Linear(dim, dim)
+ self.norm_q = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
+ self.norm_k = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
+
+ def forward(self, x, seq_lens, grid_sizes, freqs):
+ r"""
+ Args:
+ x(Tensor): Shape [B, L, num_heads, C / num_heads]
+ seq_lens(Tensor): Shape [B]
+ grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)
+ freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]
+ """
+ b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
+
+ # query, key, value function
+ def qkv_fn(x):
+ q = self.norm_q(self.q(x)).view(b, s, n, d)
+ k = self.norm_k(self.k(x)).view(b, s, n, d)
+ v = self.v(x).view(b, s, n, d)
+ return q, k, v
+
+ q, k, v = qkv_fn(x)
+
+ x = flash_attention(
+ q=rope_apply(q, grid_sizes, freqs),
+ k=rope_apply(k, grid_sizes, freqs),
+ v=v,
+ k_lens=seq_lens,
+ window_size=self.window_size)
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
+
+
+class WanCrossAttention(WanSelfAttention):
+
+ def forward(self, x, context, context_lens):
+ r"""
+ Args:
+ x(Tensor): Shape [B, L1, C]
+ context(Tensor): Shape [B, L2, C]
+ context_lens(Tensor): Shape [B]
+ """
+ b, n, d = x.size(0), self.num_heads, self.head_dim
+
+ # compute query, key, value
+ q = self.norm_q(self.q(x)).view(b, -1, n, d)
+ k = self.norm_k(self.k(context)).view(b, -1, n, d)
+ v = self.v(context).view(b, -1, n, d)
+
+ # compute attention
+ x = flash_attention(q, k, v, k_lens=context_lens)
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
+
+
+class WanAttentionBlock(nn.Module):
+
+ def __init__(self,
+ dim,
+ ffn_dim,
+ num_heads,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=False,
+ eps=1e-6):
+ super().__init__()
+ self.dim = dim
+ self.ffn_dim = ffn_dim
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.cross_attn_norm = cross_attn_norm
+ self.eps = eps
+
+ # layers
+ self.norm1 = WanLayerNorm(dim, eps)
+ self.self_attn = WanSelfAttention(dim, num_heads, window_size, qk_norm,
+ eps)
+ self.norm3 = WanLayerNorm(
+ dim, eps,
+ elementwise_affine=True) if cross_attn_norm else nn.Identity()
+ self.cross_attn = WanCrossAttention(dim, num_heads, (-1, -1), qk_norm,
+ eps)
+ self.norm2 = WanLayerNorm(dim, eps)
+ self.ffn = nn.Sequential(
+ nn.Linear(dim, ffn_dim), nn.GELU(approximate='tanh'),
+ nn.Linear(ffn_dim, dim))
+
+ # modulation
+ self.modulation = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ x,
+ e,
+ seq_lens,
+ grid_sizes,
+ freqs,
+ context,
+ context_lens,
+ ):
+ r"""
+ Args:
+ x(Tensor): Shape [B, L, C]
+ e(Tensor): Shape [B, L1, 6, C]
+ seq_lens(Tensor): Shape [B], length of each sequence in batch
+ grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)
+ freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]
+ """
+ assert e.dtype == torch.float32
+ with torch.amp.autocast('cuda', dtype=torch.float32):
+ e = (self.modulation.unsqueeze(0) + e).chunk(6, dim=2)
+ assert e[0].dtype == torch.float32
+
+ # self-attention
+ y = self.self_attn(
+ self.norm1(x).float() * (1 + e[1].squeeze(2)) + e[0].squeeze(2),
+ seq_lens, grid_sizes, freqs)
+ with torch.amp.autocast('cuda', dtype=torch.float32):
+ x = x + y * e[2].squeeze(2)
+
+ # cross-attention & ffn function
+ def cross_attn_ffn(x, context, context_lens, e):
+ x = x + self.cross_attn(self.norm3(x), context, context_lens)
+ y = self.ffn(
+ self.norm2(x).float() * (1 + e[4].squeeze(2)) + e[3].squeeze(2))
+ with torch.amp.autocast('cuda', dtype=torch.float32):
+ x = x + y * e[5].squeeze(2)
+ return x
+
+ x = cross_attn_ffn(x, context, context_lens, e)
+ return x
+
+
+class Head(nn.Module):
+
+ def __init__(self, dim, out_dim, patch_size, eps=1e-6):
+ super().__init__()
+ self.dim = dim
+ self.out_dim = out_dim
+ self.patch_size = patch_size
+ self.eps = eps
+
+ # layers
+ out_dim = math.prod(patch_size) * out_dim
+ self.norm = WanLayerNorm(dim, eps)
+ self.head = nn.Linear(dim, out_dim)
+
+ # modulation
+ self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
+
+ def forward(self, x, e):
+ r"""
+ Args:
+ x(Tensor): Shape [B, L1, C]
+ e(Tensor): Shape [B, L1, C]
+ """
+ assert e.dtype == torch.float32
+ with torch.amp.autocast('cuda', dtype=torch.float32):
+ e = (self.modulation.unsqueeze(0) + e.unsqueeze(2)).chunk(2, dim=2)
+ x = (
+ self.head(
+ self.norm(x) * (1 + e[1].squeeze(2)) + e[0].squeeze(2)))
+ return x
+
+
+class WanModel(ModelMixin, ConfigMixin):
+ r"""
+ Wan diffusion backbone supporting both text-to-video and image-to-video.
+ """
+
+ ignore_for_config = [
+ 'patch_size', 'cross_attn_norm', 'qk_norm', 'text_dim', 'window_size'
+ ]
+ _no_split_modules = ['WanAttentionBlock']
+
+ @register_to_config
+ def __init__(self,
+ model_type='t2v',
+ patch_size=(1, 2, 2),
+ text_len=512,
+ in_dim=16,
+ dim=2048,
+ ffn_dim=8192,
+ freq_dim=256,
+ text_dim=4096,
+ out_dim=16,
+ num_heads=16,
+ num_layers=32,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=True,
+ eps=1e-6):
+ r"""
+ Initialize the diffusion model backbone.
+
+ Args:
+ model_type (`str`, *optional*, defaults to 't2v'):
+ Model variant - 't2v' (text-to-video) or 'i2v' (image-to-video)
+ patch_size (`tuple`, *optional*, defaults to (1, 2, 2)):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch)
+ text_len (`int`, *optional*, defaults to 512):
+ Fixed length for text embeddings
+ in_dim (`int`, *optional*, defaults to 16):
+ Input video channels (C_in)
+ dim (`int`, *optional*, defaults to 2048):
+ Hidden dimension of the transformer
+ ffn_dim (`int`, *optional*, defaults to 8192):
+ Intermediate dimension in feed-forward network
+ freq_dim (`int`, *optional*, defaults to 256):
+ Dimension for sinusoidal time embeddings
+ text_dim (`int`, *optional*, defaults to 4096):
+ Input dimension for text embeddings
+ out_dim (`int`, *optional*, defaults to 16):
+ Output video channels (C_out)
+ num_heads (`int`, *optional*, defaults to 16):
+ Number of attention heads
+ num_layers (`int`, *optional*, defaults to 32):
+ Number of transformer blocks
+ window_size (`tuple`, *optional*, defaults to (-1, -1)):
+ Window size for local attention (-1 indicates global attention)
+ qk_norm (`bool`, *optional*, defaults to True):
+ Enable query/key normalization
+ cross_attn_norm (`bool`, *optional*, defaults to False):
+ Enable cross-attention normalization
+ eps (`float`, *optional*, defaults to 1e-6):
+ Epsilon value for normalization layers
+ """
+
+ super().__init__()
+
+ assert model_type in ['t2v', 'i2v', 'ti2v', 's2v']
+ self.model_type = model_type
+
+ self.patch_size = patch_size
+ self.text_len = text_len
+ self.in_dim = in_dim
+ self.dim = dim
+ self.ffn_dim = ffn_dim
+ self.freq_dim = freq_dim
+ self.text_dim = text_dim
+ self.out_dim = out_dim
+ self.num_heads = num_heads
+ self.num_layers = num_layers
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.cross_attn_norm = cross_attn_norm
+ self.eps = eps
+
+ # embeddings
+ self.patch_embedding = nn.Conv3d(
+ in_dim, dim, kernel_size=patch_size, stride=patch_size)
+ self.text_embedding = nn.Sequential(
+ nn.Linear(text_dim, dim), nn.GELU(approximate='tanh'),
+ nn.Linear(dim, dim))
+
+ self.time_embedding = nn.Sequential(
+ nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
+ self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6))
+
+ # blocks
+ self.blocks = nn.ModuleList([
+ WanAttentionBlock(dim, ffn_dim, num_heads, window_size, qk_norm,
+ cross_attn_norm, eps) for _ in range(num_layers)
+ ])
+
+ # head
+ self.head = Head(dim, out_dim, patch_size, eps)
+
+ # buffers (don't use register_buffer otherwise dtype will be changed in to())
+ assert (dim % num_heads) == 0 and (dim // num_heads) % 2 == 0
+ d = dim // num_heads
+ self.freqs = torch.cat([
+ rope_params(1024, d - 4 * (d // 6)),
+ rope_params(1024, 2 * (d // 6)),
+ rope_params(1024, 2 * (d // 6))
+ ],
+ dim=1)
+
+ # initialize weights
+ self.init_weights()
+
+ def forward(
+ self,
+ x,
+ t,
+ context,
+ seq_len,
+ y=None,
+ ):
+ r"""
+ Forward pass through the diffusion model
+
+ Args:
+ x (List[Tensor]):
+ List of input video tensors, each with shape [C_in, F, H, W]
+ t (Tensor):
+ Diffusion timesteps tensor of shape [B]
+ context (List[Tensor]):
+ List of text embeddings each with shape [L, C]
+ seq_len (`int`):
+ Maximum sequence length for positional encoding
+ y (List[Tensor], *optional*):
+ Conditional video inputs for image-to-video mode, same shape as x
+
+ Returns:
+ List[Tensor]:
+ List of denoised video tensors with original input shapes [C_out, F, H / 8, W / 8]
+ """
+ if self.model_type == 'i2v':
+ assert y is not None
+ # params
+ device = self.patch_embedding.weight.device
+ if self.freqs.device != device:
+ self.freqs = self.freqs.to(device)
+
+ if y is not None:
+ x = [torch.cat([u, v], dim=0) for u, v in zip(x, y)]
+
+ # embeddings
+ x = [self.patch_embedding(u.unsqueeze(0)) for u in x]
+ grid_sizes = torch.stack(
+ [torch.tensor(u.shape[2:], dtype=torch.long) for u in x])
+ x = [u.flatten(2).transpose(1, 2) for u in x]
+ seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long)
+ assert seq_lens.max() <= seq_len
+ x = torch.cat([
+ torch.cat([u, u.new_zeros(1, seq_len - u.size(1), u.size(2))],
+ dim=1) for u in x
+ ])
+
+ # time embeddings
+ if t.dim() == 1:
+ t = t.expand(t.size(0), seq_len)
+ with torch.amp.autocast('cuda', dtype=torch.float32):
+ bt = t.size(0)
+ t = t.flatten()
+ e = self.time_embedding(
+ sinusoidal_embedding_1d(self.freq_dim,
+ t).unflatten(0, (bt, seq_len)).float())
+ e0 = self.time_projection(e).unflatten(2, (6, self.dim))
+ assert e.dtype == torch.float32 and e0.dtype == torch.float32
+
+ # context
+ context_lens = None
+ context = self.text_embedding(
+ torch.stack([
+ torch.cat(
+ [u, u.new_zeros(self.text_len - u.size(0), u.size(1))])
+ for u in context
+ ]))
+
+ # arguments
+ kwargs = dict(
+ e=e0,
+ seq_lens=seq_lens,
+ grid_sizes=grid_sizes,
+ freqs=self.freqs,
+ context=context,
+ context_lens=context_lens)
+
+ for block in self.blocks:
+ x = block(x, **kwargs)
+
+ # head
+ x = self.head(x, e)
+
+ # unpatchify
+ x = self.unpatchify(x, grid_sizes)
+ return [u.float() for u in x]
+
+ def unpatchify(self, x, grid_sizes):
+ r"""
+ Reconstruct video tensors from patch embeddings.
+
+ Args:
+ x (List[Tensor]):
+ List of patchified features, each with shape [L, C_out * prod(patch_size)]
+ grid_sizes (Tensor):
+ Original spatial-temporal grid dimensions before patching,
+ shape [B, 3] (3 dimensions correspond to F_patches, H_patches, W_patches)
+
+ Returns:
+ List[Tensor]:
+ Reconstructed video tensors with shape [C_out, F, H / 8, W / 8]
+ """
+
+ c = self.out_dim
+ out = []
+ for u, v in zip(x, grid_sizes.tolist()):
+ u = u[:math.prod(v)].view(*v, *self.patch_size, c)
+ u = torch.einsum('fhwpqrc->cfphqwr', u)
+ u = u.reshape(c, *[i * j for i, j in zip(v, self.patch_size)])
+ out.append(u)
+ return out
+
+ def init_weights(self):
+ r"""
+ Initialize model parameters using Xavier initialization.
+ """
+
+ # basic init
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.xavier_uniform_(m.weight)
+ if m.bias is not None:
+ nn.init.zeros_(m.bias)
+
+ # init embeddings
+ nn.init.xavier_uniform_(self.patch_embedding.weight.flatten(1))
+ for m in self.text_embedding.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.normal_(m.weight, std=.02)
+ for m in self.time_embedding.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.normal_(m.weight, std=.02)
+
+ # init output layer
+ nn.init.zeros_(self.head.head.weight)
diff --git a/wan/modules/s2v/__init__.py b/wan/modules/s2v/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a723af7d428d88032edb31f215735dbb3c04bed4
--- /dev/null
+++ b/wan/modules/s2v/__init__.py
@@ -0,0 +1,5 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from .audio_encoder import AudioEncoder
+from .model_s2v import WanModel_S2V
+
+__all__ = ['WanModel_S2V', 'AudioEncoder']
diff --git a/wan/modules/s2v/audio_encoder.py b/wan/modules/s2v/audio_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..c035500c450d114735be64717ba4d6abf87a9e10
--- /dev/null
+++ b/wan/modules/s2v/audio_encoder.py
@@ -0,0 +1,189 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import math
+
+import librosa
+import numpy as np
+import torch
+import torch.nn.functional as F
+from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
+
+
+def get_sample_indices(original_fps,
+ total_frames,
+ target_fps,
+ num_sample,
+ fixed_start=None):
+ required_duration = num_sample / target_fps
+ required_origin_frames = int(np.ceil(required_duration * original_fps))
+ if required_duration > total_frames / original_fps:
+ raise ValueError("required_duration must be less than video length")
+
+ if not fixed_start is None and fixed_start >= 0:
+ start_frame = fixed_start
+ else:
+ max_start = total_frames - required_origin_frames
+ if max_start < 0:
+ raise ValueError("video length is too short")
+ start_frame = np.random.randint(0, max_start + 1)
+ start_time = start_frame / original_fps
+
+ end_time = start_time + required_duration
+ time_points = np.linspace(start_time, end_time, num_sample, endpoint=False)
+
+ frame_indices = np.round(np.array(time_points) * original_fps).astype(int)
+ frame_indices = np.clip(frame_indices, 0, total_frames - 1)
+ return frame_indices
+
+
+def linear_interpolation(features, input_fps, output_fps, output_len=None):
+ """
+ features: shape=[1, T, 512]
+ input_fps: fps for audio, f_a
+ output_fps: fps for video, f_m
+ output_len: video length
+ """
+ features = features.transpose(1, 2) # [1, 512, T]
+ seq_len = features.shape[2] / float(input_fps) # T/f_a
+ if output_len is None:
+ output_len = int(seq_len * output_fps) # f_m*T/f_a
+ output_features = F.interpolate(
+ features, size=output_len, align_corners=True,
+ mode='linear') # [1, 512, output_len]
+ return output_features.transpose(1, 2) # [1, output_len, 512]
+
+
+class AudioEncoder():
+
+ def __init__(self, device='cpu', model_id="facebook/wav2vec2-base-960h"):
+ # load pretrained model
+ self.processor = Wav2Vec2Processor.from_pretrained(model_id)
+ self.model = Wav2Vec2ForCTC.from_pretrained(model_id)
+
+ self.model = self.model.to(device)
+
+ self.video_rate = 30
+
+ def extract_audio_feat(self,
+ audio_path,
+ return_all_layers=False,
+ dtype=torch.float32):
+ audio_input, sample_rate = librosa.load(audio_path, sr=16000)
+
+ input_values = self.processor(
+ audio_input, sampling_rate=sample_rate,
+ return_tensors="pt").input_values
+
+ # INFERENCE
+
+ # retrieve logits & take argmax
+ res = self.model(
+ input_values.to(self.model.device), output_hidden_states=True)
+ if return_all_layers:
+ feat = torch.cat(res.hidden_states)
+ else:
+ feat = res.hidden_states[-1]
+ feat = linear_interpolation(
+ feat, input_fps=50, output_fps=self.video_rate)
+
+ z = feat.to(dtype) # Encoding for the motion
+ return z
+
+ def get_audio_embed_bucket(self,
+ audio_embed,
+ stride=2,
+ batch_frames=12,
+ m=2):
+ num_layers, audio_frame_num, audio_dim = audio_embed.shape
+
+ if num_layers > 1:
+ return_all_layers = True
+ else:
+ return_all_layers = False
+
+ min_batch_num = int(audio_frame_num / (batch_frames * stride)) + 1
+
+ bucket_num = min_batch_num * batch_frames
+ batch_idx = [stride * i for i in range(bucket_num)]
+ batch_audio_eb = []
+ for bi in batch_idx:
+ if bi < audio_frame_num:
+ audio_sample_stride = 2
+ chosen_idx = list(
+ range(bi - m * audio_sample_stride,
+ bi + (m + 1) * audio_sample_stride,
+ audio_sample_stride))
+ chosen_idx = [0 if c < 0 else c for c in chosen_idx]
+ chosen_idx = [
+ audio_frame_num - 1 if c >= audio_frame_num else c
+ for c in chosen_idx
+ ]
+
+ if return_all_layers:
+ frame_audio_embed = audio_embed[:, chosen_idx].flatten(
+ start_dim=-2, end_dim=-1)
+ else:
+ frame_audio_embed = audio_embed[0][chosen_idx].flatten()
+ else:
+ frame_audio_embed = \
+ torch.zeros([audio_dim * (2 * m + 1)], device=audio_embed.device) if not return_all_layers \
+ else torch.zeros([num_layers, audio_dim * (2 * m + 1)], device=audio_embed.device)
+ batch_audio_eb.append(frame_audio_embed)
+ batch_audio_eb = torch.cat([c.unsqueeze(0) for c in batch_audio_eb],
+ dim=0)
+
+ return batch_audio_eb, min_batch_num
+
+ def get_audio_embed_bucket_fps(self,
+ audio_embed,
+ fps=16,
+ batch_frames=81,
+ m=0):
+ num_layers, audio_frame_num, audio_dim = audio_embed.shape
+
+ if num_layers > 1:
+ return_all_layers = True
+ else:
+ return_all_layers = False
+
+ scale = self.video_rate / fps
+
+ min_batch_num = int(audio_frame_num / (batch_frames * scale)) + 1
+
+ bucket_num = min_batch_num * batch_frames
+ padd_audio_num = math.ceil(min_batch_num * batch_frames / fps *
+ self.video_rate) - audio_frame_num
+ batch_idx = get_sample_indices(
+ original_fps=self.video_rate,
+ total_frames=audio_frame_num + padd_audio_num,
+ target_fps=fps,
+ num_sample=bucket_num,
+ fixed_start=0)
+ batch_audio_eb = []
+ audio_sample_stride = int(self.video_rate / fps)
+ for bi in batch_idx:
+ if bi < audio_frame_num:
+
+ chosen_idx = list(
+ range(bi - m * audio_sample_stride,
+ bi + (m + 1) * audio_sample_stride,
+ audio_sample_stride))
+ chosen_idx = [0 if c < 0 else c for c in chosen_idx]
+ chosen_idx = [
+ audio_frame_num - 1 if c >= audio_frame_num else c
+ for c in chosen_idx
+ ]
+
+ if return_all_layers:
+ frame_audio_embed = audio_embed[:, chosen_idx].flatten(
+ start_dim=-2, end_dim=-1)
+ else:
+ frame_audio_embed = audio_embed[0][chosen_idx].flatten()
+ else:
+ frame_audio_embed = \
+ torch.zeros([audio_dim * (2 * m + 1)], device=audio_embed.device) if not return_all_layers \
+ else torch.zeros([num_layers, audio_dim * (2 * m + 1)], device=audio_embed.device)
+ batch_audio_eb.append(frame_audio_embed)
+ batch_audio_eb = torch.cat([c.unsqueeze(0) for c in batch_audio_eb],
+ dim=0)
+
+ return batch_audio_eb, min_batch_num
diff --git a/wan/modules/s2v/audio_utils.py b/wan/modules/s2v/audio_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ab7b2af1aa495f6cb05e14474fd935c7bbacb3f
--- /dev/null
+++ b/wan/modules/s2v/audio_utils.py
@@ -0,0 +1,105 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import math
+from typing import Tuple, Union
+
+import torch
+import torch.cuda.amp as amp
+import torch.nn as nn
+from diffusers.models.attention import AdaLayerNorm
+
+from ..model import WanAttentionBlock, WanCrossAttention
+from .auxi_blocks import MotionEncoder_tc
+
+
+class CausalAudioEncoder(nn.Module):
+
+ def __init__(self,
+ dim=5120,
+ num_layers=25,
+ out_dim=2048,
+ video_rate=8,
+ num_token=4,
+ need_global=False):
+ super().__init__()
+ self.encoder = MotionEncoder_tc(
+ in_dim=dim,
+ hidden_dim=out_dim,
+ num_heads=num_token,
+ need_global=need_global)
+ weight = torch.ones((1, num_layers, 1, 1)) * 0.01
+
+ self.weights = torch.nn.Parameter(weight)
+ self.act = torch.nn.SiLU()
+
+ def forward(self, features):
+ with amp.autocast(dtype=torch.float32):
+ # features B * num_layers * dim * video_length
+ weights = self.act(self.weights)
+ weights_sum = weights.sum(dim=1, keepdims=True)
+ weighted_feat = ((features * weights) / weights_sum).sum(
+ dim=1) # b dim f
+ weighted_feat = weighted_feat.permute(0, 2, 1) # b f dim
+ res = self.encoder(weighted_feat) # b f n dim
+
+ return res # b f n dim
+
+
+class AudioCrossAttention(WanCrossAttention):
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+
+class AudioInjector_WAN(nn.Module):
+
+ def __init__(self,
+ all_modules,
+ all_modules_names,
+ dim=2048,
+ num_heads=32,
+ inject_layer=[0, 27],
+ root_net=None,
+ enable_adain=False,
+ adain_dim=2048,
+ need_adain_ont=False):
+ super().__init__()
+ num_injector_layers = len(inject_layer)
+ self.injected_block_id = {}
+ audio_injector_id = 0
+ for mod_name, mod in zip(all_modules_names, all_modules):
+ if isinstance(mod, WanAttentionBlock):
+ for inject_id in inject_layer:
+ if f'transformer_blocks.{inject_id}' in mod_name:
+ self.injected_block_id[inject_id] = audio_injector_id
+ audio_injector_id += 1
+
+ self.injector = nn.ModuleList([
+ AudioCrossAttention(
+ dim=dim,
+ num_heads=num_heads,
+ qk_norm=True,
+ ) for _ in range(audio_injector_id)
+ ])
+ self.injector_pre_norm_feat = nn.ModuleList([
+ nn.LayerNorm(
+ dim,
+ elementwise_affine=False,
+ eps=1e-6,
+ ) for _ in range(audio_injector_id)
+ ])
+ self.injector_pre_norm_vec = nn.ModuleList([
+ nn.LayerNorm(
+ dim,
+ elementwise_affine=False,
+ eps=1e-6,
+ ) for _ in range(audio_injector_id)
+ ])
+ if enable_adain:
+ self.injector_adain_layers = nn.ModuleList([
+ AdaLayerNorm(
+ output_dim=dim * 2, embedding_dim=adain_dim, chunk_dim=1)
+ for _ in range(audio_injector_id)
+ ])
+ if need_adain_ont:
+ self.injector_adain_output_layers = nn.ModuleList(
+ [nn.Linear(dim, dim) for _ in range(audio_injector_id)])
diff --git a/wan/modules/s2v/auxi_blocks.py b/wan/modules/s2v/auxi_blocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..89b2fc601f7cc20d2b3f20e1d9c606083214266d
--- /dev/null
+++ b/wan/modules/s2v/auxi_blocks.py
@@ -0,0 +1,242 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import importlib.metadata
+import math
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models import ModelMixin
+from diffusers.utils import is_torch_version, logging
+from einops import rearrange
+
+try:
+ from flash_attn import flash_attn_func, flash_attn_qkvpacked_func
+except ImportError:
+ flash_attn_func = None
+
+MEMORY_LAYOUT = {
+ "flash": (
+ lambda x: x.view(x.shape[0] * x.shape[1], *x.shape[2:]),
+ lambda x: x,
+ ),
+ "torch": (
+ lambda x: x.transpose(1, 2),
+ lambda x: x.transpose(1, 2),
+ ),
+ "vanilla": (
+ lambda x: x.transpose(1, 2),
+ lambda x: x.transpose(1, 2),
+ ),
+}
+
+
+def attention(
+ q,
+ k,
+ v,
+ mode="flash",
+ drop_rate=0,
+ attn_mask=None,
+ causal=False,
+ max_seqlen_q=None,
+ batch_size=1,
+):
+ """
+ Perform QKV self attention.
+
+ Args:
+ q (torch.Tensor): Query tensor with shape [b, s, a, d], where a is the number of heads.
+ k (torch.Tensor): Key tensor with shape [b, s1, a, d]
+ v (torch.Tensor): Value tensor with shape [b, s1, a, d]
+ mode (str): Attention mode. Choose from 'self_flash', 'cross_flash', 'torch', and 'vanilla'.
+ drop_rate (float): Dropout rate in attention map. (default: 0)
+ attn_mask (torch.Tensor): Attention mask with shape [b, s1] (cross_attn), or [b, a, s, s1] (torch or vanilla).
+ (default: None)
+ causal (bool): Whether to use causal attention. (default: False)
+ cu_seqlens_q (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
+ used to index into q.
+ cu_seqlens_kv (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
+ used to index into kv.
+ max_seqlen_q (int): The maximum sequence length in the batch of q.
+ max_seqlen_kv (int): The maximum sequence length in the batch of k and v.
+
+ Returns:
+ torch.Tensor: Output tensor after self attention with shape [b, s, ad]
+ """
+ pre_attn_layout, post_attn_layout = MEMORY_LAYOUT[mode]
+
+ if mode == "torch":
+ if attn_mask is not None and attn_mask.dtype != torch.bool:
+ attn_mask = attn_mask.to(q.dtype)
+ x = F.scaled_dot_product_attention(
+ q, k, v, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal)
+ elif mode == "flash":
+ x = flash_attn_func(
+ q,
+ k,
+ v,
+ )
+ # x with shape [(bxs), a, d]
+ x = x.view(batch_size, max_seqlen_q, x.shape[-2],
+ x.shape[-1]) # reshape x to [b, s, a, d]
+ elif mode == "vanilla":
+ scale_factor = 1 / math.sqrt(q.size(-1))
+
+ b, a, s, _ = q.shape
+ s1 = k.size(2)
+ attn_bias = torch.zeros(b, a, s, s1, dtype=q.dtype, device=q.device)
+ if causal:
+ # Only applied to self attention
+ assert (
+ attn_mask
+ is None), "Causal mask and attn_mask cannot be used together"
+ temp_mask = torch.ones(
+ b, a, s, s, dtype=torch.bool, device=q.device).tril(diagonal=0)
+ attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
+ attn_bias.to(q.dtype)
+
+ if attn_mask is not None:
+ if attn_mask.dtype == torch.bool:
+ attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
+ else:
+ attn_bias += attn_mask
+
+ # TODO: Maybe force q and k to be float32 to avoid numerical overflow
+ attn = (q @ k.transpose(-2, -1)) * scale_factor
+ attn += attn_bias
+ attn = attn.softmax(dim=-1)
+ attn = torch.dropout(attn, p=drop_rate, train=True)
+ x = attn @ v
+ else:
+ raise NotImplementedError(f"Unsupported attention mode: {mode}")
+
+ x = post_attn_layout(x)
+ b, s, a, d = x.shape
+ out = x.reshape(b, s, -1)
+ return out
+
+
+class CausalConv1d(nn.Module):
+
+ def __init__(self,
+ chan_in,
+ chan_out,
+ kernel_size=3,
+ stride=1,
+ dilation=1,
+ pad_mode='replicate',
+ **kwargs):
+ super().__init__()
+
+ self.pad_mode = pad_mode
+ padding = (kernel_size - 1, 0) # T
+ self.time_causal_padding = padding
+
+ self.conv = nn.Conv1d(
+ chan_in,
+ chan_out,
+ kernel_size,
+ stride=stride,
+ dilation=dilation,
+ **kwargs)
+
+ def forward(self, x):
+ x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)
+ return self.conv(x)
+
+
+class MotionEncoder_tc(nn.Module):
+
+ def __init__(self,
+ in_dim: int,
+ hidden_dim: int,
+ num_heads=int,
+ need_global=True,
+ dtype=None,
+ device=None):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+
+ self.num_heads = num_heads
+ self.need_global = need_global
+ self.conv1_local = CausalConv1d(
+ in_dim, hidden_dim // 4 * num_heads, 3, stride=1)
+ if need_global:
+ self.conv1_global = CausalConv1d(
+ in_dim, hidden_dim // 4, 3, stride=1)
+ self.norm1 = nn.LayerNorm(
+ hidden_dim // 4,
+ elementwise_affine=False,
+ eps=1e-6,
+ **factory_kwargs)
+ self.act = nn.SiLU()
+ self.conv2 = CausalConv1d(hidden_dim // 4, hidden_dim // 2, 3, stride=2)
+ self.conv3 = CausalConv1d(hidden_dim // 2, hidden_dim, 3, stride=2)
+
+ if need_global:
+ self.final_linear = nn.Linear(hidden_dim, hidden_dim,
+ **factory_kwargs)
+
+ self.norm1 = nn.LayerNorm(
+ hidden_dim // 4,
+ elementwise_affine=False,
+ eps=1e-6,
+ **factory_kwargs)
+
+ self.norm2 = nn.LayerNorm(
+ hidden_dim // 2,
+ elementwise_affine=False,
+ eps=1e-6,
+ **factory_kwargs)
+
+ self.norm3 = nn.LayerNorm(
+ hidden_dim, elementwise_affine=False, eps=1e-6, **factory_kwargs)
+
+ self.padding_tokens = nn.Parameter(torch.zeros(1, 1, 1, hidden_dim))
+
+ def forward(self, x):
+ x = rearrange(x, 'b t c -> b c t')
+ x_ori = x.clone()
+ b, c, t = x.shape
+ x = self.conv1_local(x)
+ x = rearrange(x, 'b (n c) t -> (b n) t c', n=self.num_heads)
+ x = self.norm1(x)
+ x = self.act(x)
+ x = rearrange(x, 'b t c -> b c t')
+ x = self.conv2(x)
+ x = rearrange(x, 'b c t -> b t c')
+ x = self.norm2(x)
+ x = self.act(x)
+ x = rearrange(x, 'b t c -> b c t')
+ x = self.conv3(x)
+ x = rearrange(x, 'b c t -> b t c')
+ x = self.norm3(x)
+ x = self.act(x)
+ x = rearrange(x, '(b n) t c -> b t n c', b=b)
+ padding = self.padding_tokens.repeat(b, x.shape[1], 1, 1)
+ x = torch.cat([x, padding], dim=-2)
+ x_local = x.clone()
+
+ if not self.need_global:
+ return x_local
+
+ x = self.conv1_global(x_ori)
+ x = rearrange(x, 'b c t -> b t c')
+ x = self.norm1(x)
+ x = self.act(x)
+ x = rearrange(x, 'b t c -> b c t')
+ x = self.conv2(x)
+ x = rearrange(x, 'b c t -> b t c')
+ x = self.norm2(x)
+ x = self.act(x)
+ x = rearrange(x, 'b t c -> b c t')
+ x = self.conv3(x)
+ x = rearrange(x, 'b c t -> b t c')
+ x = self.norm3(x)
+ x = self.act(x)
+ x = self.final_linear(x)
+ x = rearrange(x, '(b n) t c -> b t n c', b=b)
+
+ return x, x_local
diff --git a/wan/modules/s2v/model_s2v.py b/wan/modules/s2v/model_s2v.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4ff734c870a4f8e6c950475283a80bcc9524a3a
--- /dev/null
+++ b/wan/modules/s2v/model_s2v.py
@@ -0,0 +1,906 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import math
+import types
+from copy import deepcopy
+
+import numpy as np
+import torch
+import torch.cuda.amp as amp
+import torch.nn as nn
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_utils import ModelMixin
+from einops import rearrange
+
+from ...distributed.sequence_parallel import (
+ distributed_attention,
+ gather_forward,
+ get_rank,
+ get_world_size,
+)
+from ..model import (
+ Head,
+ WanAttentionBlock,
+ WanLayerNorm,
+ WanModel,
+ WanSelfAttention,
+ flash_attention,
+ rope_params,
+ sinusoidal_embedding_1d,
+)
+from .audio_utils import AudioInjector_WAN, CausalAudioEncoder
+from .motioner import FramePackMotioner, MotionerTransformers
+from .s2v_utils import rope_precompute
+
+
+def zero_module(module):
+ """
+ Zero out the parameters of a module and return it.
+ """
+ for p in module.parameters():
+ p.detach().zero_()
+ return module
+
+
+def torch_dfs(model: nn.Module, parent_name='root'):
+ module_names, modules = [], []
+ current_name = parent_name if parent_name else 'root'
+ module_names.append(current_name)
+ modules.append(model)
+
+ for name, child in model.named_children():
+ if parent_name:
+ child_name = f'{parent_name}.{name}'
+ else:
+ child_name = name
+ child_modules, child_names = torch_dfs(child, child_name)
+ module_names += child_names
+ modules += child_modules
+ return modules, module_names
+
+
+@amp.autocast(enabled=False)
+def rope_apply(x, grid_sizes, freqs, start=None):
+ n, c = x.size(2), x.size(3) // 2
+ # loop over samples
+ output = []
+ for i, _ in enumerate(x):
+ s = x.size(1)
+ x_i = torch.view_as_complex(x[i, :s].to(torch.float64).reshape(
+ s, n, -1, 2))
+ freqs_i = freqs[i, :s]
+ # apply rotary embedding
+ x_i = torch.view_as_real(x_i * freqs_i).flatten(2)
+ x_i = torch.cat([x_i, x[i, s:]])
+ # append to collection
+ output.append(x_i)
+ return torch.stack(output).float()
+
+
+@amp.autocast(enabled=False)
+def rope_apply_usp(x, grid_sizes, freqs):
+ s, n, c = x.size(1), x.size(2), x.size(3) // 2
+ # loop over samples
+ output = []
+ for i, _ in enumerate(x):
+ s = x.size(1)
+ # precompute multipliers
+ x_i = torch.view_as_complex(x[i, :s].to(torch.float64).reshape(
+ s, n, -1, 2))
+ freqs_i = freqs[i]
+ freqs_i_rank = freqs_i
+ x_i = torch.view_as_real(x_i * freqs_i_rank).flatten(2)
+ x_i = torch.cat([x_i, x[i, s:]])
+ # append to collection
+ output.append(x_i)
+ return torch.stack(output).float()
+
+
+def sp_attn_forward_s2v(self,
+ x,
+ seq_lens,
+ grid_sizes,
+ freqs,
+ dtype=torch.bfloat16):
+ b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
+ half_dtypes = (torch.float16, torch.bfloat16)
+
+ def half(x):
+ return x if x.dtype in half_dtypes else x.to(dtype)
+
+ # query, key, value function
+ def qkv_fn(x):
+ q = self.norm_q(self.q(x)).view(b, s, n, d)
+ k = self.norm_k(self.k(x)).view(b, s, n, d)
+ v = self.v(x).view(b, s, n, d)
+ return q, k, v
+
+ q, k, v = qkv_fn(x)
+ q = rope_apply_usp(q, grid_sizes, freqs)
+ k = rope_apply_usp(k, grid_sizes, freqs)
+
+ x = distributed_attention(
+ half(q),
+ half(k),
+ half(v),
+ seq_lens,
+ window_size=self.window_size,
+ )
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
+
+
+class Head_S2V(Head):
+
+ def forward(self, x, e):
+ """
+ Args:
+ x(Tensor): Shape [B, L1, C]
+ e(Tensor): Shape [B, L1, C]
+ """
+ assert e.dtype == torch.float32
+ with amp.autocast(dtype=torch.float32):
+ e = (self.modulation + e.unsqueeze(1)).chunk(2, dim=1)
+ x = (self.head(self.norm(x) * (1 + e[1]) + e[0]))
+ return x
+
+
+class WanS2VSelfAttention(WanSelfAttention):
+
+ def forward(self, x, seq_lens, grid_sizes, freqs):
+ """
+ Args:
+ x(Tensor): Shape [B, L, num_heads, C / num_heads]
+ seq_lens(Tensor): Shape [B]
+ grid_sizes(Tensor): Shape [B, 3], the second dimension contains (F, H, W)
+ freqs(Tensor): Rope freqs, shape [1024, C / num_heads / 2]
+ """
+ b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
+
+ # query, key, value function
+ def qkv_fn(x):
+ q = self.norm_q(self.q(x)).view(b, s, n, d)
+ k = self.norm_k(self.k(x)).view(b, s, n, d)
+ v = self.v(x).view(b, s, n, d)
+ return q, k, v
+
+ q, k, v = qkv_fn(x)
+
+ x = flash_attention(
+ q=rope_apply(q, grid_sizes, freqs),
+ k=rope_apply(k, grid_sizes, freqs),
+ v=v,
+ k_lens=seq_lens,
+ window_size=self.window_size)
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
+
+
+class WanS2VAttentionBlock(WanAttentionBlock):
+
+ def __init__(self,
+ dim,
+ ffn_dim,
+ num_heads,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=False,
+ eps=1e-6):
+ super().__init__(dim, ffn_dim, num_heads, window_size, qk_norm,
+ cross_attn_norm, eps)
+ self.self_attn = WanS2VSelfAttention(dim, num_heads, window_size,
+ qk_norm, eps)
+
+ def forward(self, x, e, seq_lens, grid_sizes, freqs, context, context_lens):
+ assert e[0].dtype == torch.float32
+ seg_idx = e[1].item()
+ seg_idx = min(max(0, seg_idx), x.size(1))
+ seg_idx = [0, seg_idx, x.size(1)]
+ e = e[0]
+ modulation = self.modulation.unsqueeze(2)
+ with amp.autocast(dtype=torch.float32):
+ e = (modulation + e).chunk(6, dim=1)
+ assert e[0].dtype == torch.float32
+
+ e = [element.squeeze(1) for element in e]
+ norm_x = self.norm1(x).float()
+ parts = []
+ for i in range(2):
+ parts.append(norm_x[:, seg_idx[i]:seg_idx[i + 1]] *
+ (1 + e[1][:, i:i + 1]) + e[0][:, i:i + 1])
+ norm_x = torch.cat(parts, dim=1)
+ # self-attention
+ y = self.self_attn(norm_x, seq_lens, grid_sizes, freqs)
+ with amp.autocast(dtype=torch.float32):
+ z = []
+ for i in range(2):
+ z.append(y[:, seg_idx[i]:seg_idx[i + 1]] * e[2][:, i:i + 1])
+ y = torch.cat(z, dim=1)
+ x = x + y
+ # cross-attention & ffn function
+ def cross_attn_ffn(x, context, context_lens, e):
+ x = x + self.cross_attn(self.norm3(x), context, context_lens)
+ norm2_x = self.norm2(x).float()
+ parts = []
+ for i in range(2):
+ parts.append(norm2_x[:, seg_idx[i]:seg_idx[i + 1]] *
+ (1 + e[4][:, i:i + 1]) + e[3][:, i:i + 1])
+ norm2_x = torch.cat(parts, dim=1)
+ y = self.ffn(norm2_x)
+ with amp.autocast(dtype=torch.float32):
+ z = []
+ for i in range(2):
+ z.append(y[:, seg_idx[i]:seg_idx[i + 1]] * e[5][:, i:i + 1])
+ y = torch.cat(z, dim=1)
+ x = x + y
+ return x
+
+ x = cross_attn_ffn(x, context, context_lens, e)
+ return x
+
+
+class WanModel_S2V(ModelMixin, ConfigMixin):
+ ignore_for_config = [
+ 'args', 'kwargs', 'patch_size', 'cross_attn_norm', 'qk_norm',
+ 'text_dim', 'window_size'
+ ]
+ _no_split_modules = ['WanS2VAttentionBlock']
+
+ @register_to_config
+ def __init__(
+ self,
+ cond_dim=0,
+ audio_dim=5120,
+ num_audio_token=4,
+ enable_adain=False,
+ adain_mode="attn_norm",
+ audio_inject_layers=[0, 4, 8, 12, 16, 20, 24, 27],
+ zero_init=False,
+ zero_timestep=False,
+ enable_motioner=True,
+ add_last_motion=True,
+ enable_tsm=False,
+ trainable_token_pos_emb=False,
+ motion_token_num=1024,
+ enable_framepack=False, # Mutually exclusive with enable_motioner
+ framepack_drop_mode="drop",
+ model_type='s2v',
+ patch_size=(1, 2, 2),
+ text_len=512,
+ in_dim=16,
+ dim=2048,
+ ffn_dim=8192,
+ freq_dim=256,
+ text_dim=4096,
+ out_dim=16,
+ num_heads=16,
+ num_layers=32,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=True,
+ eps=1e-6,
+ *args,
+ **kwargs):
+ super().__init__()
+
+ assert model_type == 's2v'
+ self.model_type = model_type
+
+ self.patch_size = patch_size
+ self.text_len = text_len
+ self.in_dim = in_dim
+ self.dim = dim
+ self.ffn_dim = ffn_dim
+ self.freq_dim = freq_dim
+ self.text_dim = text_dim
+ self.out_dim = out_dim
+ self.num_heads = num_heads
+ self.num_layers = num_layers
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.cross_attn_norm = cross_attn_norm
+ self.eps = eps
+
+ # embeddings
+ self.patch_embedding = nn.Conv3d(
+ in_dim, dim, kernel_size=patch_size, stride=patch_size)
+ self.text_embedding = nn.Sequential(
+ nn.Linear(text_dim, dim), nn.GELU(approximate='tanh'),
+ nn.Linear(dim, dim))
+
+ self.time_embedding = nn.Sequential(
+ nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
+ self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(dim, dim * 6))
+
+ # blocks
+ self.blocks = nn.ModuleList([
+ WanS2VAttentionBlock(dim, ffn_dim, num_heads, window_size, qk_norm,
+ cross_attn_norm, eps)
+ for _ in range(num_layers)
+ ])
+
+ # head
+ self.head = Head_S2V(dim, out_dim, patch_size, eps)
+
+ # buffers (don't use register_buffer otherwise dtype will be changed in to())
+ assert (dim % num_heads) == 0 and (dim // num_heads) % 2 == 0
+ d = dim // num_heads
+ self.freqs = torch.cat([
+ rope_params(1024, d - 4 * (d // 6)),
+ rope_params(1024, 2 * (d // 6)),
+ rope_params(1024, 2 * (d // 6))
+ ],
+ dim=1)
+
+ # initialize weights
+ self.init_weights()
+
+ self.use_context_parallel = False # will modify in _configure_model func
+
+ if cond_dim > 0:
+ self.cond_encoder = nn.Conv3d(
+ cond_dim,
+ self.dim,
+ kernel_size=self.patch_size,
+ stride=self.patch_size)
+ self.enbale_adain = enable_adain
+ self.casual_audio_encoder = CausalAudioEncoder(
+ dim=audio_dim,
+ out_dim=self.dim,
+ num_token=num_audio_token,
+ need_global=enable_adain)
+ all_modules, all_modules_names = torch_dfs(
+ self.blocks, parent_name="root.transformer_blocks")
+ self.audio_injector = AudioInjector_WAN(
+ all_modules,
+ all_modules_names,
+ dim=self.dim,
+ num_heads=self.num_heads,
+ inject_layer=audio_inject_layers,
+ root_net=self,
+ enable_adain=enable_adain,
+ adain_dim=self.dim,
+ need_adain_ont=adain_mode != "attn_norm",
+ )
+ self.adain_mode = adain_mode
+
+ self.trainable_cond_mask = nn.Embedding(3, self.dim)
+
+ if zero_init:
+ self.zero_init_weights()
+
+ self.zero_timestep = zero_timestep # Whether to assign 0 value timestep to ref/motion
+
+ # init motioner
+ if enable_motioner and enable_framepack:
+ raise ValueError(
+ "enable_motioner and enable_framepack are mutually exclusive, please set one of them to False"
+ )
+ self.enable_motioner = enable_motioner
+ self.add_last_motion = add_last_motion
+ if enable_motioner:
+ motioner_dim = 2048
+ self.motioner = MotionerTransformers(
+ patch_size=(2, 4, 4),
+ dim=motioner_dim,
+ ffn_dim=motioner_dim,
+ freq_dim=256,
+ out_dim=16,
+ num_heads=16,
+ num_layers=13,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=False,
+ eps=1e-6,
+ motion_token_num=motion_token_num,
+ enable_tsm=enable_tsm,
+ motion_stride=4,
+ expand_ratio=2,
+ trainable_token_pos_emb=trainable_token_pos_emb,
+ )
+ self.zip_motion_out = torch.nn.Sequential(
+ WanLayerNorm(motioner_dim),
+ zero_module(nn.Linear(motioner_dim, self.dim)))
+
+ self.trainable_token_pos_emb = trainable_token_pos_emb
+ if trainable_token_pos_emb:
+ d = self.dim // self.num_heads
+ x = torch.zeros([1, motion_token_num, self.num_heads, d])
+ x[..., ::2] = 1
+
+ gride_sizes = [[
+ torch.tensor([0, 0, 0]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([
+ 1, self.motioner.motion_side_len,
+ self.motioner.motion_side_len
+ ]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([
+ 1, self.motioner.motion_side_len,
+ self.motioner.motion_side_len
+ ]).unsqueeze(0).repeat(1, 1),
+ ]]
+ token_freqs = rope_apply(x, gride_sizes, self.freqs)
+ token_freqs = token_freqs[0, :,
+ 0].reshape(motion_token_num, -1, 2)
+ token_freqs = token_freqs * 0.01
+ self.token_freqs = torch.nn.Parameter(token_freqs)
+
+ self.enable_framepack = enable_framepack
+ if enable_framepack:
+ self.frame_packer = FramePackMotioner(
+ inner_dim=self.dim,
+ num_heads=self.num_heads,
+ zip_frame_buckets=[1, 2, 16],
+ drop_mode=framepack_drop_mode)
+
+ def zero_init_weights(self):
+ with torch.no_grad():
+ self.trainable_cond_mask = zero_module(self.trainable_cond_mask)
+ if hasattr(self, "cond_encoder"):
+ self.cond_encoder = zero_module(self.cond_encoder)
+
+ for i in range(self.audio_injector.injector.__len__()):
+ self.audio_injector.injector[i].o = zero_module(
+ self.audio_injector.injector[i].o)
+ if self.enbale_adain:
+ self.audio_injector.injector_adain_layers[
+ i].linear = zero_module(
+ self.audio_injector.injector_adain_layers[i].linear)
+
+ def process_motion(self, motion_latents, drop_motion_frames=False):
+ if drop_motion_frames or motion_latents[0].shape[1] == 0:
+ return [], []
+ self.lat_motion_frames = motion_latents[0].shape[1]
+ mot = [self.patch_embedding(m.unsqueeze(0)) for m in motion_latents]
+ batch_size = len(mot)
+
+ mot_remb = []
+ flattern_mot = []
+ for bs in range(batch_size):
+ height, width = mot[bs].shape[3], mot[bs].shape[4]
+ flat_mot = mot[bs].flatten(2).transpose(1, 2).contiguous()
+ motion_grid_sizes = [[
+ torch.tensor([-self.lat_motion_frames, 0,
+ 0]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([0, height, width]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([self.lat_motion_frames, height,
+ width]).unsqueeze(0).repeat(1, 1)
+ ]]
+ motion_rope_emb = rope_precompute(
+ flat_mot.detach().view(1, flat_mot.shape[1], self.num_heads,
+ self.dim // self.num_heads),
+ motion_grid_sizes,
+ self.freqs,
+ start=None)
+ mot_remb.append(motion_rope_emb)
+ flattern_mot.append(flat_mot)
+ return flattern_mot, mot_remb
+
+ def process_motion_frame_pack(self,
+ motion_latents,
+ drop_motion_frames=False,
+ add_last_motion=2):
+ flattern_mot, mot_remb = self.frame_packer(motion_latents,
+ add_last_motion)
+ if drop_motion_frames:
+ return [m[:, :0] for m in flattern_mot
+ ], [m[:, :0] for m in mot_remb]
+ else:
+ return flattern_mot, mot_remb
+
+ def process_motion_transformer_motioner(self,
+ motion_latents,
+ drop_motion_frames=False,
+ add_last_motion=True):
+ batch_size, height, width = len(
+ motion_latents), motion_latents[0].shape[2] // self.patch_size[
+ 1], motion_latents[0].shape[3] // self.patch_size[2]
+
+ freqs = self.freqs
+ device = self.patch_embedding.weight.device
+ if freqs.device != device:
+ freqs = freqs.to(device)
+ if self.trainable_token_pos_emb:
+ with amp.autocast(dtype=torch.float64):
+ token_freqs = self.token_freqs.to(torch.float64)
+ token_freqs = token_freqs / token_freqs.norm(
+ dim=-1, keepdim=True)
+ freqs = [freqs, torch.view_as_complex(token_freqs)]
+
+ if not drop_motion_frames and add_last_motion:
+ last_motion_latent = [u[:, -1:] for u in motion_latents]
+ last_mot = [
+ self.patch_embedding(m.unsqueeze(0)) for m in last_motion_latent
+ ]
+ last_mot = [m.flatten(2).transpose(1, 2) for m in last_mot]
+ last_mot = torch.cat(last_mot)
+ gride_sizes = [[
+ torch.tensor([-1, 0, 0]).unsqueeze(0).repeat(batch_size, 1),
+ torch.tensor([0, height,
+ width]).unsqueeze(0).repeat(batch_size, 1),
+ torch.tensor([1, height,
+ width]).unsqueeze(0).repeat(batch_size, 1)
+ ]]
+ else:
+ last_mot = torch.zeros([batch_size, 0, self.dim],
+ device=motion_latents[0].device,
+ dtype=motion_latents[0].dtype)
+ gride_sizes = []
+
+ zip_motion = self.motioner(motion_latents)
+ zip_motion = self.zip_motion_out(zip_motion)
+ if drop_motion_frames:
+ zip_motion = zip_motion * 0.0
+ zip_motion_grid_sizes = [[
+ torch.tensor([-1, 0, 0]).unsqueeze(0).repeat(batch_size, 1),
+ torch.tensor([
+ 0, self.motioner.motion_side_len, self.motioner.motion_side_len
+ ]).unsqueeze(0).repeat(batch_size, 1),
+ torch.tensor(
+ [1 if not self.trainable_token_pos_emb else -1, height,
+ width]).unsqueeze(0).repeat(batch_size, 1),
+ ]]
+
+ mot = torch.cat([last_mot, zip_motion], dim=1)
+ gride_sizes = gride_sizes + zip_motion_grid_sizes
+
+ motion_rope_emb = rope_precompute(
+ mot.detach().view(batch_size, mot.shape[1], self.num_heads,
+ self.dim // self.num_heads),
+ gride_sizes,
+ freqs,
+ start=None)
+ return [m.unsqueeze(0) for m in mot
+ ], [r.unsqueeze(0) for r in motion_rope_emb]
+
+ def inject_motion(self,
+ x,
+ seq_lens,
+ rope_embs,
+ mask_input,
+ motion_latents,
+ drop_motion_frames=False,
+ add_last_motion=True):
+ # inject the motion frames token to the hidden states
+ if self.enable_motioner:
+ mot, mot_remb = self.process_motion_transformer_motioner(
+ motion_latents,
+ drop_motion_frames=drop_motion_frames,
+ add_last_motion=add_last_motion)
+ elif self.enable_framepack:
+ mot, mot_remb = self.process_motion_frame_pack(
+ motion_latents,
+ drop_motion_frames=drop_motion_frames,
+ add_last_motion=add_last_motion)
+ else:
+ mot, mot_remb = self.process_motion(
+ motion_latents, drop_motion_frames=drop_motion_frames)
+
+ if len(mot) > 0:
+ x = [torch.cat([u, m], dim=1) for u, m in zip(x, mot)]
+ seq_lens = seq_lens + torch.tensor([r.size(1) for r in mot],
+ dtype=torch.long)
+ rope_embs = [
+ torch.cat([u, m], dim=1) for u, m in zip(rope_embs, mot_remb)
+ ]
+ mask_input = [
+ torch.cat([
+ m, 2 * torch.ones([1, u.shape[1] - m.shape[1]],
+ device=m.device,
+ dtype=m.dtype)
+ ],
+ dim=1) for m, u in zip(mask_input, x)
+ ]
+ return x, seq_lens, rope_embs, mask_input
+
+ def after_transformer_block(self, block_idx, hidden_states):
+ if block_idx in self.audio_injector.injected_block_id.keys():
+ audio_attn_id = self.audio_injector.injected_block_id[block_idx]
+ audio_emb = self.merged_audio_emb # b f n c
+ num_frames = audio_emb.shape[1]
+
+ if self.use_context_parallel:
+ hidden_states = gather_forward(hidden_states, dim=1)
+
+ input_hidden_states = hidden_states[:, :self.
+ original_seq_len].clone(
+ ) # b (f h w) c
+ input_hidden_states = rearrange(
+ input_hidden_states, "b (t n) c -> (b t) n c", t=num_frames)
+
+ if self.enbale_adain and self.adain_mode == "attn_norm":
+ audio_emb_global = self.audio_emb_global
+ audio_emb_global = rearrange(audio_emb_global,
+ "b t n c -> (b t) n c")
+ adain_hidden_states = self.audio_injector.injector_adain_layers[
+ audio_attn_id](
+ input_hidden_states, temb=audio_emb_global[:, 0])
+ attn_hidden_states = adain_hidden_states
+ else:
+ attn_hidden_states = self.audio_injector.injector_pre_norm_feat[
+ audio_attn_id](
+ input_hidden_states)
+ audio_emb = rearrange(
+ audio_emb, "b t n c -> (b t) n c", t=num_frames)
+ attn_audio_emb = audio_emb
+ residual_out = self.audio_injector.injector[audio_attn_id](
+ x=attn_hidden_states,
+ context=attn_audio_emb,
+ context_lens=torch.ones(
+ attn_hidden_states.shape[0],
+ dtype=torch.long,
+ device=attn_hidden_states.device) * attn_audio_emb.shape[1])
+ residual_out = rearrange(
+ residual_out, "(b t) n c -> b (t n) c", t=num_frames)
+ hidden_states[:, :self.
+ original_seq_len] = hidden_states[:, :self.
+ original_seq_len] + residual_out
+
+ if self.use_context_parallel:
+ hidden_states = torch.chunk(
+ hidden_states, get_world_size(), dim=1)[get_rank()]
+
+ return hidden_states
+
+ def forward(
+ self,
+ x,
+ t,
+ context,
+ seq_len,
+ ref_latents,
+ motion_latents,
+ cond_states,
+ audio_input=None,
+ motion_frames=[17, 5],
+ add_last_motion=2,
+ drop_motion_frames=False,
+ *extra_args,
+ **extra_kwargs):
+ """
+ x: A list of videos each with shape [C, T, H, W].
+ t: [B].
+ context: A list of text embeddings each with shape [L, C].
+ seq_len: A list of video token lens, no need for this model.
+ ref_latents A list of reference image for each video with shape [C, 1, H, W].
+ motion_latents A list of motion frames for each video with shape [C, T_m, H, W].
+ cond_states A list of condition frames (i.e. pose) each with shape [C, T, H, W].
+ audio_input The input audio embedding [B, num_wav2vec_layer, C_a, T_a].
+ motion_frames The number of motion frames and motion latents frames encoded by vae, i.e. [17, 5]
+ add_last_motion For the motioner, if add_last_motion > 0, it means that the most recent frame (i.e., the last frame) will be added.
+ For frame packing, the behavior depends on the value of add_last_motion:
+ add_last_motion = 0: Only the farthest part of the latent (i.e., clean_latents_4x) is included.
+ add_last_motion = 1: Both clean_latents_2x and clean_latents_4x are included.
+ add_last_motion = 2: All motion-related latents are used.
+ drop_motion_frames Bool, whether drop the motion frames info
+ """
+ add_last_motion = self.add_last_motion * add_last_motion
+ audio_input = torch.cat([
+ audio_input[..., 0:1].repeat(1, 1, 1, motion_frames[0]), audio_input
+ ],
+ dim=-1)
+ audio_emb_res = self.casual_audio_encoder(audio_input)
+ if self.enbale_adain:
+ audio_emb_global, audio_emb = audio_emb_res
+ self.audio_emb_global = audio_emb_global[:,
+ motion_frames[1]:].clone()
+ else:
+ audio_emb = audio_emb_res
+ self.merged_audio_emb = audio_emb[:, motion_frames[1]:, :]
+
+ device = self.patch_embedding.weight.device
+
+ # embeddings
+ x = [self.patch_embedding(u.unsqueeze(0)) for u in x]
+ # cond states
+ cond = [self.cond_encoder(c.unsqueeze(0)) for c in cond_states]
+ x = [x_ + pose for x_, pose in zip(x, cond)]
+
+ grid_sizes = torch.stack(
+ [torch.tensor(u.shape[2:], dtype=torch.long) for u in x])
+ x = [u.flatten(2).transpose(1, 2) for u in x]
+ seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long)
+
+ original_grid_sizes = deepcopy(grid_sizes)
+ grid_sizes = [[torch.zeros_like(grid_sizes), grid_sizes, grid_sizes]]
+
+ # ref and motion
+ self.lat_motion_frames = motion_latents[0].shape[1]
+
+ ref = [self.patch_embedding(r.unsqueeze(0)) for r in ref_latents]
+ batch_size = len(ref)
+ height, width = ref[0].shape[3], ref[0].shape[4]
+ ref_grid_sizes = [[
+ torch.tensor([30, 0, 0]).unsqueeze(0).repeat(batch_size,
+ 1), # the start index
+ torch.tensor([31, height,
+ width]).unsqueeze(0).repeat(batch_size,
+ 1), # the end index
+ torch.tensor([1, height, width]).unsqueeze(0).repeat(batch_size, 1),
+ ] # the range
+ ]
+
+ ref = [r.flatten(2).transpose(1, 2) for r in ref] # r: 1 c f h w
+ self.original_seq_len = seq_lens[0]
+
+ seq_lens = seq_lens + torch.tensor([r.size(1) for r in ref],
+ dtype=torch.long)
+
+ grid_sizes = grid_sizes + ref_grid_sizes
+
+ x = [torch.cat([u, r], dim=1) for u, r in zip(x, ref)]
+
+ # Initialize masks to indicate noisy latent, ref latent, and motion latent.
+ # However, at this point, only the first two (noisy and ref latents) are marked;
+ # the marking of motion latent will be implemented inside `inject_motion`.
+ mask_input = [
+ torch.zeros([1, u.shape[1]], dtype=torch.long, device=x[0].device)
+ for u in x
+ ]
+ for i in range(len(mask_input)):
+ mask_input[i][:, self.original_seq_len:] = 1
+
+ # compute the rope embeddings for the input
+ x = torch.cat(x)
+ b, s, n, d = x.size(0), x.size(
+ 1), self.num_heads, self.dim // self.num_heads
+ self.pre_compute_freqs = rope_precompute(
+ x.detach().view(b, s, n, d), grid_sizes, self.freqs, start=None)
+
+ x = [u.unsqueeze(0) for u in x]
+ self.pre_compute_freqs = [
+ u.unsqueeze(0) for u in self.pre_compute_freqs
+ ]
+
+ x, seq_lens, self.pre_compute_freqs, mask_input = self.inject_motion(
+ x,
+ seq_lens,
+ self.pre_compute_freqs,
+ mask_input,
+ motion_latents,
+ drop_motion_frames=drop_motion_frames,
+ add_last_motion=add_last_motion)
+
+ x = torch.cat(x, dim=0)
+ self.pre_compute_freqs = torch.cat(self.pre_compute_freqs, dim=0)
+ mask_input = torch.cat(mask_input, dim=0)
+
+ x = x + self.trainable_cond_mask(mask_input).to(x.dtype)
+
+ # time embeddings
+ if self.zero_timestep:
+ t = torch.cat([t, torch.zeros([1], dtype=t.dtype, device=t.device)])
+ with amp.autocast(dtype=torch.float32):
+ e = self.time_embedding(
+ sinusoidal_embedding_1d(self.freq_dim, t).float())
+ e0 = self.time_projection(e).unflatten(1, (6, self.dim))
+ assert e.dtype == torch.float32 and e0.dtype == torch.float32
+
+ if self.zero_timestep:
+ e = e[:-1]
+ zero_e0 = e0[-1:]
+ e0 = e0[:-1]
+ token_len = x.shape[1]
+ e0 = torch.cat([
+ e0.unsqueeze(2),
+ zero_e0.unsqueeze(2).repeat(e0.size(0), 1, 1, 1)
+ ],
+ dim=2)
+ e0 = [e0, self.original_seq_len]
+ else:
+ e0 = e0.unsqueeze(2).repeat(1, 1, 2, 1)
+ e0 = [e0, 0]
+
+ # context
+ context_lens = None
+ context = self.text_embedding(
+ torch.stack([
+ torch.cat(
+ [u, u.new_zeros(self.text_len - u.size(0), u.size(1))])
+ for u in context
+ ]))
+
+ # grad ckpt args
+ def create_custom_forward(module, return_dict=None):
+
+ def custom_forward(*inputs, **kwargs):
+ if return_dict is not None:
+ return module(*inputs, **kwargs, return_dict=return_dict)
+ else:
+ return module(*inputs, **kwargs)
+
+ return custom_forward
+
+ if self.use_context_parallel:
+ # sharded tensors for long context attn
+ sp_rank = get_rank()
+ x = torch.chunk(x, get_world_size(), dim=1)
+ sq_size = [u.shape[1] for u in x]
+ sq_start_size = sum(sq_size[:sp_rank])
+ x = x[sp_rank]
+ # Confirm the application range of the time embedding in e0[0] for each sequence:
+ # - For tokens before seg_id: apply e0[0][:, :, 0]
+ # - For tokens after seg_id: apply e0[0][:, :, 1]
+ sp_size = x.shape[1]
+ seg_idx = e0[1] - sq_start_size
+ e0[1] = seg_idx
+
+ self.pre_compute_freqs = torch.chunk(
+ self.pre_compute_freqs, get_world_size(), dim=1)
+ self.pre_compute_freqs = self.pre_compute_freqs[sp_rank]
+
+ # arguments
+ kwargs = dict(
+ e=e0,
+ seq_lens=seq_lens,
+ grid_sizes=grid_sizes,
+ freqs=self.pre_compute_freqs,
+ context=context,
+ context_lens=context_lens)
+ for idx, block in enumerate(self.blocks):
+ x = block(x, **kwargs)
+ x = self.after_transformer_block(idx, x)
+
+ # Context Parallel
+ if self.use_context_parallel:
+ x = gather_forward(x.contiguous(), dim=1)
+ # unpatchify
+ x = x[:, :self.original_seq_len]
+ # head
+ x = self.head(x, e)
+ x = self.unpatchify(x, original_grid_sizes)
+ return [u.float() for u in x]
+
+ def unpatchify(self, x, grid_sizes):
+ """
+ Reconstruct video tensors from patch embeddings.
+
+ Args:
+ x (List[Tensor]):
+ List of patchified features, each with shape [L, C_out * prod(patch_size)]
+ grid_sizes (Tensor):
+ Original spatial-temporal grid dimensions before patching,
+ shape [B, 3] (3 dimensions correspond to F_patches, H_patches, W_patches)
+
+ Returns:
+ List[Tensor]:
+ Reconstructed video tensors with shape [C_out, F, H / 8, W / 8]
+ """
+
+ c = self.out_dim
+ out = []
+ for u, v in zip(x, grid_sizes.tolist()):
+ u = u[:math.prod(v)].view(*v, *self.patch_size, c)
+ u = torch.einsum('fhwpqrc->cfphqwr', u)
+ u = u.reshape(c, *[i * j for i, j in zip(v, self.patch_size)])
+ out.append(u)
+ return out
+
+ def init_weights(self):
+ r"""
+ Initialize model parameters using Xavier initialization.
+ """
+
+ # basic init
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.xavier_uniform_(m.weight)
+ if m.bias is not None:
+ nn.init.zeros_(m.bias)
+
+ # init embeddings
+ nn.init.xavier_uniform_(self.patch_embedding.weight.flatten(1))
+ for m in self.text_embedding.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.normal_(m.weight, std=.02)
+ for m in self.time_embedding.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.normal_(m.weight, std=.02)
+
+ # init output layer
+ nn.init.zeros_(self.head.head.weight)
diff --git a/wan/modules/s2v/motioner.py b/wan/modules/s2v/motioner.py
new file mode 100644
index 0000000000000000000000000000000000000000..ece95e5abdea8a15e29d08672fcf2f0118f2ebf9
--- /dev/null
+++ b/wan/modules/s2v/motioner.py
@@ -0,0 +1,794 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import math
+from typing import Any, Dict, List, Literal, Optional, Union
+
+import numpy as np
+import torch
+import torch.cuda.amp as amp
+import torch.nn as nn
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import BaseOutput, is_torch_version
+from einops import rearrange, repeat
+
+from ..model import flash_attention
+from .s2v_utils import rope_precompute
+
+
+def sinusoidal_embedding_1d(dim, position):
+ # preprocess
+ assert dim % 2 == 0
+ half = dim // 2
+ position = position.type(torch.float64)
+
+ # calculation
+ sinusoid = torch.outer(
+ position, torch.pow(10000, -torch.arange(half).to(position).div(half)))
+ x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
+ return x
+
+
+@amp.autocast(enabled=False)
+def rope_params(max_seq_len, dim, theta=10000):
+ assert dim % 2 == 0
+ freqs = torch.outer(
+ torch.arange(max_seq_len),
+ 1.0 / torch.pow(theta,
+ torch.arange(0, dim, 2).to(torch.float64).div(dim)))
+ freqs = torch.polar(torch.ones_like(freqs), freqs)
+ return freqs
+
+
+@amp.autocast(enabled=False)
+def rope_apply(x, grid_sizes, freqs, start=None):
+ n, c = x.size(2), x.size(3) // 2
+
+ # split freqs
+ if type(freqs) is list:
+ trainable_freqs = freqs[1]
+ freqs = freqs[0]
+ freqs = freqs.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
+
+ # loop over samples
+ output = []
+ output = x.clone()
+ seq_bucket = [0]
+ if not type(grid_sizes) is list:
+ grid_sizes = [grid_sizes]
+ for g in grid_sizes:
+ if not type(g) is list:
+ g = [torch.zeros_like(g), g]
+ batch_size = g[0].shape[0]
+ for i in range(batch_size):
+ if start is None:
+ f_o, h_o, w_o = g[0][i]
+ else:
+ f_o, h_o, w_o = start[i]
+
+ f, h, w = g[1][i]
+ t_f, t_h, t_w = g[2][i]
+ seq_f, seq_h, seq_w = f - f_o, h - h_o, w - w_o
+ seq_len = int(seq_f * seq_h * seq_w)
+ if seq_len > 0:
+ if t_f > 0:
+ factor_f, factor_h, factor_w = (t_f / seq_f).item(), (
+ t_h / seq_h).item(), (t_w / seq_w).item()
+
+ if f_o >= 0:
+ f_sam = np.linspace(f_o.item(), (t_f + f_o).item() - 1,
+ seq_f).astype(int).tolist()
+ else:
+ f_sam = np.linspace(-f_o.item(),
+ (-t_f - f_o).item() + 1,
+ seq_f).astype(int).tolist()
+ h_sam = np.linspace(h_o.item(), (t_h + h_o).item() - 1,
+ seq_h).astype(int).tolist()
+ w_sam = np.linspace(w_o.item(), (t_w + w_o).item() - 1,
+ seq_w).astype(int).tolist()
+
+ assert f_o * f >= 0 and h_o * h >= 0 and w_o * w >= 0
+ freqs_0 = freqs[0][f_sam] if f_o >= 0 else freqs[0][
+ f_sam].conj()
+ freqs_0 = freqs_0.view(seq_f, 1, 1, -1)
+
+ freqs_i = torch.cat([
+ freqs_0.expand(seq_f, seq_h, seq_w, -1),
+ freqs[1][h_sam].view(1, seq_h, 1, -1).expand(
+ seq_f, seq_h, seq_w, -1),
+ freqs[2][w_sam].view(1, 1, seq_w, -1).expand(
+ seq_f, seq_h, seq_w, -1),
+ ],
+ dim=-1).reshape(seq_len, 1, -1)
+ elif t_f < 0:
+ freqs_i = trainable_freqs.unsqueeze(1)
+ # apply rotary embedding
+ # precompute multipliers
+ x_i = torch.view_as_complex(
+ x[i, seq_bucket[-1]:seq_bucket[-1] + seq_len].to(
+ torch.float64).reshape(seq_len, n, -1, 2))
+ x_i = torch.view_as_real(x_i * freqs_i).flatten(2)
+ output[i, seq_bucket[-1]:seq_bucket[-1] + seq_len] = x_i
+ seq_bucket.append(seq_bucket[-1] + seq_len)
+ return output.float()
+
+
+class RMSNorm(nn.Module):
+
+ def __init__(self, dim, eps=1e-5):
+ super().__init__()
+ self.dim = dim
+ self.eps = eps
+ self.weight = nn.Parameter(torch.ones(dim))
+
+ def forward(self, x):
+ return self._norm(x.float()).type_as(x) * self.weight
+
+ def _norm(self, x):
+ return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
+
+
+class LayerNorm(nn.LayerNorm):
+
+ def __init__(self, dim, eps=1e-6, elementwise_affine=False):
+ super().__init__(dim, elementwise_affine=elementwise_affine, eps=eps)
+
+ def forward(self, x):
+ return super().forward(x.float()).type_as(x)
+
+
+class SelfAttention(nn.Module):
+
+ def __init__(self,
+ dim,
+ num_heads,
+ window_size=(-1, -1),
+ qk_norm=True,
+ eps=1e-6):
+ assert dim % num_heads == 0
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.eps = eps
+
+ # layers
+ self.q = nn.Linear(dim, dim)
+ self.k = nn.Linear(dim, dim)
+ self.v = nn.Linear(dim, dim)
+ self.o = nn.Linear(dim, dim)
+ self.norm_q = RMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
+ self.norm_k = RMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
+
+ def forward(self, x, seq_lens, grid_sizes, freqs):
+ b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
+
+ # query, key, value function
+ def qkv_fn(x):
+ q = self.norm_q(self.q(x)).view(b, s, n, d)
+ k = self.norm_k(self.k(x)).view(b, s, n, d)
+ v = self.v(x).view(b, s, n, d)
+ return q, k, v
+
+ q, k, v = qkv_fn(x)
+
+ x = flash_attention(
+ q=rope_apply(q, grid_sizes, freqs),
+ k=rope_apply(k, grid_sizes, freqs),
+ v=v,
+ k_lens=seq_lens,
+ window_size=self.window_size)
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
+
+
+class SwinSelfAttention(SelfAttention):
+
+ def forward(self, x, seq_lens, grid_sizes, freqs):
+ b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
+ assert b == 1, 'Only support batch_size 1'
+
+ # query, key, value function
+ def qkv_fn(x):
+ q = self.norm_q(self.q(x)).view(b, s, n, d)
+ k = self.norm_k(self.k(x)).view(b, s, n, d)
+ v = self.v(x).view(b, s, n, d)
+ return q, k, v
+
+ q, k, v = qkv_fn(x)
+
+ q = rope_apply(q, grid_sizes, freqs)
+ k = rope_apply(k, grid_sizes, freqs)
+ T, H, W = grid_sizes[0].tolist()
+
+ q = rearrange(q, 'b (t h w) n d -> (b t) (h w) n d', t=T, h=H, w=W)
+ k = rearrange(k, 'b (t h w) n d -> (b t) (h w) n d', t=T, h=H, w=W)
+ v = rearrange(v, 'b (t h w) n d -> (b t) (h w) n d', t=T, h=H, w=W)
+
+ ref_q = q[-1:]
+ q = q[:-1]
+
+ ref_k = repeat(
+ k[-1:], "1 s n d -> t s n d", t=k.shape[0] - 1) # t hw n d
+ k = k[:-1]
+ k = torch.cat([k[:1], k, k[-1:]])
+ k = torch.cat([k[1:-1], k[2:], k[:-2], ref_k], dim=1) # (bt) (3hw) n d
+
+ ref_v = repeat(v[-1:], "1 s n d -> t s n d", t=v.shape[0] - 1)
+ v = v[:-1]
+ v = torch.cat([v[:1], v, v[-1:]])
+ v = torch.cat([v[1:-1], v[2:], v[:-2], ref_v], dim=1)
+
+ # q: b (t h w) n d
+ # k: b (t h w) n d
+ out = flash_attention(
+ q=q,
+ k=k,
+ v=v,
+ # k_lens=torch.tensor([k.shape[1]] * k.shape[0], device=x.device, dtype=torch.long),
+ window_size=self.window_size)
+ out = torch.cat([out, ref_v[:1]], axis=0)
+ out = rearrange(out, '(b t) (h w) n d -> b (t h w) n d', t=T, h=H, w=W)
+ x = out
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
+
+
+#Fix the reference frame RoPE to 1,H,W.
+#Set the current frame RoPE to 1.
+#Set the previous frame RoPE to 0.
+class CasualSelfAttention(SelfAttention):
+
+ def forward(self, x, seq_lens, grid_sizes, freqs):
+ shifting = 3
+ b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
+ assert b == 1, 'Only support batch_size 1'
+
+ # query, key, value function
+ def qkv_fn(x):
+ q = self.norm_q(self.q(x)).view(b, s, n, d)
+ k = self.norm_k(self.k(x)).view(b, s, n, d)
+ v = self.v(x).view(b, s, n, d)
+ return q, k, v
+
+ q, k, v = qkv_fn(x)
+
+ T, H, W = grid_sizes[0].tolist()
+
+ q = rearrange(q, 'b (t h w) n d -> (b t) (h w) n d', t=T, h=H, w=W)
+ k = rearrange(k, 'b (t h w) n d -> (b t) (h w) n d', t=T, h=H, w=W)
+ v = rearrange(v, 'b (t h w) n d -> (b t) (h w) n d', t=T, h=H, w=W)
+
+ ref_q = q[-1:]
+ q = q[:-1]
+
+ grid_sizes = torch.tensor([[1, H, W]] * q.shape[0], dtype=torch.long)
+ start = [[shifting, 0, 0]] * q.shape[0]
+ q = rope_apply(q, grid_sizes, freqs, start=start)
+
+ ref_k = k[-1:]
+ grid_sizes = torch.tensor([[1, H, W]], dtype=torch.long)
+ # start = [[shifting, H, W]]
+
+ start = [[shifting + 10, 0, 0]]
+ ref_k = rope_apply(ref_k, grid_sizes, freqs, start)
+ ref_k = repeat(
+ ref_k, "1 s n d -> t s n d", t=k.shape[0] - 1) # t hw n d
+
+ k = k[:-1]
+ k = torch.cat([*([k[:1]] * shifting), k])
+ cat_k = []
+ for i in range(shifting):
+ cat_k.append(k[i:i - shifting])
+ cat_k.append(k[shifting:])
+ k = torch.cat(cat_k, dim=1) # (bt) (3hw) n d
+
+ grid_sizes = torch.tensor(
+ [[shifting + 1, H, W]] * q.shape[0], dtype=torch.long)
+ k = rope_apply(k, grid_sizes, freqs)
+ k = torch.cat([k, ref_k], dim=1)
+
+ ref_v = repeat(v[-1:], "1 s n d -> t s n d", t=q.shape[0]) # t hw n d
+ v = v[:-1]
+ v = torch.cat([*([v[:1]] * shifting), v])
+ cat_v = []
+ for i in range(shifting):
+ cat_v.append(v[i:i - shifting])
+ cat_v.append(v[shifting:])
+ v = torch.cat(cat_v, dim=1) # (bt) (3hw) n d
+ v = torch.cat([v, ref_v], dim=1)
+
+ # q: b (t h w) n d
+ # k: b (t h w) n d
+ outs = []
+ for i in range(q.shape[0]):
+ out = flash_attention(
+ q=q[i:i + 1],
+ k=k[i:i + 1],
+ v=v[i:i + 1],
+ window_size=self.window_size)
+ outs.append(out)
+ out = torch.cat(outs, dim=0)
+ out = torch.cat([out, ref_v[:1]], axis=0)
+ out = rearrange(out, '(b t) (h w) n d -> b (t h w) n d', t=T, h=H, w=W)
+ x = out
+
+ # output
+ x = x.flatten(2)
+ x = self.o(x)
+ return x
+
+
+class MotionerAttentionBlock(nn.Module):
+
+ def __init__(self,
+ dim,
+ ffn_dim,
+ num_heads,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=False,
+ eps=1e-6,
+ self_attn_block="SelfAttention"):
+ super().__init__()
+ self.dim = dim
+ self.ffn_dim = ffn_dim
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.cross_attn_norm = cross_attn_norm
+ self.eps = eps
+
+ # layers
+ self.norm1 = LayerNorm(dim, eps)
+ if self_attn_block == "SelfAttention":
+ self.self_attn = SelfAttention(dim, num_heads, window_size, qk_norm,
+ eps)
+ elif self_attn_block == "SwinSelfAttention":
+ self.self_attn = SwinSelfAttention(dim, num_heads, window_size,
+ qk_norm, eps)
+ elif self_attn_block == "CasualSelfAttention":
+ self.self_attn = CasualSelfAttention(dim, num_heads, window_size,
+ qk_norm, eps)
+
+ self.norm2 = LayerNorm(dim, eps)
+ self.ffn = nn.Sequential(
+ nn.Linear(dim, ffn_dim), nn.GELU(approximate='tanh'),
+ nn.Linear(ffn_dim, dim))
+
+ def forward(
+ self,
+ x,
+ seq_lens,
+ grid_sizes,
+ freqs,
+ ):
+ # self-attention
+ y = self.self_attn(self.norm1(x).float(), seq_lens, grid_sizes, freqs)
+ x = x + y
+ y = self.ffn(self.norm2(x).float())
+ x = x + y
+ return x
+
+
+class Head(nn.Module):
+
+ def __init__(self, dim, out_dim, patch_size, eps=1e-6):
+ super().__init__()
+ self.dim = dim
+ self.out_dim = out_dim
+ self.patch_size = patch_size
+ self.eps = eps
+
+ # layers
+ out_dim = math.prod(patch_size) * out_dim
+ self.norm = LayerNorm(dim, eps)
+ self.head = nn.Linear(dim, out_dim)
+
+ def forward(self, x):
+ x = self.head(self.norm(x))
+ return x
+
+
+class MotionerTransformers(nn.Module, PeftAdapterMixin):
+
+ def __init__(
+ self,
+ patch_size=(1, 2, 2),
+ in_dim=16,
+ dim=2048,
+ ffn_dim=8192,
+ freq_dim=256,
+ out_dim=16,
+ num_heads=16,
+ num_layers=32,
+ window_size=(-1, -1),
+ qk_norm=True,
+ cross_attn_norm=False,
+ eps=1e-6,
+ self_attn_block="SelfAttention",
+ motion_token_num=1024,
+ enable_tsm=False,
+ motion_stride=4,
+ expand_ratio=2,
+ trainable_token_pos_emb=False,
+ ):
+ super().__init__()
+ self.patch_size = patch_size
+ self.in_dim = in_dim
+ self.dim = dim
+ self.ffn_dim = ffn_dim
+ self.freq_dim = freq_dim
+ self.out_dim = out_dim
+ self.num_heads = num_heads
+ self.num_layers = num_layers
+ self.window_size = window_size
+ self.qk_norm = qk_norm
+ self.cross_attn_norm = cross_attn_norm
+ self.eps = eps
+
+ self.enable_tsm = enable_tsm
+ self.motion_stride = motion_stride
+ self.expand_ratio = expand_ratio
+ self.sample_c = self.patch_size[0]
+
+ # embeddings
+ self.patch_embedding = nn.Conv3d(
+ in_dim, dim, kernel_size=patch_size, stride=patch_size)
+
+ # blocks
+ self.blocks = nn.ModuleList([
+ MotionerAttentionBlock(
+ dim,
+ ffn_dim,
+ num_heads,
+ window_size,
+ qk_norm,
+ cross_attn_norm,
+ eps,
+ self_attn_block=self_attn_block) for _ in range(num_layers)
+ ])
+
+ # buffers (don't use register_buffer otherwise dtype will be changed in to())
+ assert (dim % num_heads) == 0 and (dim // num_heads) % 2 == 0
+ d = dim // num_heads
+ self.freqs = torch.cat([
+ rope_params(1024, d - 4 * (d // 6)),
+ rope_params(1024, 2 * (d // 6)),
+ rope_params(1024, 2 * (d // 6))
+ ],
+ dim=1)
+
+ self.gradient_checkpointing = False
+
+ self.motion_side_len = int(math.sqrt(motion_token_num))
+ assert self.motion_side_len**2 == motion_token_num
+ self.token = nn.Parameter(
+ torch.zeros(1, motion_token_num, dim).contiguous())
+
+ self.trainable_token_pos_emb = trainable_token_pos_emb
+ if trainable_token_pos_emb:
+ x = torch.zeros([1, motion_token_num, num_heads, d])
+ x[..., ::2] = 1
+
+ gride_sizes = [[
+ torch.tensor([0, 0, 0]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([1, self.motion_side_len,
+ self.motion_side_len]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([1, self.motion_side_len,
+ self.motion_side_len]).unsqueeze(0).repeat(1, 1),
+ ]]
+ token_freqs = rope_apply(x, gride_sizes, self.freqs)
+ token_freqs = token_freqs[0, :, 0].reshape(motion_token_num, -1, 2)
+ token_freqs = token_freqs * 0.01
+ self.token_freqs = torch.nn.Parameter(token_freqs)
+
+ def after_patch_embedding(self, x):
+ return x
+
+ def forward(
+ self,
+ x,
+ ):
+ """
+ x: A list of videos each with shape [C, T, H, W].
+ t: [B].
+ context: A list of text embeddings each with shape [L, C].
+ """
+ # params
+ motion_frames = x[0].shape[1]
+ device = self.patch_embedding.weight.device
+ freqs = self.freqs
+ if freqs.device != device:
+ freqs = freqs.to(device)
+
+ if self.trainable_token_pos_emb:
+ with amp.autocast(dtype=torch.float64):
+ token_freqs = self.token_freqs.to(torch.float64)
+ token_freqs = token_freqs / token_freqs.norm(
+ dim=-1, keepdim=True)
+ freqs = [freqs, torch.view_as_complex(token_freqs)]
+
+ if self.enable_tsm:
+ sample_idx = [
+ sample_indices(
+ u.shape[1],
+ stride=self.motion_stride,
+ expand_ratio=self.expand_ratio,
+ c=self.sample_c) for u in x
+ ]
+ x = [
+ torch.flip(torch.flip(u, [1])[:, idx], [1])
+ for idx, u in zip(sample_idx, x)
+ ]
+
+ # embeddings
+ x = [self.patch_embedding(u.unsqueeze(0)) for u in x]
+ x = self.after_patch_embedding(x)
+
+ seq_f, seq_h, seq_w = x[0].shape[-3:]
+ batch_size = len(x)
+ if not self.enable_tsm:
+ grid_sizes = torch.stack(
+ [torch.tensor(u.shape[2:], dtype=torch.long) for u in x])
+ grid_sizes = [[
+ torch.zeros_like(grid_sizes), grid_sizes, grid_sizes
+ ]]
+ seq_f = 0
+ else:
+ grid_sizes = []
+ for idx in sample_idx[0][::-1][::self.sample_c]:
+ tsm_frame_grid_sizes = [[
+ torch.tensor([idx, 0,
+ 0]).unsqueeze(0).repeat(batch_size, 1),
+ torch.tensor([idx + 1, seq_h,
+ seq_w]).unsqueeze(0).repeat(batch_size, 1),
+ torch.tensor([1, seq_h,
+ seq_w]).unsqueeze(0).repeat(batch_size, 1),
+ ]]
+ grid_sizes += tsm_frame_grid_sizes
+ seq_f = sample_idx[0][-1] + 1
+
+ x = [u.flatten(2).transpose(1, 2) for u in x]
+ seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long)
+ x = torch.cat([u for u in x])
+
+ batch_size = len(x)
+
+ token_grid_sizes = [[
+ torch.tensor([seq_f, 0, 0]).unsqueeze(0).repeat(batch_size, 1),
+ torch.tensor(
+ [seq_f + 1, self.motion_side_len,
+ self.motion_side_len]).unsqueeze(0).repeat(batch_size, 1),
+ torch.tensor(
+ [1 if not self.trainable_token_pos_emb else -1, seq_h,
+ seq_w]).unsqueeze(0).repeat(batch_size, 1),
+ ] # 第三行代表rope emb的想要覆盖到的范围
+ ]
+
+ grid_sizes = grid_sizes + token_grid_sizes
+ token_unpatch_grid_sizes = torch.stack([
+ torch.tensor([1, 32, 32], dtype=torch.long)
+ for b in range(batch_size)
+ ])
+ token_len = self.token.shape[1]
+ token = self.token.clone().repeat(x.shape[0], 1, 1).contiguous()
+ seq_lens = seq_lens + torch.tensor([t.size(0) for t in token],
+ dtype=torch.long)
+ x = torch.cat([x, token], dim=1)
+ # arguments
+ kwargs = dict(
+ seq_lens=seq_lens,
+ grid_sizes=grid_sizes,
+ freqs=freqs,
+ )
+
+ # grad ckpt args
+ def create_custom_forward(module, return_dict=None):
+
+ def custom_forward(*inputs, **kwargs):
+ if return_dict is not None:
+ return module(*inputs, **kwargs, return_dict=return_dict)
+ else:
+ return module(*inputs, **kwargs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = ({
+ "use_reentrant": False
+ } if is_torch_version(">=", "1.11.0") else {})
+
+ for idx, block in enumerate(self.blocks):
+ if self.training and self.gradient_checkpointing:
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ **kwargs,
+ **ckpt_kwargs,
+ )
+ else:
+ x = block(x, **kwargs)
+ # head
+ out = x[:, -token_len:]
+ return out
+
+ def unpatchify(self, x, grid_sizes):
+ c = self.out_dim
+ out = []
+ for u, v in zip(x, grid_sizes.tolist()):
+ u = u[:math.prod(v)].view(*v, *self.patch_size, c)
+ u = torch.einsum('fhwpqrc->cfphqwr', u)
+ u = u.reshape(c, *[i * j for i, j in zip(v, self.patch_size)])
+ out.append(u)
+ return out
+
+ def init_weights(self):
+ # basic init
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.xavier_uniform_(m.weight)
+ if m.bias is not None:
+ nn.init.zeros_(m.bias)
+
+ # init embeddings
+ nn.init.xavier_uniform_(self.patch_embedding.weight.flatten(1))
+
+
+class FramePackMotioner(nn.Module):
+
+ def __init__(
+ self,
+ inner_dim=1024,
+ num_heads=16, # Used to indicate the number of heads in the backbone network; unrelated to this module's design
+ zip_frame_buckets=[
+ 1, 2, 16
+ ], # Three numbers representing the number of frames sampled for patch operations from the nearest to the farthest frames
+ drop_mode="drop", # If not "drop", it will use "padd", meaning padding instead of deletion
+ *args,
+ **kwargs):
+ super().__init__(*args, **kwargs)
+ self.proj = nn.Conv3d(
+ 16, inner_dim, kernel_size=(1, 2, 2), stride=(1, 2, 2))
+ self.proj_2x = nn.Conv3d(
+ 16, inner_dim, kernel_size=(2, 4, 4), stride=(2, 4, 4))
+ self.proj_4x = nn.Conv3d(
+ 16, inner_dim, kernel_size=(4, 8, 8), stride=(4, 8, 8))
+ self.zip_frame_buckets = torch.tensor(
+ zip_frame_buckets, dtype=torch.long)
+
+ self.inner_dim = inner_dim
+ self.num_heads = num_heads
+
+ assert (inner_dim %
+ num_heads) == 0 and (inner_dim // num_heads) % 2 == 0
+ d = inner_dim // num_heads
+ self.freqs = torch.cat([
+ rope_params(1024, d - 4 * (d // 6)),
+ rope_params(1024, 2 * (d // 6)),
+ rope_params(1024, 2 * (d // 6))
+ ],
+ dim=1)
+ self.drop_mode = drop_mode
+
+ def forward(self, motion_latents, add_last_motion=2):
+ motion_frames = motion_latents[0].shape[1]
+ mot = []
+ mot_remb = []
+ for m in motion_latents:
+ lat_height, lat_width = m.shape[2], m.shape[3]
+ padd_lat = torch.zeros(16, self.zip_frame_buckets.sum(), lat_height,
+ lat_width).to(
+ device=m.device, dtype=m.dtype)
+ overlap_frame = min(padd_lat.shape[1], m.shape[1])
+ if overlap_frame > 0:
+ padd_lat[:, -overlap_frame:] = m[:, -overlap_frame:]
+
+ if add_last_motion < 2 and self.drop_mode != "drop":
+ zero_end_frame = self.zip_frame_buckets[:self.zip_frame_buckets.
+ __len__() -
+ add_last_motion -
+ 1].sum()
+ padd_lat[:, -zero_end_frame:] = 0
+
+ padd_lat = padd_lat.unsqueeze(0)
+ clean_latents_4x, clean_latents_2x, clean_latents_post = padd_lat[:, :, -self.zip_frame_buckets.sum(
+ ):, :, :].split(
+ list(self.zip_frame_buckets)[::-1], dim=2) # 16, 2 ,1
+
+ # patchfy
+ clean_latents_post = self.proj(clean_latents_post).flatten(
+ 2).transpose(1, 2)
+ clean_latents_2x = self.proj_2x(clean_latents_2x).flatten(
+ 2).transpose(1, 2)
+ clean_latents_4x = self.proj_4x(clean_latents_4x).flatten(
+ 2).transpose(1, 2)
+
+ if add_last_motion < 2 and self.drop_mode == "drop":
+ clean_latents_post = clean_latents_post[:, :
+ 0] if add_last_motion < 2 else clean_latents_post
+ clean_latents_2x = clean_latents_2x[:, :
+ 0] if add_last_motion < 1 else clean_latents_2x
+
+ motion_lat = torch.cat(
+ [clean_latents_post, clean_latents_2x, clean_latents_4x], dim=1)
+
+ # rope
+ start_time_id = -(self.zip_frame_buckets[:1].sum())
+ end_time_id = start_time_id + self.zip_frame_buckets[0]
+ grid_sizes = [] if add_last_motion < 2 and self.drop_mode == "drop" else \
+ [
+ [torch.tensor([start_time_id, 0, 0]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([end_time_id, lat_height // 2, lat_width // 2]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([self.zip_frame_buckets[0], lat_height // 2, lat_width // 2]).unsqueeze(0).repeat(1, 1), ]
+ ]
+
+ start_time_id = -(self.zip_frame_buckets[:2].sum())
+ end_time_id = start_time_id + self.zip_frame_buckets[1] // 2
+ grid_sizes_2x = [] if add_last_motion < 1 and self.drop_mode == "drop" else \
+ [
+ [torch.tensor([start_time_id, 0, 0]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([end_time_id, lat_height // 4, lat_width // 4]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([self.zip_frame_buckets[1], lat_height // 2, lat_width // 2]).unsqueeze(0).repeat(1, 1), ]
+ ]
+
+ start_time_id = -(self.zip_frame_buckets[:3].sum())
+ end_time_id = start_time_id + self.zip_frame_buckets[2] // 4
+ grid_sizes_4x = [[
+ torch.tensor([start_time_id, 0, 0]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([end_time_id, lat_height // 8,
+ lat_width // 8]).unsqueeze(0).repeat(1, 1),
+ torch.tensor([
+ self.zip_frame_buckets[2], lat_height // 2, lat_width // 2
+ ]).unsqueeze(0).repeat(1, 1),
+ ]]
+
+ grid_sizes = grid_sizes + grid_sizes_2x + grid_sizes_4x
+
+ motion_rope_emb = rope_precompute(
+ motion_lat.detach().view(1, motion_lat.shape[1], self.num_heads,
+ self.inner_dim // self.num_heads),
+ grid_sizes,
+ self.freqs,
+ start=None)
+
+ mot.append(motion_lat)
+ mot_remb.append(motion_rope_emb)
+ return mot, mot_remb
+
+
+def sample_indices(N, stride, expand_ratio, c):
+ indices = []
+ current_start = 0
+
+ while current_start < N:
+ bucket_width = int(stride * (expand_ratio**(len(indices) / stride)))
+
+ interval = int(bucket_width / stride * c)
+ current_end = min(N, current_start + bucket_width)
+ bucket_samples = []
+ for i in range(current_end - 1, current_start - 1, -interval):
+ for near in range(c):
+ bucket_samples.append(i - near)
+
+ indices += bucket_samples[::-1]
+ current_start += bucket_width
+
+ return indices
+
+
+if __name__ == '__main__':
+ device = "cuda"
+ model = FramePackMotioner(inner_dim=1024)
+ batch_size = 2
+ num_frame, height, width = (28, 32, 32)
+ single_input = torch.ones([16, num_frame, height, width], device=device)
+ for i in range(num_frame):
+ single_input[:, num_frame - 1 - i] *= i
+ x = [single_input] * batch_size
+ model.forward(x)
diff --git a/wan/modules/s2v/s2v_utils.py b/wan/modules/s2v/s2v_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..70dc72700572b129baf3f46a78c42185af67ab09
--- /dev/null
+++ b/wan/modules/s2v/s2v_utils.py
@@ -0,0 +1,70 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import numpy as np
+import torch
+
+
+def rope_precompute(x, grid_sizes, freqs, start=None):
+ b, s, n, c = x.size(0), x.size(1), x.size(2), x.size(3) // 2
+
+ # split freqs
+ if type(freqs) is list:
+ trainable_freqs = freqs[1]
+ freqs = freqs[0]
+ freqs = freqs.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
+
+ # loop over samples
+ output = torch.view_as_complex(x.detach().reshape(b, s, n, -1,
+ 2).to(torch.float64))
+ seq_bucket = [0]
+ if not type(grid_sizes) is list:
+ grid_sizes = [grid_sizes]
+ for g in grid_sizes:
+ if not type(g) is list:
+ g = [torch.zeros_like(g), g]
+ batch_size = g[0].shape[0]
+ for i in range(batch_size):
+ if start is None:
+ f_o, h_o, w_o = g[0][i]
+ else:
+ f_o, h_o, w_o = start[i]
+
+ f, h, w = g[1][i]
+ t_f, t_h, t_w = g[2][i]
+ seq_f, seq_h, seq_w = f - f_o, h - h_o, w - w_o
+ seq_len = int(seq_f * seq_h * seq_w)
+ if seq_len > 0:
+ if t_f > 0:
+ factor_f, factor_h, factor_w = (t_f / seq_f).item(), (
+ t_h / seq_h).item(), (t_w / seq_w).item()
+ # Generate a list of seq_f integers starting from f_o and ending at math.ceil(factor_f * seq_f.item() + f_o.item())
+ if f_o >= 0:
+ f_sam = np.linspace(f_o.item(), (t_f + f_o).item() - 1,
+ seq_f).astype(int).tolist()
+ else:
+ f_sam = np.linspace(-f_o.item(),
+ (-t_f - f_o).item() + 1,
+ seq_f).astype(int).tolist()
+ h_sam = np.linspace(h_o.item(), (t_h + h_o).item() - 1,
+ seq_h).astype(int).tolist()
+ w_sam = np.linspace(w_o.item(), (t_w + w_o).item() - 1,
+ seq_w).astype(int).tolist()
+
+ assert f_o * f >= 0 and h_o * h >= 0 and w_o * w >= 0
+ freqs_0 = freqs[0][f_sam] if f_o >= 0 else freqs[0][
+ f_sam].conj()
+ freqs_0 = freqs_0.view(seq_f, 1, 1, -1)
+
+ freqs_i = torch.cat([
+ freqs_0.expand(seq_f, seq_h, seq_w, -1),
+ freqs[1][h_sam].view(1, seq_h, 1, -1).expand(
+ seq_f, seq_h, seq_w, -1),
+ freqs[2][w_sam].view(1, 1, seq_w, -1).expand(
+ seq_f, seq_h, seq_w, -1),
+ ],
+ dim=-1).reshape(seq_len, 1, -1)
+ elif t_f < 0:
+ freqs_i = trainable_freqs.unsqueeze(1)
+ # apply rotary embedding
+ output[i, seq_bucket[-1]:seq_bucket[-1] + seq_len] = freqs_i
+ seq_bucket.append(seq_bucket[-1] + seq_len)
+ return output
diff --git a/wan/modules/t5.py b/wan/modules/t5.py
new file mode 100644
index 0000000000000000000000000000000000000000..99011940857b6a474fc466059fbded3d9f6ff4c7
--- /dev/null
+++ b/wan/modules/t5.py
@@ -0,0 +1,513 @@
+# Modified from transformers.models.t5.modeling_t5
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import logging
+import math
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from .tokenizers import HuggingfaceTokenizer
+
+__all__ = [
+ 'T5Model',
+ 'T5Encoder',
+ 'T5Decoder',
+ 'T5EncoderModel',
+]
+
+
+def fp16_clamp(x):
+ if x.dtype == torch.float16 and torch.isinf(x).any():
+ clamp = torch.finfo(x.dtype).max - 1000
+ x = torch.clamp(x, min=-clamp, max=clamp)
+ return x
+
+
+def init_weights(m):
+ if isinstance(m, T5LayerNorm):
+ nn.init.ones_(m.weight)
+ elif isinstance(m, T5Model):
+ nn.init.normal_(m.token_embedding.weight, std=1.0)
+ elif isinstance(m, T5FeedForward):
+ nn.init.normal_(m.gate[0].weight, std=m.dim**-0.5)
+ nn.init.normal_(m.fc1.weight, std=m.dim**-0.5)
+ nn.init.normal_(m.fc2.weight, std=m.dim_ffn**-0.5)
+ elif isinstance(m, T5Attention):
+ nn.init.normal_(m.q.weight, std=(m.dim * m.dim_attn)**-0.5)
+ nn.init.normal_(m.k.weight, std=m.dim**-0.5)
+ nn.init.normal_(m.v.weight, std=m.dim**-0.5)
+ nn.init.normal_(m.o.weight, std=(m.num_heads * m.dim_attn)**-0.5)
+ elif isinstance(m, T5RelativeEmbedding):
+ nn.init.normal_(
+ m.embedding.weight, std=(2 * m.num_buckets * m.num_heads)**-0.5)
+
+
+class GELU(nn.Module):
+
+ def forward(self, x):
+ return 0.5 * x * (1.0 + torch.tanh(
+ math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
+
+
+class T5LayerNorm(nn.Module):
+
+ def __init__(self, dim, eps=1e-6):
+ super(T5LayerNorm, self).__init__()
+ self.dim = dim
+ self.eps = eps
+ self.weight = nn.Parameter(torch.ones(dim))
+
+ def forward(self, x):
+ x = x * torch.rsqrt(x.float().pow(2).mean(dim=-1, keepdim=True) +
+ self.eps)
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
+ x = x.type_as(self.weight)
+ return self.weight * x
+
+
+class T5Attention(nn.Module):
+
+ def __init__(self, dim, dim_attn, num_heads, dropout=0.1):
+ assert dim_attn % num_heads == 0
+ super(T5Attention, self).__init__()
+ self.dim = dim
+ self.dim_attn = dim_attn
+ self.num_heads = num_heads
+ self.head_dim = dim_attn // num_heads
+
+ # layers
+ self.q = nn.Linear(dim, dim_attn, bias=False)
+ self.k = nn.Linear(dim, dim_attn, bias=False)
+ self.v = nn.Linear(dim, dim_attn, bias=False)
+ self.o = nn.Linear(dim_attn, dim, bias=False)
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(self, x, context=None, mask=None, pos_bias=None):
+ """
+ x: [B, L1, C].
+ context: [B, L2, C] or None.
+ mask: [B, L2] or [B, L1, L2] or None.
+ """
+ # check inputs
+ context = x if context is None else context
+ b, n, c = x.size(0), self.num_heads, self.head_dim
+
+ # compute query, key, value
+ q = self.q(x).view(b, -1, n, c)
+ k = self.k(context).view(b, -1, n, c)
+ v = self.v(context).view(b, -1, n, c)
+
+ # attention bias
+ attn_bias = x.new_zeros(b, n, q.size(1), k.size(1))
+ if pos_bias is not None:
+ attn_bias += pos_bias
+ if mask is not None:
+ assert mask.ndim in [2, 3]
+ mask = mask.view(b, 1, 1,
+ -1) if mask.ndim == 2 else mask.unsqueeze(1)
+ attn_bias.masked_fill_(mask == 0, torch.finfo(x.dtype).min)
+
+ # compute attention (T5 does not use scaling)
+ attn = torch.einsum('binc,bjnc->bnij', q, k) + attn_bias
+ attn = F.softmax(attn.float(), dim=-1).type_as(attn)
+ x = torch.einsum('bnij,bjnc->binc', attn, v)
+
+ # output
+ x = x.reshape(b, -1, n * c)
+ x = self.o(x)
+ x = self.dropout(x)
+ return x
+
+
+class T5FeedForward(nn.Module):
+
+ def __init__(self, dim, dim_ffn, dropout=0.1):
+ super(T5FeedForward, self).__init__()
+ self.dim = dim
+ self.dim_ffn = dim_ffn
+
+ # layers
+ self.gate = nn.Sequential(nn.Linear(dim, dim_ffn, bias=False), GELU())
+ self.fc1 = nn.Linear(dim, dim_ffn, bias=False)
+ self.fc2 = nn.Linear(dim_ffn, dim, bias=False)
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(self, x):
+ x = self.fc1(x) * self.gate(x)
+ x = self.dropout(x)
+ x = self.fc2(x)
+ x = self.dropout(x)
+ return x
+
+
+class T5SelfAttention(nn.Module):
+
+ def __init__(self,
+ dim,
+ dim_attn,
+ dim_ffn,
+ num_heads,
+ num_buckets,
+ shared_pos=True,
+ dropout=0.1):
+ super(T5SelfAttention, self).__init__()
+ self.dim = dim
+ self.dim_attn = dim_attn
+ self.dim_ffn = dim_ffn
+ self.num_heads = num_heads
+ self.num_buckets = num_buckets
+ self.shared_pos = shared_pos
+
+ # layers
+ self.norm1 = T5LayerNorm(dim)
+ self.attn = T5Attention(dim, dim_attn, num_heads, dropout)
+ self.norm2 = T5LayerNorm(dim)
+ self.ffn = T5FeedForward(dim, dim_ffn, dropout)
+ self.pos_embedding = None if shared_pos else T5RelativeEmbedding(
+ num_buckets, num_heads, bidirectional=True)
+
+ def forward(self, x, mask=None, pos_bias=None):
+ e = pos_bias if self.shared_pos else self.pos_embedding(
+ x.size(1), x.size(1))
+ x = fp16_clamp(x + self.attn(self.norm1(x), mask=mask, pos_bias=e))
+ x = fp16_clamp(x + self.ffn(self.norm2(x)))
+ return x
+
+
+class T5CrossAttention(nn.Module):
+
+ def __init__(self,
+ dim,
+ dim_attn,
+ dim_ffn,
+ num_heads,
+ num_buckets,
+ shared_pos=True,
+ dropout=0.1):
+ super(T5CrossAttention, self).__init__()
+ self.dim = dim
+ self.dim_attn = dim_attn
+ self.dim_ffn = dim_ffn
+ self.num_heads = num_heads
+ self.num_buckets = num_buckets
+ self.shared_pos = shared_pos
+
+ # layers
+ self.norm1 = T5LayerNorm(dim)
+ self.self_attn = T5Attention(dim, dim_attn, num_heads, dropout)
+ self.norm2 = T5LayerNorm(dim)
+ self.cross_attn = T5Attention(dim, dim_attn, num_heads, dropout)
+ self.norm3 = T5LayerNorm(dim)
+ self.ffn = T5FeedForward(dim, dim_ffn, dropout)
+ self.pos_embedding = None if shared_pos else T5RelativeEmbedding(
+ num_buckets, num_heads, bidirectional=False)
+
+ def forward(self,
+ x,
+ mask=None,
+ encoder_states=None,
+ encoder_mask=None,
+ pos_bias=None):
+ e = pos_bias if self.shared_pos else self.pos_embedding(
+ x.size(1), x.size(1))
+ x = fp16_clamp(x + self.self_attn(self.norm1(x), mask=mask, pos_bias=e))
+ x = fp16_clamp(x + self.cross_attn(
+ self.norm2(x), context=encoder_states, mask=encoder_mask))
+ x = fp16_clamp(x + self.ffn(self.norm3(x)))
+ return x
+
+
+class T5RelativeEmbedding(nn.Module):
+
+ def __init__(self, num_buckets, num_heads, bidirectional, max_dist=128):
+ super(T5RelativeEmbedding, self).__init__()
+ self.num_buckets = num_buckets
+ self.num_heads = num_heads
+ self.bidirectional = bidirectional
+ self.max_dist = max_dist
+
+ # layers
+ self.embedding = nn.Embedding(num_buckets, num_heads)
+
+ def forward(self, lq, lk):
+ device = self.embedding.weight.device
+ # rel_pos = torch.arange(lk).unsqueeze(0).to(device) - \
+ # torch.arange(lq).unsqueeze(1).to(device)
+ rel_pos = torch.arange(lk, device=device).unsqueeze(0) - \
+ torch.arange(lq, device=device).unsqueeze(1)
+ rel_pos = self._relative_position_bucket(rel_pos)
+ rel_pos_embeds = self.embedding(rel_pos)
+ rel_pos_embeds = rel_pos_embeds.permute(2, 0, 1).unsqueeze(
+ 0) # [1, N, Lq, Lk]
+ return rel_pos_embeds.contiguous()
+
+ def _relative_position_bucket(self, rel_pos):
+ # preprocess
+ if self.bidirectional:
+ num_buckets = self.num_buckets // 2
+ rel_buckets = (rel_pos > 0).long() * num_buckets
+ rel_pos = torch.abs(rel_pos)
+ else:
+ num_buckets = self.num_buckets
+ rel_buckets = 0
+ rel_pos = -torch.min(rel_pos, torch.zeros_like(rel_pos))
+
+ # embeddings for small and large positions
+ max_exact = num_buckets // 2
+ rel_pos_large = max_exact + (torch.log(rel_pos.float() / max_exact) /
+ math.log(self.max_dist / max_exact) *
+ (num_buckets - max_exact)).long()
+ rel_pos_large = torch.min(
+ rel_pos_large, torch.full_like(rel_pos_large, num_buckets - 1))
+ rel_buckets += torch.where(rel_pos < max_exact, rel_pos, rel_pos_large)
+ return rel_buckets
+
+
+class T5Encoder(nn.Module):
+
+ def __init__(self,
+ vocab,
+ dim,
+ dim_attn,
+ dim_ffn,
+ num_heads,
+ num_layers,
+ num_buckets,
+ shared_pos=True,
+ dropout=0.1):
+ super(T5Encoder, self).__init__()
+ self.dim = dim
+ self.dim_attn = dim_attn
+ self.dim_ffn = dim_ffn
+ self.num_heads = num_heads
+ self.num_layers = num_layers
+ self.num_buckets = num_buckets
+ self.shared_pos = shared_pos
+
+ # layers
+ self.token_embedding = vocab if isinstance(vocab, nn.Embedding) \
+ else nn.Embedding(vocab, dim)
+ self.pos_embedding = T5RelativeEmbedding(
+ num_buckets, num_heads, bidirectional=True) if shared_pos else None
+ self.dropout = nn.Dropout(dropout)
+ self.blocks = nn.ModuleList([
+ T5SelfAttention(dim, dim_attn, dim_ffn, num_heads, num_buckets,
+ shared_pos, dropout) for _ in range(num_layers)
+ ])
+ self.norm = T5LayerNorm(dim)
+
+ # initialize weights
+ self.apply(init_weights)
+
+ def forward(self, ids, mask=None):
+ x = self.token_embedding(ids)
+ x = self.dropout(x)
+ e = self.pos_embedding(x.size(1),
+ x.size(1)) if self.shared_pos else None
+ for block in self.blocks:
+ x = block(x, mask, pos_bias=e)
+ x = self.norm(x)
+ x = self.dropout(x)
+ return x
+
+
+class T5Decoder(nn.Module):
+
+ def __init__(self,
+ vocab,
+ dim,
+ dim_attn,
+ dim_ffn,
+ num_heads,
+ num_layers,
+ num_buckets,
+ shared_pos=True,
+ dropout=0.1):
+ super(T5Decoder, self).__init__()
+ self.dim = dim
+ self.dim_attn = dim_attn
+ self.dim_ffn = dim_ffn
+ self.num_heads = num_heads
+ self.num_layers = num_layers
+ self.num_buckets = num_buckets
+ self.shared_pos = shared_pos
+
+ # layers
+ self.token_embedding = vocab if isinstance(vocab, nn.Embedding) \
+ else nn.Embedding(vocab, dim)
+ self.pos_embedding = T5RelativeEmbedding(
+ num_buckets, num_heads, bidirectional=False) if shared_pos else None
+ self.dropout = nn.Dropout(dropout)
+ self.blocks = nn.ModuleList([
+ T5CrossAttention(dim, dim_attn, dim_ffn, num_heads, num_buckets,
+ shared_pos, dropout) for _ in range(num_layers)
+ ])
+ self.norm = T5LayerNorm(dim)
+
+ # initialize weights
+ self.apply(init_weights)
+
+ def forward(self, ids, mask=None, encoder_states=None, encoder_mask=None):
+ b, s = ids.size()
+
+ # causal mask
+ if mask is None:
+ mask = torch.tril(torch.ones(1, s, s).to(ids.device))
+ elif mask.ndim == 2:
+ mask = torch.tril(mask.unsqueeze(1).expand(-1, s, -1))
+
+ # layers
+ x = self.token_embedding(ids)
+ x = self.dropout(x)
+ e = self.pos_embedding(x.size(1),
+ x.size(1)) if self.shared_pos else None
+ for block in self.blocks:
+ x = block(x, mask, encoder_states, encoder_mask, pos_bias=e)
+ x = self.norm(x)
+ x = self.dropout(x)
+ return x
+
+
+class T5Model(nn.Module):
+
+ def __init__(self,
+ vocab_size,
+ dim,
+ dim_attn,
+ dim_ffn,
+ num_heads,
+ encoder_layers,
+ decoder_layers,
+ num_buckets,
+ shared_pos=True,
+ dropout=0.1):
+ super(T5Model, self).__init__()
+ self.vocab_size = vocab_size
+ self.dim = dim
+ self.dim_attn = dim_attn
+ self.dim_ffn = dim_ffn
+ self.num_heads = num_heads
+ self.encoder_layers = encoder_layers
+ self.decoder_layers = decoder_layers
+ self.num_buckets = num_buckets
+
+ # layers
+ self.token_embedding = nn.Embedding(vocab_size, dim)
+ self.encoder = T5Encoder(self.token_embedding, dim, dim_attn, dim_ffn,
+ num_heads, encoder_layers, num_buckets,
+ shared_pos, dropout)
+ self.decoder = T5Decoder(self.token_embedding, dim, dim_attn, dim_ffn,
+ num_heads, decoder_layers, num_buckets,
+ shared_pos, dropout)
+ self.head = nn.Linear(dim, vocab_size, bias=False)
+
+ # initialize weights
+ self.apply(init_weights)
+
+ def forward(self, encoder_ids, encoder_mask, decoder_ids, decoder_mask):
+ x = self.encoder(encoder_ids, encoder_mask)
+ x = self.decoder(decoder_ids, decoder_mask, x, encoder_mask)
+ x = self.head(x)
+ return x
+
+
+def _t5(name,
+ encoder_only=False,
+ decoder_only=False,
+ return_tokenizer=False,
+ tokenizer_kwargs={},
+ dtype=torch.float32,
+ device='cpu',
+ **kwargs):
+ # sanity check
+ assert not (encoder_only and decoder_only)
+
+ # params
+ if encoder_only:
+ model_cls = T5Encoder
+ kwargs['vocab'] = kwargs.pop('vocab_size')
+ kwargs['num_layers'] = kwargs.pop('encoder_layers')
+ _ = kwargs.pop('decoder_layers')
+ elif decoder_only:
+ model_cls = T5Decoder
+ kwargs['vocab'] = kwargs.pop('vocab_size')
+ kwargs['num_layers'] = kwargs.pop('decoder_layers')
+ _ = kwargs.pop('encoder_layers')
+ else:
+ model_cls = T5Model
+
+ # init model
+ with torch.device(device):
+ model = model_cls(**kwargs)
+
+ # set device
+ model = model.to(dtype=dtype, device=device)
+
+ # init tokenizer
+ if return_tokenizer:
+ from .tokenizers import HuggingfaceTokenizer
+ tokenizer = HuggingfaceTokenizer(f'google/{name}', **tokenizer_kwargs)
+ return model, tokenizer
+ else:
+ return model
+
+
+def umt5_xxl(**kwargs):
+ cfg = dict(
+ vocab_size=256384,
+ dim=4096,
+ dim_attn=4096,
+ dim_ffn=10240,
+ num_heads=64,
+ encoder_layers=24,
+ decoder_layers=24,
+ num_buckets=32,
+ shared_pos=False,
+ dropout=0.1)
+ cfg.update(**kwargs)
+ return _t5('umt5-xxl', **cfg)
+
+
+class T5EncoderModel:
+
+ def __init__(
+ self,
+ text_len,
+ dtype=torch.bfloat16,
+ device=torch.cuda.current_device(),
+ checkpoint_path=None,
+ tokenizer_path=None,
+ shard_fn=None,
+ ):
+ self.text_len = text_len
+ self.dtype = dtype
+ self.device = device
+ self.checkpoint_path = checkpoint_path
+ self.tokenizer_path = tokenizer_path
+
+ # init model
+ model = umt5_xxl(
+ encoder_only=True,
+ return_tokenizer=False,
+ dtype=dtype,
+ device=device).eval().requires_grad_(False)
+ logging.info(f'loading {checkpoint_path}')
+ model.load_state_dict(torch.load(checkpoint_path, map_location='cpu'))
+ self.model = model
+ if shard_fn is not None:
+ self.model = shard_fn(self.model, sync_module_states=False)
+ else:
+ self.model.to(self.device)
+ # init tokenizer
+ self.tokenizer = HuggingfaceTokenizer(
+ name=tokenizer_path, seq_len=text_len, clean='whitespace')
+
+ def __call__(self, texts, device):
+ ids, mask = self.tokenizer(
+ texts, return_mask=True, add_special_tokens=True)
+ ids = ids.to(device)
+ mask = mask.to(device)
+ seq_lens = mask.gt(0).sum(dim=1).long()
+ context = self.model(ids, mask)
+ return [u[:v] for u, v in zip(context, seq_lens)]
diff --git a/wan/modules/tokenizers.py b/wan/modules/tokenizers.py
new file mode 100644
index 0000000000000000000000000000000000000000..329c2add418c49c5df1c589c45dd124a59caafc7
--- /dev/null
+++ b/wan/modules/tokenizers.py
@@ -0,0 +1,82 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import html
+import string
+
+import ftfy
+import regex as re
+from transformers import AutoTokenizer
+
+__all__ = ['HuggingfaceTokenizer']
+
+
+def basic_clean(text):
+ text = ftfy.fix_text(text)
+ text = html.unescape(html.unescape(text))
+ return text.strip()
+
+
+def whitespace_clean(text):
+ text = re.sub(r'\s+', ' ', text)
+ text = text.strip()
+ return text
+
+
+def canonicalize(text, keep_punctuation_exact_string=None):
+ text = text.replace('_', ' ')
+ if keep_punctuation_exact_string:
+ text = keep_punctuation_exact_string.join(
+ part.translate(str.maketrans('', '', string.punctuation))
+ for part in text.split(keep_punctuation_exact_string))
+ else:
+ text = text.translate(str.maketrans('', '', string.punctuation))
+ text = text.lower()
+ text = re.sub(r'\s+', ' ', text)
+ return text.strip()
+
+
+class HuggingfaceTokenizer:
+
+ def __init__(self, name, seq_len=None, clean=None, **kwargs):
+ assert clean in (None, 'whitespace', 'lower', 'canonicalize')
+ self.name = name
+ self.seq_len = seq_len
+ self.clean = clean
+
+ # init tokenizer
+ self.tokenizer = AutoTokenizer.from_pretrained(name, **kwargs)
+ self.vocab_size = self.tokenizer.vocab_size
+
+ def __call__(self, sequence, **kwargs):
+ return_mask = kwargs.pop('return_mask', False)
+
+ # arguments
+ _kwargs = {'return_tensors': 'pt'}
+ if self.seq_len is not None:
+ _kwargs.update({
+ 'padding': 'max_length',
+ 'truncation': True,
+ 'max_length': self.seq_len
+ })
+ _kwargs.update(**kwargs)
+
+ # tokenization
+ if isinstance(sequence, str):
+ sequence = [sequence]
+ if self.clean:
+ sequence = [self._clean(u) for u in sequence]
+ ids = self.tokenizer(sequence, **_kwargs)
+
+ # output
+ if return_mask:
+ return ids.input_ids, ids.attention_mask
+ else:
+ return ids.input_ids
+
+ def _clean(self, text):
+ if self.clean == 'whitespace':
+ text = whitespace_clean(basic_clean(text))
+ elif self.clean == 'lower':
+ text = whitespace_clean(basic_clean(text)).lower()
+ elif self.clean == 'canonicalize':
+ text = canonicalize(basic_clean(text))
+ return text
diff --git a/wan/modules/vae2_1.py b/wan/modules/vae2_1.py
new file mode 100644
index 0000000000000000000000000000000000000000..c081977f0e0b977d1dc846fbb3f032f6d28eceab
--- /dev/null
+++ b/wan/modules/vae2_1.py
@@ -0,0 +1,663 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import logging
+
+import torch
+import torch.cuda.amp as amp
+import torch.nn as nn
+import torch.nn.functional as F
+from einops import rearrange
+
+__all__ = [
+ 'Wan2_1_VAE',
+]
+
+CACHE_T = 2
+
+
+class CausalConv3d(nn.Conv3d):
+ """
+ Causal 3d convolusion.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._padding = (self.padding[2], self.padding[2], self.padding[1],
+ self.padding[1], 2 * self.padding[0], 0)
+ self.padding = (0, 0, 0)
+
+ def forward(self, x, cache_x=None):
+ padding = list(self._padding)
+ if cache_x is not None and self._padding[4] > 0:
+ cache_x = cache_x.to(x.device)
+ x = torch.cat([cache_x, x], dim=2)
+ padding[4] -= cache_x.shape[2]
+ x = F.pad(x, padding)
+
+ return super().forward(x)
+
+
+class RMS_norm(nn.Module):
+
+ def __init__(self, dim, channel_first=True, images=True, bias=False):
+ super().__init__()
+ broadcastable_dims = (1, 1, 1) if not images else (1, 1)
+ shape = (dim, *broadcastable_dims) if channel_first else (dim,)
+
+ self.channel_first = channel_first
+ self.scale = dim**0.5
+ self.gamma = nn.Parameter(torch.ones(shape))
+ self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.
+
+ def forward(self, x):
+ return F.normalize(
+ x, dim=(1 if self.channel_first else
+ -1)) * self.scale * self.gamma + self.bias
+
+
+class Upsample(nn.Upsample):
+
+ def forward(self, x):
+ """
+ Fix bfloat16 support for nearest neighbor interpolation.
+ """
+ return super().forward(x.float()).type_as(x)
+
+
+class Resample(nn.Module):
+
+ def __init__(self, dim, mode):
+ assert mode in ('none', 'upsample2d', 'upsample3d', 'downsample2d',
+ 'downsample3d')
+ super().__init__()
+ self.dim = dim
+ self.mode = mode
+
+ # layers
+ if mode == 'upsample2d':
+ self.resample = nn.Sequential(
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
+ elif mode == 'upsample3d':
+ self.resample = nn.Sequential(
+ Upsample(scale_factor=(2., 2.), mode='nearest-exact'),
+ nn.Conv2d(dim, dim // 2, 3, padding=1))
+ self.time_conv = CausalConv3d(
+ dim, dim * 2, (3, 1, 1), padding=(1, 0, 0))
+
+ elif mode == 'downsample2d':
+ self.resample = nn.Sequential(
+ nn.ZeroPad2d((0, 1, 0, 1)),
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
+ elif mode == 'downsample3d':
+ self.resample = nn.Sequential(
+ nn.ZeroPad2d((0, 1, 0, 1)),
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
+ self.time_conv = CausalConv3d(
+ dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0))
+
+ else:
+ self.resample = nn.Identity()
+
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
+ b, c, t, h, w = x.size()
+ if self.mode == 'upsample3d':
+ if feat_cache is not None:
+ idx = feat_idx[0]
+ if feat_cache[idx] is None:
+ feat_cache[idx] = 'Rep'
+ feat_idx[0] += 1
+ else:
+
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[
+ idx] is not None and feat_cache[idx] != 'Rep':
+ # cache last frame of last two chunk
+ cache_x = torch.cat([
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device), cache_x
+ ],
+ dim=2)
+ if cache_x.shape[2] < 2 and feat_cache[
+ idx] is not None and feat_cache[idx] == 'Rep':
+ cache_x = torch.cat([
+ torch.zeros_like(cache_x).to(cache_x.device),
+ cache_x
+ ],
+ dim=2)
+ if feat_cache[idx] == 'Rep':
+ x = self.time_conv(x)
+ else:
+ x = self.time_conv(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+
+ x = x.reshape(b, 2, c, t, h, w)
+ x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]),
+ 3)
+ x = x.reshape(b, c, t * 2, h, w)
+ t = x.shape[2]
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
+ x = self.resample(x)
+ x = rearrange(x, '(b t) c h w -> b c t h w', t=t)
+
+ if self.mode == 'downsample3d':
+ if feat_cache is not None:
+ idx = feat_idx[0]
+ if feat_cache[idx] is None:
+ feat_cache[idx] = x.clone()
+ feat_idx[0] += 1
+ else:
+
+ cache_x = x[:, :, -1:, :, :].clone()
+ # if cache_x.shape[2] < 2 and feat_cache[idx] is not None and feat_cache[idx]!='Rep':
+ # # cache last frame of last two chunk
+ # cache_x = torch.cat([feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(cache_x.device), cache_x], dim=2)
+
+ x = self.time_conv(
+ torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2))
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ return x
+
+ def init_weight(self, conv):
+ conv_weight = conv.weight
+ nn.init.zeros_(conv_weight)
+ c1, c2, t, h, w = conv_weight.size()
+ one_matrix = torch.eye(c1, c2)
+ init_matrix = one_matrix
+ nn.init.zeros_(conv_weight)
+ #conv_weight.data[:,:,-1,1,1] = init_matrix * 0.5
+ conv_weight.data[:, :, 1, 0, 0] = init_matrix #* 0.5
+ conv.weight.data.copy_(conv_weight)
+ nn.init.zeros_(conv.bias.data)
+
+ def init_weight2(self, conv):
+ conv_weight = conv.weight.data
+ nn.init.zeros_(conv_weight)
+ c1, c2, t, h, w = conv_weight.size()
+ init_matrix = torch.eye(c1 // 2, c2)
+ #init_matrix = repeat(init_matrix, 'o ... -> (o 2) ...').permute(1,0,2).contiguous().reshape(c1,c2)
+ conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix
+ conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix
+ conv.weight.data.copy_(conv_weight)
+ nn.init.zeros_(conv.bias.data)
+
+
+class ResidualBlock(nn.Module):
+
+ def __init__(self, in_dim, out_dim, dropout=0.0):
+ super().__init__()
+ self.in_dim = in_dim
+ self.out_dim = out_dim
+
+ # layers
+ self.residual = nn.Sequential(
+ RMS_norm(in_dim, images=False), nn.SiLU(),
+ CausalConv3d(in_dim, out_dim, 3, padding=1),
+ RMS_norm(out_dim, images=False), nn.SiLU(), nn.Dropout(dropout),
+ CausalConv3d(out_dim, out_dim, 3, padding=1))
+ self.shortcut = CausalConv3d(in_dim, out_dim, 1) \
+ if in_dim != out_dim else nn.Identity()
+
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
+ h = self.shortcut(x)
+ for layer in self.residual:
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ # cache last frame of last two chunk
+ cache_x = torch.cat([
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device), cache_x
+ ],
+ dim=2)
+ x = layer(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = layer(x)
+ return x + h
+
+
+class AttentionBlock(nn.Module):
+ """
+ Causal self-attention with a single head.
+ """
+
+ def __init__(self, dim):
+ super().__init__()
+ self.dim = dim
+
+ # layers
+ self.norm = RMS_norm(dim)
+ self.to_qkv = nn.Conv2d(dim, dim * 3, 1)
+ self.proj = nn.Conv2d(dim, dim, 1)
+
+ # zero out the last layer params
+ nn.init.zeros_(self.proj.weight)
+
+ def forward(self, x):
+ identity = x
+ b, c, t, h, w = x.size()
+ x = rearrange(x, 'b c t h w -> (b t) c h w')
+ x = self.norm(x)
+ # compute query, key, value
+ q, k, v = self.to_qkv(x).reshape(b * t, 1, c * 3,
+ -1).permute(0, 1, 3,
+ 2).contiguous().chunk(
+ 3, dim=-1)
+
+ # apply attention
+ x = F.scaled_dot_product_attention(
+ q,
+ k,
+ v,
+ )
+ x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w)
+
+ # output
+ x = self.proj(x)
+ x = rearrange(x, '(b t) c h w-> b c t h w', t=t)
+ return x + identity
+
+
+class Encoder3d(nn.Module):
+
+ def __init__(self,
+ dim=128,
+ z_dim=4,
+ dim_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ attn_scales=[],
+ temperal_downsample=[True, True, False],
+ dropout=0.0):
+ super().__init__()
+ self.dim = dim
+ self.z_dim = z_dim
+ self.dim_mult = dim_mult
+ self.num_res_blocks = num_res_blocks
+ self.attn_scales = attn_scales
+ self.temperal_downsample = temperal_downsample
+
+ # dimensions
+ dims = [dim * u for u in [1] + dim_mult]
+ scale = 1.0
+
+ # init block
+ self.conv1 = CausalConv3d(3, dims[0], 3, padding=1)
+
+ # downsample blocks
+ downsamples = []
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
+ # residual (+attention) blocks
+ for _ in range(num_res_blocks):
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
+ if scale in attn_scales:
+ downsamples.append(AttentionBlock(out_dim))
+ in_dim = out_dim
+
+ # downsample block
+ if i != len(dim_mult) - 1:
+ mode = 'downsample3d' if temperal_downsample[
+ i] else 'downsample2d'
+ downsamples.append(Resample(out_dim, mode=mode))
+ scale /= 2.0
+ self.downsamples = nn.Sequential(*downsamples)
+
+ # middle blocks
+ self.middle = nn.Sequential(
+ ResidualBlock(out_dim, out_dim, dropout), AttentionBlock(out_dim),
+ ResidualBlock(out_dim, out_dim, dropout))
+
+ # output blocks
+ self.head = nn.Sequential(
+ RMS_norm(out_dim, images=False), nn.SiLU(),
+ CausalConv3d(out_dim, z_dim, 3, padding=1))
+
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
+ if feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ # cache last frame of last two chunk
+ cache_x = torch.cat([
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device), cache_x
+ ],
+ dim=2)
+ x = self.conv1(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = self.conv1(x)
+
+ ## downsamples
+ for layer in self.downsamples:
+ if feat_cache is not None:
+ x = layer(x, feat_cache, feat_idx)
+ else:
+ x = layer(x)
+
+ ## middle
+ for layer in self.middle:
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
+ x = layer(x, feat_cache, feat_idx)
+ else:
+ x = layer(x)
+
+ ## head
+ for layer in self.head:
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ # cache last frame of last two chunk
+ cache_x = torch.cat([
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device), cache_x
+ ],
+ dim=2)
+ x = layer(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = layer(x)
+ return x
+
+
+class Decoder3d(nn.Module):
+
+ def __init__(self,
+ dim=128,
+ z_dim=4,
+ dim_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ attn_scales=[],
+ temperal_upsample=[False, True, True],
+ dropout=0.0):
+ super().__init__()
+ self.dim = dim
+ self.z_dim = z_dim
+ self.dim_mult = dim_mult
+ self.num_res_blocks = num_res_blocks
+ self.attn_scales = attn_scales
+ self.temperal_upsample = temperal_upsample
+
+ # dimensions
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
+ scale = 1.0 / 2**(len(dim_mult) - 2)
+
+ # init block
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
+
+ # middle blocks
+ self.middle = nn.Sequential(
+ ResidualBlock(dims[0], dims[0], dropout), AttentionBlock(dims[0]),
+ ResidualBlock(dims[0], dims[0], dropout))
+
+ # upsample blocks
+ upsamples = []
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
+ # residual (+attention) blocks
+ if i == 1 or i == 2 or i == 3:
+ in_dim = in_dim // 2
+ for _ in range(num_res_blocks + 1):
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
+ if scale in attn_scales:
+ upsamples.append(AttentionBlock(out_dim))
+ in_dim = out_dim
+
+ # upsample block
+ if i != len(dim_mult) - 1:
+ mode = 'upsample3d' if temperal_upsample[i] else 'upsample2d'
+ upsamples.append(Resample(out_dim, mode=mode))
+ scale *= 2.0
+ self.upsamples = nn.Sequential(*upsamples)
+
+ # output blocks
+ self.head = nn.Sequential(
+ RMS_norm(out_dim, images=False), nn.SiLU(),
+ CausalConv3d(out_dim, 3, 3, padding=1))
+
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
+ ## conv1
+ if feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ # cache last frame of last two chunk
+ cache_x = torch.cat([
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device), cache_x
+ ],
+ dim=2)
+ x = self.conv1(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = self.conv1(x)
+
+ ## middle
+ for layer in self.middle:
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
+ x = layer(x, feat_cache, feat_idx)
+ else:
+ x = layer(x)
+
+ ## upsamples
+ for layer in self.upsamples:
+ if feat_cache is not None:
+ x = layer(x, feat_cache, feat_idx)
+ else:
+ x = layer(x)
+
+ ## head
+ for layer in self.head:
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ # cache last frame of last two chunk
+ cache_x = torch.cat([
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device), cache_x
+ ],
+ dim=2)
+ x = layer(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = layer(x)
+ return x
+
+
+def count_conv3d(model):
+ count = 0
+ for m in model.modules():
+ if isinstance(m, CausalConv3d):
+ count += 1
+ return count
+
+
+class WanVAE_(nn.Module):
+
+ def __init__(self,
+ dim=128,
+ z_dim=4,
+ dim_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ attn_scales=[],
+ temperal_downsample=[True, True, False],
+ dropout=0.0):
+ super().__init__()
+ self.dim = dim
+ self.z_dim = z_dim
+ self.dim_mult = dim_mult
+ self.num_res_blocks = num_res_blocks
+ self.attn_scales = attn_scales
+ self.temperal_downsample = temperal_downsample
+ self.temperal_upsample = temperal_downsample[::-1]
+
+ # modules
+ self.encoder = Encoder3d(dim, z_dim * 2, dim_mult, num_res_blocks,
+ attn_scales, self.temperal_downsample, dropout)
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
+ self.decoder = Decoder3d(dim, z_dim, dim_mult, num_res_blocks,
+ attn_scales, self.temperal_upsample, dropout)
+
+ def forward(self, x):
+ mu, log_var = self.encode(x)
+ z = self.reparameterize(mu, log_var)
+ x_recon = self.decode(z)
+ return x_recon, mu, log_var
+
+ def encode(self, x, scale):
+ self.clear_cache()
+ ## cache
+ t = x.shape[2]
+ iter_ = 1 + (t - 1) // 4
+ ## 对encode输入的x,按时间拆分为1、4、4、4....
+ for i in range(iter_):
+ self._enc_conv_idx = [0]
+ if i == 0:
+ out = self.encoder(
+ x[:, :, :1, :, :],
+ feat_cache=self._enc_feat_map,
+ feat_idx=self._enc_conv_idx)
+ else:
+ out_ = self.encoder(
+ x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
+ feat_cache=self._enc_feat_map,
+ feat_idx=self._enc_conv_idx)
+ out = torch.cat([out, out_], 2)
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
+ if isinstance(scale[0], torch.Tensor):
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
+ 1, self.z_dim, 1, 1, 1)
+ else:
+ mu = (mu - scale[0]) * scale[1]
+ self.clear_cache()
+ return mu
+
+ def decode(self, z, scale):
+ self.clear_cache()
+ # z: [b,c,t,h,w]
+ if isinstance(scale[0], torch.Tensor):
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
+ 1, self.z_dim, 1, 1, 1)
+ else:
+ z = z / scale[1] + scale[0]
+ iter_ = z.shape[2]
+ x = self.conv2(z)
+ for i in range(iter_):
+ self._conv_idx = [0]
+ if i == 0:
+ out = self.decoder(
+ x[:, :, i:i + 1, :, :],
+ feat_cache=self._feat_map,
+ feat_idx=self._conv_idx)
+ else:
+ out_ = self.decoder(
+ x[:, :, i:i + 1, :, :],
+ feat_cache=self._feat_map,
+ feat_idx=self._conv_idx)
+ out = torch.cat([out, out_], 2)
+ self.clear_cache()
+ return out
+
+ def reparameterize(self, mu, log_var):
+ std = torch.exp(0.5 * log_var)
+ eps = torch.randn_like(std)
+ return eps * std + mu
+
+ def sample(self, imgs, deterministic=False):
+ mu, log_var = self.encode(imgs)
+ if deterministic:
+ return mu
+ std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0))
+ return mu + std * torch.randn_like(std)
+
+ def clear_cache(self):
+ self._conv_num = count_conv3d(self.decoder)
+ self._conv_idx = [0]
+ self._feat_map = [None] * self._conv_num
+ #cache encode
+ self._enc_conv_num = count_conv3d(self.encoder)
+ self._enc_conv_idx = [0]
+ self._enc_feat_map = [None] * self._enc_conv_num
+
+
+def _video_vae(pretrained_path=None, z_dim=None, device='cpu', **kwargs):
+ """
+ Autoencoder3d adapted from Stable Diffusion 1.x, 2.x and XL.
+ """
+ # params
+ cfg = dict(
+ dim=96,
+ z_dim=z_dim,
+ dim_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ attn_scales=[],
+ temperal_downsample=[False, True, True],
+ dropout=0.0)
+ cfg.update(**kwargs)
+
+ # init model
+ with torch.device('meta'):
+ model = WanVAE_(**cfg)
+
+ # load checkpoint
+ logging.info(f'loading {pretrained_path}')
+ model.load_state_dict(
+ torch.load(pretrained_path, map_location=device), assign=True)
+
+ return model
+
+
+class Wan2_1_VAE:
+
+ def __init__(self,
+ z_dim=16,
+ vae_pth='cache/vae_step_411000.pth',
+ dtype=torch.float,
+ device="cuda"):
+ self.dtype = dtype
+ self.device = device
+
+ mean = [
+ -0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508,
+ 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921
+ ]
+ std = [
+ 2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743,
+ 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160
+ ]
+ self.mean = torch.tensor(mean, dtype=dtype, device=device)
+ self.std = torch.tensor(std, dtype=dtype, device=device)
+ self.scale = [self.mean, 1.0 / self.std]
+
+ # init model
+ self.model = _video_vae(
+ pretrained_path=vae_pth,
+ z_dim=z_dim,
+ ).eval().requires_grad_(False).to(device)
+
+ def encode(self, videos):
+ """
+ videos: A list of videos each with shape [C, T, H, W].
+ """
+ with amp.autocast(dtype=self.dtype):
+ return [
+ self.model.encode(u.unsqueeze(0), self.scale).float().squeeze(0)
+ for u in videos
+ ]
+
+ def decode(self, zs):
+ with amp.autocast(dtype=self.dtype):
+ return [
+ self.model.decode(u.unsqueeze(0),
+ self.scale).float().clamp_(-1, 1).squeeze(0)
+ for u in zs
+ ]
diff --git a/wan/modules/vae2_2.py b/wan/modules/vae2_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f860d7a099205f6ab61b331952cc9e056e80e2a
--- /dev/null
+++ b/wan/modules/vae2_2.py
@@ -0,0 +1,1051 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import logging
+
+import torch
+import torch.cuda.amp as amp
+import torch.nn as nn
+import torch.nn.functional as F
+from einops import rearrange
+
+__all__ = [
+ "Wan2_2_VAE",
+]
+
+CACHE_T = 2
+
+
+class CausalConv3d(nn.Conv3d):
+ """
+ Causal 3d convolusion.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self._padding = (
+ self.padding[2],
+ self.padding[2],
+ self.padding[1],
+ self.padding[1],
+ 2 * self.padding[0],
+ 0,
+ )
+ self.padding = (0, 0, 0)
+
+ def forward(self, x, cache_x=None):
+ padding = list(self._padding)
+ if cache_x is not None and self._padding[4] > 0:
+ cache_x = cache_x.to(x.device)
+ x = torch.cat([cache_x, x], dim=2)
+ padding[4] -= cache_x.shape[2]
+ x = F.pad(x, padding)
+
+ return super().forward(x)
+
+
+class RMS_norm(nn.Module):
+
+ def __init__(self, dim, channel_first=True, images=True, bias=False):
+ super().__init__()
+ broadcastable_dims = (1, 1, 1) if not images else (1, 1)
+ shape = (dim, *broadcastable_dims) if channel_first else (dim,)
+
+ self.channel_first = channel_first
+ self.scale = dim**0.5
+ self.gamma = nn.Parameter(torch.ones(shape))
+ self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.0
+
+ def forward(self, x):
+ return (F.normalize(x, dim=(1 if self.channel_first else -1)) *
+ self.scale * self.gamma + self.bias)
+
+
+class Upsample(nn.Upsample):
+
+ def forward(self, x):
+ """
+ Fix bfloat16 support for nearest neighbor interpolation.
+ """
+ return super().forward(x.float()).type_as(x)
+
+
+class Resample(nn.Module):
+
+ def __init__(self, dim, mode):
+ assert mode in (
+ "none",
+ "upsample2d",
+ "upsample3d",
+ "downsample2d",
+ "downsample3d",
+ )
+ super().__init__()
+ self.dim = dim
+ self.mode = mode
+
+ # layers
+ if mode == "upsample2d":
+ self.resample = nn.Sequential(
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
+ nn.Conv2d(dim, dim, 3, padding=1),
+ )
+ elif mode == "upsample3d":
+ self.resample = nn.Sequential(
+ Upsample(scale_factor=(2.0, 2.0), mode="nearest-exact"),
+ nn.Conv2d(dim, dim, 3, padding=1),
+ # nn.Conv2d(dim, dim//2, 3, padding=1)
+ )
+ self.time_conv = CausalConv3d(
+ dim, dim * 2, (3, 1, 1), padding=(1, 0, 0))
+ elif mode == "downsample2d":
+ self.resample = nn.Sequential(
+ nn.ZeroPad2d((0, 1, 0, 1)),
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
+ elif mode == "downsample3d":
+ self.resample = nn.Sequential(
+ nn.ZeroPad2d((0, 1, 0, 1)),
+ nn.Conv2d(dim, dim, 3, stride=(2, 2)))
+ self.time_conv = CausalConv3d(
+ dim, dim, (3, 1, 1), stride=(2, 1, 1), padding=(0, 0, 0))
+ else:
+ self.resample = nn.Identity()
+
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
+ b, c, t, h, w = x.size()
+ if self.mode == "upsample3d":
+ if feat_cache is not None:
+ idx = feat_idx[0]
+ if feat_cache[idx] is None:
+ feat_cache[idx] = "Rep"
+ feat_idx[0] += 1
+ else:
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if (cache_x.shape[2] < 2 and feat_cache[idx] is not None and
+ feat_cache[idx] != "Rep"):
+ # cache last frame of last two chunk
+ cache_x = torch.cat(
+ [
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device),
+ cache_x,
+ ],
+ dim=2,
+ )
+ if (cache_x.shape[2] < 2 and feat_cache[idx] is not None and
+ feat_cache[idx] == "Rep"):
+ cache_x = torch.cat(
+ [
+ torch.zeros_like(cache_x).to(cache_x.device),
+ cache_x
+ ],
+ dim=2,
+ )
+ if feat_cache[idx] == "Rep":
+ x = self.time_conv(x)
+ else:
+ x = self.time_conv(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ x = x.reshape(b, 2, c, t, h, w)
+ x = torch.stack((x[:, 0, :, :, :, :], x[:, 1, :, :, :, :]),
+ 3)
+ x = x.reshape(b, c, t * 2, h, w)
+ t = x.shape[2]
+ x = rearrange(x, "b c t h w -> (b t) c h w")
+ x = self.resample(x)
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=t)
+
+ if self.mode == "downsample3d":
+ if feat_cache is not None:
+ idx = feat_idx[0]
+ if feat_cache[idx] is None:
+ feat_cache[idx] = x.clone()
+ feat_idx[0] += 1
+ else:
+ cache_x = x[:, :, -1:, :, :].clone()
+ x = self.time_conv(
+ torch.cat([feat_cache[idx][:, :, -1:, :, :], x], 2))
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ return x
+
+ def init_weight(self, conv):
+ conv_weight = conv.weight.detach().clone()
+ nn.init.zeros_(conv_weight)
+ c1, c2, t, h, w = conv_weight.size()
+ one_matrix = torch.eye(c1, c2)
+ init_matrix = one_matrix
+ nn.init.zeros_(conv_weight)
+ conv_weight.data[:, :, 1, 0, 0] = init_matrix # * 0.5
+ conv.weight = nn.Parameter(conv_weight)
+ nn.init.zeros_(conv.bias.data)
+
+ def init_weight2(self, conv):
+ conv_weight = conv.weight.data.detach().clone()
+ nn.init.zeros_(conv_weight)
+ c1, c2, t, h, w = conv_weight.size()
+ init_matrix = torch.eye(c1 // 2, c2)
+ conv_weight[:c1 // 2, :, -1, 0, 0] = init_matrix
+ conv_weight[c1 // 2:, :, -1, 0, 0] = init_matrix
+ conv.weight = nn.Parameter(conv_weight)
+ nn.init.zeros_(conv.bias.data)
+
+
+class ResidualBlock(nn.Module):
+
+ def __init__(self, in_dim, out_dim, dropout=0.0):
+ super().__init__()
+ self.in_dim = in_dim
+ self.out_dim = out_dim
+
+ # layers
+ self.residual = nn.Sequential(
+ RMS_norm(in_dim, images=False),
+ nn.SiLU(),
+ CausalConv3d(in_dim, out_dim, 3, padding=1),
+ RMS_norm(out_dim, images=False),
+ nn.SiLU(),
+ nn.Dropout(dropout),
+ CausalConv3d(out_dim, out_dim, 3, padding=1),
+ )
+ self.shortcut = (
+ CausalConv3d(in_dim, out_dim, 1)
+ if in_dim != out_dim else nn.Identity())
+
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
+ h = self.shortcut(x)
+ for layer in self.residual:
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ # cache last frame of last two chunk
+ cache_x = torch.cat(
+ [
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device),
+ cache_x,
+ ],
+ dim=2,
+ )
+ x = layer(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = layer(x)
+ return x + h
+
+
+class AttentionBlock(nn.Module):
+ """
+ Causal self-attention with a single head.
+ """
+
+ def __init__(self, dim):
+ super().__init__()
+ self.dim = dim
+
+ # layers
+ self.norm = RMS_norm(dim)
+ self.to_qkv = nn.Conv2d(dim, dim * 3, 1)
+ self.proj = nn.Conv2d(dim, dim, 1)
+
+ # zero out the last layer params
+ nn.init.zeros_(self.proj.weight)
+
+ def forward(self, x):
+ identity = x
+ b, c, t, h, w = x.size()
+ x = rearrange(x, "b c t h w -> (b t) c h w")
+ x = self.norm(x)
+ # compute query, key, value
+ q, k, v = (
+ self.to_qkv(x).reshape(b * t, 1, c * 3,
+ -1).permute(0, 1, 3,
+ 2).contiguous().chunk(3, dim=-1))
+
+ # apply attention
+ x = F.scaled_dot_product_attention(
+ q,
+ k,
+ v,
+ )
+ x = x.squeeze(1).permute(0, 2, 1).reshape(b * t, c, h, w)
+
+ # output
+ x = self.proj(x)
+ x = rearrange(x, "(b t) c h w-> b c t h w", t=t)
+ return x + identity
+
+
+def patchify(x, patch_size):
+ if patch_size == 1:
+ return x
+ if x.dim() == 4:
+ x = rearrange(
+ x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size, r=patch_size)
+ elif x.dim() == 5:
+ x = rearrange(
+ x,
+ "b c f (h q) (w r) -> b (c r q) f h w",
+ q=patch_size,
+ r=patch_size,
+ )
+ else:
+ raise ValueError(f"Invalid input shape: {x.shape}")
+
+ return x
+
+
+def unpatchify(x, patch_size):
+ if patch_size == 1:
+ return x
+
+ if x.dim() == 4:
+ x = rearrange(
+ x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size, r=patch_size)
+ elif x.dim() == 5:
+ x = rearrange(
+ x,
+ "b (c r q) f h w -> b c f (h q) (w r)",
+ q=patch_size,
+ r=patch_size,
+ )
+ return x
+
+
+class AvgDown3D(nn.Module):
+
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ factor_t,
+ factor_s=1,
+ ):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.factor_t = factor_t
+ self.factor_s = factor_s
+ self.factor = self.factor_t * self.factor_s * self.factor_s
+
+ assert in_channels * self.factor % out_channels == 0
+ self.group_size = in_channels * self.factor // out_channels
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ pad_t = (self.factor_t - x.shape[2] % self.factor_t) % self.factor_t
+ pad = (0, 0, 0, 0, pad_t, 0)
+ x = F.pad(x, pad)
+ B, C, T, H, W = x.shape
+ x = x.view(
+ B,
+ C,
+ T // self.factor_t,
+ self.factor_t,
+ H // self.factor_s,
+ self.factor_s,
+ W // self.factor_s,
+ self.factor_s,
+ )
+ x = x.permute(0, 1, 3, 5, 7, 2, 4, 6).contiguous()
+ x = x.view(
+ B,
+ C * self.factor,
+ T // self.factor_t,
+ H // self.factor_s,
+ W // self.factor_s,
+ )
+ x = x.view(
+ B,
+ self.out_channels,
+ self.group_size,
+ T // self.factor_t,
+ H // self.factor_s,
+ W // self.factor_s,
+ )
+ x = x.mean(dim=2)
+ return x
+
+
+class DupUp3D(nn.Module):
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ factor_t,
+ factor_s=1,
+ ):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+
+ self.factor_t = factor_t
+ self.factor_s = factor_s
+ self.factor = self.factor_t * self.factor_s * self.factor_s
+
+ assert out_channels * self.factor % in_channels == 0
+ self.repeats = out_channels * self.factor // in_channels
+
+ def forward(self, x: torch.Tensor, first_chunk=False) -> torch.Tensor:
+ x = x.repeat_interleave(self.repeats, dim=1)
+ x = x.view(
+ x.size(0),
+ self.out_channels,
+ self.factor_t,
+ self.factor_s,
+ self.factor_s,
+ x.size(2),
+ x.size(3),
+ x.size(4),
+ )
+ x = x.permute(0, 1, 5, 2, 6, 3, 7, 4).contiguous()
+ x = x.view(
+ x.size(0),
+ self.out_channels,
+ x.size(2) * self.factor_t,
+ x.size(4) * self.factor_s,
+ x.size(6) * self.factor_s,
+ )
+ if first_chunk:
+ x = x[:, :, self.factor_t - 1:, :, :]
+ return x
+
+
+class Down_ResidualBlock(nn.Module):
+
+ def __init__(self,
+ in_dim,
+ out_dim,
+ dropout,
+ mult,
+ temperal_downsample=False,
+ down_flag=False):
+ super().__init__()
+
+ # Shortcut path with downsample
+ self.avg_shortcut = AvgDown3D(
+ in_dim,
+ out_dim,
+ factor_t=2 if temperal_downsample else 1,
+ factor_s=2 if down_flag else 1,
+ )
+
+ # Main path with residual blocks and downsample
+ downsamples = []
+ for _ in range(mult):
+ downsamples.append(ResidualBlock(in_dim, out_dim, dropout))
+ in_dim = out_dim
+
+ # Add the final downsample block
+ if down_flag:
+ mode = "downsample3d" if temperal_downsample else "downsample2d"
+ downsamples.append(Resample(out_dim, mode=mode))
+
+ self.downsamples = nn.Sequential(*downsamples)
+
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
+ x_copy = x.clone()
+ for module in self.downsamples:
+ x = module(x, feat_cache, feat_idx)
+
+ return x + self.avg_shortcut(x_copy)
+
+
+class Up_ResidualBlock(nn.Module):
+
+ def __init__(self,
+ in_dim,
+ out_dim,
+ dropout,
+ mult,
+ temperal_upsample=False,
+ up_flag=False):
+ super().__init__()
+ # Shortcut path with upsample
+ if up_flag:
+ self.avg_shortcut = DupUp3D(
+ in_dim,
+ out_dim,
+ factor_t=2 if temperal_upsample else 1,
+ factor_s=2 if up_flag else 1,
+ )
+ else:
+ self.avg_shortcut = None
+
+ # Main path with residual blocks and upsample
+ upsamples = []
+ for _ in range(mult):
+ upsamples.append(ResidualBlock(in_dim, out_dim, dropout))
+ in_dim = out_dim
+
+ # Add the final upsample block
+ if up_flag:
+ mode = "upsample3d" if temperal_upsample else "upsample2d"
+ upsamples.append(Resample(out_dim, mode=mode))
+
+ self.upsamples = nn.Sequential(*upsamples)
+
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
+ x_main = x.clone()
+ for module in self.upsamples:
+ x_main = module(x_main, feat_cache, feat_idx)
+ if self.avg_shortcut is not None:
+ x_shortcut = self.avg_shortcut(x, first_chunk)
+ return x_main + x_shortcut
+ else:
+ return x_main
+
+
+class Encoder3d(nn.Module):
+
+ def __init__(
+ self,
+ dim=128,
+ z_dim=4,
+ dim_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ attn_scales=[],
+ temperal_downsample=[True, True, False],
+ dropout=0.0,
+ ):
+ super().__init__()
+ self.dim = dim
+ self.z_dim = z_dim
+ self.dim_mult = dim_mult
+ self.num_res_blocks = num_res_blocks
+ self.attn_scales = attn_scales
+ self.temperal_downsample = temperal_downsample
+
+ # dimensions
+ dims = [dim * u for u in [1] + dim_mult]
+ scale = 1.0
+
+ # init block
+ self.conv1 = CausalConv3d(12, dims[0], 3, padding=1)
+
+ # downsample blocks
+ downsamples = []
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
+ t_down_flag = (
+ temperal_downsample[i]
+ if i < len(temperal_downsample) else False)
+ downsamples.append(
+ Down_ResidualBlock(
+ in_dim=in_dim,
+ out_dim=out_dim,
+ dropout=dropout,
+ mult=num_res_blocks,
+ temperal_downsample=t_down_flag,
+ down_flag=i != len(dim_mult) - 1,
+ ))
+ scale /= 2.0
+ self.downsamples = nn.Sequential(*downsamples)
+
+ # middle blocks
+ self.middle = nn.Sequential(
+ ResidualBlock(out_dim, out_dim, dropout),
+ AttentionBlock(out_dim),
+ ResidualBlock(out_dim, out_dim, dropout),
+ )
+
+ # # output blocks
+ self.head = nn.Sequential(
+ RMS_norm(out_dim, images=False),
+ nn.SiLU(),
+ CausalConv3d(out_dim, z_dim, 3, padding=1),
+ )
+
+ def forward(self, x, feat_cache=None, feat_idx=[0]):
+
+ if feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ cache_x = torch.cat(
+ [
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device),
+ cache_x,
+ ],
+ dim=2,
+ )
+ x = self.conv1(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = self.conv1(x)
+
+ ## downsamples
+ for layer in self.downsamples:
+ if feat_cache is not None:
+ x = layer(x, feat_cache, feat_idx)
+ else:
+ x = layer(x)
+
+ ## middle
+ for layer in self.middle:
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
+ x = layer(x, feat_cache, feat_idx)
+ else:
+ x = layer(x)
+
+ ## head
+ for layer in self.head:
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ cache_x = torch.cat(
+ [
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device),
+ cache_x,
+ ],
+ dim=2,
+ )
+ x = layer(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = layer(x)
+
+ return x
+
+
+class Decoder3d(nn.Module):
+
+ def __init__(
+ self,
+ dim=128,
+ z_dim=4,
+ dim_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ attn_scales=[],
+ temperal_upsample=[False, True, True],
+ dropout=0.0,
+ ):
+ super().__init__()
+ self.dim = dim
+ self.z_dim = z_dim
+ self.dim_mult = dim_mult
+ self.num_res_blocks = num_res_blocks
+ self.attn_scales = attn_scales
+ self.temperal_upsample = temperal_upsample
+
+ # dimensions
+ dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]]
+ scale = 1.0 / 2**(len(dim_mult) - 2)
+ # init block
+ self.conv1 = CausalConv3d(z_dim, dims[0], 3, padding=1)
+
+ # middle blocks
+ self.middle = nn.Sequential(
+ ResidualBlock(dims[0], dims[0], dropout),
+ AttentionBlock(dims[0]),
+ ResidualBlock(dims[0], dims[0], dropout),
+ )
+
+ # upsample blocks
+ upsamples = []
+ for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])):
+ t_up_flag = temperal_upsample[i] if i < len(
+ temperal_upsample) else False
+ upsamples.append(
+ Up_ResidualBlock(
+ in_dim=in_dim,
+ out_dim=out_dim,
+ dropout=dropout,
+ mult=num_res_blocks + 1,
+ temperal_upsample=t_up_flag,
+ up_flag=i != len(dim_mult) - 1,
+ ))
+ self.upsamples = nn.Sequential(*upsamples)
+
+ # output blocks
+ self.head = nn.Sequential(
+ RMS_norm(out_dim, images=False),
+ nn.SiLU(),
+ CausalConv3d(out_dim, 12, 3, padding=1),
+ )
+
+ def forward(self, x, feat_cache=None, feat_idx=[0], first_chunk=False):
+ if feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ cache_x = torch.cat(
+ [
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device),
+ cache_x,
+ ],
+ dim=2,
+ )
+ x = self.conv1(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = self.conv1(x)
+
+ for layer in self.middle:
+ if isinstance(layer, ResidualBlock) and feat_cache is not None:
+ x = layer(x, feat_cache, feat_idx)
+ else:
+ x = layer(x)
+
+ ## upsamples
+ for layer in self.upsamples:
+ if feat_cache is not None:
+ x = layer(x, feat_cache, feat_idx, first_chunk)
+ else:
+ x = layer(x)
+
+ ## head
+ for layer in self.head:
+ if isinstance(layer, CausalConv3d) and feat_cache is not None:
+ idx = feat_idx[0]
+ cache_x = x[:, :, -CACHE_T:, :, :].clone()
+ if cache_x.shape[2] < 2 and feat_cache[idx] is not None:
+ cache_x = torch.cat(
+ [
+ feat_cache[idx][:, :, -1, :, :].unsqueeze(2).to(
+ cache_x.device),
+ cache_x,
+ ],
+ dim=2,
+ )
+ x = layer(x, feat_cache[idx])
+ feat_cache[idx] = cache_x
+ feat_idx[0] += 1
+ else:
+ x = layer(x)
+ return x
+
+
+def count_conv3d(model):
+ count = 0
+ for m in model.modules():
+ if isinstance(m, CausalConv3d):
+ count += 1
+ return count
+
+
+class WanVAE_(nn.Module):
+
+ def __init__(
+ self,
+ dim=160,
+ dec_dim=256,
+ z_dim=16,
+ dim_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ attn_scales=[],
+ temperal_downsample=[True, True, False],
+ dropout=0.0,
+ ):
+ super().__init__()
+ self.dim = dim
+ self.z_dim = z_dim
+ self.dim_mult = dim_mult
+ self.num_res_blocks = num_res_blocks
+ self.attn_scales = attn_scales
+ self.temperal_downsample = temperal_downsample
+ self.temperal_upsample = temperal_downsample[::-1]
+
+ # modules
+ self.encoder = Encoder3d(
+ dim,
+ z_dim * 2,
+ dim_mult,
+ num_res_blocks,
+ attn_scales,
+ self.temperal_downsample,
+ dropout,
+ )
+ self.conv1 = CausalConv3d(z_dim * 2, z_dim * 2, 1)
+ self.conv2 = CausalConv3d(z_dim, z_dim, 1)
+ self.decoder = Decoder3d(
+ dec_dim,
+ z_dim,
+ dim_mult,
+ num_res_blocks,
+ attn_scales,
+ self.temperal_upsample,
+ dropout,
+ )
+
+ def forward(self, x, scale=[0, 1]):
+ mu = self.encode(x, scale)
+ x_recon = self.decode(mu, scale)
+ return x_recon, mu
+
+ def encode(self, x, scale):
+ self.clear_cache()
+ x = patchify(x, patch_size=2)
+ t = x.shape[2]
+ iter_ = 1 + (t - 1) // 4
+ for i in range(iter_):
+ self._enc_conv_idx = [0]
+ if i == 0:
+ out = self.encoder(
+ x[:, :, :1, :, :],
+ feat_cache=self._enc_feat_map,
+ feat_idx=self._enc_conv_idx,
+ )
+ else:
+ out_ = self.encoder(
+ x[:, :, 1 + 4 * (i - 1):1 + 4 * i, :, :],
+ feat_cache=self._enc_feat_map,
+ feat_idx=self._enc_conv_idx,
+ )
+ out = torch.cat([out, out_], 2)
+ mu, log_var = self.conv1(out).chunk(2, dim=1)
+ if isinstance(scale[0], torch.Tensor):
+ mu = (mu - scale[0].view(1, self.z_dim, 1, 1, 1)) * scale[1].view(
+ 1, self.z_dim, 1, 1, 1)
+ else:
+ mu = (mu - scale[0]) * scale[1]
+ self.clear_cache()
+ return mu
+
+ def decode(self, z, scale):
+ self.clear_cache()
+ if isinstance(scale[0], torch.Tensor):
+ z = z / scale[1].view(1, self.z_dim, 1, 1, 1) + scale[0].view(
+ 1, self.z_dim, 1, 1, 1)
+ else:
+ z = z / scale[1] + scale[0]
+ iter_ = z.shape[2]
+ x = self.conv2(z)
+ for i in range(iter_):
+ self._conv_idx = [0]
+ if i == 0:
+ out = self.decoder(
+ x[:, :, i:i + 1, :, :],
+ feat_cache=self._feat_map,
+ feat_idx=self._conv_idx,
+ first_chunk=True,
+ )
+ else:
+ out_ = self.decoder(
+ x[:, :, i:i + 1, :, :],
+ feat_cache=self._feat_map,
+ feat_idx=self._conv_idx,
+ )
+ out = torch.cat([out, out_], 2)
+ out = unpatchify(out, patch_size=2)
+ self.clear_cache()
+ return out
+
+ def reparameterize(self, mu, log_var):
+ std = torch.exp(0.5 * log_var)
+ eps = torch.randn_like(std)
+ return eps * std + mu
+
+ def sample(self, imgs, deterministic=False):
+ mu, log_var = self.encode(imgs)
+ if deterministic:
+ return mu
+ std = torch.exp(0.5 * log_var.clamp(-30.0, 20.0))
+ return mu + std * torch.randn_like(std)
+
+ def clear_cache(self):
+ self._conv_num = count_conv3d(self.decoder)
+ self._conv_idx = [0]
+ self._feat_map = [None] * self._conv_num
+ # cache encode
+ self._enc_conv_num = count_conv3d(self.encoder)
+ self._enc_conv_idx = [0]
+ self._enc_feat_map = [None] * self._enc_conv_num
+
+
+def _video_vae(pretrained_path=None, z_dim=16, dim=160, device="cpu", **kwargs):
+ # params
+ cfg = dict(
+ dim=dim,
+ z_dim=z_dim,
+ dim_mult=[1, 2, 4, 4],
+ num_res_blocks=2,
+ attn_scales=[],
+ temperal_downsample=[True, True, True],
+ dropout=0.0,
+ )
+ cfg.update(**kwargs)
+
+ # init model
+ with torch.device("meta"):
+ model = WanVAE_(**cfg)
+
+ # load checkpoint
+ logging.info(f"loading {pretrained_path}")
+ model.load_state_dict(
+ torch.load(pretrained_path, map_location=device), assign=True)
+
+ return model
+
+
+class Wan2_2_VAE:
+
+ def __init__(
+ self,
+ z_dim=48,
+ c_dim=160,
+ vae_pth=None,
+ dim_mult=[1, 2, 4, 4],
+ temperal_downsample=[False, True, True],
+ dtype=torch.float,
+ device="cuda",
+ ):
+
+ self.dtype = dtype
+ self.device = device
+
+ mean = torch.tensor(
+ [
+ -0.2289,
+ -0.0052,
+ -0.1323,
+ -0.2339,
+ -0.2799,
+ 0.0174,
+ 0.1838,
+ 0.1557,
+ -0.1382,
+ 0.0542,
+ 0.2813,
+ 0.0891,
+ 0.1570,
+ -0.0098,
+ 0.0375,
+ -0.1825,
+ -0.2246,
+ -0.1207,
+ -0.0698,
+ 0.5109,
+ 0.2665,
+ -0.2108,
+ -0.2158,
+ 0.2502,
+ -0.2055,
+ -0.0322,
+ 0.1109,
+ 0.1567,
+ -0.0729,
+ 0.0899,
+ -0.2799,
+ -0.1230,
+ -0.0313,
+ -0.1649,
+ 0.0117,
+ 0.0723,
+ -0.2839,
+ -0.2083,
+ -0.0520,
+ 0.3748,
+ 0.0152,
+ 0.1957,
+ 0.1433,
+ -0.2944,
+ 0.3573,
+ -0.0548,
+ -0.1681,
+ -0.0667,
+ ],
+ dtype=dtype,
+ device=device,
+ )
+ std = torch.tensor(
+ [
+ 0.4765,
+ 1.0364,
+ 0.4514,
+ 1.1677,
+ 0.5313,
+ 0.4990,
+ 0.4818,
+ 0.5013,
+ 0.8158,
+ 1.0344,
+ 0.5894,
+ 1.0901,
+ 0.6885,
+ 0.6165,
+ 0.8454,
+ 0.4978,
+ 0.5759,
+ 0.3523,
+ 0.7135,
+ 0.6804,
+ 0.5833,
+ 1.4146,
+ 0.8986,
+ 0.5659,
+ 0.7069,
+ 0.5338,
+ 0.4889,
+ 0.4917,
+ 0.4069,
+ 0.4999,
+ 0.6866,
+ 0.4093,
+ 0.5709,
+ 0.6065,
+ 0.6415,
+ 0.4944,
+ 0.5726,
+ 1.2042,
+ 0.5458,
+ 1.6887,
+ 0.3971,
+ 1.0600,
+ 0.3943,
+ 0.5537,
+ 0.5444,
+ 0.4089,
+ 0.7468,
+ 0.7744,
+ ],
+ dtype=dtype,
+ device=device,
+ )
+ self.scale = [mean, 1.0 / std]
+
+ # init model
+ self.model = (
+ _video_vae(
+ pretrained_path=vae_pth,
+ z_dim=z_dim,
+ dim=c_dim,
+ dim_mult=dim_mult,
+ temperal_downsample=temperal_downsample,
+ ).eval().requires_grad_(False).to(device))
+
+ def encode(self, videos):
+ try:
+ if not isinstance(videos, list):
+ raise TypeError("videos should be a list")
+ with amp.autocast(dtype=self.dtype):
+ return [
+ self.model.encode(u.unsqueeze(0),
+ self.scale).float().squeeze(0)
+ for u in videos
+ ]
+ except TypeError as e:
+ logging.info(e)
+ return None
+
+ def decode(self, zs):
+ try:
+ if not isinstance(zs, list):
+ raise TypeError("zs should be a list")
+ with amp.autocast(dtype=self.dtype):
+ return [
+ self.model.decode(u.unsqueeze(0),
+ self.scale).float().clamp_(-1,
+ 1).squeeze(0)
+ for u in zs
+ ]
+ except TypeError as e:
+ logging.info(e)
+ return None
diff --git a/wan/speech2video.py b/wan/speech2video.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bf611c9c3bf566eba424be5a514f4e9b7873e65
--- /dev/null
+++ b/wan/speech2video.py
@@ -0,0 +1,707 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import gc
+import logging
+import math
+import os
+import random
+import sys
+import types
+from contextlib import contextmanager
+from copy import deepcopy
+from functools import partial
+
+import numpy as np
+import torch
+import torch.cuda.amp as amp
+import torch.distributed as dist
+import torchvision.transforms.functional as TF
+from decord import VideoReader
+from PIL import Image
+from safetensors import safe_open
+from torchvision import transforms
+from tqdm import tqdm
+
+from .distributed.fsdp import shard_model
+from .distributed.sequence_parallel import sp_attn_forward, sp_dit_forward
+from .distributed.util import get_world_size
+from .modules.s2v.audio_encoder import AudioEncoder
+from .modules.s2v.model_s2v import WanModel_S2V, sp_attn_forward_s2v
+from .modules.t5 import T5EncoderModel
+from .modules.vae2_1 import Wan2_1_VAE
+from .utils.fm_solvers import (
+ FlowDPMSolverMultistepScheduler,
+ get_sampling_sigmas,
+ retrieve_timesteps,
+)
+from .utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
+
+
+def load_safetensors(path):
+ tensors = {}
+ with safe_open(path, framework="pt", device="cpu") as f:
+ for key in f.keys():
+ tensors[key] = f.get_tensor(key)
+ return tensors
+
+
+class WanS2V:
+
+ def __init__(
+ self,
+ config,
+ checkpoint_dir,
+ device_id=0,
+ rank=0,
+ t5_fsdp=False,
+ dit_fsdp=False,
+ use_sp=False,
+ t5_cpu=False,
+ init_on_cpu=True,
+ convert_model_dtype=False,
+ ):
+ r"""
+ Initializes the image-to-video generation model components.
+
+ Args:
+ config (EasyDict):
+ Object containing model parameters initialized from config.py
+ checkpoint_dir (`str`):
+ Path to directory containing model checkpoints
+ device_id (`int`, *optional*, defaults to 0):
+ Id of target GPU device
+ rank (`int`, *optional*, defaults to 0):
+ Process rank for distributed training
+ t5_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for T5 model
+ dit_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for DiT model
+ use_sp (`bool`, *optional*, defaults to False):
+ Enable distribution strategy of sequence parallel.
+ t5_cpu (`bool`, *optional*, defaults to False):
+ Whether to place T5 model on CPU. Only works without t5_fsdp.
+ init_on_cpu (`bool`, *optional*, defaults to True):
+ Enable initializing Transformer Model on CPU. Only works without FSDP or USP.
+ convert_model_dtype (`bool`, *optional*, defaults to False):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+ """
+ self.device = torch.device(f"cuda:{device_id}")
+ self.config = config
+ self.rank = rank
+ self.t5_cpu = t5_cpu
+ self.init_on_cpu = init_on_cpu
+
+ self.num_train_timesteps = config.num_train_timesteps
+ self.param_dtype = config.param_dtype
+
+ if t5_fsdp or dit_fsdp or use_sp:
+ self.init_on_cpu = False
+
+ shard_fn = partial(shard_model, device_id=device_id)
+ self.text_encoder = T5EncoderModel(
+ text_len=config.text_len,
+ dtype=config.t5_dtype,
+ device=torch.device('cpu'),
+ checkpoint_path=os.path.join(checkpoint_dir, config.t5_checkpoint),
+ tokenizer_path=os.path.join(checkpoint_dir, config.t5_tokenizer),
+ shard_fn=shard_fn if t5_fsdp else None,
+ )
+
+ self.vae = Wan2_1_VAE(
+ vae_pth=os.path.join(checkpoint_dir, config.vae_checkpoint),
+ device=self.device)
+
+ logging.info(f"Creating WanModel from {checkpoint_dir}")
+ if not dit_fsdp:
+ self.noise_model = WanModel_S2V.from_pretrained(
+ checkpoint_dir,
+ torch_dtype=self.param_dtype,
+ device_map=self.device)
+ else:
+ self.noise_model = WanModel_S2V.from_pretrained(
+ checkpoint_dir, torch_dtype=self.param_dtype)
+
+ self.noise_model = self._configure_model(
+ model=self.noise_model,
+ use_sp=use_sp,
+ dit_fsdp=dit_fsdp,
+ shard_fn=shard_fn,
+ convert_model_dtype=convert_model_dtype)
+
+ self.audio_encoder = AudioEncoder(
+ model_id=os.path.join(checkpoint_dir,
+ "wav2vec2-large-xlsr-53-english"))
+
+ if use_sp:
+ self.sp_size = get_world_size()
+ else:
+ self.sp_size = 1
+
+ self.sample_neg_prompt = config.sample_neg_prompt
+ self.motion_frames = config.transformer.motion_frames
+ self.drop_first_motion = config.drop_first_motion
+ self.fps = config.sample_fps
+ self.audio_sample_m = 0
+
+ def _configure_model(self, model, use_sp, dit_fsdp, shard_fn,
+ convert_model_dtype):
+ """
+ Configures a model object. This includes setting evaluation modes,
+ applying distributed parallel strategy, and handling device placement.
+
+ Args:
+ model (torch.nn.Module):
+ The model instance to configure.
+ use_sp (`bool`):
+ Enable distribution strategy of sequence parallel.
+ dit_fsdp (`bool`):
+ Enable FSDP sharding for DiT model.
+ shard_fn (callable):
+ The function to apply FSDP sharding.
+ convert_model_dtype (`bool`):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+
+ Returns:
+ torch.nn.Module:
+ The configured model.
+ """
+ model.eval().requires_grad_(False)
+ if use_sp:
+ for block in model.blocks:
+ block.self_attn.forward = types.MethodType(
+ sp_attn_forward_s2v, block.self_attn)
+ model.use_context_parallel = True
+
+ if dist.is_initialized():
+ dist.barrier()
+
+ if dit_fsdp:
+ model = shard_fn(model)
+ else:
+ if convert_model_dtype:
+ model.to(self.param_dtype)
+ if not self.init_on_cpu:
+ model.to(self.device)
+
+ return model
+
+ def get_size_less_than_area(self,
+ height,
+ width,
+ target_area=1024 * 704,
+ divisor=64):
+ if height * width <= target_area:
+ # If the original image area is already less than or equal to the target,
+ # no resizing is needed—just padding. Still need to ensure that the padded area doesn't exceed the target.
+ max_upper_area = target_area
+ min_scale = 0.1
+ max_scale = 1.0
+ else:
+ # Resize to fit within the target area and then pad to multiples of `divisor`
+ max_upper_area = target_area # Maximum allowed total pixel count after padding
+ d = divisor - 1
+ b = d * (height + width)
+ a = height * width
+ c = d**2 - max_upper_area
+
+ # Calculate scale boundaries using quadratic equation
+ min_scale = (-b + math.sqrt(b**2 - 2 * a * c)) / (
+ 2 * a) # Scale when maximum padding is applied
+ max_scale = math.sqrt(max_upper_area /
+ (height * width)) # Scale without any padding
+
+ # We want to choose the largest possible scale such that the final padded area does not exceed max_upper_area
+ # Use binary search-like iteration to find this scale
+ find_it = False
+ for i in range(100):
+ scale = max_scale - (max_scale - min_scale) * i / 100
+ new_height, new_width = int(height * scale), int(width * scale)
+
+ # Pad to make dimensions divisible by 64
+ pad_height = (64 - new_height % 64) % 64
+ pad_width = (64 - new_width % 64) % 64
+ pad_top = pad_height // 2
+ pad_bottom = pad_height - pad_top
+ pad_left = pad_width // 2
+ pad_right = pad_width - pad_left
+
+ padded_height, padded_width = new_height + pad_height, new_width + pad_width
+
+ if padded_height * padded_width <= max_upper_area:
+ find_it = True
+ break
+
+ if find_it:
+ return padded_height, padded_width
+ else:
+ # Fallback: calculate target dimensions based on aspect ratio and divisor alignment
+ aspect_ratio = width / height
+ target_width = int(
+ (target_area * aspect_ratio)**0.5 // divisor * divisor)
+ target_height = int(
+ (target_area / aspect_ratio)**0.5 // divisor * divisor)
+
+ # Ensure the result is not larger than the original resolution
+ if target_width >= width or target_height >= height:
+ target_width = int(width // divisor * divisor)
+ target_height = int(height // divisor * divisor)
+
+ return target_height, target_width
+
+ def prepare_default_cond_input(self,
+ map_shape=[3, 12, 64, 64],
+ motion_frames=5,
+ lat_motion_frames=2,
+ enable_mano=False,
+ enable_kp=False,
+ enable_pose=False):
+ default_value = [1.0, -1.0, -1.0]
+ cond_enable = [enable_mano, enable_kp, enable_pose]
+ cond = []
+ for d, c in zip(default_value, cond_enable):
+ if c:
+ map_value = torch.ones(
+ map_shape, dtype=self.param_dtype, device=self.device) * d
+ cond_lat = torch.cat([
+ map_value[:, :, 0:1].repeat(1, 1, motion_frames, 1, 1),
+ map_value
+ ],
+ dim=2)
+ cond_lat = torch.stack(
+ self.vae.encode(cond_lat.to(
+ self.param_dtype)))[:, :, lat_motion_frames:].to(
+ self.param_dtype)
+
+ cond.append(cond_lat)
+ if len(cond) >= 1:
+ cond = torch.cat(cond, dim=1)
+ else:
+ cond = None
+ return cond
+
+ def encode_audio(self, audio_path, infer_frames):
+ z = self.audio_encoder.extract_audio_feat(
+ audio_path, return_all_layers=True)
+ audio_embed_bucket, num_repeat = self.audio_encoder.get_audio_embed_bucket_fps(
+ z, fps=self.fps, batch_frames=infer_frames, m=self.audio_sample_m)
+ audio_embed_bucket = audio_embed_bucket.to(self.device,
+ self.param_dtype)
+ audio_embed_bucket = audio_embed_bucket.unsqueeze(0)
+ if len(audio_embed_bucket.shape) == 3:
+ audio_embed_bucket = audio_embed_bucket.permute(0, 2, 1)
+ elif len(audio_embed_bucket.shape) == 4:
+ audio_embed_bucket = audio_embed_bucket.permute(0, 2, 3, 1)
+ return audio_embed_bucket, num_repeat
+
+ def read_last_n_frames(self,
+ video_path,
+ n_frames,
+ target_fps=16,
+ reverse=False):
+ """
+ Read the last `n_frames` from a video at the specified frame rate.
+
+ Parameters:
+ video_path (str): Path to the video file.
+ n_frames (int): Number of frames to read.
+ target_fps (int, optional): Target sampling frame rate. Defaults to 16.
+ reverse (bool, optional): Whether to read frames in reverse order.
+ If True, reads the first `n_frames` instead of the last ones.
+
+ Returns:
+ np.ndarray: A NumPy array of shape [n_frames, H, W, 3], representing the sampled video frames.
+ """
+ vr = VideoReader(video_path)
+ original_fps = vr.get_avg_fps()
+ total_frames = len(vr)
+
+ interval = max(1, round(original_fps / target_fps))
+
+ required_span = (n_frames - 1) * interval
+
+ start_frame = max(0, total_frames - required_span -
+ 1) if not reverse else 0
+
+ sampled_indices = []
+ for i in range(n_frames):
+ indice = start_frame + i * interval
+ if indice >= total_frames:
+ break
+ else:
+ sampled_indices.append(indice)
+
+ return vr.get_batch(sampled_indices).asnumpy()
+
+ def load_pose_cond(self, pose_video, num_repeat, infer_frames, size):
+ HEIGHT, WIDTH = size
+ if not pose_video is None:
+ pose_seq = self.read_last_n_frames(
+ pose_video,
+ n_frames=infer_frames * num_repeat,
+ target_fps=self.fps,
+ reverse=True)
+
+ resize_opreat = transforms.Resize(min(HEIGHT, WIDTH))
+ crop_opreat = transforms.CenterCrop((HEIGHT, WIDTH))
+ tensor_trans = transforms.ToTensor()
+
+ cond_tensor = torch.from_numpy(pose_seq)
+ cond_tensor = cond_tensor.permute(0, 3, 1, 2) / 255.0 * 2 - 1.0
+ cond_tensor = crop_opreat(resize_opreat(cond_tensor)).permute(
+ 1, 0, 2, 3).unsqueeze(0)
+
+ padding_frame_num = num_repeat * infer_frames - cond_tensor.shape[2]
+ cond_tensor = torch.cat([
+ cond_tensor,
+ - torch.ones([1, 3, padding_frame_num, HEIGHT, WIDTH])
+ ],
+ dim=2)
+
+ cond_tensors = torch.chunk(cond_tensor, num_repeat, dim=2)
+ else:
+ cond_tensors = [-torch.ones([1, 3, infer_frames, HEIGHT, WIDTH])]
+
+ COND = []
+ for r in range(len(cond_tensors)):
+ cond = cond_tensors[r]
+ cond = torch.cat([cond[:, :, 0:1].repeat(1, 1, 1, 1, 1), cond],
+ dim=2)
+ cond_lat = torch.stack(
+ self.vae.encode(
+ cond.to(dtype=self.param_dtype,
+ device=self.device)))[:, :,
+ 1:].cpu() # for mem save
+ COND.append(cond_lat)
+ return COND
+
+ def get_gen_size(self, size, max_area, ref_image_path, pre_video_path):
+ if not size is None:
+ HEIGHT, WIDTH = size
+ else:
+ if pre_video_path:
+ ref_image = self.read_last_n_frames(
+ pre_video_path, n_frames=1)[0]
+ else:
+ ref_image = np.array(Image.open(ref_image_path).convert('RGB'))
+ HEIGHT, WIDTH = ref_image.shape[:2]
+ HEIGHT, WIDTH = self.get_size_less_than_area(
+ HEIGHT, WIDTH, target_area=max_area)
+ return (HEIGHT, WIDTH)
+
+ def generate(
+ self,
+ input_prompt,
+ ref_image_path,
+ audio_path,
+ enable_tts,
+ tts_prompt_audio,
+ tts_prompt_text,
+ tts_text,
+ num_repeat=1,
+ pose_video=None,
+ max_area=720 * 1280,
+ infer_frames=80,
+ shift=5.0,
+ sample_solver='unipc',
+ sampling_steps=40,
+ guide_scale=5.0,
+ n_prompt="",
+ seed=-1,
+ offload_model=True,
+ init_first_frame=False,
+ ):
+ r"""
+ Generates video frames from input image and text prompt using diffusion process.
+
+ Args:
+ input_prompt (`str`):
+ Text prompt for content generation.
+ ref_image_path ('str'):
+ Input image path
+ audio_path ('str'):
+ Audio for video driven
+ num_repeat ('int'):
+ Number of clips to generate; will be automatically adjusted based on the audio length
+ pose_video ('str'):
+ If provided, uses a sequence of poses to drive the generated video
+ max_area (`int`, *optional*, defaults to 720*1280):
+ Maximum pixel area for latent space calculation. Controls video resolution scaling
+ infer_frames (`int`, *optional*, defaults to 80):
+ How many frames to generate per clips. The number should be 4n
+ shift (`float`, *optional*, defaults to 5.0):
+ Noise schedule shift parameter. Affects temporal dynamics
+ [NOTE]: If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
+ sample_solver (`str`, *optional*, defaults to 'unipc'):
+ Solver used to sample the video.
+ sampling_steps (`int`, *optional*, defaults to 40):
+ Number of diffusion sampling steps. Higher values improve quality but slow generation
+ guide_scale (`float` or tuple[`float`], *optional*, defaults 5.0):
+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.
+ If tuple, the first guide_scale will be used for low noise model and
+ the second guide_scale will be used for high noise model.
+ n_prompt (`str`, *optional*, defaults to ""):
+ Negative prompt for content exclusion. If not given, use `config.sample_neg_prompt`
+ seed (`int`, *optional*, defaults to -1):
+ Random seed for noise generation. If -1, use random seed
+ offload_model (`bool`, *optional*, defaults to True):
+ If True, offloads models to CPU during generation to save VRAM
+ init_first_frame (`bool`, *optional*, defaults to False):
+ Whether to use the reference image as the first frame (i.e., standard image-to-video generation)
+
+ Returns:
+ torch.Tensor:
+ Generated video frames tensor. Dimensions: (C, N H, W) where:
+ - C: Color channels (3 for RGB)
+ - N: Number of frames (81)
+ - H: Frame height (from max_area)
+ - W: Frame width from max_area)
+ """
+ # preprocess
+ size = self.get_gen_size(
+ size=None,
+ max_area=max_area,
+ ref_image_path=ref_image_path,
+ pre_video_path=None)
+ HEIGHT, WIDTH = size
+ channel = 3
+
+ resize_opreat = transforms.Resize(min(HEIGHT, WIDTH))
+ crop_opreat = transforms.CenterCrop((HEIGHT, WIDTH))
+ tensor_trans = transforms.ToTensor()
+
+ ref_image = None
+ motion_latents = None
+
+ if ref_image is None:
+ ref_image = np.array(Image.open(ref_image_path).convert('RGB'))
+ if motion_latents is None:
+ motion_latents = torch.zeros(
+ [1, channel, self.motion_frames, HEIGHT, WIDTH],
+ dtype=self.param_dtype,
+ device=self.device)
+
+ # extract audio emb
+ if enable_tts is True:
+ audio_path = self.tts(tts_prompt_audio, tts_prompt_text, tts_text)
+ audio_emb, nr = self.encode_audio(audio_path, infer_frames=infer_frames)
+ if num_repeat is None or num_repeat > nr:
+ num_repeat = nr
+
+ lat_motion_frames = (self.motion_frames + 3) // 4
+ model_pic = crop_opreat(resize_opreat(Image.fromarray(ref_image)))
+
+ ref_pixel_values = tensor_trans(model_pic)
+ ref_pixel_values = ref_pixel_values.unsqueeze(1).unsqueeze(
+ 0) * 2 - 1.0 # b c 1 h w
+ ref_pixel_values = ref_pixel_values.to(
+ dtype=self.vae.dtype, device=self.vae.device)
+ ref_latents = torch.stack(self.vae.encode(ref_pixel_values))
+
+ # encode the motion latents
+ videos_last_frames = motion_latents.detach()
+ drop_first_motion = self.drop_first_motion
+ if init_first_frame:
+ drop_first_motion = False
+ motion_latents[:, :, -6:] = ref_pixel_values
+ motion_latents = torch.stack(self.vae.encode(motion_latents))
+
+ # get pose cond input if need
+ COND = self.load_pose_cond(
+ pose_video=pose_video,
+ num_repeat=num_repeat,
+ infer_frames=infer_frames,
+ size=size)
+
+ seed = seed if seed >= 0 else random.randint(0, sys.maxsize)
+
+ if n_prompt == "":
+ n_prompt = self.sample_neg_prompt
+
+ # preprocess
+ if not self.t5_cpu:
+ self.text_encoder.model.to(self.device)
+ context = self.text_encoder([input_prompt], self.device)
+ context_null = self.text_encoder([n_prompt], self.device)
+ if offload_model:
+ self.text_encoder.model.cpu()
+ else:
+ context = self.text_encoder([input_prompt], torch.device('cpu'))
+ context_null = self.text_encoder([n_prompt], torch.device('cpu'))
+ context = [t.to(self.device) for t in context]
+ context_null = [t.to(self.device) for t in context_null]
+
+ out = []
+ # evaluation mode
+ with (
+ torch.amp.autocast('cuda', dtype=self.param_dtype),
+ torch.no_grad(),
+ ):
+ for r in range(num_repeat):
+ seed_g = torch.Generator(device=self.device)
+ seed_g.manual_seed(seed + r)
+
+ lat_target_frames = (infer_frames + 3 + self.motion_frames
+ ) // 4 - lat_motion_frames
+ target_shape = [lat_target_frames, HEIGHT // 8, WIDTH // 8]
+ noise = [
+ torch.randn(
+ 16,
+ target_shape[0],
+ target_shape[1],
+ target_shape[2],
+ dtype=self.param_dtype,
+ device=self.device,
+ generator=seed_g)
+ ]
+ max_seq_len = np.prod(target_shape) // 4
+
+ if sample_solver == 'unipc':
+ sample_scheduler = FlowUniPCMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sample_scheduler.set_timesteps(
+ sampling_steps, device=self.device, shift=shift)
+ timesteps = sample_scheduler.timesteps
+ elif sample_solver == 'dpm++':
+ sample_scheduler = FlowDPMSolverMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sampling_sigmas = get_sampling_sigmas(sampling_steps, shift)
+ timesteps, _ = retrieve_timesteps(
+ sample_scheduler,
+ device=self.device,
+ sigmas=sampling_sigmas)
+ else:
+ raise NotImplementedError("Unsupported solver.")
+
+ latents = deepcopy(noise)
+ with torch.no_grad():
+ left_idx = r * infer_frames
+ right_idx = r * infer_frames + infer_frames
+ cond_latents = COND[r] if pose_video else COND[0] * 0
+ cond_latents = cond_latents.to(
+ dtype=self.param_dtype, device=self.device)
+ audio_input = audio_emb[..., left_idx:right_idx]
+ input_motion_latents = motion_latents.clone()
+
+ arg_c = {
+ 'context': context[0:1],
+ 'seq_len': max_seq_len,
+ 'cond_states': cond_latents,
+ "motion_latents": input_motion_latents,
+ 'ref_latents': ref_latents,
+ "audio_input": audio_input,
+ "motion_frames": [self.motion_frames, lat_motion_frames],
+ "drop_motion_frames": drop_first_motion and r == 0,
+ }
+ if guide_scale > 1:
+ arg_null = {
+ 'context': context_null[0:1],
+ 'seq_len': max_seq_len,
+ 'cond_states': cond_latents,
+ "motion_latents": input_motion_latents,
+ 'ref_latents': ref_latents,
+ "audio_input": 0.0 * audio_input,
+ "motion_frames": [
+ self.motion_frames, lat_motion_frames
+ ],
+ "drop_motion_frames": drop_first_motion and r == 0,
+ }
+ if offload_model or self.init_on_cpu:
+ self.noise_model.to(self.device)
+ torch.cuda.empty_cache()
+
+ for i, t in enumerate(tqdm(timesteps)):
+ latent_model_input = latents[0:1]
+ timestep = [t]
+
+ timestep = torch.stack(timestep).to(self.device)
+
+ noise_pred_cond = self.noise_model(
+ latent_model_input, t=timestep, **arg_c)
+
+ if guide_scale > 1:
+ noise_pred_uncond = self.noise_model(
+ latent_model_input, t=timestep, **arg_null)
+ noise_pred = [
+ u + guide_scale * (c - u)
+ for c, u in zip(noise_pred_cond, noise_pred_uncond)
+ ]
+ else:
+ noise_pred = noise_pred_cond
+
+ temp_x0 = sample_scheduler.step(
+ noise_pred[0].unsqueeze(0),
+ t,
+ latents[0].unsqueeze(0),
+ return_dict=False,
+ generator=seed_g)[0]
+ latents[0] = temp_x0.squeeze(0)
+
+ if offload_model:
+ self.noise_model.cpu()
+ torch.cuda.synchronize()
+ torch.cuda.empty_cache()
+ latents = torch.stack(latents)
+ if not (drop_first_motion and r == 0):
+ decode_latents = torch.cat([motion_latents, latents], dim=2)
+ else:
+ decode_latents = torch.cat([ref_latents, latents], dim=2)
+ image = torch.stack(self.vae.decode(decode_latents))
+ image = image[:, :, -(infer_frames):]
+ if (drop_first_motion and r == 0):
+ image = image[:, :, 3:]
+
+ overlap_frames_num = min(self.motion_frames, image.shape[2])
+ videos_last_frames = torch.cat([
+ videos_last_frames[:, :, overlap_frames_num:],
+ image[:, :, -overlap_frames_num:]
+ ],
+ dim=2)
+ videos_last_frames = videos_last_frames.to(
+ dtype=motion_latents.dtype, device=motion_latents.device)
+ motion_latents = torch.stack(
+ self.vae.encode(videos_last_frames))
+ out.append(image.cpu())
+
+ videos = torch.cat(out, dim=2)
+ del noise, latents
+ del sample_scheduler
+ if offload_model:
+ gc.collect()
+ torch.cuda.synchronize()
+ if dist.is_initialized():
+ dist.barrier()
+
+ return videos[0] if self.rank == 0 else None
+
+ def tts(self, tts_prompt_audio, tts_prompt_text, tts_text):
+ if not hasattr(self, 'cosyvoice'):
+ self.load_tts()
+ speech_list = []
+ from cosyvoice.utils.file_utils import load_wav
+ import torchaudio
+ prompt_speech_16k = load_wav(tts_prompt_audio, 16000)
+ if tts_prompt_text is not None:
+ for i in self.cosyvoice.inference_zero_shot(tts_text, tts_prompt_text, prompt_speech_16k):
+ speech_list.append(i['tts_speech'])
+ else:
+ for i in self.cosyvoice.inference_cross_lingual(tts_text, prompt_speech_16k):
+ speech_list.append(i['tts_speech'])
+ torchaudio.save('tts.wav', torch.concat(speech_list, dim=1), self.cosyvoice.sample_rate)
+ return 'tts.wav'
+
+ def load_tts(self):
+ if not os.path.exists('CosyVoice'):
+ from wan.utils.utils import download_cosyvoice_repo
+ download_cosyvoice_repo('CosyVoice')
+ if not os.path.exists('CosyVoice2-0.5B'):
+ from wan.utils.utils import download_cosyvoice_model
+ download_cosyvoice_model('CosyVoice2-0.5B', 'CosyVoice2-0.5B')
+ sys.path.append('CosyVoice')
+ sys.path.append('CosyVoice/third_party/Matcha-TTS')
+ from cosyvoice.cli.cosyvoice import CosyVoice2
+ self.cosyvoice = CosyVoice2('CosyVoice2-0.5B')
\ No newline at end of file
diff --git a/wan/text2video.py b/wan/text2video.py
new file mode 100644
index 0000000000000000000000000000000000000000..f40cad9f12a91db77c39b7d41f05cd37cf4a08de
--- /dev/null
+++ b/wan/text2video.py
@@ -0,0 +1,378 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import gc
+import logging
+import math
+import os
+import random
+import sys
+import types
+from contextlib import contextmanager
+from functools import partial
+
+import torch
+import torch.cuda.amp as amp
+import torch.distributed as dist
+from tqdm import tqdm
+
+from .distributed.fsdp import shard_model
+from .distributed.sequence_parallel import sp_attn_forward, sp_dit_forward
+from .distributed.util import get_world_size
+from .modules.model import WanModel
+from .modules.t5 import T5EncoderModel
+from .modules.vae2_1 import Wan2_1_VAE
+from .utils.fm_solvers import (
+ FlowDPMSolverMultistepScheduler,
+ get_sampling_sigmas,
+ retrieve_timesteps,
+)
+from .utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
+
+
+class WanT2V:
+
+ def __init__(
+ self,
+ config,
+ checkpoint_dir,
+ device_id=0,
+ rank=0,
+ t5_fsdp=False,
+ dit_fsdp=False,
+ use_sp=False,
+ t5_cpu=False,
+ init_on_cpu=True,
+ convert_model_dtype=False,
+ ):
+ r"""
+ Initializes the Wan text-to-video generation model components.
+
+ Args:
+ config (EasyDict):
+ Object containing model parameters initialized from config.py
+ checkpoint_dir (`str`):
+ Path to directory containing model checkpoints
+ device_id (`int`, *optional*, defaults to 0):
+ Id of target GPU device
+ rank (`int`, *optional*, defaults to 0):
+ Process rank for distributed training
+ t5_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for T5 model
+ dit_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for DiT model
+ use_sp (`bool`, *optional*, defaults to False):
+ Enable distribution strategy of sequence parallel.
+ t5_cpu (`bool`, *optional*, defaults to False):
+ Whether to place T5 model on CPU. Only works without t5_fsdp.
+ init_on_cpu (`bool`, *optional*, defaults to True):
+ Enable initializing Transformer Model on CPU. Only works without FSDP or USP.
+ convert_model_dtype (`bool`, *optional*, defaults to False):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+ """
+ self.device = torch.device(f"cuda:{device_id}")
+ self.config = config
+ self.rank = rank
+ self.t5_cpu = t5_cpu
+ self.init_on_cpu = init_on_cpu
+
+ self.num_train_timesteps = config.num_train_timesteps
+ self.boundary = config.boundary
+ self.param_dtype = config.param_dtype
+
+ if t5_fsdp or dit_fsdp or use_sp:
+ self.init_on_cpu = False
+
+ shard_fn = partial(shard_model, device_id=device_id)
+ self.text_encoder = T5EncoderModel(
+ text_len=config.text_len,
+ dtype=config.t5_dtype,
+ device=torch.device('cpu'),
+ checkpoint_path=os.path.join(checkpoint_dir, config.t5_checkpoint),
+ tokenizer_path=os.path.join(checkpoint_dir, config.t5_tokenizer),
+ shard_fn=shard_fn if t5_fsdp else None)
+
+ self.vae_stride = config.vae_stride
+ self.patch_size = config.patch_size
+ self.vae = Wan2_1_VAE(
+ vae_pth=os.path.join(checkpoint_dir, config.vae_checkpoint),
+ device=self.device)
+
+ logging.info(f"Creating WanModel from {checkpoint_dir}")
+ self.low_noise_model = WanModel.from_pretrained(
+ checkpoint_dir, subfolder=config.low_noise_checkpoint)
+ self.low_noise_model = self._configure_model(
+ model=self.low_noise_model,
+ use_sp=use_sp,
+ dit_fsdp=dit_fsdp,
+ shard_fn=shard_fn,
+ convert_model_dtype=convert_model_dtype)
+
+ self.high_noise_model = WanModel.from_pretrained(
+ checkpoint_dir, subfolder=config.high_noise_checkpoint)
+ self.high_noise_model = self._configure_model(
+ model=self.high_noise_model,
+ use_sp=use_sp,
+ dit_fsdp=dit_fsdp,
+ shard_fn=shard_fn,
+ convert_model_dtype=convert_model_dtype)
+ if use_sp:
+ self.sp_size = get_world_size()
+ else:
+ self.sp_size = 1
+
+ self.sample_neg_prompt = config.sample_neg_prompt
+
+ def _configure_model(self, model, use_sp, dit_fsdp, shard_fn,
+ convert_model_dtype):
+ """
+ Configures a model object. This includes setting evaluation modes,
+ applying distributed parallel strategy, and handling device placement.
+
+ Args:
+ model (torch.nn.Module):
+ The model instance to configure.
+ use_sp (`bool`):
+ Enable distribution strategy of sequence parallel.
+ dit_fsdp (`bool`):
+ Enable FSDP sharding for DiT model.
+ shard_fn (callable):
+ The function to apply FSDP sharding.
+ convert_model_dtype (`bool`):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+
+ Returns:
+ torch.nn.Module:
+ The configured model.
+ """
+ model.eval().requires_grad_(False)
+
+ if use_sp:
+ for block in model.blocks:
+ block.self_attn.forward = types.MethodType(
+ sp_attn_forward, block.self_attn)
+ model.forward = types.MethodType(sp_dit_forward, model)
+
+ if dist.is_initialized():
+ dist.barrier()
+
+ if dit_fsdp:
+ model = shard_fn(model)
+ else:
+ if convert_model_dtype:
+ model.to(self.param_dtype)
+ if not self.init_on_cpu:
+ model.to(self.device)
+
+ return model
+
+ def _prepare_model_for_timestep(self, t, boundary, offload_model):
+ r"""
+ Prepares and returns the required model for the current timestep.
+
+ Args:
+ t (torch.Tensor):
+ current timestep.
+ boundary (`int`):
+ The timestep threshold. If `t` is at or above this value,
+ the `high_noise_model` is considered as the required model.
+ offload_model (`bool`):
+ A flag intended to control the offloading behavior.
+
+ Returns:
+ torch.nn.Module:
+ The active model on the target device for the current timestep.
+ """
+ if t.item() >= boundary:
+ required_model_name = 'high_noise_model'
+ offload_model_name = 'low_noise_model'
+ else:
+ required_model_name = 'low_noise_model'
+ offload_model_name = 'high_noise_model'
+ if offload_model or self.init_on_cpu:
+ if next(getattr(
+ self,
+ offload_model_name).parameters()).device.type == 'cuda':
+ getattr(self, offload_model_name).to('cpu')
+ if next(getattr(
+ self,
+ required_model_name).parameters()).device.type == 'cpu':
+ getattr(self, required_model_name).to(self.device)
+ return getattr(self, required_model_name)
+
+ def generate(self,
+ input_prompt,
+ size=(1280, 720),
+ frame_num=81,
+ shift=5.0,
+ sample_solver='unipc',
+ sampling_steps=50,
+ guide_scale=5.0,
+ n_prompt="",
+ seed=-1,
+ offload_model=True):
+ r"""
+ Generates video frames from text prompt using diffusion process.
+
+ Args:
+ input_prompt (`str`):
+ Text prompt for content generation
+ size (`tuple[int]`, *optional*, defaults to (1280,720)):
+ Controls video resolution, (width,height).
+ frame_num (`int`, *optional*, defaults to 81):
+ How many frames to sample from a video. The number should be 4n+1
+ shift (`float`, *optional*, defaults to 5.0):
+ Noise schedule shift parameter. Affects temporal dynamics
+ sample_solver (`str`, *optional*, defaults to 'unipc'):
+ Solver used to sample the video.
+ sampling_steps (`int`, *optional*, defaults to 50):
+ Number of diffusion sampling steps. Higher values improve quality but slow generation
+ guide_scale (`float` or tuple[`float`], *optional*, defaults 5.0):
+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.
+ If tuple, the first guide_scale will be used for low noise model and
+ the second guide_scale will be used for high noise model.
+ n_prompt (`str`, *optional*, defaults to ""):
+ Negative prompt for content exclusion. If not given, use `config.sample_neg_prompt`
+ seed (`int`, *optional*, defaults to -1):
+ Random seed for noise generation. If -1, use random seed.
+ offload_model (`bool`, *optional*, defaults to True):
+ If True, offloads models to CPU during generation to save VRAM
+
+ Returns:
+ torch.Tensor:
+ Generated video frames tensor. Dimensions: (C, N H, W) where:
+ - C: Color channels (3 for RGB)
+ - N: Number of frames (81)
+ - H: Frame height (from size)
+ - W: Frame width from size)
+ """
+ # preprocess
+ guide_scale = (guide_scale, guide_scale) if isinstance(
+ guide_scale, float) else guide_scale
+ F = frame_num
+ target_shape = (self.vae.model.z_dim, (F - 1) // self.vae_stride[0] + 1,
+ size[1] // self.vae_stride[1],
+ size[0] // self.vae_stride[2])
+
+ seq_len = math.ceil((target_shape[2] * target_shape[3]) /
+ (self.patch_size[1] * self.patch_size[2]) *
+ target_shape[1] / self.sp_size) * self.sp_size
+
+ if n_prompt == "":
+ n_prompt = self.sample_neg_prompt
+ seed = seed if seed >= 0 else random.randint(0, sys.maxsize)
+ seed_g = torch.Generator(device=self.device)
+ seed_g.manual_seed(seed)
+
+ if not self.t5_cpu:
+ self.text_encoder.model.to(self.device)
+ context = self.text_encoder([input_prompt], self.device)
+ context_null = self.text_encoder([n_prompt], self.device)
+ if offload_model:
+ self.text_encoder.model.cpu()
+ else:
+ context = self.text_encoder([input_prompt], torch.device('cpu'))
+ context_null = self.text_encoder([n_prompt], torch.device('cpu'))
+ context = [t.to(self.device) for t in context]
+ context_null = [t.to(self.device) for t in context_null]
+
+ noise = [
+ torch.randn(
+ target_shape[0],
+ target_shape[1],
+ target_shape[2],
+ target_shape[3],
+ dtype=torch.float32,
+ device=self.device,
+ generator=seed_g)
+ ]
+
+ @contextmanager
+ def noop_no_sync():
+ yield
+
+ no_sync_low_noise = getattr(self.low_noise_model, 'no_sync',
+ noop_no_sync)
+ no_sync_high_noise = getattr(self.high_noise_model, 'no_sync',
+ noop_no_sync)
+
+ # evaluation mode
+ with (
+ torch.amp.autocast('cuda', dtype=self.param_dtype),
+ torch.no_grad(),
+ no_sync_low_noise(),
+ no_sync_high_noise(),
+ ):
+ boundary = self.boundary * self.num_train_timesteps
+
+ if sample_solver == 'unipc':
+ sample_scheduler = FlowUniPCMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sample_scheduler.set_timesteps(
+ sampling_steps, device=self.device, shift=shift)
+ timesteps = sample_scheduler.timesteps
+ elif sample_solver == 'dpm++':
+ sample_scheduler = FlowDPMSolverMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sampling_sigmas = get_sampling_sigmas(sampling_steps, shift)
+ timesteps, _ = retrieve_timesteps(
+ sample_scheduler,
+ device=self.device,
+ sigmas=sampling_sigmas)
+ else:
+ raise NotImplementedError("Unsupported solver.")
+
+ # sample videos
+ latents = noise
+
+ arg_c = {'context': context, 'seq_len': seq_len}
+ arg_null = {'context': context_null, 'seq_len': seq_len}
+
+ for _, t in enumerate(tqdm(timesteps)):
+ latent_model_input = latents
+ timestep = [t]
+
+ timestep = torch.stack(timestep)
+
+ model = self._prepare_model_for_timestep(
+ t, boundary, offload_model)
+ sample_guide_scale = guide_scale[1] if t.item(
+ ) >= boundary else guide_scale[0]
+
+ noise_pred_cond = model(
+ latent_model_input, t=timestep, **arg_c)[0]
+ noise_pred_uncond = model(
+ latent_model_input, t=timestep, **arg_null)[0]
+
+ noise_pred = noise_pred_uncond + sample_guide_scale * (
+ noise_pred_cond - noise_pred_uncond)
+
+ temp_x0 = sample_scheduler.step(
+ noise_pred.unsqueeze(0),
+ t,
+ latents[0].unsqueeze(0),
+ return_dict=False,
+ generator=seed_g)[0]
+ latents = [temp_x0.squeeze(0)]
+
+ x0 = latents
+ if offload_model:
+ self.low_noise_model.cpu()
+ self.high_noise_model.cpu()
+ torch.cuda.empty_cache()
+ if self.rank == 0:
+ videos = self.vae.decode(x0)
+
+ del noise, latents
+ del sample_scheduler
+ if offload_model:
+ gc.collect()
+ torch.cuda.synchronize()
+ if dist.is_initialized():
+ dist.barrier()
+
+ return videos[0] if self.rank == 0 else None
diff --git a/wan/textimage2video.py b/wan/textimage2video.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb1aa776cbf13d46f0c9b58e76668eb39f981fe2
--- /dev/null
+++ b/wan/textimage2video.py
@@ -0,0 +1,619 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import gc
+import logging
+import math
+import os
+import random
+import sys
+import types
+from contextlib import contextmanager
+from functools import partial
+
+import torch
+import torch.cuda.amp as amp
+import torch.distributed as dist
+import torchvision.transforms.functional as TF
+from PIL import Image
+from tqdm import tqdm
+
+from .distributed.fsdp import shard_model
+from .distributed.sequence_parallel import sp_attn_forward, sp_dit_forward
+from .distributed.util import get_world_size
+from .modules.model import WanModel
+from .modules.t5 import T5EncoderModel
+from .modules.vae2_2 import Wan2_2_VAE
+from .utils.fm_solvers import (
+ FlowDPMSolverMultistepScheduler,
+ get_sampling_sigmas,
+ retrieve_timesteps,
+)
+from .utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
+from .utils.utils import best_output_size, masks_like
+
+
+class WanTI2V:
+
+ def __init__(
+ self,
+ config,
+ checkpoint_dir,
+ device_id=0,
+ rank=0,
+ t5_fsdp=False,
+ dit_fsdp=False,
+ use_sp=False,
+ t5_cpu=False,
+ init_on_cpu=True,
+ convert_model_dtype=False,
+ ):
+ r"""
+ Initializes the Wan text-to-video generation model components.
+
+ Args:
+ config (EasyDict):
+ Object containing model parameters initialized from config.py
+ checkpoint_dir (`str`):
+ Path to directory containing model checkpoints
+ device_id (`int`, *optional*, defaults to 0):
+ Id of target GPU device
+ rank (`int`, *optional*, defaults to 0):
+ Process rank for distributed training
+ t5_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for T5 model
+ dit_fsdp (`bool`, *optional*, defaults to False):
+ Enable FSDP sharding for DiT model
+ use_sp (`bool`, *optional*, defaults to False):
+ Enable distribution strategy of sequence parallel.
+ t5_cpu (`bool`, *optional*, defaults to False):
+ Whether to place T5 model on CPU. Only works without t5_fsdp.
+ init_on_cpu (`bool`, *optional*, defaults to True):
+ Enable initializing Transformer Model on CPU. Only works without FSDP or USP.
+ convert_model_dtype (`bool`, *optional*, defaults to False):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+ """
+ self.device = torch.device(f"cuda:{device_id}")
+ self.config = config
+ self.rank = rank
+ self.t5_cpu = t5_cpu
+ self.init_on_cpu = init_on_cpu
+
+ self.num_train_timesteps = config.num_train_timesteps
+ self.param_dtype = config.param_dtype
+
+ if t5_fsdp or dit_fsdp or use_sp:
+ self.init_on_cpu = False
+
+ shard_fn = partial(shard_model, device_id=device_id)
+ self.text_encoder = T5EncoderModel(
+ text_len=config.text_len,
+ dtype=config.t5_dtype,
+ device=torch.device('cpu'),
+ checkpoint_path=os.path.join(checkpoint_dir, config.t5_checkpoint),
+ tokenizer_path=os.path.join(checkpoint_dir, config.t5_tokenizer),
+ shard_fn=shard_fn if t5_fsdp else None)
+
+ self.vae_stride = config.vae_stride
+ self.patch_size = config.patch_size
+ self.vae = Wan2_2_VAE(
+ vae_pth=os.path.join(checkpoint_dir, config.vae_checkpoint),
+ device=self.device)
+
+ logging.info(f"Creating WanModel from {checkpoint_dir}")
+ self.model = WanModel.from_pretrained(checkpoint_dir)
+ self.model = self._configure_model(
+ model=self.model,
+ use_sp=use_sp,
+ dit_fsdp=dit_fsdp,
+ shard_fn=shard_fn,
+ convert_model_dtype=convert_model_dtype)
+
+ if use_sp:
+ self.sp_size = get_world_size()
+ else:
+ self.sp_size = 1
+
+ self.sample_neg_prompt = config.sample_neg_prompt
+
+ def _configure_model(self, model, use_sp, dit_fsdp, shard_fn,
+ convert_model_dtype):
+ """
+ Configures a model object. This includes setting evaluation modes,
+ applying distributed parallel strategy, and handling device placement.
+
+ Args:
+ model (torch.nn.Module):
+ The model instance to configure.
+ use_sp (`bool`):
+ Enable distribution strategy of sequence parallel.
+ dit_fsdp (`bool`):
+ Enable FSDP sharding for DiT model.
+ shard_fn (callable):
+ The function to apply FSDP sharding.
+ convert_model_dtype (`bool`):
+ Convert DiT model parameters dtype to 'config.param_dtype'.
+ Only works without FSDP.
+
+ Returns:
+ torch.nn.Module:
+ The configured model.
+ """
+ model.eval().requires_grad_(False)
+
+ if use_sp:
+ for block in model.blocks:
+ block.self_attn.forward = types.MethodType(
+ sp_attn_forward, block.self_attn)
+ model.forward = types.MethodType(sp_dit_forward, model)
+
+ if dist.is_initialized():
+ dist.barrier()
+
+ if dit_fsdp:
+ model = shard_fn(model)
+ else:
+ if convert_model_dtype:
+ model.to(self.param_dtype)
+ if not self.init_on_cpu:
+ model.to(self.device)
+
+ return model
+
+ def generate(self,
+ input_prompt,
+ img=None,
+ size=(1280, 704),
+ max_area=704 * 1280,
+ frame_num=81,
+ shift=5.0,
+ sample_solver='unipc',
+ sampling_steps=50,
+ guide_scale=5.0,
+ n_prompt="",
+ seed=-1,
+ offload_model=True):
+ r"""
+ Generates video frames from text prompt using diffusion process.
+
+ Args:
+ input_prompt (`str`):
+ Text prompt for content generation
+ img (PIL.Image.Image):
+ Input image tensor. Shape: [3, H, W]
+ size (`tuple[int]`, *optional*, defaults to (1280,704)):
+ Controls video resolution, (width,height).
+ max_area (`int`, *optional*, defaults to 704*1280):
+ Maximum pixel area for latent space calculation. Controls video resolution scaling
+ frame_num (`int`, *optional*, defaults to 81):
+ How many frames to sample from a video. The number should be 4n+1
+ shift (`float`, *optional*, defaults to 5.0):
+ Noise schedule shift parameter. Affects temporal dynamics
+ sample_solver (`str`, *optional*, defaults to 'unipc'):
+ Solver used to sample the video.
+ sampling_steps (`int`, *optional*, defaults to 50):
+ Number of diffusion sampling steps. Higher values improve quality but slow generation
+ guide_scale (`float`, *optional*, defaults 5.0):
+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.
+ n_prompt (`str`, *optional*, defaults to ""):
+ Negative prompt for content exclusion. If not given, use `config.sample_neg_prompt`
+ seed (`int`, *optional*, defaults to -1):
+ Random seed for noise generation. If -1, use random seed.
+ offload_model (`bool`, *optional*, defaults to True):
+ If True, offloads models to CPU during generation to save VRAM
+
+ Returns:
+ torch.Tensor:
+ Generated video frames tensor. Dimensions: (C, N H, W) where:
+ - C: Color channels (3 for RGB)
+ - N: Number of frames (81)
+ - H: Frame height (from size)
+ - W: Frame width from size)
+ """
+ # i2v
+ if img is not None:
+ return self.i2v(
+ input_prompt=input_prompt,
+ img=img,
+ max_area=max_area,
+ frame_num=frame_num,
+ shift=shift,
+ sample_solver=sample_solver,
+ sampling_steps=sampling_steps,
+ guide_scale=guide_scale,
+ n_prompt=n_prompt,
+ seed=seed,
+ offload_model=offload_model)
+ # t2v
+ return self.t2v(
+ input_prompt=input_prompt,
+ size=size,
+ frame_num=frame_num,
+ shift=shift,
+ sample_solver=sample_solver,
+ sampling_steps=sampling_steps,
+ guide_scale=guide_scale,
+ n_prompt=n_prompt,
+ seed=seed,
+ offload_model=offload_model)
+
+ def t2v(self,
+ input_prompt,
+ size=(1280, 704),
+ frame_num=121,
+ shift=5.0,
+ sample_solver='unipc',
+ sampling_steps=50,
+ guide_scale=5.0,
+ n_prompt="",
+ seed=-1,
+ offload_model=True):
+ r"""
+ Generates video frames from text prompt using diffusion process.
+
+ Args:
+ input_prompt (`str`):
+ Text prompt for content generation
+ size (`tuple[int]`, *optional*, defaults to (1280,704)):
+ Controls video resolution, (width,height).
+ frame_num (`int`, *optional*, defaults to 121):
+ How many frames to sample from a video. The number should be 4n+1
+ shift (`float`, *optional*, defaults to 5.0):
+ Noise schedule shift parameter. Affects temporal dynamics
+ sample_solver (`str`, *optional*, defaults to 'unipc'):
+ Solver used to sample the video.
+ sampling_steps (`int`, *optional*, defaults to 50):
+ Number of diffusion sampling steps. Higher values improve quality but slow generation
+ guide_scale (`float`, *optional*, defaults 5.0):
+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.
+ n_prompt (`str`, *optional*, defaults to ""):
+ Negative prompt for content exclusion. If not given, use `config.sample_neg_prompt`
+ seed (`int`, *optional*, defaults to -1):
+ Random seed for noise generation. If -1, use random seed.
+ offload_model (`bool`, *optional*, defaults to True):
+ If True, offloads models to CPU during generation to save VRAM
+
+ Returns:
+ torch.Tensor:
+ Generated video frames tensor. Dimensions: (C, N H, W) where:
+ - C: Color channels (3 for RGB)
+ - N: Number of frames (81)
+ - H: Frame height (from size)
+ - W: Frame width from size)
+ """
+ # preprocess
+ F = frame_num
+ target_shape = (self.vae.model.z_dim, (F - 1) // self.vae_stride[0] + 1,
+ size[1] // self.vae_stride[1],
+ size[0] // self.vae_stride[2])
+
+ seq_len = math.ceil((target_shape[2] * target_shape[3]) /
+ (self.patch_size[1] * self.patch_size[2]) *
+ target_shape[1] / self.sp_size) * self.sp_size
+
+ if n_prompt == "":
+ n_prompt = self.sample_neg_prompt
+ seed = seed if seed >= 0 else random.randint(0, sys.maxsize)
+ seed_g = torch.Generator(device=self.device)
+ seed_g.manual_seed(seed)
+
+ if not self.t5_cpu:
+ self.text_encoder.model.to(self.device)
+ context = self.text_encoder([input_prompt], self.device)
+ context_null = self.text_encoder([n_prompt], self.device)
+ if offload_model:
+ self.text_encoder.model.cpu()
+ else:
+ context = self.text_encoder([input_prompt], torch.device('cpu'))
+ context_null = self.text_encoder([n_prompt], torch.device('cpu'))
+ context = [t.to(self.device) for t in context]
+ context_null = [t.to(self.device) for t in context_null]
+
+ noise = [
+ torch.randn(
+ target_shape[0],
+ target_shape[1],
+ target_shape[2],
+ target_shape[3],
+ dtype=torch.float32,
+ device=self.device,
+ generator=seed_g)
+ ]
+
+ @contextmanager
+ def noop_no_sync():
+ yield
+
+ no_sync = getattr(self.model, 'no_sync', noop_no_sync)
+
+ # evaluation mode
+ with (
+ torch.amp.autocast('cuda', dtype=self.param_dtype),
+ torch.no_grad(),
+ no_sync(),
+ ):
+
+ if sample_solver == 'unipc':
+ sample_scheduler = FlowUniPCMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sample_scheduler.set_timesteps(
+ sampling_steps, device=self.device, shift=shift)
+ timesteps = sample_scheduler.timesteps
+ elif sample_solver == 'dpm++':
+ sample_scheduler = FlowDPMSolverMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sampling_sigmas = get_sampling_sigmas(sampling_steps, shift)
+ timesteps, _ = retrieve_timesteps(
+ sample_scheduler,
+ device=self.device,
+ sigmas=sampling_sigmas)
+ else:
+ raise NotImplementedError("Unsupported solver.")
+
+ # sample videos
+ latents = noise
+ mask1, mask2 = masks_like(noise, zero=False)
+
+ arg_c = {'context': context, 'seq_len': seq_len}
+ arg_null = {'context': context_null, 'seq_len': seq_len}
+
+ if offload_model or self.init_on_cpu:
+ self.model.to(self.device)
+ torch.cuda.empty_cache()
+
+ for _, t in enumerate(tqdm(timesteps)):
+ latent_model_input = latents
+ timestep = [t]
+
+ timestep = torch.stack(timestep)
+
+ temp_ts = (mask2[0][0][:, ::2, ::2] * timestep).flatten()
+ temp_ts = torch.cat([
+ temp_ts,
+ temp_ts.new_ones(seq_len - temp_ts.size(0)) * timestep
+ ])
+ timestep = temp_ts.unsqueeze(0)
+
+ noise_pred_cond = self.model(
+ latent_model_input, t=timestep, **arg_c)[0]
+ noise_pred_uncond = self.model(
+ latent_model_input, t=timestep, **arg_null)[0]
+
+ noise_pred = noise_pred_uncond + guide_scale * (
+ noise_pred_cond - noise_pred_uncond)
+
+ temp_x0 = sample_scheduler.step(
+ noise_pred.unsqueeze(0),
+ t,
+ latents[0].unsqueeze(0),
+ return_dict=False,
+ generator=seed_g)[0]
+ latents = [temp_x0.squeeze(0)]
+ x0 = latents
+ if offload_model:
+ self.model.cpu()
+ torch.cuda.synchronize()
+ torch.cuda.empty_cache()
+ if self.rank == 0:
+ videos = self.vae.decode(x0)
+
+ del noise, latents
+ del sample_scheduler
+ if offload_model:
+ gc.collect()
+ torch.cuda.synchronize()
+ if dist.is_initialized():
+ dist.barrier()
+
+ return videos[0] if self.rank == 0 else None
+
+ def i2v(self,
+ input_prompt,
+ img,
+ max_area=704 * 1280,
+ frame_num=121,
+ shift=5.0,
+ sample_solver='unipc',
+ sampling_steps=40,
+ guide_scale=5.0,
+ n_prompt="",
+ seed=-1,
+ offload_model=True):
+ r"""
+ Generates video frames from input image and text prompt using diffusion process.
+
+ Args:
+ input_prompt (`str`):
+ Text prompt for content generation.
+ img (PIL.Image.Image):
+ Input image tensor. Shape: [3, H, W]
+ max_area (`int`, *optional*, defaults to 704*1280):
+ Maximum pixel area for latent space calculation. Controls video resolution scaling
+ frame_num (`int`, *optional*, defaults to 121):
+ How many frames to sample from a video. The number should be 4n+1
+ shift (`float`, *optional*, defaults to 5.0):
+ Noise schedule shift parameter. Affects temporal dynamics
+ [NOTE]: If you want to generate a 480p video, it is recommended to set the shift value to 3.0.
+ sample_solver (`str`, *optional*, defaults to 'unipc'):
+ Solver used to sample the video.
+ sampling_steps (`int`, *optional*, defaults to 40):
+ Number of diffusion sampling steps. Higher values improve quality but slow generation
+ guide_scale (`float`, *optional*, defaults 5.0):
+ Classifier-free guidance scale. Controls prompt adherence vs. creativity.
+ n_prompt (`str`, *optional*, defaults to ""):
+ Negative prompt for content exclusion. If not given, use `config.sample_neg_prompt`
+ seed (`int`, *optional*, defaults to -1):
+ Random seed for noise generation. If -1, use random seed
+ offload_model (`bool`, *optional*, defaults to True):
+ If True, offloads models to CPU during generation to save VRAM
+
+ Returns:
+ torch.Tensor:
+ Generated video frames tensor. Dimensions: (C, N H, W) where:
+ - C: Color channels (3 for RGB)
+ - N: Number of frames (121)
+ - H: Frame height (from max_area)
+ - W: Frame width (from max_area)
+ """
+ # preprocess
+ ih, iw = img.height, img.width
+ dh, dw = self.patch_size[1] * self.vae_stride[1], self.patch_size[
+ 2] * self.vae_stride[2]
+ ow, oh = best_output_size(iw, ih, dw, dh, max_area)
+
+ scale = max(ow / iw, oh / ih)
+ img = img.resize((round(iw * scale), round(ih * scale)), Image.LANCZOS)
+
+ # center-crop
+ x1 = (img.width - ow) // 2
+ y1 = (img.height - oh) // 2
+ img = img.crop((x1, y1, x1 + ow, y1 + oh))
+ assert img.width == ow and img.height == oh
+
+ # to tensor
+ img = TF.to_tensor(img).sub_(0.5).div_(0.5).to(self.device).unsqueeze(1)
+
+ F = frame_num
+ seq_len = ((F - 1) // self.vae_stride[0] + 1) * (
+ oh // self.vae_stride[1]) * (ow // self.vae_stride[2]) // (
+ self.patch_size[1] * self.patch_size[2])
+ seq_len = int(math.ceil(seq_len / self.sp_size)) * self.sp_size
+
+ seed = seed if seed >= 0 else random.randint(0, sys.maxsize)
+ seed_g = torch.Generator(device=self.device)
+ seed_g.manual_seed(seed)
+ noise = torch.randn(
+ self.vae.model.z_dim, (F - 1) // self.vae_stride[0] + 1,
+ oh // self.vae_stride[1],
+ ow // self.vae_stride[2],
+ dtype=torch.float32,
+ generator=seed_g,
+ device=self.device)
+
+ if n_prompt == "":
+ n_prompt = self.sample_neg_prompt
+
+ # preprocess
+ if not self.t5_cpu:
+ self.text_encoder.model.to(self.device)
+ context = self.text_encoder([input_prompt], self.device)
+ context_null = self.text_encoder([n_prompt], self.device)
+ if offload_model:
+ self.text_encoder.model.cpu()
+ else:
+ context = self.text_encoder([input_prompt], torch.device('cpu'))
+ context_null = self.text_encoder([n_prompt], torch.device('cpu'))
+ context = [t.to(self.device) for t in context]
+ context_null = [t.to(self.device) for t in context_null]
+
+ z = self.vae.encode([img])
+
+ @contextmanager
+ def noop_no_sync():
+ yield
+
+ no_sync = getattr(self.model, 'no_sync', noop_no_sync)
+
+ # evaluation mode
+ with (
+ torch.amp.autocast('cuda', dtype=self.param_dtype),
+ torch.no_grad(),
+ no_sync(),
+ ):
+
+ if sample_solver == 'unipc':
+ sample_scheduler = FlowUniPCMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sample_scheduler.set_timesteps(
+ sampling_steps, device=self.device, shift=shift)
+ timesteps = sample_scheduler.timesteps
+ elif sample_solver == 'dpm++':
+ sample_scheduler = FlowDPMSolverMultistepScheduler(
+ num_train_timesteps=self.num_train_timesteps,
+ shift=1,
+ use_dynamic_shifting=False)
+ sampling_sigmas = get_sampling_sigmas(sampling_steps, shift)
+ timesteps, _ = retrieve_timesteps(
+ sample_scheduler,
+ device=self.device,
+ sigmas=sampling_sigmas)
+ else:
+ raise NotImplementedError("Unsupported solver.")
+
+ # sample videos
+ latent = noise
+ mask1, mask2 = masks_like([noise], zero=True)
+ latent = (1. - mask2[0]) * z[0] + mask2[0] * latent
+
+ arg_c = {
+ 'context': [context[0]],
+ 'seq_len': seq_len,
+ }
+
+ arg_null = {
+ 'context': context_null,
+ 'seq_len': seq_len,
+ }
+
+ if offload_model or self.init_on_cpu:
+ self.model.to(self.device)
+ torch.cuda.empty_cache()
+
+ for _, t in enumerate(tqdm(timesteps)):
+ latent_model_input = [latent.to(self.device)]
+ timestep = [t]
+
+ timestep = torch.stack(timestep).to(self.device)
+
+ temp_ts = (mask2[0][0][:, ::2, ::2] * timestep).flatten()
+ temp_ts = torch.cat([
+ temp_ts,
+ temp_ts.new_ones(seq_len - temp_ts.size(0)) * timestep
+ ])
+ timestep = temp_ts.unsqueeze(0)
+
+ noise_pred_cond = self.model(
+ latent_model_input, t=timestep, **arg_c)[0]
+ if offload_model:
+ torch.cuda.empty_cache()
+ noise_pred_uncond = self.model(
+ latent_model_input, t=timestep, **arg_null)[0]
+ if offload_model:
+ torch.cuda.empty_cache()
+ noise_pred = noise_pred_uncond + guide_scale * (
+ noise_pred_cond - noise_pred_uncond)
+
+ temp_x0 = sample_scheduler.step(
+ noise_pred.unsqueeze(0),
+ t,
+ latent.unsqueeze(0),
+ return_dict=False,
+ generator=seed_g)[0]
+ latent = temp_x0.squeeze(0)
+ latent = (1. - mask2[0]) * z[0] + mask2[0] * latent
+
+ x0 = [latent]
+ del latent_model_input, timestep
+
+ if offload_model:
+ self.model.cpu()
+ torch.cuda.synchronize()
+ torch.cuda.empty_cache()
+
+ if self.rank == 0:
+ videos = self.vae.decode(x0)
+
+ del noise, latent, x0
+ del sample_scheduler
+ if offload_model:
+ gc.collect()
+ torch.cuda.synchronize()
+ if dist.is_initialized():
+ dist.barrier()
+
+ return videos[0] if self.rank == 0 else None
diff --git a/wan/utils/__init__.py b/wan/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7df474b92afc851864de611e5cbed78a50fcb3f0
--- /dev/null
+++ b/wan/utils/__init__.py
@@ -0,0 +1,12 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from .fm_solvers import (
+ FlowDPMSolverMultistepScheduler,
+ get_sampling_sigmas,
+ retrieve_timesteps,
+)
+from .fm_solvers_unipc import FlowUniPCMultistepScheduler
+
+__all__ = [
+ 'HuggingfaceTokenizer', 'get_sampling_sigmas', 'retrieve_timesteps',
+ 'FlowDPMSolverMultistepScheduler', 'FlowUniPCMultistepScheduler'
+]
diff --git a/wan/utils/fm_solvers.py b/wan/utils/fm_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f4e546d2d6ad99a6ab698b839fe7a36c0300239
--- /dev/null
+++ b/wan/utils/fm_solvers.py
@@ -0,0 +1,859 @@
+# Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/schedulers/scheduling_dpmsolver_multistep.py
+# Convert dpm solver for flow matching
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+
+import inspect
+import math
+from typing import List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.schedulers.scheduling_utils import (
+ KarrasDiffusionSchedulers,
+ SchedulerMixin,
+ SchedulerOutput,
+)
+from diffusers.utils import deprecate, is_scipy_available
+from diffusers.utils.torch_utils import randn_tensor
+
+if is_scipy_available():
+ pass
+
+
+def get_sampling_sigmas(sampling_steps, shift):
+ sigma = np.linspace(1, 0, sampling_steps + 1)[:sampling_steps]
+ sigma = (shift * sigma / (1 + (shift - 1) * sigma))
+
+ return sigma
+
+
+def retrieve_timesteps(
+ scheduler,
+ num_inference_steps=None,
+ device=None,
+ timesteps=None,
+ sigmas=None,
+ **kwargs,
+):
+ if timesteps is not None and sigmas is not None:
+ raise ValueError(
+ "Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values"
+ )
+ if timesteps is not None:
+ accepts_timesteps = "timesteps" in set(
+ inspect.signature(scheduler.set_timesteps).parameters.keys())
+ if not accepts_timesteps:
+ raise ValueError(
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
+ f" timestep schedules. Please check whether you are using the correct scheduler."
+ )
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
+ timesteps = scheduler.timesteps
+ num_inference_steps = len(timesteps)
+ elif sigmas is not None:
+ accept_sigmas = "sigmas" in set(
+ inspect.signature(scheduler.set_timesteps).parameters.keys())
+ if not accept_sigmas:
+ raise ValueError(
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
+ )
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
+ timesteps = scheduler.timesteps
+ num_inference_steps = len(timesteps)
+ else:
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
+ timesteps = scheduler.timesteps
+ return timesteps, num_inference_steps
+
+
+class FlowDPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin):
+ """
+ `FlowDPMSolverMultistepScheduler` is a fast dedicated high-order solver for diffusion ODEs.
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
+ methods the library implements for all schedulers such as loading and saving.
+ Args:
+ num_train_timesteps (`int`, defaults to 1000):
+ The number of diffusion steps to train the model. This determines the resolution of the diffusion process.
+ solver_order (`int`, defaults to 2):
+ The DPMSolver order which can be `1`, `2`, or `3`. It is recommended to use `solver_order=2` for guided
+ sampling, and `solver_order=3` for unconditional sampling. This affects the number of model outputs stored
+ and used in multistep updates.
+ prediction_type (`str`, defaults to "flow_prediction"):
+ Prediction type of the scheduler function; must be `flow_prediction` for this scheduler, which predicts
+ the flow of the diffusion process.
+ shift (`float`, *optional*, defaults to 1.0):
+ A factor used to adjust the sigmas in the noise schedule. It modifies the step sizes during the sampling
+ process.
+ use_dynamic_shifting (`bool`, defaults to `False`):
+ Whether to apply dynamic shifting to the timesteps based on image resolution. If `True`, the shifting is
+ applied on the fly.
+ thresholding (`bool`, defaults to `False`):
+ Whether to use the "dynamic thresholding" method. This method adjusts the predicted sample to prevent
+ saturation and improve photorealism.
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
+ sample_max_value (`float`, defaults to 1.0):
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True` and
+ `algorithm_type="dpmsolver++"`.
+ algorithm_type (`str`, defaults to `dpmsolver++`):
+ Algorithm type for the solver; can be `dpmsolver`, `dpmsolver++`, `sde-dpmsolver` or `sde-dpmsolver++`. The
+ `dpmsolver` type implements the algorithms in the [DPMSolver](https://huggingface.co/papers/2206.00927)
+ paper, and the `dpmsolver++` type implements the algorithms in the
+ [DPMSolver++](https://huggingface.co/papers/2211.01095) paper. It is recommended to use `dpmsolver++` or
+ `sde-dpmsolver++` with `solver_order=2` for guided sampling like in Stable Diffusion.
+ solver_type (`str`, defaults to `midpoint`):
+ Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the
+ sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers.
+ lower_order_final (`bool`, defaults to `True`):
+ Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
+ stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
+ euler_at_final (`bool`, defaults to `False`):
+ Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail
+ richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference
+ steps, but sometimes may result in blurring.
+ final_sigmas_type (`str`, *optional*, defaults to "zero"):
+ The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
+ sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
+ lambda_min_clipped (`float`, defaults to `-inf`):
+ Clipping threshold for the minimum value of `lambda(t)` for numerical stability. This is critical for the
+ cosine (`squaredcos_cap_v2`) noise schedule.
+ variance_type (`str`, *optional*):
+ Set to "learned" or "learned_range" for diffusion models that predict variance. If set, the model's output
+ contains the predicted Gaussian variance.
+ """
+
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
+ order = 1
+
+ @register_to_config
+ def __init__(
+ self,
+ num_train_timesteps: int = 1000,
+ solver_order: int = 2,
+ prediction_type: str = "flow_prediction",
+ shift: Optional[float] = 1.0,
+ use_dynamic_shifting=False,
+ thresholding: bool = False,
+ dynamic_thresholding_ratio: float = 0.995,
+ sample_max_value: float = 1.0,
+ algorithm_type: str = "dpmsolver++",
+ solver_type: str = "midpoint",
+ lower_order_final: bool = True,
+ euler_at_final: bool = False,
+ final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min"
+ lambda_min_clipped: float = -float("inf"),
+ variance_type: Optional[str] = None,
+ invert_sigmas: bool = False,
+ ):
+ if algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
+ deprecation_message = f"algorithm_type {algorithm_type} is deprecated and will be removed in a future version. Choose from `dpmsolver++` or `sde-dpmsolver++` instead"
+ deprecate("algorithm_types dpmsolver and sde-dpmsolver", "1.0.0",
+ deprecation_message)
+
+ # settings for DPM-Solver
+ if algorithm_type not in [
+ "dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"
+ ]:
+ if algorithm_type == "deis":
+ self.register_to_config(algorithm_type="dpmsolver++")
+ else:
+ raise NotImplementedError(
+ f"{algorithm_type} is not implemented for {self.__class__}")
+
+ if solver_type not in ["midpoint", "heun"]:
+ if solver_type in ["logrho", "bh1", "bh2"]:
+ self.register_to_config(solver_type="midpoint")
+ else:
+ raise NotImplementedError(
+ f"{solver_type} is not implemented for {self.__class__}")
+
+ if algorithm_type not in ["dpmsolver++", "sde-dpmsolver++"
+ ] and final_sigmas_type == "zero":
+ raise ValueError(
+ f"`final_sigmas_type` {final_sigmas_type} is not supported for `algorithm_type` {algorithm_type}. Please choose `sigma_min` instead."
+ )
+
+ # setable values
+ self.num_inference_steps = None
+ alphas = np.linspace(1, 1 / num_train_timesteps,
+ num_train_timesteps)[::-1].copy()
+ sigmas = 1.0 - alphas
+ sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32)
+
+ if not use_dynamic_shifting:
+ # when use_dynamic_shifting is True, we apply the timestep shifting on the fly based on the image resolution
+ sigmas = shift * sigmas / (1 +
+ (shift - 1) * sigmas) # pyright: ignore
+
+ self.sigmas = sigmas
+ self.timesteps = sigmas * num_train_timesteps
+
+ self.model_outputs = [None] * solver_order
+ self.lower_order_nums = 0
+ self._step_index = None
+ self._begin_index = None
+
+ # self.sigmas = self.sigmas.to(
+ # "cpu") # to avoid too much CPU/GPU communication
+ self.sigma_min = self.sigmas[-1].item()
+ self.sigma_max = self.sigmas[0].item()
+
+ @property
+ def step_index(self):
+ """
+ The index counter for current timestep. It will increase 1 after each scheduler step.
+ """
+ return self._step_index
+
+ @property
+ def begin_index(self):
+ """
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
+ """
+ return self._begin_index
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
+ def set_begin_index(self, begin_index: int = 0):
+ """
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
+ Args:
+ begin_index (`int`):
+ The begin index for the scheduler.
+ """
+ self._begin_index = begin_index
+
+ # Modified from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler.set_timesteps
+ def set_timesteps(
+ self,
+ num_inference_steps: Union[int, None] = None,
+ device: Union[str, torch.device] = None,
+ sigmas: Optional[List[float]] = None,
+ mu: Optional[Union[float, None]] = None,
+ shift: Optional[Union[float, None]] = None,
+ ):
+ """
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
+ Args:
+ num_inference_steps (`int`):
+ Total number of the spacing of the time steps.
+ device (`str` or `torch.device`, *optional*):
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
+ """
+
+ if self.config.use_dynamic_shifting and mu is None:
+ raise ValueError(
+ " you have to pass a value for `mu` when `use_dynamic_shifting` is set to be `True`"
+ )
+
+ if sigmas is None:
+ sigmas = np.linspace(self.sigma_max, self.sigma_min,
+ num_inference_steps +
+ 1).copy()[:-1] # pyright: ignore
+
+ if self.config.use_dynamic_shifting:
+ sigmas = self.time_shift(mu, 1.0, sigmas) # pyright: ignore
+ else:
+ if shift is None:
+ shift = self.config.shift
+ sigmas = shift * sigmas / (1 +
+ (shift - 1) * sigmas) # pyright: ignore
+
+ if self.config.final_sigmas_type == "sigma_min":
+ sigma_last = ((1 - self.alphas_cumprod[0]) /
+ self.alphas_cumprod[0])**0.5
+ elif self.config.final_sigmas_type == "zero":
+ sigma_last = 0
+ else:
+ raise ValueError(
+ f"`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got {self.config.final_sigmas_type}"
+ )
+
+ timesteps = sigmas * self.config.num_train_timesteps
+ sigmas = np.concatenate([sigmas, [sigma_last]
+ ]).astype(np.float32) # pyright: ignore
+
+ self.sigmas = torch.from_numpy(sigmas)
+ self.timesteps = torch.from_numpy(timesteps).to(
+ device=device, dtype=torch.int64)
+
+ self.num_inference_steps = len(timesteps)
+
+ self.model_outputs = [
+ None,
+ ] * self.config.solver_order
+ self.lower_order_nums = 0
+
+ self._step_index = None
+ self._begin_index = None
+ # self.sigmas = self.sigmas.to(
+ # "cpu") # to avoid too much CPU/GPU communication
+
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
+ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
+ """
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
+ https://arxiv.org/abs/2205.11487
+ """
+ dtype = sample.dtype
+ batch_size, channels, *remaining_dims = sample.shape
+
+ if dtype not in (torch.float32, torch.float64):
+ sample = sample.float(
+ ) # upcast for quantile calculation, and clamp not implemented for cpu half
+
+ # Flatten sample for doing quantile calculation along each image
+ sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
+
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
+
+ s = torch.quantile(
+ abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
+ s = torch.clamp(
+ s, min=1, max=self.config.sample_max_value
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
+ s = s.unsqueeze(
+ 1) # (batch_size, 1) because clamp will broadcast along dim=0
+ sample = torch.clamp(
+ sample, -s, s
+ ) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
+
+ sample = sample.reshape(batch_size, channels, *remaining_dims)
+ sample = sample.to(dtype)
+
+ return sample
+
+ # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._sigma_to_t
+ def _sigma_to_t(self, sigma):
+ return sigma * self.config.num_train_timesteps
+
+ def _sigma_to_alpha_sigma_t(self, sigma):
+ return 1 - sigma, sigma
+
+ # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.set_timesteps
+ def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1)**sigma)
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.convert_model_output
+ def convert_model_output(
+ self,
+ model_output: torch.Tensor,
+ *args,
+ sample: torch.Tensor = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is
+ designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an
+ integral of the data prediction model.
+
+ The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both noise
+ prediction and data prediction models.
+
+ Args:
+ model_output (`torch.Tensor`):
+ The direct output from the learned diffusion model.
+ sample (`torch.Tensor`):
+ A current instance of a sample created by the diffusion process.
+ Returns:
+ `torch.Tensor`:
+ The converted model output.
+ """
+ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
+ if sample is None:
+ if len(args) > 1:
+ sample = args[1]
+ else:
+ raise ValueError(
+ "missing `sample` as a required keyward argument")
+ if timestep is not None:
+ deprecate(
+ "timesteps",
+ "1.0.0",
+ "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ # DPM-Solver++ needs to solve an integral of the data prediction model.
+ if self.config.algorithm_type in ["dpmsolver++", "sde-dpmsolver++"]:
+ if self.config.prediction_type == "flow_prediction":
+ sigma_t = self.sigmas[self.step_index]
+ x0_pred = sample - sigma_t * model_output
+ else:
+ raise ValueError(
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`,"
+ " `v_prediction`, or `flow_prediction` for the FlowDPMSolverMultistepScheduler."
+ )
+
+ if self.config.thresholding:
+ x0_pred = self._threshold_sample(x0_pred)
+
+ return x0_pred
+
+ # DPM-Solver needs to solve an integral of the noise prediction model.
+ elif self.config.algorithm_type in ["dpmsolver", "sde-dpmsolver"]:
+ if self.config.prediction_type == "flow_prediction":
+ sigma_t = self.sigmas[self.step_index]
+ epsilon = sample - (1 - sigma_t) * model_output
+ else:
+ raise ValueError(
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`,"
+ " `v_prediction` or `flow_prediction` for the FlowDPMSolverMultistepScheduler."
+ )
+
+ if self.config.thresholding:
+ sigma_t = self.sigmas[self.step_index]
+ x0_pred = sample - sigma_t * model_output
+ x0_pred = self._threshold_sample(x0_pred)
+ epsilon = model_output + x0_pred
+
+ return epsilon
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.dpm_solver_first_order_update
+ def dpm_solver_first_order_update(
+ self,
+ model_output: torch.Tensor,
+ *args,
+ sample: torch.Tensor = None,
+ noise: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ One step for the first-order DPMSolver (equivalent to DDIM).
+ Args:
+ model_output (`torch.Tensor`):
+ The direct output from the learned diffusion model.
+ sample (`torch.Tensor`):
+ A current instance of a sample created by the diffusion process.
+ Returns:
+ `torch.Tensor`:
+ The sample tensor at the previous timestep.
+ """
+ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop(
+ "prev_timestep", None)
+ if sample is None:
+ if len(args) > 2:
+ sample = args[2]
+ else:
+ raise ValueError(
+ " missing `sample` as a required keyward argument")
+ if timestep is not None:
+ deprecate(
+ "timesteps",
+ "1.0.0",
+ "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ if prev_timestep is not None:
+ deprecate(
+ "prev_timestep",
+ "1.0.0",
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[
+ self.step_index] # pyright: ignore
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
+ alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s)
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
+ lambda_s = torch.log(alpha_s) - torch.log(sigma_s)
+
+ h = lambda_t - lambda_s
+ if self.config.algorithm_type == "dpmsolver++":
+ x_t = (sigma_t /
+ sigma_s) * sample - (alpha_t *
+ (torch.exp(-h) - 1.0)) * model_output
+ elif self.config.algorithm_type == "dpmsolver":
+ x_t = (alpha_t /
+ alpha_s) * sample - (sigma_t *
+ (torch.exp(h) - 1.0)) * model_output
+ elif self.config.algorithm_type == "sde-dpmsolver++":
+ assert noise is not None
+ x_t = ((sigma_t / sigma_s * torch.exp(-h)) * sample +
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output +
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise)
+ elif self.config.algorithm_type == "sde-dpmsolver":
+ assert noise is not None
+ x_t = ((alpha_t / alpha_s) * sample - 2.0 *
+ (sigma_t * (torch.exp(h) - 1.0)) * model_output +
+ sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise)
+ return x_t # pyright: ignore
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.multistep_dpm_solver_second_order_update
+ def multistep_dpm_solver_second_order_update(
+ self,
+ model_output_list: List[torch.Tensor],
+ *args,
+ sample: torch.Tensor = None,
+ noise: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ One step for the second-order multistep DPMSolver.
+ Args:
+ model_output_list (`List[torch.Tensor]`):
+ The direct outputs from learned diffusion model at current and latter timesteps.
+ sample (`torch.Tensor`):
+ A current instance of a sample created by the diffusion process.
+ Returns:
+ `torch.Tensor`:
+ The sample tensor at the previous timestep.
+ """
+ timestep_list = args[0] if len(args) > 0 else kwargs.pop(
+ "timestep_list", None)
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop(
+ "prev_timestep", None)
+ if sample is None:
+ if len(args) > 2:
+ sample = args[2]
+ else:
+ raise ValueError(
+ " missing `sample` as a required keyward argument")
+ if timestep_list is not None:
+ deprecate(
+ "timestep_list",
+ "1.0.0",
+ "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ if prev_timestep is not None:
+ deprecate(
+ "prev_timestep",
+ "1.0.0",
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ sigma_t, sigma_s0, sigma_s1 = (
+ self.sigmas[self.step_index + 1], # pyright: ignore
+ self.sigmas[self.step_index],
+ self.sigmas[self.step_index - 1], # pyright: ignore
+ )
+
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
+
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
+
+ m0, m1 = model_output_list[-1], model_output_list[-2]
+
+ h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1
+ r0 = h_0 / h
+ D0, D1 = m0, (1.0 / r0) * (m0 - m1)
+ if self.config.algorithm_type == "dpmsolver++":
+ # See https://arxiv.org/abs/2211.01095 for detailed derivations
+ if self.config.solver_type == "midpoint":
+ x_t = ((sigma_t / sigma_s0) * sample -
+ (alpha_t * (torch.exp(-h) - 1.0)) * D0 - 0.5 *
+ (alpha_t * (torch.exp(-h) - 1.0)) * D1)
+ elif self.config.solver_type == "heun":
+ x_t = ((sigma_t / sigma_s0) * sample -
+ (alpha_t * (torch.exp(-h) - 1.0)) * D0 +
+ (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1)
+ elif self.config.algorithm_type == "dpmsolver":
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
+ if self.config.solver_type == "midpoint":
+ x_t = ((alpha_t / alpha_s0) * sample -
+ (sigma_t * (torch.exp(h) - 1.0)) * D0 - 0.5 *
+ (sigma_t * (torch.exp(h) - 1.0)) * D1)
+ elif self.config.solver_type == "heun":
+ x_t = ((alpha_t / alpha_s0) * sample -
+ (sigma_t * (torch.exp(h) - 1.0)) * D0 -
+ (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1)
+ elif self.config.algorithm_type == "sde-dpmsolver++":
+ assert noise is not None
+ if self.config.solver_type == "midpoint":
+ x_t = ((sigma_t / sigma_s0 * torch.exp(-h)) * sample +
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D0 + 0.5 *
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D1 +
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise)
+ elif self.config.solver_type == "heun":
+ x_t = ((sigma_t / sigma_s0 * torch.exp(-h)) * sample +
+ (alpha_t * (1 - torch.exp(-2.0 * h))) * D0 +
+ (alpha_t * ((1.0 - torch.exp(-2.0 * h)) /
+ (-2.0 * h) + 1.0)) * D1 +
+ sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise)
+ elif self.config.algorithm_type == "sde-dpmsolver":
+ assert noise is not None
+ if self.config.solver_type == "midpoint":
+ x_t = ((alpha_t / alpha_s0) * sample - 2.0 *
+ (sigma_t * (torch.exp(h) - 1.0)) * D0 -
+ (sigma_t * (torch.exp(h) - 1.0)) * D1 +
+ sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise)
+ elif self.config.solver_type == "heun":
+ x_t = ((alpha_t / alpha_s0) * sample - 2.0 *
+ (sigma_t * (torch.exp(h) - 1.0)) * D0 - 2.0 *
+ (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1 +
+ sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise)
+ return x_t # pyright: ignore
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.multistep_dpm_solver_third_order_update
+ def multistep_dpm_solver_third_order_update(
+ self,
+ model_output_list: List[torch.Tensor],
+ *args,
+ sample: torch.Tensor = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ One step for the third-order multistep DPMSolver.
+ Args:
+ model_output_list (`List[torch.Tensor]`):
+ The direct outputs from learned diffusion model at current and latter timesteps.
+ sample (`torch.Tensor`):
+ A current instance of a sample created by diffusion process.
+ Returns:
+ `torch.Tensor`:
+ The sample tensor at the previous timestep.
+ """
+
+ timestep_list = args[0] if len(args) > 0 else kwargs.pop(
+ "timestep_list", None)
+ prev_timestep = args[1] if len(args) > 1 else kwargs.pop(
+ "prev_timestep", None)
+ if sample is None:
+ if len(args) > 2:
+ sample = args[2]
+ else:
+ raise ValueError(
+ " missing`sample` as a required keyward argument")
+ if timestep_list is not None:
+ deprecate(
+ "timestep_list",
+ "1.0.0",
+ "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ if prev_timestep is not None:
+ deprecate(
+ "prev_timestep",
+ "1.0.0",
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ sigma_t, sigma_s0, sigma_s1, sigma_s2 = (
+ self.sigmas[self.step_index + 1], # pyright: ignore
+ self.sigmas[self.step_index],
+ self.sigmas[self.step_index - 1], # pyright: ignore
+ self.sigmas[self.step_index - 2], # pyright: ignore
+ )
+
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
+ alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1)
+ alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2)
+
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
+ lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1)
+ lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2)
+
+ m0, m1, m2 = model_output_list[-1], model_output_list[
+ -2], model_output_list[-3]
+
+ h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2
+ r0, r1 = h_0 / h, h_1 / h
+ D0 = m0
+ D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2)
+ D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1)
+ D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1)
+ if self.config.algorithm_type == "dpmsolver++":
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
+ x_t = ((sigma_t / sigma_s0) * sample -
+ (alpha_t * (torch.exp(-h) - 1.0)) * D0 +
+ (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1 -
+ (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2)
+ elif self.config.algorithm_type == "dpmsolver":
+ # See https://arxiv.org/abs/2206.00927 for detailed derivations
+ x_t = ((alpha_t / alpha_s0) * sample - (sigma_t *
+ (torch.exp(h) - 1.0)) * D0 -
+ (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1 -
+ (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2)
+ return x_t # pyright: ignore
+
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
+ if schedule_timesteps is None:
+ schedule_timesteps = self.timesteps
+
+ indices = (schedule_timesteps == timestep).nonzero()
+
+ # The sigma index that is taken for the **very** first `step`
+ # is always the second index (or the last index if there is only 1)
+ # This way we can ensure we don't accidentally skip a sigma in
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
+ pos = 1 if len(indices) > 1 else 0
+
+ return indices[pos].item()
+
+ def _init_step_index(self, timestep):
+ """
+ Initialize the step_index counter for the scheduler.
+ """
+
+ if self.begin_index is None:
+ if isinstance(timestep, torch.Tensor):
+ timestep = timestep.to(self.timesteps.device)
+ self._step_index = self.index_for_timestep(timestep)
+ else:
+ self._step_index = self._begin_index
+
+ # Modified from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.step
+ def step(
+ self,
+ model_output: torch.Tensor,
+ timestep: Union[int, torch.Tensor],
+ sample: torch.Tensor,
+ generator=None,
+ variance_noise: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ ) -> Union[SchedulerOutput, Tuple]:
+ """
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
+ the multistep DPMSolver.
+ Args:
+ model_output (`torch.Tensor`):
+ The direct output from learned diffusion model.
+ timestep (`int`):
+ The current discrete timestep in the diffusion chain.
+ sample (`torch.Tensor`):
+ A current instance of a sample created by the diffusion process.
+ generator (`torch.Generator`, *optional*):
+ A random number generator.
+ variance_noise (`torch.Tensor`):
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
+ itself. Useful for methods such as [`LEdits++`].
+ return_dict (`bool`):
+ Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
+ Returns:
+ [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
+ If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
+ tuple is returned where the first element is the sample tensor.
+ """
+ if self.num_inference_steps is None:
+ raise ValueError(
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
+ )
+
+ if self.step_index is None:
+ self._init_step_index(timestep)
+
+ # Improve numerical stability for small number of steps
+ lower_order_final = (self.step_index == len(self.timesteps) - 1) and (
+ self.config.euler_at_final or
+ (self.config.lower_order_final and len(self.timesteps) < 15) or
+ self.config.final_sigmas_type == "zero")
+ lower_order_second = ((self.step_index == len(self.timesteps) - 2) and
+ self.config.lower_order_final and
+ len(self.timesteps) < 15)
+
+ model_output = self.convert_model_output(model_output, sample=sample)
+ for i in range(self.config.solver_order - 1):
+ self.model_outputs[i] = self.model_outputs[i + 1]
+ self.model_outputs[-1] = model_output
+
+ # Upcast to avoid precision issues when computing prev_sample
+ sample = sample.to(torch.float32)
+ if self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"
+ ] and variance_noise is None:
+ noise = randn_tensor(
+ model_output.shape,
+ generator=generator,
+ device=model_output.device,
+ dtype=torch.float32)
+ elif self.config.algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
+ noise = variance_noise.to(
+ device=model_output.device,
+ dtype=torch.float32) # pyright: ignore
+ else:
+ noise = None
+
+ if self.config.solver_order == 1 or self.lower_order_nums < 1 or lower_order_final:
+ prev_sample = self.dpm_solver_first_order_update(
+ model_output, sample=sample, noise=noise)
+ elif self.config.solver_order == 2 or self.lower_order_nums < 2 or lower_order_second:
+ prev_sample = self.multistep_dpm_solver_second_order_update(
+ self.model_outputs, sample=sample, noise=noise)
+ else:
+ prev_sample = self.multistep_dpm_solver_third_order_update(
+ self.model_outputs, sample=sample)
+
+ if self.lower_order_nums < self.config.solver_order:
+ self.lower_order_nums += 1
+
+ # Cast sample back to expected dtype
+ prev_sample = prev_sample.to(model_output.dtype)
+
+ # upon completion increase step index by one
+ self._step_index += 1 # pyright: ignore
+
+ if not return_dict:
+ return (prev_sample,)
+
+ return SchedulerOutput(prev_sample=prev_sample)
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.scale_model_input
+ def scale_model_input(self, sample: torch.Tensor, *args,
+ **kwargs) -> torch.Tensor:
+ """
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
+ current timestep.
+ Args:
+ sample (`torch.Tensor`):
+ The input sample.
+ Returns:
+ `torch.Tensor`:
+ A scaled input sample.
+ """
+ return sample
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.scale_model_input
+ def add_noise(
+ self,
+ original_samples: torch.Tensor,
+ noise: torch.Tensor,
+ timesteps: torch.IntTensor,
+ ) -> torch.Tensor:
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
+ sigmas = self.sigmas.to(
+ device=original_samples.device, dtype=original_samples.dtype)
+ if original_samples.device.type == "mps" and torch.is_floating_point(
+ timesteps):
+ # mps does not support float64
+ schedule_timesteps = self.timesteps.to(
+ original_samples.device, dtype=torch.float32)
+ timesteps = timesteps.to(
+ original_samples.device, dtype=torch.float32)
+ else:
+ schedule_timesteps = self.timesteps.to(original_samples.device)
+ timesteps = timesteps.to(original_samples.device)
+
+ # begin_index is None when the scheduler is used for training or pipeline does not implement set_begin_index
+ if self.begin_index is None:
+ step_indices = [
+ self.index_for_timestep(t, schedule_timesteps)
+ for t in timesteps
+ ]
+ elif self.step_index is not None:
+ # add_noise is called after first denoising step (for inpainting)
+ step_indices = [self.step_index] * timesteps.shape[0]
+ else:
+ # add noise is called before first denoising step to create initial latent(img2img)
+ step_indices = [self.begin_index] * timesteps.shape[0]
+
+ sigma = sigmas[step_indices].flatten()
+ while len(sigma.shape) < len(original_samples.shape):
+ sigma = sigma.unsqueeze(-1)
+
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
+ noisy_samples = alpha_t * original_samples + sigma_t * noise
+ return noisy_samples
+
+ def __len__(self):
+ return self.config.num_train_timesteps
diff --git a/wan/utils/fm_solvers_unipc.py b/wan/utils/fm_solvers_unipc.py
new file mode 100644
index 0000000000000000000000000000000000000000..88b894590ef8a371dbbf651fc457a6e430520b89
--- /dev/null
+++ b/wan/utils/fm_solvers_unipc.py
@@ -0,0 +1,802 @@
+# Copied from https://github.com/huggingface/diffusers/blob/v0.31.0/src/diffusers/schedulers/scheduling_unipc_multistep.py
+# Convert unipc for flow matching
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+
+import math
+from typing import List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.schedulers.scheduling_utils import (
+ KarrasDiffusionSchedulers,
+ SchedulerMixin,
+ SchedulerOutput,
+)
+from diffusers.utils import deprecate, is_scipy_available
+
+if is_scipy_available():
+ import scipy.stats
+
+
+class FlowUniPCMultistepScheduler(SchedulerMixin, ConfigMixin):
+ """
+ `UniPCMultistepScheduler` is a training-free framework designed for the fast sampling of diffusion models.
+
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
+ methods the library implements for all schedulers such as loading and saving.
+
+ Args:
+ num_train_timesteps (`int`, defaults to 1000):
+ The number of diffusion steps to train the model.
+ solver_order (`int`, default `2`):
+ The UniPC order which can be any positive integer. The effective order of accuracy is `solver_order + 1`
+ due to the UniC. It is recommended to use `solver_order=2` for guided sampling, and `solver_order=3` for
+ unconditional sampling.
+ prediction_type (`str`, defaults to "flow_prediction"):
+ Prediction type of the scheduler function; must be `flow_prediction` for this scheduler, which predicts
+ the flow of the diffusion process.
+ thresholding (`bool`, defaults to `False`):
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
+ as Stable Diffusion.
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
+ sample_max_value (`float`, defaults to 1.0):
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True` and `predict_x0=True`.
+ predict_x0 (`bool`, defaults to `True`):
+ Whether to use the updating algorithm on the predicted x0.
+ solver_type (`str`, default `bh2`):
+ Solver type for UniPC. It is recommended to use `bh1` for unconditional sampling when steps < 10, and `bh2`
+ otherwise.
+ lower_order_final (`bool`, default `True`):
+ Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can
+ stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10.
+ disable_corrector (`list`, default `[]`):
+ Decides which step to disable the corrector to mitigate the misalignment between `epsilon_theta(x_t, c)`
+ and `epsilon_theta(x_t^c, c)` which can influence convergence for a large guidance scale. Corrector is
+ usually disabled during the first few steps.
+ solver_p (`SchedulerMixin`, default `None`):
+ Any other scheduler that if specified, the algorithm becomes `solver_p + UniC`.
+ use_karras_sigmas (`bool`, *optional*, defaults to `False`):
+ Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
+ the sigmas are determined according to a sequence of noise levels {σi}.
+ use_exponential_sigmas (`bool`, *optional*, defaults to `False`):
+ Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process.
+ timestep_spacing (`str`, defaults to `"linspace"`):
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
+ steps_offset (`int`, defaults to 0):
+ An offset added to the inference steps, as required by some model families.
+ final_sigmas_type (`str`, defaults to `"zero"`):
+ The final `sigma` value for the noise schedule during the sampling process. If `"sigma_min"`, the final
+ sigma is the same as the last sigma in the training schedule. If `zero`, the final sigma is set to 0.
+ """
+
+ _compatibles = [e.name for e in KarrasDiffusionSchedulers]
+ order = 1
+
+ @register_to_config
+ def __init__(
+ self,
+ num_train_timesteps: int = 1000,
+ solver_order: int = 2,
+ prediction_type: str = "flow_prediction",
+ shift: Optional[float] = 1.0,
+ use_dynamic_shifting=False,
+ thresholding: bool = False,
+ dynamic_thresholding_ratio: float = 0.995,
+ sample_max_value: float = 1.0,
+ predict_x0: bool = True,
+ solver_type: str = "bh2",
+ lower_order_final: bool = True,
+ disable_corrector: List[int] = [],
+ solver_p: SchedulerMixin = None,
+ timestep_spacing: str = "linspace",
+ steps_offset: int = 0,
+ final_sigmas_type: Optional[str] = "zero", # "zero", "sigma_min"
+ ):
+
+ if solver_type not in ["bh1", "bh2"]:
+ if solver_type in ["midpoint", "heun", "logrho"]:
+ self.register_to_config(solver_type="bh2")
+ else:
+ raise NotImplementedError(
+ f"{solver_type} is not implemented for {self.__class__}")
+
+ self.predict_x0 = predict_x0
+ # setable values
+ self.num_inference_steps = None
+ alphas = np.linspace(1, 1 / num_train_timesteps,
+ num_train_timesteps)[::-1].copy()
+ sigmas = 1.0 - alphas
+ sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32)
+
+ if not use_dynamic_shifting:
+ # when use_dynamic_shifting is True, we apply the timestep shifting on the fly based on the image resolution
+ sigmas = shift * sigmas / (1 +
+ (shift - 1) * sigmas) # pyright: ignore
+
+ self.sigmas = sigmas
+ self.timesteps = sigmas * num_train_timesteps
+
+ self.model_outputs = [None] * solver_order
+ self.timestep_list = [None] * solver_order
+ self.lower_order_nums = 0
+ self.disable_corrector = disable_corrector
+ self.solver_p = solver_p
+ self.last_sample = None
+ self._step_index = None
+ self._begin_index = None
+
+ self.sigmas = self.sigmas.to(
+ "cpu") # to avoid too much CPU/GPU communication
+ self.sigma_min = self.sigmas[-1].item()
+ self.sigma_max = self.sigmas[0].item()
+
+ @property
+ def step_index(self):
+ """
+ The index counter for current timestep. It will increase 1 after each scheduler step.
+ """
+ return self._step_index
+
+ @property
+ def begin_index(self):
+ """
+ The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
+ """
+ return self._begin_index
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
+ def set_begin_index(self, begin_index: int = 0):
+ """
+ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
+
+ Args:
+ begin_index (`int`):
+ The begin index for the scheduler.
+ """
+ self._begin_index = begin_index
+
+ # Modified from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler.set_timesteps
+ def set_timesteps(
+ self,
+ num_inference_steps: Union[int, None] = None,
+ device: Union[str, torch.device] = None,
+ sigmas: Optional[List[float]] = None,
+ mu: Optional[Union[float, None]] = None,
+ shift: Optional[Union[float, None]] = None,
+ ):
+ """
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
+ Args:
+ num_inference_steps (`int`):
+ Total number of the spacing of the time steps.
+ device (`str` or `torch.device`, *optional*):
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
+ """
+
+ if self.config.use_dynamic_shifting and mu is None:
+ raise ValueError(
+ " you have to pass a value for `mu` when `use_dynamic_shifting` is set to be `True`"
+ )
+
+ if sigmas is None:
+ sigmas = np.linspace(self.sigma_max, self.sigma_min,
+ num_inference_steps +
+ 1).copy()[:-1] # pyright: ignore
+
+ if self.config.use_dynamic_shifting:
+ sigmas = self.time_shift(mu, 1.0, sigmas) # pyright: ignore
+ else:
+ if shift is None:
+ shift = self.config.shift
+ sigmas = shift * sigmas / (1 +
+ (shift - 1) * sigmas) # pyright: ignore
+
+ if self.config.final_sigmas_type == "sigma_min":
+ sigma_last = ((1 - self.alphas_cumprod[0]) /
+ self.alphas_cumprod[0])**0.5
+ elif self.config.final_sigmas_type == "zero":
+ sigma_last = 0
+ else:
+ raise ValueError(
+ f"`final_sigmas_type` must be one of 'zero', or 'sigma_min', but got {self.config.final_sigmas_type}"
+ )
+
+ timesteps = sigmas * self.config.num_train_timesteps
+ sigmas = np.concatenate([sigmas, [sigma_last]
+ ]).astype(np.float32) # pyright: ignore
+
+ self.sigmas = torch.from_numpy(sigmas)
+ self.timesteps = torch.from_numpy(timesteps).to(
+ device=device, dtype=torch.int64)
+
+ self.num_inference_steps = len(timesteps)
+
+ self.model_outputs = [
+ None,
+ ] * self.config.solver_order
+ self.lower_order_nums = 0
+ self.last_sample = None
+ if self.solver_p:
+ self.solver_p.set_timesteps(self.num_inference_steps, device=device)
+
+ # add an index counter for schedulers that allow duplicated timesteps
+ self._step_index = None
+ self._begin_index = None
+ self.sigmas = self.sigmas.to(
+ "cpu") # to avoid too much CPU/GPU communication
+
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
+ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
+ """
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
+
+ https://arxiv.org/abs/2205.11487
+ """
+ dtype = sample.dtype
+ batch_size, channels, *remaining_dims = sample.shape
+
+ if dtype not in (torch.float32, torch.float64):
+ sample = sample.float(
+ ) # upcast for quantile calculation, and clamp not implemented for cpu half
+
+ # Flatten sample for doing quantile calculation along each image
+ sample = sample.reshape(batch_size, channels * np.prod(remaining_dims))
+
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
+
+ s = torch.quantile(
+ abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
+ s = torch.clamp(
+ s, min=1, max=self.config.sample_max_value
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
+ s = s.unsqueeze(
+ 1) # (batch_size, 1) because clamp will broadcast along dim=0
+ sample = torch.clamp(
+ sample, -s, s
+ ) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
+
+ sample = sample.reshape(batch_size, channels, *remaining_dims)
+ sample = sample.to(dtype)
+
+ return sample
+
+ # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler._sigma_to_t
+ def _sigma_to_t(self, sigma):
+ return sigma * self.config.num_train_timesteps
+
+ def _sigma_to_alpha_sigma_t(self, sigma):
+ return 1 - sigma, sigma
+
+ # Copied from diffusers.schedulers.scheduling_flow_match_euler_discrete.set_timesteps
+ def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1)**sigma)
+
+ def convert_model_output(
+ self,
+ model_output: torch.Tensor,
+ *args,
+ sample: torch.Tensor = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ r"""
+ Convert the model output to the corresponding type the UniPC algorithm needs.
+
+ Args:
+ model_output (`torch.Tensor`):
+ The direct output from the learned diffusion model.
+ timestep (`int`):
+ The current discrete timestep in the diffusion chain.
+ sample (`torch.Tensor`):
+ A current instance of a sample created by the diffusion process.
+
+ Returns:
+ `torch.Tensor`:
+ The converted model output.
+ """
+ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None)
+ if sample is None:
+ if len(args) > 1:
+ sample = args[1]
+ else:
+ raise ValueError(
+ "missing `sample` as a required keyward argument")
+ if timestep is not None:
+ deprecate(
+ "timesteps",
+ "1.0.0",
+ "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ sigma = self.sigmas[self.step_index]
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
+
+ if self.predict_x0:
+ if self.config.prediction_type == "flow_prediction":
+ sigma_t = self.sigmas[self.step_index]
+ x0_pred = sample - sigma_t * model_output
+ else:
+ raise ValueError(
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`,"
+ " `v_prediction` or `flow_prediction` for the UniPCMultistepScheduler."
+ )
+
+ if self.config.thresholding:
+ x0_pred = self._threshold_sample(x0_pred)
+
+ return x0_pred
+ else:
+ if self.config.prediction_type == "flow_prediction":
+ sigma_t = self.sigmas[self.step_index]
+ epsilon = sample - (1 - sigma_t) * model_output
+ else:
+ raise ValueError(
+ f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`,"
+ " `v_prediction` or `flow_prediction` for the UniPCMultistepScheduler."
+ )
+
+ if self.config.thresholding:
+ sigma_t = self.sigmas[self.step_index]
+ x0_pred = sample - sigma_t * model_output
+ x0_pred = self._threshold_sample(x0_pred)
+ epsilon = model_output + x0_pred
+
+ return epsilon
+
+ def multistep_uni_p_bh_update(
+ self,
+ model_output: torch.Tensor,
+ *args,
+ sample: torch.Tensor = None,
+ order: int = None, # pyright: ignore
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ One step for the UniP (B(h) version). Alternatively, `self.solver_p` is used if is specified.
+
+ Args:
+ model_output (`torch.Tensor`):
+ The direct output from the learned diffusion model at the current timestep.
+ prev_timestep (`int`):
+ The previous discrete timestep in the diffusion chain.
+ sample (`torch.Tensor`):
+ A current instance of a sample created by the diffusion process.
+ order (`int`):
+ The order of UniP at this timestep (corresponds to the *p* in UniPC-p).
+
+ Returns:
+ `torch.Tensor`:
+ The sample tensor at the previous timestep.
+ """
+ prev_timestep = args[0] if len(args) > 0 else kwargs.pop(
+ "prev_timestep", None)
+ if sample is None:
+ if len(args) > 1:
+ sample = args[1]
+ else:
+ raise ValueError(
+ " missing `sample` as a required keyward argument")
+ if order is None:
+ if len(args) > 2:
+ order = args[2]
+ else:
+ raise ValueError(
+ " missing `order` as a required keyward argument")
+ if prev_timestep is not None:
+ deprecate(
+ "prev_timestep",
+ "1.0.0",
+ "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+ model_output_list = self.model_outputs
+
+ s0 = self.timestep_list[-1]
+ m0 = model_output_list[-1]
+ x = sample
+
+ if self.solver_p:
+ x_t = self.solver_p.step(model_output, s0, x).prev_sample
+ return x_t
+
+ sigma_t, sigma_s0 = self.sigmas[self.step_index + 1], self.sigmas[
+ self.step_index] # pyright: ignore
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
+
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
+
+ h = lambda_t - lambda_s0
+ device = sample.device
+
+ rks = []
+ D1s = []
+ for i in range(1, order):
+ si = self.step_index - i # pyright: ignore
+ mi = model_output_list[-(i + 1)]
+ alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
+ lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
+ rk = (lambda_si - lambda_s0) / h
+ rks.append(rk)
+ D1s.append((mi - m0) / rk) # pyright: ignore
+
+ rks.append(1.0)
+ rks = torch.tensor(rks, device=device)
+
+ R = []
+ b = []
+
+ hh = -h if self.predict_x0 else h
+ h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
+ h_phi_k = h_phi_1 / hh - 1
+
+ factorial_i = 1
+
+ if self.config.solver_type == "bh1":
+ B_h = hh
+ elif self.config.solver_type == "bh2":
+ B_h = torch.expm1(hh)
+ else:
+ raise NotImplementedError()
+
+ for i in range(1, order + 1):
+ R.append(torch.pow(rks, i - 1))
+ b.append(h_phi_k * factorial_i / B_h)
+ factorial_i *= i + 1
+ h_phi_k = h_phi_k / hh - 1 / factorial_i
+
+ R = torch.stack(R)
+ b = torch.tensor(b, device=device)
+
+ if len(D1s) > 0:
+ D1s = torch.stack(D1s, dim=1) # (B, K)
+ # for order 2, we use a simplified version
+ if order == 2:
+ rhos_p = torch.tensor([0.5], dtype=x.dtype, device=device)
+ else:
+ rhos_p = torch.linalg.solve(R[:-1, :-1],
+ b[:-1]).to(device).to(x.dtype)
+ else:
+ D1s = None
+
+ if self.predict_x0:
+ x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
+ if D1s is not None:
+ pred_res = torch.einsum("k,bkc...->bc...", rhos_p,
+ D1s) # pyright: ignore
+ else:
+ pred_res = 0
+ x_t = x_t_ - alpha_t * B_h * pred_res
+ else:
+ x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
+ if D1s is not None:
+ pred_res = torch.einsum("k,bkc...->bc...", rhos_p,
+ D1s) # pyright: ignore
+ else:
+ pred_res = 0
+ x_t = x_t_ - sigma_t * B_h * pred_res
+
+ x_t = x_t.to(x.dtype)
+ return x_t
+
+ def multistep_uni_c_bh_update(
+ self,
+ this_model_output: torch.Tensor,
+ *args,
+ last_sample: torch.Tensor = None,
+ this_sample: torch.Tensor = None,
+ order: int = None, # pyright: ignore
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ One step for the UniC (B(h) version).
+
+ Args:
+ this_model_output (`torch.Tensor`):
+ The model outputs at `x_t`.
+ this_timestep (`int`):
+ The current timestep `t`.
+ last_sample (`torch.Tensor`):
+ The generated sample before the last predictor `x_{t-1}`.
+ this_sample (`torch.Tensor`):
+ The generated sample after the last predictor `x_{t}`.
+ order (`int`):
+ The `p` of UniC-p at this step. The effective order of accuracy should be `order + 1`.
+
+ Returns:
+ `torch.Tensor`:
+ The corrected sample tensor at the current timestep.
+ """
+ this_timestep = args[0] if len(args) > 0 else kwargs.pop(
+ "this_timestep", None)
+ if last_sample is None:
+ if len(args) > 1:
+ last_sample = args[1]
+ else:
+ raise ValueError(
+ " missing`last_sample` as a required keyward argument")
+ if this_sample is None:
+ if len(args) > 2:
+ this_sample = args[2]
+ else:
+ raise ValueError(
+ " missing`this_sample` as a required keyward argument")
+ if order is None:
+ if len(args) > 3:
+ order = args[3]
+ else:
+ raise ValueError(
+ " missing`order` as a required keyward argument")
+ if this_timestep is not None:
+ deprecate(
+ "this_timestep",
+ "1.0.0",
+ "Passing `this_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`",
+ )
+
+ model_output_list = self.model_outputs
+
+ m0 = model_output_list[-1]
+ x = last_sample
+ x_t = this_sample
+ model_t = this_model_output
+
+ sigma_t, sigma_s0 = self.sigmas[self.step_index], self.sigmas[
+ self.step_index - 1] # pyright: ignore
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t)
+ alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0)
+
+ lambda_t = torch.log(alpha_t) - torch.log(sigma_t)
+ lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0)
+
+ h = lambda_t - lambda_s0
+ device = this_sample.device
+
+ rks = []
+ D1s = []
+ for i in range(1, order):
+ si = self.step_index - (i + 1) # pyright: ignore
+ mi = model_output_list[-(i + 1)]
+ alpha_si, sigma_si = self._sigma_to_alpha_sigma_t(self.sigmas[si])
+ lambda_si = torch.log(alpha_si) - torch.log(sigma_si)
+ rk = (lambda_si - lambda_s0) / h
+ rks.append(rk)
+ D1s.append((mi - m0) / rk) # pyright: ignore
+
+ rks.append(1.0)
+ rks = torch.tensor(rks, device=device)
+
+ R = []
+ b = []
+
+ hh = -h if self.predict_x0 else h
+ h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1
+ h_phi_k = h_phi_1 / hh - 1
+
+ factorial_i = 1
+
+ if self.config.solver_type == "bh1":
+ B_h = hh
+ elif self.config.solver_type == "bh2":
+ B_h = torch.expm1(hh)
+ else:
+ raise NotImplementedError()
+
+ for i in range(1, order + 1):
+ R.append(torch.pow(rks, i - 1))
+ b.append(h_phi_k * factorial_i / B_h)
+ factorial_i *= i + 1
+ h_phi_k = h_phi_k / hh - 1 / factorial_i
+
+ R = torch.stack(R)
+ b = torch.tensor(b, device=device)
+
+ if len(D1s) > 0:
+ D1s = torch.stack(D1s, dim=1)
+ else:
+ D1s = None
+
+ # for order 1, we use a simplified version
+ if order == 1:
+ rhos_c = torch.tensor([0.5], dtype=x.dtype, device=device)
+ else:
+ rhos_c = torch.linalg.solve(R, b).to(device).to(x.dtype)
+
+ if self.predict_x0:
+ x_t_ = sigma_t / sigma_s0 * x - alpha_t * h_phi_1 * m0
+ if D1s is not None:
+ corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
+ else:
+ corr_res = 0
+ D1_t = model_t - m0
+ x_t = x_t_ - alpha_t * B_h * (corr_res + rhos_c[-1] * D1_t)
+ else:
+ x_t_ = alpha_t / alpha_s0 * x - sigma_t * h_phi_1 * m0
+ if D1s is not None:
+ corr_res = torch.einsum("k,bkc...->bc...", rhos_c[:-1], D1s)
+ else:
+ corr_res = 0
+ D1_t = model_t - m0
+ x_t = x_t_ - sigma_t * B_h * (corr_res + rhos_c[-1] * D1_t)
+ x_t = x_t.to(x.dtype)
+ return x_t
+
+ def index_for_timestep(self, timestep, schedule_timesteps=None):
+ if schedule_timesteps is None:
+ schedule_timesteps = self.timesteps
+
+ indices = (schedule_timesteps == timestep).nonzero()
+
+ # The sigma index that is taken for the **very** first `step`
+ # is always the second index (or the last index if there is only 1)
+ # This way we can ensure we don't accidentally skip a sigma in
+ # case we start in the middle of the denoising schedule (e.g. for image-to-image)
+ pos = 1 if len(indices) > 1 else 0
+
+ return indices[pos].item()
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler._init_step_index
+ def _init_step_index(self, timestep):
+ """
+ Initialize the step_index counter for the scheduler.
+ """
+
+ if self.begin_index is None:
+ if isinstance(timestep, torch.Tensor):
+ timestep = timestep.to(self.timesteps.device)
+ self._step_index = self.index_for_timestep(timestep)
+ else:
+ self._step_index = self._begin_index
+
+ def step(self,
+ model_output: torch.Tensor,
+ timestep: Union[int, torch.Tensor],
+ sample: torch.Tensor,
+ return_dict: bool = True,
+ generator=None) -> Union[SchedulerOutput, Tuple]:
+ """
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the sample with
+ the multistep UniPC.
+
+ Args:
+ model_output (`torch.Tensor`):
+ The direct output from learned diffusion model.
+ timestep (`int`):
+ The current discrete timestep in the diffusion chain.
+ sample (`torch.Tensor`):
+ A current instance of a sample created by the diffusion process.
+ return_dict (`bool`):
+ Whether or not to return a [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`.
+
+ Returns:
+ [`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
+ If return_dict is `True`, [`~schedulers.scheduling_utils.SchedulerOutput`] is returned, otherwise a
+ tuple is returned where the first element is the sample tensor.
+
+ """
+ if self.num_inference_steps is None:
+ raise ValueError(
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
+ )
+
+ if self.step_index is None:
+ self._init_step_index(timestep)
+
+ use_corrector = (
+ self.step_index > 0 and
+ self.step_index - 1 not in self.disable_corrector and
+ self.last_sample is not None # pyright: ignore
+ )
+
+ model_output_convert = self.convert_model_output(
+ model_output, sample=sample)
+ if use_corrector:
+ sample = self.multistep_uni_c_bh_update(
+ this_model_output=model_output_convert,
+ last_sample=self.last_sample,
+ this_sample=sample,
+ order=self.this_order,
+ )
+
+ for i in range(self.config.solver_order - 1):
+ self.model_outputs[i] = self.model_outputs[i + 1]
+ self.timestep_list[i] = self.timestep_list[i + 1]
+
+ self.model_outputs[-1] = model_output_convert
+ self.timestep_list[-1] = timestep # pyright: ignore
+
+ if self.config.lower_order_final:
+ this_order = min(self.config.solver_order,
+ len(self.timesteps) -
+ self.step_index) # pyright: ignore
+ else:
+ this_order = self.config.solver_order
+
+ self.this_order = min(this_order,
+ self.lower_order_nums + 1) # warmup for multistep
+ assert self.this_order > 0
+
+ self.last_sample = sample
+ prev_sample = self.multistep_uni_p_bh_update(
+ model_output=model_output, # pass the original non-converted model output, in case solver-p is used
+ sample=sample,
+ order=self.this_order,
+ )
+
+ if self.lower_order_nums < self.config.solver_order:
+ self.lower_order_nums += 1
+
+ # upon completion increase step index by one
+ self._step_index += 1 # pyright: ignore
+
+ if not return_dict:
+ return (prev_sample,)
+
+ return SchedulerOutput(prev_sample=prev_sample)
+
+ def scale_model_input(self, sample: torch.Tensor, *args,
+ **kwargs) -> torch.Tensor:
+ """
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
+ current timestep.
+
+ Args:
+ sample (`torch.Tensor`):
+ The input sample.
+
+ Returns:
+ `torch.Tensor`:
+ A scaled input sample.
+ """
+ return sample
+
+ # Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.add_noise
+ def add_noise(
+ self,
+ original_samples: torch.Tensor,
+ noise: torch.Tensor,
+ timesteps: torch.IntTensor,
+ ) -> torch.Tensor:
+ # Make sure sigmas and timesteps have the same device and dtype as original_samples
+ sigmas = self.sigmas.to(
+ device=original_samples.device, dtype=original_samples.dtype)
+ if original_samples.device.type == "mps" and torch.is_floating_point(
+ timesteps):
+ # mps does not support float64
+ schedule_timesteps = self.timesteps.to(
+ original_samples.device, dtype=torch.float32)
+ timesteps = timesteps.to(
+ original_samples.device, dtype=torch.float32)
+ else:
+ schedule_timesteps = self.timesteps.to(original_samples.device)
+ timesteps = timesteps.to(original_samples.device)
+
+ # begin_index is None when the scheduler is used for training or pipeline does not implement set_begin_index
+ if self.begin_index is None:
+ step_indices = [
+ self.index_for_timestep(t, schedule_timesteps)
+ for t in timesteps
+ ]
+ elif self.step_index is not None:
+ # add_noise is called after first denoising step (for inpainting)
+ step_indices = [self.step_index] * timesteps.shape[0]
+ else:
+ # add noise is called before first denoising step to create initial latent(img2img)
+ step_indices = [self.begin_index] * timesteps.shape[0]
+
+ sigma = sigmas[step_indices].flatten()
+ while len(sigma.shape) < len(original_samples.shape):
+ sigma = sigma.unsqueeze(-1)
+
+ alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma)
+ noisy_samples = alpha_t * original_samples + sigma_t * noise
+ return noisy_samples
+
+ def __len__(self):
+ return self.config.num_train_timesteps
diff --git a/wan/utils/prompt_extend.py b/wan/utils/prompt_extend.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cec9b84e98c0d57ff29acdf11d83f8b877e4800
--- /dev/null
+++ b/wan/utils/prompt_extend.py
@@ -0,0 +1,542 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import json
+import logging
+import math
+import os
+import random
+import sys
+import tempfile
+from dataclasses import dataclass
+from http import HTTPStatus
+from typing import Optional, Union
+
+import dashscope
+import torch
+from PIL import Image
+
+try:
+ from flash_attn import flash_attn_varlen_func
+ FLASH_VER = 2
+except ModuleNotFoundError:
+ flash_attn_varlen_func = None # in compatible with CPU machines
+ FLASH_VER = None
+
+from .system_prompt import *
+
+DEFAULT_SYS_PROMPTS = {
+ "t2v-A14B": {
+ "zh": T2V_A14B_ZH_SYS_PROMPT,
+ "en": T2V_A14B_EN_SYS_PROMPT,
+ },
+ "i2v-A14B": {
+ "zh": I2V_A14B_ZH_SYS_PROMPT,
+ "en": I2V_A14B_EN_SYS_PROMPT,
+ "empty": {
+ "zh": I2V_A14B_EMPTY_ZH_SYS_PROMPT,
+ "en": I2V_A14B_EMPTY_EN_SYS_PROMPT,
+ }
+ },
+ "ti2v-5B": {
+ "t2v": {
+ "zh": T2V_A14B_ZH_SYS_PROMPT,
+ "en": T2V_A14B_EN_SYS_PROMPT,
+ },
+ "i2v": {
+ "zh": I2V_A14B_ZH_SYS_PROMPT,
+ "en": I2V_A14B_EN_SYS_PROMPT,
+ }
+ },
+}
+
+
+@dataclass
+class PromptOutput(object):
+ status: bool
+ prompt: str
+ seed: int
+ system_prompt: str
+ message: str
+
+ def add_custom_field(self, key: str, value) -> None:
+ self.__setattr__(key, value)
+
+
+class PromptExpander:
+
+ def __init__(self, model_name, task, is_vl=False, device=0, **kwargs):
+ self.model_name = model_name
+ self.task = task
+ self.is_vl = is_vl
+ self.device = device
+
+ def extend_with_img(self,
+ prompt,
+ system_prompt,
+ image=None,
+ seed=-1,
+ *args,
+ **kwargs):
+ pass
+
+ def extend(self, prompt, system_prompt, seed=-1, *args, **kwargs):
+ pass
+
+ def decide_system_prompt(self, tar_lang="zh", prompt=None):
+ assert self.task is not None
+ if "ti2v" in self.task:
+ if self.is_vl:
+ return DEFAULT_SYS_PROMPTS[self.task]["i2v"][tar_lang]
+ else:
+ return DEFAULT_SYS_PROMPTS[self.task]["t2v"][tar_lang]
+ if "i2v" in self.task and len(prompt) == 0:
+ return DEFAULT_SYS_PROMPTS[self.task]["empty"][tar_lang]
+ return DEFAULT_SYS_PROMPTS[self.task][tar_lang]
+
+ def __call__(self,
+ prompt,
+ system_prompt=None,
+ tar_lang="zh",
+ image=None,
+ seed=-1,
+ *args,
+ **kwargs):
+ if system_prompt is None:
+ system_prompt = self.decide_system_prompt(
+ tar_lang=tar_lang, prompt=prompt)
+ if seed < 0:
+ seed = random.randint(0, sys.maxsize)
+ if image is not None and self.is_vl:
+ return self.extend_with_img(
+ prompt, system_prompt, image=image, seed=seed, *args, **kwargs)
+ elif not self.is_vl:
+ return self.extend(prompt, system_prompt, seed, *args, **kwargs)
+ else:
+ raise NotImplementedError
+
+
+class DashScopePromptExpander(PromptExpander):
+
+ def __init__(self,
+ api_key=None,
+ model_name=None,
+ task=None,
+ max_image_size=512 * 512,
+ retry_times=4,
+ is_vl=False,
+ **kwargs):
+ '''
+ Args:
+ api_key: The API key for Dash Scope authentication and access to related services.
+ model_name: Model name, 'qwen-plus' for extending prompts, 'qwen-vl-max' for extending prompt-images.
+ task: Task name. This is required to determine the default system prompt.
+ max_image_size: The maximum size of the image; unit unspecified (e.g., pixels, KB). Please specify the unit based on actual usage.
+ retry_times: Number of retry attempts in case of request failure.
+ is_vl: A flag indicating whether the task involves visual-language processing.
+ **kwargs: Additional keyword arguments that can be passed to the function or method.
+ '''
+ if model_name is None:
+ model_name = 'qwen-plus' if not is_vl else 'qwen-vl-max'
+ super().__init__(model_name, task, is_vl, **kwargs)
+ if api_key is not None:
+ dashscope.api_key = api_key
+ elif 'DASH_API_KEY' in os.environ and os.environ[
+ 'DASH_API_KEY'] is not None:
+ dashscope.api_key = os.environ['DASH_API_KEY']
+ else:
+ raise ValueError("DASH_API_KEY is not set")
+ if 'DASH_API_URL' in os.environ and os.environ[
+ 'DASH_API_URL'] is not None:
+ dashscope.base_http_api_url = os.environ['DASH_API_URL']
+ else:
+ dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
+ self.api_key = api_key
+
+ self.max_image_size = max_image_size
+ self.model = model_name
+ self.retry_times = retry_times
+
+ def extend(self, prompt, system_prompt, seed=-1, *args, **kwargs):
+ messages = [{
+ 'role': 'system',
+ 'content': system_prompt
+ }, {
+ 'role': 'user',
+ 'content': prompt
+ }]
+
+ exception = None
+ for _ in range(self.retry_times):
+ try:
+ response = dashscope.Generation.call(
+ self.model,
+ messages=messages,
+ seed=seed,
+ result_format='message', # set the result to be "message" format.
+ )
+ assert response.status_code == HTTPStatus.OK, response
+ expanded_prompt = response['output']['choices'][0]['message'][
+ 'content']
+ return PromptOutput(
+ status=True,
+ prompt=expanded_prompt,
+ seed=seed,
+ system_prompt=system_prompt,
+ message=json.dumps(response, ensure_ascii=False))
+ except Exception as e:
+ exception = e
+ return PromptOutput(
+ status=False,
+ prompt=prompt,
+ seed=seed,
+ system_prompt=system_prompt,
+ message=str(exception))
+
+ def extend_with_img(self,
+ prompt,
+ system_prompt,
+ image: Union[Image.Image, str] = None,
+ seed=-1,
+ *args,
+ **kwargs):
+ if isinstance(image, str):
+ image = Image.open(image).convert('RGB')
+ w = image.width
+ h = image.height
+ area = min(w * h, self.max_image_size)
+ aspect_ratio = h / w
+ resized_h = round(math.sqrt(area * aspect_ratio))
+ resized_w = round(math.sqrt(area / aspect_ratio))
+ image = image.resize((resized_w, resized_h))
+ with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as f:
+ image.save(f.name)
+ fname = f.name
+ image_path = f"file://{f.name}"
+ prompt = f"{prompt}"
+ messages = [
+ {
+ 'role': 'system',
+ 'content': [{
+ "text": system_prompt
+ }]
+ },
+ {
+ 'role': 'user',
+ 'content': [{
+ "text": prompt
+ }, {
+ "image": image_path
+ }]
+ },
+ ]
+ response = None
+ result_prompt = prompt
+ exception = None
+ status = False
+ for _ in range(self.retry_times):
+ try:
+ response = dashscope.MultiModalConversation.call(
+ self.model,
+ messages=messages,
+ seed=seed,
+ result_format='message', # set the result to be "message" format.
+ )
+ assert response.status_code == HTTPStatus.OK, response
+ result_prompt = response['output']['choices'][0]['message'][
+ 'content'][0]['text'].replace('\n', '\\n')
+ status = True
+ break
+ except Exception as e:
+ exception = e
+ result_prompt = result_prompt.replace('\n', '\\n')
+ os.remove(fname)
+
+ return PromptOutput(
+ status=status,
+ prompt=result_prompt,
+ seed=seed,
+ system_prompt=system_prompt,
+ message=str(exception) if not status else json.dumps(
+ response, ensure_ascii=False))
+
+
+class QwenPromptExpander(PromptExpander):
+ model_dict = {
+ "QwenVL2.5_3B": "Qwen/Qwen2.5-VL-3B-Instruct",
+ "QwenVL2.5_7B": "Qwen/Qwen2.5-VL-7B-Instruct",
+ "Qwen2.5_3B": "Qwen/Qwen2.5-3B-Instruct",
+ "Qwen2.5_7B": "Qwen/Qwen2.5-7B-Instruct",
+ "Qwen2.5_14B": "Qwen/Qwen2.5-14B-Instruct",
+ }
+
+ def __init__(self,
+ model_name=None,
+ task=None,
+ device=0,
+ is_vl=False,
+ **kwargs):
+ '''
+ Args:
+ model_name: Use predefined model names such as 'QwenVL2.5_7B' and 'Qwen2.5_14B',
+ which are specific versions of the Qwen model. Alternatively, you can use the
+ local path to a downloaded model or the model name from Hugging Face."
+ Detailed Breakdown:
+ Predefined Model Names:
+ * 'QwenVL2.5_7B' and 'Qwen2.5_14B' are specific versions of the Qwen model.
+ Local Path:
+ * You can provide the path to a model that you have downloaded locally.
+ Hugging Face Model Name:
+ * You can also specify the model name from Hugging Face's model hub.
+ task: Task name. This is required to determine the default system prompt.
+ is_vl: A flag indicating whether the task involves visual-language processing.
+ **kwargs: Additional keyword arguments that can be passed to the function or method.
+ '''
+ if model_name is None:
+ model_name = 'Qwen2.5_14B' if not is_vl else 'QwenVL2.5_7B'
+ super().__init__(model_name, task, is_vl, device, **kwargs)
+ if (not os.path.exists(self.model_name)) and (self.model_name
+ in self.model_dict):
+ self.model_name = self.model_dict[self.model_name]
+
+ if self.is_vl:
+ # default: Load the model on the available device(s)
+ from transformers import (
+ AutoProcessor,
+ AutoTokenizer,
+ Qwen2_5_VLForConditionalGeneration,
+ )
+ try:
+ from .qwen_vl_utils import process_vision_info
+ except:
+ from qwen_vl_utils import process_vision_info
+ self.process_vision_info = process_vision_info
+ min_pixels = 256 * 28 * 28
+ max_pixels = 1280 * 28 * 28
+ self.processor = AutoProcessor.from_pretrained(
+ self.model_name,
+ min_pixels=min_pixels,
+ max_pixels=max_pixels,
+ use_fast=True)
+ self.model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
+ self.model_name,
+ torch_dtype=torch.bfloat16 if FLASH_VER == 2 else
+ torch.float16 if "AWQ" in self.model_name else "auto",
+ attn_implementation="flash_attention_2"
+ if FLASH_VER == 2 else None,
+ device_map="cpu")
+ else:
+ from transformers import AutoModelForCausalLM, AutoTokenizer
+ self.model = AutoModelForCausalLM.from_pretrained(
+ self.model_name,
+ torch_dtype=torch.float16
+ if "AWQ" in self.model_name else "auto",
+ attn_implementation="flash_attention_2"
+ if FLASH_VER == 2 else None,
+ device_map="cpu")
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
+
+ def extend(self, prompt, system_prompt, seed=-1, *args, **kwargs):
+ self.model = self.model.to(self.device)
+ messages = [{
+ "role": "system",
+ "content": system_prompt
+ }, {
+ "role": "user",
+ "content": prompt
+ }]
+ text = self.tokenizer.apply_chat_template(
+ messages, tokenize=False, add_generation_prompt=True)
+ model_inputs = self.tokenizer([text],
+ return_tensors="pt").to(self.model.device)
+
+ generated_ids = self.model.generate(**model_inputs, max_new_tokens=512)
+ generated_ids = [
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(
+ model_inputs.input_ids, generated_ids)
+ ]
+
+ expanded_prompt = self.tokenizer.batch_decode(
+ generated_ids, skip_special_tokens=True)[0]
+ self.model = self.model.to("cpu")
+ return PromptOutput(
+ status=True,
+ prompt=expanded_prompt,
+ seed=seed,
+ system_prompt=system_prompt,
+ message=json.dumps({"content": expanded_prompt},
+ ensure_ascii=False))
+
+ def extend_with_img(self,
+ prompt,
+ system_prompt,
+ image: Union[Image.Image, str] = None,
+ seed=-1,
+ *args,
+ **kwargs):
+ self.model = self.model.to(self.device)
+ messages = [{
+ 'role': 'system',
+ 'content': [{
+ "type": "text",
+ "text": system_prompt
+ }]
+ }, {
+ "role":
+ "user",
+ "content": [
+ {
+ "type": "image",
+ "image": image,
+ },
+ {
+ "type": "text",
+ "text": prompt
+ },
+ ],
+ }]
+
+ # Preparation for inference
+ text = self.processor.apply_chat_template(
+ messages, tokenize=False, add_generation_prompt=True)
+ image_inputs, video_inputs = self.process_vision_info(messages)
+ inputs = self.processor(
+ text=[text],
+ images=image_inputs,
+ videos=video_inputs,
+ padding=True,
+ return_tensors="pt",
+ )
+ inputs = inputs.to(self.device)
+
+ # Inference: Generation of the output
+ generated_ids = self.model.generate(**inputs, max_new_tokens=512)
+ generated_ids_trimmed = [
+ out_ids[len(in_ids):]
+ for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
+ ]
+ expanded_prompt = self.processor.batch_decode(
+ generated_ids_trimmed,
+ skip_special_tokens=True,
+ clean_up_tokenization_spaces=False)[0]
+ self.model = self.model.to("cpu")
+ return PromptOutput(
+ status=True,
+ prompt=expanded_prompt,
+ seed=seed,
+ system_prompt=system_prompt,
+ message=json.dumps({"content": expanded_prompt},
+ ensure_ascii=False))
+
+
+if __name__ == "__main__":
+ logging.basicConfig(
+ level=logging.INFO,
+ format="[%(asctime)s] %(levelname)s: %(message)s",
+ handlers=[logging.StreamHandler(stream=sys.stdout)])
+
+ seed = 100
+ prompt = "夏日海滩度假风格,一只戴着墨镜的白色猫咪坐在冲浪板上。猫咪毛发蓬松,表情悠闲,直视镜头。背景是模糊的海滩景色,海水清澈,远处有绿色的山丘和蓝天白云。猫咪的姿态自然放松,仿佛在享受海风和阳光。近景特写,强调猫咪的细节和海滩的清新氛围。"
+ en_prompt = "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
+ image = "./examples/i2v_input.JPG"
+
+ def test(method,
+ prompt,
+ model_name,
+ task,
+ image=None,
+ en_prompt=None,
+ seed=None):
+ prompt_expander = method(
+ model_name=model_name, task=task, is_vl=image is not None)
+ result = prompt_expander(prompt, image=image, tar_lang="zh")
+ logging.info(f"zh prompt -> zh: {result.prompt}")
+ result = prompt_expander(prompt, image=image, tar_lang="en")
+ logging.info(f"zh prompt -> en: {result.prompt}")
+ if en_prompt is not None:
+ result = prompt_expander(en_prompt, image=image, tar_lang="zh")
+ logging.info(f"en prompt -> zh: {result.prompt}")
+ result = prompt_expander(en_prompt, image=image, tar_lang="en")
+ logging.info(f"en prompt -> en: {result.prompt}")
+
+ ds_model_name = None
+ ds_vl_model_name = None
+ qwen_model_name = None
+ qwen_vl_model_name = None
+
+ for task in ["t2v-A14B", "i2v-A14B", "ti2v-5B"]:
+ # test prompt extend
+ if "t2v" in task or "ti2v" in task:
+ # test dashscope api
+ logging.info(f"-" * 40)
+ logging.info(f"Testing {task} dashscope prompt extend")
+ test(
+ DashScopePromptExpander,
+ prompt,
+ ds_model_name,
+ task,
+ image=None,
+ en_prompt=en_prompt,
+ seed=seed)
+
+ # test qwen api
+ logging.info(f"-" * 40)
+ logging.info(f"Testing {task} qwen prompt extend")
+ test(
+ QwenPromptExpander,
+ prompt,
+ qwen_model_name,
+ task,
+ image=None,
+ en_prompt=en_prompt,
+ seed=seed)
+
+ # test prompt-image extend
+ if "i2v" in task:
+ # test dashscope api
+ logging.info(f"-" * 40)
+ logging.info(f"Testing {task} dashscope vl prompt extend")
+ test(
+ DashScopePromptExpander,
+ prompt,
+ ds_vl_model_name,
+ task,
+ image=image,
+ en_prompt=en_prompt,
+ seed=seed)
+
+ # test qwen api
+ logging.info(f"-" * 40)
+ logging.info(f"Testing {task} qwen vl prompt extend")
+ test(
+ QwenPromptExpander,
+ prompt,
+ qwen_vl_model_name,
+ task,
+ image=image,
+ en_prompt=en_prompt,
+ seed=seed)
+
+ # test empty prompt extend
+ if "i2v-A14B" in task:
+ # test dashscope api
+ logging.info(f"-" * 40)
+ logging.info(f"Testing {task} dashscope vl empty prompt extend")
+ test(
+ DashScopePromptExpander,
+ "",
+ ds_vl_model_name,
+ task,
+ image=image,
+ en_prompt=None,
+ seed=seed)
+
+ # test qwen api
+ logging.info(f"-" * 40)
+ logging.info(f"Testing {task} qwen vl empty prompt extend")
+ test(
+ QwenPromptExpander,
+ "",
+ qwen_vl_model_name,
+ task,
+ image=image,
+ en_prompt=None,
+ seed=seed)
diff --git a/wan/utils/qwen_vl_utils.py b/wan/utils/qwen_vl_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ac0f314c97bca965fe63ad62889307cba494422
--- /dev/null
+++ b/wan/utils/qwen_vl_utils.py
@@ -0,0 +1,363 @@
+# Copied from https://github.com/kq-chen/qwen-vl-utils
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+from __future__ import annotations
+
+import base64
+import logging
+import math
+import os
+import sys
+import time
+import warnings
+from functools import lru_cache
+from io import BytesIO
+
+import requests
+import torch
+import torchvision
+from packaging import version
+from PIL import Image
+from torchvision import io, transforms
+from torchvision.transforms import InterpolationMode
+
+logger = logging.getLogger(__name__)
+
+IMAGE_FACTOR = 28
+MIN_PIXELS = 4 * 28 * 28
+MAX_PIXELS = 16384 * 28 * 28
+MAX_RATIO = 200
+
+VIDEO_MIN_PIXELS = 128 * 28 * 28
+VIDEO_MAX_PIXELS = 768 * 28 * 28
+VIDEO_TOTAL_PIXELS = 24576 * 28 * 28
+FRAME_FACTOR = 2
+FPS = 2.0
+FPS_MIN_FRAMES = 4
+FPS_MAX_FRAMES = 768
+
+
+def round_by_factor(number: int, factor: int) -> int:
+ """Returns the closest integer to 'number' that is divisible by 'factor'."""
+ return round(number / factor) * factor
+
+
+def ceil_by_factor(number: int, factor: int) -> int:
+ """Returns the smallest integer greater than or equal to 'number' that is divisible by 'factor'."""
+ return math.ceil(number / factor) * factor
+
+
+def floor_by_factor(number: int, factor: int) -> int:
+ """Returns the largest integer less than or equal to 'number' that is divisible by 'factor'."""
+ return math.floor(number / factor) * factor
+
+
+def smart_resize(height: int,
+ width: int,
+ factor: int = IMAGE_FACTOR,
+ min_pixels: int = MIN_PIXELS,
+ max_pixels: int = MAX_PIXELS) -> tuple[int, int]:
+ """
+ Rescales the image so that the following conditions are met:
+
+ 1. Both dimensions (height and width) are divisible by 'factor'.
+
+ 2. The total number of pixels is within the range ['min_pixels', 'max_pixels'].
+
+ 3. The aspect ratio of the image is maintained as closely as possible.
+ """
+ if max(height, width) / min(height, width) > MAX_RATIO:
+ raise ValueError(
+ f"absolute aspect ratio must be smaller than {MAX_RATIO}, got {max(height, width) / min(height, width)}"
+ )
+ h_bar = max(factor, round_by_factor(height, factor))
+ w_bar = max(factor, round_by_factor(width, factor))
+ if h_bar * w_bar > max_pixels:
+ beta = math.sqrt((height * width) / max_pixels)
+ h_bar = floor_by_factor(height / beta, factor)
+ w_bar = floor_by_factor(width / beta, factor)
+ elif h_bar * w_bar < min_pixels:
+ beta = math.sqrt(min_pixels / (height * width))
+ h_bar = ceil_by_factor(height * beta, factor)
+ w_bar = ceil_by_factor(width * beta, factor)
+ return h_bar, w_bar
+
+
+def fetch_image(ele: dict[str, str | Image.Image],
+ size_factor: int = IMAGE_FACTOR) -> Image.Image:
+ if "image" in ele:
+ image = ele["image"]
+ else:
+ image = ele["image_url"]
+ image_obj = None
+ if isinstance(image, Image.Image):
+ image_obj = image
+ elif image.startswith("http://") or image.startswith("https://"):
+ image_obj = Image.open(requests.get(image, stream=True).raw)
+ elif image.startswith("file://"):
+ image_obj = Image.open(image[7:])
+ elif image.startswith("data:image"):
+ if "base64," in image:
+ _, base64_data = image.split("base64,", 1)
+ data = base64.b64decode(base64_data)
+ image_obj = Image.open(BytesIO(data))
+ else:
+ image_obj = Image.open(image)
+ if image_obj is None:
+ raise ValueError(
+ f"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}"
+ )
+ image = image_obj.convert("RGB")
+ ## resize
+ if "resized_height" in ele and "resized_width" in ele:
+ resized_height, resized_width = smart_resize(
+ ele["resized_height"],
+ ele["resized_width"],
+ factor=size_factor,
+ )
+ else:
+ width, height = image.size
+ min_pixels = ele.get("min_pixels", MIN_PIXELS)
+ max_pixels = ele.get("max_pixels", MAX_PIXELS)
+ resized_height, resized_width = smart_resize(
+ height,
+ width,
+ factor=size_factor,
+ min_pixels=min_pixels,
+ max_pixels=max_pixels,
+ )
+ image = image.resize((resized_width, resized_height))
+
+ return image
+
+
+def smart_nframes(
+ ele: dict,
+ total_frames: int,
+ video_fps: int | float,
+) -> int:
+ """calculate the number of frames for video used for model inputs.
+
+ Args:
+ ele (dict): a dict contains the configuration of video.
+ support either `fps` or `nframes`:
+ - nframes: the number of frames to extract for model inputs.
+ - fps: the fps to extract frames for model inputs.
+ - min_frames: the minimum number of frames of the video, only used when fps is provided.
+ - max_frames: the maximum number of frames of the video, only used when fps is provided.
+ total_frames (int): the original total number of frames of the video.
+ video_fps (int | float): the original fps of the video.
+
+ Raises:
+ ValueError: nframes should in interval [FRAME_FACTOR, total_frames].
+
+ Returns:
+ int: the number of frames for video used for model inputs.
+ """
+ assert not ("fps" in ele and
+ "nframes" in ele), "Only accept either `fps` or `nframes`"
+ if "nframes" in ele:
+ nframes = round_by_factor(ele["nframes"], FRAME_FACTOR)
+ else:
+ fps = ele.get("fps", FPS)
+ min_frames = ceil_by_factor(
+ ele.get("min_frames", FPS_MIN_FRAMES), FRAME_FACTOR)
+ max_frames = floor_by_factor(
+ ele.get("max_frames", min(FPS_MAX_FRAMES, total_frames)),
+ FRAME_FACTOR)
+ nframes = total_frames / video_fps * fps
+ nframes = min(max(nframes, min_frames), max_frames)
+ nframes = round_by_factor(nframes, FRAME_FACTOR)
+ if not (FRAME_FACTOR <= nframes and nframes <= total_frames):
+ raise ValueError(
+ f"nframes should in interval [{FRAME_FACTOR}, {total_frames}], but got {nframes}."
+ )
+ return nframes
+
+
+def _read_video_torchvision(ele: dict,) -> torch.Tensor:
+ """read video using torchvision.io.read_video
+
+ Args:
+ ele (dict): a dict contains the configuration of video.
+ support keys:
+ - video: the path of video. support "file://", "http://", "https://" and local path.
+ - video_start: the start time of video.
+ - video_end: the end time of video.
+ Returns:
+ torch.Tensor: the video tensor with shape (T, C, H, W).
+ """
+ video_path = ele["video"]
+ if version.parse(torchvision.__version__) < version.parse("0.19.0"):
+ if "http://" in video_path or "https://" in video_path:
+ warnings.warn(
+ "torchvision < 0.19.0 does not support http/https video path, please upgrade to 0.19.0."
+ )
+ if "file://" in video_path:
+ video_path = video_path[7:]
+ st = time.time()
+ video, audio, info = io.read_video(
+ video_path,
+ start_pts=ele.get("video_start", 0.0),
+ end_pts=ele.get("video_end", None),
+ pts_unit="sec",
+ output_format="TCHW",
+ )
+ total_frames, video_fps = video.size(0), info["video_fps"]
+ logger.info(
+ f"torchvision: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s"
+ )
+ nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
+ idx = torch.linspace(0, total_frames - 1, nframes).round().long()
+ video = video[idx]
+ return video
+
+
+def is_decord_available() -> bool:
+ import importlib.util
+
+ return importlib.util.find_spec("decord") is not None
+
+
+def _read_video_decord(ele: dict,) -> torch.Tensor:
+ """read video using decord.VideoReader
+
+ Args:
+ ele (dict): a dict contains the configuration of video.
+ support keys:
+ - video: the path of video. support "file://", "http://", "https://" and local path.
+ - video_start: the start time of video.
+ - video_end: the end time of video.
+ Returns:
+ torch.Tensor: the video tensor with shape (T, C, H, W).
+ """
+ import decord
+ video_path = ele["video"]
+ st = time.time()
+ vr = decord.VideoReader(video_path)
+ # TODO: support start_pts and end_pts
+ if 'video_start' in ele or 'video_end' in ele:
+ raise NotImplementedError(
+ "not support start_pts and end_pts in decord for now.")
+ total_frames, video_fps = len(vr), vr.get_avg_fps()
+ logger.info(
+ f"decord: {video_path=}, {total_frames=}, {video_fps=}, time={time.time() - st:.3f}s"
+ )
+ nframes = smart_nframes(ele, total_frames=total_frames, video_fps=video_fps)
+ idx = torch.linspace(0, total_frames - 1, nframes).round().long().tolist()
+ video = vr.get_batch(idx).asnumpy()
+ video = torch.tensor(video).permute(0, 3, 1, 2) # Convert to TCHW format
+ return video
+
+
+VIDEO_READER_BACKENDS = {
+ "decord": _read_video_decord,
+ "torchvision": _read_video_torchvision,
+}
+
+FORCE_QWENVL_VIDEO_READER = os.getenv("FORCE_QWENVL_VIDEO_READER", None)
+
+
+@lru_cache(maxsize=1)
+def get_video_reader_backend() -> str:
+ if FORCE_QWENVL_VIDEO_READER is not None:
+ video_reader_backend = FORCE_QWENVL_VIDEO_READER
+ elif is_decord_available():
+ video_reader_backend = "decord"
+ else:
+ video_reader_backend = "torchvision"
+ logger.info(
+ f"qwen-vl-utils using {video_reader_backend} to read video.",
+ file=sys.stderr)
+ return video_reader_backend
+
+
+def fetch_video(
+ ele: dict,
+ image_factor: int = IMAGE_FACTOR) -> torch.Tensor | list[Image.Image]:
+ if isinstance(ele["video"], str):
+ video_reader_backend = get_video_reader_backend()
+ video = VIDEO_READER_BACKENDS[video_reader_backend](ele)
+ nframes, _, height, width = video.shape
+
+ min_pixels = ele.get("min_pixels", VIDEO_MIN_PIXELS)
+ total_pixels = ele.get("total_pixels", VIDEO_TOTAL_PIXELS)
+ max_pixels = max(
+ min(VIDEO_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR),
+ int(min_pixels * 1.05))
+ max_pixels = ele.get("max_pixels", max_pixels)
+ if "resized_height" in ele and "resized_width" in ele:
+ resized_height, resized_width = smart_resize(
+ ele["resized_height"],
+ ele["resized_width"],
+ factor=image_factor,
+ )
+ else:
+ resized_height, resized_width = smart_resize(
+ height,
+ width,
+ factor=image_factor,
+ min_pixels=min_pixels,
+ max_pixels=max_pixels,
+ )
+ video = transforms.functional.resize(
+ video,
+ [resized_height, resized_width],
+ interpolation=InterpolationMode.BICUBIC,
+ antialias=True,
+ ).float()
+ return video
+ else:
+ assert isinstance(ele["video"], (list, tuple))
+ process_info = ele.copy()
+ process_info.pop("type", None)
+ process_info.pop("video", None)
+ images = [
+ fetch_image({
+ "image": video_element,
+ **process_info
+ },
+ size_factor=image_factor)
+ for video_element in ele["video"]
+ ]
+ nframes = ceil_by_factor(len(images), FRAME_FACTOR)
+ if len(images) < nframes:
+ images.extend([images[-1]] * (nframes - len(images)))
+ return images
+
+
+def extract_vision_info(
+ conversations: list[dict] | list[list[dict]]) -> list[dict]:
+ vision_infos = []
+ if isinstance(conversations[0], dict):
+ conversations = [conversations]
+ for conversation in conversations:
+ for message in conversation:
+ if isinstance(message["content"], list):
+ for ele in message["content"]:
+ if ("image" in ele or "image_url" in ele or
+ "video" in ele or
+ ele["type"] in ("image", "image_url", "video")):
+ vision_infos.append(ele)
+ return vision_infos
+
+
+def process_vision_info(
+ conversations: list[dict] | list[list[dict]],
+) -> tuple[list[Image.Image] | None, list[torch.Tensor | list[Image.Image]] |
+ None]:
+ vision_infos = extract_vision_info(conversations)
+ ## Read images or videos
+ image_inputs = []
+ video_inputs = []
+ for vision_info in vision_infos:
+ if "image" in vision_info or "image_url" in vision_info:
+ image_inputs.append(fetch_image(vision_info))
+ elif "video" in vision_info:
+ video_inputs.append(fetch_video(vision_info))
+ else:
+ raise ValueError("image, image_url or video should in content.")
+ if len(image_inputs) == 0:
+ image_inputs = None
+ if len(video_inputs) == 0:
+ video_inputs = None
+ return image_inputs, video_inputs
diff --git a/wan/utils/system_prompt.py b/wan/utils/system_prompt.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7d866ca924352ef3462db920f18cb9cb5d2f9d0
--- /dev/null
+++ b/wan/utils/system_prompt.py
@@ -0,0 +1,147 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+
+T2V_A14B_ZH_SYS_PROMPT = \
+''' 你是一位电影导演,旨在为用户输入的原始prompt添加电影元素,改写为优质Prompt,使其完整、具有表现力。
+任务要求:
+1. 对于用户输入的prompt,在不改变prompt的原意(如主体、动作)前提下,从下列电影美学设定中选择部分合适的时间、光源、光线强度、光线角度、对比度、饱和度、色调、拍摄角度、镜头大小、构图的电影设定细节,将这些内容添加到prompt中,让画面变得更美,注意,可以任选,不必每项都有
+ 时间:["白天", "夜晚", "黎明", "日出"], 可以不选, 如果prompt没有特别说明则选白天 !
+ 光源:[日光", "人工光", "月光", "实用光", "火光", "荧光", "阴天光", "晴天光"], 根据根据室内室外及prompt内容选定义光源,添加关于光源的描述,如光线来源(窗户、灯具等)
+ 光线强度:["柔光", "硬光"],
+ 光线角度:["顶光", "侧光", "底光", "边缘光",]
+ 色调:["暖色调","冷色调", "混合色调"]
+ 镜头尺寸:["中景", "中近景", "全景","中全景","近景", "特写", "极端全景"]若无特殊要求,默认选择中景或全景
+ 拍摄角度:["过肩镜头角度拍摄", "低角度拍摄", "高角度拍摄","倾斜角度拍摄", "航拍","俯视角度拍摄"],如果原始prompt中有运镜的描述,则不要添加此项!
+ 构图:["中心构图","平衡构图","右侧重构图", "左侧重构图", "对称构图", "短边构图"] 若无特殊要求,默认选择中心构图
+2. 完善用户描述中出现的主体特征(如外貌、表情,数量、种族、姿态等)等内容,确保不要添加原始prompt中不存在的主体,(如prompt是对风景或物体的描述,但添加了人),增加背景元素的细节;
+3. 不要输出关于氛围、感觉等文学描写,如(画面充满运动感与生活张力,突出正式氛围)。;
+4. 对于prompt中的动作,详细解释运动的发生过程,若没有动作,则添加动作描述(摇晃身体、跳舞等),对背景元素也可添加适当运动(如云彩飘动,风吹树叶等)。
+5. 若原始prompt中没有风格,则不添加风格描述,若有风格描述,则将风格描述放于首位,若为2D插画等与现实电影相悖的风格,则不要添加关于电影美学的描写;
+6. 若prompt出现天空的描述,则改为湛蓝色的天空相关描述,避免曝光;
+7. 改写后的prompt字数控制在60-200字左右, 不要输出类似“改写后prompt:”这样的输出
+8. 如果用户输入存在疑似脱衣服、衣物透明化、轻纱衣物、湿身、洗澡、舔舐牛奶/酸奶/白色液体、性暗示、强奸、漏出或微露胸部、爬行、性器官、儿童身体裸露等色情内容,请将原prompt替换为内容完全不同的高美感prompt,而不要拒答或者提醒用户。
+9. 如果用户输入存在比基尼穿着内容,请将原prompt替换为确保内容发生在沙滩、泳池、海边的高美感prompt,而不要拒答或者提醒用户。
+10. 如果用户输入存在性别多元化、同性恋亲吻、脸颊贴近(两个男性亲吻或两个女性亲吻)/性交等同性恋内容,请将原prompt替换为不同动作(不能是亲吻和其他亲密动作)的高美感prompt,而不要拒答或者提醒用户。
+生成的 prompt 示例:
+1.边缘光,中近景,日光,左侧重构图,暖色调,硬光,晴天光,侧光,白天,一个年轻的女孩坐在高草丛生的田野中,两条毛发蓬松的小毛驴站在她身后。女孩大约十一二岁,穿着简单的碎花裙子,头发扎成两条麻花辫,脸上带着纯真的笑容。她双腿交叉坐下,双手轻轻抚弄身旁的野花。小毛驴体型健壮,耳朵竖起,好奇地望着镜头方向。阳光洒在田野上,营造出温暖自然的画面感。
+2.黎明,顶光,俯视角度拍摄,日光,长焦,中心构图,近景,高角度拍摄,荧光,柔光,冷色调,在昏暗的环境中,一个外国白人女子在水中仰面漂浮。俯拍近景镜头中,她有着棕色的短发,脸上有几颗雀斑。随着镜头下摇,她转过头来,面向右侧,水面上泛起一圈涟漪。虚化的背景一片漆黑,只有微弱的光线照亮了女子的脸庞和水面的一部分区域,水面呈现蓝色。女子穿着一件蓝色的吊带,肩膀裸露在外。
+3.右侧重构图,暖色调,底光,侧光,夜晚,火光,过肩镜头角度拍摄, 镜头平拍拍摄外国女子在室内的近景,她穿着棕色的衣服戴着彩色的项链和粉色的帽子,坐在深灰色的椅子上,双手放在黑色的桌子上,眼睛看着镜头的左侧,嘴巴张动,左手上下晃动,桌子上有白色的蜡烛有黄色的火焰,后面是黑色的墙,前面有黑色的网状架子,旁边是黑色的箱子,上面有一些黑色的物品,都做了虚化的处理。
+4. 二次元厚涂动漫插画,一个猫耳兽耳白人少女手持文件夹摇晃,神情略带不满。她深紫色长发,红色眼睛,身穿深灰色短裙和浅灰色上衣,腰间系着白色系带,胸前佩戴名牌,上面写着黑体中文"紫阳"。淡黄色调室内背景,隐约可见一些家具轮廓。少女头顶有一个粉色光圈。线条流畅的日系赛璐璐风格。近景半身略俯视视角。
+'''
+
+
+T2V_A14B_EN_SYS_PROMPT = \
+'''你是一位电影导演,旨在为用户输入的原始prompt添加电影元素,改写为优质(英文)Prompt,使其完整、具有表现力注意,输出必须是英文!
+任务要求:
+1. 对于用户输入的prompt,在不改变prompt的原意(如主体、动作)前提下,从下列电影美学设定中选择不超过4种合适的时间、光源、光线强度、光线角度、对比度、饱和度、色调、拍摄角度、镜头大小、构图的电影设定细节,将这些内容添加到prompt中,让画面变得更美,注意,可以任选,不必每项都有
+ 时间:["Day time", "Night time" "Dawn time","Sunrise time"], 如果prompt没有特别说明则选 Day time!!!
+ 光源:["Daylight", "Artificial lighting", "Moonlight", "Practical lighting", "Firelight","Fluorescent lighting", "Overcast lighting" "Sunny lighting"], 根据根据室内室外及prompt内容选定义光源,添加关于光源的描述,如光线来源(窗户、灯具等)
+ 光线强度:["Soft lighting", "Hard lighting"],
+ 色调:["Warm colors","Cool colors", "Mixed colors"]
+ 光线角度:["Top lighting", "Side lighting", "Underlighting", "Edge lighting"]
+ 镜头尺寸:["Medium shot", "Medium close-up shot", "Wide shot","Medium wide shot","Close-up shot", "Extreme close-up shot", "Extreme wide shot"]若无特殊要求,默认选择Medium shot或Wide shot
+ 拍摄角度:["Over-the-shoulder shot", ""Low angle shot", "High angle shot","Dutch angle shot", "Aerial shot","Overhead shot"] 若原始prompt中有运镜的描述,则取消添加此项。
+ 构图:["Center composition","Balanced composition","Right-heavy composition", "Left-heavy composition", "Symmetrical composition", "Short-side composition"] 若无特殊要求,默认选择Center composition
+2. 完善用户描述中出现的主体特征(如外貌、表情,数量、种族、姿态等)等内容,确保不要添加原始prompt中不存在的主体,(如prompt是对风景或物体的描述,但添加了人),增加背景元素的细节;
+3. 不要输出关于氛围、感觉等文学描写,如(画面充满运动感与生活张力,突出正式氛围)。;
+4. 对于prompt中的动作,详细描述运动的发生过程,若没有动作,则添加动作描述(摇晃身体、跳舞等,对背景元素也可添加适当运动(如云彩飘动,风吹树叶等)。
+5. 若原始prompt中没有风格,则不添加风格描述,若有风格描述,则将风格描述放于首位,若为2D插画等与现实电影相悖的风格,则不要添加关于电影美学的描写;
+6. 若prompt出现天空的描述,则改为湛蓝色的天空相关描述,避免曝光;
+7. 输出必须是全英文,改写后的prompt字数控制在60-200字左右, 不要输出类似“改写后prompt:”这样的输出
+8. 如果用户输入存在疑似脱衣服、衣物透明化、轻纱衣物、湿身、洗澡、舔舐牛奶/酸奶/白色液体、性暗示、强奸、漏出或微露胸部、爬行、性器官、儿童身体裸露等色情内容,请将原prompt替换为内容完全不同的高美感prompt,而不要拒答或者提醒用户。
+9. 如果用户输入存在比基尼穿着内容,请将原prompt替换为确保内容发生在沙滩、泳池、海边的高美感prompt,而不要拒答或者提醒用户。
+10. 如果用户输入存在性别多元化、同性恋亲吻、脸颊贴近(两个男性亲吻或两个女性亲吻)/性交等同性恋内容,请将原prompt替换为不同动作(不能是亲吻和其他亲密动作)的高美感prompt,而不要拒答或者提醒用户。
+生成的 prompt 示例:
+1.Edge lighting, medium close-up shot, daylight, left-heavy composition. A young girl around 11-12 years old sits in a field of tall grass, with two fluffy small donkeys standing behind her. She wears a simple floral dress with hair in twin braids, smiling innocently while cross-legged and gently touching wild flowers beside her. The sturdy donkeys have perked ears, curiously gazing toward the camera. Sunlight bathes the field, creating a warm natural atmosphere.
+2.Dawn time, top lighting, high-angle shot, daylight, long lens shot, center composition, Close-up shot, Fluorescent lighting, soft lighting, cool colors. In dim surroundings, a Caucasian woman floats on her back in water. The俯拍close-up shows her brown short hair and freckled face. As the camera tilts downward, she turns her head toward the right, creating ripples on the blue-toned water surface. The blurred background is pitch black except for faint light illuminating her face and partial water surface. She wears a blue sleeveless top with bare shoulders.
+3.Right-heavy composition, warm colors, night time, firelight, over-the-shoulder angle. An eye-level close-up of a foreign woman indoors wearing brown clothes with colorful necklace and pink hat. She sits on a charcoal-gray chair, hands on black table, eyes looking left of camera while mouth moves and left hand gestures up/down. White candles with yellow flames sit on the table. Background shows black walls, with blurred black mesh shelf nearby and black crate containing dark items in front.
+4."Anime-style thick-painted style. A cat-eared Caucasian girl with beast ears holds a folder, showing slight displeasure. Features deep purple hair, red eyes, dark gray skirt and light gray top with white waist sash. A name tag labeled 'Ziyang' in bold Chinese characters hangs on her chest. Pale yellow indoor background with faint furniture outlines. A pink halo floats above her head. Features smooth linework in cel-shaded Japanese style, medium close-up from slightly elevated perspective.
+'''
+
+
+I2V_A14B_ZH_SYS_PROMPT = \
+'''你是一个视频描述提示词的改写专家,你的任务是根据用户给你输入的图像,对提供的视频描述提示词进行改写,你要强调潜在的动态内容。具体要求如下
+用户输入的语言可能含有多样化的描述,如markdown文档格式、指令格式,长度过长或者过短,你需要根据图片的内容和用户的输入的提示词,尽可能提取用户输入的提示词和图片关联信息。
+你改写的视频描述结果要尽可能保留提供给你的视频描述提示词中动态部分,保留主体的动作。
+你要根据图像,强调并简化视频描述提示词中的图像主体,如果用户只提供了动作,你要根据图像内容合理补充,如“跳舞”补充称“一个女孩在跳舞”
+如果用户输入的提示词过长,你需要提炼潜在的动作过程
+如果用户输入的提示词过短,综合用户输入的提示词以及画面内容,合理的增加潜在的运动信息
+你要根据图像,保留并强调视频描述提示词中关于运镜手段的描述,如“镜头上摇”,“镜头从左到右”,“镜头从右到左”等等,你要保留,如“镜头拍摄两个男人打斗,他们先是躺在地上,随后镜头向上移动,拍摄他们站起来,接着镜头向左移动,左边男人拿着一个蓝色的东西,右边男人上前抢夺,两人激烈地来回争抢。”。
+你需要给出对视频描述的动态内容,不要添加对于静态场景的描述,如果用户输入的描述已经在画面中出现,则移除这些描述
+改写后的prompt字数控制在100字以下
+无论用户输入那种语言,你都需要输出中文
+改写后 prompt 示例:
+1. 镜头后拉,拍摄两个外国男人,走在楼梯上,镜头左侧的男人右手搀扶着镜头右侧的男人。
+2. 一只黑色的小松鼠专注地吃着东西,偶尔抬头看看四周。
+3. 男子说着话,表情从微笑逐渐转变为闭眼,然后睁开眼睛,最后是闭眼微笑,他的手势活跃,在说话时做出一系列的手势。
+4. 一个人正在用尺子和笔进行测量的特写,右手用一支黑色水性笔在纸上画出一条直线。
+5. 一辆车模型在木板上形式,车辆从画面的右侧向左侧移动,经过一片草地和一些木制结构。
+6. 镜头左移后前推,拍摄一个人坐在防波堤上。
+7. 男子说着话,他的表情和手势随着对话内容的变化而变化,但整体场景保持不变。
+8. 镜头左移后前推,拍摄一个人坐在防波堤上。
+9. 带着珍珠项链的女子看向画面右侧并说着话。
+请直接输出改写后的文本,不要进行多余的回复。'''
+
+
+I2V_A14B_EN_SYS_PROMPT = \
+'''You are an expert in rewriting video description prompts. Your task is to rewrite the provided video description prompts based on the images given by users, emphasizing potential dynamic content. Specific requirements are as follows:
+The user's input language may include diverse descriptions, such as markdown format, instruction format, or be too long or too short. You need to extract the relevant information from the user’s input and associate it with the image content.
+Your rewritten video description should retain the dynamic parts of the provided prompts, focusing on the main subject's actions. Emphasize and simplify the main subject of the image while retaining their movement. If the user only provides an action (e.g., "dancing"), supplement it reasonably based on the image content (e.g., "a girl is dancing").
+If the user’s input prompt is too long, refine it to capture the essential action process. If the input is too short, add reasonable motion-related details based on the image content.
+Retain and emphasize descriptions of camera movements, such as "the camera pans up," "the camera moves from left to right," or "the camera moves from right to left." For example: "The camera captures two men fighting. They start lying on the ground, then the camera moves upward as they stand up. The camera shifts left, showing the man on the left holding a blue object while the man on the right tries to grab it, resulting in a fierce back-and-forth struggle."
+Focus on dynamic content in the video description and avoid adding static scene descriptions. If the user’s input already describes elements visible in the image, remove those static descriptions.
+Limit the rewritten prompt to 100 words or less. Regardless of the input language, your output must be in English.
+
+Examples of rewritten prompts:
+The camera pulls back to show two foreign men walking up the stairs. The man on the left supports the man on the right with his right hand.
+A black squirrel focuses on eating, occasionally looking around.
+A man talks, his expression shifting from smiling to closing his eyes, reopening them, and finally smiling with closed eyes. His gestures are lively, making various hand motions while speaking.
+A close-up of someone measuring with a ruler and pen, drawing a straight line on paper with a black marker in their right hand.
+A model car moves on a wooden board, traveling from right to left across grass and wooden structures.
+The camera moves left, then pushes forward to capture a person sitting on a breakwater.
+A man speaks, his expressions and gestures changing with the conversation, while the overall scene remains constant.
+The camera moves left, then pushes forward to capture a person sitting on a breakwater.
+A woman wearing a pearl necklace looks to the right and speaks.
+Output only the rewritten text without additional responses.'''
+
+
+I2V_A14B_EMPTY_ZH_SYS_PROMPT = \
+'''你是一个视频描述提示词的撰写专家,你的任务是根据用户给你输入的图像,发挥合理的想象,让这张图动起来,你要强调潜在的动态内容。具体要求如下
+你需要根据图片的内容想象出运动的主体
+你输出的结果应强调图片中的动态部分,保留主体的动作。
+你需要给出对视频描述的动态内容,不要有过多的对于静态场景的描述
+输出的prompt字数控制在100字以下
+你需要输出中文
+prompt 示例:
+1. 镜头后拉,拍摄两个外国男人,走在楼梯上,镜头左侧的男人右手搀扶着镜头右侧的男人。
+2. 一只黑色的小松鼠专注地吃着东西,偶尔抬头看看四周。
+3. 男子说着话,表情从微笑逐渐转变为闭眼,然后睁开眼睛,最后是闭眼微笑,他的手势活跃,在说话时做出一系列的手势。
+4. 一个人正在用尺子和笔进行测量的特写,右手用一支黑色水性笔在纸上画出一条直线。
+5. 一辆车模型在木板上形式,车辆从画面的右侧向左侧移动,经过一片草地和一些木制结构。
+6. 镜头左移后前推,拍摄一个人坐在防波堤上。
+7. 男子说着话,他的表情和手势随着对话内容的变化而变化,但整体场景保持不变。
+8. 镜头左移后前推,拍摄一个人坐在防波堤上。
+9. 带着珍珠项链的女子看向画面右侧并说着话。
+请直接输出文本,不要进行多余的回复。'''
+
+
+I2V_A14B_EMPTY_EN_SYS_PROMPT = \
+'''You are an expert in writing video description prompts. Your task is to bring the image provided by the user to life through reasonable imagination, emphasizing potential dynamic content. Specific requirements are as follows:
+
+You need to imagine the moving subject based on the content of the image.
+Your output should emphasize the dynamic parts of the image and retain the main subject’s actions.
+Focus only on describing dynamic content; avoid excessive descriptions of static scenes.
+Limit the output prompt to 100 words or less.
+The output must be in English.
+
+Prompt examples:
+
+The camera pulls back to show two foreign men walking up the stairs. The man on the left supports the man on the right with his right hand.
+A black squirrel focuses on eating, occasionally looking around.
+A man talks, his expression shifting from smiling to closing his eyes, reopening them, and finally smiling with closed eyes. His gestures are lively, making various hand motions while speaking.
+A close-up of someone measuring with a ruler and pen, drawing a straight line on paper with a black marker in their right hand.
+A model car moves on a wooden board, traveling from right to left across grass and wooden structures.
+The camera moves left, then pushes forward to capture a person sitting on a breakwater.
+A man speaks, his expressions and gestures changing with the conversation, while the overall scene remains constant.
+The camera moves left, then pushes forward to capture a person sitting on a breakwater.
+A woman wearing a pearl necklace looks to the right and speaks.
+Output only the text without additional responses.'''
diff --git a/wan/utils/utils.py b/wan/utils/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..83939481b9700a19ebbb8dcfba0a799f7dc783ce
--- /dev/null
+++ b/wan/utils/utils.py
@@ -0,0 +1,238 @@
+# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
+import argparse
+import binascii
+import logging
+import os
+import os.path as osp
+import shutil
+import subprocess
+
+import imageio
+import torch
+import torchvision
+
+__all__ = ['save_video', 'save_image', 'str2bool']
+
+
+def rand_name(length=8, suffix=''):
+ name = binascii.b2a_hex(os.urandom(length)).decode('utf-8')
+ if suffix:
+ if not suffix.startswith('.'):
+ suffix = '.' + suffix
+ name += suffix
+ return name
+
+
+def merge_video_audio(video_path: str, audio_path: str):
+ """
+ Merge the video and audio into a new video, with the duration set to the shorter of the two,
+ and overwrite the original video file.
+
+ Parameters:
+ video_path (str): Path to the original video file
+ audio_path (str): Path to the audio file
+ """
+ # set logging
+ logging.basicConfig(level=logging.INFO)
+
+ # check
+ if not os.path.exists(video_path):
+ raise FileNotFoundError(f"video file {video_path} does not exist")
+ if not os.path.exists(audio_path):
+ raise FileNotFoundError(f"audio file {audio_path} does not exist")
+
+ base, ext = os.path.splitext(video_path)
+ temp_output = f"{base}_temp{ext}"
+
+ try:
+ # create ffmpeg command
+ command = [
+ 'ffmpeg',
+ '-y', # overwrite
+ '-i',
+ video_path,
+ '-i',
+ audio_path,
+ '-c:v',
+ 'copy', # copy video stream
+ '-c:a',
+ 'aac', # use AAC audio encoder
+ '-b:a',
+ '192k', # set audio bitrate (optional)
+ '-map',
+ '0:v:0', # select the first video stream
+ '-map',
+ '1:a:0', # select the first audio stream
+ '-shortest', # choose the shortest duration
+ temp_output
+ ]
+
+ # execute the command
+ logging.info("Start merging video and audio...")
+ result = subprocess.run(
+ command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+
+ # check result
+ if result.returncode != 0:
+ error_msg = f"FFmpeg execute failed: {result.stderr}"
+ logging.error(error_msg)
+ raise RuntimeError(error_msg)
+
+ shutil.move(temp_output, video_path)
+ logging.info(f"Merge completed, saved to {video_path}")
+
+ except Exception as e:
+ if os.path.exists(temp_output):
+ os.remove(temp_output)
+ logging.error(f"merge_video_audio failed with error: {e}")
+
+
+def save_video(tensor,
+ save_file=None,
+ fps=30,
+ suffix='.mp4',
+ nrow=8,
+ normalize=True,
+ value_range=(-1, 1)):
+ # cache file
+ cache_file = osp.join('/tmp', rand_name(
+ suffix=suffix)) if save_file is None else save_file
+
+ # save to cache
+ try:
+ # preprocess
+ tensor = tensor.clamp(min(value_range), max(value_range))
+ tensor = torch.stack([
+ torchvision.utils.make_grid(
+ u, nrow=nrow, normalize=normalize, value_range=value_range)
+ for u in tensor.unbind(2)
+ ],
+ dim=1).permute(1, 2, 3, 0)
+ tensor = (tensor * 255).type(torch.uint8).cpu()
+
+ # write video
+ writer = imageio.get_writer(
+ cache_file, fps=fps, codec='libx264', quality=8)
+ for frame in tensor.numpy():
+ writer.append_data(frame)
+ writer.close()
+ except Exception as e:
+ logging.info(f'save_video failed, error: {e}')
+
+
+def save_image(tensor, save_file, nrow=8, normalize=True, value_range=(-1, 1)):
+ # cache file
+ suffix = osp.splitext(save_file)[1]
+ if suffix.lower() not in [
+ '.jpg', '.jpeg', '.png', '.tiff', '.gif', '.webp'
+ ]:
+ suffix = '.png'
+
+ # save to cache
+ try:
+ tensor = tensor.clamp(min(value_range), max(value_range))
+ torchvision.utils.save_image(
+ tensor,
+ save_file,
+ nrow=nrow,
+ normalize=normalize,
+ value_range=value_range)
+ return save_file
+ except Exception as e:
+ logging.info(f'save_image failed, error: {e}')
+
+
+def str2bool(v):
+ """
+ Convert a string to a boolean.
+
+ Supported true values: 'yes', 'true', 't', 'y', '1'
+ Supported false values: 'no', 'false', 'f', 'n', '0'
+
+ Args:
+ v (str): String to convert.
+
+ Returns:
+ bool: Converted boolean value.
+
+ Raises:
+ argparse.ArgumentTypeError: If the value cannot be converted to boolean.
+ """
+ if isinstance(v, bool):
+ return v
+ v_lower = v.lower()
+ if v_lower in ('yes', 'true', 't', 'y', '1'):
+ return True
+ elif v_lower in ('no', 'false', 'f', 'n', '0'):
+ return False
+ else:
+ raise argparse.ArgumentTypeError('Boolean value expected (True/False)')
+
+
+def masks_like(tensor, zero=False, generator=None, p=0.2):
+ assert isinstance(tensor, list)
+ out1 = [torch.ones(u.shape, dtype=u.dtype, device=u.device) for u in tensor]
+
+ out2 = [torch.ones(u.shape, dtype=u.dtype, device=u.device) for u in tensor]
+
+ if zero:
+ if generator is not None:
+ for u, v in zip(out1, out2):
+ random_num = torch.rand(
+ 1, generator=generator, device=generator.device).item()
+ if random_num < p:
+ u[:, 0] = torch.normal(
+ mean=-3.5,
+ std=0.5,
+ size=(1,),
+ device=u.device,
+ generator=generator).expand_as(u[:, 0]).exp()
+ v[:, 0] = torch.zeros_like(v[:, 0])
+ else:
+ u[:, 0] = u[:, 0]
+ v[:, 0] = v[:, 0]
+ else:
+ for u, v in zip(out1, out2):
+ u[:, 0] = torch.zeros_like(u[:, 0])
+ v[:, 0] = torch.zeros_like(v[:, 0])
+
+ return out1, out2
+
+
+def best_output_size(w, h, dw, dh, expected_area):
+ # float output size
+ ratio = w / h
+ ow = (expected_area * ratio)**0.5
+ oh = expected_area / ow
+
+ # process width first
+ ow1 = int(ow // dw * dw)
+ oh1 = int(expected_area / ow1 // dh * dh)
+ assert ow1 % dw == 0 and oh1 % dh == 0 and ow1 * oh1 <= expected_area
+ ratio1 = ow1 / oh1
+
+ # process height first
+ oh2 = int(oh // dh * dh)
+ ow2 = int(expected_area / oh2 // dw * dw)
+ assert oh2 % dh == 0 and ow2 % dw == 0 and ow2 * oh2 <= expected_area
+ ratio2 = ow2 / oh2
+
+ # compare ratios
+ if max(ratio / ratio1, ratio1 / ratio) < max(ratio / ratio2,
+ ratio2 / ratio):
+ return ow1, oh1
+ else:
+ return ow2, oh2
+
+
+def download_cosyvoice_repo(repo_path):
+ try:
+ import git
+ except ImportError:
+ raise ImportError('failed to import git, please run pip install GitPython')
+ repo = git.Repo.clone_from('https://github.com/FunAudioLLM/CosyVoice.git', repo_path, multi_options=['--recursive'], branch='main')
+
+
+def download_cosyvoice_model(model_name, model_path):
+ from modelscope import snapshot_download
+ snapshot_download('iic/{}'.format(model_name), local_dir=model_path)