Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/.msc +0 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/.mv +1 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/README.md +165 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/alphabet.json +1 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/config.json +75 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/configuration.json +1 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/eval.py +164 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/full_eval.sh +15 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/language_model/attrs.json +1 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/language_model/unigrams.txt +0 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_mozilla-foundation_common_voice_6_0_en_test_predictions.txt +0 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_mozilla-foundation_common_voice_6_0_en_test_predictions_greedy.txt +0 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_mozilla-foundation_common_voice_6_0_en_test_targets.txt +0 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_speech-recognition-community-v2_dev_data_en_validation_predictions.txt +0 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_speech-recognition-community-v2_dev_data_en_validation_predictions_greedy.txt +0 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_speech-recognition-community-v2_dev_data_en_validation_targets.txt +0 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/mozilla-foundation_common_voice_6_0_en_test_eval_results.txt +2 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/mozilla-foundation_common_voice_6_0_en_test_eval_results_greedy.txt +2 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/preprocessor_config.json +10 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/special_tokens_map.json +1 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/speech-recognition-community-v2_dev_data_en_validation_eval_results.txt +2 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/speech-recognition-community-v2_dev_data_en_validation_eval_results_greedy.txt +2 -0
- exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/vocab.json +1 -0
- exp_code/1_benchmark/Wan2.2-diffusers/infer_i2v.py +47 -0
- exp_code/1_benchmark/Wan2.2-diffusers/infer_t2v.py +33 -0
- exp_code/1_benchmark/Wan2.2-diffusers/pipeline_wan.py +656 -0
- exp_code/1_benchmark/Wan2.2-diffusers/pipeline_wan_i2v.py +824 -0
- exp_code/1_benchmark/Wan2.2/.gitignore +7 -0
- exp_code/1_benchmark/Wan2.2/INSTALL.md +55 -0
- exp_code/1_benchmark/Wan2.2/LICENSE.txt +201 -0
- exp_code/1_benchmark/Wan2.2/Makefile +5 -0
- exp_code/1_benchmark/Wan2.2/README.md +354 -0
- exp_code/1_benchmark/Wan2.2/generate.py +486 -0
- exp_code/1_benchmark/Wan2.2/pyproject.toml +66 -0
- exp_code/1_benchmark/Wan2.2/requirements.txt +15 -0
- exp_code/1_benchmark/Wan2.2/run.sh +6 -0
- exp_code/1_benchmark/Wan2.2/tests/README.md +6 -0
- exp_code/1_benchmark/Wan2.2/tests/test.sh +91 -0
- exp_code/1_benchmark/Wan2.2/wan/__init__.py +6 -0
- exp_code/1_benchmark/Wan2.2/wan/__pycache__/__init__.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/__pycache__/image2video.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/__pycache__/speech2video.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/__pycache__/text2video.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/__pycache__/textimage2video.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/configs/__init__.py +47 -0
- exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/__init__.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/shared_config.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/wan_i2v_A14B.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/wan_s2v_14B.cpython-311.pyc +0 -0
- exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/wan_t2v_A14B.cpython-311.pyc +0 -0
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/.msc
ADDED
|
Binary file (2.33 kB). View file
|
|
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/.mv
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Revision:master,CreatedAt:1730986758
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/README.md
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language: en
|
| 3 |
+
datasets:
|
| 4 |
+
- common_voice
|
| 5 |
+
- mozilla-foundation/common_voice_6_0
|
| 6 |
+
metrics:
|
| 7 |
+
- wer
|
| 8 |
+
- cer
|
| 9 |
+
tags:
|
| 10 |
+
- audio
|
| 11 |
+
- automatic-speech-recognition
|
| 12 |
+
- en
|
| 13 |
+
- hf-asr-leaderboard
|
| 14 |
+
- mozilla-foundation/common_voice_6_0
|
| 15 |
+
- robust-speech-event
|
| 16 |
+
- speech
|
| 17 |
+
- xlsr-fine-tuning-week
|
| 18 |
+
license: apache-2.0
|
| 19 |
+
model-index:
|
| 20 |
+
- name: XLSR Wav2Vec2 English by Jonatas Grosman
|
| 21 |
+
results:
|
| 22 |
+
- task:
|
| 23 |
+
name: Automatic Speech Recognition
|
| 24 |
+
type: automatic-speech-recognition
|
| 25 |
+
dataset:
|
| 26 |
+
name: Common Voice en
|
| 27 |
+
type: common_voice
|
| 28 |
+
args: en
|
| 29 |
+
metrics:
|
| 30 |
+
- name: Test WER
|
| 31 |
+
type: wer
|
| 32 |
+
value: 19.06
|
| 33 |
+
- name: Test CER
|
| 34 |
+
type: cer
|
| 35 |
+
value: 7.69
|
| 36 |
+
- name: Test WER (+LM)
|
| 37 |
+
type: wer
|
| 38 |
+
value: 14.81
|
| 39 |
+
- name: Test CER (+LM)
|
| 40 |
+
type: cer
|
| 41 |
+
value: 6.84
|
| 42 |
+
- task:
|
| 43 |
+
name: Automatic Speech Recognition
|
| 44 |
+
type: automatic-speech-recognition
|
| 45 |
+
dataset:
|
| 46 |
+
name: Robust Speech Event - Dev Data
|
| 47 |
+
type: speech-recognition-community-v2/dev_data
|
| 48 |
+
args: en
|
| 49 |
+
metrics:
|
| 50 |
+
- name: Dev WER
|
| 51 |
+
type: wer
|
| 52 |
+
value: 27.72
|
| 53 |
+
- name: Dev CER
|
| 54 |
+
type: cer
|
| 55 |
+
value: 11.65
|
| 56 |
+
- name: Dev WER (+LM)
|
| 57 |
+
type: wer
|
| 58 |
+
value: 20.85
|
| 59 |
+
- name: Dev CER (+LM)
|
| 60 |
+
type: cer
|
| 61 |
+
value: 11.01
|
| 62 |
+
---
|
| 63 |
+
|
| 64 |
+
# Fine-tuned XLSR-53 large model for speech recognition in English
|
| 65 |
+
|
| 66 |
+
Fine-tuned [facebook/wav2vec2-large-xlsr-53](https://huggingface.co/facebook/wav2vec2-large-xlsr-53) on English using the train and validation splits of [Common Voice 6.1](https://huggingface.co/datasets/common_voice).
|
| 67 |
+
When using this model, make sure that your speech input is sampled at 16kHz.
|
| 68 |
+
|
| 69 |
+
This model has been fine-tuned thanks to the GPU credits generously given by the [OVHcloud](https://www.ovhcloud.com/en/public-cloud/ai-training/) :)
|
| 70 |
+
|
| 71 |
+
The script used for training can be found here: https://github.com/jonatasgrosman/wav2vec2-sprint
|
| 72 |
+
|
| 73 |
+
## Usage
|
| 74 |
+
|
| 75 |
+
The model can be used directly (without a language model) as follows...
|
| 76 |
+
|
| 77 |
+
Using the [HuggingSound](https://github.com/jonatasgrosman/huggingsound) library:
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
from huggingsound import SpeechRecognitionModel
|
| 81 |
+
|
| 82 |
+
model = SpeechRecognitionModel("jonatasgrosman/wav2vec2-large-xlsr-53-english")
|
| 83 |
+
audio_paths = ["/path/to/file.mp3", "/path/to/another_file.wav"]
|
| 84 |
+
|
| 85 |
+
transcriptions = model.transcribe(audio_paths)
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
Writing your own inference script:
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
import torch
|
| 92 |
+
import librosa
|
| 93 |
+
from datasets import load_dataset
|
| 94 |
+
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
|
| 95 |
+
|
| 96 |
+
LANG_ID = "en"
|
| 97 |
+
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-english"
|
| 98 |
+
SAMPLES = 10
|
| 99 |
+
|
| 100 |
+
test_dataset = load_dataset("common_voice", LANG_ID, split=f"test[:{SAMPLES}]")
|
| 101 |
+
|
| 102 |
+
processor = Wav2Vec2Processor.from_pretrained(MODEL_ID)
|
| 103 |
+
model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID)
|
| 104 |
+
|
| 105 |
+
# Preprocessing the datasets.
|
| 106 |
+
# We need to read the audio files as arrays
|
| 107 |
+
def speech_file_to_array_fn(batch):
|
| 108 |
+
speech_array, sampling_rate = librosa.load(batch["path"], sr=16_000)
|
| 109 |
+
batch["speech"] = speech_array
|
| 110 |
+
batch["sentence"] = batch["sentence"].upper()
|
| 111 |
+
return batch
|
| 112 |
+
|
| 113 |
+
test_dataset = test_dataset.map(speech_file_to_array_fn)
|
| 114 |
+
inputs = processor(test_dataset["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
|
| 115 |
+
|
| 116 |
+
with torch.no_grad():
|
| 117 |
+
logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits
|
| 118 |
+
|
| 119 |
+
predicted_ids = torch.argmax(logits, dim=-1)
|
| 120 |
+
predicted_sentences = processor.batch_decode(predicted_ids)
|
| 121 |
+
|
| 122 |
+
for i, predicted_sentence in enumerate(predicted_sentences):
|
| 123 |
+
print("-" * 100)
|
| 124 |
+
print("Reference:", test_dataset[i]["sentence"])
|
| 125 |
+
print("Prediction:", predicted_sentence)
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
| Reference | Prediction |
|
| 129 |
+
| ------------- | ------------- |
|
| 130 |
+
| "SHE'LL BE ALL RIGHT." | SHE'LL BE ALL RIGHT |
|
| 131 |
+
| SIX | SIX |
|
| 132 |
+
| "ALL'S WELL THAT ENDS WELL." | ALL AS WELL THAT ENDS WELL |
|
| 133 |
+
| DO YOU MEAN IT? | DO YOU MEAN IT |
|
| 134 |
+
| THE NEW PATCH IS LESS INVASIVE THAN THE OLD ONE, BUT STILL CAUSES REGRESSIONS. | THE NEW PATCH IS LESS INVASIVE THAN THE OLD ONE BUT STILL CAUSES REGRESSION |
|
| 135 |
+
| HOW IS MOZILLA GOING TO HANDLE AMBIGUITIES LIKE QUEUE AND CUE? | HOW IS MOSLILLAR GOING TO HANDLE ANDBEWOOTH HIS LIKE Q AND Q |
|
| 136 |
+
| "I GUESS YOU MUST THINK I'M KINDA BATTY." | RUSTIAN WASTIN PAN ONTE BATTLY |
|
| 137 |
+
| NO ONE NEAR THE REMOTE MACHINE YOU COULD RING? | NO ONE NEAR THE REMOTE MACHINE YOU COULD RING |
|
| 138 |
+
| SAUCE FOR THE GOOSE IS SAUCE FOR THE GANDER. | SAUCE FOR THE GUICE IS SAUCE FOR THE GONDER |
|
| 139 |
+
| GROVES STARTED WRITING SONGS WHEN SHE WAS FOUR YEARS OLD. | GRAFS STARTED WRITING SONGS WHEN SHE WAS FOUR YEARS OLD |
|
| 140 |
+
|
| 141 |
+
## Evaluation
|
| 142 |
+
|
| 143 |
+
1. To evaluate on `mozilla-foundation/common_voice_6_0` with split `test`
|
| 144 |
+
|
| 145 |
+
```bash
|
| 146 |
+
python eval.py --model_id jonatasgrosman/wav2vec2-large-xlsr-53-english --dataset mozilla-foundation/common_voice_6_0 --config en --split test
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
2. To evaluate on `speech-recognition-community-v2/dev_data`
|
| 150 |
+
|
| 151 |
+
```bash
|
| 152 |
+
python eval.py --model_id jonatasgrosman/wav2vec2-large-xlsr-53-english --dataset speech-recognition-community-v2/dev_data --config en --split validation --chunk_length_s 5.0 --stride_length_s 1.0
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
## Citation
|
| 156 |
+
If you want to cite this model you can use this:
|
| 157 |
+
|
| 158 |
+
```bibtex
|
| 159 |
+
@misc{grosman2021xlsr53-large-english,
|
| 160 |
+
title={Fine-tuned {XLSR}-53 large model for speech recognition in {E}nglish},
|
| 161 |
+
author={Grosman, Jonatas},
|
| 162 |
+
howpublished={\url{https://huggingface.co/jonatasgrosman/wav2vec2-large-xlsr-53-english}},
|
| 163 |
+
year={2021}
|
| 164 |
+
}
|
| 165 |
+
```
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/alphabet.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"labels": ["", "<s>", "</s>", "⁇", " ", "'", "-", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"], "is_bpe": false}
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/config.json
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "facebook/wav2vec2-large-xlsr-53",
|
| 3 |
+
"activation_dropout": 0.05,
|
| 4 |
+
"apply_spec_augment": true,
|
| 5 |
+
"architectures": [
|
| 6 |
+
"Wav2Vec2ForCTC"
|
| 7 |
+
],
|
| 8 |
+
"attention_dropout": 0.1,
|
| 9 |
+
"bos_token_id": 1,
|
| 10 |
+
"conv_bias": true,
|
| 11 |
+
"conv_dim": [
|
| 12 |
+
512,
|
| 13 |
+
512,
|
| 14 |
+
512,
|
| 15 |
+
512,
|
| 16 |
+
512,
|
| 17 |
+
512,
|
| 18 |
+
512
|
| 19 |
+
],
|
| 20 |
+
"conv_kernel": [
|
| 21 |
+
10,
|
| 22 |
+
3,
|
| 23 |
+
3,
|
| 24 |
+
3,
|
| 25 |
+
3,
|
| 26 |
+
2,
|
| 27 |
+
2
|
| 28 |
+
],
|
| 29 |
+
"conv_stride": [
|
| 30 |
+
5,
|
| 31 |
+
2,
|
| 32 |
+
2,
|
| 33 |
+
2,
|
| 34 |
+
2,
|
| 35 |
+
2,
|
| 36 |
+
2
|
| 37 |
+
],
|
| 38 |
+
"ctc_loss_reduction": "mean",
|
| 39 |
+
"ctc_zero_infinity": true,
|
| 40 |
+
"do_stable_layer_norm": true,
|
| 41 |
+
"eos_token_id": 2,
|
| 42 |
+
"feat_extract_activation": "gelu",
|
| 43 |
+
"feat_extract_dropout": 0.0,
|
| 44 |
+
"feat_extract_norm": "layer",
|
| 45 |
+
"feat_proj_dropout": 0.05,
|
| 46 |
+
"final_dropout": 0.0,
|
| 47 |
+
"hidden_act": "gelu",
|
| 48 |
+
"hidden_dropout": 0.05,
|
| 49 |
+
"hidden_size": 1024,
|
| 50 |
+
"initializer_range": 0.02,
|
| 51 |
+
"intermediate_size": 4096,
|
| 52 |
+
"layer_norm_eps": 1e-05,
|
| 53 |
+
"layerdrop": 0.05,
|
| 54 |
+
"mask_channel_length": 10,
|
| 55 |
+
"mask_channel_min_space": 1,
|
| 56 |
+
"mask_channel_other": 0.0,
|
| 57 |
+
"mask_channel_prob": 0.0,
|
| 58 |
+
"mask_channel_selection": "static",
|
| 59 |
+
"mask_feature_length": 10,
|
| 60 |
+
"mask_feature_prob": 0.0,
|
| 61 |
+
"mask_time_length": 10,
|
| 62 |
+
"mask_time_min_space": 1,
|
| 63 |
+
"mask_time_other": 0.0,
|
| 64 |
+
"mask_time_prob": 0.05,
|
| 65 |
+
"mask_time_selection": "static",
|
| 66 |
+
"model_type": "wav2vec2",
|
| 67 |
+
"num_attention_heads": 16,
|
| 68 |
+
"num_conv_pos_embedding_groups": 16,
|
| 69 |
+
"num_conv_pos_embeddings": 128,
|
| 70 |
+
"num_feat_extract_layers": 7,
|
| 71 |
+
"num_hidden_layers": 24,
|
| 72 |
+
"pad_token_id": 0,
|
| 73 |
+
"transformers_version": "4.7.0.dev0",
|
| 74 |
+
"vocab_size": 33
|
| 75 |
+
}
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/configuration.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"framework": "pytorch", "task": "automatic-speech-recognition", "allow_remote": true}
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/eval.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from datasets import load_dataset, load_metric, Audio, Dataset
|
| 3 |
+
from transformers import pipeline, AutoFeatureExtractor, AutoTokenizer, AutoConfig, AutoModelForCTC, Wav2Vec2Processor, Wav2Vec2ProcessorWithLM
|
| 4 |
+
import re
|
| 5 |
+
import torch
|
| 6 |
+
import argparse
|
| 7 |
+
from typing import Dict
|
| 8 |
+
|
| 9 |
+
def log_results(result: Dataset, args: Dict[str, str]):
|
| 10 |
+
""" DO NOT CHANGE. This function computes and logs the result metrics. """
|
| 11 |
+
|
| 12 |
+
log_outputs = args.log_outputs
|
| 13 |
+
dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
|
| 14 |
+
|
| 15 |
+
# load metric
|
| 16 |
+
wer = load_metric("wer")
|
| 17 |
+
cer = load_metric("cer")
|
| 18 |
+
|
| 19 |
+
# compute metrics
|
| 20 |
+
wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
|
| 21 |
+
cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
|
| 22 |
+
|
| 23 |
+
# print & log results
|
| 24 |
+
result_str = (
|
| 25 |
+
f"WER: {wer_result}\n"
|
| 26 |
+
f"CER: {cer_result}"
|
| 27 |
+
)
|
| 28 |
+
print(result_str)
|
| 29 |
+
|
| 30 |
+
with open(f"{dataset_id}_eval_results.txt", "w") as f:
|
| 31 |
+
f.write(result_str)
|
| 32 |
+
|
| 33 |
+
# log all results in text file. Possibly interesting for analysis
|
| 34 |
+
if log_outputs is not None:
|
| 35 |
+
pred_file = f"log_{dataset_id}_predictions.txt"
|
| 36 |
+
target_file = f"log_{dataset_id}_targets.txt"
|
| 37 |
+
|
| 38 |
+
with open(pred_file, "w") as p, open(target_file, "w") as t:
|
| 39 |
+
|
| 40 |
+
# mapping function to write output
|
| 41 |
+
def write_to_file(batch, i):
|
| 42 |
+
p.write(f"{i}" + "\n")
|
| 43 |
+
p.write(batch["prediction"] + "\n")
|
| 44 |
+
t.write(f"{i}" + "\n")
|
| 45 |
+
t.write(batch["target"] + "\n")
|
| 46 |
+
|
| 47 |
+
result.map(write_to_file, with_indices=True)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def normalize_text(text: str, invalid_chars_regex: str, to_lower: bool) -> str:
|
| 51 |
+
""" DO ADAPT FOR YOUR USE CASE. this function normalizes the target text. """
|
| 52 |
+
|
| 53 |
+
text = text.lower() if to_lower else text.upper()
|
| 54 |
+
|
| 55 |
+
text = re.sub(invalid_chars_regex, " ", text)
|
| 56 |
+
|
| 57 |
+
text = re.sub("\s+", " ", text).strip()
|
| 58 |
+
|
| 59 |
+
return text
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main(args):
|
| 63 |
+
# load dataset
|
| 64 |
+
dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
|
| 65 |
+
|
| 66 |
+
# for testing: only process the first two examples as a test
|
| 67 |
+
# dataset = dataset.select(range(10))
|
| 68 |
+
|
| 69 |
+
# load processor
|
| 70 |
+
if args.greedy:
|
| 71 |
+
processor = Wav2Vec2Processor.from_pretrained(args.model_id)
|
| 72 |
+
decoder = None
|
| 73 |
+
else:
|
| 74 |
+
processor = Wav2Vec2ProcessorWithLM.from_pretrained(args.model_id)
|
| 75 |
+
decoder = processor.decoder
|
| 76 |
+
|
| 77 |
+
feature_extractor = processor.feature_extractor
|
| 78 |
+
tokenizer = processor.tokenizer
|
| 79 |
+
|
| 80 |
+
# resample audio
|
| 81 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
|
| 82 |
+
|
| 83 |
+
# load eval pipeline
|
| 84 |
+
if args.device is None:
|
| 85 |
+
args.device = 0 if torch.cuda.is_available() else -1
|
| 86 |
+
|
| 87 |
+
config = AutoConfig.from_pretrained(args.model_id)
|
| 88 |
+
model = AutoModelForCTC.from_pretrained(args.model_id)
|
| 89 |
+
|
| 90 |
+
#asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
|
| 91 |
+
asr = pipeline("automatic-speech-recognition", config=config, model=model, tokenizer=tokenizer,
|
| 92 |
+
feature_extractor=feature_extractor, decoder=decoder, device=args.device)
|
| 93 |
+
|
| 94 |
+
# build normalizer config
|
| 95 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_id)
|
| 96 |
+
tokens = [x for x in tokenizer.convert_ids_to_tokens(range(0, tokenizer.vocab_size))]
|
| 97 |
+
special_tokens = [
|
| 98 |
+
tokenizer.pad_token, tokenizer.word_delimiter_token,
|
| 99 |
+
tokenizer.unk_token, tokenizer.bos_token,
|
| 100 |
+
tokenizer.eos_token,
|
| 101 |
+
]
|
| 102 |
+
non_special_tokens = [x for x in tokens if x not in special_tokens]
|
| 103 |
+
invalid_chars_regex = f"[^\s{re.escape(''.join(set(non_special_tokens)))}]"
|
| 104 |
+
normalize_to_lower = False
|
| 105 |
+
for token in non_special_tokens:
|
| 106 |
+
if token.isalpha() and token.islower():
|
| 107 |
+
normalize_to_lower = True
|
| 108 |
+
break
|
| 109 |
+
|
| 110 |
+
# map function to decode audio
|
| 111 |
+
def map_to_pred(batch, args=args, asr=asr, invalid_chars_regex=invalid_chars_regex, normalize_to_lower=normalize_to_lower):
|
| 112 |
+
prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
|
| 113 |
+
|
| 114 |
+
batch["prediction"] = prediction["text"]
|
| 115 |
+
batch["target"] = normalize_text(batch["sentence"], invalid_chars_regex, normalize_to_lower)
|
| 116 |
+
return batch
|
| 117 |
+
|
| 118 |
+
# run inference on all examples
|
| 119 |
+
result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
|
| 120 |
+
|
| 121 |
+
# filtering out empty targets
|
| 122 |
+
result = result.filter(lambda example: example["target"] != "")
|
| 123 |
+
|
| 124 |
+
# compute and log_results
|
| 125 |
+
# do not change function below
|
| 126 |
+
log_results(result, args)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
parser = argparse.ArgumentParser()
|
| 131 |
+
|
| 132 |
+
parser.add_argument(
|
| 133 |
+
"--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
|
| 134 |
+
)
|
| 135 |
+
parser.add_argument(
|
| 136 |
+
"--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
|
| 137 |
+
)
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
|
| 140 |
+
)
|
| 141 |
+
parser.add_argument(
|
| 142 |
+
"--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
|
| 143 |
+
)
|
| 144 |
+
parser.add_argument(
|
| 145 |
+
"--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to None. For long audio files a good value would be 5.0 seconds."
|
| 146 |
+
)
|
| 147 |
+
parser.add_argument(
|
| 148 |
+
"--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to None. For long audio files a good value would be 1.0 seconds."
|
| 149 |
+
)
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
|
| 152 |
+
)
|
| 153 |
+
parser.add_argument(
|
| 154 |
+
"--greedy", action='store_true', help="If defined, the LM will be ignored during inference."
|
| 155 |
+
)
|
| 156 |
+
parser.add_argument(
|
| 157 |
+
"--device",
|
| 158 |
+
type=int,
|
| 159 |
+
default=None,
|
| 160 |
+
help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
|
| 161 |
+
)
|
| 162 |
+
args = parser.parse_args()
|
| 163 |
+
|
| 164 |
+
main(args)
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/full_eval.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CV - TEST
|
| 2 |
+
|
| 3 |
+
python eval.py --model_id jonatasgrosman/wav2vec2-large-xlsr-53-english --dataset mozilla-foundation/common_voice_6_0 --config en --split test --log_outputs --greedy
|
| 4 |
+
mv log_mozilla-foundation_common_voice_6_0_en_test_predictions.txt log_mozilla-foundation_common_voice_6_0_en_test_predictions_greedy.txt
|
| 5 |
+
mv mozilla-foundation_common_voice_6_0_en_test_eval_results.txt mozilla-foundation_common_voice_6_0_en_test_eval_results_greedy.txt
|
| 6 |
+
|
| 7 |
+
python eval.py --model_id jonatasgrosman/wav2vec2-large-xlsr-53-english --dataset mozilla-foundation/common_voice_6_0 --config en --split test --log_outputs
|
| 8 |
+
|
| 9 |
+
# HF EVENT - DEV
|
| 10 |
+
|
| 11 |
+
python eval.py --model_id jonatasgrosman/wav2vec2-large-xlsr-53-english --dataset speech-recognition-community-v2/dev_data --config en --split validation --chunk_length_s 5.0 --stride_length_s 1.0 --log_outputs --greedy
|
| 12 |
+
mv log_speech-recognition-community-v2_dev_data_en_validation_predictions.txt log_speech-recognition-community-v2_dev_data_en_validation_predictions_greedy.txt
|
| 13 |
+
mv speech-recognition-community-v2_dev_data_en_validation_eval_results.txt speech-recognition-community-v2_dev_data_en_validation_eval_results_greedy.txt
|
| 14 |
+
|
| 15 |
+
python eval.py --model_id jonatasgrosman/wav2vec2-large-xlsr-53-english --dataset speech-recognition-community-v2/dev_data --config en --split validation --chunk_length_s 5.0 --stride_length_s 1.0 --log_outputs
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/language_model/attrs.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"alpha": 0.5, "beta": 1.5, "unk_score_offset": -10.0, "score_boundary": true}
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/language_model/unigrams.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_mozilla-foundation_common_voice_6_0_en_test_predictions.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_mozilla-foundation_common_voice_6_0_en_test_predictions_greedy.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_mozilla-foundation_common_voice_6_0_en_test_targets.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_speech-recognition-community-v2_dev_data_en_validation_predictions.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_speech-recognition-community-v2_dev_data_en_validation_predictions_greedy.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/log_speech-recognition-community-v2_dev_data_en_validation_targets.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/mozilla-foundation_common_voice_6_0_en_test_eval_results.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
WER: 0.1481828839390387
|
| 2 |
+
CER: 0.06848087313203592
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/mozilla-foundation_common_voice_6_0_en_test_eval_results_greedy.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
WER: 0.19067492882264278
|
| 2 |
+
CER: 0.07694957927516068
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/preprocessor_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"do_normalize": true,
|
| 3 |
+
"feature_extractor_type": "Wav2Vec2FeatureExtractor",
|
| 4 |
+
"feature_size": 1,
|
| 5 |
+
"padding_side": "right",
|
| 6 |
+
"padding_value": 0.0,
|
| 7 |
+
"return_attention_mask": true,
|
| 8 |
+
"sampling_rate": 16000,
|
| 9 |
+
"processor_class": "Wav2Vec2ProcessorWithLM"
|
| 10 |
+
}
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/special_tokens_map.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>"}
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/speech-recognition-community-v2_dev_data_en_validation_eval_results.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
WER: 0.2085057090848916
|
| 2 |
+
CER: 0.11011805154105943
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/speech-recognition-community-v2_dev_data_en_validation_eval_results_greedy.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
WER: 0.27722157868608305
|
| 2 |
+
CER: 0.11652265190008215
|
exp_code/1_benchmark/Wan-S2V/models/Wan-AI/Wan2.2-S2V-14B/wav2vec2-large-xlsr-53-english/vocab.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"<pad>": 0, "<s>": 1, "</s>": 2, "<unk>": 3, "|": 4, "'": 5, "-": 6, "a": 7, "b": 8, "c": 9, "d": 10, "e": 11, "f": 12, "g": 13, "h": 14, "i": 15, "j": 16, "k": 17, "l": 18, "m": 19, "n": 20, "o": 21, "p": 22, "q": 23, "r": 24, "s": 25, "t": 26, "u": 27, "v": 28, "w": 29, "x": 30, "y": 31, "z": 32}
|
exp_code/1_benchmark/Wan2.2-diffusers/infer_i2v.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from diffusers import WanImageToVideoPipeline, AutoencoderKLWan
|
| 4 |
+
from diffusers.utils import export_to_video, load_image
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
model_id = "/mnt/bn/yufan-dev-my/ysh/Ckpts/Wan-AI/Wan2.2-TI2V-5B-Diffusers"
|
| 8 |
+
dtype = torch.bfloat16
|
| 9 |
+
device = "cuda"
|
| 10 |
+
|
| 11 |
+
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 12 |
+
pipe = WanImageToVideoPipeline.from_pretrained(model_id, vae=vae, torch_dtype=dtype)
|
| 13 |
+
vae.to(device)
|
| 14 |
+
pipe.to(device)
|
| 15 |
+
|
| 16 |
+
# use default wan image processor to resize and crop the image
|
| 17 |
+
image = load_image(
|
| 18 |
+
"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
|
| 19 |
+
)
|
| 20 |
+
max_area = 480 * 832
|
| 21 |
+
aspect_ratio = image.height / image.width
|
| 22 |
+
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
|
| 23 |
+
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
|
| 24 |
+
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
|
| 25 |
+
image = image.resize((width, height))
|
| 26 |
+
|
| 27 |
+
height, width = image.height, image.width
|
| 28 |
+
print(f"height: {height}, width: {width}")
|
| 29 |
+
num_frames = 121
|
| 30 |
+
num_inference_steps = 50
|
| 31 |
+
guidance_scale = 5.0
|
| 32 |
+
|
| 33 |
+
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."
|
| 34 |
+
|
| 35 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 36 |
+
|
| 37 |
+
output = pipe(
|
| 38 |
+
image=image,
|
| 39 |
+
prompt=prompt,
|
| 40 |
+
negative_prompt=negative_prompt,
|
| 41 |
+
height=height,
|
| 42 |
+
width=width,
|
| 43 |
+
num_frames=num_frames,
|
| 44 |
+
guidance_scale=guidance_scale,
|
| 45 |
+
num_inference_steps=num_inference_steps,
|
| 46 |
+
).frames[0]
|
| 47 |
+
export_to_video(output, "yiyi_test_6_ti2v_5b_output.mp4", fps=24)
|
exp_code/1_benchmark/Wan2.2-diffusers/infer_t2v.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
from diffusers import WanPipeline, AutoencoderKLWan, WanTransformer3DModel, UniPCMultistepScheduler
|
| 4 |
+
from diffusers.utils import export_to_video, load_image
|
| 5 |
+
|
| 6 |
+
dtype = torch.bfloat16
|
| 7 |
+
device = "cuda"
|
| 8 |
+
|
| 9 |
+
model_id = "/mnt/bn/yufan-dev-my/ysh/Ckpts/Wan-AI/Wan2.2-TI2V-5B-Diffusers"
|
| 10 |
+
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 11 |
+
pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=dtype)
|
| 12 |
+
pipe.to(device)
|
| 13 |
+
|
| 14 |
+
height = 704
|
| 15 |
+
width = 1280
|
| 16 |
+
num_frames = 121
|
| 17 |
+
num_inference_steps = 50
|
| 18 |
+
guidance_scale = 5.0
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
prompt = "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
|
| 22 |
+
negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
|
| 23 |
+
|
| 24 |
+
output = pipe(
|
| 25 |
+
prompt=prompt,
|
| 26 |
+
negative_prompt=negative_prompt,
|
| 27 |
+
height=height,
|
| 28 |
+
width=width,
|
| 29 |
+
num_frames=num_frames,
|
| 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
|
|
|
|
| 1 |
+
# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import html
|
| 16 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import regex as re
|
| 19 |
+
import torch
|
| 20 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 21 |
+
|
| 22 |
+
from ...callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 23 |
+
from ...loaders import WanLoraLoaderMixin
|
| 24 |
+
from ...models import AutoencoderKLWan, WanTransformer3DModel
|
| 25 |
+
from ...schedulers import FlowMatchEulerDiscreteScheduler
|
| 26 |
+
from ...utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
|
| 27 |
+
from ...utils.torch_utils import randn_tensor
|
| 28 |
+
from ...video_processor import VideoProcessor
|
| 29 |
+
from ..pipeline_utils import DiffusionPipeline
|
| 30 |
+
from .pipeline_output import WanPipelineOutput
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if is_torch_xla_available():
|
| 34 |
+
import torch_xla.core.xla_model as xm
|
| 35 |
+
|
| 36 |
+
XLA_AVAILABLE = True
|
| 37 |
+
else:
|
| 38 |
+
XLA_AVAILABLE = False
|
| 39 |
+
|
| 40 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 41 |
+
|
| 42 |
+
if is_ftfy_available():
|
| 43 |
+
import ftfy
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
EXAMPLE_DOC_STRING = """
|
| 47 |
+
Examples:
|
| 48 |
+
```python
|
| 49 |
+
>>> import torch
|
| 50 |
+
>>> from diffusers.utils import export_to_video
|
| 51 |
+
>>> from diffusers import AutoencoderKLWan, WanPipeline
|
| 52 |
+
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
|
| 53 |
+
|
| 54 |
+
>>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
|
| 55 |
+
>>> model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
|
| 56 |
+
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 57 |
+
>>> pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
|
| 58 |
+
>>> flow_shift = 5.0 # 5.0 for 720P, 3.0 for 480P
|
| 59 |
+
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
|
| 60 |
+
>>> pipe.to("cuda")
|
| 61 |
+
|
| 62 |
+
>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
|
| 63 |
+
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 64 |
+
|
| 65 |
+
>>> output = pipe(
|
| 66 |
+
... prompt=prompt,
|
| 67 |
+
... negative_prompt=negative_prompt,
|
| 68 |
+
... height=720,
|
| 69 |
+
... width=1280,
|
| 70 |
+
... num_frames=81,
|
| 71 |
+
... guidance_scale=5.0,
|
| 72 |
+
... ).frames[0]
|
| 73 |
+
>>> export_to_video(output, "output.mp4", fps=16)
|
| 74 |
+
```
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def basic_clean(text):
|
| 79 |
+
text = ftfy.fix_text(text)
|
| 80 |
+
text = html.unescape(html.unescape(text))
|
| 81 |
+
return text.strip()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def whitespace_clean(text):
|
| 85 |
+
text = re.sub(r"\s+", " ", text)
|
| 86 |
+
text = text.strip()
|
| 87 |
+
return text
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def prompt_clean(text):
|
| 91 |
+
text = whitespace_clean(basic_clean(text))
|
| 92 |
+
return text
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class WanPipeline(DiffusionPipeline, WanLoraLoaderMixin):
|
| 96 |
+
r"""
|
| 97 |
+
Pipeline for text-to-video generation using Wan.
|
| 98 |
+
|
| 99 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 100 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
tokenizer ([`T5Tokenizer`]):
|
| 104 |
+
Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
|
| 105 |
+
specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 106 |
+
text_encoder ([`T5EncoderModel`]):
|
| 107 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 108 |
+
the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 109 |
+
transformer ([`WanTransformer3DModel`]):
|
| 110 |
+
Conditional Transformer to denoise the input latents.
|
| 111 |
+
scheduler ([`UniPCMultistepScheduler`]):
|
| 112 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 113 |
+
vae ([`AutoencoderKLWan`]):
|
| 114 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
| 115 |
+
transformer_2 ([`WanTransformer3DModel`], *optional*):
|
| 116 |
+
Conditional Transformer to denoise the input latents during the low-noise stage. If provided, enables
|
| 117 |
+
two-stage denoising where `transformer` handles high-noise stages and `transformer_2` handles low-noise
|
| 118 |
+
stages. If not provided, only `transformer` is used.
|
| 119 |
+
boundary_ratio (`float`, *optional*, defaults to `None`):
|
| 120 |
+
Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising.
|
| 121 |
+
The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided,
|
| 122 |
+
`transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps <
|
| 123 |
+
boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
model_cpu_offload_seq = "text_encoder->transformer->transformer_2->vae"
|
| 127 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 128 |
+
_optional_components = ["transformer", "transformer_2"]
|
| 129 |
+
|
| 130 |
+
def __init__(
|
| 131 |
+
self,
|
| 132 |
+
tokenizer: AutoTokenizer,
|
| 133 |
+
text_encoder: UMT5EncoderModel,
|
| 134 |
+
vae: AutoencoderKLWan,
|
| 135 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
| 136 |
+
transformer: Optional[WanTransformer3DModel] = None,
|
| 137 |
+
transformer_2: Optional[WanTransformer3DModel] = None,
|
| 138 |
+
boundary_ratio: Optional[float] = None,
|
| 139 |
+
expand_timesteps: bool = False, # Wan2.2 ti2v
|
| 140 |
+
):
|
| 141 |
+
super().__init__()
|
| 142 |
+
|
| 143 |
+
self.register_modules(
|
| 144 |
+
vae=vae,
|
| 145 |
+
text_encoder=text_encoder,
|
| 146 |
+
tokenizer=tokenizer,
|
| 147 |
+
transformer=transformer,
|
| 148 |
+
scheduler=scheduler,
|
| 149 |
+
transformer_2=transformer_2,
|
| 150 |
+
)
|
| 151 |
+
self.register_to_config(boundary_ratio=boundary_ratio)
|
| 152 |
+
self.register_to_config(expand_timesteps=expand_timesteps)
|
| 153 |
+
self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
|
| 154 |
+
self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
|
| 155 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
| 156 |
+
|
| 157 |
+
def _get_t5_prompt_embeds(
|
| 158 |
+
self,
|
| 159 |
+
prompt: Union[str, List[str]] = None,
|
| 160 |
+
num_videos_per_prompt: int = 1,
|
| 161 |
+
max_sequence_length: int = 226,
|
| 162 |
+
device: Optional[torch.device] = None,
|
| 163 |
+
dtype: Optional[torch.dtype] = None,
|
| 164 |
+
):
|
| 165 |
+
device = device or self._execution_device
|
| 166 |
+
dtype = dtype or self.text_encoder.dtype
|
| 167 |
+
|
| 168 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 169 |
+
prompt = [prompt_clean(u) for u in prompt]
|
| 170 |
+
batch_size = len(prompt)
|
| 171 |
+
|
| 172 |
+
text_inputs = self.tokenizer(
|
| 173 |
+
prompt,
|
| 174 |
+
padding="max_length",
|
| 175 |
+
max_length=max_sequence_length,
|
| 176 |
+
truncation=True,
|
| 177 |
+
add_special_tokens=True,
|
| 178 |
+
return_attention_mask=True,
|
| 179 |
+
return_tensors="pt",
|
| 180 |
+
)
|
| 181 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 182 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
| 183 |
+
|
| 184 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
| 185 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 186 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 187 |
+
prompt_embeds = torch.stack(
|
| 188 |
+
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 192 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 193 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 194 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 195 |
+
|
| 196 |
+
return prompt_embeds
|
| 197 |
+
|
| 198 |
+
def encode_prompt(
|
| 199 |
+
self,
|
| 200 |
+
prompt: Union[str, List[str]],
|
| 201 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 202 |
+
do_classifier_free_guidance: bool = True,
|
| 203 |
+
num_videos_per_prompt: int = 1,
|
| 204 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 205 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 206 |
+
max_sequence_length: int = 226,
|
| 207 |
+
device: Optional[torch.device] = None,
|
| 208 |
+
dtype: Optional[torch.dtype] = None,
|
| 209 |
+
):
|
| 210 |
+
r"""
|
| 211 |
+
Encodes the prompt into text encoder hidden states.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 215 |
+
prompt to be encoded
|
| 216 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 217 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 218 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 219 |
+
less than `1`).
|
| 220 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 221 |
+
Whether to use classifier free guidance or not.
|
| 222 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 223 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
| 224 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 225 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 226 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 227 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 228 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 229 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 230 |
+
argument.
|
| 231 |
+
device: (`torch.device`, *optional*):
|
| 232 |
+
torch device
|
| 233 |
+
dtype: (`torch.dtype`, *optional*):
|
| 234 |
+
torch dtype
|
| 235 |
+
"""
|
| 236 |
+
device = device or self._execution_device
|
| 237 |
+
|
| 238 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 239 |
+
if prompt is not None:
|
| 240 |
+
batch_size = len(prompt)
|
| 241 |
+
else:
|
| 242 |
+
batch_size = prompt_embeds.shape[0]
|
| 243 |
+
|
| 244 |
+
if prompt_embeds is None:
|
| 245 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
| 246 |
+
prompt=prompt,
|
| 247 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 248 |
+
max_sequence_length=max_sequence_length,
|
| 249 |
+
device=device,
|
| 250 |
+
dtype=dtype,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 254 |
+
negative_prompt = negative_prompt or ""
|
| 255 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
| 256 |
+
|
| 257 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 258 |
+
raise TypeError(
|
| 259 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 260 |
+
f" {type(prompt)}."
|
| 261 |
+
)
|
| 262 |
+
elif batch_size != len(negative_prompt):
|
| 263 |
+
raise ValueError(
|
| 264 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 265 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 266 |
+
" the batch size of `prompt`."
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
negative_prompt_embeds = self._get_t5_prompt_embeds(
|
| 270 |
+
prompt=negative_prompt,
|
| 271 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 272 |
+
max_sequence_length=max_sequence_length,
|
| 273 |
+
device=device,
|
| 274 |
+
dtype=dtype,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
return prompt_embeds, negative_prompt_embeds
|
| 278 |
+
|
| 279 |
+
def check_inputs(
|
| 280 |
+
self,
|
| 281 |
+
prompt,
|
| 282 |
+
negative_prompt,
|
| 283 |
+
height,
|
| 284 |
+
width,
|
| 285 |
+
prompt_embeds=None,
|
| 286 |
+
negative_prompt_embeds=None,
|
| 287 |
+
callback_on_step_end_tensor_inputs=None,
|
| 288 |
+
guidance_scale_2=None,
|
| 289 |
+
):
|
| 290 |
+
if height % 16 != 0 or width % 16 != 0:
|
| 291 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
| 292 |
+
|
| 293 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 294 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 295 |
+
):
|
| 296 |
+
raise ValueError(
|
| 297 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
if prompt is not None and prompt_embeds is not None:
|
| 301 |
+
raise ValueError(
|
| 302 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 303 |
+
" only forward one of the two."
|
| 304 |
+
)
|
| 305 |
+
elif negative_prompt is not None and negative_prompt_embeds is not None:
|
| 306 |
+
raise ValueError(
|
| 307 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
| 308 |
+
" only forward one of the two."
|
| 309 |
+
)
|
| 310 |
+
elif prompt is None and prompt_embeds is None:
|
| 311 |
+
raise ValueError(
|
| 312 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 313 |
+
)
|
| 314 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 315 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 316 |
+
elif negative_prompt is not None and (
|
| 317 |
+
not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
|
| 318 |
+
):
|
| 319 |
+
raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
|
| 320 |
+
|
| 321 |
+
if self.config.boundary_ratio is None and guidance_scale_2 is not None:
|
| 322 |
+
raise ValueError("`guidance_scale_2` is only supported when the pipeline's `boundary_ratio` is not None.")
|
| 323 |
+
|
| 324 |
+
def prepare_latents(
|
| 325 |
+
self,
|
| 326 |
+
batch_size: int,
|
| 327 |
+
num_channels_latents: int = 16,
|
| 328 |
+
height: int = 480,
|
| 329 |
+
width: int = 832,
|
| 330 |
+
num_frames: int = 81,
|
| 331 |
+
dtype: Optional[torch.dtype] = None,
|
| 332 |
+
device: Optional[torch.device] = None,
|
| 333 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 334 |
+
latents: Optional[torch.Tensor] = None,
|
| 335 |
+
) -> torch.Tensor:
|
| 336 |
+
if latents is not None:
|
| 337 |
+
return latents.to(device=device, dtype=dtype)
|
| 338 |
+
|
| 339 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 340 |
+
shape = (
|
| 341 |
+
batch_size,
|
| 342 |
+
num_channels_latents,
|
| 343 |
+
num_latent_frames,
|
| 344 |
+
int(height) // self.vae_scale_factor_spatial,
|
| 345 |
+
int(width) // self.vae_scale_factor_spatial,
|
| 346 |
+
)
|
| 347 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 348 |
+
raise ValueError(
|
| 349 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 350 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 354 |
+
return latents
|
| 355 |
+
|
| 356 |
+
@property
|
| 357 |
+
def guidance_scale(self):
|
| 358 |
+
return self._guidance_scale
|
| 359 |
+
|
| 360 |
+
@property
|
| 361 |
+
def do_classifier_free_guidance(self):
|
| 362 |
+
return self._guidance_scale > 1.0
|
| 363 |
+
|
| 364 |
+
@property
|
| 365 |
+
def num_timesteps(self):
|
| 366 |
+
return self._num_timesteps
|
| 367 |
+
|
| 368 |
+
@property
|
| 369 |
+
def current_timestep(self):
|
| 370 |
+
return self._current_timestep
|
| 371 |
+
|
| 372 |
+
@property
|
| 373 |
+
def interrupt(self):
|
| 374 |
+
return self._interrupt
|
| 375 |
+
|
| 376 |
+
@property
|
| 377 |
+
def attention_kwargs(self):
|
| 378 |
+
return self._attention_kwargs
|
| 379 |
+
|
| 380 |
+
@torch.no_grad()
|
| 381 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 382 |
+
def __call__(
|
| 383 |
+
self,
|
| 384 |
+
prompt: Union[str, List[str]] = None,
|
| 385 |
+
negative_prompt: Union[str, List[str]] = None,
|
| 386 |
+
height: int = 480,
|
| 387 |
+
width: int = 832,
|
| 388 |
+
num_frames: int = 81,
|
| 389 |
+
num_inference_steps: int = 50,
|
| 390 |
+
guidance_scale: float = 5.0,
|
| 391 |
+
guidance_scale_2: Optional[float] = None,
|
| 392 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 393 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 394 |
+
latents: Optional[torch.Tensor] = None,
|
| 395 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 396 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 397 |
+
output_type: Optional[str] = "np",
|
| 398 |
+
return_dict: bool = True,
|
| 399 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 400 |
+
callback_on_step_end: Optional[
|
| 401 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
| 402 |
+
] = None,
|
| 403 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 404 |
+
max_sequence_length: int = 512,
|
| 405 |
+
):
|
| 406 |
+
r"""
|
| 407 |
+
The call function to the pipeline for generation.
|
| 408 |
+
|
| 409 |
+
Args:
|
| 410 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 411 |
+
The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
|
| 412 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 413 |
+
The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
|
| 414 |
+
instead. Ignored when not using guidance (`guidance_scale` < `1`).
|
| 415 |
+
height (`int`, defaults to `480`):
|
| 416 |
+
The height in pixels of the generated image.
|
| 417 |
+
width (`int`, defaults to `832`):
|
| 418 |
+
The width in pixels of the generated image.
|
| 419 |
+
num_frames (`int`, defaults to `81`):
|
| 420 |
+
The number of frames in the generated video.
|
| 421 |
+
num_inference_steps (`int`, defaults to `50`):
|
| 422 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 423 |
+
expense of slower inference.
|
| 424 |
+
guidance_scale (`float`, defaults to `5.0`):
|
| 425 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
| 426 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
| 427 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
| 428 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
| 429 |
+
the text `prompt`, usually at the expense of lower image quality.
|
| 430 |
+
guidance_scale_2 (`float`, *optional*, defaults to `None`):
|
| 431 |
+
Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline's
|
| 432 |
+
`boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2`
|
| 433 |
+
and the pipeline's `boundary_ratio` are not None.
|
| 434 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 435 |
+
The number of images to generate per prompt.
|
| 436 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 437 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 438 |
+
generation deterministic.
|
| 439 |
+
latents (`torch.Tensor`, *optional*):
|
| 440 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 441 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 442 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 443 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 444 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 445 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 446 |
+
output_type (`str`, *optional*, defaults to `"np"`):
|
| 447 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 448 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 449 |
+
Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
|
| 450 |
+
attention_kwargs (`dict`, *optional*):
|
| 451 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 452 |
+
`self.processor` in
|
| 453 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 454 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 455 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 456 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 457 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 458 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 459 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 460 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 461 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 462 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 463 |
+
max_sequence_length (`int`, defaults to `512`):
|
| 464 |
+
The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
|
| 465 |
+
truncated. If the prompt is shorter, it will be padded to this length.
|
| 466 |
+
|
| 467 |
+
Examples:
|
| 468 |
+
|
| 469 |
+
Returns:
|
| 470 |
+
[`~WanPipelineOutput`] or `tuple`:
|
| 471 |
+
If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
|
| 472 |
+
the first element is a list with the generated images and the second element is a list of `bool`s
|
| 473 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
| 474 |
+
"""
|
| 475 |
+
|
| 476 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 477 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 478 |
+
|
| 479 |
+
# 1. Check inputs. Raise error if not correct
|
| 480 |
+
self.check_inputs(
|
| 481 |
+
prompt,
|
| 482 |
+
negative_prompt,
|
| 483 |
+
height,
|
| 484 |
+
width,
|
| 485 |
+
prompt_embeds,
|
| 486 |
+
negative_prompt_embeds,
|
| 487 |
+
callback_on_step_end_tensor_inputs,
|
| 488 |
+
guidance_scale_2,
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
if num_frames % self.vae_scale_factor_temporal != 1:
|
| 492 |
+
logger.warning(
|
| 493 |
+
f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
|
| 494 |
+
)
|
| 495 |
+
num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
|
| 496 |
+
num_frames = max(num_frames, 1)
|
| 497 |
+
|
| 498 |
+
if self.config.boundary_ratio is not None and guidance_scale_2 is None:
|
| 499 |
+
guidance_scale_2 = guidance_scale
|
| 500 |
+
|
| 501 |
+
self._guidance_scale = guidance_scale
|
| 502 |
+
self._guidance_scale_2 = guidance_scale_2
|
| 503 |
+
self._attention_kwargs = attention_kwargs
|
| 504 |
+
self._current_timestep = None
|
| 505 |
+
self._interrupt = False
|
| 506 |
+
|
| 507 |
+
device = self._execution_device
|
| 508 |
+
|
| 509 |
+
# 2. Define call parameters
|
| 510 |
+
if prompt is not None and isinstance(prompt, str):
|
| 511 |
+
batch_size = 1
|
| 512 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 513 |
+
batch_size = len(prompt)
|
| 514 |
+
else:
|
| 515 |
+
batch_size = prompt_embeds.shape[0]
|
| 516 |
+
|
| 517 |
+
# 3. Encode input prompt
|
| 518 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 519 |
+
prompt=prompt,
|
| 520 |
+
negative_prompt=negative_prompt,
|
| 521 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 522 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 523 |
+
prompt_embeds=prompt_embeds,
|
| 524 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 525 |
+
max_sequence_length=max_sequence_length,
|
| 526 |
+
device=device,
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
transformer_dtype = self.transformer.dtype if self.transformer is not None else self.transformer_2.dtype
|
| 530 |
+
prompt_embeds = prompt_embeds.to(transformer_dtype)
|
| 531 |
+
if negative_prompt_embeds is not None:
|
| 532 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
| 533 |
+
|
| 534 |
+
# 4. Prepare timesteps
|
| 535 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 536 |
+
timesteps = self.scheduler.timesteps
|
| 537 |
+
|
| 538 |
+
# 5. Prepare latent variables
|
| 539 |
+
num_channels_latents = (
|
| 540 |
+
self.transformer.config.in_channels
|
| 541 |
+
if self.transformer is not None
|
| 542 |
+
else self.transformer_2.config.in_channels
|
| 543 |
+
)
|
| 544 |
+
latents = self.prepare_latents(
|
| 545 |
+
batch_size * num_videos_per_prompt,
|
| 546 |
+
num_channels_latents,
|
| 547 |
+
height,
|
| 548 |
+
width,
|
| 549 |
+
num_frames,
|
| 550 |
+
torch.float32,
|
| 551 |
+
device,
|
| 552 |
+
generator,
|
| 553 |
+
latents,
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
mask = torch.ones(latents.shape, dtype=torch.float32, device=device)
|
| 557 |
+
|
| 558 |
+
# 6. Denoising loop
|
| 559 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 560 |
+
self._num_timesteps = len(timesteps)
|
| 561 |
+
|
| 562 |
+
if self.config.boundary_ratio is not None:
|
| 563 |
+
boundary_timestep = self.config.boundary_ratio * self.scheduler.config.num_train_timesteps
|
| 564 |
+
else:
|
| 565 |
+
boundary_timestep = None
|
| 566 |
+
|
| 567 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 568 |
+
for i, t in enumerate(timesteps):
|
| 569 |
+
if self.interrupt:
|
| 570 |
+
continue
|
| 571 |
+
|
| 572 |
+
self._current_timestep = t
|
| 573 |
+
|
| 574 |
+
if boundary_timestep is None or t >= boundary_timestep:
|
| 575 |
+
# wan2.1 or high-noise stage in wan2.2
|
| 576 |
+
current_model = self.transformer
|
| 577 |
+
current_guidance_scale = guidance_scale
|
| 578 |
+
else:
|
| 579 |
+
# low-noise stage in wan2.2
|
| 580 |
+
current_model = self.transformer_2
|
| 581 |
+
current_guidance_scale = guidance_scale_2
|
| 582 |
+
|
| 583 |
+
latent_model_input = latents.to(transformer_dtype)
|
| 584 |
+
if self.config.expand_timesteps:
|
| 585 |
+
# seq_len: num_latent_frames * latent_height//2 * latent_width//2
|
| 586 |
+
temp_ts = (mask[0][0][:, ::2, ::2] * t).flatten()
|
| 587 |
+
# batch_size, seq_len
|
| 588 |
+
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
| 589 |
+
else:
|
| 590 |
+
timestep = t.expand(latents.shape[0])
|
| 591 |
+
|
| 592 |
+
with current_model.cache_context("cond"):
|
| 593 |
+
noise_pred = current_model(
|
| 594 |
+
hidden_states=latent_model_input,
|
| 595 |
+
timestep=timestep,
|
| 596 |
+
encoder_hidden_states=prompt_embeds,
|
| 597 |
+
attention_kwargs=attention_kwargs,
|
| 598 |
+
return_dict=False,
|
| 599 |
+
)[0]
|
| 600 |
+
|
| 601 |
+
if self.do_classifier_free_guidance:
|
| 602 |
+
with current_model.cache_context("uncond"):
|
| 603 |
+
noise_uncond = current_model(
|
| 604 |
+
hidden_states=latent_model_input,
|
| 605 |
+
timestep=timestep,
|
| 606 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 607 |
+
attention_kwargs=attention_kwargs,
|
| 608 |
+
return_dict=False,
|
| 609 |
+
)[0]
|
| 610 |
+
noise_pred = noise_uncond + current_guidance_scale * (noise_pred - noise_uncond)
|
| 611 |
+
|
| 612 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 613 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 614 |
+
|
| 615 |
+
if callback_on_step_end is not None:
|
| 616 |
+
callback_kwargs = {}
|
| 617 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 618 |
+
callback_kwargs[k] = locals()[k]
|
| 619 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 620 |
+
|
| 621 |
+
latents = callback_outputs.pop("latents", latents)
|
| 622 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 623 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 624 |
+
|
| 625 |
+
# call the callback, if provided
|
| 626 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 627 |
+
progress_bar.update()
|
| 628 |
+
|
| 629 |
+
if XLA_AVAILABLE:
|
| 630 |
+
xm.mark_step()
|
| 631 |
+
|
| 632 |
+
self._current_timestep = None
|
| 633 |
+
|
| 634 |
+
if not output_type == "latent":
|
| 635 |
+
latents = latents.to(self.vae.dtype)
|
| 636 |
+
latents_mean = (
|
| 637 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 638 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 639 |
+
.to(latents.device, latents.dtype)
|
| 640 |
+
)
|
| 641 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 642 |
+
latents.device, latents.dtype
|
| 643 |
+
)
|
| 644 |
+
latents = latents / latents_std + latents_mean
|
| 645 |
+
video = self.vae.decode(latents, return_dict=False)[0]
|
| 646 |
+
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
| 647 |
+
else:
|
| 648 |
+
video = latents
|
| 649 |
+
|
| 650 |
+
# Offload all models
|
| 651 |
+
self.maybe_free_model_hooks()
|
| 652 |
+
|
| 653 |
+
if not return_dict:
|
| 654 |
+
return (video,)
|
| 655 |
+
|
| 656 |
+
return WanPipelineOutput(frames=video)
|
exp_code/1_benchmark/Wan2.2-diffusers/pipeline_wan_i2v.py
ADDED
|
@@ -0,0 +1,824 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import html
|
| 16 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import PIL
|
| 19 |
+
import regex as re
|
| 20 |
+
import torch
|
| 21 |
+
from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel, UMT5EncoderModel
|
| 22 |
+
|
| 23 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 24 |
+
from diffusers.image_processor import PipelineImageInput
|
| 25 |
+
from diffusers.loaders import WanLoraLoaderMixin
|
| 26 |
+
from diffusers.models import AutoencoderKLWan, WanTransformer3DModel
|
| 27 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
| 28 |
+
from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
|
| 29 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 30 |
+
from diffusers.video_processor import VideoProcessor
|
| 31 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 32 |
+
from diffusers.pipelines.wan.pipeline_output import WanPipelineOutput
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_torch_xla_available():
|
| 36 |
+
import torch_xla.core.xla_model as xm
|
| 37 |
+
|
| 38 |
+
XLA_AVAILABLE = True
|
| 39 |
+
else:
|
| 40 |
+
XLA_AVAILABLE = False
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 43 |
+
|
| 44 |
+
if is_ftfy_available():
|
| 45 |
+
import ftfy
|
| 46 |
+
|
| 47 |
+
EXAMPLE_DOC_STRING = """
|
| 48 |
+
Examples:
|
| 49 |
+
```python
|
| 50 |
+
>>> import torch
|
| 51 |
+
>>> import numpy as np
|
| 52 |
+
>>> from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
|
| 53 |
+
>>> from diffusers.utils import export_to_video, load_image
|
| 54 |
+
>>> from transformers import CLIPVisionModel
|
| 55 |
+
|
| 56 |
+
>>> # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
|
| 57 |
+
>>> model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
|
| 58 |
+
>>> image_encoder = CLIPVisionModel.from_pretrained(
|
| 59 |
+
... model_id, subfolder="image_encoder", torch_dtype=torch.float32
|
| 60 |
+
... )
|
| 61 |
+
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 62 |
+
>>> pipe = WanImageToVideoPipeline.from_pretrained(
|
| 63 |
+
... model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
|
| 64 |
+
... )
|
| 65 |
+
>>> pipe.to("cuda")
|
| 66 |
+
|
| 67 |
+
>>> image = load_image(
|
| 68 |
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
|
| 69 |
+
... )
|
| 70 |
+
>>> max_area = 480 * 832
|
| 71 |
+
>>> aspect_ratio = image.height / image.width
|
| 72 |
+
>>> mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
|
| 73 |
+
>>> height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
|
| 74 |
+
>>> width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
|
| 75 |
+
>>> image = image.resize((width, height))
|
| 76 |
+
>>> prompt = (
|
| 77 |
+
... "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
|
| 78 |
+
... "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
|
| 79 |
+
... )
|
| 80 |
+
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 81 |
+
|
| 82 |
+
>>> output = pipe(
|
| 83 |
+
... image=image,
|
| 84 |
+
... prompt=prompt,
|
| 85 |
+
... negative_prompt=negative_prompt,
|
| 86 |
+
... height=height,
|
| 87 |
+
... width=width,
|
| 88 |
+
... num_frames=81,
|
| 89 |
+
... guidance_scale=5.0,
|
| 90 |
+
... ).frames[0]
|
| 91 |
+
>>> export_to_video(output, "output.mp4", fps=16)
|
| 92 |
+
```
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def basic_clean(text):
|
| 97 |
+
text = ftfy.fix_text(text)
|
| 98 |
+
text = html.unescape(html.unescape(text))
|
| 99 |
+
return text.strip()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def whitespace_clean(text):
|
| 103 |
+
text = re.sub(r"\s+", " ", text)
|
| 104 |
+
text = text.strip()
|
| 105 |
+
return text
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def prompt_clean(text):
|
| 109 |
+
text = whitespace_clean(basic_clean(text))
|
| 110 |
+
return text
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
| 114 |
+
def retrieve_latents(
|
| 115 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
| 116 |
+
):
|
| 117 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
| 118 |
+
return encoder_output.latent_dist.sample(generator)
|
| 119 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
| 120 |
+
return encoder_output.latent_dist.mode()
|
| 121 |
+
elif hasattr(encoder_output, "latents"):
|
| 122 |
+
return encoder_output.latents
|
| 123 |
+
else:
|
| 124 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class WanImageToVideoPipeline(DiffusionPipeline, WanLoraLoaderMixin):
|
| 128 |
+
r"""
|
| 129 |
+
Pipeline for image-to-video generation using Wan.
|
| 130 |
+
|
| 131 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 132 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
tokenizer ([`T5Tokenizer`]):
|
| 136 |
+
Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
|
| 137 |
+
specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 138 |
+
text_encoder ([`T5EncoderModel`]):
|
| 139 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 140 |
+
the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 141 |
+
image_encoder ([`CLIPVisionModel`]):
|
| 142 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModel), specifically
|
| 143 |
+
the
|
| 144 |
+
[clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large)
|
| 145 |
+
variant.
|
| 146 |
+
transformer ([`WanTransformer3DModel`]):
|
| 147 |
+
Conditional Transformer to denoise the input latents.
|
| 148 |
+
scheduler ([`UniPCMultistepScheduler`]):
|
| 149 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 150 |
+
vae ([`AutoencoderKLWan`]):
|
| 151 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
| 152 |
+
transformer_2 ([`WanTransformer3DModel`], *optional*):
|
| 153 |
+
Conditional Transformer to denoise the input latents during the low-noise stage. In two-stage denoising,
|
| 154 |
+
`transformer` handles high-noise stages and `transformer_2` handles low-noise stages. If not provided, only
|
| 155 |
+
`transformer` is used.
|
| 156 |
+
boundary_ratio (`float`, *optional*, defaults to `None`):
|
| 157 |
+
Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising.
|
| 158 |
+
The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided,
|
| 159 |
+
`transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps <
|
| 160 |
+
boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
model_cpu_offload_seq = "text_encoder->image_encoder->transformer->transformer_2->vae"
|
| 164 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 165 |
+
_optional_components = ["transformer", "transformer_2", "image_encoder", "image_processor"]
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
tokenizer: AutoTokenizer,
|
| 170 |
+
text_encoder: UMT5EncoderModel,
|
| 171 |
+
vae: AutoencoderKLWan,
|
| 172 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
| 173 |
+
image_processor: CLIPImageProcessor = None,
|
| 174 |
+
image_encoder: CLIPVisionModel = None,
|
| 175 |
+
transformer: WanTransformer3DModel = None,
|
| 176 |
+
transformer_2: WanTransformer3DModel = None,
|
| 177 |
+
boundary_ratio: Optional[float] = None,
|
| 178 |
+
expand_timesteps: bool = False,
|
| 179 |
+
):
|
| 180 |
+
super().__init__()
|
| 181 |
+
|
| 182 |
+
self.register_modules(
|
| 183 |
+
vae=vae,
|
| 184 |
+
text_encoder=text_encoder,
|
| 185 |
+
tokenizer=tokenizer,
|
| 186 |
+
image_encoder=image_encoder,
|
| 187 |
+
transformer=transformer,
|
| 188 |
+
scheduler=scheduler,
|
| 189 |
+
image_processor=image_processor,
|
| 190 |
+
transformer_2=transformer_2,
|
| 191 |
+
)
|
| 192 |
+
self.register_to_config(boundary_ratio=boundary_ratio, expand_timesteps=expand_timesteps)
|
| 193 |
+
|
| 194 |
+
self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
|
| 195 |
+
self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
|
| 196 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
| 197 |
+
self.image_processor = image_processor
|
| 198 |
+
|
| 199 |
+
def _get_t5_prompt_embeds(
|
| 200 |
+
self,
|
| 201 |
+
prompt: Union[str, List[str]] = None,
|
| 202 |
+
num_videos_per_prompt: int = 1,
|
| 203 |
+
max_sequence_length: int = 512,
|
| 204 |
+
device: Optional[torch.device] = None,
|
| 205 |
+
dtype: Optional[torch.dtype] = None,
|
| 206 |
+
):
|
| 207 |
+
device = device or self._execution_device
|
| 208 |
+
dtype = dtype or self.text_encoder.dtype
|
| 209 |
+
|
| 210 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 211 |
+
prompt = [prompt_clean(u) for u in prompt]
|
| 212 |
+
batch_size = len(prompt)
|
| 213 |
+
|
| 214 |
+
text_inputs = self.tokenizer(
|
| 215 |
+
prompt,
|
| 216 |
+
padding="max_length",
|
| 217 |
+
max_length=max_sequence_length,
|
| 218 |
+
truncation=True,
|
| 219 |
+
add_special_tokens=True,
|
| 220 |
+
return_attention_mask=True,
|
| 221 |
+
return_tensors="pt",
|
| 222 |
+
)
|
| 223 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 224 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
| 225 |
+
|
| 226 |
+
prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
| 227 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 228 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 229 |
+
prompt_embeds = torch.stack(
|
| 230 |
+
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 234 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 235 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 236 |
+
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 237 |
+
|
| 238 |
+
return prompt_embeds
|
| 239 |
+
|
| 240 |
+
def encode_image(
|
| 241 |
+
self,
|
| 242 |
+
image: PipelineImageInput,
|
| 243 |
+
device: Optional[torch.device] = None,
|
| 244 |
+
):
|
| 245 |
+
device = device or self._execution_device
|
| 246 |
+
image = self.image_processor(images=image, return_tensors="pt").to(device)
|
| 247 |
+
image_embeds = self.image_encoder(**image, output_hidden_states=True)
|
| 248 |
+
return image_embeds.hidden_states[-2]
|
| 249 |
+
|
| 250 |
+
# Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
|
| 251 |
+
def encode_prompt(
|
| 252 |
+
self,
|
| 253 |
+
prompt: Union[str, List[str]],
|
| 254 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 255 |
+
do_classifier_free_guidance: bool = True,
|
| 256 |
+
num_videos_per_prompt: int = 1,
|
| 257 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 258 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 259 |
+
max_sequence_length: int = 226,
|
| 260 |
+
device: Optional[torch.device] = None,
|
| 261 |
+
dtype: Optional[torch.dtype] = None,
|
| 262 |
+
):
|
| 263 |
+
r"""
|
| 264 |
+
Encodes the prompt into text encoder hidden states.
|
| 265 |
+
|
| 266 |
+
Args:
|
| 267 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 268 |
+
prompt to be encoded
|
| 269 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 270 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 271 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 272 |
+
less than `1`).
|
| 273 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 274 |
+
Whether to use classifier free guidance or not.
|
| 275 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 276 |
+
Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
| 277 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 278 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 279 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 280 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 281 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 282 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 283 |
+
argument.
|
| 284 |
+
device: (`torch.device`, *optional*):
|
| 285 |
+
torch device
|
| 286 |
+
dtype: (`torch.dtype`, *optional*):
|
| 287 |
+
torch dtype
|
| 288 |
+
"""
|
| 289 |
+
device = device or self._execution_device
|
| 290 |
+
|
| 291 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 292 |
+
if prompt is not None:
|
| 293 |
+
batch_size = len(prompt)
|
| 294 |
+
else:
|
| 295 |
+
batch_size = prompt_embeds.shape[0]
|
| 296 |
+
|
| 297 |
+
if prompt_embeds is None:
|
| 298 |
+
prompt_embeds = self._get_t5_prompt_embeds(
|
| 299 |
+
prompt=prompt,
|
| 300 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 301 |
+
max_sequence_length=max_sequence_length,
|
| 302 |
+
device=device,
|
| 303 |
+
dtype=dtype,
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 307 |
+
negative_prompt = negative_prompt or ""
|
| 308 |
+
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
| 309 |
+
|
| 310 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 311 |
+
raise TypeError(
|
| 312 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 313 |
+
f" {type(prompt)}."
|
| 314 |
+
)
|
| 315 |
+
elif batch_size != len(negative_prompt):
|
| 316 |
+
raise ValueError(
|
| 317 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 318 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 319 |
+
" the batch size of `prompt`."
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
negative_prompt_embeds = self._get_t5_prompt_embeds(
|
| 323 |
+
prompt=negative_prompt,
|
| 324 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 325 |
+
max_sequence_length=max_sequence_length,
|
| 326 |
+
device=device,
|
| 327 |
+
dtype=dtype,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
return prompt_embeds, negative_prompt_embeds
|
| 331 |
+
|
| 332 |
+
def check_inputs(
|
| 333 |
+
self,
|
| 334 |
+
prompt,
|
| 335 |
+
negative_prompt,
|
| 336 |
+
image,
|
| 337 |
+
height,
|
| 338 |
+
width,
|
| 339 |
+
prompt_embeds=None,
|
| 340 |
+
negative_prompt_embeds=None,
|
| 341 |
+
image_embeds=None,
|
| 342 |
+
callback_on_step_end_tensor_inputs=None,
|
| 343 |
+
guidance_scale_2=None,
|
| 344 |
+
):
|
| 345 |
+
if image is not None and image_embeds is not None:
|
| 346 |
+
raise ValueError(
|
| 347 |
+
f"Cannot forward both `image`: {image} and `image_embeds`: {image_embeds}. Please make sure to"
|
| 348 |
+
" only forward one of the two."
|
| 349 |
+
)
|
| 350 |
+
if image is None and image_embeds is None:
|
| 351 |
+
raise ValueError(
|
| 352 |
+
"Provide either `image` or `prompt_embeds`. Cannot leave both `image` and `image_embeds` undefined."
|
| 353 |
+
)
|
| 354 |
+
if image is not None and not isinstance(image, torch.Tensor) and not isinstance(image, PIL.Image.Image):
|
| 355 |
+
raise ValueError(f"`image` has to be of type `torch.Tensor` or `PIL.Image.Image` but is {type(image)}")
|
| 356 |
+
if height % 16 != 0 or width % 16 != 0:
|
| 357 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
| 358 |
+
|
| 359 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 360 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 361 |
+
):
|
| 362 |
+
raise ValueError(
|
| 363 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
if prompt is not None and prompt_embeds is not None:
|
| 367 |
+
raise ValueError(
|
| 368 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 369 |
+
" only forward one of the two."
|
| 370 |
+
)
|
| 371 |
+
elif negative_prompt is not None and negative_prompt_embeds is not None:
|
| 372 |
+
raise ValueError(
|
| 373 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
| 374 |
+
" only forward one of the two."
|
| 375 |
+
)
|
| 376 |
+
elif prompt is None and prompt_embeds is None:
|
| 377 |
+
raise ValueError(
|
| 378 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 379 |
+
)
|
| 380 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 381 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 382 |
+
elif negative_prompt is not None and (
|
| 383 |
+
not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
|
| 384 |
+
):
|
| 385 |
+
raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
|
| 386 |
+
|
| 387 |
+
if self.config.boundary_ratio is None and guidance_scale_2 is not None:
|
| 388 |
+
raise ValueError("`guidance_scale_2` is only supported when the pipeline's `boundary_ratio` is not None.")
|
| 389 |
+
|
| 390 |
+
if self.config.boundary_ratio is not None and image_embeds is not None:
|
| 391 |
+
raise ValueError("Cannot forward `image_embeds` when the pipeline's `boundary_ratio` is not configured.")
|
| 392 |
+
|
| 393 |
+
def prepare_latents(
|
| 394 |
+
self,
|
| 395 |
+
image: PipelineImageInput,
|
| 396 |
+
batch_size: int,
|
| 397 |
+
num_channels_latents: int = 16,
|
| 398 |
+
height: int = 480,
|
| 399 |
+
width: int = 832,
|
| 400 |
+
num_frames: int = 81,
|
| 401 |
+
dtype: Optional[torch.dtype] = None,
|
| 402 |
+
device: Optional[torch.device] = None,
|
| 403 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 404 |
+
latents: Optional[torch.Tensor] = None,
|
| 405 |
+
last_image: Optional[torch.Tensor] = None,
|
| 406 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 407 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 408 |
+
latent_height = height // self.vae_scale_factor_spatial
|
| 409 |
+
latent_width = width // self.vae_scale_factor_spatial
|
| 410 |
+
|
| 411 |
+
shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
|
| 412 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 413 |
+
raise ValueError(
|
| 414 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 415 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
if latents is None:
|
| 419 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 420 |
+
else:
|
| 421 |
+
latents = latents.to(device=device, dtype=dtype)
|
| 422 |
+
|
| 423 |
+
image = image.unsqueeze(2) # [batch_size, channels, 1, height, width]
|
| 424 |
+
|
| 425 |
+
if self.config.expand_timesteps:
|
| 426 |
+
video_condition = image
|
| 427 |
+
|
| 428 |
+
elif last_image is None:
|
| 429 |
+
video_condition = torch.cat(
|
| 430 |
+
[image, image.new_zeros(image.shape[0], image.shape[1], num_frames - 1, height, width)], dim=2
|
| 431 |
+
)
|
| 432 |
+
else:
|
| 433 |
+
last_image = last_image.unsqueeze(2)
|
| 434 |
+
video_condition = torch.cat(
|
| 435 |
+
[image, image.new_zeros(image.shape[0], image.shape[1], num_frames - 2, height, width), last_image],
|
| 436 |
+
dim=2,
|
| 437 |
+
)
|
| 438 |
+
video_condition = video_condition.to(device=device, dtype=self.vae.dtype)
|
| 439 |
+
|
| 440 |
+
latents_mean = (
|
| 441 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 442 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 443 |
+
.to(latents.device, latents.dtype)
|
| 444 |
+
)
|
| 445 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 446 |
+
latents.device, latents.dtype
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
if isinstance(generator, list):
|
| 450 |
+
latent_condition = [
|
| 451 |
+
retrieve_latents(self.vae.encode(video_condition), sample_mode="argmax") for _ in generator
|
| 452 |
+
]
|
| 453 |
+
latent_condition = torch.cat(latent_condition)
|
| 454 |
+
else:
|
| 455 |
+
latent_condition = retrieve_latents(self.vae.encode(video_condition), sample_mode="argmax")
|
| 456 |
+
latent_condition = latent_condition.repeat(batch_size, 1, 1, 1, 1)
|
| 457 |
+
|
| 458 |
+
latent_condition = latent_condition.to(dtype)
|
| 459 |
+
latent_condition = (latent_condition - latents_mean) * latents_std
|
| 460 |
+
|
| 461 |
+
if self.config.expand_timesteps:
|
| 462 |
+
first_frame_mask = torch.ones(
|
| 463 |
+
1, 1, num_latent_frames, latent_height, latent_width, dtype=dtype, device=device
|
| 464 |
+
)
|
| 465 |
+
first_frame_mask[:, :, 0] = 0
|
| 466 |
+
return latents, latent_condition, first_frame_mask
|
| 467 |
+
|
| 468 |
+
mask_lat_size = torch.ones(batch_size, 1, num_frames, latent_height, latent_width)
|
| 469 |
+
|
| 470 |
+
if last_image is None:
|
| 471 |
+
mask_lat_size[:, :, list(range(1, num_frames))] = 0
|
| 472 |
+
else:
|
| 473 |
+
mask_lat_size[:, :, list(range(1, num_frames - 1))] = 0
|
| 474 |
+
first_frame_mask = mask_lat_size[:, :, 0:1]
|
| 475 |
+
first_frame_mask = torch.repeat_interleave(first_frame_mask, dim=2, repeats=self.vae_scale_factor_temporal)
|
| 476 |
+
mask_lat_size = torch.concat([first_frame_mask, mask_lat_size[:, :, 1:, :]], dim=2)
|
| 477 |
+
mask_lat_size = mask_lat_size.view(batch_size, -1, self.vae_scale_factor_temporal, latent_height, latent_width)
|
| 478 |
+
mask_lat_size = mask_lat_size.transpose(1, 2)
|
| 479 |
+
mask_lat_size = mask_lat_size.to(latent_condition.device)
|
| 480 |
+
|
| 481 |
+
return latents, torch.concat([mask_lat_size, latent_condition], dim=1)
|
| 482 |
+
|
| 483 |
+
@property
|
| 484 |
+
def guidance_scale(self):
|
| 485 |
+
return self._guidance_scale
|
| 486 |
+
|
| 487 |
+
@property
|
| 488 |
+
def do_classifier_free_guidance(self):
|
| 489 |
+
return self._guidance_scale > 1
|
| 490 |
+
|
| 491 |
+
@property
|
| 492 |
+
def num_timesteps(self):
|
| 493 |
+
return self._num_timesteps
|
| 494 |
+
|
| 495 |
+
@property
|
| 496 |
+
def current_timestep(self):
|
| 497 |
+
return self._current_timestep
|
| 498 |
+
|
| 499 |
+
@property
|
| 500 |
+
def interrupt(self):
|
| 501 |
+
return self._interrupt
|
| 502 |
+
|
| 503 |
+
@property
|
| 504 |
+
def attention_kwargs(self):
|
| 505 |
+
return self._attention_kwargs
|
| 506 |
+
|
| 507 |
+
@torch.no_grad()
|
| 508 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 509 |
+
def __call__(
|
| 510 |
+
self,
|
| 511 |
+
image: PipelineImageInput,
|
| 512 |
+
prompt: Union[str, List[str]] = None,
|
| 513 |
+
negative_prompt: Union[str, List[str]] = None,
|
| 514 |
+
height: int = 480,
|
| 515 |
+
width: int = 832,
|
| 516 |
+
num_frames: int = 81,
|
| 517 |
+
num_inference_steps: int = 50,
|
| 518 |
+
guidance_scale: float = 5.0,
|
| 519 |
+
guidance_scale_2: Optional[float] = None,
|
| 520 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 521 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 522 |
+
latents: Optional[torch.Tensor] = None,
|
| 523 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 524 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 525 |
+
image_embeds: Optional[torch.Tensor] = None,
|
| 526 |
+
last_image: Optional[torch.Tensor] = None,
|
| 527 |
+
output_type: Optional[str] = "np",
|
| 528 |
+
return_dict: bool = True,
|
| 529 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 530 |
+
callback_on_step_end: Optional[
|
| 531 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
| 532 |
+
] = None,
|
| 533 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 534 |
+
max_sequence_length: int = 512,
|
| 535 |
+
):
|
| 536 |
+
r"""
|
| 537 |
+
The call function to the pipeline for generation.
|
| 538 |
+
|
| 539 |
+
Args:
|
| 540 |
+
image (`PipelineImageInput`):
|
| 541 |
+
The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
|
| 542 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 543 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 544 |
+
instead.
|
| 545 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 546 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 547 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 548 |
+
less than `1`).
|
| 549 |
+
height (`int`, defaults to `480`):
|
| 550 |
+
The height of the generated video.
|
| 551 |
+
width (`int`, defaults to `832`):
|
| 552 |
+
The width of the generated video.
|
| 553 |
+
num_frames (`int`, defaults to `81`):
|
| 554 |
+
The number of frames in the generated video.
|
| 555 |
+
num_inference_steps (`int`, defaults to `50`):
|
| 556 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 557 |
+
expense of slower inference.
|
| 558 |
+
guidance_scale (`float`, defaults to `5.0`):
|
| 559 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
| 560 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
| 561 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
| 562 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
| 563 |
+
the text `prompt`, usually at the expense of lower image quality.
|
| 564 |
+
guidance_scale_2 (`float`, *optional*, defaults to `None`):
|
| 565 |
+
Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline's
|
| 566 |
+
`boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2`
|
| 567 |
+
and the pipeline's `boundary_ratio` are not None.
|
| 568 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 569 |
+
The number of images to generate per prompt.
|
| 570 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 571 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 572 |
+
generation deterministic.
|
| 573 |
+
latents (`torch.Tensor`, *optional*):
|
| 574 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 575 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 576 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 577 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 578 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 579 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 580 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 581 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 582 |
+
provided, text embeddings are generated from the `negative_prompt` input argument.
|
| 583 |
+
image_embeds (`torch.Tensor`, *optional*):
|
| 584 |
+
Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
|
| 585 |
+
image embeddings are generated from the `image` input argument.
|
| 586 |
+
output_type (`str`, *optional*, defaults to `"np"`):
|
| 587 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 588 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 589 |
+
Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
|
| 590 |
+
attention_kwargs (`dict`, *optional*):
|
| 591 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 592 |
+
`self.processor` in
|
| 593 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 594 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 595 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 596 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 597 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 598 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 599 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 600 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 601 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 602 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 603 |
+
max_sequence_length (`int`, defaults to `512`):
|
| 604 |
+
The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
|
| 605 |
+
truncated. If the prompt is shorter, it will be padded to this length.
|
| 606 |
+
|
| 607 |
+
Examples:
|
| 608 |
+
|
| 609 |
+
Returns:
|
| 610 |
+
[`~WanPipelineOutput`] or `tuple`:
|
| 611 |
+
If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
|
| 612 |
+
the first element is a list with the generated images and the second element is a list of `bool`s
|
| 613 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
| 614 |
+
"""
|
| 615 |
+
|
| 616 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 617 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 618 |
+
|
| 619 |
+
# 1. Check inputs. Raise error if not correct
|
| 620 |
+
self.check_inputs(
|
| 621 |
+
prompt,
|
| 622 |
+
negative_prompt,
|
| 623 |
+
image,
|
| 624 |
+
height,
|
| 625 |
+
width,
|
| 626 |
+
prompt_embeds,
|
| 627 |
+
negative_prompt_embeds,
|
| 628 |
+
image_embeds,
|
| 629 |
+
callback_on_step_end_tensor_inputs,
|
| 630 |
+
guidance_scale_2,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
if num_frames % self.vae_scale_factor_temporal != 1:
|
| 634 |
+
logger.warning(
|
| 635 |
+
f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
|
| 636 |
+
)
|
| 637 |
+
num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
|
| 638 |
+
num_frames = max(num_frames, 1)
|
| 639 |
+
|
| 640 |
+
if self.config.boundary_ratio is not None and guidance_scale_2 is None:
|
| 641 |
+
guidance_scale_2 = guidance_scale
|
| 642 |
+
|
| 643 |
+
self._guidance_scale = guidance_scale
|
| 644 |
+
self._guidance_scale_2 = guidance_scale_2
|
| 645 |
+
self._attention_kwargs = attention_kwargs
|
| 646 |
+
self._current_timestep = None
|
| 647 |
+
self._interrupt = False
|
| 648 |
+
|
| 649 |
+
device = self._execution_device
|
| 650 |
+
|
| 651 |
+
# 2. Define call parameters
|
| 652 |
+
if prompt is not None and isinstance(prompt, str):
|
| 653 |
+
batch_size = 1
|
| 654 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 655 |
+
batch_size = len(prompt)
|
| 656 |
+
else:
|
| 657 |
+
batch_size = prompt_embeds.shape[0]
|
| 658 |
+
|
| 659 |
+
# 3. Encode input prompt
|
| 660 |
+
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 661 |
+
prompt=prompt,
|
| 662 |
+
negative_prompt=negative_prompt,
|
| 663 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 664 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 665 |
+
prompt_embeds=prompt_embeds,
|
| 666 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 667 |
+
max_sequence_length=max_sequence_length,
|
| 668 |
+
device=device,
|
| 669 |
+
)
|
| 670 |
+
|
| 671 |
+
# Encode image embedding
|
| 672 |
+
transformer_dtype = self.transformer.dtype if self.transformer is not None else self.transformer_2.dtype
|
| 673 |
+
prompt_embeds = prompt_embeds.to(transformer_dtype)
|
| 674 |
+
if negative_prompt_embeds is not None:
|
| 675 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
| 676 |
+
|
| 677 |
+
# only wan 2.1 i2v transformer accepts image_embeds
|
| 678 |
+
if self.transformer is not None and self.transformer.config.image_dim is not None:
|
| 679 |
+
if image_embeds is None:
|
| 680 |
+
if last_image is None:
|
| 681 |
+
image_embeds = self.encode_image(image, device)
|
| 682 |
+
else:
|
| 683 |
+
image_embeds = self.encode_image([image, last_image], device)
|
| 684 |
+
image_embeds = image_embeds.repeat(batch_size, 1, 1)
|
| 685 |
+
image_embeds = image_embeds.to(transformer_dtype)
|
| 686 |
+
|
| 687 |
+
# 4. Prepare timesteps
|
| 688 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 689 |
+
timesteps = self.scheduler.timesteps
|
| 690 |
+
|
| 691 |
+
# 5. Prepare latent variables
|
| 692 |
+
num_channels_latents = self.vae.config.z_dim
|
| 693 |
+
image = self.video_processor.preprocess(image, height=height, width=width).to(device, dtype=torch.float32)
|
| 694 |
+
if last_image is not None:
|
| 695 |
+
last_image = self.video_processor.preprocess(last_image, height=height, width=width).to(
|
| 696 |
+
device, dtype=torch.float32
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
latents_outputs = self.prepare_latents(
|
| 700 |
+
image,
|
| 701 |
+
batch_size * num_videos_per_prompt,
|
| 702 |
+
num_channels_latents,
|
| 703 |
+
height,
|
| 704 |
+
width,
|
| 705 |
+
num_frames,
|
| 706 |
+
torch.float32,
|
| 707 |
+
device,
|
| 708 |
+
generator,
|
| 709 |
+
latents,
|
| 710 |
+
last_image,
|
| 711 |
+
)
|
| 712 |
+
if self.config.expand_timesteps:
|
| 713 |
+
# wan 2.2 5b i2v use firt_frame_mask to mask timesteps
|
| 714 |
+
latents, condition, first_frame_mask = latents_outputs
|
| 715 |
+
else:
|
| 716 |
+
latents, condition = latents_outputs
|
| 717 |
+
|
| 718 |
+
# 6. Denoising loop
|
| 719 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 720 |
+
self._num_timesteps = len(timesteps)
|
| 721 |
+
|
| 722 |
+
if self.config.boundary_ratio is not None:
|
| 723 |
+
boundary_timestep = self.config.boundary_ratio * self.scheduler.config.num_train_timesteps
|
| 724 |
+
else:
|
| 725 |
+
boundary_timestep = None
|
| 726 |
+
|
| 727 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 728 |
+
for i, t in enumerate(timesteps):
|
| 729 |
+
if self.interrupt:
|
| 730 |
+
continue
|
| 731 |
+
|
| 732 |
+
self._current_timestep = t
|
| 733 |
+
|
| 734 |
+
if boundary_timestep is None or t >= boundary_timestep:
|
| 735 |
+
# wan2.1 or high-noise stage in wan2.2
|
| 736 |
+
current_model = self.transformer
|
| 737 |
+
current_guidance_scale = guidance_scale
|
| 738 |
+
else:
|
| 739 |
+
# low-noise stage in wan2.2
|
| 740 |
+
current_model = self.transformer_2
|
| 741 |
+
current_guidance_scale = guidance_scale_2
|
| 742 |
+
|
| 743 |
+
if self.config.expand_timesteps:
|
| 744 |
+
latent_model_input = (1 - first_frame_mask) * condition + first_frame_mask * latents
|
| 745 |
+
latent_model_input = latent_model_input.to(transformer_dtype)
|
| 746 |
+
|
| 747 |
+
# seq_len: num_latent_frames * (latent_height // patch_size) * (latent_width // patch_size)
|
| 748 |
+
temp_ts = (first_frame_mask[0][0][:, ::2, ::2] * t).flatten()
|
| 749 |
+
# batch_size, seq_len
|
| 750 |
+
timestep = temp_ts.unsqueeze(0).expand(latents.shape[0], -1)
|
| 751 |
+
else:
|
| 752 |
+
latent_model_input = torch.cat([latents, condition], dim=1).to(transformer_dtype)
|
| 753 |
+
timestep = t.expand(latents.shape[0])
|
| 754 |
+
|
| 755 |
+
with current_model.cache_context("cond"):
|
| 756 |
+
noise_pred = current_model(
|
| 757 |
+
hidden_states=latent_model_input,
|
| 758 |
+
timestep=timestep,
|
| 759 |
+
encoder_hidden_states=prompt_embeds,
|
| 760 |
+
encoder_hidden_states_image=image_embeds,
|
| 761 |
+
attention_kwargs=attention_kwargs,
|
| 762 |
+
return_dict=False,
|
| 763 |
+
)[0]
|
| 764 |
+
|
| 765 |
+
if self.do_classifier_free_guidance:
|
| 766 |
+
with current_model.cache_context("uncond"):
|
| 767 |
+
noise_uncond = current_model(
|
| 768 |
+
hidden_states=latent_model_input,
|
| 769 |
+
timestep=timestep,
|
| 770 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 771 |
+
encoder_hidden_states_image=image_embeds,
|
| 772 |
+
attention_kwargs=attention_kwargs,
|
| 773 |
+
return_dict=False,
|
| 774 |
+
)[0]
|
| 775 |
+
noise_pred = noise_uncond + current_guidance_scale * (noise_pred - noise_uncond)
|
| 776 |
+
|
| 777 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 778 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 779 |
+
|
| 780 |
+
if callback_on_step_end is not None:
|
| 781 |
+
callback_kwargs = {}
|
| 782 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 783 |
+
callback_kwargs[k] = locals()[k]
|
| 784 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 785 |
+
|
| 786 |
+
latents = callback_outputs.pop("latents", latents)
|
| 787 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 788 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 789 |
+
|
| 790 |
+
# call the callback, if provided
|
| 791 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 792 |
+
progress_bar.update()
|
| 793 |
+
|
| 794 |
+
if XLA_AVAILABLE:
|
| 795 |
+
xm.mark_step()
|
| 796 |
+
|
| 797 |
+
self._current_timestep = None
|
| 798 |
+
|
| 799 |
+
if self.config.expand_timesteps:
|
| 800 |
+
latents = (1 - first_frame_mask) * condition + first_frame_mask * latents
|
| 801 |
+
|
| 802 |
+
if not output_type == "latent":
|
| 803 |
+
latents = latents.to(self.vae.dtype)
|
| 804 |
+
latents_mean = (
|
| 805 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 806 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 807 |
+
.to(latents.device, latents.dtype)
|
| 808 |
+
)
|
| 809 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 810 |
+
latents.device, latents.dtype
|
| 811 |
+
)
|
| 812 |
+
latents = latents / latents_std + latents_mean
|
| 813 |
+
video = self.vae.decode(latents, return_dict=False)[0]
|
| 814 |
+
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
| 815 |
+
else:
|
| 816 |
+
video = latents
|
| 817 |
+
|
| 818 |
+
# Offload all models
|
| 819 |
+
self.maybe_free_model_hooks()
|
| 820 |
+
|
| 821 |
+
if not return_dict:
|
| 822 |
+
return (video,)
|
| 823 |
+
|
| 824 |
+
return WanPipelineOutput(frames=video)
|
exp_code/1_benchmark/Wan2.2/.gitignore
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
.DS_Store
|
| 3 |
+
.vscode*
|
| 4 |
+
tmp_examples*
|
| 5 |
+
new_checkpoint*
|
| 6 |
+
batch_test*
|
| 7 |
+
nohup*
|
exp_code/1_benchmark/Wan2.2/INSTALL.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Installation Guide
|
| 2 |
+
|
| 3 |
+
## Install with pip
|
| 4 |
+
|
| 5 |
+
```bash
|
| 6 |
+
pip install .
|
| 7 |
+
pip install .[dev] # Installe aussi les outils de dev
|
| 8 |
+
```
|
| 9 |
+
|
| 10 |
+
## Install with Poetry
|
| 11 |
+
|
| 12 |
+
Ensure you have [Poetry](https://python-poetry.org/docs/#installation) installed on your system.
|
| 13 |
+
|
| 14 |
+
To install all dependencies:
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
poetry install
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
### Handling `flash-attn` Installation Issues
|
| 21 |
+
|
| 22 |
+
If `flash-attn` fails due to **PEP 517 build issues**, you can try one of the following fixes.
|
| 23 |
+
|
| 24 |
+
#### No-Build-Isolation Installation (Recommended)
|
| 25 |
+
```bash
|
| 26 |
+
poetry run pip install --upgrade pip setuptools wheel
|
| 27 |
+
poetry run pip install flash-attn --no-build-isolation
|
| 28 |
+
poetry install
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
#### Install from Git (Alternative)
|
| 32 |
+
```bash
|
| 33 |
+
poetry run pip install git+https://github.com/Dao-AILab/flash-attention.git
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
---
|
| 37 |
+
|
| 38 |
+
### Running the Model
|
| 39 |
+
|
| 40 |
+
Once the installation is complete, you can run **Wan2.2** using:
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
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."
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
#### Test
|
| 47 |
+
```bash
|
| 48 |
+
bash tests/test.sh
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
#### Format
|
| 52 |
+
```bash
|
| 53 |
+
black .
|
| 54 |
+
isort .
|
| 55 |
+
```
|
exp_code/1_benchmark/Wan2.2/LICENSE.txt
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
exp_code/1_benchmark/Wan2.2/Makefile
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.PHONY: format
|
| 2 |
+
|
| 3 |
+
format:
|
| 4 |
+
isort generate.py wan
|
| 5 |
+
yapf -i -r *.py generate.py wan
|
exp_code/1_benchmark/Wan2.2/README.md
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Wan2.2
|
| 2 |
+
|
| 3 |
+
<p align="center">
|
| 4 |
+
<img src="assets/logo.png" width="400"/>
|
| 5 |
+
<p>
|
| 6 |
+
|
| 7 |
+
<p align="center">
|
| 8 |
+
💜 <a href="https://wan.video"><b>Wan</b></a>    |    🖥️ <a href="https://github.com/Wan-Video/Wan2.2">GitHub</a>    |   🤗 <a href="https://huggingface.co/Wan-AI/">Hugging Face</a>   |   🤖 <a href="https://modelscope.cn/organization/Wan-AI">ModelScope</a>   |    📑 <a href="https://arxiv.org/abs/2503.20314">Paper</a>    |    📑 <a href="https://wan.video/welcome?spm=a2ty_o02.30011076.0.0.6c9ee41eCcluqg">Blog</a>    |    💬 <a href="https://discord.gg/AKNgpMK4Yj">Discord</a>  
|
| 9 |
+
<br>
|
| 10 |
+
📕 <a href="https://alidocs.dingtalk.com/i/nodes/jb9Y4gmKWrx9eo4dCql9LlbYJGXn6lpz">使用指南(中文)</a>   |    📘 <a href="https://alidocs.dingtalk.com/i/nodes/EpGBa2Lm8aZxe5myC99MelA2WgN7R35y">User Guide(English)</a>   |   💬 <a href="https://gw.alicdn.com/imgextra/i2/O1CN01tqjWFi1ByuyehkTSB_!!6000000000015-0-tps-611-1279.jpg">WeChat(微信)</a>  
|
| 11 |
+
<br>
|
| 12 |
+
|
| 13 |
+
-----
|
| 14 |
+
|
| 15 |
+
[**Wan: Open and Advanced Large-Scale Video Generative Models**](https://arxiv.org/abs/2503.20314) <be>
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
We are excited to introduce **Wan2.2**, a major upgrade to our foundational video models. With **Wan2.2**, we have focused on incorporating the following innovations:
|
| 19 |
+
|
| 20 |
+
- 👍 **Effective MoE Architecture**: Wan2.2 introduces a Mixture-of-Experts (MoE) architecture into video diffusion models. By separating the denoising process cross timesteps with specialized powerful expert models, this enlarges the overall model capacity while maintaining the same computational cost.
|
| 21 |
+
|
| 22 |
+
- 👍 **Cinematic-level Aesthetics**: Wan2.2 incorporates meticulously curated aesthetic data, complete with detailed labels for lighting, composition, contrast, color tone, and more. This allows for more precise and controllable cinematic style generation, facilitating the creation of videos with customizable aesthetic preferences.
|
| 23 |
+
|
| 24 |
+
- 👍 **Complex Motion Generation**: Compared to Wan2.1, Wan2.2 is trained on a significantly larger data, with +65.6% more images and +83.2% more videos. This expansion notably enhances the model's generalization across multiple dimensions such as motions, semantics, and aesthetics, achieving TOP performance among all open-sourced and closed-sourced models.
|
| 25 |
+
|
| 26 |
+
- 👍 **Efficient High-Definition Hybrid TI2V**: Wan2.2 open-sources a 5B model built with our advanced Wan2.2-VAE that achieves a compression ratio of **16×16×4**. This model supports both text-to-video and image-to-video generation at 720P resolution with 24fps and can also run on consumer-grade graphics cards like 4090. It is one of the fastest **720P@24fps** models currently available, capable of serving both the industrial and academic sectors simultaneously.
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
## Video Demos
|
| 30 |
+
|
| 31 |
+
<div align="center">
|
| 32 |
+
<video src="https://github.com/user-attachments/assets/b63bfa58-d5d7-4de6-a1a2-98970b06d9a7" width="70%" poster=""> </video>
|
| 33 |
+
</div>
|
| 34 |
+
|
| 35 |
+
## 🔥 Latest News!!
|
| 36 |
+
|
| 37 |
+
* Aug 26, 2025: 🎵 We introduce **[Wan2.2-S2V-14B](https://humanaigc.github.io/wan-s2v-webpage)**, an audio-driven cinematic video generation model, including [inference code](#run-speech-to-video-generation), [model weights](#model-download), and [technical report](https://humanaigc.github.io/wan-s2v-webpage/content/wan-s2v.pdf)! Now you can try it on [wan.video](https://wan.video/), [ModelScope Gradio](https://www.modelscope.cn/studios/Wan-AI/Wan2.2-S2V) or [HuggingFace Gradio](https://huggingface.co/spaces/Wan-AI/Wan2.2-S2V)!
|
| 38 |
+
* Jul 28, 2025: 👋 We have open a [HF space](https://huggingface.co/spaces/Wan-AI/Wan-2.2-5B) using the TI2V-5B model. Enjoy!
|
| 39 |
+
* Jul 28, 2025: 👋 Wan2.2 has been integrated into ComfyUI ([CN](https://docs.comfy.org/zh-CN/tutorials/video/wan/wan2_2) | [EN](https://docs.comfy.org/tutorials/video/wan/wan2_2)). Enjoy!
|
| 40 |
+
* Jul 28, 2025: 👋 Wan2.2's T2V, I2V and TI2V have been integrated into Diffusers ([T2V-A14B](https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B-Diffusers) | [I2V-A14B](https://huggingface.co/Wan-AI/Wan2.2-I2V-A14B-Diffusers) | [TI2V-5B](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B-Diffusers)). Feel free to give it a try!
|
| 41 |
+
* Jul 28, 2025: 👋 We've released the inference code and model weights of **Wan2.2**.
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
## Community Works
|
| 45 |
+
If your research or project builds upon [**Wan2.1**](https://github.com/Wan-Video/Wan2.1) or [**Wan2.2**](https://github.com/Wan-Video/Wan2.2), and you would like more people to see it, please inform us.
|
| 46 |
+
|
| 47 |
+
- [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio) provides comprehensive support for Wan 2.2, including low-GPU-memory layer-by-layer offload, FP8 quantization, sequence parallelism, LoRA training, full training.
|
| 48 |
+
- [Kijai's ComfyUI WanVideoWrapper](https://github.com/kijai/ComfyUI-WanVideoWrapper) is an alternative implementation of Wan models for ComfyUI. Thanks to its Wan-only focus, it's on the frontline of getting cutting edge optimizations and hot research features, which are often hard to integrate into ComfyUI quickly due to its more rigid structure.
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
## 📑 Todo List
|
| 52 |
+
- Wan2.2 Text-to-Video
|
| 53 |
+
- [x] Multi-GPU Inference code of the A14B and 14B models
|
| 54 |
+
- [x] Checkpoints of the A14B and 14B models
|
| 55 |
+
- [x] ComfyUI integration
|
| 56 |
+
- [x] Diffusers integration
|
| 57 |
+
- Wan2.2 Image-to-Video
|
| 58 |
+
- [x] Multi-GPU Inference code of the A14B model
|
| 59 |
+
- [x] Checkpoints of the A14B model
|
| 60 |
+
- [x] ComfyUI integration
|
| 61 |
+
- [x] Diffusers integration
|
| 62 |
+
- Wan2.2 Text-Image-to-Video
|
| 63 |
+
- [x] Multi-GPU Inference code of the 5B model
|
| 64 |
+
- [x] Checkpoints of the 5B model
|
| 65 |
+
- [x] ComfyUI integration
|
| 66 |
+
- [x] Diffusers integration
|
| 67 |
+
- Wan2.2-S2V Speech-to-Video
|
| 68 |
+
- [x] Inference code of Wan2.2-S2V
|
| 69 |
+
- [x] Checkpoints of Wan2.2-S2V-14B
|
| 70 |
+
- [ ] ComfyUI integration
|
| 71 |
+
- [ ] Diffusers integration
|
| 72 |
+
|
| 73 |
+
## Run Wan2.2
|
| 74 |
+
|
| 75 |
+
#### Installation
|
| 76 |
+
Clone the repo:
|
| 77 |
+
```sh
|
| 78 |
+
git clone https://github.com/Wan-Video/Wan2.2.git
|
| 79 |
+
cd Wan2.2
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Install dependencies:
|
| 83 |
+
```sh
|
| 84 |
+
# Ensure torch >= 2.4.0
|
| 85 |
+
# If the installation of `flash_attn` fails, try installing the other packages first and install `flash_attn` last
|
| 86 |
+
pip install -r requirements.txt
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
#### Model Download
|
| 91 |
+
|
| 92 |
+
| Models | Download Links | Description |
|
| 93 |
+
|--------------------|---------------------------------------------------------------------------------------------------------------------------------------------|-------------|
|
| 94 |
+
| T2V-A14B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B) 🤖 [ModelScope](https://modelscope.cn/models/Wan-AI/Wan2.2-T2V-A14B) | Text-to-Video MoE model, supports 480P & 720P |
|
| 95 |
+
| I2V-A14B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.2-I2V-A14B) 🤖 [ModelScope](https://modelscope.cn/models/Wan-AI/Wan2.2-I2V-A14B) | Image-to-Video MoE model, supports 480P & 720P |
|
| 96 |
+
| TI2V-5B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.2-TI2V-5B) 🤖 [ModelScope](https://modelscope.cn/models/Wan-AI/Wan2.2-TI2V-5B) | High-compression VAE, T2V+I2V, supports 720P |
|
| 97 |
+
| S2V-14B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.2-S2V-14B) 🤖 [ModelScope](https://modelscope.cn/models/Wan-AI/Wan2.2-S2V-14B) | Speech-to-Video model, supports 480P & 720P |
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
> 💡Note:
|
| 102 |
+
> The TI2V-5B model supports 720P video generation at **24 FPS**.
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
Download models using huggingface-cli:
|
| 106 |
+
``` sh
|
| 107 |
+
pip install "huggingface_hub[cli]"
|
| 108 |
+
huggingface-cli download Wan-AI/Wan2.2-T2V-A14B --local-dir ./Wan2.2-T2V-A14B
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
Download models using modelscope-cli:
|
| 112 |
+
``` sh
|
| 113 |
+
pip install modelscope
|
| 114 |
+
modelscope download Wan-AI/Wan2.2-T2V-A14B --local_dir ./Wan2.2-T2V-A14B
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
#### Run Text-to-Video Generation
|
| 118 |
+
|
| 119 |
+
This repository supports the `Wan2.2-T2V-A14B` Text-to-Video model and can simultaneously support video generation at 480P and 720P resolutions.
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
##### (1) Without Prompt Extension
|
| 123 |
+
|
| 124 |
+
To facilitate implementation, we will start with a basic version of the inference process that skips the [prompt extension](#2-using-prompt-extention) step.
|
| 125 |
+
|
| 126 |
+
- Single-GPU inference
|
| 127 |
+
|
| 128 |
+
``` sh
|
| 129 |
+
python generate.py --task t2v-A14B --size 1280*720 --ckpt_dir ./Wan2.2-T2V-A14B --offload_model True --convert_model_dtype --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
> 💡 This command can run on a GPU with at least 80GB VRAM.
|
| 133 |
+
|
| 134 |
+
> 💡If you encounter OOM (Out-of-Memory) issues, you can use the `--offload_model True`, `--convert_model_dtype` and `--t5_cpu` options to reduce GPU memory usage.
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
- Multi-GPU inference using FSDP + DeepSpeed Ulysses
|
| 138 |
+
|
| 139 |
+
We use [PyTorch FSDP](https://docs.pytorch.org/docs/stable/fsdp.html) and [DeepSpeed Ulysses](https://arxiv.org/abs/2309.14509) to accelerate inference.
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
``` sh
|
| 143 |
+
torchrun --nproc_per_node=8 generate.py --task t2v-A14B --size 1280*720 --ckpt_dir ./Wan2.2-T2V-A14B --dit_fsdp --t5_fsdp --ulysses_size 8 --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
##### (2) Using Prompt Extension
|
| 148 |
+
|
| 149 |
+
Extending the prompts can effectively enrich the details in the generated videos, further enhancing the video quality. Therefore, we recommend enabling prompt extension. We provide the following two methods for prompt extension:
|
| 150 |
+
|
| 151 |
+
- Use the Dashscope API for extension.
|
| 152 |
+
- Apply for a `dashscope.api_key` in advance ([EN](https://www.alibabacloud.com/help/en/model-studio/getting-started/first-api-call-to-qwen) | [CN](https://help.aliyun.com/zh/model-studio/getting-started/first-api-call-to-qwen)).
|
| 153 |
+
- Configure the environment variable `DASH_API_KEY` to specify the Dashscope API key. For users of Alibaba Cloud's international site, you also need to set the environment variable `DASH_API_URL` to 'https://dashscope-intl.aliyuncs.com/api/v1'. For more detailed instructions, please refer to the [dashscope document](https://www.alibabacloud.com/help/en/model-studio/developer-reference/use-qwen-by-calling-api?spm=a2c63.p38356.0.i1).
|
| 154 |
+
- Use the `qwen-plus` model for text-to-video tasks and `qwen-vl-max` for image-to-video tasks.
|
| 155 |
+
- You can modify the model used for extension with the parameter `--prompt_extend_model`. For example:
|
| 156 |
+
```sh
|
| 157 |
+
DASH_API_KEY=your_key torchrun --nproc_per_node=8 generate.py --task t2v-A14B --size 1280*720 --ckpt_dir ./Wan2.2-T2V-A14B --dit_fsdp --t5_fsdp --ulysses_size 8 --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage" --use_prompt_extend --prompt_extend_method 'dashscope' --prompt_extend_target_lang 'zh'
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
- Using a local model for extension.
|
| 161 |
+
|
| 162 |
+
- By default, the Qwen model on HuggingFace is used for this extension. Users can choose Qwen models or other models based on the available GPU memory size.
|
| 163 |
+
- For text-to-video tasks, you can use models like `Qwen/Qwen2.5-14B-Instruct`, `Qwen/Qwen2.5-7B-Instruct` and `Qwen/Qwen2.5-3B-Instruct`.
|
| 164 |
+
- For image-to-video tasks, you can use models like `Qwen/Qwen2.5-VL-7B-Instruct` and `Qwen/Qwen2.5-VL-3B-Instruct`.
|
| 165 |
+
- Larger models generally provide better extension results but require more GPU memory.
|
| 166 |
+
- You can modify the model used for extension with the parameter `--prompt_extend_model` , allowing you to specify either a local model path or a Hugging Face model. For example:
|
| 167 |
+
|
| 168 |
+
``` sh
|
| 169 |
+
torchrun --nproc_per_node=8 generate.py --task t2v-A14B --size 1280*720 --ckpt_dir ./Wan2.2-T2V-A14B --dit_fsdp --t5_fsdp --ulysses_size 8 --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage" --use_prompt_extend --prompt_extend_method 'local_qwen' --prompt_extend_target_lang 'zh'
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
#### Run Image-to-Video Generation
|
| 174 |
+
|
| 175 |
+
This repository supports the `Wan2.2-I2V-A14B` Image-to-Video model and can simultaneously support video generation at 480P and 720P resolutions.
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
- Single-GPU inference
|
| 179 |
+
```sh
|
| 180 |
+
python generate.py --task i2v-A14B --size 1280*720 --ckpt_dir ./Wan2.2-I2V-A14B --offload_model True --convert_model_dtype --image examples/i2v_input.JPG --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."
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
> This command can run on a GPU with at least 80GB VRAM.
|
| 184 |
+
|
| 185 |
+
> 💡For the Image-to-Video task, the `size` parameter represents the area of the generated video, with the aspect ratio following that of the original input image.
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
- Multi-GPU inference using FSDP + DeepSpeed Ulysses
|
| 189 |
+
|
| 190 |
+
```sh
|
| 191 |
+
torchrun --nproc_per_node=8 generate.py --task i2v-A14B --size 1280*720 --ckpt_dir ./Wan2.2-I2V-A14B --image examples/i2v_input.JPG --dit_fsdp --t5_fsdp --ulysses_size 8 --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."
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
- Image-to-Video Generation without prompt
|
| 195 |
+
|
| 196 |
+
```sh
|
| 197 |
+
DASH_API_KEY=your_key torchrun --nproc_per_node=8 generate.py --task i2v-A14B --size 1280*720 --ckpt_dir ./Wan2.2-I2V-A14B --prompt '' --image examples/i2v_input.JPG --dit_fsdp --t5_fsdp --ulysses_size 8 --use_prompt_extend --prompt_extend_method 'dashscope'
|
| 198 |
+
```
|
| 199 |
+
|
| 200 |
+
> 💡The model can generate videos solely from the input image. You can use prompt extension to generate prompt from the image.
|
| 201 |
+
|
| 202 |
+
> The process of prompt extension can be referenced [here](#2-using-prompt-extention).
|
| 203 |
+
|
| 204 |
+
#### Run Text-Image-to-Video Generation
|
| 205 |
+
|
| 206 |
+
This repository supports the `Wan2.2-TI2V-5B` Text-Image-to-Video model and can support video generation at 720P resolutions.
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
- Single-GPU Text-to-Video inference
|
| 210 |
+
```sh
|
| 211 |
+
python generate.py --task ti2v-5B --size 1280*704 --ckpt_dir ./Wan2.2-TI2V-5B --offload_model True --convert_model_dtype --t5_cpu --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage"
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
> 💡Unlike other tasks, the 720P resolution of the Text-Image-to-Video task is `1280*704` or `704*1280`.
|
| 215 |
+
|
| 216 |
+
> This command can run on a GPU with at least 24GB VRAM (e.g, RTX 4090 GPU).
|
| 217 |
+
|
| 218 |
+
> 💡If you are running on a GPU with at least 80GB VRAM, you can remove the `--offload_model True`, `--convert_model_dtype` and `--t5_cpu` options to speed up execution.
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
- Single-GPU Image-to-Video inference
|
| 222 |
+
```sh
|
| 223 |
+
python generate.py --task ti2v-5B --size 1280*704 --ckpt_dir ./Wan2.2-TI2V-5B --offload_model True --convert_model_dtype --t5_cpu --image examples/i2v_input.JPG --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."
|
| 224 |
+
```
|
| 225 |
+
|
| 226 |
+
> 💡If the image parameter is configured, it is an Image-to-Video generation; otherwise, it defaults to a Text-to-Video generation.
|
| 227 |
+
|
| 228 |
+
> 💡Similar to Image-to-Video, the `size` parameter represents the area of the generated video, with the aspect ratio following that of the original input image.
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
- Multi-GPU inference using FSDP + DeepSpeed Ulysses
|
| 232 |
+
|
| 233 |
+
```sh
|
| 234 |
+
torchrun --nproc_per_node=8 generate.py --task ti2v-5B --size 1280*704 --ckpt_dir ./Wan2.2-TI2V-5B --dit_fsdp --t5_fsdp --ulysses_size 8 --image examples/i2v_input.JPG --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."
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
> The process of prompt extension can be referenced [here](#2-using-prompt-extention).
|
| 238 |
+
|
| 239 |
+
#### Run Speech-to-Video Generation
|
| 240 |
+
|
| 241 |
+
This repository supports the `Wan2.2-S2V-14B` Speech-to-Video model and can simultaneously support video generation at 480P and 720P resolutions.
|
| 242 |
+
|
| 243 |
+
- Single-GPU Speech-to-Video inference
|
| 244 |
+
|
| 245 |
+
```sh
|
| 246 |
+
python generate.py --task s2v-14B --size 1024*704 --ckpt_dir ./Wan2.2-S2V-14B/ --offload_model True --convert_model_dtype --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard." --image "examples/i2v_input.JPG" --audio "examples/talk.wav"
|
| 247 |
+
# Without setting --num_clip, the generated video length will automatically adjust based on the input audio length
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
> 💡 This command can run on a GPU with at least 80GB VRAM.
|
| 251 |
+
|
| 252 |
+
- Multi-GPU inference using FSDP + DeepSpeed Ulysses
|
| 253 |
+
|
| 254 |
+
```sh
|
| 255 |
+
torchrun --nproc_per_node=8 generate.py --task s2v-14B --size 1024*704 --ckpt_dir ./Wan2.2-S2V-14B/ --dit_fsdp --t5_fsdp --ulysses_size 8 --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard." --image "examples/i2v_input.JPG" --audio "examples/talk.wav"
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
- Pose + Audio driven generation
|
| 259 |
+
|
| 260 |
+
```sh
|
| 261 |
+
torchrun --nproc_per_node=8 generate.py --task s2v-14B --size 1024*704 --ckpt_dir ./Wan2.2-S2V-14B/ --dit_fsdp --t5_fsdp --ulysses_size 8 --prompt "a person is singing" --image "examples/pose.png" --audio "examples/sing.MP3" --pose_video "./examples/pose.mp4"
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
> 💡For the Speech-to-Video task, the `size` parameter represents the area of the generated video, with the aspect ratio following that of the original input image.
|
| 265 |
+
|
| 266 |
+
> 💡The model can generate videos from audio input combined with reference image and optional text prompt.
|
| 267 |
+
|
| 268 |
+
> 💡The `--pose_video` parameter enables pose-driven generation, allowing the model to follow specific pose sequences while generating videos synchronized with audio input.
|
| 269 |
+
|
| 270 |
+
> 💡The `--num_clip` parameter controls the number of video clips generated, useful for quick preview with shorter generation time.
|
| 271 |
+
|
| 272 |
+
## Computational Efficiency on Different GPUs
|
| 273 |
+
|
| 274 |
+
We test the computational efficiency of different **Wan2.2** models on different GPUs in the following table. The results are presented in the format: **Total time (s) / peak GPU memory (GB)**.
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
<div align="center">
|
| 278 |
+
<img src="assets/comp_effic.png" alt="" style="width: 80%;" />
|
| 279 |
+
</div>
|
| 280 |
+
|
| 281 |
+
> The parameter settings for the tests presented in this table are as follows:
|
| 282 |
+
> (1) Multi-GPU: 14B: `--ulysses_size 4/8 --dit_fsdp --t5_fsdp`, 5B: `--ulysses_size 4/8 --offload_model True --convert_model_dtype --t5_cpu`; Single-GPU: 14B: `--offload_model True --convert_model_dtype`, 5B: `--offload_model True --convert_model_dtype --t5_cpu`
|
| 283 |
+
(--convert_model_dtype converts model parameter types to config.param_dtype);
|
| 284 |
+
> (2) The distributed testing utilizes the built-in FSDP and Ulysses implementations, with FlashAttention3 deployed on Hopper architecture GPUs;
|
| 285 |
+
> (3) Tests were run without the `--use_prompt_extend` flag;
|
| 286 |
+
> (4) Reported results are the average of multiple samples taken after the warm-up phase.
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
-------
|
| 290 |
+
|
| 291 |
+
## Introduction of Wan2.2
|
| 292 |
+
|
| 293 |
+
**Wan2.2** builds on the foundation of Wan2.1 with notable improvements in generation quality and model capability. This upgrade is driven by a series of key technical innovations, mainly including the Mixture-of-Experts (MoE) architecture, upgraded training data, and high-compression video generation.
|
| 294 |
+
|
| 295 |
+
##### (1) Mixture-of-Experts (MoE) Architecture
|
| 296 |
+
|
| 297 |
+
Wan2.2 introduces Mixture-of-Experts (MoE) architecture into the video generation diffusion model. MoE has been widely validated in large language models as an efficient approach to increase total model parameters while keeping inference cost nearly unchanged. In Wan2.2, the A14B model series adopts a two-expert design tailored to the denoising process of diffusion models: a high-noise expert for the early stages, focusing on overall layout; and a low-noise expert for the later stages, refining video details. Each expert model has about 14B parameters, resulting in a total of 27B parameters but only 14B active parameters per step, keeping inference computation and GPU memory nearly unchanged.
|
| 298 |
+
|
| 299 |
+
<div align="center">
|
| 300 |
+
<img src="assets/moe_arch.png" alt="" style="width: 90%;" />
|
| 301 |
+
</div>
|
| 302 |
+
|
| 303 |
+
The transition point between the two experts is determined by the signal-to-noise ratio (SNR), a metric that decreases monotonically as the denoising step $t$ increases. At the beginning of the denoising process, $t$ is large and the noise level is high, so the SNR is at its minimum, denoted as ${SNR}_{min}$. In this stage, the high-noise expert is activated. We define a threshold step ${t}_{moe}$ corresponding to half of the ${SNR}_{min}$, and switch to the low-noise expert when $t<{t}_{moe}$.
|
| 304 |
+
|
| 305 |
+
<div align="center">
|
| 306 |
+
<img src="assets/moe_2.png" alt="" style="width: 90%;" />
|
| 307 |
+
</div>
|
| 308 |
+
|
| 309 |
+
To validate the effectiveness of the MoE architecture, four settings are compared based on their validation loss curves. The baseline **Wan2.1** model does not employ the MoE architecture. Among the MoE-based variants, the **Wan2.1 & High-Noise Expert** reuses the Wan2.1 model as the low-noise expert while uses the Wan2.2's high-noise expert, while the **Wan2.1 & Low-Noise Expert** uses Wan2.1 as the high-noise expert and employ the Wan2.2's low-noise expert. The **Wan2.2 (MoE)** (our final version) achieves the lowest validation loss, indicating that its generated video distribution is closest to ground-truth and exhibits superior convergence.
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
##### (2) Efficient High-Definition Hybrid TI2V
|
| 313 |
+
To enable more efficient deployment, Wan2.2 also explores a high-compression design. In addition to the 27B MoE models, a 5B dense model, i.e., TI2V-5B, is released. It is supported by a high-compression Wan2.2-VAE, which achieves a $T\times H\times W$ compression ratio of $4\times16\times16$, increasing the overall compression rate to 64 while maintaining high-quality video reconstruction. With an additional patchification layer, the total compression ratio of TI2V-5B reaches $4\times32\times32$. Without specific optimization, TI2V-5B can generate a 5-second 720P video in under 9 minutes on a single consumer-grade GPU, ranking among the fastest 720P@24fps video generation models. This model also natively supports both text-to-video and image-to-video tasks within a single unified framework, covering both academic research and practical applications.
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
<div align="center">
|
| 317 |
+
<img src="assets/vae.png" alt="" style="width: 80%;" />
|
| 318 |
+
</div>
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
##### Comparisons to SOTAs
|
| 323 |
+
We compared Wan2.2 with leading closed-source commercial models on our new Wan-Bench 2.0, evaluating performance across multiple crucial dimensions. The results demonstrate that Wan2.2 achieves superior performance compared to these leading models.
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
<div align="center">
|
| 327 |
+
<img src="assets/performance.png" alt="" style="width: 90%;" />
|
| 328 |
+
</div>
|
| 329 |
+
|
| 330 |
+
## Citation
|
| 331 |
+
If you find our work helpful, please cite us.
|
| 332 |
+
|
| 333 |
+
```
|
| 334 |
+
@article{wan2025,
|
| 335 |
+
title={Wan: Open and Advanced Large-Scale Video Generative Models},
|
| 336 |
+
author={Team Wan and Ang Wang and Baole Ai and Bin Wen and Chaojie Mao and Chen-Wei Xie and Di Chen and Feiwu Yu and Haiming Zhao and Jianxiao Yang and Jianyuan Zeng and Jiayu Wang and Jingfeng Zhang and Jingren Zhou and Jinkai Wang and Jixuan Chen and Kai Zhu and Kang Zhao and Keyu Yan and Lianghua Huang and Mengyang Feng and Ningyi Zhang and Pandeng Li and Pingyu Wu and Ruihang Chu and Ruili Feng and Shiwei Zhang and Siyang Sun and Tao Fang and Tianxing Wang and Tianyi Gui and Tingyu Weng and Tong Shen and Wei Lin and Wei Wang and Wei Wang and Wenmeng Zhou and Wente Wang and Wenting Shen and Wenyuan Yu and Xianzhong Shi and Xiaoming Huang and Xin Xu and Yan Kou and Yangyu Lv and Yifei Li and Yijing Liu and Yiming Wang and Yingya Zhang and Yitong Huang and Yong Li and You Wu and Yu Liu and Yulin Pan and Yun Zheng and Yuntao Hong and Yupeng Shi and Yutong Feng and Zeyinzi Jiang and Zhen Han and Zhi-Fan Wu and Ziyu Liu},
|
| 337 |
+
journal = {arXiv preprint arXiv:2503.20314},
|
| 338 |
+
year={2025}
|
| 339 |
+
}
|
| 340 |
+
```
|
| 341 |
+
|
| 342 |
+
## License Agreement
|
| 343 |
+
The models in this repository are licensed under the Apache 2.0 License. We claim no rights over the your generated contents, granting you the freedom to use them while ensuring that your usage complies with the provisions of this license. You are fully accountable for your use of the models, which must not involve sharing any content that violates applicable laws, causes harm to individuals or groups, disseminates personal information intended for harm, spreads misinformation, or targets vulnerable populations. For a complete list of restrictions and details regarding your rights, please refer to the full text of the [license](LICENSE.txt).
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
## Acknowledgements
|
| 347 |
+
|
| 348 |
+
We would like to thank the contributors to the [SD3](https://huggingface.co/stabilityai/stable-diffusion-3-medium), [Qwen](https://huggingface.co/Qwen), [umt5-xxl](https://huggingface.co/google/umt5-xxl), [diffusers](https://github.com/huggingface/diffusers) and [HuggingFace](https://huggingface.co) repositories, for their open research.
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
## Contact Us
|
| 353 |
+
If you would like to leave a message to our research or product teams, feel free to join our [Discord](https://discord.gg/AKNgpMK4Yj) or [WeChat groups](https://gw.alicdn.com/imgextra/i2/O1CN01tqjWFi1ByuyehkTSB_!!6000000000015-0-tps-611-1279.jpg)!
|
| 354 |
+
|
exp_code/1_benchmark/Wan2.2/generate.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
| 2 |
+
import argparse
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import warnings
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
warnings.filterwarnings('ignore')
|
| 10 |
+
|
| 11 |
+
import random
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.distributed as dist
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
import wan
|
| 18 |
+
from wan.configs import MAX_AREA_CONFIGS, SIZE_CONFIGS, SUPPORTED_SIZES, WAN_CONFIGS
|
| 19 |
+
from wan.distributed.util import init_distributed_group
|
| 20 |
+
from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
|
| 21 |
+
from wan.utils.utils import merge_video_audio, save_video, str2bool
|
| 22 |
+
|
| 23 |
+
EXAMPLE_PROMPT = {
|
| 24 |
+
"t2v-A14B": {
|
| 25 |
+
"prompt":
|
| 26 |
+
"Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
|
| 27 |
+
},
|
| 28 |
+
"i2v-A14B": {
|
| 29 |
+
"prompt":
|
| 30 |
+
"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.",
|
| 31 |
+
"image":
|
| 32 |
+
"examples/i2v_input.JPG",
|
| 33 |
+
},
|
| 34 |
+
"ti2v-5B": {
|
| 35 |
+
"prompt":
|
| 36 |
+
"Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
|
| 37 |
+
},
|
| 38 |
+
"s2v-14B": {
|
| 39 |
+
"prompt":
|
| 40 |
+
"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.",
|
| 41 |
+
"image":
|
| 42 |
+
"examples/i2v_input.JPG",
|
| 43 |
+
"audio":
|
| 44 |
+
"examples/talk.wav",
|
| 45 |
+
},
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _validate_args(args):
|
| 50 |
+
# Basic check
|
| 51 |
+
assert args.ckpt_dir is not None, "Please specify the checkpoint directory."
|
| 52 |
+
assert args.task in WAN_CONFIGS, f"Unsupport task: {args.task}"
|
| 53 |
+
assert args.task in EXAMPLE_PROMPT, f"Unsupport task: {args.task}"
|
| 54 |
+
|
| 55 |
+
if args.prompt is None:
|
| 56 |
+
args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
|
| 57 |
+
if args.image is None and "image" in EXAMPLE_PROMPT[args.task]:
|
| 58 |
+
args.image = EXAMPLE_PROMPT[args.task]["image"]
|
| 59 |
+
if args.audio is None and "audio" in EXAMPLE_PROMPT[args.task]:
|
| 60 |
+
args.audio = EXAMPLE_PROMPT[args.task]["audio"]
|
| 61 |
+
|
| 62 |
+
if args.task == "i2v-A14B":
|
| 63 |
+
assert args.image is not None, "Please specify the image path for i2v."
|
| 64 |
+
|
| 65 |
+
cfg = WAN_CONFIGS[args.task]
|
| 66 |
+
|
| 67 |
+
if args.sample_steps is None:
|
| 68 |
+
args.sample_steps = cfg.sample_steps
|
| 69 |
+
|
| 70 |
+
if args.sample_shift is None:
|
| 71 |
+
args.sample_shift = cfg.sample_shift
|
| 72 |
+
|
| 73 |
+
if args.sample_guide_scale is None:
|
| 74 |
+
args.sample_guide_scale = cfg.sample_guide_scale
|
| 75 |
+
|
| 76 |
+
if args.frame_num is None:
|
| 77 |
+
args.frame_num = cfg.frame_num
|
| 78 |
+
|
| 79 |
+
args.base_seed = args.base_seed if args.base_seed >= 0 else random.randint(
|
| 80 |
+
0, sys.maxsize)
|
| 81 |
+
# Size check
|
| 82 |
+
if not 's2v' in args.task:
|
| 83 |
+
assert args.size in SUPPORTED_SIZES[
|
| 84 |
+
args.
|
| 85 |
+
task], f"Unsupport size {args.size} for task {args.task}, supported sizes are: {', '.join(SUPPORTED_SIZES[args.task])}"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _parse_args():
|
| 89 |
+
parser = argparse.ArgumentParser(
|
| 90 |
+
description="Generate a image or video from a text prompt or image using Wan"
|
| 91 |
+
)
|
| 92 |
+
parser.add_argument(
|
| 93 |
+
"--task",
|
| 94 |
+
type=str,
|
| 95 |
+
default="t2v-A14B",
|
| 96 |
+
choices=list(WAN_CONFIGS.keys()),
|
| 97 |
+
help="The task to run.")
|
| 98 |
+
parser.add_argument(
|
| 99 |
+
"--size",
|
| 100 |
+
type=str,
|
| 101 |
+
default="1280*720",
|
| 102 |
+
choices=list(SIZE_CONFIGS.keys()),
|
| 103 |
+
help="The area (width*height) of the generated video. For the I2V task, the aspect ratio of the output video will follow that of the input image."
|
| 104 |
+
)
|
| 105 |
+
parser.add_argument(
|
| 106 |
+
"--frame_num",
|
| 107 |
+
type=int,
|
| 108 |
+
default=None,
|
| 109 |
+
help="How many frames of video are generated. The number should be 4n+1"
|
| 110 |
+
)
|
| 111 |
+
parser.add_argument(
|
| 112 |
+
"--ckpt_dir",
|
| 113 |
+
type=str,
|
| 114 |
+
default=None,
|
| 115 |
+
help="The path to the checkpoint directory.")
|
| 116 |
+
parser.add_argument(
|
| 117 |
+
"--offload_model",
|
| 118 |
+
type=str2bool,
|
| 119 |
+
default=None,
|
| 120 |
+
help="Whether to offload the model to CPU after each model forward, reducing GPU memory usage."
|
| 121 |
+
)
|
| 122 |
+
parser.add_argument(
|
| 123 |
+
"--ulysses_size",
|
| 124 |
+
type=int,
|
| 125 |
+
default=1,
|
| 126 |
+
help="The size of the ulysses parallelism in DiT.")
|
| 127 |
+
parser.add_argument(
|
| 128 |
+
"--t5_fsdp",
|
| 129 |
+
action="store_true",
|
| 130 |
+
default=False,
|
| 131 |
+
help="Whether to use FSDP for T5.")
|
| 132 |
+
parser.add_argument(
|
| 133 |
+
"--t5_cpu",
|
| 134 |
+
action="store_true",
|
| 135 |
+
default=False,
|
| 136 |
+
help="Whether to place T5 model on CPU.")
|
| 137 |
+
parser.add_argument(
|
| 138 |
+
"--dit_fsdp",
|
| 139 |
+
action="store_true",
|
| 140 |
+
default=False,
|
| 141 |
+
help="Whether to use FSDP for DiT.")
|
| 142 |
+
parser.add_argument(
|
| 143 |
+
"--save_file",
|
| 144 |
+
type=str,
|
| 145 |
+
default=None,
|
| 146 |
+
help="The file to save the generated video to.")
|
| 147 |
+
parser.add_argument(
|
| 148 |
+
"--prompt",
|
| 149 |
+
type=str,
|
| 150 |
+
default=None,
|
| 151 |
+
help="The prompt to generate the video from.")
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--use_prompt_extend",
|
| 154 |
+
action="store_true",
|
| 155 |
+
default=False,
|
| 156 |
+
help="Whether to use prompt extend.")
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"--prompt_extend_method",
|
| 159 |
+
type=str,
|
| 160 |
+
default="local_qwen",
|
| 161 |
+
choices=["dashscope", "local_qwen"],
|
| 162 |
+
help="The prompt extend method to use.")
|
| 163 |
+
parser.add_argument(
|
| 164 |
+
"--prompt_extend_model",
|
| 165 |
+
type=str,
|
| 166 |
+
default=None,
|
| 167 |
+
help="The prompt extend model to use.")
|
| 168 |
+
parser.add_argument(
|
| 169 |
+
"--prompt_extend_target_lang",
|
| 170 |
+
type=str,
|
| 171 |
+
default="zh",
|
| 172 |
+
choices=["zh", "en"],
|
| 173 |
+
help="The target language of prompt extend.")
|
| 174 |
+
parser.add_argument(
|
| 175 |
+
"--base_seed",
|
| 176 |
+
type=int,
|
| 177 |
+
default=-1,
|
| 178 |
+
help="The seed to use for generating the video.")
|
| 179 |
+
parser.add_argument(
|
| 180 |
+
"--image",
|
| 181 |
+
type=str,
|
| 182 |
+
default=None,
|
| 183 |
+
help="The image to generate the video from.")
|
| 184 |
+
parser.add_argument(
|
| 185 |
+
"--sample_solver",
|
| 186 |
+
type=str,
|
| 187 |
+
default='unipc',
|
| 188 |
+
choices=['unipc', 'dpm++'],
|
| 189 |
+
help="The solver used to sample.")
|
| 190 |
+
parser.add_argument(
|
| 191 |
+
"--sample_steps", type=int, default=None, help="The sampling steps.")
|
| 192 |
+
parser.add_argument(
|
| 193 |
+
"--sample_shift",
|
| 194 |
+
type=float,
|
| 195 |
+
default=None,
|
| 196 |
+
help="Sampling shift factor for flow matching schedulers.")
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--sample_guide_scale",
|
| 199 |
+
type=float,
|
| 200 |
+
default=None,
|
| 201 |
+
help="Classifier free guidance scale.")
|
| 202 |
+
parser.add_argument(
|
| 203 |
+
"--convert_model_dtype",
|
| 204 |
+
action="store_true",
|
| 205 |
+
default=False,
|
| 206 |
+
help="Whether to convert model paramerters dtype.")
|
| 207 |
+
|
| 208 |
+
# following args only works for s2v
|
| 209 |
+
parser.add_argument(
|
| 210 |
+
"--num_clip",
|
| 211 |
+
type=int,
|
| 212 |
+
default=None,
|
| 213 |
+
help="Number of video clips to generate, the whole video will not exceed the length of audio."
|
| 214 |
+
)
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--audio",
|
| 217 |
+
type=str,
|
| 218 |
+
default=None,
|
| 219 |
+
help="Path to the audio file, e.g. wav, mp3")
|
| 220 |
+
parser.add_argument(
|
| 221 |
+
"--pose_video",
|
| 222 |
+
type=str,
|
| 223 |
+
default=None,
|
| 224 |
+
help="Provide Dw-pose sequence to do Pose Driven")
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--start_from_ref",
|
| 227 |
+
action="store_true",
|
| 228 |
+
default=False,
|
| 229 |
+
help="whether set the reference image as the starting point for generation"
|
| 230 |
+
)
|
| 231 |
+
parser.add_argument(
|
| 232 |
+
"--infer_frames",
|
| 233 |
+
type=int,
|
| 234 |
+
default=80,
|
| 235 |
+
help="Number of frames per clip, 48 or 80 or others (must be multiple of 4) for 14B s2v"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
args = parser.parse_args()
|
| 239 |
+
|
| 240 |
+
_validate_args(args)
|
| 241 |
+
|
| 242 |
+
return args
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _init_logging(rank):
|
| 246 |
+
# logging
|
| 247 |
+
if rank == 0:
|
| 248 |
+
# set format
|
| 249 |
+
logging.basicConfig(
|
| 250 |
+
level=logging.INFO,
|
| 251 |
+
format="[%(asctime)s] %(levelname)s: %(message)s",
|
| 252 |
+
handlers=[logging.StreamHandler(stream=sys.stdout)])
|
| 253 |
+
else:
|
| 254 |
+
logging.basicConfig(level=logging.ERROR)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def generate(args):
|
| 258 |
+
rank = int(os.getenv("RANK", 0))
|
| 259 |
+
world_size = int(os.getenv("WORLD_SIZE", 1))
|
| 260 |
+
local_rank = int(os.getenv("LOCAL_RANK", 0))
|
| 261 |
+
device = local_rank
|
| 262 |
+
_init_logging(rank)
|
| 263 |
+
|
| 264 |
+
if args.offload_model is None:
|
| 265 |
+
args.offload_model = False if world_size > 1 else True
|
| 266 |
+
logging.info(
|
| 267 |
+
f"offload_model is not specified, set to {args.offload_model}.")
|
| 268 |
+
if world_size > 1:
|
| 269 |
+
torch.cuda.set_device(local_rank)
|
| 270 |
+
dist.init_process_group(
|
| 271 |
+
backend="nccl",
|
| 272 |
+
init_method="env://",
|
| 273 |
+
rank=rank,
|
| 274 |
+
world_size=world_size)
|
| 275 |
+
else:
|
| 276 |
+
assert not (
|
| 277 |
+
args.t5_fsdp or args.dit_fsdp
|
| 278 |
+
), f"t5_fsdp and dit_fsdp are not supported in non-distributed environments."
|
| 279 |
+
assert not (
|
| 280 |
+
args.ulysses_size > 1
|
| 281 |
+
), f"sequence parallel are not supported in non-distributed environments."
|
| 282 |
+
|
| 283 |
+
if args.ulysses_size > 1:
|
| 284 |
+
assert args.ulysses_size == world_size, f"The number of ulysses_size should be equal to the world size."
|
| 285 |
+
init_distributed_group()
|
| 286 |
+
|
| 287 |
+
if args.use_prompt_extend:
|
| 288 |
+
if args.prompt_extend_method == "dashscope":
|
| 289 |
+
prompt_expander = DashScopePromptExpander(
|
| 290 |
+
model_name=args.prompt_extend_model,
|
| 291 |
+
task=args.task,
|
| 292 |
+
is_vl=args.image is not None)
|
| 293 |
+
elif args.prompt_extend_method == "local_qwen":
|
| 294 |
+
prompt_expander = QwenPromptExpander(
|
| 295 |
+
model_name=args.prompt_extend_model,
|
| 296 |
+
task=args.task,
|
| 297 |
+
is_vl=args.image is not None,
|
| 298 |
+
device=rank)
|
| 299 |
+
else:
|
| 300 |
+
raise NotImplementedError(
|
| 301 |
+
f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
|
| 302 |
+
|
| 303 |
+
cfg = WAN_CONFIGS[args.task]
|
| 304 |
+
if args.ulysses_size > 1:
|
| 305 |
+
assert cfg.num_heads % args.ulysses_size == 0, f"`{cfg.num_heads=}` cannot be divided evenly by `{args.ulysses_size=}`."
|
| 306 |
+
|
| 307 |
+
logging.info(f"Generation job args: {args}")
|
| 308 |
+
logging.info(f"Generation model config: {cfg}")
|
| 309 |
+
|
| 310 |
+
if dist.is_initialized():
|
| 311 |
+
base_seed = [args.base_seed] if rank == 0 else [None]
|
| 312 |
+
dist.broadcast_object_list(base_seed, src=0)
|
| 313 |
+
args.base_seed = base_seed[0]
|
| 314 |
+
|
| 315 |
+
logging.info(f"Input prompt: {args.prompt}")
|
| 316 |
+
img = None
|
| 317 |
+
if args.image is not None:
|
| 318 |
+
img = Image.open(args.image).convert("RGB")
|
| 319 |
+
logging.info(f"Input image: {args.image}")
|
| 320 |
+
|
| 321 |
+
# prompt extend
|
| 322 |
+
if args.use_prompt_extend:
|
| 323 |
+
logging.info("Extending prompt ...")
|
| 324 |
+
if rank == 0:
|
| 325 |
+
prompt_output = prompt_expander(
|
| 326 |
+
args.prompt,
|
| 327 |
+
image=img,
|
| 328 |
+
tar_lang=args.prompt_extend_target_lang,
|
| 329 |
+
seed=args.base_seed)
|
| 330 |
+
if prompt_output.status == False:
|
| 331 |
+
logging.info(
|
| 332 |
+
f"Extending prompt failed: {prompt_output.message}")
|
| 333 |
+
logging.info("Falling back to original prompt.")
|
| 334 |
+
input_prompt = args.prompt
|
| 335 |
+
else:
|
| 336 |
+
input_prompt = prompt_output.prompt
|
| 337 |
+
input_prompt = [input_prompt]
|
| 338 |
+
else:
|
| 339 |
+
input_prompt = [None]
|
| 340 |
+
if dist.is_initialized():
|
| 341 |
+
dist.broadcast_object_list(input_prompt, src=0)
|
| 342 |
+
args.prompt = input_prompt[0]
|
| 343 |
+
logging.info(f"Extended prompt: {args.prompt}")
|
| 344 |
+
|
| 345 |
+
if "t2v" in args.task:
|
| 346 |
+
logging.info("Creating WanT2V pipeline.")
|
| 347 |
+
wan_t2v = wan.WanT2V(
|
| 348 |
+
config=cfg,
|
| 349 |
+
checkpoint_dir=args.ckpt_dir,
|
| 350 |
+
device_id=device,
|
| 351 |
+
rank=rank,
|
| 352 |
+
t5_fsdp=args.t5_fsdp,
|
| 353 |
+
dit_fsdp=args.dit_fsdp,
|
| 354 |
+
use_sp=(args.ulysses_size > 1),
|
| 355 |
+
t5_cpu=args.t5_cpu,
|
| 356 |
+
convert_model_dtype=args.convert_model_dtype,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
logging.info(f"Generating video ...")
|
| 360 |
+
video = wan_t2v.generate(
|
| 361 |
+
args.prompt,
|
| 362 |
+
size=SIZE_CONFIGS[args.size],
|
| 363 |
+
frame_num=args.frame_num,
|
| 364 |
+
shift=args.sample_shift,
|
| 365 |
+
sample_solver=args.sample_solver,
|
| 366 |
+
sampling_steps=args.sample_steps,
|
| 367 |
+
guide_scale=args.sample_guide_scale,
|
| 368 |
+
seed=args.base_seed,
|
| 369 |
+
offload_model=args.offload_model)
|
| 370 |
+
elif "ti2v" in args.task:
|
| 371 |
+
logging.info("Creating WanTI2V pipeline.")
|
| 372 |
+
wan_ti2v = wan.WanTI2V(
|
| 373 |
+
config=cfg,
|
| 374 |
+
checkpoint_dir=args.ckpt_dir,
|
| 375 |
+
device_id=device,
|
| 376 |
+
rank=rank,
|
| 377 |
+
t5_fsdp=args.t5_fsdp,
|
| 378 |
+
dit_fsdp=args.dit_fsdp,
|
| 379 |
+
use_sp=(args.ulysses_size > 1),
|
| 380 |
+
t5_cpu=args.t5_cpu,
|
| 381 |
+
convert_model_dtype=args.convert_model_dtype,
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
logging.info(f"Generating video ...")
|
| 385 |
+
video = wan_ti2v.generate(
|
| 386 |
+
args.prompt,
|
| 387 |
+
img=img,
|
| 388 |
+
size=SIZE_CONFIGS[args.size],
|
| 389 |
+
max_area=MAX_AREA_CONFIGS[args.size],
|
| 390 |
+
frame_num=args.frame_num,
|
| 391 |
+
shift=args.sample_shift,
|
| 392 |
+
sample_solver=args.sample_solver,
|
| 393 |
+
sampling_steps=args.sample_steps,
|
| 394 |
+
guide_scale=args.sample_guide_scale,
|
| 395 |
+
seed=args.base_seed,
|
| 396 |
+
offload_model=args.offload_model)
|
| 397 |
+
elif "s2v" in args.task:
|
| 398 |
+
print("Creating WanS2V pipeline.")
|
| 399 |
+
logging.info("Creating WanS2V pipeline.")
|
| 400 |
+
wan_s2v = wan.WanS2V(
|
| 401 |
+
config=cfg,
|
| 402 |
+
checkpoint_dir=args.ckpt_dir,
|
| 403 |
+
device_id=device,
|
| 404 |
+
rank=rank,
|
| 405 |
+
t5_fsdp=args.t5_fsdp,
|
| 406 |
+
dit_fsdp=args.dit_fsdp,
|
| 407 |
+
use_sp=(args.ulysses_size > 1),
|
| 408 |
+
t5_cpu=args.t5_cpu,
|
| 409 |
+
convert_model_dtype=args.convert_model_dtype,
|
| 410 |
+
)
|
| 411 |
+
logging.info(f"Generating video ...")
|
| 412 |
+
video = wan_s2v.generate(
|
| 413 |
+
input_prompt=args.prompt,
|
| 414 |
+
ref_image_path=args.image,
|
| 415 |
+
audio_path=args.audio,
|
| 416 |
+
num_repeat=args.num_clip,
|
| 417 |
+
pose_video=args.pose_video,
|
| 418 |
+
max_area=MAX_AREA_CONFIGS[args.size],
|
| 419 |
+
infer_frames=args.infer_frames,
|
| 420 |
+
shift=args.sample_shift,
|
| 421 |
+
sample_solver=args.sample_solver,
|
| 422 |
+
sampling_steps=args.sample_steps,
|
| 423 |
+
guide_scale=args.sample_guide_scale,
|
| 424 |
+
seed=args.base_seed,
|
| 425 |
+
offload_model=args.offload_model,
|
| 426 |
+
init_first_frame=args.start_from_ref,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
else:
|
| 430 |
+
logging.info("Creating WanI2V pipeline.")
|
| 431 |
+
wan_i2v = wan.WanI2V(
|
| 432 |
+
config=cfg,
|
| 433 |
+
checkpoint_dir=args.ckpt_dir,
|
| 434 |
+
device_id=device,
|
| 435 |
+
rank=rank,
|
| 436 |
+
t5_fsdp=args.t5_fsdp,
|
| 437 |
+
dit_fsdp=args.dit_fsdp,
|
| 438 |
+
use_sp=(args.ulysses_size > 1),
|
| 439 |
+
t5_cpu=args.t5_cpu,
|
| 440 |
+
convert_model_dtype=args.convert_model_dtype,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
logging.info("Generating video ...")
|
| 444 |
+
video = wan_i2v.generate(
|
| 445 |
+
args.prompt,
|
| 446 |
+
img,
|
| 447 |
+
max_area=MAX_AREA_CONFIGS[args.size],
|
| 448 |
+
frame_num=args.frame_num,
|
| 449 |
+
shift=args.sample_shift,
|
| 450 |
+
sample_solver=args.sample_solver,
|
| 451 |
+
sampling_steps=args.sample_steps,
|
| 452 |
+
guide_scale=args.sample_guide_scale,
|
| 453 |
+
seed=args.base_seed,
|
| 454 |
+
offload_model=args.offload_model)
|
| 455 |
+
|
| 456 |
+
if rank == 0:
|
| 457 |
+
if args.save_file is None:
|
| 458 |
+
formatted_time = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 459 |
+
formatted_prompt = args.prompt.replace(" ", "_").replace("/",
|
| 460 |
+
"_")[:50]
|
| 461 |
+
suffix = '.mp4'
|
| 462 |
+
args.save_file = f"{args.task}_{args.size.replace('*','x') if sys.platform=='win32' else args.size}_{args.ulysses_size}_{formatted_prompt}_{formatted_time}" + suffix
|
| 463 |
+
|
| 464 |
+
logging.info(f"Saving generated video to {args.save_file}")
|
| 465 |
+
save_video(
|
| 466 |
+
tensor=video[None],
|
| 467 |
+
save_file=args.save_file,
|
| 468 |
+
fps=cfg.sample_fps,
|
| 469 |
+
nrow=1,
|
| 470 |
+
normalize=True,
|
| 471 |
+
value_range=(-1, 1))
|
| 472 |
+
if "s2v" in args.task:
|
| 473 |
+
merge_video_audio(video_path=args.save_file, audio_path=args.audio)
|
| 474 |
+
del video
|
| 475 |
+
|
| 476 |
+
torch.cuda.synchronize()
|
| 477 |
+
if dist.is_initialized():
|
| 478 |
+
dist.barrier()
|
| 479 |
+
dist.destroy_process_group()
|
| 480 |
+
|
| 481 |
+
logging.info("Finished.")
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
if __name__ == "__main__":
|
| 485 |
+
args = _parse_args()
|
| 486 |
+
generate(args)
|
exp_code/1_benchmark/Wan2.2/pyproject.toml
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=61.0"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "wan"
|
| 7 |
+
version = "2.2.0"
|
| 8 |
+
description = "Wan: Open and Advanced Large-Scale Video Generative Models"
|
| 9 |
+
authors = [
|
| 10 |
+
{ name = "Wan Team", email = "wan.ai@alibabacloud.com" }
|
| 11 |
+
]
|
| 12 |
+
license = { file = "LICENSE.txt" }
|
| 13 |
+
readme = "README.md"
|
| 14 |
+
requires-python = ">=3.10,<4.0"
|
| 15 |
+
dependencies = [
|
| 16 |
+
"torch>=2.4.0",
|
| 17 |
+
"torchvision>=0.19.0",
|
| 18 |
+
"opencv-python>=4.9.0.80",
|
| 19 |
+
"diffusers>=0.31.0",
|
| 20 |
+
"transformers>=4.49.0",
|
| 21 |
+
"tokenizers>=0.20.3",
|
| 22 |
+
"accelerate>=1.1.1",
|
| 23 |
+
"tqdm",
|
| 24 |
+
"imageio",
|
| 25 |
+
"easydict",
|
| 26 |
+
"ftfy",
|
| 27 |
+
"dashscope",
|
| 28 |
+
"imageio-ffmpeg",
|
| 29 |
+
"flash_attn",
|
| 30 |
+
"numpy>=1.23.5,<2"
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
[project.optional-dependencies]
|
| 34 |
+
dev = [
|
| 35 |
+
"pytest",
|
| 36 |
+
"black",
|
| 37 |
+
"flake8",
|
| 38 |
+
"isort",
|
| 39 |
+
"mypy",
|
| 40 |
+
"huggingface-hub[cli]"
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
[project.urls]
|
| 44 |
+
homepage = "https://wanxai.com"
|
| 45 |
+
documentation = "https://github.com/Wan-Video/Wan2.2"
|
| 46 |
+
repository = "https://github.com/Wan-Video/Wan2.2"
|
| 47 |
+
huggingface = "https://huggingface.co/Wan-AI/"
|
| 48 |
+
modelscope = "https://modelscope.cn/organization/Wan-AI"
|
| 49 |
+
discord = "https://discord.gg/p5XbdQV7"
|
| 50 |
+
|
| 51 |
+
[tool.setuptools]
|
| 52 |
+
packages = ["wan"]
|
| 53 |
+
|
| 54 |
+
[tool.setuptools.package-data]
|
| 55 |
+
"wan" = ["**/*.py"]
|
| 56 |
+
|
| 57 |
+
[tool.black]
|
| 58 |
+
line-length = 88
|
| 59 |
+
|
| 60 |
+
[tool.isort]
|
| 61 |
+
profile = "black"
|
| 62 |
+
|
| 63 |
+
[tool.mypy]
|
| 64 |
+
strict = true
|
| 65 |
+
|
| 66 |
+
|
exp_code/1_benchmark/Wan2.2/requirements.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.4.0
|
| 2 |
+
torchvision>=0.19.0
|
| 3 |
+
opencv-python>=4.9.0.80
|
| 4 |
+
diffusers>=0.31.0
|
| 5 |
+
transformers>=4.49.0
|
| 6 |
+
tokenizers>=0.20.3
|
| 7 |
+
accelerate>=1.1.1
|
| 8 |
+
tqdm
|
| 9 |
+
imageio[ffmpeg]
|
| 10 |
+
easydict
|
| 11 |
+
ftfy
|
| 12 |
+
dashscope
|
| 13 |
+
imageio-ffmpeg
|
| 14 |
+
flash_attn
|
| 15 |
+
numpy>=1.23.5,<2
|
exp_code/1_benchmark/Wan2.2/run.sh
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
python generate.py \
|
| 2 |
+
--task s2v-14B --size 1024*704 \
|
| 3 |
+
--ckpt_dir "/mnt/bn/yufan-dev-my/ysh/Ckpts/Wan-AI/Wan2.2-S2V-14B" \
|
| 4 |
+
--prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard." \
|
| 5 |
+
--image "examples/i2v_input.JPG" \
|
| 6 |
+
--audio "examples/talk.wav"
|
exp_code/1_benchmark/Wan2.2/tests/README.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Put all your models (Wan2.2-T2V-A14B, Wan2.2-I2V-A14B, Wan2.2-TI2V-5B) in a folder and specify the max GPU number you want to use.
|
| 3 |
+
|
| 4 |
+
```bash
|
| 5 |
+
bash ./tests/test.sh <local model dir> <gpu number>
|
| 6 |
+
```
|
exp_code/1_benchmark/Wan2.2/tests/test.sh
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -x
|
| 3 |
+
|
| 4 |
+
unset NCCL_DEBUG
|
| 5 |
+
|
| 6 |
+
if [ "$#" -eq 2 ]; then
|
| 7 |
+
MODEL_DIR=$(realpath "$1")
|
| 8 |
+
GPUS=$2
|
| 9 |
+
else
|
| 10 |
+
echo "Usage: $0 <local model dir> <gpu number>"
|
| 11 |
+
exit 1
|
| 12 |
+
fi
|
| 13 |
+
|
| 14 |
+
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
|
| 15 |
+
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
| 16 |
+
cd "$REPO_ROOT" || exit 1
|
| 17 |
+
|
| 18 |
+
PY_FILE=./generate.py
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
function t2v_A14B() {
|
| 22 |
+
CKPT_DIR="$MODEL_DIR/Wan2.2-T2V-A14B"
|
| 23 |
+
|
| 24 |
+
# # 1-GPU Test
|
| 25 |
+
# echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_A14B 1-GPU Test: "
|
| 26 |
+
# python $PY_FILE --task t2v-A14B --size 480*832 --ckpt_dir $CKPT_DIR
|
| 27 |
+
|
| 28 |
+
# Multiple GPU Test
|
| 29 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_A14B Multiple GPU Test: "
|
| 30 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-A14B --ckpt_dir $CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
|
| 31 |
+
|
| 32 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_A14B Multiple GPU Test: "
|
| 33 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-A14B --ckpt_dir $CKPT_DIR --size 720*1280 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
|
| 34 |
+
|
| 35 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_A14B Multiple GPU Test: "
|
| 36 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-A14B --ckpt_dir $CKPT_DIR --size 1280*720 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
|
| 37 |
+
|
| 38 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_A14B Multiple GPU, prompt extend local_qwen: "
|
| 39 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-A14B --ckpt_dir $CKPT_DIR --size 480*832 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-3B-Instruct" --prompt_extend_target_lang "en"
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
function i2v_A14B() {
|
| 44 |
+
CKPT_DIR="$MODEL_DIR/Wan2.2-I2V-A14B"
|
| 45 |
+
|
| 46 |
+
# echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B 1-GPU Test: "
|
| 47 |
+
# python $PY_FILE --task i2v-A14B --size 832*480 --ckpt_dir $CKPT_DIR
|
| 48 |
+
|
| 49 |
+
# Multiple GPU Test
|
| 50 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B Multiple GPU Test: "
|
| 51 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task i2v-A14B --ckpt_dir $CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
|
| 52 |
+
|
| 53 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B Multiple GPU, prompt extend local_qwen: "
|
| 54 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task i2v-A14B --ckpt_dir $CKPT_DIR --size 720*1280 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-VL-3B-Instruct" --prompt_extend_target_lang "en"
|
| 55 |
+
|
| 56 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B Multiple GPU, prompt extend local_qwen: "
|
| 57 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task i2v-A14B --ckpt_dir $CKPT_DIR --size 1280*720 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-VL-3B-Instruct" --prompt_extend_target_lang "en"
|
| 58 |
+
|
| 59 |
+
if [ -n "${DASH_API_KEY+x}" ]; then
|
| 60 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B Multiple GPU, prompt extend dashscope: "
|
| 61 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task i2v-A14B --ckpt_dir $CKPT_DIR --size 480*832 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_method "dashscope"
|
| 62 |
+
else
|
| 63 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> No DASH_API_KEY found, skip the dashscope extend test."
|
| 64 |
+
fi
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
function ti2v_5B() {
|
| 68 |
+
CKPT_DIR="$MODEL_DIR/Wan2.2-TI2V-5B"
|
| 69 |
+
|
| 70 |
+
# # 1-GPU Test
|
| 71 |
+
# echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ti2v_5B t2v 1-GPU Test: "
|
| 72 |
+
# python $PY_FILE --task ti2v-5B --size 1280*704 --ckpt_dir $CKPT_DIR
|
| 73 |
+
|
| 74 |
+
# Multiple GPU Test
|
| 75 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ti2v_5B t2v Multiple GPU Test: "
|
| 76 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task ti2v-5B --ckpt_dir $CKPT_DIR --size 1280*704 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
|
| 77 |
+
|
| 78 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ti2v_5B t2v Multiple GPU, prompt extend local_qwen: "
|
| 79 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task ti2v-5B --ckpt_dir $CKPT_DIR --size 704*1280 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-3B-Instruct" --prompt_extend_target_lang "en"
|
| 80 |
+
|
| 81 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ti2v_5B i2v Multiple GPU Test: "
|
| 82 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task ti2v-5B --ckpt_dir $CKPT_DIR --size 704*1280 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --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"
|
| 83 |
+
|
| 84 |
+
echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ti2v_5B i2v Multiple GPU, prompt extend local_qwen: "
|
| 85 |
+
torchrun --nproc_per_node=$GPUS $PY_FILE --task ti2v-5B --ckpt_dir $CKPT_DIR --size 1280*704 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-3B-Instruct" --prompt_extend_target_lang '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"
|
| 86 |
+
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
t2v_A14B
|
| 90 |
+
i2v_A14B
|
| 91 |
+
ti2v_5B
|
exp_code/1_benchmark/Wan2.2/wan/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
| 2 |
+
from . import configs, distributed, modules
|
| 3 |
+
from .image2video import WanI2V
|
| 4 |
+
from .speech2video import WanS2V
|
| 5 |
+
from .text2video import WanT2V
|
| 6 |
+
from .textimage2video import WanTI2V
|
exp_code/1_benchmark/Wan2.2/wan/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (519 Bytes). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/__pycache__/image2video.cpython-311.pyc
ADDED
|
Binary file (21 kB). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/__pycache__/speech2video.cpython-311.pyc
ADDED
|
Binary file (31 kB). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/__pycache__/text2video.cpython-311.pyc
ADDED
|
Binary file (18.1 kB). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/__pycache__/textimage2video.cpython-311.pyc
ADDED
|
Binary file (29.3 kB). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/configs/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
| 2 |
+
import copy
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
|
| 6 |
+
|
| 7 |
+
from .wan_i2v_A14B import i2v_A14B
|
| 8 |
+
from .wan_s2v_14B import s2v_14B
|
| 9 |
+
from .wan_t2v_A14B import t2v_A14B
|
| 10 |
+
from .wan_ti2v_5B import ti2v_5B
|
| 11 |
+
|
| 12 |
+
WAN_CONFIGS = {
|
| 13 |
+
't2v-A14B': t2v_A14B,
|
| 14 |
+
'i2v-A14B': i2v_A14B,
|
| 15 |
+
'ti2v-5B': ti2v_5B,
|
| 16 |
+
's2v-14B': s2v_14B,
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
SIZE_CONFIGS = {
|
| 20 |
+
'720*1280': (720, 1280),
|
| 21 |
+
'1280*720': (1280, 720),
|
| 22 |
+
'480*832': (480, 832),
|
| 23 |
+
'832*480': (832, 480),
|
| 24 |
+
'704*1280': (704, 1280),
|
| 25 |
+
'1280*704': (1280, 704),
|
| 26 |
+
'1024*704': (1024, 704),
|
| 27 |
+
'704*1024': (704, 1024),
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
MAX_AREA_CONFIGS = {
|
| 31 |
+
'720*1280': 720 * 1280,
|
| 32 |
+
'1280*720': 1280 * 720,
|
| 33 |
+
'480*832': 480 * 832,
|
| 34 |
+
'832*480': 832 * 480,
|
| 35 |
+
'704*1280': 704 * 1280,
|
| 36 |
+
'1280*704': 1280 * 704,
|
| 37 |
+
'1024*704': 1024 * 704,
|
| 38 |
+
'704*1024': 704 * 1024,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
SUPPORTED_SIZES = {
|
| 42 |
+
't2v-A14B': ('720*1280', '1280*720', '480*832', '832*480'),
|
| 43 |
+
'i2v-A14B': ('720*1280', '1280*720', '480*832', '832*480'),
|
| 44 |
+
'ti2v-5B': ('704*1280', '1280*704'),
|
| 45 |
+
's2v-14B': ('720*1280', '1280*720', '480*832', '832*480', '1024*704',
|
| 46 |
+
'704*1024', '704*1280', '1280*704'),
|
| 47 |
+
}
|
exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/shared_config.cpython-311.pyc
ADDED
|
Binary file (1.09 kB). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/wan_i2v_A14B.cpython-311.pyc
ADDED
|
Binary file (1.42 kB). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/wan_s2v_14B.cpython-311.pyc
ADDED
|
Binary file (2.81 kB). View file
|
|
|
exp_code/1_benchmark/Wan2.2/wan/configs/__pycache__/wan_t2v_A14B.cpython-311.pyc
ADDED
|
Binary file (1.41 kB). View file
|
|
|