Python
merged doc
DeepBeepMeepa669de3d8281
diff --cc README.mdindex 3b7fbd5,1158458..bd9a1aa--- a/README.md+++ b/README.md@@@ -15,144 -15,44 +15,48 @@@ WanGP supports the Wan (and derived mod- Loras Support to customize each model- Queuing system : make your shopping list of videos to generate and come back later-**Discord Server to get Help from Other Users and show your Best Videos:** https://discord.gg/g7efUW9jGV+ ## π₯ Latest Updates++### May 28 2025: WanGP v5.4++π World Exclusive : Hunyuan Video Avatar Support ! You won't need 80 GB of VRAM nor 32 GB oF VRAM, just 10 GB of VRAM will be sufficient to generate up to 15s of high quality speech / song driven Video at a high speed with no quality degradation. Support for TeaCache included.\++Also many thanks to Reevoy24 for his repackaging / completing the documentation++ ### May 28 2025: WanGP v5.31+ π Added Phantom 14B, a model that you can use to transfer objects / people in the video. My preference goes to Vace that remains the king of controlnets.+ VACE improvements: Better sliding window transitions, image mask support in Matanyone, new Extend Video feature, and enhanced background removal options.- ## π₯ Latest News!!- * May 28 2025: π WanGP v5.31 : Added Phantom 14B, a model that you can use to transfer objects / people in the video. My preference goes to Vace that remains the king of controlnets.- * May 26 2025: π WanGP v5.3 : Happy with a Video generation and want to do more generations using the same settings but you can't remember what you did or you find it to hard to copy / paste one per one each setting from the file metadata ? Rejoice ! There are now multiple ways to turn this tedious process into a one click task:- - Select one Video recently generated in the Video Gallery and click *Use Selected Video Settings*- - Click *Drop File Here* and select a Video you saved somewhere, if the settings metadata have been saved with the Video you will be able to extract them automatically- - Click *Export Settings to File* to save on your harddrive the current settings. You will be able to use them later again by clicking *Drop File Here* and select this time a Settings json file- * May 23 2025: π WanGP v5.21 : Improvements for Vace: better transitions between Sliding Windows,Support for Image masks in Matanyone, new Extend Video for Vace, different types of automated background removal- * May 20 2025: π WanGP v5.2 : Added support for Wan CausVid which is a distilled Wan model that can generate nice looking videos in only 4 to 12 steps.- The great thing is that Kijai (Kudos to him !) has created a CausVid Lora that can be combined with any existing Wan t2v model 14B like Wan Vace 14B.- See instructions below on how to use CausVid.\- Also as an experiment I have added support for the MoviiGen, the first model that claims to capable to generate 1080p videos (if you have enough VRAM (20GB...) and be ready to wait for a long time...). Don't hesitate to share your impressions on the Discord server.- * May 18 2025: π WanGP v5.1 : Bonus Day, added LTX Video 13B Distilled: generate in less than one minute, very high quality Videos !- * May 17 2025: π WanGP v5.0 : One App to Rule Them All !\- Added support for the other great open source architectures:- - Hunyuan Video : text 2 video (one of the best, if not the best t2v) ,image 2 video and the recently released Hunyuan Custom (very good identify preservation when injecting a person into a video)- - LTX Video 13B (released last week): very long video support and fast 720p generation.Wan GP version has been greatly optimzed and reduced LTX Video VRAM requirements by 4 !-- Also:- - Added supported for the best Control Video Model, released 2 days ago : Vace 14B- - New Integrated prompt enhancer to increase the quality of the generated videos- You will need one more *pip install -r requirements.txt*-- * May 5 2025: π WanGP v4.5: FantasySpeaking model, you can animate a talking head using a voice track. This works not only on people but also on objects. Also better seamless transitions between Vace sliding windows for very long videos (see recommended settings). New high quality processing features (mixed 16/32 bits calculation and 32 bitsVAE)- * April 27 2025: π WanGP v4.4: Phantom model support, very good model to transfer people or objects into video, works quite well at 720p and with the number of steps > 30- * April 25 2025: π WanGP v4.3: Added preview mode and support for Sky Reels v2 Diffusion Forcing for high quality "infinite length videos" (see Window Sliding section below).Note that Skyreel uses causal attention that is only supported by Sdpa attention so even if chose an other type of attention, some of the processes will use Sdpa attention.-- * April 18 2025: π WanGP v4.2: FLF2V model support, official support from Wan for image2video start and end frames specialized for 720p.- * April 17 2025: π WanGP v4.1: Recam Master model support, view a video from a different angle. The video to process must be at least 81 frames long and you should set at least 15 steps denoising to get good results.- * April 13 2025: π WanGP v4.0: lots of goodies for you !- - A new UI, tabs were replaced by a Dropdown box to easily switch models- - A new queuing system that lets you stack in a queue as many text2video, imag2video tasks, ... as you want. Each task can rely on complete different generation parameters (different number of frames, steps, loras, ...). Many thanks to **Tophness** for being a big contributor on this new feature- - Temporal upsampling (Rife) and spatial upsampling (Lanczos) for a smoother video (32 fps or 64 fps) and to enlarge your video by x2 or x4. Check these new advanced options.- - Wan Vace Control Net support : with Vace you can inject in the scene people or objects, animate a person, perform inpainting or outpainting, continue a video, ... I have provided an introduction guide below.- - Integrated *Matanyone* tool directly inside WanGP so that you can create easily inpainting masks used in Vace- - Sliding Window generation for Vace, create windows that can last dozen of seconds- - New optimisations for old generation GPUs: Generate 5s (81 frames, 15 steps) of Vace 1.3B with only 5GB and in only 6 minutes on a RTX 2080Ti and 5s of t2v 14B in less than 10 minutes.-- * Mar 27 2025: π Added support for the new Wan Fun InP models (image2video). The 14B Fun InP has probably better end image support but unfortunately existing loras do not work so well with it. The great novelty is the Fun InP image2 1.3B model : Image 2 Video is now accessible to even lower hardware configuration. It is not as good as the 14B models but very impressive for its size. You can choose any of those models in the Configuration tab. Many thanks to the VideoX-Fun team (https://github.com/aigc-apps/VideoX-Fun)- * Mar 26 2025: π Good news ! Official support for RTX 50xx please check the installation instructions below.- * Mar 24 2025: π Wan2.1GP v3.2:- - Added Classifier-Free Guidance Zero Star. The video should match better the text prompt (especially with text2video) at no performance cost: many thanks to the **CFG Zero * Team:**\- Dont hesitate to give them a star if you appreciate the results: https://github.com/WeichenFan/CFG-Zero-star- - Added back support for Pytorch compilation with Loras. It seems it had been broken for some time- - Added possibility to keep a number of pregenerated videos in the Video Gallery (useful to compare outputs of different settings)- You will need one more *pip install -r requirements.txt*- * Mar 19 2025: π Wan2.1GP v3.1: Faster launch and RAM optimizations (should require less RAM to run)\- You will need one more *pip install -r requirements.txt*- * Mar 18 2025: π Wan2.1GP v3.0:- - New Tab based interface, yon can switch from i2v to t2v conversely without restarting the app- - Experimental Dual Frames mode for i2v, you can also specify an End frame. It doesn't always work, so you will need a few attempts.- - You can save default settings in the files *i2v_settings.json* and *t2v_settings.json* that will be used when launching the app (you can also specify the path to different settings files)- - Slight acceleration with loras\- You will need one more *pip install -r requirements.txt*- Many thanks to *Tophness* who created the framework (and did a big part of the work) of the multitabs and saved settings features- * Mar 18 2025: π Wan2.1GP v2.11: Added more command line parameters to prefill the generation settings + customizable output directory and choice of type of metadata for generated videos. Many thanks to *Tophness* for his contributions. You will need one more *pip install -r requirements.txt* to reflect new dependencies\- * Mar 18 2025: π Wan2.1GP v2.1: More Loras !: added support for 'Safetensors' and 'Replicate' Lora formats.\- You will need to refresh the requirements with a *pip install -r requirements.txt*- * Mar 17 2025: π Wan2.1GP v2.0: The Lora festival continues:- - Clearer user interface- - Download 30 Loras in one click to try them all (expand the info section)- - Very to use Loras as now Lora presets can input the subject (or other need terms) of the Lora so that you dont have to modify manually a prompt- - Added basic macro prompt language to prefill prompts with differnent values. With one prompt template, you can generate multiple prompts.- - New Multiple images prompts: you can now combine any number of images with any number of text promtps (need to launch the app with --multiple-images)- - New command lines options to launch directly the 1.3B t2v model or the 14B t2v model- * Mar 14, 2025: π Wan2.1GP v1.7:- - Lora Fest special edition: very fast loading / unload of loras for those Loras collectors around. You can also now add / remove loras in the Lora folder without restarting the app. You will need to refresh the requirements *pip install -r requirements.txt*- - Added experimental Skip Layer Guidance (advanced settings), that should improve the image quality at no extra cost. Many thanks to the *AmericanPresidentJimmyCarter* for the original implementation- * Mar 13, 2025: π Wan2.1GP v1.6: Better Loras support, accelerated loading Loras. You will need to refresh the requirements *pip install -r requirements.txt*- * Mar 10, 2025: π Wan2.1GP v1.5: Official Teacache support + Smart Teacache (find automatically best parameters for a requested speed multiplier), 10% speed boost with no quality loss, improved lora presets (they can now include prompts and comments to guide the user)- * Mar 07, 2025: π Wan2.1GP v1.4: Fix Pytorch compilation, now it is really 20% faster when activated- * Mar 04, 2025: π Wan2.1GP v1.3: Support for Image to Video with multiples images for different images / prompts combinations (requires *--multiple-images* switch), and added command line *--preload x* to preload in VRAM x MB of the main diffusion model if you find there is too much unused VRAM and you want to (slightly) accelerate the generation process.- If you upgrade you will need to do a 'pip install -r requirements.txt' again.- * Mar 04, 2025: π Wan2.1GP v1.2: Implemented tiling on VAE encoding and decoding. No more VRAM peaks at the beginning and at the end- * Mar 03, 2025: π Wan2.1GP v1.1: added Tea Cache support for faster generations: optimization of kijai's implementation (https://github.com/kijai/ComfyUI-WanVideoWrapper/) of teacache (https://github.com/ali-vilab/TeaCache)- * Mar 02, 2025: π Wan2.1GP by DeepBeepMeep v1 brings:- - Support for all Wan including the Image to Video model- - Reduced memory consumption by 2, with possiblity to generate more than 10s of video at 720p with a RTX 4090 and 10s of video at 480p with less than 12GB of VRAM. Many thanks to REFLEx (https://github.com/thu-ml/RIFLEx) for their algorithm that allows generating nice looking video longer than 5s.- - The usual perks: web interface, multiple generations, loras support, sage attebtion, auto download of models, ...-- * Feb 25, 2025: π We've released the inference code and weights of Wan2.1.- * Feb 27, 2025: π Wan2.1 has been integrated into [ComfyUI](https://comfyanonymous.github.io/ComfyUI_examples/wan/). Enjoy!---- ## Installation Guide for Linux and Windows for GPUs up to RTX40xx-- **If you are looking for a one click installation, just go to the Pinokio App store : https://pinokio.computer/**\- Otherwise you will find the instructions below:-- This app has been tested on Python 3.10 / 2.6.0 / Cuda 12.4.-- ```shell- # 0 Download the source and create a Python 3.10.9 environment using conda or create a venv using python- git clone https://github.com/deepbeepmeep/Wan2GP.git- cd Wan2GP- conda create -n wan2gp python=3.10.9- conda activate wan2gp+ ### May 26, 2025: WanGP v5.3+ π Settings management revolution! Now you can:+ - Select any generated video and click *Use Selected Video Settings* to instantly reuse its configuration+ - Drag & drop videos to automatically extract their settings metadata+ - Export/import settings as JSON files for easy sharing and backup- # 1 Install pytorch 2.6.0- pip install torch==2.6.0 torchvision torchaudio --index-url https://download.pytorch.org/whl/test/cu124+ ### May 20, 2025: WanGP v5.2+ π **CausVid support** - Generate videos in just 4-12 steps with the new distilled Wan model! Also added experimental MoviiGen for 1080p generation (20GB+ VRAM required).- # 2. Install pip dependencies- pip install -r requirements.txt+ ### May 18, 2025: WanGP v5.1+ π **LTX Video 13B Distilled** - Generate high-quality videos in less than one minute!- # 3.1 optional Sage attention support (30% faster)- # Windows only: extra step only needed for windows as triton is included in pytorch with the Linux version of pytorch- pip install triton-windows- # For both Windows and Linux- pip install sageattention==1.0.6+ ### May 17, 2025: WanGP v5.0+ π **One App to Rule Them All!** Added Hunyuan Video and LTX Video support, plus Vace 14B and integrated prompt enhancer.+ See full changelog: **[Changelog](docs/CHANGELOG.md)**- # 3.2 optional Sage 2 attention support (40% faster)- # Windows only- pip install triton-windows- pip install https://github.com/woct0rdho/SageAttention/releases/download/v2.1.1-windows/sageattention-2.1.1+cu126torch2.6.0-cp310-cp310-win_amd64.whl- # Linux only (sorry only manual compilation for the moment, but is straight forward with Linux)- git clone https://github.com/thu-ml/SageAttention- cd SageAttention- pip install -e .+ ## π Table of Contents- # 3.3 optional Flash attention support (easy to install on Linux but may be complex on Windows as it will try to compile the cuda kernels)- pip install flash-attn==2.7.2.post1+ - [π Quick Start](#-quick-start)+ - [π¦ Installation](#-installation)+ - [π― Usage](#-usage)+ - [π Documentation](#-documentation)+ - [π Related Projects](#-related-projects)- ```+ ## π Quick Start- Note pytorch *sdpa attention* is available by default. It is worth installing *Sage attention* (albout not as simple as it sounds) because it offers a 30% speed boost over *sdpa attention* at a small quality cost.- In order to install Sage, you will need to install also Triton. If Triton is installed you can turn on *Pytorch Compilation* which will give you an additional 20% speed boost and reduced VRAM consumption.+ **One-click installation:** Get started instantly with [Pinokio App](https://pinokio.computer/)- ## Installation Guide for Linux and Windows for GPUs up to RTX50xx- RTX50XX are only supported by pytorch starting from pytorch 2.7.0 which is still in beta. Therefore this version may be less stable.\- It is important to use Python 3.10 otherwise the pip wheels may not be compatible.- ```- # 0 Download the source and create a Python 3.10.9 environment using conda or create a venv using python+ **Manual installation:**+ ```bashgit clone https://github.com/deepbeepmeep/Wan2GP.gitcd Wan2GPconda create -n wan2gp python=3.10.9diff --cc docs/CHANGELOG.mdindex 0000000,435ac7b..08a4baemode 000000,100644..100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@@ -1,0 -1,148 +1,150 @@@+ # Changelog++ ## π₯ Latest News++### May 28 2025: WanGP v5.4++π World Exclusive : Hunyuan Video Avatar Support ! You won't need 80 GB of VRAM nor 32 GB oF VRAM, just 10 GB of VRAM will be sufficient to generate up to 15s of high quality speech / song driven Video at a high speed with no quality degradation. Support for TeaCache included.+-### May 26, 2025: Wan 2.1GP v5.3++### May 26, 2025: WanGP v5.3+ π Happy with a Video generation and want to do more generations using the same settings but you can't remember what you did or you find it too hard to copy/paste one per one each setting from the file metadata? Rejoice! There are now multiple ways to turn this tedious process into a one click task:+ - Select one Video recently generated in the Video Gallery and click *Use Selected Video Settings*+ - Click *Drop File Here* and select a Video you saved somewhere, if the settings metadata have been saved with the Video you will be able to extract them automatically+ - Click *Export Settings to File* to save on your harddrive the current settings. You will be able to use them later again by clicking *Drop File Here* and select this time a Settings json file+-### May 23, 2025: Wan 2.1GP v5.21++### May 23, 2025: WanGP v5.21+ π Improvements for Vace: better transitions between Sliding Windows, Support for Image masks in Matanyone, new Extend Video for Vace, different types of automated background removal+-### May 20, 2025: Wan 2.1GP v5.2++### May 20, 2025: WanGP v5.2+ π Added support for Wan CausVid which is a distilled Wan model that can generate nice looking videos in only 4 to 12 steps. The great thing is that Kijai (Kudos to him!) has created a CausVid Lora that can be combined with any existing Wan t2v model 14B like Wan Vace 14B. See [LORAS.md](LORAS.md) for instructions on how to use CausVid.++ Also as an experiment I have added support for the MoviiGen, the first model that claims to be capable of generating 1080p videos (if you have enough VRAM (20GB...) and be ready to wait for a long time...). Don't hesitate to share your impressions on the Discord server.+-### May 18, 2025: Wan 2.1GP v5.1++### May 18, 2025: WanGP v5.1+ π Bonus Day, added LTX Video 13B Distilled: generate in less than one minute, very high quality Videos!+-### May 17, 2025: Wan 2.1GP v5.0++### May 17, 2025: WanGP v5.0+ π One App to Rule Them All! Added support for the other great open source architectures:+ - **Hunyuan Video**: text 2 video (one of the best, if not the best t2v), image 2 video and the recently released Hunyuan Custom (very good identity preservation when injecting a person into a video)+ - **LTX Video 13B** (released last week): very long video support and fast 720p generation. Wan GP version has been greatly optimized and reduced LTX Video VRAM requirements by 4!++ Also:+ - Added support for the best Control Video Model, released 2 days ago: Vace 14B+ - New Integrated prompt enhancer to increase the quality of the generated videos++ *You will need one more `pip install -r requirements.txt`*+-### May 5, 2025: Wan 2.1GP v4.5++### May 5, 2025: WanGP v4.5+ π FantasySpeaking model, you can animate a talking head using a voice track. This works not only on people but also on objects. Also better seamless transitions between Vace sliding windows for very long videos. New high quality processing features (mixed 16/32 bits calculation and 32 bits VAE)+-### April 27, 2025: Wan 2.1GP v4.4++### April 27, 2025: WanGP v4.4+ π Phantom model support, very good model to transfer people or objects into video, works quite well at 720p and with the number of steps > 30+-### April 25, 2025: Wan 2.1GP v4.3++### April 25, 2025: WanGP v4.3+ π Added preview mode and support for Sky Reels v2 Diffusion Forcing for high quality "infinite length videos". Note that Skyreel uses causal attention that is only supported by Sdpa attention so even if you choose another type of attention, some of the processes will use Sdpa attention.+-### April 18, 2025: Wan 2.1GP v4.2++### April 18, 2025: WanGP v4.2+ π FLF2V model support, official support from Wan for image2video start and end frames specialized for 720p.+-### April 17, 2025: Wan 2.1GP v4.1++### April 17, 2025: WanGP v4.1+ π Recam Master model support, view a video from a different angle. The video to process must be at least 81 frames long and you should set at least 15 steps denoising to get good results.+-### April 13, 2025: Wan 2.1GP v4.0++### April 13, 2025: WanGP v4.0+ π Lots of goodies for you!+ - A new UI, tabs were replaced by a Dropdown box to easily switch models+ - A new queuing system that lets you stack in a queue as many text2video, image2video tasks, ... as you want. Each task can rely on complete different generation parameters (different number of frames, steps, loras, ...). Many thanks to **Tophness** for being a big contributor on this new feature+ - Temporal upsampling (Rife) and spatial upsampling (Lanczos) for a smoother video (32 fps or 64 fps) and to enlarge your video by x2 or x4. Check these new advanced options.+ - Wan Vace Control Net support: with Vace you can inject in the scene people or objects, animate a person, perform inpainting or outpainting, continue a video, ... See [VACE.md](VACE.md) for introduction guide.+ - Integrated *Matanyone* tool directly inside WanGP so that you can create easily inpainting masks used in Vace+ - Sliding Window generation for Vace, create windows that can last dozens of seconds+ - New optimizations for old generation GPUs: Generate 5s (81 frames, 15 steps) of Vace 1.3B with only 5GB and in only 6 minutes on a RTX 2080Ti and 5s of t2v 14B in less than 10 minutes.++ ### March 27, 2025+ π Added support for the new Wan Fun InP models (image2video). The 14B Fun InP has probably better end image support but unfortunately existing loras do not work so well with it. The great novelty is the Fun InP image2 1.3B model: Image 2 Video is now accessible to even lower hardware configuration. It is not as good as the 14B models but very impressive for its size. Many thanks to the VideoX-Fun team (https://github.com/aigc-apps/VideoX-Fun)++ ### March 26, 2025+ π Good news! Official support for RTX 50xx please check the [installation instructions](INSTALLATION.md).++ ### March 24, 2025: Wan2.1GP v3.2+ π+ - Added Classifier-Free Guidance Zero Star. The video should match better the text prompt (especially with text2video) at no performance cost: many thanks to the **CFG Zero * Team**. Don't hesitate to give them a star if you appreciate the results: https://github.com/WeichenFan/CFG-Zero-star+ - Added back support for PyTorch compilation with Loras. It seems it had been broken for some time+ - Added possibility to keep a number of pregenerated videos in the Video Gallery (useful to compare outputs of different settings)++ *You will need one more `pip install -r requirements.txt`*++ ### March 19, 2025: Wan2.1GP v3.1+ π Faster launch and RAM optimizations (should require less RAM to run)++ *You will need one more `pip install -r requirements.txt`*++ ### March 18, 2025: Wan2.1GP v3.0+ π+ - New Tab based interface, you can switch from i2v to t2v conversely without restarting the app+ - Experimental Dual Frames mode for i2v, you can also specify an End frame. It doesn't always work, so you will need a few attempts.+ - You can save default settings in the files *i2v_settings.json* and *t2v_settings.json* that will be used when launching the app (you can also specify the path to different settings files)+ - Slight acceleration with loras++ *You will need one more `pip install -r requirements.txt`*++ Many thanks to *Tophness* who created the framework (and did a big part of the work) of the multitabs and saved settings features++ ### March 18, 2025: Wan2.1GP v2.11+ π Added more command line parameters to prefill the generation settings + customizable output directory and choice of type of metadata for generated videos. Many thanks to *Tophness* for his contributions.++ *You will need one more `pip install -r requirements.txt` to reflect new dependencies*++ ### March 18, 2025: Wan2.1GP v2.1+ π More Loras!: added support for 'Safetensors' and 'Replicate' Lora formats.++ *You will need to refresh the requirements with a `pip install -r requirements.txt`*++ ### March 17, 2025: Wan2.1GP v2.0+ π The Lora festival continues:+ - Clearer user interface+ - Download 30 Loras in one click to try them all (expand the info section)+ - Very easy to use Loras as now Lora presets can input the subject (or other needed terms) of the Lora so that you don't have to modify manually a prompt+ - Added basic macro prompt language to prefill prompts with different values. With one prompt template, you can generate multiple prompts.+ - New Multiple images prompts: you can now combine any number of images with any number of text prompts (need to launch the app with --multiple-images)+ - New command lines options to launch directly the 1.3B t2v model or the 14B t2v model++ ### March 14, 2025: Wan2.1GP v1.7+ π+ - Lora Fest special edition: very fast loading/unload of loras for those Loras collectors around. You can also now add/remove loras in the Lora folder without restarting the app.+ - Added experimental Skip Layer Guidance (advanced settings), that should improve the image quality at no extra cost. Many thanks to the *AmericanPresidentJimmyCarter* for the original implementation++ *You will need to refresh the requirements `pip install -r requirements.txt`*++ ### March 13, 2025: Wan2.1GP v1.6+ π Better Loras support, accelerated loading Loras.++ *You will need to refresh the requirements `pip install -r requirements.txt`*++ ### March 10, 2025: Wan2.1GP v1.5+ π Official Teacache support + Smart Teacache (find automatically best parameters for a requested speed multiplier), 10% speed boost with no quality loss, improved lora presets (they can now include prompts and comments to guide the user)++ ### March 7, 2025: Wan2.1GP v1.4+ π Fix PyTorch compilation, now it is really 20% faster when activated++ ### March 4, 2025: Wan2.1GP v1.3+ π Support for Image to Video with multiples images for different images/prompts combinations (requires *--multiple-images* switch), and added command line *--preload x* to preload in VRAM x MB of the main diffusion model if you find there is too much unused VRAM and you want to (slightly) accelerate the generation process.++ *If you upgrade you will need to do a `pip install -r requirements.txt` again.*++ ### March 4, 2025: Wan2.1GP v1.2+ π Implemented tiling on VAE encoding and decoding. No more VRAM peaks at the beginning and at the end++ ### March 3, 2025: Wan2.1GP v1.1+ π Added Tea Cache support for faster generations: optimization of kijai's implementation (https://github.com/kijai/ComfyUI-WanVideoWrapper/) of teacache (https://github.com/ali-vilab/TeaCache)++ ### March 2, 2025: Wan2.1GP by DeepBeepMeep v1+ π Brings:+ - Support for all Wan including the Image to Video model+ - Reduced memory consumption by 2, with possibility to generate more than 10s of video at 720p with a RTX 4090 and 10s of video at 480p with less than 12GB of VRAM. Many thanks to REFLEx (https://github.com/thu-ml/RIFLEx) for their algorithm that allows generating nice looking video longer than 5s.+ - The usual perks: web interface, multiple generations, loras support, sage attention, auto download of models, ...++ ## Original Wan Releases++ ### February 25, 2025+ π We've released the inference code and weights of Wan2.1.++ ### February 27, 2025+ π Wan2.1 has been integrated into [ComfyUI](https://comfyanonymous.github.io/ComfyUI_examples/wan/). Enjoy!diff --cc docs/CLI.mdindex 0000000,40b3268..38538b3mode 000000,100644..100644--- a/docs/CLI.md+++ b/docs/CLI.md@@@ -1,0 -1,242 +1,226 @@@-# Command Line Reference++--vace-1-3B--vace-1-3B# Command Line Reference++ This document covers all available command line options for WanGP.++ ## Basic Usage++ ```bash-# Default launch (text-to-video)++# Default launch+ python wgp.py++ # Specific model modes+ python wgp.py --i2v # Image-to-video+ python wgp.py --t2v # Text-to-video (default)+ python wgp.py --t2v-14B # 14B text-to-video model+ python wgp.py --t2v-1-3B # 1.3B text-to-video model+ python wgp.py --i2v-14B # 14B image-to-video model+ python wgp.py --i2v-1-3B # Fun InP 1.3B image-to-video model-python wgp.py --vace # VACE ControlNet 1.3B model++python wgp.py --vace-1-3B # VACE ControlNet 1.3B model+ ```++ ## Model and Performance Options++ ### Model Configuration+ ```bash+ --quantize-transformer BOOL # Enable/disable transformer quantization (default: True)+ --compile # Enable PyTorch compilation (requires Triton)+ --attention MODE # Force attention mode: sdpa, flash, sage, sage2+ --profile NUMBER # Performance profile 1-5 (default: 4)+ --preload NUMBER # Preload N MB of diffusion model in VRAM+ --fp16 # Force fp16 instead of bf16 models+ --gpu DEVICE # Run on specific GPU device (e.g., "cuda:1")+ ```++ ### Performance Profiles-- **Profile 1**: Maximum RAM usage, minimum VRAM-- **Profile 2**: Balanced RAM/VRAM usage-- **Profile 3 (LowRAM_HighVRAM)**: Load entire model in VRAM (requires 24GB for 14B model)-- **Profile 4 (LowRAM_LowVRAM)**: Default, load model parts as needed++- **Profile 1**: Load entire current model in VRAM and keep all unused models in reserved RAM for fast VRAM tranfers++- **Profile 2**: Load model parts as needed, keep all unused models in reserved RAM for fast VRAM tranfers++- **Profile 3**: Load entire current model in VRAM (requires 24GB for 14B model)++- **Profile 4**: Default and recommended, load model parts as needed, most flexible option+ - **Profile 5**: Minimum RAM usage++ ### Memory Management+ ```bash+ --perc-reserved-mem-max FLOAT # Max percentage of RAM for reserved memory (< 0.5)+ ```++ ## Lora Configuration++ ```bash+ --lora-dir PATH # Path to Wan t2v loras directory+ --lora-dir-i2v PATH # Path to Wan i2v loras directory+ --lora-dir-hunyuan PATH # Path to Hunyuan t2v loras directory+ --lora-dir-hunyuan-i2v PATH # Path to Hunyuan i2v loras directory+ --lora-dir-ltxv PATH # Path to LTX Video loras directory+ --lora-preset PRESET # Load lora preset file (.lset) on startup+ --check-loras # Filter incompatible loras (slower startup)+ ```++ ## Generation Settings++ ### Basic Generation+ ```bash+ --seed NUMBER # Set default seed value+ --frames NUMBER # Set default number of frames to generate+ --steps NUMBER # Set default number of denoising steps+ --advanced # Launch with advanced mode enabled+ ```++ ### Advanced Generation+ ```bash+ --teacache MULTIPLIER # TeaCache speed multiplier: 0, 1.5, 1.75, 2.0, 2.25, 2.5---slg # Enable Skip Layer Guidance for improved quality+ ```++ ## Interface and Server Options++ ### Server Configuration+ ```bash+ --server-port PORT # Gradio server port (default: 7860)+ --server-name NAME # Gradio server name (default: localhost)+ --listen # Make server accessible on network+ --share # Create shareable HuggingFace URL for remote access+ --open-browser # Open browser automatically when launching+ ```++ ### Interface Options+ ```bash---multiple-images # Allow multiple image inputs for different starting points+ --lock-config # Prevent modifying video engine configuration from interface+ --theme THEME_NAME # UI theme: "default" or "gradio"+ ```++ ## File and Directory Options++ ```bash+ --settings PATH # Path to folder containing default settings for all models+ --verbose LEVEL # Information level 0-2 (default: 1)+ ```++ ## Examples++ ### Basic Usage Examples+ ```bash+ # Launch with specific model and loras+ python wgp.py --t2v-14B --lora-preset mystyle.lset++ # High-performance setup with compilation+ python wgp.py --compile --attention sage2 --profile 3++ # Low VRAM setup+ python wgp.py --t2v-1-3B --profile 4 --attention sdpa++ # Multiple images with custom lora directory+ python wgp.py --i2v --multiple-images --lora-dir /path/to/shared/loras+ ```++ ### Server Configuration Examples+ ```bash+ # Network accessible server+ python wgp.py --listen --server-port 8080++ # Shareable server with custom theme+ python wgp.py --share --theme gradio --open-browser++ # Locked configuration for public use+ python wgp.py --lock-config --share+ ```++ ### Advanced Performance Examples+ ```bash+ # Maximum performance (requires high-end GPU)+ python wgp.py --compile --attention sage2 --profile 3 --preload 2000++ # Optimized for RTX 2080Ti+ python wgp.py --profile 4 --attention sdpa --teacache 2.0++ # Memory-efficient setup+ python wgp.py --fp16 --profile 4 --perc-reserved-mem-max 0.3+ ```++ ### TeaCache Configuration+ ```bash+ # Different speed multipliers+ python wgp.py --teacache 1.5 # 1.5x speed, minimal quality loss+ python wgp.py --teacache 2.0 # 2x speed, some quality loss+ python wgp.py --teacache 2.5 # 2.5x speed, noticeable quality loss+ python wgp.py --teacache 0 # Disable TeaCache+ ```++ ## Attention Modes++ ### SDPA (Default)+ ```bash+ python wgp.py --attention sdpa+ ```+ - Available by default with PyTorch+ - Good compatibility with all GPUs+ - Moderate performance++ ### Sage Attention+ ```bash+ python wgp.py --attention sage+ ```+ - Requires Triton installation+ - 30% faster than SDPA+ - Small quality cost++ ### Sage2 Attention+ ```bash+ python wgp.py --attention sage2+ ```+ - Requires Triton and SageAttention 2.x+ - 40% faster than SDPA+ - Best performance option++ ### Flash Attention+ ```bash+ python wgp.py --attention flash+ ```+ - May require CUDA kernel compilation+ - Good performance+ - Can be complex to install on Windows++ ## Troubleshooting Command Lines++ ### Fallback to Basic Setup+ ```bash+ # If advanced features don't work+ python wgp.py --attention sdpa --profile 4 --fp16+ ```++ ### Debug Mode+ ```bash+ # Maximum verbosity for troubleshooting+ python wgp.py --verbose 2 --check-loras+ ```++ ### Memory Issue Debugging+ ```bash+ # Minimal memory usage+ python wgp.py --profile 4 --attention sdpa --perc-reserved-mem-max 0.2+ ```+-### GPU-specific Configurations-```bash-# RTX 10XX/20XX series-python wgp.py --attention sdpa --profile 4 --fp16+-# RTX 30XX/40XX series-python wgp.py --attention sage --compile --profile 3--# RTX 50XX series (beta)-python wgp.py --attention sage --fp16 --profile 4-```++ ## Configuration Files++ ### Settings Files-You can save default settings in JSON files:-- `i2v_settings.json` - Image-to-video default settings-- `t2v_settings.json` - Text-to-video default settings-+ Load custom settings:+ ```bash+ python wgp.py --settings /path/to/settings/folder+ ```++ ### Lora Presets+ Create and share lora configurations:+ ```bash+ # Load specific preset+ python wgp.py --lora-preset anime_style.lset++ # With custom lora directory+ python wgp.py --lora-preset mystyle.lset --lora-dir /shared/loras+ ```++ ## Environment Variables++ While not command line options, these environment variables can affect behavior:+ - `CUDA_VISIBLE_DEVICES` - Limit visible GPUs+ - `PYTORCH_CUDA_ALLOC_CONF` - CUDA memory allocation settings+ - `TRITON_CACHE_DIR` - Triton cache directory (for Sage attention)diff --cc docs/GETTING_STARTED.mdindex 0000000,1bd20b7..2449e4fmode 000000,100644..100644--- a/docs/GETTING_STARTED.md+++ b/docs/GETTING_STARTED.md@@@ -1,0 -1,194 +1,194 @@@+ # Getting Started with WanGP++ This guide will help you get started with WanGP video generation quickly and easily.++ ## Prerequisites++ Before starting, ensure you have:+ - A compatible GPU (RTX 10XX or newer recommended)+ - Python 3.10.9 installed+ - At least 6GB of VRAM for basic models+ - Internet connection for model downloads++ ## Quick Setup++ ### Option 1: One-Click Installation (Recommended)+ Use [Pinokio App](https://pinokio.computer/) for the easiest installation experience.++ ### Option 2: Manual Installation+ ```bash+ git clone https://github.com/deepbeepmeep/Wan2GP.git+ cd Wan2GP+ conda create -n wan2gp python=3.10.9+ conda activate wan2gp+ pip install torch==2.6.0 torchvision torchaudio --index-url https://download.pytorch.org/whl/test/cu124+ pip install -r requirements.txt+ ```++ For detailed installation instructions, see [INSTALLATION.md](INSTALLATION.md).++ ## First Launch++ ### Basic Launch+ ```bash+ python wgp.py+ ```-This launches the text-to-video generator with default settings.++This launches the WanGP generator with default settings. You will be able to pick from a Drop Down menu which model you want to use.++ ### Alternative Modes+ ```bash-python wgp.py --i2v # Image-to-video mode-python wgp.py --t2v-1-3B # Smaller, faster model++python wgp.py --i2v # Wan Image-to-video mode++python wgp.py --t2v-1-3B # Wan Smaller, faster model+ ```++ ## Understanding the Interface++ When you launch WanGP, you'll see a web interface with several sections:++ ### Main Generation Panel+ - **Model Selection**: Dropdown to choose between different models+ - **Prompt**: Text description of what you want to generate+ - **Generate Button**: Start the video generation process++ ### Advanced Settings (click checkbox to enable)+ - **Generation Settings**: Steps, guidance, seeds+ - **Loras**: Additional style customizations+ - **Sliding Window**: For longer videos++ ## Your First Video++ Let's generate a simple text-to-video:++ 1. **Launch WanGP**: `python wgp.py`+ 2. **Open Browser**: Navigate to `http://localhost:7860`+ 3. **Enter Prompt**: "A cat walking in a garden"+ 4. **Click Generate**: Wait for the video to be created+ 5. **View Result**: The video will appear in the output section++ ### Recommended First Settings+ - **Model**: Wan 2.1 text2video 1.3B (faster, lower VRAM)+ - **Frames**: 49 (about 2 seconds)+ - **Steps**: 20 (good balance of speed/quality)++ ## Model Selection++ ### Text-to-Video Models+ - **Wan 2.1 T2V 1.3B**: Fastest, lowest VRAM (6GB), good quality+ - **Wan 2.1 T2V 14B**: Best quality, requires more VRAM (12GB+)+ - **Hunyuan Video**: Excellent quality, slower generation+ - **LTX Video**: Good for longer videos++ ### Image-to-Video Models+ - **Wan Fun InP 1.3B**: Fast image animation+ - **Wan Fun InP 14B**: Higher quality image animation+ - **VACE**: Advanced control over video generation++ ### Choosing the Right Model+ - **Low VRAM (6-8GB)**: Use 1.3B models+ - **Medium VRAM (10-12GB)**: Use 14B models or Hunyuan+ - **High VRAM (16GB+)**: Any model, longer videos++ ## Basic Settings Explained++ ### Generation Settings+ - **Frames**: Number of frames (more = longer video)+ - 25 frames β 1 second+ - 49 frames β 2 seconds+ - 73 frames β 3 seconds++ - **Steps**: Quality vs Speed tradeoff+ - 15 steps: Fast, lower quality+ - 20 steps: Good balance+ - 30+ steps: High quality, slower++ - **Guidance Scale**: How closely to follow the prompt+ - 3-5: More creative interpretation+ - 7-10: Closer to prompt description+ - 12+: Very literal interpretation++ ### Seeds+ - **Random Seed**: Different result each time+ - **Fixed Seed**: Reproducible results+ - **Use same seed + prompt**: Generate variations++ ## Common Beginner Issues++ ### "Out of Memory" Errors+ 1. Use smaller models (1.3B instead of 14B)+ 2. Reduce frame count+ 3. Lower resolution in advanced settings+ 4. Enable quantization (usually on by default)++ ### Slow Generation+ 1. Use 1.3B models for speed+ 2. Reduce number of steps+ 3. Install Sage attention (see [INSTALLATION.md](INSTALLATION.md))+ 4. Enable TeaCache: `python wgp.py --teacache 2.0`++ ### Poor Quality Results+ 1. Increase number of steps (25-30)+ 2. Improve prompt description+ 3. Use 14B models if you have enough VRAM+ 4. Enable Skip Layer Guidance in advanced settings++ ## Writing Good Prompts++ ### Basic Structure+ ```+ [Subject] [Action] [Setting] [Style/Quality modifiers]+ ```++ ### Examples+ ```+ A red sports car driving through a mountain road at sunset, cinematic, high quality++ A woman with long hair walking on a beach, waves in the background, realistic, detailed++ A cat sitting on a windowsill watching rain, cozy atmosphere, soft lighting+ ```++ ### Tips+ - Be specific about what you want+ - Include style descriptions (cinematic, realistic, etc.)+ - Mention lighting and atmosphere+ - Describe the setting in detail+ - Use quality modifiers (high quality, detailed, etc.)++ ## Next Steps++ Once you're comfortable with basic generation:++ 1. **Explore Advanced Features**:+ - [Loras Guide](LORAS.md) - Customize styles and characters+ - [VACE ControlNet](VACE.md) - Advanced video control+ - [Command Line Options](CLI.md) - Optimize performance++ 2. **Improve Performance**:+ - Install better attention mechanisms+ - Optimize memory settings+ - Use compilation for speed++ 3. **Join the Community**:+ - [Discord Server](https://discord.gg/g7efUW9jGV) - Get help and share videos+ - Share your best results+ - Learn from other users++ ## Troubleshooting First Steps++ ### Installation Issues+ - Ensure Python 3.10.9 is used+ - Check CUDA version compatibility+ - See [INSTALLATION.md](INSTALLATION.md) for detailed steps++ ### Generation Issues+ - Check GPU compatibility+ - Verify sufficient VRAM+ - Try basic settings first+ - See [TROUBLESHOOTING.md](TROUBLESHOOTING.md) for specific issues++ ### Performance Issues+ - Use appropriate model for your hardware+ - Enable performance optimizations+ - Check [CLI.md](CLI.md) for optimization flags++ Remember: Start simple and gradually explore more advanced features as you become comfortable with the basics!diff --cc docs/MODELS.mdindex 0000000,beb2d64..27ab39bmode 000000,100644..100644--- a/docs/MODELS.md+++ b/docs/MODELS.md@@@ -1,0 -1,232 +1,268 @@@+ # Models Overview+-WanGP supports multiple video generation models, each optimized for different use cases and hardware configurations.++WanGP supports multiple video generation models, each optimized for different use cases and hardware configurations.+-## Text-to-Video Models+-### Wan 2.1 Models++## Wan 2.1 Text2Video Models++Please note that that the term *Text2Video* refers to the underlying Wan architecture but as it has been greatly improved overtime many derived Text2Video models can now generate videos using images.++ #### Wan 2.1 Text2Video 1.3B+ - **Size**: 1.3 billion parameters+ - **VRAM**: 6GB minimum+ - **Speed**: Fast generation+ - **Quality**: Good quality for the size+ - **Best for**: Quick iterations, lower-end hardware+ - **Command**: `python wgp.py --t2v-1-3B`++ #### Wan 2.1 Text2Video 14B+ - **Size**: 14 billion parameters+ - **VRAM**: 12GB+ recommended+ - **Speed**: Slower but higher quality+ - **Quality**: Excellent detail and coherence+ - **Best for**: Final production videos+ - **Command**: `python wgp.py --t2v-14B`++ #### Wan Vace 1.3B+ - **Type**: ControlNet for advanced video control+ - **VRAM**: 6GB minimum+ - **Features**: Motion transfer, object injection, inpainting+ - **Best for**: Advanced video manipulation-- **Command**: `python wgp.py --vace`++- **Command**: `python wgp.py --vace-1.3B`++ #### Wan Vace 14B+ - **Type**: Large ControlNet model+ - **VRAM**: 12GB+ recommended+ - **Features**: All Vace features with higher quality+ - **Best for**: Professional video editing workflows+-### Hunyuan Video Models++#### MoviiGen (Experimental)++- **Resolution**: Claims 1080p capability++- **VRAM**: 20GB+ required++- **Speed**: Very slow generation++- **Features**: Should generate cinema like video, specialized for 2.1 / 1 ratios++- **Status**: Experimental, feedback welcome+-#### Hunyuan Video Text2Video-- **Quality**: Among the best open source t2v models++<BR>++++## Wan 2.1 Image-to-Video Models++++#### Wan 2.1 Image2Video 14B++- **Size**: 14 billion parameters+ - **VRAM**: 12GB+ recommended-- **Speed**: Slower generation but excellent results-- **Features**: Superior text adherence and video quality-- **Best for**: High-quality text-to-video generation++- **Speed**: Slower but higher quality++- **Quality**: Excellent detail and coherence++- **Best for**: Most Loras available work with this model++- **Command**: `python wgp.py --i2v-14B`+-#### Hunyuan Video Custom-- **Specialty**: Identity preservation-- **Use case**: Injecting specific people into videos-- **Quality**: Excellent for character consistency-- **Best for**: Character-focused video generation++#### FLF2V++- **Type**: Start/end frame specialist++- **Resolution**: Optimized for 720p++- **Official**: Wan team supported++- **Use case**: Image-to-video with specific endpoints+-### LTX Video Models+-#### LTX Video 13B-- **Specialty**: Long video generation-- **Resolution**: Fast 720p generation-- **VRAM**: Optimized by WanGP (4x reduction in requirements)-- **Best for**: Longer duration videos++<BR>+-#### LTX Video 13B Distilled-- **Speed**: Generate in less than one minute-- **Quality**: Very high quality despite speed-- **Best for**: Rapid prototyping and quick results++## Wan 2.1 Specialized Models+-### Other Models++#### FantasySpeaking++- **Type**: Talking head animation++- **Input**: Voice track + image++- **Works on**: People and objects++- **Use case**: Lip-sync and voice-driven animation++++#### Phantom++- **Type**: Person/object transfer++- **Resolution**: Works well at 720p++- **Requirements**: 30+ steps for good results++- **Best for**: Transferring subjects between videos++++#### Recam Master++- **Type**: Viewpoint change++- **Requirements**: 81+ frame input videos, 15+ denoising steps++- **Use case**: View same scene from different angles++ #### Sky Reels v2+ - **Type**: Diffusion Forcing model+ - **Specialty**: "Infinite length" videos+ - **Features**: High quality continuous generation-- **Note**: Uses causal attention (SDPA only)+-#### MoviiGen (Experimental)-- **Resolution**: Claims 1080p capability-- **VRAM**: 20GB+ required-- **Speed**: Very slow generation-- **Status**: Experimental, feedback welcome+-#### CausVid (Via Lora)-- **Type**: Distilled model (Lora implementation)-- **Speed**: 4-12 steps generation, 2x faster-- **Compatible**: Works with Wan 14B models-- **Setup**: Requires CausVid Lora (see [LORAS.md](LORAS.md))++<BR>+-## Image-to-Video Models--### Wan Fun InP Models++## Wan Fun InP Models++ #### Wan Fun InP 1.3B+ - **Size**: 1.3 billion parameters+ - **VRAM**: 6GB minimum+ - **Quality**: Good for the size, accessible to lower hardware+ - **Best for**: Entry-level image animation+ - **Command**: `python wgp.py --i2v-1-3B`++ #### Wan Fun InP 14B+ - **Size**: 14 billion parameters+ - **VRAM**: 12GB+ recommended+ - **Quality**: Better end image support+ - **Limitation**: Existing loras don't work as well-- **Command**: `python wgp.py --i2v-14B`+-### Specialized Models++<BR>+-#### FantasySpeaking-- **Type**: Talking head animation-- **Input**: Voice track + image-- **Works on**: People and objects-- **Use case**: Lip-sync and voice-driven animation++## Wan Special Loras++### Causvid++- **Type**: Distilled model (Lora implementation)++- **Speed**: 4-12 steps generation, 2x faster++- **Compatible**: Works with Wan 14B models++- **Setup**: Requires CausVid Lora (see [LORAS.md](LORAS.md))+-#### Phantom-- **Type**: Person/object transfer-- **Resolution**: Works well at 720p-- **Requirements**: 30+ steps for good results-- **Best for**: Transferring subjects between videos+-#### Recam Master-- **Type**: Viewpoint change-- **Requirements**: 81+ frame input videos, 15+ denoising steps-- **Use case**: View same scene from different angles++<BR>+-#### FLF2V-- **Type**: Start/end frame specialist-- **Resolution**: Optimized for 720p-- **Official**: Wan team supported-- **Use case**: Image-to-video with specific endpoints++## Hunyuan Video Models++++#### Hunyuan Video Text2Video++- **Quality**: Among the best open source t2v models++- **VRAM**: 12GB+ recommended++- **Speed**: Slower generation but excellent results++- **Features**: Superior text adherence and video quality, up to 10s of video++- **Best for**: High-quality text-to-video generation++++#### Hunyuan Video Custom++- **Specialty**: Identity preservation++- **Use case**: Injecting specific people into videos++- **Quality**: Excellent for character consistency++- **Best for**: Character-focused video generation++++#### Hunyuan Video Avater++- **Specialty**: Generate up to 15s of high quality speech / song driven Video .++- **Use case**: Injecting specific people into videos++- **Quality**: Excellent for character consistency++- **Best for**: Character-focused video generation, Video synchronized with voice++++++<BR>++++## LTX Video Models++++#### LTX Video 13B++- **Specialty**: Long video generation++- **Resolution**: Fast 720p generation++- **VRAM**: Optimized by WanGP (4x reduction in requirements)++- **Best for**: Longer duration videos++++#### LTX Video 13B Distilled++- **Speed**: Generate in less than one minute++- **Quality**: Very high quality despite speed++- **Best for**: Rapid prototyping and quick results++++<BR>++ ## Model Selection Guide++ ### By Hardware (VRAM)++ #### 6-8GB VRAM+ - Wan 2.1 T2V 1.3B+ - Wan Fun InP 1.3B+ - Wan Vace 1.3B++ #### 10-12GB VRAM+ - Wan 2.1 T2V 14B+ - Wan Fun InP 14B+ - Hunyuan Video (with optimizations)+ - LTX Video 13B++ #### 16GB+ VRAM+ - All models supported+ - Longer videos possible+ - Higher resolutions+ - Multiple simultaneous Loras++ #### 20GB+ VRAM+ - MoviiGen (experimental 1080p)+ - Very long videos+ - Maximum quality settings++ ### By Use Case++ #### Quick Prototyping+ 1. **LTX Video 13B Distilled** - Fastest, high quality+ 2. **Wan 2.1 T2V 1.3B** - Fast, good quality+ 3. **CausVid Lora** - 4-12 steps, very fast++ #### Best Quality+ 1. **Hunyuan Video** - Overall best t2v quality+ 2. **Wan 2.1 T2V 14B** - Excellent Wan quality+ 3. **Wan Vace 14B** - Best for controlled generation++ #### Advanced Control+ 1. **Wan Vace 14B/1.3B** - Motion transfer, object injection+ 2. **Phantom** - Person/object transfer+ 3. **FantasySpeaking** - Voice-driven animation++ #### Long Videos+ 1. **LTX Video 13B** - Specialized for length+ 2. **Sky Reels v2** - Infinite length videos+ 3. **Wan Vace + Sliding Windows** - Up to 1 minute++ #### Lower Hardware+ 1. **Wan Fun InP 1.3B** - Image-to-video+ 2. **Wan 2.1 T2V 1.3B** - Text-to-video+ 3. **Wan Vace 1.3B** - Advanced control+++<BR>+++ ## Performance Comparison++ ### Speed (Relative)+ 1. **CausVid Lora** (4-12 steps) - Fastest+ 2. **LTX Video Distilled** - Very fast+ 3. **Wan 1.3B models** - Fast+ 4. **Wan 14B models** - Medium+ 5. **Hunyuan Video** - Slower+ 6. **MoviiGen** - Slowest++ ### Quality (Subjective)+ 1. **Hunyuan Video** - Highest overall+ 2. **Wan 14B models** - Excellent+ 3. **LTX Video models** - Very good+ 4. **Wan 1.3B models** - Good+ 5. **CausVid** - Good (varies with steps)++ ### VRAM Efficiency+ 1. **Wan 1.3B models** - Most efficient+ 2. **LTX Video** (with WanGP optimizations)+ 3. **Wan 14B models**+ 4. **Hunyuan Video**+ 5. **MoviiGen** - Least efficient+++<BR>+++ ## Model Switching++ WanGP allows switching between models without restarting:++ 1. Use the dropdown menu in the web interface+ 2. Models are loaded on-demand+ 3. Previous model is unloaded to save VRAM+ 4. Settings are preserved when possible+++<BR>+++ ## Tips for Model Selection++ ### First Time Users+ Start with **Wan 2.1 T2V 1.3B** to learn the interface and test your hardware.++ ### Production Work+ Use **Hunyuan Video** or **Wan 14B** models for final output quality.++ ### Experimentation+ **CausVid Lora** or **LTX Distilled** for rapid iteration and testing.++ ### Specialized Tasks+ - **VACE** for advanced control+ - **FantasySpeaking** for talking heads+ - **LTX Video** for long sequences++ ### Hardware Optimization+ Always start with the largest model your VRAM can handle, then optimize settings for speed vs quality based on your needs.diff --cc hyvideo/diffusion/pipelines/pipeline_hunyuan_video_audio.pyindex 358615b,0000000..8be3c47mode 100644,000000..100644--- a/hyvideo/diffusion/pipelines/pipeline_hunyuan_video_audio.py+++ b/hyvideo/diffusion/pipelines/pipeline_hunyuan_video_audio.py@@@ -1,1359 -1,0 +1,1359 @@@+# Copyright 2024 The HuggingFace Team. All rights reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ==============================================================================+#+# Modified from diffusers==0.29.2+#+# ==============================================================================+import inspect+from typing import Any, Callable, Dict, List, Optional, Union, Tuple+import numpy as np+import torch+from packaging import version+from diffusers.utils import BaseOutput+from dataclasses import dataclass+from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback+from diffusers.configuration_utils import FrozenDict+from diffusers.image_processor import PipelineImageInput, VaeImageProcessor+from diffusers.loaders import LoraLoaderMixin, TextualInversionLoaderMixin+from diffusers.models import AutoencoderKL, ImageProjection+from diffusers.models.lora import adjust_lora_scale_text_encoder+from diffusers.schedulers import KarrasDiffusionSchedulers+from diffusers.utils import (+ USE_PEFT_BACKEND,+ deprecate,+ logging,+ replace_example_docstring,+ scale_lora_layers,+ unscale_lora_layers,+)+from diffusers.utils.torch_utils import randn_tensor+from diffusers.pipelines.pipeline_utils import DiffusionPipeline++from hyvideo.constants import PRECISION_TO_TYPE+from hyvideo.vae.autoencoder_kl_causal_3d import AutoencoderKLCausal3D+from hyvideo.text_encoder import TextEncoder+from einops import rearrange+from ...modules import HYVideoDiffusionTransformer++logger = logging.get_logger(__name__) # pylint: disable=invalid-name++EXAMPLE_DOC_STRING = """"""+++def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):+ """+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4+ """+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)+ # rescale the results from guidance (fixes overexposure)+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg+ return noise_cfg+++def retrieve_timesteps(+ scheduler,+ num_inference_steps: Optional[int] = None,+ device: Optional[Union[str, torch.device]] = None,+ timesteps: Optional[List[int]] = None,+ sigmas: Optional[List[float]] = None,+ **kwargs,+):+ """+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.++ Args:+ scheduler (`SchedulerMixin`):+ The scheduler to get timesteps from.+ num_inference_steps (`int`):+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`+ must be `None`.+ device (`str` or `torch.device`, *optional*):+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.+ timesteps (`List[int]`, *optional*):+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,+ `num_inference_steps` and `sigmas` must be `None`.+ sigmas (`List[float]`, *optional*):+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,+ `num_inference_steps` and `timesteps` must be `None`.++ Returns:+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the+ second element is the number of inference steps.+ """+ if timesteps is not None and sigmas is not None:+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")+ if timesteps is not None:+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())+ if not accepts_timesteps:+ raise ValueError(+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"+ f" timestep schedules. Please check whether you are using the correct scheduler."+ )+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)+ timesteps = scheduler.timesteps+ num_inference_steps = len(timesteps)+ elif sigmas is not None:+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())+ if not accept_sigmas:+ raise ValueError(+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"+ f" sigmas schedules. Please check whether you are using the correct scheduler."+ )+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)+ timesteps = scheduler.timesteps+ num_inference_steps = len(timesteps)+ else:+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)+ timesteps = scheduler.timesteps+ return timesteps, num_inference_steps++@dataclass+class HunyuanVideoPipelineOutput(BaseOutput):+ videos: Union[torch.Tensor, np.ndarray]+++class HunyuanVideoAudioPipeline(DiffusionPipeline):+ r"""+ Pipeline for text-to-video generation using HunyuanVideo.++ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).++ Args:+ vae ([`AutoencoderKL`]):+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.+ text_encoder ([`TextEncoder`]):+ Frozen text-encoder.+ text_encoder_2 ([`TextEncoder`]):+ Frozen text-encoder_2.+ transformer ([`HYVideoDiffusionTransformer`]):+ A `HYVideoDiffusionTransformer` to denoise the encoded video latents.+ scheduler ([`SchedulerMixin`]):+ A scheduler to be used in combination with `unet` to denoise the encoded image latents.+ """++ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"+ _optional_components = ["text_encoder_2"]+ _exclude_from_cpu_offload = ["transformer"]+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]++ def __init__(+ self,+ vae: AutoencoderKL,+ text_encoder: TextEncoder,+ transformer: HYVideoDiffusionTransformer,+ scheduler: KarrasDiffusionSchedulers,+ text_encoder_2: Optional[TextEncoder] = None,+ progress_bar_config: Dict[str, Any] = None,+ args=None,+ ):+ super().__init__()++ # ==========================================================================================+ if progress_bar_config is None:+ progress_bar_config = {}+ if not hasattr(self, '_progress_bar_config'):+ self._progress_bar_config = {}+ self._progress_bar_config.update(progress_bar_config)++ self.args = args+ # ==========================================================================================++ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:+ deprecation_message = (+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"+ " file"+ )+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)+ new_config = dict(scheduler.config)+ new_config["steps_offset"] = 1+ scheduler._internal_dict = FrozenDict(new_config)++ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:+ deprecation_message = (+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"+ )+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)+ new_config = dict(scheduler.config)+ new_config["clip_sample"] = False+ scheduler._internal_dict = FrozenDict(new_config)++ self.register_modules(+ vae=vae,+ text_encoder=text_encoder,+ transformer=transformer,+ scheduler=scheduler,+ text_encoder_2=text_encoder_2+ )+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)++ def encode_prompt(+ self,+ prompt,+ name,+ device,+ num_videos_per_prompt,+ do_classifier_free_guidance,+ negative_prompt=None,+ pixel_value_llava: Optional[torch.Tensor] = None,+ uncond_pixel_value_llava: Optional[torch.Tensor] = None,+ prompt_embeds: Optional[torch.Tensor] = None,+ attention_mask: Optional[torch.Tensor] = None,+ negative_prompt_embeds: Optional[torch.Tensor] = None,+ negative_attention_mask: Optional[torch.Tensor] = None,+ lora_scale: Optional[float] = None,+ clip_skip: Optional[int] = None,+ text_encoder: Optional[TextEncoder] = None,+ data_type: Optional[str] = "image",+ ):+ r"""+ Encodes the prompt into text encoder hidden states.++ Args:+ prompt (`str` or `List[str]`, *optional*):+ prompt to be encoded+ device: (`torch.device`):+ torch device+ num_videos_per_prompt (`int`):+ number of images that should be generated per prompt+ do_classifier_free_guidance (`bool`):+ whether to use classifier free guidance or not+ negative_prompt (`str` or `List[str]`, *optional*):+ The prompt or prompts not to guide the image generation. If not defined, one has to pass+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is+ less than `1`).+ pixel_value_llava (`torch.Tensor`, *optional*):+ The image tensor for llava.+ uncond_pixel_value_llava (`torch.Tensor`, *optional*):+ The image tensor for llava. Ignored when not using guidance (i.e., ignored if `guidance_scale` is+ less than `1`).+ prompt_embeds (`torch.Tensor`, *optional*):+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not+ provided, text embeddings will be generated from `prompt` input argument.+ attention_mask (`torch.Tensor`, *optional*):+ negative_prompt_embeds (`torch.Tensor`, *optional*):+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input+ argument.+ negative_attention_mask (`torch.Tensor`, *optional*):+ lora_scale (`float`, *optional*):+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.+ clip_skip (`int`, *optional*):+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that+ the output of the pre-final layer will be used for computing the prompt embeddings.+ text_encoder (TextEncoder, *optional*):+ """+ if text_encoder is None:+ text_encoder = self.text_encoder++ # set lora scale so that monkey patched LoRA+ # function of text encoder can correctly access it+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):+ self._lora_scale = lora_scale++ # dynamically adjust the LoRA scale+ if not USE_PEFT_BACKEND:+ adjust_lora_scale_text_encoder(text_encoder.model, lora_scale)+ else:+ scale_lora_layers(text_encoder.model, lora_scale)++ if prompt is not None and isinstance(prompt, str):+ batch_size = 1+ elif prompt is not None and isinstance(prompt, list):+ batch_size = len(prompt)+ else:+ batch_size = prompt_embeds.shape[0]++ if prompt_embeds is None:+ # textual inversion: process multi-vector tokens if necessary+ if isinstance(self, TextualInversionLoaderMixin):+ prompt = self.maybe_convert_prompt(prompt, text_encoder.tokenizer)+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, name=name)++ if pixel_value_llava is not None:+ text_inputs['pixel_value_llava'] = pixel_value_llava+ text_inputs['attention_mask'] = torch.cat([text_inputs['attention_mask'], torch.ones((1, 575 * len(pixel_value_llava))).to(text_inputs['attention_mask'])], dim=1)++ if clip_skip is None:+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type)+ prompt_embeds = prompt_outputs.hidden_state+ else:+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type)+ # Access the `hidden_states` first, that contains a tuple of+ # all the hidden states from the encoder layers. Then index into+ # the tuple to access the hidden states from the desired layer.+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]+ # We also need to apply the final LayerNorm here to not mess with the+ # representations. The `last_hidden_states` that we typically use for+ # obtaining the final prompt representations passes through the LayerNorm+ # layer.+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)++ attention_mask = prompt_outputs.attention_mask+ if attention_mask is not None:+ attention_mask = attention_mask.to(device)+ bs_embed, seq_len = attention_mask.shape+ attention_mask = attention_mask.repeat(1, num_videos_per_prompt)+ attention_mask = attention_mask.view(bs_embed * num_videos_per_prompt, seq_len)++ if text_encoder is not None:+ prompt_embeds_dtype = text_encoder.dtype+ elif self.transformer is not None:+ prompt_embeds_dtype = self.transformer.dtype+ else:+ prompt_embeds_dtype = prompt_embeds.dtype++ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)++ if prompt_embeds.ndim == 2:+ bs_embed, _ = prompt_embeds.shape+ # duplicate text embeddings for each generation per prompt, using mps friendly method+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)+ prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, -1)+ else:+ bs_embed, seq_len, _ = prompt_embeds.shape+ # duplicate text embeddings for each generation per prompt, using mps friendly method+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)+ prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, seq_len, -1)++ # get unconditional embeddings for classifier free guidance+ if do_classifier_free_guidance and negative_prompt_embeds is None:+ uncond_tokens: List[str]+ if negative_prompt is None:+ uncond_tokens = [""] * batch_size+ elif prompt is not None and type(prompt) is not type(negative_prompt):+ raise TypeError(+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="+ f" {type(prompt)}."+ )+ elif isinstance(negative_prompt, str):+ uncond_tokens = [negative_prompt]+ elif batch_size != len(negative_prompt):+ raise ValueError(+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"+ " the batch size of `prompt`."+ )+ else:+ uncond_tokens = negative_prompt++ # textual inversion: process multi-vector tokens if necessary+ if isinstance(self, TextualInversionLoaderMixin):+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, text_encoder.tokenizer)+ uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type)+ if uncond_pixel_value_llava is not None:+ uncond_input['pixel_value_llava'] = uncond_pixel_value_llava+ uncond_input['attention_mask'] = torch.cat([uncond_input['attention_mask'], torch.ones((1, 575 * len(uncond_pixel_value_llava))).to(uncond_input['attention_mask'])], dim=1)++ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type)+ negative_prompt_embeds = negative_prompt_outputs.hidden_state++ negative_attention_mask = negative_prompt_outputs.attention_mask+ if negative_attention_mask is not None:+ negative_attention_mask = negative_attention_mask.to(device)+ _, seq_len = negative_attention_mask.shape+ negative_attention_mask = negative_attention_mask.repeat(1, num_videos_per_prompt)+ negative_attention_mask = negative_attention_mask.view(batch_size * num_videos_per_prompt, seq_len)++ if do_classifier_free_guidance:+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method+ seq_len = negative_prompt_embeds.shape[1]++ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)++ if negative_prompt_embeds.ndim == 2:+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt)+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_videos_per_prompt, -1)+ else:+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt, 1)+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)++ if text_encoder is not None:+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:+ # Retrieve the original scale by scaling back the LoRA layers+ unscale_lora_layers(text_encoder.model, lora_scale)++ return prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask++ def encode_prompt_audio_text_base(+ self,+ prompt,+ uncond_prompt,+ pixel_value_llava,+ uncond_pixel_value_llava,+ device,+ num_images_per_prompt,+ do_classifier_free_guidance,+ negative_prompt=None,+ prompt_embeds: Optional[torch.Tensor] = None,+ negative_prompt_embeds: Optional[torch.Tensor] = None,+ lora_scale: Optional[float] = None,+ clip_skip: Optional[int] = None,+ text_encoder: Optional[TextEncoder] = None,+ data_type: Optional[str] = "image",+ name = "person"+ ):+ if text_encoder is None:+ text_encoder = self.text_encoder++ # set lora scale so that monkey patched LoRA+ # function of text encoder can correctly access it+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):+ self._lora_scale = lora_scale++ # dynamically adjust the LoRA scale+ if not USE_PEFT_BACKEND:+ adjust_lora_scale_text_encoder(text_encoder.model, lora_scale)+ else:+ scale_lora_layers(text_encoder.model, lora_scale)++ if prompt is not None and isinstance(prompt, str):+ batch_size = 1+ elif prompt is not None and isinstance(prompt, list):+ batch_size = len(prompt)+ else:+ batch_size = prompt_embeds.shape[0]++ prompt_embeds = None++ if prompt_embeds is None:+ # textual inversion: process multi-vector tokens if necessary+ if isinstance(self, TextualInversionLoaderMixin):+ prompt = self.maybe_convert_prompt(prompt, text_encoder.tokenizer)+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type, name=name) # data_type: video, text_inputs: {'input_ids', 'attention_mask'}++ text_keys = ['input_ids', 'attention_mask']++ if pixel_value_llava is not None:+ text_inputs['pixel_value_llava'] = pixel_value_llava+ text_inputs['attention_mask'] = torch.cat([text_inputs['attention_mask'], torch.ones((1, 575)).to(text_inputs['attention_mask'])], dim=1)+++ if clip_skip is None:+ prompt_outputs = text_encoder.encode(text_inputs, data_type=data_type)+ prompt_embeds = prompt_outputs.hidden_state+ else:+ prompt_outputs = text_encoder.encode(text_inputs, output_hidden_states=True, data_type=data_type)+ # Access the `hidden_states` first, that contains a tuple of+ # all the hidden states from the encoder layers. Then index into+ # the tuple to access the hidden states from the desired layer.+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]+ # We also need to apply the final LayerNorm here to not mess with the+ # representations. The `last_hidden_states` that we typically use for+ # obtaining the final prompt representations passes through the LayerNorm+ # layer.+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(prompt_embeds)++ attention_mask = prompt_outputs.attention_mask+ if attention_mask is not None:+ attention_mask = attention_mask.to(device)+ bs_embed, seq_len = attention_mask.shape+ attention_mask = attention_mask.repeat(1, num_images_per_prompt)+ attention_mask = attention_mask.view(bs_embed * num_images_per_prompt, seq_len)++ if text_encoder is not None:+ prompt_embeds_dtype = text_encoder.dtype+ elif self.unet is not None:+ prompt_embeds_dtype = self.unet.dtype+ else:+ prompt_embeds_dtype = prompt_embeds.dtype++ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)++ if prompt_embeds.ndim == 2:+ bs_embed, _ = prompt_embeds.shape+ # duplicate text embeddings for each generation per prompt, using mps friendly method+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, -1)+ else:+ bs_embed, seq_len, _ = prompt_embeds.shape+ # duplicate text embeddings for each generation per prompt, using mps friendly method+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)++ # get unconditional embeddings for classifier free guidance+ if do_classifier_free_guidance and negative_prompt_embeds is None:+ uncond_tokens: List[str]+ if negative_prompt is None:+ uncond_tokens = [""] * batch_size+ elif prompt is not None and type(prompt) is not type(negative_prompt):+ raise TypeError(+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="+ f" {type(prompt)}."+ )+ elif isinstance(negative_prompt, str):+ uncond_tokens = [negative_prompt]+ elif batch_size != len(negative_prompt):+ raise ValueError(+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"+ " the batch size of `prompt`."+ )+ else:+ uncond_tokens = negative_prompt++ # textual inversion: process multi-vector tokens if necessary+ if isinstance(self, TextualInversionLoaderMixin):+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, text_encoder.tokenizer)+ # max_length = prompt_embeds.shape[1]+ uncond_input = text_encoder.text2tokens(uncond_tokens, data_type=data_type, name=name)++ # if hasattr(text_encoder.model.config, "use_attention_mask") and text_encoder.model.config.use_attention_mask:+ # attention_mask = uncond_input.attention_mask.to(device)+ # else:+ # attention_mask = None+ if uncond_pixel_value_llava is not None:+ uncond_input['pixel_value_llava'] = uncond_pixel_value_llava+ uncond_input['attention_mask'] = torch.cat([uncond_input['attention_mask'], torch.ones((1, 575)).to(uncond_input['attention_mask'])], dim=1)++ negative_prompt_outputs = text_encoder.encode(uncond_input, data_type=data_type)+ negative_prompt_embeds = negative_prompt_outputs.hidden_state++ negative_attention_mask = negative_prompt_outputs.attention_mask+ if negative_attention_mask is not None:+ negative_attention_mask = negative_attention_mask.to(device)+ _, seq_len = negative_attention_mask.shape+ negative_attention_mask = negative_attention_mask.repeat(1, num_images_per_prompt)+ negative_attention_mask = negative_attention_mask.view(batch_size * num_images_per_prompt, seq_len)++ if do_classifier_free_guidance:+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method+ seq_len = negative_prompt_embeds.shape[1]++ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)++ if negative_prompt_embeds.ndim == 2:+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt)+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, -1)+ else:+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)++ if text_encoder is not None:+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:+ # Retrieve the original scale by scaling back the LoRA layers+ unscale_lora_layers(text_encoder.model, lora_scale)++ return prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask++ def decode_latents(self, latents, enable_tiling=True):+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)++ latents = 1 / self.vae.config.scaling_factor * latents+ if enable_tiling:+ self.vae.enable_tiling()+ image = self.vae.decode(latents, return_dict=False)[0]+ self.vae.disable_tiling()+ else:+ image = self.vae.decode(latents, return_dict=False)[0]+ image = (image / 2 + 0.5).clamp(0, 1)+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16+ if image.ndim==4: image = image.cpu().permute(0, 2, 3, 1).float()+ else: image = image.cpu().float()+ return image++ def prepare_extra_func_kwargs(self, func, kwargs):+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature+ # eta (Ξ·) is only used with the DDIMScheduler, it will be ignored for other schedulers.+ # eta corresponds to Ξ· in DDIM paper: https://arxiv.org/abs/2010.02502+ # and should be between [0, 1]+ extra_step_kwargs = {}++ for k, v in kwargs.items():+ accepts = k in set(inspect.signature(func).parameters.keys())+ if accepts:+ extra_step_kwargs[k] = v+ return extra_step_kwargs++ def check_inputs(+ self,+ prompt,+ height,+ width,+ frame,+ callback_steps,+ pixel_value_llava=None,+ uncond_pixel_value_llava=None,+ negative_prompt=None,+ prompt_embeds=None,+ negative_prompt_embeds=None,+ callback_on_step_end_tensor_inputs=None,+ vae_ver='88-4c-sd'+ ):+ if height % 8 != 0 or width % 8 != 0:+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")++ if frame is not None:+ if '884' in vae_ver:+ if frame!=1 and (frame-1)%4!=0:+ raise ValueError(f'`frame` has to be 1 or a multiple of 4 but is {frame}.')+ elif '888' in vae_ver:+ if frame!=1 and (frame-1)%8!=0:+ raise ValueError(f'`frame` has to be 1 or a multiple of 8 but is {frame}.')++ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):+ raise ValueError(+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"+ f" {type(callback_steps)}."+ )+ if callback_on_step_end_tensor_inputs is not None and not all(+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs+ ):+ raise ValueError(+ 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]}"+ )++ if prompt is not None and prompt_embeds is not None:+ raise ValueError(+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"+ " only forward one of the two."+ )+ elif prompt is None and prompt_embeds is None:+ raise ValueError(+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."+ )+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")++ if negative_prompt is not None and negative_prompt_embeds is not None:+ raise ValueError(+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."+ )++ if pixel_value_llava is not None and uncond_pixel_value_llava is not None:+ if len(pixel_value_llava) != len(uncond_pixel_value_llava):+ raise ValueError(+ "`pixel_value_llava` and `uncond_pixel_value_llava` must have the same length when passed directly, but"+ f" got: `pixel_value_llava` {len(pixel_value_llava)} != `uncond_pixel_value_llava`"+ f" {len(uncond_pixel_value_llava)}."+ )++ if prompt_embeds is not None and negative_prompt_embeds is not None:+ if prompt_embeds.shape != negative_prompt_embeds.shape:+ raise ValueError(+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"+ f" {negative_prompt_embeds.shape}."+ )++ def get_timesteps(self, num_inference_steps, strength, device):+ # get the original timestep using init_timestep+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)++ t_start = max(num_inference_steps - init_timestep, 0)+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]+ if hasattr(self.scheduler, "set_begin_index"):+ self.scheduler.set_begin_index(t_start * self.scheduler.order)++ return timesteps.to(device), num_inference_steps - t_start++ def prepare_latents(self, batch_size, num_channels_latents, height, width, frame, dtype, device, generator, latents=None, ref_latents=None, timestep=None):+ shape = (+ batch_size,+ num_channels_latents,+ frame,+ int(height) // self.vae_scale_factor,+ int(width) // self.vae_scale_factor,+ )+ if isinstance(generator, list) and len(generator) != batch_size:+ raise ValueError(+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."+ )++ if latents is None:+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)+ else:+ latents = latents.to(device)+++ if timestep is not None:+ init_latents = ref_latents.clone().repeat(1,1,frame,1,1).to(device).to(dtype)+ latents = latents++ # Check existence to make it compatible with FlowMatchEulerDiscreteScheduler+ if hasattr(self.scheduler, "init_noise_sigma"):+ latents = latents * self.scheduler.init_noise_sigma++ return latents++ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding+ def get_guidance_scale_embedding(+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32+ ) -> torch.Tensor:+ """+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298++ Args:+ w (`torch.Tensor`):+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.+ embedding_dim (`int`, *optional*, defaults to 512):+ Dimension of the embeddings to generate.+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):+ Data type of the generated embeddings.++ Returns:+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.+ """+ assert len(w.shape) == 1+ w = w * 1000.0++ half_dim = embedding_dim // 2+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)+ emb = w.to(dtype)[:, None] * emb[None, :]+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)+ if embedding_dim % 2 == 1: # zero pad+ emb = torch.nn.functional.pad(emb, (0, 1))+ assert emb.shape == (w.shape[0], embedding_dim)+ return emb++ @property+ def guidance_scale(self):+ return self._guidance_scale++ @property+ def guidance_rescale(self):+ return self._guidance_rescale++ @property+ def clip_skip(self):+ return self._clip_skip++ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`+ # corresponds to doing no classifier free guidance.+ @property+ def do_classifier_free_guidance(self):+ # return self._guidance_scale > 1 and self.transformer.config.time_cond_proj_dim is None+ return self._guidance_scale > 1++ @property+ def cross_attention_kwargs(self):+ return self._cross_attention_kwargs++ @property+ def num_timesteps(self):+ return self._num_timesteps++ @property+ def interrupt(self):+ return self._interrupt++ @torch.no_grad()+ @replace_example_docstring(EXAMPLE_DOC_STRING)+ def __call__(+ self,+ prompt: Union[str, List[str]],++ ref_latents: Union[torch.Tensor], # [1, 16, 1, h//8, w//8]+ # uncond_ref_latents: Union[torch.Tensor],+ pixel_value_llava: Union[torch.Tensor], # [1, 3, 336, 336]+ uncond_pixel_value_llava: Union[torch.Tensor],- pixel_value_ref,++ pixel_value_ref: Union[torch.Tensor],+ face_masks: Union[torch.Tensor], # [b f h w]+ audio_prompts: Union[torch.Tensor],+ uncond_audio_prompts: Union[torch.Tensor],+ motion_exp: Union[torch.Tensor],+ motion_pose: Union[torch.Tensor],+ fps: Union[torch.Tensor],++ height: int,+ width: int,+ video_length: int,+ data_type: str = "video",+ num_inference_steps: int = 50,+ timesteps: List[int] = None,+ sigmas: List[float] = None,+ guidance_scale: float = 7.5,+ negative_prompt: Optional[Union[str, List[str]]] = None,+ num_videos_per_prompt: Optional[int] = 1,+ eta: float = 0.0,+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,+ latents: Optional[torch.Tensor] = None,+ prompt_embeds: Optional[torch.Tensor] = None,+ attention_mask: Optional[torch.Tensor] = None,+ negative_prompt_embeds: Optional[torch.Tensor] = None,+ negative_attention_mask: Optional[torch.Tensor] = None,+ output_type: Optional[str] = "pil",+ return_dict: bool = True,+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,+ guidance_rescale: float = 0.0,+ clip_skip: Optional[int] = None,+ callback_on_step_end: Optional[+ Union[+ Callable[[int, int, Dict], None],+ PipelineCallback,+ MultiPipelineCallbacks,+ ]+ ] = None,+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,+ vae_ver: str = "88-4c-sd",+ enable_tiling: bool = False,+ n_tokens: Optional[int] = None,+ embedded_guidance_scale: Optional[float] = None,+ joint_pass = False,+ cfg_star_rescale = False,+ name = None,+ **kwargs,+ ):+ r"""+ The call function to the pipeline for generation.++ Args:+ prompt (`str` or `List[str]`):+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.+ height (`int`):+ The height in pixels of the generated image.+ width (`int`):+ The width in pixels of the generated image.+ video_length (`int`):+ The number of frames in the generated video.+ num_inference_steps (`int`, *optional*, defaults to 50):+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the+ expense of slower inference.+ timesteps (`List[int]`, *optional*):+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is+ passed will be used. Must be in descending order.+ sigmas (`List[float]`, *optional*):+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed+ will be used.+ guidance_scale (`float`, *optional*, defaults to 7.5):+ A higher guidance scale value encourages the model to generate images closely linked to the text+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.+ negative_prompt (`str` or `List[str]`, *optional*):+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).+ num_videos_per_prompt (`int`, *optional*, defaults to 1):+ The number of images to generate per prompt.+ eta (`float`, *optional*, defaults to 0.0):+ Corresponds to parameter eta (Ξ·) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make+ generation deterministic.+ latents (`torch.Tensor`, *optional*):+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents+ tensor is generated by sampling using the supplied random `generator`.+ prompt_embeds (`torch.Tensor`, *optional*):+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not+ provided, text embeddings are generated from the `prompt` input argument.+ negative_prompt_embeds (`torch.Tensor`, *optional*):+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.++ output_type (`str`, *optional*, defaults to `"pil"`):+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.+ return_dict (`bool`, *optional*, defaults to `True`):+ Whether or not to return a [`HunyuanVideoPipelineOutput`] instead of a+ plain tuple.+ cross_attention_kwargs (`dict`, *optional*):+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).+ guidance_rescale (`float`, *optional*, defaults to 0.0):+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when+ using zero terminal SNR.+ clip_skip (`int`, *optional*):+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that+ the output of the pre-final layer will be used for computing the prompt embeddings.+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.+ callback_on_step_end_tensor_inputs (`List`, *optional*):+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the+ `._callback_tensor_inputs` attribute of your pipeline class.++ Examples:++ Returns:+ [`~HunyuanVideoPipelineOutput`] or `tuple`:+ If `return_dict` is `True`, [`HunyuanVideoPipelineOutput`] is returned,+ otherwise a `tuple` is returned where the first element is a list with the generated images and the+ second element is a list of `bool`s indicating whether the corresponding generated image contains+ "not-safe-for-work" (nsfw) content.+ """+ callback = kwargs.pop("callback", None)+ callback_steps = kwargs.pop("callback_steps", None)+ if callback_steps is not None:+ deprecate(+ "callback_steps",+ "1.0.0",+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",+ )++ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs+++ # num_inference_steps = 50++ # 0. Default height and width to transformer+ # height = height or self.transformer.config.sample_size * self.vae_scale_factor+ # width = width or self.transformer.config.sample_size * self.vae_scale_factor+ # to deal with lora scaling and other possible forward hooks++ transformer = self.transformer++ if transformer.enable_teacache:+ teacache_multiplier = transformer.teacache_multiplier+ transformer.accumulated_rel_l1_distance = 0+ transformer.rel_l1_thresh = 0.1 if teacache_multiplier < 2 else 0.15++ # 1. Check inputs. Raise error if not correct+ self.check_inputs(+ prompt,+ height,+ width,+ video_length,+ callback_steps,+ pixel_value_llava,+ uncond_pixel_value_llava,+ negative_prompt,+ prompt_embeds,+ negative_prompt_embeds,+ callback_on_step_end_tensor_inputs,+ vae_ver=vae_ver+ )++ self._guidance_scale = guidance_scale+ self.start_cfg_scale = guidance_scale+ self._guidance_rescale = guidance_rescale+ self._clip_skip = clip_skip+ self._cross_attention_kwargs = cross_attention_kwargs+ self._interrupt = False++ # 2. Define call parameters+ if prompt is not None and isinstance(prompt, str):+ batch_size = 1+ elif prompt is not None and isinstance(prompt, list):+ batch_size = len(prompt)+ else:+ batch_size = prompt_embeds.shape[0]++ device = self._execution_device++ # 3. Encode input prompt+ lora_scale = (+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None+ )+++ # ========== Encode text prompt (image prompt) ==========+ prompt_embeds, negative_prompt_embeds, prompt_mask, negative_prompt_mask = \+ self.encode_prompt_audio_text_base(+ prompt=prompt,+ uncond_prompt=negative_prompt,+ pixel_value_llava=pixel_value_llava,+ uncond_pixel_value_llava=uncond_pixel_value_llava,+ device=device,+ num_images_per_prompt=num_videos_per_prompt,+ do_classifier_free_guidance=self.do_classifier_free_guidance,+ negative_prompt=negative_prompt,+ prompt_embeds=prompt_embeds,+ negative_prompt_embeds=negative_prompt_embeds,+ lora_scale=lora_scale,+ clip_skip=self.clip_skip,+ text_encoder=self.text_encoder,+ data_type=data_type,+ name= name,+ # **kwargs+ )+ if self.text_encoder_2 is not None:+ prompt_embeds_2, negative_prompt_embeds_2, prompt_mask_2, negative_prompt_mask_2 = \+ self.encode_prompt_audio_text_base(+ prompt=prompt,+ uncond_prompt=negative_prompt,+ pixel_value_llava=None,+ uncond_pixel_value_llava=None,+ device=device,+ num_images_per_prompt=num_videos_per_prompt,+ do_classifier_free_guidance=self.do_classifier_free_guidance,+ negative_prompt=negative_prompt,+ prompt_embeds=None,+ negative_prompt_embeds=None,+ lora_scale=lora_scale,+ clip_skip=self.clip_skip,+ text_encoder=self.text_encoder_2,+ # **kwargs+ )+ else:+ prompt_embeds_2 = None+ negative_prompt_embeds_2 = None+ prompt_mask_2 = None+ negative_prompt_mask_2 = None++ if self.transformer.mixed_precision:+ latent_dtype = torch.float32+ else:+ latent_dtype = torch.bfloat16+ if prompt_embeds != None:+ prompt_embeds = prompt_embeds.to(torch.bfloat16)+ if negative_prompt_embeds != None:+ negative_prompt_embeds = negative_prompt_embeds.to(torch.bfloat16)+ if prompt_embeds_2 != None:+ prompt_embeds_2 = prompt_embeds_2.to(torch.bfloat16)+ if negative_prompt_embeds_2 != None:+ negative_prompt_embeds_2 = negative_prompt_embeds_2.to(torch.bfloat16)+ if audio_prompts != None:+ audio_prompts = audio_prompts.to(torch.bfloat16)+ if face_masks!= None:+ face_masks = face_masks.to(torch.bfloat16)+ if ref_latents != None:+ ref_latents = ref_latents.to(torch.bfloat16)++ # For classifier free guidance, we need to do two forward passes.+ # Here we concatenate the unconditional and text embeddings into a single batch+ # to avoid doing two forward passes+ if self.do_classifier_free_guidance:+ prompt_embeds_input = torch.cat([negative_prompt_embeds, prompt_embeds])+ if prompt_mask is not None:+ prompt_mask_input = torch.cat([negative_prompt_mask, prompt_mask])+ if prompt_embeds_2 is not None:+ prompt_embeds_2_input = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])+ if prompt_mask_2 is not None:+ prompt_mask_2_input = torch.cat([negative_prompt_mask_2, prompt_mask_2])++ if self.do_classifier_free_guidance and ref_latents != None:+ ref_latents = torch.cat([ref_latents, ref_latents], dim=0)+++ # 4. Prepare timesteps+ extra_set_timesteps_kwargs = self.prepare_extra_func_kwargs(+ self.scheduler.set_timesteps, {"n_tokens": n_tokens}+ )+ timesteps, num_inference_steps = retrieve_timesteps(+ self.scheduler, num_inference_steps, device, timesteps, sigmas, **extra_set_timesteps_kwargs,+ )++ video_length = audio_prompts.shape[1] // 4 * 4 + 1+ if "884" in vae_ver:+ video_length = (video_length - 1) // 4 + 1+ elif "888" in vae_ver:+ video_length = (video_length - 1) // 8 + 1+ else:+ video_length = video_length+++ # 5. Prepare latent variables+ num_channels_latents = self.transformer.config.in_channels+ infer_length = (audio_prompts.shape[1] // 128 + 1) * 32 + 1+ latents = self.prepare_latents(+ batch_size * num_videos_per_prompt,+ num_channels_latents,+ height,+ width,+ infer_length,+ latent_dtype, #prompt_embeds.dtype,+ device,+ generator,+ latents,+ ref_latents[-1:] if ref_latents != None else None,+ timesteps[:1]+ )++ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline+ extra_step_kwargs = self.prepare_extra_func_kwargs(+ self.scheduler.step, {"generator": generator, "eta": eta},+ )++ vae_precision = "fp16" # torch.float16+ precision = "bf16" # torch.bfloat16+ disable_autocast = True++ target_dtype = PRECISION_TO_TYPE[precision]+ autocast_enabled = (target_dtype != torch.float32) and not disable_autocast+ vae_dtype = self.vae._model_dtype #PRECISION_TO_TYPE[vae_precision]+ vae_autocast_enabled = (vae_dtype != torch.float32) and not disable_autocast++ # 7. Denoising loop+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order+ self._num_timesteps = len(timesteps)++ latents_all = latents.clone()+ pad_audio_length = (audio_prompts.shape[1] // 128 + 1) * 128 + 4 - audio_prompts.shape[1]+ audio_prompts_all = torch.cat([audio_prompts, torch.zeros_like(audio_prompts[:, :pad_audio_length])], dim=1)+++ shift = 0+ shift_offset = 10+ frames_per_batch = 33+ self.cache_tensor = None++ """ If the total length is shorter than 129, shift is not required """+ if video_length == 33 or infer_length == 33:+ infer_length = 33+ shift_offset = 0+ latents_all = latents_all[:, :, :33]+ audio_prompts_all = audio_prompts_all[:, :132]+ joint_pass = joint_pass or not self.do_classifier_free_guidance++ if callback != None:+ callback(-1, None, True, override_num_inference_steps = num_inference_steps)++ latent_items = 2 if self.do_classifier_free_guidance else 1++ fps = torch.from_numpy(np.array(fps)).unsqueeze(0).to(dtype=torch.float16)++ if self._interrupt:+ return [None]++ if transformer.enable_teacache:+ cache_size = round( infer_length / frames_per_batch )+ transformer.previous_residual = [None] * latent_items+ cache_all_previous_residual = [None] * latent_items+ cache_all_previous_modulated_input = None+ cache_should_calc = [True] * cache_size+ cache_accumulated_rel_l1_distance = [0.] * cache_size+ cache_teacache_skipped_steps = [0] * cache_size+++ with self.progress_bar(total=num_inference_steps) as progress_bar:+ for i, t in enumerate(timesteps):+ # init+ pred_latents = torch.zeros_like(+ latents_all,+ dtype=latents_all.dtype,+ )+ counter = torch.zeros(+ (latents_all.shape[0], latents_all.shape[1], infer_length, 1, 1),+ dtype=latents_all.dtype,+ ).to(device=latents_all.device)++ cache_slot_no = 0+ for index_start in range(0, infer_length, frames_per_batch):+ self.scheduler._step_index = None++ index_start = index_start - shift+ idx_list = [ii % latents_all.shape[2] for ii in range(index_start, index_start + frames_per_batch)]+ latents = latents_all[:, :, idx_list].clone()++ idx_list_audio = [ii % audio_prompts_all.shape[1] for ii in range(index_start * 4, (index_start + frames_per_batch) * 4 - 3)]+ audio_prompts = audio_prompts_all[:, idx_list_audio].clone()++ # expand the latents if we are doing classifier free guidance+ if self.do_classifier_free_guidance:+ latent_model_input = torch.cat([latents] * 2)+ else:+ latent_model_input = latents++ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)+ embedded_hw = (latent_model_input.shape[-1] // 2) * (latent_model_input.shape[-2] // 2) * 3072+ img_ref_len = (latent_model_input.shape[-1] // 2) * (latent_model_input.shape[-2] // 2) * ( 1)+ img_all_len = (latents_all.shape[-1] // 2) * (latents_all.shape[-2] // 2) * latents_all.shape[-3]++ if transformer.enable_teacache and cache_size > 1:+ for l in range(latent_items):+ if cache_all_previous_residual[l] != None:+ bsz = cache_all_previous_residual[l].shape[0]+ transformer.previous_residual[l][:, img_ref_len:] = cache_all_previous_residual[l].reshape(1, -1, embedded_hw) [:, idx_list].reshape(1, -1, 3072)+ if cache_all_previous_modulated_input != None:+ transformer.previous_modulated_input[:, img_ref_len:] = cache_all_previous_modulated_input.reshape(1, -1, embedded_hw) [:, idx_list].reshape(1, -1, 3072)+ transformer.should_calc = cache_should_calc[cache_slot_no]+ transformer.accumulated_rel_l1_distance = cache_accumulated_rel_l1_distance[cache_slot_no]+ transformer.teacache_skipped_steps = cache_teacache_skipped_steps[cache_slot_no]+++ if self.do_classifier_free_guidance:+ if i < num_inference_steps * 0.2 :+ self._guidance_scale = (1 - i / len(timesteps)) * (self.start_cfg_scale - 2) + 2+ audio_prompts_input = torch.cat([uncond_audio_prompts, audio_prompts], dim=0)+ face_masks_input = torch.cat([face_masks * 0.6] * 2, dim=0)+ else:+ # define 10-50 step cfg+ self._guidance_scale = (1 - i / len(timesteps)) * (6.5 - 3.5) + 3.5 # 5-2 +2++ prompt_embeds_input = torch.cat([prompt_embeds, prompt_embeds])+ if prompt_mask is not None:+ prompt_mask_input = torch.cat([prompt_mask, prompt_mask])+ if prompt_embeds_2 is not None:+ prompt_embeds_2_input = torch.cat([prompt_embeds_2, prompt_embeds_2])+ if prompt_mask_2 is not None:+ prompt_mask_2_input = torch.cat([prompt_mask_2, prompt_mask_2])+ audio_prompts_input = torch.cat([uncond_audio_prompts, audio_prompts], dim=0)+ face_masks_input = torch.cat([face_masks] * 2, dim=0)++ motion_exp_input = torch.cat([motion_exp] * 2, dim=0)+ motion_pose_input = torch.cat([motion_pose] * 2, dim=0)+ fps_input = torch.cat([fps] * 2, dim=0)++ else:+ audio_prompts_input = audio_prompts+ face_masks_input = face_masks+ motion_exp_input = motion_exp+ motion_pose_input = motion_pose+ fps_input = fps++ t_expand = t.repeat(latent_model_input.shape[0])+ guidance_expand = None++ with torch.autocast(device_type="cuda", dtype=target_dtype, enabled=autocast_enabled):+ additional_kwargs = {+ "pipeline": self,+ "step_no": i,+ }+ if joint_pass:+ additional_kwargs.update({+ "motion_exp": motion_exp_input,+ "motion_pose": motion_pose_input,+ "fps": fps_input,+ "audio_prompts": audio_prompts_input,+ "face_mask": face_masks_input+ })+ noise_pred = self.transformer(latent_model_input, t_expand, ref_latents=ref_latents, text_states=prompt_embeds_input, text_mask=prompt_mask_input, text_states_2=prompt_embeds_2_input, freqs_cos=freqs_cis[0], freqs_sin=freqs_cis[1], guidance=guidance_expand, **additional_kwargs,)+ if self._interrupt:+ return [None]+ if self.do_classifier_free_guidance:+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)+ else:+ additional_kwargs.update({+ "motion_exp": motion_exp_input[:1],+ "motion_pose": motion_pose_input[:1],+ "fps": fps_input[:1],+ "audio_prompts": audio_prompts_input[:1],+ "face_mask": face_masks_input[:1]+ })+ noise_pred_uncond = self.transformer(latent_model_input[:1], t_expand[:1], ref_latents=ref_latents[:1], text_states=prompt_embeds_input[:1], text_mask=prompt_mask_input[:1], text_states_2=prompt_embeds_2_input[:1], freqs_cos=freqs_cis[0], freqs_sin=freqs_cis[1], guidance=guidance_expand, x_id = 0, **additional_kwargs,)+ if self._interrupt:+ return [None]+ noise_pred_uncond = noise_pred_uncond[0]+ additional_kwargs.update({+ "motion_exp": motion_exp_input[1:],+ "motion_pose": motion_pose_input[1:],+ "fps": fps_input[1:],+ "audio_prompts": audio_prompts_input[1:],+ "face_mask": face_masks_input[1:]+ })+ noise_pred_text = self.transformer(latent_model_input[1:], t_expand[1:], ref_latents=ref_latents[1:], text_states=prompt_embeds_input[1:], text_mask=prompt_mask_input[1:], text_states_2=prompt_embeds_2_input[1:], freqs_cos=freqs_cis[0], freqs_sin=freqs_cis[1], guidance=guidance_expand, x_id = 1, **additional_kwargs,)+ if self._interrupt:+ return [None]+ noise_pred_text = noise_pred_text[0]++ # perform guidance+ if self.do_classifier_free_guidance:+ if cfg_star_rescale:+ batch_size = 1+ positive_flat = noise_pred_text.view(batch_size, -1)+ negative_flat = noise_pred_uncond.view(batch_size, -1)+ dot_product = torch.sum(+ positive_flat * negative_flat, dim=1, keepdim=True+ )+ squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8+ positive_flat, negative_flat = None, None+ alpha = dot_product / squared_norm+ noise_pred_uncond *= alpha++ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)++ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)+ noise_pred_text, noise_pred_uncond = None, None+ # compute the previous noisy sample x_t -> x_t-1+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]+ noise_pred = None++ latents = latents.to(torch.bfloat16)+ for iii in range(frames_per_batch):+ p = (index_start + iii) % pred_latents.shape[2]+ pred_latents[:, :, p] += latents[:, :, iii]+ counter[:, :, p] += 1++ if transformer.enable_teacache and cache_size > 1:+ for l in range(latent_items):+ if transformer.previous_residual[l] != None:+ bsz = transformer.previous_residual[l].shape[0]+ if cache_all_previous_residual[l] == None:+ cache_all_previous_residual[l] = torch.zeros((bsz, img_all_len, 3072 ), device=transformer.previous_residual[l].device, dtype=transformer.previous_residual[l].dtype)+ cache_all_previous_residual[l].reshape(bsz, -1, embedded_hw)[:, idx_list] = transformer.previous_residual[l][:, img_ref_len:].reshape(bsz, -1, embedded_hw)++ if transformer.previous_modulated_input != None:+ if cache_all_previous_modulated_input == None:+ cache_all_previous_modulated_input = torch.zeros((1, img_all_len, 3072 ), device=transformer.previous_modulated_input.device, dtype=transformer.previous_modulated_input.dtype)+ cache_all_previous_modulated_input.reshape(1, -1, embedded_hw)[:, idx_list] = transformer.previous_modulated_input[:, img_ref_len:].reshape(1, -1, embedded_hw)+ cache_should_calc[cache_slot_no] = transformer.should_calc+ cache_accumulated_rel_l1_distance[cache_slot_no] = transformer.accumulated_rel_l1_distance+ cache_teacache_skipped_steps[cache_slot_no] = transformer.teacache_skipped_steps++ cache_slot_no += 1++ shift += shift_offset+ shift = shift % frames_per_batch+ pred_latents = pred_latents / counter+ latents_all = pred_latents++ if callback is not None:+ callback(i, latents_all.squeeze(0), False)++ latents = latents_all.float()[:, :, :video_length]++ if not output_type == "latent":+ expand_temporal_dim = False+ if len(latents.shape) == 4:+ if isinstance(self.vae, AutoencoderKLCausal3D):+ latents = latents.unsqueeze(2)+ expand_temporal_dim = True+ elif len(latents.shape) == 5:+ pass+ else:+ raise ValueError(+ f"Only support latents with shape (b, c, h, w) or (b, c, f, h, w), but got {latents.shape}.")++ if hasattr(self.vae.config, 'shift_factor') and self.vae.config.shift_factor:+ latents = latents / self.vae.config.scaling_factor + self.vae.config.shift_factor+ else:+ latents = latents / self.vae.config.scaling_factor++ with torch.autocast(device_type="cuda", dtype=vae_dtype, enabled=vae_autocast_enabled):+ image = self.vae.decode(latents, return_dict=False, generator=generator)[0]+ if image is None:+ return (None, )++ if expand_temporal_dim or image.shape[2] == 1:+ image = image.squeeze(2)++ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16+ image = image.cpu().float()++ # Offload all models+ self.maybe_free_model_hooks()++ if not return_dict:+ return image++ return HunyuanVideoPipelineOutput(videos=image)diff --cc wgp.pyindex 1ae7ab2,45e0e50..b5ba519--- a/wgp.py+++ b/wgp.py@@@ -43,7 -43,7 +43,7 @@@ AUTOSAVE_FILENAME = "queue.zipPROMPT_VARS_MAX = 10target_mmgp_version = "3.4.7"--WanGP_version = "5.31"++WanGP_version = "5.4"prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, Nonefrom importlib.metadata import version@@@ -1255,6 -1251,6 +1255,14 @@@ def _parse_args()help="default denoising steps")++++ parser.add_argument(++ "--teacache",++ type=float,++ default=-1,++ help="teacache speed multiplier"++ )++parser.add_argument("--frames",type=int,@@@ -1768,14 -1758,7 +1776,15 @@@ def get_default_settings(filename)ui_defaults.update({"guidance_scale": 7.5,"flow_shift": 13,- "resolution": "1280x720"+ "resolution": "1280x720",+ })+ elif get_model_type(filename) in ("hunyuan_avatar"):+ ui_defaults.update({+ "guidance_scale": 7.5,+ "flow_shift": 5,+ "tea_cache_start_step_perc": 25,+ "video_length": 129,++ "video_prompt_type": "I",})elif get_model_type(filename) in ("vace_14B"):ui_defaults.update({@@@ -2874,7 -2838,7 +2883,9 @@@ def generate_videosend_cmd("output")joint_pass = boost ==1 #and profile != 1 and profile != 3-- # TeaCache++ # TeaCache++ if args.teacache > 0:++ tea_cache_setting = args.teacachetrans.enable_teacache = tea_cache_setting > 0if trans.enable_teacache:trans.teacache_multiplier = tea_cache_setting@@@ -3555,7 -3517,7 +3566,10 @@@ def generate_preview(latents)images = torch.nn.functional.conv3d(latents, weight, bias=bias, stride=1, padding=0, dilation=1, groups=1)images = images.add_(1.0).mul_(127.5)-- images = images.detach().cpu().numpy().clip(0, 255).astype(np.uint8)++ images = images.detach().cpu()++ if images.dtype == torch.bfloat16:++ images = images.to(torch.float16)++ images = images.numpy().clip(0, 255).astype(np.uint8)images = einops.rearrange(images, 'b c t h w -> (b h) (t w) c')h, w, _ = images.shapescale = 200 / h@@@ -5516,10 -5475,10 +5530,13 @@@ def generate_about_tab()gr.Markdown("Many thanks to:")gr.Markdown("- <B>Alibaba Wan team for the best open source video generator")gr.Markdown("- <B>Alibaba Vace and Fun Teams for their incredible control net models")++ gr.Markdown("- <B>Tencent for the impressive Hunyuan Video models")++ gr.Markdown("- <B>Lightricks for the super fast LTX Video models")gr.Markdown("- <B>Cocktail Peanuts</B> : QA and simple installation via Pinokio.computer")gr.Markdown("- <B>Tophness</B> : created (former) multi tabs and queuing frameworks")gr.Markdown("- <B>AmericanPresidentJimmyCarter</B> : added original support for Skip Layer Guidance")gr.Markdown("- <B>Remade_AI</B> : for their awesome Loras collection")++ gr.Markdown("- <B>Reevoy24</B> : for his repackaging / completing the documentation")gr.Markdown("<BR>Huge acknowlegments to these great open source projects used in WanGP:")gr.Markdown("- <B>Rife</B>: temporal upsampler (https://github.com/hzwer/ECCV2022-RIFE)")gr.Markdown("- <B>DwPose</B>: Open Pose extractor (https://github.com/IDEA-Research/DWPose)")@@@ -5528,14 -5487,14 +5545,25 @@@def generate_info_tab():-- gr.Markdown("<FONT SIZE=3>Welcome to WanGP a super fast and low VRAM AI Video Generator !</FONT>")---- gr.Markdown("The VRAM requirements will depend greatly of the resolution and the duration of the video, for instance :")-- gr.Markdown("- 848 x 480 with a 14B model: 80 frames (5s) : 8 GB of VRAM")-- gr.Markdown("- 848 x 480 with the 1.3B model: 80 frames (5s) : 5 GB of VRAM")-- gr.Markdown("- 1280 x 720 with a 14B model: 80 frames (5s): 11 GB of VRAM")-- gr.Markdown("It is not recommmended to generate a video longer than 8s (128 frames) even if there is still some VRAM left as some artifacts may appear")-- gr.Markdown("Please note that if your turn on compilation, the first denoising step of the first video generation will be slow due to the compilation. Therefore all your tests should be done with compilation turned off.")++++++ with open("docs/VACE.md", "r", encoding="utf-8") as reader:++ vace= reader.read()++++ with open("docs/MODELS.md", "r", encoding="utf-8") as reader:++ models = reader.read()++++ with open("docs/LORAS.md", "r", encoding="utf-8") as reader:++ loras = reader.read()++++ with gr.Tabs() :++ with gr.Tab("Models", id="models"):++ gr.Markdown(models)++ with gr.Tab("Loras", id="loras"):++ gr.Markdown(loras)++ with gr.Tab("Vace", id="vace"):++ gr.Markdown(vace)++def generate_dropdown_model_list(model_filename):@@@ -5942,7 -5901,7 +5970,7 @@@ def create_ui()( state, loras_choices, lset_name, state,video_guide, video_mask, image_refs, video_prompt_type_video_trigger, prompt_enhancer_row) = generate_video_tab(model_choice=model_choice, header=header, main = main)-- with gr.Tab("Informations", id="info"):++ with gr.Tab("Guides", id="info"):generate_info_tab()with gr.Tab("Video Mask Creator", id="video_mask_creator") as video_mask_creator:from preprocessing.matanyone import app as matanyone_app