weathon commited on
Commit
a67076d
·
1 Parent(s): 4341f93
app.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import imageio
4
+
5
+ import torch
6
+ from diffusers import AutoencoderKLWan
7
+ from vsfwan.pipeline import WanPipeline
8
+ from vsfwan.processor import WanAttnProcessor2_0
9
+ from diffusers import WanVACEPipeline
10
+ from diffusers.utils import export_to_video
11
+ import uuid
12
+ try:
13
+ import spaces
14
+ except ImportError:
15
+ class spaces:
16
+ @staticmethod
17
+ def GPU(fn):
18
+ return fn
19
+
20
+
21
+ model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
22
+ vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
23
+ pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
24
+ pipe.load_lora_weights(
25
+ "Kijai/WanVideo_comfy",
26
+ weight_name="Wan21_CausVid_bidirect2_T2V_1_3B_lora_rank32.safetensors",
27
+ adapter_name="lora"
28
+ )
29
+ pipe = pipe.to("cuda")
30
+ height = 480
31
+ width = 832
32
+ import os
33
+ os.makedirs("videos", exist_ok=True)
34
+
35
+ @spaces.GPU
36
+ def generate_video(positive_prompt, negative_prompt, guidance_scale, bias, step, frames, seed, progress=gr.Progress(track_tqdm=False)):
37
+ lambda total: progress.tqdm(range(total))
38
+
39
+ print(f"Generating video with params: {positive_prompt}, {negative_prompt}, {guidance_scale}, {bias}, {step}, {frames}")
40
+ pipe.set_adapters("lora", 0.6)
41
+ prompt = positive_prompt
42
+ neg_prompt = negative_prompt
43
+
44
+ neg_prompt_embeds, _ = pipe.encode_prompt(
45
+ prompt=neg_prompt,
46
+ padding=False,
47
+ do_classifier_free_guidance=False,
48
+ )
49
+
50
+ pos_prompt_embeds, _ = pipe.encode_prompt(
51
+ prompt=prompt,
52
+ do_classifier_free_guidance=False,
53
+ max_sequence_length=512 - neg_prompt_embeds.shape[1],
54
+ )
55
+
56
+ neg_len = neg_prompt_embeds.shape[1]
57
+ pos_len = pos_prompt_embeds.shape[1]
58
+ print(neg_len, pos_len)
59
+
60
+
61
+ img_len = (height//8) * (width//8) * 3 * (frames // 4 + 1) // 12
62
+ print(img_len)
63
+ mask = torch.zeros((1, img_len, pos_len+neg_len)).cuda()
64
+ # mask[:, :, -neg_len:] = -torch.inf # this should be negative
65
+ mask[:, :, -neg_len:] = bias
66
+
67
+ for block in pipe.transformer.blocks:
68
+ block.attn2.processor = WanAttnProcessor2_0(scale=guidance_scale, neg_prompt_length=neg_len, attn_mask=mask)
69
+
70
+ prompt_embeds = torch.cat([pos_prompt_embeds, neg_prompt_embeds], dim=1)
71
+
72
+ output = pipe(
73
+ prompt_embeds=prompt_embeds,
74
+ negative_prompt=neg_prompt,
75
+ height=height,
76
+ width=width,
77
+ num_frames=frames,
78
+ num_inference_steps=step,
79
+ guidance_scale=0.0,
80
+ generator=torch.Generator(device="cuda").manual_seed(seed),
81
+ ).frames[0]
82
+ path = f"videos/{uuid.uuid4().hex}.mp4"
83
+ export_to_video(output[5:], path, fps=15)
84
+ output_path = path
85
+ with open(output_path.replace(".mp4", ".txt"), "w") as f:
86
+ f.write(f"Positive Prompt: {positive_prompt}\n")
87
+ f.write(f"Negative Prompt: {negative_prompt}\n")
88
+ f.write(f"Guidance Scale: {guidance_scale}\n")
89
+ f.write(f"Bias: {bias}\n")
90
+ f.write(f"Steps: {step}\n")
91
+ f.write(f"Frames: {frames}\n")
92
+ f.write(f"Seed: {seed}\n")
93
+ print(f"Video saved to {output_path}")
94
+ return output_path
95
+
96
+
97
+ with gr.Blocks(title="Value Sign Flip Wan 2.1 Demo") as demo:
98
+ gr.Markdown("# Value Sign Flip Wan 2.1 Demo \n All videos generated are saved and might be used as demo videos in the future. \n\n This demo is based on Wan 2.1 T2V model and uses Value Sign Flip technique to generate videos with different guidance scales and biases. More on [GitHub](https://github.com/weathon/VSF/blob/main/wan.md)")
99
+
100
+ with gr.Row():
101
+ pos = gr.Textbox(label="Positive Prompt", value="A chef cat and a chef dog with chef suit baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon.")
102
+ neg = gr.Textbox(label="Negative Prompt", value="white dog")
103
+
104
+ with gr.Row():
105
+ guidance = gr.Slider(0, 5, step=0.1, label="Guidance Scale", value=1.5)
106
+ bias = gr.Slider(0, 0.5, step=0.01, label="Bias", value=0.1)
107
+ step = gr.Slider(6, 15, step=1, label="Step", value=10)
108
+ frames = gr.Slider(31, 81, step=1, label="Frames", value=81)
109
+ seed = gr.Number(label="Seed", value=0, precision=0)
110
+
111
+ out = gr.Video(label="Generated Video")
112
+
113
+ btn = gr.Button("Generate")
114
+ btn.click(fn=generate_video, inputs=[pos, neg, guidance, bias, step, frames, seed], outputs=out)
115
+
116
+ demo.launch()
vsfwan/__init__.py ADDED
File without changes
vsfwan/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (130 Bytes). View file
 
vsfwan/__pycache__/pipeline.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
vsfwan/__pycache__/processor.cpython-310.pyc ADDED
Binary file (2.91 kB). View file
 
vsfwan/main.ipynb ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "b53f5b58",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "data": {
11
+ "application/vnd.jupyter.widget-view+json": {
12
+ "model_id": "e3c8361d88484d9984ecd3746399940f",
13
+ "version_major": 2,
14
+ "version_minor": 0
15
+ },
16
+ "text/plain": [
17
+ "Loading pipeline components...: 0%| | 0/5 [00:00<?, ?it/s]"
18
+ ]
19
+ },
20
+ "metadata": {},
21
+ "output_type": "display_data"
22
+ },
23
+ {
24
+ "data": {
25
+ "application/vnd.jupyter.widget-view+json": {
26
+ "model_id": "d82356db6da94c5cb78b8f5681f87304",
27
+ "version_major": 2,
28
+ "version_minor": 0
29
+ },
30
+ "text/plain": [
31
+ "Loading checkpoint shards: 0%| | 0/2 [00:00<?, ?it/s]"
32
+ ]
33
+ },
34
+ "metadata": {},
35
+ "output_type": "display_data"
36
+ },
37
+ {
38
+ "data": {
39
+ "application/vnd.jupyter.widget-view+json": {
40
+ "model_id": "5052153c971542aa9dc0a9561f040bc5",
41
+ "version_major": 2,
42
+ "version_minor": 0
43
+ },
44
+ "text/plain": [
45
+ "Loading checkpoint shards: 0%| | 0/5 [00:00<?, ?it/s]"
46
+ ]
47
+ },
48
+ "metadata": {},
49
+ "output_type": "display_data"
50
+ }
51
+ ],
52
+ "source": [
53
+ "import torch\n",
54
+ "from diffusers import AutoencoderKLWan\n",
55
+ "from pipeline import WanPipeline\n",
56
+ "from diffusers.utils import export_to_video\n",
57
+ "\n",
58
+ "model_id = \"Wan-AI/Wan2.1-T2V-1.3B-Diffusers\"\n",
59
+ "vae = AutoencoderKLWan.from_pretrained(model_id, subfolder=\"vae\", torch_dtype=torch.float32)\n",
60
+ "pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)\n",
61
+ "pipe.load_lora_weights(\n",
62
+ " \"Kijai/WanVideo_comfy\",\n",
63
+ " weight_name=\"Wan21_CausVid_bidirect2_T2V_1_3B_lora_rank32.safetensors\",\n",
64
+ " adapter_name=\"lora\"\n",
65
+ ") \n",
66
+ "pipe = pipe.to(\"cuda\")"
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "execution_count": 20,
72
+ "id": "cc3c8947",
73
+ "metadata": {},
74
+ "outputs": [
75
+ {
76
+ "name": "stdout",
77
+ "output_type": "stream",
78
+ "text": [
79
+ "False\n",
80
+ "True\n",
81
+ "2 510\n",
82
+ "32760\n"
83
+ ]
84
+ },
85
+ {
86
+ "name": "stderr",
87
+ "output_type": "stream",
88
+ "text": [
89
+ "`num_frames - 1` has to be divisible by 4. Rounding to the nearest number.\n"
90
+ ]
91
+ },
92
+ {
93
+ "data": {
94
+ "application/vnd.jupyter.widget-view+json": {
95
+ "model_id": "2f9f2e39d9584aab8cc0f27e4f061dc1",
96
+ "version_major": 2,
97
+ "version_minor": 0
98
+ },
99
+ "text/plain": [
100
+ " 0%| | 0/12 [00:00<?, ?it/s]"
101
+ ]
102
+ },
103
+ "metadata": {},
104
+ "output_type": "display_data"
105
+ },
106
+ {
107
+ "name": "stderr",
108
+ "output_type": "stream",
109
+ "text": [
110
+ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n",
111
+ "To disable this warning, you can either:\n",
112
+ "\t- Avoid using `tokenizers` before the fork if possible\n",
113
+ "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"
114
+ ]
115
+ },
116
+ {
117
+ "data": {
118
+ "text/plain": [
119
+ "'vsf.mp4'"
120
+ ]
121
+ },
122
+ "execution_count": 20,
123
+ "metadata": {},
124
+ "output_type": "execute_result"
125
+ }
126
+ ],
127
+ "source": [
128
+ "from processor import WanAttnProcessor2_0\n",
129
+ "\n",
130
+ "# prompt = \"A chef 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 cat is wearing a chef suit\"\n",
131
+ "# neg_prompt = \"chef hat\"\n",
132
+ "prompt = \"A cessna flying over a snowy mountain landscape, with a clear blue sky and fluffy white clouds. The plane is flying at a low altitude, casting a shadow on the snow-covered ground below. The mountains are rugged and steep, with patches of evergreen trees visible in the foreground.\"\n",
133
+ "neg_prompt = \"trees\"\n",
134
+ "\n",
135
+ "neg_prompt_embeds, _ = pipe.encode_prompt(\n",
136
+ " prompt=neg_prompt,\n",
137
+ " padding=False,\n",
138
+ " do_classifier_free_guidance=False,\n",
139
+ ")\n",
140
+ "\n",
141
+ "pos_prompt_embeds, _ = pipe.encode_prompt( \n",
142
+ " prompt=prompt,\n",
143
+ " do_classifier_free_guidance=False, \n",
144
+ " max_sequence_length=512 - neg_prompt_embeds.shape[1],\n",
145
+ ")\n",
146
+ "pipe.set_adapters(\"lora\", 0.5)\n",
147
+ "\n",
148
+ "\n",
149
+ "\n",
150
+ "neg_len = neg_prompt_embeds.shape[1]\n",
151
+ "pos_len = pos_prompt_embeds.shape[1]\n",
152
+ "print(neg_len, pos_len)\n",
153
+ "height = 480\n",
154
+ "width = 832\n",
155
+ "frames = 81\n",
156
+ "\n",
157
+ "img_len = (height//8) * (width//8) * 3 * (frames // 4 + 1) // 12\n",
158
+ "print(img_len)\n",
159
+ "mask = torch.zeros((1, img_len, pos_len+neg_len)).cuda()\n",
160
+ "mask[:, :, -neg_len:] = -torch.inf # this should be negative -torch.inf #\n",
161
+ "# mask[:, :, -neg_len:] = -0.2 # this should be negative -torch.inf #\n",
162
+ "\n",
163
+ "for block in pipe.transformer.blocks:\n",
164
+ " block.attn2.processor = WanAttnProcessor2_0(scale=1.7, neg_prompt_length=neg_len, attn_mask=mask)\n",
165
+ "# should we still do exploation in space \n",
166
+ "\n",
167
+ "prompt_embeds = torch.cat([pos_prompt_embeds, neg_prompt_embeds], dim=1)\n",
168
+ "\n",
169
+ "output = pipe(\n",
170
+ " prompt_embeds=prompt_embeds,\n",
171
+ " # prompt_embeds=pos_prompt_embeds,\n",
172
+ " negative_prompt=neg_prompt,\n",
173
+ " height=height,\n",
174
+ " width=width,\n",
175
+ " num_frames=frames + 1,\n",
176
+ " num_inference_steps=12,\n",
177
+ " guidance_scale=0.0, \n",
178
+ " generator=torch.Generator(device=\"cuda\").manual_seed(42),\n",
179
+ ").frames[0]\n",
180
+ "export_to_video(output, \"vsf.mp4\", fps=15)\n"
181
+ ]
182
+ }
183
+ ],
184
+ "metadata": {
185
+ "kernelspec": {
186
+ "display_name": "neg",
187
+ "language": "python",
188
+ "name": "python3"
189
+ },
190
+ "language_info": {
191
+ "codemirror_mode": {
192
+ "name": "ipython",
193
+ "version": 3
194
+ },
195
+ "file_extension": ".py",
196
+ "mimetype": "text/x-python",
197
+ "name": "python",
198
+ "nbconvert_exporter": "python",
199
+ "pygments_lexer": "ipython3",
200
+ "version": "3.10.17"
201
+ }
202
+ },
203
+ "nbformat": 4,
204
+ "nbformat_minor": 5
205
+ }
vsfwan/pipeline.py ADDED
@@ -0,0 +1,612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
23
+ from diffusers.loaders import WanLoraLoaderMixin
24
+ from diffusers.models import AutoencoderKLWan, WanTransformer3DModel
25
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
26
+ from diffusers.utils import is_ftfy_available, is_torch_xla_available, logging, replace_example_docstring
27
+ from diffusers.utils.torch_utils import randn_tensor
28
+ from diffusers.video_processor import VideoProcessor
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ from diffusers.pipelines.wan.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
+ """
116
+
117
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
118
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
119
+
120
+ def __init__(
121
+ self,
122
+ tokenizer: AutoTokenizer,
123
+ text_encoder: UMT5EncoderModel,
124
+ transformer: WanTransformer3DModel,
125
+ vae: AutoencoderKLWan,
126
+ scheduler: FlowMatchEulerDiscreteScheduler,
127
+ ):
128
+ super().__init__()
129
+
130
+ self.register_modules(
131
+ vae=vae,
132
+ text_encoder=text_encoder,
133
+ tokenizer=tokenizer,
134
+ transformer=transformer,
135
+ scheduler=scheduler,
136
+ )
137
+
138
+ self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
139
+ self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
140
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
141
+
142
+ def _get_t5_prompt_embeds(
143
+ self,
144
+ prompt: Union[str, List[str]] = None,
145
+ num_videos_per_prompt: int = 1,
146
+ max_sequence_length: int = 226,
147
+ device: Optional[torch.device] = None,
148
+ dtype: Optional[torch.dtype] = None,
149
+ padding: bool = True,
150
+ ):
151
+ device = device or self._execution_device
152
+ dtype = dtype or self.text_encoder.dtype
153
+
154
+ prompt = [prompt] if isinstance(prompt, str) else prompt
155
+ prompt = [prompt_clean(u) for u in prompt]
156
+ batch_size = len(prompt)
157
+ print(padding)
158
+ text_inputs = self.tokenizer(
159
+ prompt,
160
+ padding="max_length" if padding else False,
161
+ max_length=max_sequence_length,
162
+ truncation=True,
163
+ add_special_tokens=True,
164
+ return_attention_mask=True,
165
+ return_tensors="pt",
166
+ )
167
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
168
+ seq_lens = mask.gt(0).sum(dim=1).long()
169
+
170
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
171
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
172
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
173
+ if padding:
174
+ prompt_embeds = torch.stack(
175
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
176
+ )
177
+ else:
178
+ prompt_embeds = torch.stack(
179
+ [torch.cat([u]) for u in prompt_embeds], dim=0
180
+ )
181
+
182
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
183
+ _, seq_len, _ = prompt_embeds.shape
184
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
185
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
186
+
187
+ return prompt_embeds
188
+
189
+ def encode_prompt(
190
+ self,
191
+ prompt: Union[str, List[str]],
192
+ negative_prompt: Optional[Union[str, List[str]]] = None,
193
+ do_classifier_free_guidance: bool = True,
194
+ num_videos_per_prompt: int = 1,
195
+ prompt_embeds: Optional[torch.Tensor] = None,
196
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
197
+ max_sequence_length: int = 226,
198
+ device: Optional[torch.device] = None,
199
+ dtype: Optional[torch.dtype] = None,
200
+ padding: bool = True,
201
+ ):
202
+ r"""
203
+ Encodes the prompt into text encoder hidden states.
204
+
205
+ Args:
206
+ prompt (`str` or `List[str]`, *optional*):
207
+ prompt to be encoded
208
+ negative_prompt (`str` or `List[str]`, *optional*):
209
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
210
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
211
+ less than `1`).
212
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
213
+ Whether to use classifier free guidance or not.
214
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
215
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
216
+ prompt_embeds (`torch.Tensor`, *optional*):
217
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
218
+ provided, text embeddings will be generated from `prompt` input argument.
219
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
220
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
221
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
222
+ argument.
223
+ device: (`torch.device`, *optional*):
224
+ torch device
225
+ dtype: (`torch.dtype`, *optional*):
226
+ torch dtype
227
+ """
228
+ device = device or self._execution_device
229
+
230
+ prompt = [prompt] if isinstance(prompt, str) else prompt
231
+ if prompt is not None:
232
+ batch_size = len(prompt)
233
+ else:
234
+ batch_size = prompt_embeds.shape[0]
235
+
236
+ if prompt_embeds is None:
237
+ prompt_embeds = self._get_t5_prompt_embeds(
238
+ prompt=prompt,
239
+ num_videos_per_prompt=num_videos_per_prompt,
240
+ max_sequence_length=max_sequence_length,
241
+ device=device,
242
+ dtype=dtype,
243
+ padding=padding
244
+ )
245
+
246
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
247
+ negative_prompt = negative_prompt or ""
248
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
249
+
250
+ if prompt is not None and type(prompt) is not type(negative_prompt):
251
+ raise TypeError(
252
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
253
+ f" {type(prompt)}."
254
+ )
255
+ elif batch_size != len(negative_prompt):
256
+ raise ValueError(
257
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
258
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
259
+ " the batch size of `prompt`."
260
+ )
261
+
262
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
263
+ prompt=negative_prompt,
264
+ num_videos_per_prompt=num_videos_per_prompt,
265
+ max_sequence_length=max_sequence_length,
266
+ device=device,
267
+ dtype=dtype,
268
+ )
269
+
270
+ return prompt_embeds, negative_prompt_embeds
271
+
272
+ def check_inputs(
273
+ self,
274
+ prompt,
275
+ negative_prompt,
276
+ height,
277
+ width,
278
+ prompt_embeds=None,
279
+ negative_prompt_embeds=None,
280
+ callback_on_step_end_tensor_inputs=None,
281
+ ):
282
+ if height % 16 != 0 or width % 16 != 0:
283
+ raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
284
+
285
+ if callback_on_step_end_tensor_inputs is not None and not all(
286
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
287
+ ):
288
+ raise ValueError(
289
+ 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]}"
290
+ )
291
+
292
+ if prompt is not None and prompt_embeds is not None:
293
+ raise ValueError(
294
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
295
+ " only forward one of the two."
296
+ )
297
+ elif negative_prompt is not None and negative_prompt_embeds is not None:
298
+ raise ValueError(
299
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
300
+ " only forward one of the two."
301
+ )
302
+ elif prompt is None and prompt_embeds is None:
303
+ raise ValueError(
304
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
305
+ )
306
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
307
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
308
+ elif negative_prompt is not None and (
309
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
310
+ ):
311
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
312
+
313
+ def prepare_latents(
314
+ self,
315
+ batch_size: int,
316
+ num_channels_latents: int = 16,
317
+ height: int = 480,
318
+ width: int = 832,
319
+ num_frames: int = 81,
320
+ dtype: Optional[torch.dtype] = None,
321
+ device: Optional[torch.device] = None,
322
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
323
+ latents: Optional[torch.Tensor] = None,
324
+ ) -> torch.Tensor:
325
+ if latents is not None:
326
+ return latents.to(device=device, dtype=dtype)
327
+
328
+ num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
329
+ shape = (
330
+ batch_size,
331
+ num_channels_latents,
332
+ num_latent_frames,
333
+ int(height) // self.vae_scale_factor_spatial,
334
+ int(width) // self.vae_scale_factor_spatial,
335
+ )
336
+ if isinstance(generator, list) and len(generator) != batch_size:
337
+ raise ValueError(
338
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
339
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
340
+ )
341
+
342
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
343
+ return latents
344
+
345
+ @property
346
+ def guidance_scale(self):
347
+ return self._guidance_scale
348
+
349
+ @property
350
+ def do_classifier_free_guidance(self):
351
+ return self._guidance_scale > 1.0
352
+
353
+ @property
354
+ def num_timesteps(self):
355
+ return self._num_timesteps
356
+
357
+ @property
358
+ def current_timestep(self):
359
+ return self._current_timestep
360
+
361
+ @property
362
+ def interrupt(self):
363
+ return self._interrupt
364
+
365
+ @property
366
+ def attention_kwargs(self):
367
+ return self._attention_kwargs
368
+
369
+ @torch.no_grad()
370
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
371
+ def __call__(
372
+ self,
373
+ prompt: Union[str, List[str]] = None,
374
+ negative_prompt: Union[str, List[str]] = None,
375
+ height: int = 480,
376
+ width: int = 832,
377
+ num_frames: int = 81,
378
+ num_inference_steps: int = 50,
379
+ guidance_scale: float = 5.0,
380
+ num_videos_per_prompt: Optional[int] = 1,
381
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
382
+ latents: Optional[torch.Tensor] = None,
383
+ prompt_embeds: Optional[torch.Tensor] = None,
384
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
385
+ output_type: Optional[str] = "np",
386
+ return_dict: bool = True,
387
+ attention_kwargs: Optional[Dict[str, Any]] = None,
388
+ callback_on_step_end: Optional[
389
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
390
+ ] = None,
391
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
392
+ max_sequence_length: int = 512,
393
+ ):
394
+ r"""
395
+ The call function to the pipeline for generation.
396
+
397
+ Args:
398
+ prompt (`str` or `List[str]`, *optional*):
399
+ The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
400
+ negative_prompt (`str` or `List[str]`, *optional*):
401
+ The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
402
+ instead. Ignored when not using guidance (`guidance_scale` < `1`).
403
+ height (`int`, defaults to `480`):
404
+ The height in pixels of the generated image.
405
+ width (`int`, defaults to `832`):
406
+ The width in pixels of the generated image.
407
+ num_frames (`int`, defaults to `81`):
408
+ The number of frames in the generated video.
409
+ num_inference_steps (`int`, defaults to `50`):
410
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
411
+ expense of slower inference.
412
+ guidance_scale (`float`, defaults to `5.0`):
413
+ Guidance scale as defined in [Classifier-Free Diffusion
414
+ Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
415
+ of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
416
+ `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
417
+ the text `prompt`, usually at the expense of lower image quality.
418
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
419
+ The number of images to generate per prompt.
420
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
421
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
422
+ generation deterministic.
423
+ latents (`torch.Tensor`, *optional*):
424
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
425
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
426
+ tensor is generated by sampling using the supplied random `generator`.
427
+ prompt_embeds (`torch.Tensor`, *optional*):
428
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
429
+ provided, text embeddings are generated from the `prompt` input argument.
430
+ output_type (`str`, *optional*, defaults to `"np"`):
431
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
432
+ return_dict (`bool`, *optional*, defaults to `True`):
433
+ Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
434
+ attention_kwargs (`dict`, *optional*):
435
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
436
+ `self.processor` in
437
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
438
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
439
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
440
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
441
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
442
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
443
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
444
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
445
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
446
+ `._callback_tensor_inputs` attribute of your pipeline class.
447
+ max_sequence_length (`int`, defaults to `512`):
448
+ The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
449
+ truncated. If the prompt is shorter, it will be padded to this length.
450
+
451
+ Examples:
452
+
453
+ Returns:
454
+ [`~WanPipelineOutput`] or `tuple`:
455
+ If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
456
+ the first element is a list with the generated images and the second element is a list of `bool`s
457
+ indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
458
+ """
459
+
460
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
461
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
462
+
463
+ # 1. Check inputs. Raise error if not correct
464
+ self.check_inputs(
465
+ prompt,
466
+ negative_prompt,
467
+ height,
468
+ width,
469
+ prompt_embeds,
470
+ negative_prompt_embeds,
471
+ callback_on_step_end_tensor_inputs,
472
+ )
473
+
474
+ if num_frames % self.vae_scale_factor_temporal != 1:
475
+ logger.warning(
476
+ f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
477
+ )
478
+ num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
479
+ num_frames = max(num_frames, 1)
480
+
481
+ self._guidance_scale = guidance_scale
482
+ self._attention_kwargs = attention_kwargs
483
+ self._current_timestep = None
484
+ self._interrupt = False
485
+
486
+ device = self._execution_device
487
+
488
+ # 2. Define call parameters
489
+ if prompt is not None and isinstance(prompt, str):
490
+ batch_size = 1
491
+ elif prompt is not None and isinstance(prompt, list):
492
+ batch_size = len(prompt)
493
+ else:
494
+ batch_size = prompt_embeds.shape[0]
495
+
496
+ # 3. Encode input prompt
497
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
498
+ prompt=prompt,
499
+ negative_prompt=negative_prompt,
500
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
501
+ num_videos_per_prompt=num_videos_per_prompt,
502
+ prompt_embeds=prompt_embeds,
503
+ negative_prompt_embeds=negative_prompt_embeds,
504
+ max_sequence_length=max_sequence_length,
505
+ device=device,
506
+ )
507
+
508
+ transformer_dtype = self.transformer.dtype
509
+ prompt_embeds = prompt_embeds.to(transformer_dtype)
510
+ if negative_prompt_embeds is not None:
511
+ negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
512
+
513
+ # 4. Prepare timesteps
514
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
515
+ timesteps = self.scheduler.timesteps
516
+
517
+ # 5. Prepare latent variables
518
+ num_channels_latents = self.transformer.config.in_channels
519
+ latents = self.prepare_latents(
520
+ batch_size * num_videos_per_prompt,
521
+ num_channels_latents,
522
+ height,
523
+ width,
524
+ num_frames,
525
+ torch.float32,
526
+ device,
527
+ generator,
528
+ latents,
529
+ )
530
+
531
+ # 6. Denoising loop
532
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
533
+ self._num_timesteps = len(timesteps)
534
+
535
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
536
+ for i, t in enumerate(timesteps):
537
+ if self.interrupt:
538
+ continue
539
+
540
+ self._current_timestep = t
541
+ latent_model_input = latents.to(transformer_dtype)
542
+ timestep = t.expand(latents.shape[0])
543
+ for block in self.transformer.blocks:
544
+ if hasattr(block.attn2, "processor"):
545
+ block.attn2.processor.pos = True
546
+
547
+ noise_pred = self.transformer(
548
+ hidden_states=latent_model_input,
549
+ timestep=timestep,
550
+ encoder_hidden_states=prompt_embeds,
551
+ attention_kwargs=attention_kwargs,
552
+ return_dict=False,
553
+ )[0]
554
+
555
+ if self.do_classifier_free_guidance:
556
+ for block in self.transformer.blocks:
557
+ if hasattr(block.attn2, "processor"):
558
+ block.attn2.processor.pos = False
559
+ noise_uncond = self.transformer(
560
+ hidden_states=latent_model_input,
561
+ timestep=timestep,
562
+ encoder_hidden_states=negative_prompt_embeds,
563
+ attention_kwargs=attention_kwargs,
564
+ return_dict=False,
565
+ )[0]
566
+ noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
567
+
568
+ # compute the previous noisy sample x_t -> x_t-1
569
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
570
+
571
+ if callback_on_step_end is not None:
572
+ callback_kwargs = {}
573
+ for k in callback_on_step_end_tensor_inputs:
574
+ callback_kwargs[k] = locals()[k]
575
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
576
+
577
+ latents = callback_outputs.pop("latents", latents)
578
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
579
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
580
+
581
+ # call the callback, if provided
582
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
583
+ progress_bar.update()
584
+
585
+ if XLA_AVAILABLE:
586
+ xm.mark_step()
587
+
588
+ self._current_timestep = None
589
+
590
+ if not output_type == "latent":
591
+ latents = latents.to(self.vae.dtype)
592
+ latents_mean = (
593
+ torch.tensor(self.vae.config.latents_mean)
594
+ .view(1, self.vae.config.z_dim, 1, 1, 1)
595
+ .to(latents.device, latents.dtype)
596
+ )
597
+ latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
598
+ latents.device, latents.dtype
599
+ )
600
+ latents = latents / latents_std + latents_mean
601
+ video = self.vae.decode(latents, return_dict=False)[0]
602
+ video = self.video_processor.postprocess_video(video, output_type=output_type)
603
+ else:
604
+ video = latents
605
+
606
+ # Offload all models
607
+ self.maybe_free_model_hooks()
608
+
609
+ if not return_dict:
610
+ return (video,)
611
+
612
+ return WanPipelineOutput(frames=video)
vsfwan/processor.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import torch.nn.functional as F
4
+ from typing import Optional
5
+ from diffusers.models.attention_processor import Attention
6
+
7
+ class WanAttnProcessor2_0:
8
+ def __init__(self, scale=4, attn_mask=None, neg_prompt_length=0):
9
+ if not hasattr(F, "scaled_dot_product_attention"):
10
+ raise ImportError("WanAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
11
+ self.attn_mask = attn_mask
12
+ self.neg_prompt_length = neg_prompt_length
13
+ self.scale = scale
14
+
15
+ def __call__(
16
+ self,
17
+ attn: Attention,
18
+ hidden_states: torch.Tensor,
19
+ encoder_hidden_states: Optional[torch.Tensor] = None,
20
+ attention_mask: Optional[torch.Tensor] = None,
21
+ rotary_emb: Optional[torch.Tensor] = None,
22
+ ) -> torch.Tensor:
23
+ encoder_hidden_states_img = None
24
+ if attn.add_k_proj is not None:
25
+ # 512 is the context length of the text encoder, hardcoded for now
26
+ image_context_length = encoder_hidden_states.shape[1] - 512
27
+ encoder_hidden_states_img = encoder_hidden_states[:, :image_context_length]
28
+ encoder_hidden_states = encoder_hidden_states[:, image_context_length:]
29
+ cross_attn = False
30
+ if encoder_hidden_states is None:
31
+ encoder_hidden_states = hidden_states
32
+ query = attn.to_q(hidden_states)
33
+ key = attn.to_k(encoder_hidden_states)
34
+ value = attn.to_v(encoder_hidden_states)
35
+ else:
36
+ query = attn.to_q(hidden_states)
37
+ key = attn.to_k(encoder_hidden_states)
38
+ value = attn.to_v(encoder_hidden_states)
39
+ cross_attn = True
40
+
41
+ if cross_attn and self.pos:
42
+ # print(value.shape, self.neg_prompt_length)
43
+ value[:,-self.neg_prompt_length:] *= -self.scale # should we flip before
44
+
45
+ if attn.norm_q is not None:
46
+ query = attn.norm_q(query)
47
+ if attn.norm_k is not None:
48
+ key = attn.norm_k(key)
49
+
50
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
51
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
52
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
53
+ # print(self.pos)
54
+
55
+ if rotary_emb is not None:
56
+ def apply_rotary_emb(
57
+ hidden_states: torch.Tensor,
58
+ freqs_cos: torch.Tensor,
59
+ freqs_sin: torch.Tensor,
60
+ ):
61
+ x = hidden_states.view(*hidden_states.shape[:-1], -1, 2)
62
+ x1, x2 = x[..., 0], x[..., 1]
63
+ cos = freqs_cos[..., 0::2]
64
+ sin = freqs_sin[..., 1::2]
65
+ out = torch.empty_like(hidden_states)
66
+ out[..., 0::2] = x1 * cos - x2 * sin
67
+ out[..., 1::2] = x1 * sin + x2 * cos
68
+ return out.type_as(hidden_states)
69
+
70
+ query = apply_rotary_emb(query, *rotary_emb)
71
+ key = apply_rotary_emb(key, *rotary_emb)
72
+
73
+ # I2V task
74
+ hidden_states_img = None
75
+ if encoder_hidden_states_img is not None:
76
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
77
+ key_img = attn.norm_added_k(key_img)
78
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
79
+
80
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
81
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
82
+ print(query.shape, key_img.shape, value_img.shape)
83
+ hidden_states_img = F.scaled_dot_product_attention(
84
+ query, key_img, value_img, attn_mask=None, dropout_p=0.0, is_causal=False
85
+ )
86
+ hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
87
+ hidden_states_img = hidden_states_img.type_as(query)
88
+
89
+ if self.attn_mask is not None:
90
+ self.attn_mask = self.attn_mask.to(query.dtype)
91
+ if not self.pos:
92
+ hidden_states = F.scaled_dot_product_attention(
93
+ query, key, value, dropout_p=0.0, is_causal=False
94
+ )
95
+ else:
96
+ hidden_states = F.scaled_dot_product_attention(
97
+ query, key, value, attn_mask=self.attn_mask, dropout_p=0.0, is_causal=False
98
+ )
99
+ # if cross_attn:
100
+ # # print(hidden_states.shape)
101
+ # hidden_states_norm = torch.norm(hidden_states, dim=-1, keepdim=True)
102
+ # new_norm = torch.where(hidden_states_norm > max_norm * 2, max_norm * 2, hidden_states_norm)
103
+ # hidden_states = hidden_states * (new_norm / hidden_states_norm)
104
+
105
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
106
+ hidden_states = hidden_states.type_as(query)
107
+
108
+ if hidden_states_img is not None:
109
+ hidden_states = hidden_states + hidden_states_img
110
+
111
+ hidden_states = attn.to_out[0](hidden_states)
112
+ hidden_states = attn.to_out[1](hidden_states)
113
+ return hidden_states