Spaces:
Running on Zero
Running on Zero
Initial VitronEdit demo
Browse filesFiles changed (47)
- .gitattributes+7
- License.txtAdded+78
- Notice.txtAdded+34
- README.md+20-30
- app.py+433-435
- examples/border_collie_running.mp4Added+3
- examples/cat.mp4Added+3
- examples/cat_tabby.jpgAdded
- examples/dog.jpgAdded
- examples/lighthouse_coast.jpgAdded
- examples/living_room_blue_couch.jpgAdded
- examples/red_fox.jpgAdded
- examples/rubber_ducks.jpgAdded
- hyvideo/__init__.pyAdded+44
- hyvideo/commons/__init__.pyAdded+176
- hyvideo/commons/infer_state.pyAdded+88
- hyvideo/commons/parallel_states.pyAdded+93
- hyvideo/models/__init__.pyAdded+16
- hyvideo/models/autoencoders/__init__.pyAdded+17
- hyvideo/models/autoencoders/hunyuanvideo_15_vae.pyAdded+898
- hyvideo/models/text_encoders/__init__.pyAdded+911
- hyvideo/models/text_encoders/byT5/__init__.pyAdded+229
- hyvideo/models/text_encoders/byT5/format_prompt.pyAdded+86
- hyvideo/models/transformers/hunyuanvideo_1_5_transformer.pyAdded+1015
- hyvideo/models/transformers/modules/activation_layers.pyAdded+39
- hyvideo/models/transformers/modules/attention.pyAdded+298
- hyvideo/models/transformers/modules/embed_layers.pyAdded+213
- hyvideo/models/transformers/modules/mlp_layers.pyAdded+137
- hyvideo/models/transformers/modules/modulate_layers.pyAdded+92
- hyvideo/models/transformers/modules/norm_layers.pyAdded+97
- hyvideo/models/transformers/modules/posemb_layers.pyAdded+330
- hyvideo/models/transformers/modules/ssta_attention.pyAdded+700
- hyvideo/models/transformers/modules/token_refiner.pyAdded+283
- hyvideo/models/vision_encoder/__init__.pyAdded+235
- hyvideo/optim/muon.pyAdded+234
- hyvideo/pipelines/hunyuan_video_pipeline.pyAdded
- hyvideo/pipelines/pipeline_utils.pyAdded+101
- hyvideo/schedulers/scheduling_flow_match_discrete.pyAdded+292
- hyvideo/utils/communications.pyAdded+314
- hyvideo/utils/data_utils.pyAdded+73
- hyvideo/utils/flash_attn_no_pad.pyAdded+95
- hyvideo/utils/multitask_utils.pyAdded+120
- requirements.txt+11-20
- univedit/__init__.pyAdded+1
- univedit/data/__init__.pyAdded+1
- univedit/data/preprocessing.pyAdded+232
- univedit/tokens.pyAdded+40
35 unmodified lines36373835 unmodified linesexamples_assets/couple.jpg filter=lfs diff=lfs merge=lfs -textexamples_assets/dog.jpg filter=lfs diff=lfs merge=lfs -textexamples_assets/robot.png filter=lfs diff=lfs merge=lfs -text35 unmodified lines3637383940414243444535 unmodified linesexamples_assets/couple.jpg filter=lfs diff=lfs merge=lfs -textexamples_assets/dog.jpg filter=lfs diff=lfs merge=lfs -textexamples_assets/robot.png filter=lfs diff=lfs merge=lfs -textexamples/border_collie_running.mp4 filter=lfs diff=lfs merge=lfs -textexamples/cat.mp4 filter=lfs diff=lfs merge=lfs -textexamples/cat_tabby.jpg filter=lfs diff=lfs merge=lfs -textexamples/dog.jpg filter=lfs diff=lfs merge=lfs -textexamples/lighthouse_coast.jpg filter=lfs diff=lfs merge=lfs -textexamples/living_room_blue_couch.jpg filter=lfs diff=lfs merge=lfs -textexamples/red_fox.jpg filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778TENCENT HY COMMUNITY LICENSE AGREEMENTTencent HY-OmniWeaving Release Date: March 31, 2026THIS LICENSE AGREEMENT DOES NOT APPLY IN THE EUROPEAN UNION, UNITED KINGDOM AND SOUTH KOREA AND IS EXPRESSLY LIMITED TO THE TERRITORY, AS DEFINED BELOW.By clicking to agree or by using, reproducing, modifying, distributing, performing or displaying any portion or element of the Tencent HY Works, including via any Hosted Service, You will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.1. DEFINITIONS.a. “Acceptable Use Policy” shall mean the policy made available by Tencent as set forth in the Exhibit A.b. “Agreement” shall mean the terms and conditions for use, reproduction, distribution, modification, performance and displaying of Tencent HY Works or any portion or element thereof set forth herein.c. “Documentation” shall mean the specifications, manuals and documentation for Tencent HY made publicly available by Tencent.d. “Hosted Service” shall mean a hosted service offered via an application programming interface (API), web access, or any other electronic or remote means.e. “Licensee,” “You” or “Your” shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Tencent HY Works for any purpose and in any field of use.f. “Materials” shall mean, collectively, Tencent’s proprietary Tencent HY and Documentation (and any portion thereof) as made available by Tencent under this Agreement.g. “Model Derivatives” shall mean all: (i) modifications to Tencent HY or any Model Derivative of Tencent HY; (ii) works based on Tencent HY or any Model Derivative of Tencent HY; or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Tencent HY or any Model Derivative of Tencent HY, to that model in order to cause that model to perform similarly to Tencent HY or a Model Derivative of Tencent HY, including distillation methods, methods that use intermediate data representations, or methods based on the generation of synthetic data Outputs by Tencent HY or a Model Derivative of Tencent HY for training that model. For clarity, Outputs by themselves are not deemed Model Derivatives.h. “Output” shall mean the information and/or content output of Tencent HY or a Model Derivative that results from operating or otherwise using Tencent HY or a Model Derivative, including via a Hosted Service.i. “Tencent,” “We” or “Us” shall mean the applicable entity or entities in the Tencent corporate family that own(s) intellectual property or other rights embodied in or utilized by the Materials.j. “Tencent HY” shall mean the large language models, text/image/video/audio/3D generation models, and multimodal large language models and their software and algorithms, including trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing made publicly available by Us, including, without limitation to, Tencent HY-OmniWeaving released at https://github.com/Tencent-Hunyuan/OmniWeaving.k. “Tencent HY Works” shall mean: (i) the Materials; (ii) Model Derivatives; and (iii) all derivative works thereof.l. “Territory” shall mean the worldwide territory, excluding the territory of the European Union, United Kingdom and South Korea. m. “Third Party” or “Third Parties” shall mean individuals or legal entities that are not under common control with Us or You.n. “including” shall mean including but not limited to.2. GRANT OF RIGHTS.We grant You, for the Territory only, a non-exclusive, non-transferable and royalty-free limited license under Tencent’s intellectual property or other rights owned by Us embodied in or utilized by the Materials to use, reproduce, distribute, create derivative works of (including Model Derivatives), and make modifications to the Materials, only in accordance with the terms of this Agreement and the Acceptable Use Policy, and You must not violate (or encourage or permit anyone else to violate) any term of this Agreement or the Acceptable Use Policy.3. DISTRIBUTION.You may, subject to Your compliance with this Agreement, distribute or make available to Third Parties the Tencent HY Works, exclusively in the Territory, provided that You meet all of the following conditions:a. You must provide all such Third Party recipients of the Tencent HY Works or products or services using them a copy of this Agreement;b. You must cause any modified files to carry prominent notices stating that You changed the files;c. You are encouraged to: (i) publish at least one technology introduction blogpost or one public statement expressing Your experience of using the Tencent HY Works; and (ii) mark the products or services developed by using the Tencent HY Works to indicate that the product/service is “Powered by Tencent HY”; andd. All distributions to Third Parties (other than through a Hosted Service) must be accompanied by a “Notice” text file that contains the following notice: “Tencent HY is licensed under the Tencent HY Community License Agreement, Copyright © 2026 Tencent. All Rights Reserved. The trademark rights of “Tencent HY” are owned by Tencent or its affiliate.”e. In the event that You use, integrate, implement, or otherwise deploy the Tencent HY Works, in whole or in part, to provide, enable, or support any service, product, or functionality to third parties, You shall clearly, accurately, and prominently disclose to all end users the full legal name and entity of the actual provider of such service, product, or functionality. You shall expressly and conspicuously state that Tencent is not affiliated with, associated with, sponsoring, or endorsing any such service, product, or functionality. You shall not use or display any name, logo, trademark, trade name, or other indicia of Tencent in any manner that could be construed as, or be likely to create, confusion, deception, or a false impression regarding any relationship, affiliation, sponsorship, or endorsement by Tencent.You may add Your own copyright statement to Your modifications and, except as set forth in this Section and in Section 5, may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Model Derivatives as a whole, provided Your use, reproduction, modification, distribution, performance and display of the work otherwise complies with the terms and conditions of this Agreement (including as regards the Territory). If You receive Tencent HY Works from a Licensee as part of an integrated end user product, then this Section 3 of this Agreement will not apply to You.4. ADDITIONAL COMMERCIAL TERMS.If, on the Tencent HY version release date, the monthly active users of all products or services made available by or for Licensee is greater than 100 million monthly active users in the preceding calendar month, You must request a license from Tencent, which Tencent may grant to You in its sole discretion, and You are not authorized to exercise any of the rights under this Agreement unless or until Tencent otherwise expressly grants You such rights.5. RULES OF USE.a. Your use of the Tencent HY Works must comply with applicable laws and regulations (including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for the Tencent HY Works, which is hereby incorporated by reference into this Agreement. You must include the use restrictions referenced in these Sections 5(a) and 5(b) as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Tencent HY Works and You must provide notice to subsequent users to whom You distribute that Tencent HY Works are subject to the use restrictions in these Sections 5(a) and 5(b).b. You must not use the Tencent HY Works or any Output or results of the Tencent HY Works to improve any other AI model (other than Tencent HY or Model Derivatives thereof).c. You must not use, reproduce, modify, distribute, or display the Tencent HY Works, Output or results of the Tencent HY Works outside the Territory. Any such use outside the Territory is unlicensed and unauthorized under this Agreement.6. INTELLECTUAL PROPERTY.a. Subject to Tencent’s ownership of Tencent HY Works made by or for Tencent and intellectual property rights therein, conditioned upon Your compliance with the terms and conditions of this Agreement, as between You and Tencent, You will be the owner of any derivative works and modifications of the Materials and any Model Derivatives that are made by or for You.b. No trademark licenses are granted under this Agreement, and in connection with the Tencent HY Works, Licensee may not use any name or mark owned by or associated with Tencent or any of its affiliates, except as required for reasonable and customary use in describing and distributing the Tencent HY Works. Tencent hereby grants You a license to use “Tencent HY” (the “Mark”) in the Territory solely as required to comply with the provisions of Section 3(c), provided that You comply with any applicable laws related to trademark protection. All goodwill arising out of Your use of the Mark will inure to the benefit of Tencent.c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us or any person or entity alleging that the Materials or any Output, or any portion of any of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licenses granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is filed. You will defend, indemnify and hold harmless Us from and against any claim by any Third Party arising out of or related to Your or the Third Party’s use or distribution of the Tencent HY Works.d. Tencent claims no rights in Outputs You generate. You and Your users are solely responsible for Outputs and their subsequent uses.7. DISCLAIMERS OF WARRANTY AND LIMITATIONS OF LIABILITY.a. We are not obligated to support, update, provide training for, or develop any further version of the Tencent HY Works or to grant any license thereto.b. UNLESS AND ONLY TO THE EXTENT REQUIRED BY APPLICABLE LAW, THE TENCENT HY WORKS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED “AS IS” WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND INCLUDING ANY WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, COURSE OF DEALING, USAGE OF TRADE, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE TENCENT HY WORKS OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR OR A THIRD PARTY’S USE OR DISTRIBUTION OF ANY OF THE TENCENT HY WORKS OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.c. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL TENCENT OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO ANY OF THE TENCENT HY WORKS OR OUTPUTS, EVEN IF TENCENT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.8. SURVIVAL AND TERMINATION.a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must promptly delete and cease use of the Tencent HY Works. Sections 6(a), 6(c), 7 and 9 shall survive the termination of this Agreement.9. GOVERNING LAW AND JURISDICTION.a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of the Hong Kong Special Administrative Region of the People’s Republic of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.b. Exclusive jurisdiction and venue for any dispute arising out of or relating to this Agreement will be a court of competent jurisdiction in the Hong Kong Special Administrative Region of the People’s Republic of China, and Tencent and Licensee consent to the exclusive jurisdiction of such court with respect to any such dispute. EXHIBIT AACCEPTABLE USE POLICY
Tencent reserves the right to update this Acceptable Use Policy from time to time.Last modified: December 30, 2025
Tencent endeavors to promote safe and fair use of its tools and features, including Tencent HY. You agree not to use Tencent HY or Model Derivatives:1. Outside the Territory;2. In any way that violates any applicable national, federal, state, local, international or any other law or regulation;3. To harm Yourself or others;4. To repurpose or distribute output from Tencent HY or any Model Derivatives to harm Yourself or others; 5. To override or circumvent the safety guardrails and safeguards We have put in place;6. For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;7. To generate or disseminate verifiably false information and/or content with the purpose of harming others or influencing elections;8. To generate or facilitate false online engagement, including fake reviews and other means of fake online engagement;9. To intentionally defame, disparage or otherwise harass others;10. To generate and/or disseminate malware (including ransomware) or any other content to be used for the purpose of harming electronic systems;11. To generate or disseminate personal identifiable information with the purpose of harming others;12. To generate or disseminate information (including images, code, posts, articles), and place the information in any public context (including –through the use of bot generated tweets), without expressly and conspicuously identifying that the information and/or content is machine generated;13. To impersonate another individual without consent, authorization, or legal right;14. To make high-stakes automated decisions in domains that affect an individual’s safety, rights or wellbeing (e.g., law enforcement, migration, medicine/health, management of critical infrastructure, safety components of products, essential services, credit, employment, housing, education, social scoring, or insurance);15. In a manner that violates or disrespects the social ethics and moral standards of other countries or regions;16. To perform, facilitate, threaten, incite, plan, promote or encourage violent extremism or terrorism;17. For any use intended to discriminate against or harm individuals or groups based on protected characteristics or categories, online or offline social behavior or known or predicted personal or personality characteristics;18. To intentionally exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;19. For military purposes;20. To engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or other professional practices.12345678910111213141516171819202122232425262728293031323334Usage and Legal Notices:
Tencent is pleased to support the open source community by making Tencent HY-OmniWeaving available.
Copyright (C) 2026 Tencent. All rights reserved.
Tencent HY-OmniWeaving is licensed under the TENCENT HY COMMUNITY LICENSE AGREEMENT, except for the third-party components listed below, which remain licensed under their respective original terms. Tencent HY-OmniWeaving does not impose any additional restrictions beyond those specified in the original licenses of these third-party components. Users are required to comply with all applicable terms and conditions of the original licenses and to ensure that the use of these third-party components conforms to all relevant laws and regulations.
For the avoidance of doubt, Tencent HY-OmniWeaving refers solely to training code, inference code, parameters, and weights made publicly available by Tencent in accordance with the TENCENT HY COMMUNITY LICENSE AGREEMENT.
Open Source Model Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT:--------------------------------------------------------------------1. HunyuanVideo-1.5Copyright © 2025 TencentPlease note this model has been modified by Tencent in this distribution.
Terms of the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT:--------------------------------------------------------------------
Please find the license here: https://huggingface.co/tencent/HunyuanVideo-1.5/blob/main/LICENSE
Please find its third-party reliance here: https://huggingface.co/tencent/HunyuanVideo-1.5/blob/main/NOTICE
Modifications in this repository:--------------------------------------------------------------------This repository (UniVEdit) contains a modified copy of Tencent HY-OmniWeaving.Files under src/hyvideo/ that were changed, and files under src/univedit/ thatare derived from the Tencent HY-OmniWeaving training code, carry a "Modified bythe UniVEdit authors" header.
Tencent HY is licensed under the Tencent HY Community License Agreement, Copyright © 2026 Tencent. All Rights Reserved. The trademark rights of “Tencent HY” are owned by Tencent or its affiliate.5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445465 unmodified linessdk: gradiosdk_version: 6.30.0app_file: app.pyshort_description: Universal instruction-based image editingpython_version: "3.12"startup_duration_timeout: 1hpinned: false---# VitronEdit / UniVEdit — universal visual editingDemo of the **image-editing mode** of [VitronEdit: Universal Visual Editing acrossImages, Videos, and 3D Scenes](https://huggingface.co/papers/2610.27049) (arXiv 2610.27049).UniVEdit fine-tunes [Tencent HY-OmniWeaving](https://huggingface.co/tencent/HY-OmniWeaving)(HunyuanVideo-1.5 MMDiT with a Qwen2.5-VL-7B semantic encoder, SigLIP vision encoder andByT5 glyph encoder) with LoRA adapters and new modality tokens (`<T_IMG>`, `<T_VID>`,`<T_3D>`), giving one model that follows free-form edit instructions — add / remove /replace / restyle — across images, videos and 3D scenes.This Space runs the two image tasks of the framework:- **i2i** — instruction-based editing of a source image- **ti_i2i** — reference-guided editing: transfer a subject or style from a reference imageThe default sampling settings (50 steps, guidance 6.0, flow shift 5.0, image buckets up to624×352) follow the official `scripts/infer/batch.sh` of the[VitronEdit-Code](https://github.com/Vitron-LLM/VitronEdit-Code) repository, and the exampleinputs are the images shipped with that repository.- 📄 Paper: [huggingface.co/papers/2610.27049](https://huggingface.co/papers/2610.27049)- 💻 Code: [github.com/Vitron-LLM/VitronEdit-Code](https://github.com/Vitron-LLM/VitronEdit-Code)- 🤗 Checkpoint: [SanRiiiii/UniVEdit](https://huggingface.co/SanRiiiii/UniVEdit)## License notesThe UniVEdit code and weights derive from Tencent HY-OmniWeaving and are distributed underthe **Tencent HY Community License Agreement** (see `License.txt` / `Notice.txt` in the coderepository). This demo Space is a Hosted Service of that model. The example images come fromthe VitronEdit-Code repository and are shown here for demonstration of the model's ownpublished results.5 unmodified lines67891011121314151617181920212223242526272829303132333435365 unmodified linessdk: gradiosdk_version: 6.30.0app_file: app.pyshort_description: Instruction-based image & video editing (UniVEdit)python_version: "3.12"startup_duration_timeout: 1hlicense: otherlicense_name: tencent-hy-communitylicense_link: License.txtmodels:- SanRiiiii/UniVEdit- tencent/HY-OmniWeaving---# VitronEdit / UniVEditGradio demo of [VitronEdit: Universal Visual Editing across Images, Videos, and 3D Scenes](https://huggingface.co/papers/2610.27049)([code](https://github.com/Vitron-LLM/VitronEdit-Code), [weights](https://huggingface.co/SanRiiiii/UniVEdit)).It supports instruction-based image editing (`i2i`), reference-guided image editing (`ti_i2i`), andvideo editing with or without a reference image (`v2v` / `tiv2v`). It runs the authors' inference code(`hyvideo/`, `univedit/`, vendored from the official repo) on top of[tencent/HY-OmniWeaving](https://huggingface.co/tencent/HY-OmniWeaving).The 3D scene editing mode (`3d23d` + 3D Gaussian export) is not included in this demo.The code and weights are derived from Tencent HY-OmniWeaving and distributed under the Tencent HY CommunityLicense Agreement (see `License.txt` and `Notice.txt`).The example images and videos come from the CC0 pools[linoyts/repo-to-space-example-inputs](https://huggingface.co/datasets/linoyts/repo-to-space-example-inputs) and[linoyts/repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos).
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033041 unmodified line306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513"""VitronEdit / UniVEdit: universal instruction-based visual editing.Demo Space for the paper "VitronEdit: Universal Visual Editing across Images,Videos, and 3D Scenes" (arXiv 2610.27049). This Space runs the image-editingmode (i2i and the reference-guided ti_i2i) of the UniVEdit checkpoint, whichfine-tunes Tencent HY-OmniWeaving (HunyuanVideo-1.5 MMDiT + Qwen2.5-VL-7Bsemantic encoder + SigLIP vision encoder) with LoRA adapters and new modalitytokens (<T_IMG>)."""import os# Allocator config for the video-DiT memory spikes, before any torch import.os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")import spaces # MUST come before torch / any CUDA-touching importimport jsonimport randomimport reimport shutilimport sys as _sysimport tempfileimport timefrom pathlib import Pathimport torchimport torchvision.transforms as transformsfrom PIL import ImageAPP_DIR = Path(__file__).resolve().parentREPO_DIR = APP_DIR / "vendored_univedit"CKPT_DIR = Path(os.environ.get("UNIVEDIT_CKPTS", "/tmp/ckpts"))# Repos the Space assembles its model directory from.HF_MAIN_REPO = "tencent/HY-OmniWeaving"HF_LLM_REPO = "Qwen/Qwen2.5-VL-7B-Instruct"HF_VISION_REPO = "google/siglip-so400m-patch14-384" # same SigLIP as FLUX.1-Redux-dev, ungatedHF_GLYPH_REPO = "multimodalart/glyph-sdxl-v2-byt5-small" # Glyph-SDXL-v2 byt5 mirrorHF_EDIT_REPO = "SanRiiiii/UniVEdit" # redirects to SanRiiiii/VitronEditMODEL_DIR = CKPT_DIR / "omniweaving"def _log(msg: str) -> None:print(f"[vitronedit] {msg}", flush=True)def _download(repo_id: str, local_dir, allow_patterns, ignore_patterns=None) -> None:"""snapshot_download wrapper with progress logging."""from huggingface_hub import snapshot_download_log(f"downloading {repo_id} ({', '.join(allow_patterns)}) …")t0 = time.perf_counter()snapshot_download(repo_id=repo_id,local_dir=str(local_dir),allow_patterns=allow_patterns,ignore_patterns=ignore_patterns,)_log(f"downloaded {repo_id} in {time.perf_counter() - t0:.0f}s")def setup_weights() -> None:"""Assemble the OmniWeaving model directory the pipeline expects.Layout (per the repo's download-checkpoint.md):ckpts/omniweaving/{transformer,vae,scheduler,config.json}ckpts/omniweaving/text_encoder/ckpt/text_encoder_model.safetensors (fine-tuned Qwen2.5-VL)ckpts/omniweaving/text_encoder/llm (Qwen2.5-VL-7B-Instruct)ckpts/omniweaving/text_encoder/byt5-small (byT5 base)ckpts/omniweaving/text_encoder/Glyph-SDXL-v2/{assets,checkpoints}ckpts/omniweaving/vision_encoder/siglip/{image_encoder,feature_extractor}ckpts/univedit/geo3d/{pytorch_lora_weights.safetensors,modality_token_embeddings.pt}"""llm_dir = MODEL_DIR / "text_encoder" / "llm"te_ckpt_path = MODEL_DIR / "text_encoder" / "ckpt" / "text_encoder_model.safetensors"siglip_dir = MODEL_DIR / "vision_encoder" / "siglip"glyph_dir = MODEL_DIR / "text_encoder" / "Glyph-SDXL-v2"byt5_dir = MODEL_DIR / "text_encoder" / "byt5-small"# 1) Transformer / VAE / scheduler (+ the fine-tuned text-encoder checkpoint# in text_encoder/ckpt — without it create_pipeline silently falls back# to the *base* Qwen2.5-VL and the edits come out wrong).if not (MODEL_DIR / "transformer" / "config.json").exists():_download(HF_MAIN_REPO,MODEL_DIR,allow_patterns=["transformer/*", "vae/*", "scheduler/*", "config.json","text_encoder/ckpt/*",],ignore_patterns=["upsampler/*", "assets/*", "*.gif", "*.png"],)elif not te_ckpt_path.exists():_download(HF_MAIN_REPO, MODEL_DIR, allow_patterns=["text_encoder/ckpt/*"])# 2) Qwen2.5-VL-7B-Instruct (base of the fine-tuned semantic encoder).if not (llm_dir / "config.json").exists():_download(HF_LLM_REPO,llm_dir,allow_patterns=["config.json", "generation_config.json", "merges.txt","model-*.safetensors", "model.safetensors.index.json","preprocessor_config.json", "tokenizer.json","tokenizer_config.json", "vocab.json", "chat_template.json",],)# 3) SigLIP vision encoder. google/siglip-so400m-patch14-384 is flat and# holds a SiglipModel config (nested vision_config); the loader wants the# FLUX.1-Redux-dev layout — image_encoder/ + feature_extractor/ with a# *vision-only* config — so download flat and restructure here.if not (siglip_dir / "image_encoder" / "model.safetensors").exists():siglip_tmp = CKPT_DIR / "siglip_temp"_download(HF_VISION_REPO,siglip_tmp,allow_patterns=["config.json", "model.safetensors", "preprocessor_config.json"],)img_enc_dir = siglip_dir / "image_encoder"feat_dir = siglip_dir / "feature_extractor"img_enc_dir.mkdir(parents=True, exist_ok=True)feat_dir.mkdir(parents=True, exist_ok=True)full_cfg = json.loads((siglip_tmp / "config.json").read_text())vision_cfg = dict(full_cfg.get("vision_config", {}))vision_cfg.setdefault("model_type", "siglip_vision_model")vision_cfg["architectures"] = ["SiglipVisionModel"]vision_cfg["torch_dtype"] = full_cfg.get("torch_dtype", "float32")(img_enc_dir / "config.json").write_text(json.dumps(vision_cfg, indent=2))shutil.move(str(siglip_tmp / "model.safetensors"), str(img_enc_dir / "model.safetensors"))shutil.copy(str(siglip_tmp / "preprocessor_config.json"), str(feat_dir / "preprocessor_config.json"))shutil.rmtree(siglip_tmp, ignore_errors=True)# 4) Glyph-SDXL-v2 byt5. byt5_model.pt must be a torch pickle (the loader# torch.load()s it), so take the mirror's pytorch_model.bin.if not (glyph_dir / "checkpoints" / "byt5_model.pt").exists():glyph_tmp = CKPT_DIR / "glyph_temp"_download(HF_GLYPH_REPO,glyph_tmp,allow_patterns=["pytorch_model.bin","assets/color_idx.json", "assets/multilingual_10-lang_idx.json",],)(glyph_dir / "assets").mkdir(parents=True, exist_ok=True)(glyph_dir / "checkpoints").mkdir(parents=True, exist_ok=True)for name in ("color_idx.json", "multilingual_10-lang_idx.json"):src = glyph_tmp / "assets" / nameif src.exists():shutil.copy(src, glyph_dir / "assets" / name)src_bin = glyph_tmp / "pytorch_model.bin"if src_bin.exists():shutil.move(str(src_bin), str(glyph_dir / "checkpoints" / "byt5_model.pt"))else: # fall back to the safetensors copy of the same weightsshutil.copy(str(glyph_tmp / "model.safetensors"),str(glyph_dir / "checkpoints" / "byt5_model.pt"),)shutil.rmtree(glyph_tmp, ignore_errors=True)# byt5-small base: T5ForConditionalGeneration needs the weights too.if not (byt5_dir / "pytorch_model.bin").exists():_download("google/byt5-small",byt5_dir,allow_patterns=["config.json", "generation_config.json", "pytorch_model.bin","special_tokens_map.json", "tokenizer_config.json",],)# 5) UniVEdit LoRA adapter + modality token embeddings.if not (CKPT_DIR / "univedit" / "geo3d" / "pytorch_lora_weights.safetensors").exists():_download(HF_EDIT_REPO, CKPT_DIR / "univedit", allow_patterns=["geo3d/*"])setup_weights()# --- compat shim: peft 0.17 imports HybridCache at module scope ------------# transformers 5.x removed HybridCache (deprecated since 4.56: "Use StaticCache# instead which will correctly infer the type of each layer"). peft 0.17.0's# peft_model.py does `from transformers import ..., HybridCache, ...` at module# scope, so importing diffusers.loaders.peft (which the pipeline does) crashes# with ImportError on transformers 5.x. transformers 4.x is not installable in# this base image (it pins huggingface-hub<1.0; gradio 6.30 + spaces need# huggingface-hub>=1.16). peft only uses HybridCache for Gemma2/3 generation,# never in the LoRA-adapter path this demo exercises, so aliasing it to# StaticCache (the documented replacement, same constructor contract) is safe.import transformers as _transformersif not hasattr(_transformers, "HybridCache"):_transformers.HybridCache = _transformers.StaticCache# --- import the vendored inference stack -----------------------------------_sys.path.insert(0, str(REPO_DIR / "src"))import einopsimport gradio as grfrom hyvideo.commons.infer_state import initialize_infer_statefrom hyvideo.pipelines.hunyuan_video_pipeline import HunyuanVideo_1_5_Pipelinefrom univedit.data.preprocessing import (IMAGE_CLIP_FRAMES,resize_and_center_crop_image,resize_and_pad_image,)class _Args:"""Defaults of scripts/infer/batch.sh for the infer-state fields read at init."""sage_blocks_range = "0-53"no_cache_block_id = "53"use_sageattn = Falseenable_torch_compile = Falseenable_cache = Falsecache_type = "deepcache"cache_start_step = 11cache_end_step = 45total_steps = 50cache_step_interval = 4use_fp8_gemm = Falsequant_type = "fp8-per-token-sgl"include_patterns = "double_blocks"initialize_infer_state(_Args())_log("building pipeline (this streams ~55 GB of weights) …")_t0 = time.perf_counter()# get_gpu_memory() returns 0 before CUDA is up, which would pick the tiny-VAE# tile config; pin the >21 GB branch (matches ZeroGPU's 48 GB slice).import hyvideo.pipelines.hunyuan_video_pipeline as _pipe_modimport hyvideo.commons as _commons_mod_pipe_mod.get_gpu_memory = lambda device=None: 80 * 1024 * 1024 * 1024_commons_mod.get_gpu_memory = lambda device=None: 80 * 1024 * 1024 * 1024pipe = HunyuanVideo_1_5_Pipeline.create_pipeline(pretrained_model_name_or_path=str(MODEL_DIR),transformer_dtype=torch.bfloat16,device=torch.device("cuda"),transformer_init_device=torch.device("cuda"),pipeline_config="omniweaving",)# No CPU offloading on ZeroGPU: the whole model stays resident.pipe.enable_offloading = False_log(f"pipeline built in {time.perf_counter() - _t0:.0f}s")# --- UniVEdit checkpoint: LoRA adapter + modality token embeddings -----------_lora_dir = CKPT_DIR / "univedit" / "geo3d"pipe.transformer.load_lora_adapter(pretrained_model_name_or_path_or_dict=str(_lora_dir),prefix=None,adapter_name="default",weight_name="pytorch_lora_weights.safetensors",use_safetensors=True,hotswap=False,)pipe.load_modality_token_embeddings(str(_lora_dir / "modality_token_embeddings.pt"), strict=True)_log("UniVEdit LoRA adapter and modality tokens loaded")# Free disk: everything is resident on the GPU now, and ZeroGPU's pack step# keeps its own copy of the weights, so the raw snapshots are dead weight on# the ephemeral disk (~77 GB otherwise).import gcdef _rm_tree_weights(subdir: Path) -> None:for f in subdir.glob("*.safetensors"):_log(f"cleaning up {f.name} ({f.stat().st_size / 1e9:.1f} GB)")f.unlink(missing_ok=True)_rm_tree_weights(MODEL_DIR / "transformer")_rm_tree_weights(MODEL_DIR / "vae")_rm_tree_weights(MODEL_DIR / "text_encoder" / "llm")_rm_tree_weights(MODEL_DIR / "text_encoder" / "ckpt")_rm_tree_weights(MODEL_DIR / "text_encoder" / "byt5-small")_rm_tree_weights(MODEL_DIR / "vision_encoder" / "siglip" / "image_encoder")(MODEL_DIR / "text_encoder" / "byt5-small" / "pytorch_model.bin").unlink(missing_ok=True)(MODEL_DIR / "text_encoder" / "Glyph-SDXL-v2" / "checkpoints" / "byt5_model.pt").unlink(missing_ok=True)gc.collect()_log("weight snapshots cleaned up")# Resolution buckets of the image-editing mode (height, width) — from# src/univedit/inference/batch_infer.py.IMAGE_EDIT_BUCKETS = ((352, 624),(432, 576),(480, 480),(576, 432),(624, 352),)def replace_reference_placeholder(text: str) -> str:"""The batch runner swaps [V*] for 'the reference image' before the prompt."""text = re.sub(r"\b(?:a|an|the)\s*\[\s*v\s*\*\s*\]", "the reference image", text, flags=re.IGNORECASE)text = re.sub(r"\[\s*v\s*\*\s*\]", "the reference image", text, flags=re.IGNORECASE)text = re.sub(r"\s+([,.;:!?])", r"\1", text)1 unmodified linereturn text.strip()def image_bucket_size(source_image: Image.Image):ratio = source_image.width / source_image.heightbucket_width, bucket_height = min(IMAGE_EDIT_BUCKETS, key=lambda s: abs((s[0] / s[1]) - ratio))return bucket_height, bucket_widthdef encode_frames_to_latents(frames: torch.Tensor, scale: bool) -> torch.Tensor:"""VAE latents [1, C, F_lat, H_lat, W_lat] of frames [F, 3, H, W] in [0, 1]."""pixel_values = transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])(frames)pixel_values = pixel_values.unsqueeze(0).transpose(1, 2).to(pipe.execution_device)with (torch.no_grad(),torch.autocast(device_type="cuda", dtype=torch.float16, enabled=True),pipe.vae.memory_efficient_context(),):latents = pipe.vae.encode(pixel_values).latent_dist.mode()if scale:if hasattr(pipe.vae.config, "shift_factor") and pipe.vae.config.shift_factor:latents = (latents - pipe.vae.config.shift_factor) * pipe.vae.config.scaling_factorelse:latents = latents * pipe.vae.config.scaling_factorreturn latentsdef save_first_frame(video, path):if video.ndim == 5:frame = video[0, :, 0]elif video.ndim == 4:frame = video[0]elif video.ndim == 3:frame = videoelse:raise ValueError(f"Unsupported output tensor shape: {tuple(video.shape)}")frame = (frame * 255).clamp(0, 255).to(torch.uint8)frame = einops.rearrange(frame, "c h w -> h w c").cpu().numpy()Image.fromarray(frame).save(path)@spaces.GPU(duration=160)def edit_image(input_image,prompt: str,reference_image,steps: int = 50,guidance_scale: float = 6.0,flow_shift: float = 5.0,seed: int = 123,progress=gr.Progress(track_tqdm=True),):"""Edit an image following a text instruction (VitronEdit / UniVEdit i2i).Args:input_image: the source image to edit.prompt: the editing instruction, e.g. "replace the scarf with a hat".reference_image: optional reference image; when given, the model runs thereference-guided ti_i2i mode and the instruction can describe how toapply the reference (use "the reference image" to refer to it).steps: number of denoising steps (default 50, as in the paper's runner).guidance_scale: classifier-free guidance scale (default 6.0).flow_shift: flow-matching timestep shift (default 5.0).seed: sampling seed."""if input_image is None:raise gr.Error("Please provide a source image.")if not (isinstance(prompt, str) and prompt.strip()):raise gr.Error("Please provide an editing instruction.")src = input_image if isinstance(input_image, Image.Image) else Image.fromarray(input_image)src = src.convert("RGB")ti_i2i = reference_image is not Nonetask_type = "ti_i2i" if ti_i2i else "i2i"instruction = replace_reference_placeholder(prompt.strip()) if ti_i2i else prompt.strip()ref = Noneif ti_i2i:ref = reference_image if isinstance(reference_image, Image.Image) else Image.fromarray(reference_image)ref = ref.convert("RGB")target_height, target_width = image_bucket_size(src)resized = resize_and_center_crop_image(src, target_height, target_width)with torch.no_grad():clip = transforms.ToTensor()(resized).unsqueeze(0).repeat(IMAGE_CLIP_FRAMES, 1, 1, 1)source_image_latents = encode_frames_to_latents(clip, scale=True)out = pipe(prompt=instruction,negative_prompt="",aspect_ratio=f"{target_width}:{target_height}",num_inference_steps=int(steps),guidance_scale=float(guidance_scale),flow_shift=float(flow_shift),video_length=IMAGE_CLIP_FRAMES,seed=int(seed),output_type="pt",return_dict=True,deepstack=[8, 16, 24],setclip=True,task_type=task_type,source_image=src,source_image_latents=source_image_latents,target_height=target_height,target_width=target_width,**({"reference_image": ref} if ti_i2i else {}),)out_path = Path(tempfile.mkdtemp()) / "edited.png"save_first_frame(out.videos, out_path)torch.cuda.empty_cache()return str(out_path)# --- UI ----------------------------------------------------------------------ASSETS = APP_DIR / "examples_assets"EXAMPLES = [[str(ASSETS / "house.jpg"), "include a person walking down the street"],[str(ASSETS / "flowerpot.jpg"), "erase the paintbrush on top"],[str(ASSETS / "woman.jpg"), "replace the scarf with a hat"],[str(ASSETS / "couple.jpg"), "Make the style of the image to old fashioned"],]REFERENCE_EXAMPLES = [[str(ASSETS / "dog.jpg"), "change the dog to the reference image", str(ASSETS / "dragon.jpg")],]CSS = """#col-container { max-width: 1100px; margin: 0 auto; }.dark .gradio-container { color: var(--body-text-color); }"""with gr.Blocks(theme=gr.themes.Citrus(), css=CSS, title="VitronEdit") as demo:gr.Markdown("# VitronEdit / UniVEdit — universal visual editing\n""Instruction-based **image editing** with the UniVEdit checkpoint: it fine-tunes ""[HY-OmniWeaving](https://huggingface.co/tencent/HY-OmniWeaving) with LoRA and new ""modality tokens to follow free-form edit instructions (add / remove / replace / restyle), ""preserving the rest of the image. Optionally add a **reference image** to run the ""reference-guided mode (ti_i2i) and transfer a subject or style from it.\n\n""📄 [Paper](https://huggingface.co/papers/2610.27049) · ""💻 [Code](https://github.com/Vitron-LLM/VitronEdit-Code) · ""🤗 [UniVEdit checkpoint](https://huggingface.co/SanRiiiii/UniVEdit)")with gr.Column(elem_id="col-container"):with gr.Row():with gr.Column():input_image = gr.Image(label="Source image", type="pil", height=320)prompt = gr.Textbox(label="Edit instruction",placeholder="e.g. replace the scarf with a hat",lines=2,)reference_image = gr.Image(label="Reference image (optional — enables reference-guided ti_i2i)",type="pil",height=240,)run_btn = gr.Button("Edit image", variant="primary")with gr.Column():output_image = gr.Image(label="Edited image", type="pil", height=320)with gr.Accordion("Advanced settings", open=False):with gr.Row():steps = gr.Slider(10, 60, value=50, step=1, label="Inference steps")guidance = gr.Slider(1.0, 12.0, value=6.0, step=0.1, label="Guidance scale")with gr.Row():flow_shift = gr.Slider(1.0, 12.0, value=5.0, step=0.5, label="Flow shift")seed = gr.Number(value=123, label="Seed", precision=0)gr.Examples(examples=EXAMPLES,inputs=[input_image, prompt],outputs=output_image,fn=edit_image,cache_examples=True,cache_mode="lazy",label="Instruction editing examples (from the paper's repo)",)gr.Examples(examples=REFERENCE_EXAMPLES,inputs=[input_image, prompt, reference_image],outputs=output_image,fn=edit_image,cache_examples=True,cache_mode="lazy",label="Reference-guided example (ti_i2i, from the paper's repo)",)gr.Markdown("*The demo runs the image-editing mode of the paper's five-task framework ""(i2i / ti_i2i / v2v / tiv2v / 3d23d). Defaults follow the official ""batch-inference runner: 50 steps, guidance 6.0, flow shift 5.0.*")run_btn.click(edit_image,inputs=[input_image, prompt, reference_image, steps, guidance, flow_shift, seed],outputs=output_image,api_name="edit_image",queue=True,)demo.launch(mcp_server=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881 unmodified line190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511import jsonimport osos.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")import spaces # must be imported before torch / CUDA-touching libsimport randomimport reimport tempfilefrom types import SimpleNamespaceimport einopsimport gradio as grimport imageioimport numpy as npimport torchfrom huggingface_hub import snapshot_downloadfrom PIL import Imagefrom torchvision import transformsimport hyvideo.commonsimport hyvideo.pipelines.hunyuan_video_pipeline as hv_pipeline_modulefrom hyvideo.commons import auto_offload_modelfrom hyvideo.commons.infer_state import initialize_infer_statefrom hyvideo.commons.parallel_states import initialize_parallel_statefrom hyvideo.pipelines.hunyuan_video_pipeline import HunyuanVideo_1_5_Pipelinefrom univedit.data.preprocessing import IMAGE_CLIP_FRAMES, resize_and_center_crop_image# ---------------------------------------------------------------------------# Weights# ---------------------------------------------------------------------------CKPT_DIR = os.path.abspath("ckpts/omniweaving")BASE_REPO = "tencent/HY-OmniWeaving"UNIVEDIT_REPO = "SanRiiiii/UniVEdit"SIGLIP_VISION_CONFIG = {"architectures": ["SiglipVisionModel"],"attention_dropout": 0.0,"hidden_act": "gelu_pytorch_tanh","hidden_size": 1152,"image_size": 384,"intermediate_size": 4304,"layer_norm_eps": 1e-06,"model_type": "siglip_vision_model","num_attention_heads": 16,"num_channels": 3,"num_hidden_layers": 27,"patch_size": 14,}def _link(src, dst):os.makedirs(os.path.dirname(dst), exist_ok=True)if not os.path.lexists(dst):os.symlink(src, dst)def prepare_weights() -> str:# OmniWeaving base: transformer, VAE, scheduler and the fine-tuned MLLM text encoder.base = snapshot_download(BASE_REPO,allow_patterns=["config.json","scheduler/*","transformer/*","vae/*","text_encoder/ckpt/*",],)_link(os.path.join(base, "config.json"), os.path.join(CKPT_DIR, "config.json"))for sub in ("scheduler", "transformer", "vae"):_link(os.path.join(base, sub), os.path.join(CKPT_DIR, sub))te_ckpt = os.path.join(base, "text_encoder", "ckpt", "text_encoder_model.safetensors")_link(te_ckpt, os.path.join(CKPT_DIR, "text_encoder", "ckpt", "text_encoder_model.safetensors"))# Qwen2.5-VL-7B-Instruct: config / tokenizer / processor only. The OmniWeaving# fine-tuned MLLM checkpoint holds the full weights in HF key format, so it is# used directly as the model weights (no need to fetch the 16 GB base model).qwen = snapshot_download("Qwen/Qwen2.5-VL-7B-Instruct",allow_patterns=["*.json", "*.txt"],ignore_patterns=["model.safetensors.index.json"],)llm_dir = os.path.join(CKPT_DIR, "text_encoder", "llm")os.makedirs(llm_dir, exist_ok=True)for f in os.listdir(qwen):if f != "model.safetensors.index.json":_link(os.path.join(qwen, f), os.path.join(llm_dir, f))_link(te_ckpt, os.path.join(llm_dir, "model.safetensors"))# Glyph-SDXL-v2 byT5 encoder.glyph = snapshot_download("multimodalart/glyph-sdxl-v2-byt5-small", allow_patterns=["assets/*", "pytorch_model.bin"])glyph_root = os.path.join(CKPT_DIR, "text_encoder", "Glyph-SDXL-v2")for f in ("color_idx.json", "multilingual_10-lang_idx.json"):_link(os.path.join(glyph, "assets", f), os.path.join(glyph_root, "assets", f))_link(os.path.join(glyph, "pytorch_model.bin"), os.path.join(glyph_root, "checkpoints", "byt5_model.pt"))# SigLIP vision encoder. OmniWeaving points at FLUX.1-Redux-dev/image_encoder, which is# the (gated) bf16 copy of google/siglip-so400m-patch14-384's vision tower; we use the# ungated original with the same vision config + preprocessor.siglip = snapshot_download("google/siglip-so400m-patch14-384", allow_patterns=["model.safetensors", "preprocessor_config.json"])siglip_dir = os.path.join(CKPT_DIR, "vision_encoder", "siglip")enc_dir = os.path.join(siglip_dir, "image_encoder")os.makedirs(enc_dir, exist_ok=True)with open(os.path.join(enc_dir, "config.json"), "w") as f:json.dump(SIGLIP_VISION_CONFIG, f)_link(os.path.join(siglip, "model.safetensors"), os.path.join(enc_dir, "model.safetensors"))_link(os.path.join(siglip, "preprocessor_config.json"),os.path.join(siglip_dir, "feature_extractor", "preprocessor_config.json"),)# UniVEdit: LoRA + modality token embeddings.univedit = snapshot_download(UNIVEDIT_REPO, allow_patterns=["geo3d/*"])return os.path.join(univedit, "geo3d")UNIVEDIT_DIR = prepare_weights()# ---------------------------------------------------------------------------# Pipeline# ---------------------------------------------------------------------------# ZeroGPU has no GPU in the main process: report a large card so the pipeline# picks the non-tiled-small VAE config, and never enables offloading._fake_mem = lambda device=None: 96 * 1024**3 # noqa: E731hyvideo.commons.get_gpu_memory = _fake_memhv_pipeline_module.get_gpu_memory = _fake_meminitialize_parallel_state(sp=1)initialize_infer_state(SimpleNamespace(sage_blocks_range="0-53",no_cache_block_id="53",use_sageattn=False,enable_torch_compile=False,enable_cache=False,cache_type="deepcache",cache_start_step=11,cache_end_step=45,total_steps=50,cache_step_interval=4,use_fp8_gemm=False,quant_type="fp8-per-token-sgl",include_patterns="double_blocks",))# The MLLM weights are already loaded from the fine-tuned checkpoint (see above).HunyuanVideo_1_5_Pipeline._load_text_encoder_ckpt = staticmethod(lambda text_encoder, ckpt_path: None)pipe = HunyuanVideo_1_5_Pipeline.create_pipeline(pretrained_model_name_or_path=CKPT_DIR,transformer_dtype=torch.bfloat16,device=torch.device("cpu"),transformer_init_device=torch.device("cpu"),pipeline_config="omniweaving",)pipe.apply_infer_optimization(infer_state=None, enable_offloading=False, enable_group_offloading=False)pipe.load_modality_token_embeddings(UNIVEDIT_DIR, strict=True)pipe.transformer.load_lora_adapter(pretrained_model_name_or_path_or_dict=UNIVEDIT_DIR,prefix=None,adapter_name="default",weight_name="pytorch_lora_weights.safetensors",use_safetensors=True,)pipe.to("cuda")pipe.execution_device = torch.device("cuda")pipe.noise_init_device = torch.device("cuda")print("UniVEdit pipeline ready.")# ---------------------------------------------------------------------------# Helpers (ported 1:1 from univedit/inference/batch_infer.py)# ---------------------------------------------------------------------------IMAGE_EDIT_BUCKETS = ((352, 624), (432, 576), (480, 480), (576, 432), (624, 352)) # (width, height)VIDEO_EDIT_360P_BUCKETS = {"1:1": (480, 480), "16:9": (352, 624), "9:16": (624, 352)} # (height, width)MAX_SEED = 2**31 - 1DEFAULT_STEPS = 50DEFAULT_GUIDANCE = 6.0DEFAULT_SHIFT = 5.0def replace_reference_placeholder(text: str) -> str:text = re.sub(r"\b(?:a|an|the)\s*\[\s*v\s*\*\s*\]", "the reference image", text, flags=re.IGNORECASE)text = re.sub(r"\[\s*v\s*\*\s*\]", "the reference image", text, flags=re.IGNORECASE)text = re.sub(r"\s+([,.;:!?])", r"\1", text)1 unmodified linereturn text.strip()def image_bucket_size(img: Image.Image):ratio = img.width / img.heightw, h = min(IMAGE_EDIT_BUCKETS, key=lambda s: abs((s[0] / s[1]) - ratio))return h, wdef video_bucket_size(width: int, height: int):ratio = width / height_, (h, w) = min(VIDEO_EDIT_360P_BUCKETS.items(), key=lambda it: abs((it[1][1] / it[1][0]) - ratio))return h, wdef encode_frames_to_latents(frames: torch.Tensor, *, scale: bool) -> torch.Tensor:pixel_values = transforms.Normalize(mean=[0.5] * 3, std=[0.5] * 3)(frames)pixel_values = pixel_values.unsqueeze(0).transpose(1, 2).to(pipe.execution_device)with (torch.no_grad(),torch.autocast(device_type="cuda", dtype=torch.float16, enabled=True),auto_offload_model(pipe.vae, pipe.execution_device, enabled=False),pipe.vae.memory_efficient_context(),):latents = pipe.vae.encode(pixel_values).latent_dist.mode()if scale:if getattr(pipe.vae.config, "shift_factor", None):latents = (latents - pipe.vae.config.shift_factor) * pipe.vae.config.scaling_factorelse:latents = latents * pipe.vae.config.scaling_factorreturn latentsdef to_pil_first_frame(video: torch.Tensor) -> Image.Image:frame = video[0, :, 0] if video.ndim == 5 else video[0]frame = (frame * 255).clamp(0, 255).to(torch.uint8)return Image.fromarray(einops.rearrange(frame, "c h w -> h w c").cpu().numpy())def resolve_seed(seed, randomize):return random.randint(0, MAX_SEED) if randomize else int(seed)# ---------------------------------------------------------------------------# Inference# ---------------------------------------------------------------------------@spaces.GPU(duration=90)def edit_image(source_image: Image.Image,instruction: str,reference_image: Image.Image | None = None,steps: int = DEFAULT_STEPS,guidance_scale: float = DEFAULT_GUIDANCE,flow_shift: float = DEFAULT_SHIFT,seed: int = 123,randomize_seed: bool = False,progress=gr.Progress(track_tqdm=True),):"""Edit an image with a text instruction (optionally guided by a reference image).Args:source_image: the image to edit.instruction: the editing instruction, e.g. "replace the scarf with a hat". With a referenceimage, refer to it as "[V*]" (e.g. "change the dog to a [V*]").reference_image: optional reference image (switches to reference-guided editing, ti_i2i).steps: number of denoising steps.guidance_scale: classifier-free guidance scale.flow_shift: timestep shift of the sampling schedule.seed: random seed.randomize_seed: pick a random seed instead of `seed`.Returns:The edited image and the seed that was used."""if source_image is None:raise gr.Error("Please upload an image to edit.")if not instruction or not instruction.strip():raise gr.Error("Please enter an editing instruction.")seed = resolve_seed(seed, randomize_seed)source_image = source_image.convert("RGB")task = "ti_i2i" if reference_image is not None else "i2i"prompt = replace_reference_placeholder(instruction) if task == "ti_i2i" else instruction.strip()h, w = image_bucket_size(source_image)resized = resize_and_center_crop_image(source_image, h, w)clip = transforms.ToTensor()(resized).unsqueeze(0).repeat(IMAGE_CLIP_FRAMES, 1, 1, 1)latents = encode_frames_to_latents(clip, scale=True)kwargs = dict(prompt=prompt,negative_prompt="",aspect_ratio=f"{w}:{h}",num_inference_steps=int(steps),guidance_scale=float(guidance_scale),flow_shift=float(flow_shift),video_length=IMAGE_CLIP_FRAMES,seed=seed,output_type="pt",return_dict=True,deepstack=[8, 16, 24],setclip=True,task_type=task,source_image=source_image,source_image_latents=latents,target_height=h,target_width=w,)if task == "ti_i2i":kwargs["reference_image"] = reference_image.convert("RGB")with torch.no_grad():out = pipe(**kwargs)return to_pil_first_frame(out.videos), seed@spaces.GPU(duration=180)def edit_video(source_video: str,instruction: str,reference_image: Image.Image | None = None,num_frames: int = 33,steps: int = DEFAULT_STEPS,guidance_scale: float = DEFAULT_GUIDANCE,flow_shift: float = DEFAULT_SHIFT,seed: int = 123,randomize_seed: bool = False,progress=gr.Progress(track_tqdm=True),):"""Edit a short video with a text instruction (optionally guided by a reference image).Args:source_video: path of the video to edit (the first `num_frames` frames are edited).instruction: the editing instruction, e.g. "Replace the brown bear with a panda.".reference_image: optional reference image (switches to reference-guided video editing, tiv2v).num_frames: number of frames to edit (4n+1, at most 81).steps: number of denoising steps.guidance_scale: classifier-free guidance scale.flow_shift: timestep shift of the sampling schedule.seed: random seed.randomize_seed: pick a random seed instead of `seed`.Returns:Path of the edited mp4 video and the seed that was used."""from decord import VideoReaderif not source_video:raise gr.Error("Please upload a video to edit.")if not instruction or not instruction.strip():raise gr.Error("Please enter an editing instruction.")seed = resolve_seed(seed, randomize_seed)num_frames = int(num_frames)num_frames = max(5, min(81, ((num_frames - 1) // 4) * 4 + 1))task = "tiv2v" if reference_image is not None else "v2v"vr = VideoReader(source_video)total = len(vr)if total == 0:raise gr.Error("The video has no frames.")fps = round(vr.get_avg_fps()) or 12indices = list(range(min(total, num_frames))) + [total - 1] * max(0, num_frames - total)frames = torch.from_numpy(vr.get_batch(indices).asnumpy()).permute(0, 3, 1, 2).contiguous() / 255.0del vrheight, width = frames.shape[-2:]th, tw = video_bucket_size(width, height)if th / height > tw / width:resize_size = th, int(width * th / height)else:resize_size = int(height * tw / width), twframes = transforms.Compose([transforms.Resize(resize_size, antialias=True), transforms.CenterCrop((th, tw))])(frames)latents = encode_frames_to_latents(frames, scale=False)kwargs = dict(prompt=instruction.strip(),negative_prompt="",aspect_ratio=f"{tw}:{th}",num_inference_steps=int(steps),guidance_scale=float(guidance_scale),flow_shift=float(flow_shift),video_length=num_frames,seed=seed,output_type="pt",return_dict=True,deepstack=[8, 16, 24],setclip=True,task_type=task,source_video=[source_video],source_video_latents=latents,)if task == "tiv2v":ref_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).namereference_image.convert("RGB").save(ref_path)kwargs["reference_image"] = ref_pathwith torch.no_grad():out = pipe(**kwargs)video = out.videosif video.ndim == 5:video = video[0]vid = (video * 255).clamp(0, 255).to(torch.uint8)vid = einops.rearrange(vid, "c f h w -> f h w c").cpu().numpy()out_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).nameimageio.mimwrite(out_path, list(vid), fps=fps, quality=8)return out_path, seed# ---------------------------------------------------------------------------# UI# ---------------------------------------------------------------------------CSS = """#col-container { max-width: 1200px; margin: 0 auto; }.dark .gradio-container { color: var(--body-text-color); }"""with gr.Blocks() as demo:with gr.Column(elem_id="col-container"):gr.Markdown("# VitronEdit (UniVEdit): universal visual editing\n""Edit images and videos with a text instruction, and optionally a reference image. ""This is a LoRA plus modality tokens on top of ""[HY-OmniWeaving](https://huggingface.co/tencent/HY-OmniWeaving) (HunyuanVideo-1.5).\n\n""[Paper](https://huggingface.co/papers/2610.27049) · ""[Code](https://github.com/Vitron-LLM/VitronEdit-Code) · ""[Model](https://huggingface.co/SanRiiiii/UniVEdit)")with gr.Tabs():# ---------------- Image editing ----------------with gr.Tab("Image editing"):with gr.Row():with gr.Column():img_src = gr.Image(label="Image to edit", type="pil", height=380)img_prompt = gr.Textbox(label="Instruction",placeholder='e.g. "replace the scarf with a hat". With a reference image, call it [V*].',lines=2,)with gr.Accordion("Reference image (optional)", open=False):img_ref = gr.Image(label="Reference image", type="pil", height=240)img_btn = gr.Button("Edit image", variant="primary")with gr.Accordion("Advanced settings", open=False):img_steps = gr.Slider(10, 50, value=DEFAULT_STEPS, step=1, label="Steps")img_cfg = gr.Slider(1.0, 10.0, value=DEFAULT_GUIDANCE, step=0.5, label="Guidance scale")img_shift = gr.Slider(1.0, 10.0, value=DEFAULT_SHIFT, step=0.5, label="Flow shift")img_seed = gr.Slider(0, MAX_SEED, value=123, step=1, label="Seed")img_rand = gr.Checkbox(label="Randomize seed", value=False)with gr.Column():img_out = gr.Image(label="Edited image", height=480)img_btn.click(edit_image,inputs=[img_src, img_prompt, img_ref, img_steps, img_cfg, img_shift, img_seed, img_rand],outputs=[img_out, img_seed],api_name="edit_image",)gr.Examples(examples=[["examples/cat_tabby.jpg", "add a small red bow tie under the cat's chin"],["examples/living_room_blue_couch.jpg", "replace the blue sofa with a brown leather sofa"],["examples/rubber_ducks.jpg", "remove the smallest rubber duck on the left"],["examples/lighthouse_coast.jpg", "Make the style of the image a watercolor painting"],],inputs=[img_src, img_prompt],outputs=[img_out, img_seed],fn=edit_image,cache_examples=True,cache_mode="lazy",label="Image examples",)gr.Examples(examples=[["examples/dog.jpg", "change the dog to a [V*]", "examples/red_fox.jpg"]],inputs=[img_src, img_prompt, img_ref],outputs=[img_out, img_seed],fn=edit_image,cache_examples=True,cache_mode="lazy",label="Reference-guided example",)# ---------------- Video editing ----------------with gr.Tab("Video editing"):with gr.Row():with gr.Column():vid_src = gr.Video(label="Video to edit", height=340)vid_prompt = gr.Textbox(label="Instruction",placeholder='e.g. "Replace the brown bear with a panda."',lines=2,)with gr.Accordion("Reference image (optional)", open=False):vid_ref = gr.Image(label="Reference image", type="pil", height=240)vid_btn = gr.Button("Edit video", variant="primary")with gr.Accordion("Advanced settings", open=False):vid_frames = gr.Slider(5, 81, value=33, step=4, label="Frames (4n+1)")vid_steps = gr.Slider(10, 50, value=DEFAULT_STEPS, step=1, label="Steps")vid_cfg = gr.Slider(1.0, 10.0, value=DEFAULT_GUIDANCE, step=0.5, label="Guidance scale")vid_shift = gr.Slider(1.0, 10.0, value=DEFAULT_SHIFT, step=0.5, label="Flow shift")vid_seed = gr.Slider(0, MAX_SEED, value=123, step=1, label="Seed")vid_rand = gr.Checkbox(label="Randomize seed", value=False)with gr.Column():vid_out = gr.Video(label="Edited video", autoplay=True, height=420)vid_btn.click(edit_video,inputs=[vid_src, vid_prompt, vid_ref, vid_frames, vid_steps, vid_cfg, vid_shift, vid_seed, vid_rand],outputs=[vid_out, vid_seed],api_name="edit_video",)gr.Examples(examples=[["examples/cat.mp4", "Replace the cat with a tiger."],["examples/border_collie_running.mp4", "Transform the entire scene into Sketch style."],],inputs=[vid_src, vid_prompt],outputs=[vid_out, vid_seed],fn=edit_video,cache_examples=True,cache_mode="lazy",label="Video examples",)if __name__ == "__main__":demo.queue().launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
123version https://git-lfs.github.com/spec/v1oid sha256:207dce067972aa74a242400b0992533079c4ccb5cb034069a48df73c1291ba46size 6739717123version https://git-lfs.github.com/spec/v1oid sha256:d22e1330d349cf4da47866d9022709cfc67bc70ad4bdba606cd82fd459c42ce0size 7785051234567891011121314151617181920212223242526272829303132333435363738394041424344# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import osimport socketfrom .commons import get_gpu_memory
if 'TOKENIZERS_PARALLELISM' not in os.environ: os.environ['TOKENIZERS_PARALLELISM'] = 'false'
def find_free_port(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 0)) port = sock.getsockname()[1] sock.close() return port def __initialize_default_distributed_environment(): if 'RANK' not in os.environ: os.environ['RANK'] = '0' if 'WORLD_SIZE' not in os.environ: os.environ['WORLD_SIZE'] = '1' if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = '0' if 'MASTER_ADDR' not in os.environ: os.environ['MASTER_ADDR'] = 'localhost' if 'MASTER_PORT' not in os.environ: os.environ['MASTER_PORT'] = str(find_free_port())
__initialize_default_distributed_environment()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176# Modified by the UniVEdit authors from Tencent-Hunyuan/OmniWeaving (HunyuanVideo-1.5).# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import osimport torchfrom itertools import repeatfrom contextlib import contextmanagerfrom torch import nnimport collections.abc
def _ntuple(n): """Create a function that converts input to n-tuple.""" def parse(x): if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): x = tuple(x) if len(x) == 1: x = tuple(repeat(x[0], n)) return x return tuple(repeat(x, n)) return parse
# Convenience functions for common tuple sizesto_1tuple = _ntuple(1)to_2tuple = _ntuple(2)to_3tuple = _ntuple(3)to_4tuple = _ntuple(4)
PRECISION_TO_TYPE = { 'fp32': torch.float32, 'fp16': torch.float16, 'bf16': torch.bfloat16,}
# Default generation pipeline configurationsPIPELINE_CONFIGS = { 'omniweaving': { 'guidance_scale': 6.0, 'embedded_guidance_scale': None, 'flow_shift': 5.0, }, 'omniweaving2': { 'guidance_scale': 6.0, 'embedded_guidance_scale': None, 'flow_shift': 5.0, }}
def is_flash2_available(): try: from flash_attn import flash_attn_varlen_qkvpacked_func return True except Exception: return False
def is_flash3_available(): try: from flash_attn_interface import flash_attn_varlen_func as flash_attn_varlen_func_v3 # noqa: F401 return True except Exception: return False
def is_flash_available(): return is_flash2_available() or is_flash3_available()
def is_sparse_attn_supported(): return 'nvidia h' in torch.cuda.get_device_properties(0).name.lower()
def is_sparse_attn_available(): if not is_sparse_attn_supported(): return False try: from flex_block_attn import flex_block_attn_func # noqa: F401 return True except Exception: return False
def is_angelslim_available(): try: import angelslim return True except Exception: return False
def maybe_fallback_attn_mode(attn_mode): """ Determine the final attention mode based on configuration and availability. Args: attn_mode: Requested attention mode infer_state: Inference configuration object (optional) block_idx: Current block index (optional) Returns: Final attention mode to use """ import warnings original_attn_mode = attn_mode
if attn_mode in ('flex-block-attn'): from hyvideo.commons import is_sparse_attn_available if not is_sparse_attn_available(): raise ValueError(f"{attn_mode} is not available for your GPU or flex-block-attn is not properly installed.") enable_sageattn = attn_mode == 'sageattn' assert not (enable_sageattn and attn_mode == 'flex-block-attn'), \ ("SageAttention cannot be used with flex-block-attn mode. " "Please disable enable_sageattn or use a different attention mode.") # Use SageAttention if configured if attn_mode == 'sageattn': try: from sageattention import sageattn except Exception: attn_mode = 'flash' # Handle flash attention modes if attn_mode == 'flash': if is_flash3_available(): attn_mode = 'flash3' elif is_flash2_available(): attn_mode = 'flash2' else: attn_mode = 'torch' elif attn_mode == 'flash3': if not is_flash3_available(): attn_mode = 'flash2' if is_flash2_available() else 'torch' elif attn_mode == 'flash2': if not is_flash2_available(): attn_mode = 'torch' if attn_mode != original_attn_mode and not ('flash' in original_attn_mode and 'flash' in attn_mode): warnings.warn(f"Falling back from `{original_attn_mode}` to `{attn_mode}` because `{original_attn_mode}` is not properly installed.") return attn_mode
@contextmanagerdef auto_offload_model(models, device, enabled=True): # from diffusers.hooks.group_offloading import _is_group_offload_enabled if enabled: if isinstance(models, nn.Module): models = [models] for model in models: if model is not None: model.to(device) yield if enabled: for model in models: if model is not None: model.to(torch.device('cpu'))
def get_gpu_memory(device=None): if not torch.cuda.is_available(): return 0 device = device if device is not None else torch.cuda.current_device() props = torch.cuda.get_device_properties(device) if hasattr(torch.cuda, 'get_per_process_memory_fraction'): memory_fraction = torch.cuda.get_per_process_memory_fraction() else: memory_fraction = 1.0 return props.total_memory * memory_fraction
def get_rank(): return int(os.environ.get('RANK', '0'))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
from typing import Optionalfrom dataclasses import dataclass, field
@dataclassclass InferState: enable_sageattn: bool = False # whether to use SageAttention sage_blocks_range: Optional[range] = None # block range to use SageAttention enable_torch_compile: bool = False # whether to use torch compile
enable_cache: bool = False # whether to use cache cache_type: str = "deepcache" # cache type no_cache_block_id: Optional[range] = None # block ids to skip cache_start_step: int = 11 # start step to skip cache_end_step: int = 45 # end step to skip total_steps: int = 50 # total steps cache_step_interval: int = 4 # step interval to skip
use_fp8_gemm: bool = False # whether to use fp8 gemm quant_type: str = "fp8-per-token-sgl" # fp8 quantization type include_patterns: list = field(default_factory=lambda: ["double_blocks"]) # include patterns for fp8 gemm
__infer_state = None
def parse_range(value): if '-' in value: start, end = map(int, value.split('-')) return list(range(start, end + 1)) else: return [int(x) for x in value.split(',')]
def initialize_infer_state(args): global __infer_state sage_blocks_range = parse_range(args.sage_blocks_range) no_cache_block_id = parse_range(args.no_cache_block_id) # Map CLI argument use_sageattn to internal enable_sageattn field use_sageattn = getattr(args, 'use_sageattn', False)
# Parse include_patterns from args include_patterns = getattr(args, 'include_patterns', "double_blocks") if isinstance(include_patterns, str): # Split by comma and strip whitespace include_patterns = [p.strip() for p in include_patterns.split(',') if p.strip()]
__infer_state = InferState( enable_sageattn = use_sageattn, sage_blocks_range = sage_blocks_range, enable_torch_compile = args.enable_torch_compile,
# cache related enable_cache = args.enable_cache, cache_type = args.cache_type, no_cache_block_id = no_cache_block_id, cache_start_step = args.cache_start_step, cache_end_step = args.cache_end_step, total_steps = args.total_steps, cache_step_interval = args.cache_step_interval,
# fp8 gemm related use_fp8_gemm = args.use_fp8_gemm, quant_type = args.quant_type, include_patterns = include_patterns, ) return __infer_state
def get_infer_state(): return __infer_state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import osfrom dataclasses import dataclass
import torch.distributed as distfrom torch.distributed.device_mesh import init_device_mesh
@dataclassclass ParallelDims: sp: int = 1 world_size: int = -1 dp_replicate: int = 1
def __post_init__(self): if self.world_size == -1: if dist.is_initialized(): self.world_size = dist.get_world_size() else: self.world_size = int(os.getenv("WORLD_SIZE", "1")) self.build_mesh("cuda")
def build_mesh(self, device_type): if self.dp_replicate == -1: assert self.world_size % 8 == 0, "world_size must be divisible by 8 for dp_replicate==-1" self.dp_replicate = self.world_size // 8 assert self.world_size % self.sp == 0, "world_size must be divisible by sp" assert self.world_size % self.dp_replicate == 0, "world_size must be divisible by dp_replicate"
fsdp_shard = self.world_size // self.dp_replicate
mesh = init_device_mesh( device_type, [self.world_size // self.sp, self.sp], mesh_dim_names=["dp", "sp"] ) self.world_mesh = mesh self.fsdp_mesh = init_device_mesh( device_type, [self.dp_replicate, fsdp_shard], mesh_dim_names=["dp_replicate", "fsdp_shard"] )
if self.sp_enabled: self.sp_rank = mesh['sp'].get_local_rank() self.sp_group = mesh['sp'].get_group() else: self.sp_rank = dist.get_rank() self.sp_group = None
return mesh
@property def sp_enabled(self): return self.sp > 1
@property def sp_mesh(self): return self.world_mesh['sp']
@property def dp_enabled(self): return (self.world_size // self.sp) > 1
__parallel_dims = None
def initialize_parallel_state( sp: int = 1, dp_replicate: int = 1,): global __parallel_dims __parallel_dims = ParallelDims(sp=sp, dp_replicate=dp_replicate) return __parallel_dims
def get_parallel_state(): if __parallel_dims is None: # create default parallel states (without enabling any parallelism) initialize_parallel_state() return __parallel_dims12345678910111213141516# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
1234567891011121314151617# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import mathfrom dataclasses import dataclassfrom typing import Optional, Tuple, Unionfrom contextlib import contextmanager
import loguruimport numpy as npimport torchimport torch.nn.functional as Ffrom einops import rearrangefrom torch import Tensor, nnfrom torch.nn import Conv3dfrom torch import distributed as dist
from diffusers.configuration_utils import ConfigMixin, register_to_configfrom diffusers.models.autoencoders.vae import BaseOutput, DiagonalGaussianDistributionfrom diffusers.models.modeling_outputs import AutoencoderKLOutputfrom diffusers.models.modeling_utils import ModelMixin
from hyvideo.commons.parallel_states import get_parallel_state
@dataclassclass DecoderOutput(BaseOutput): sample: torch.FloatTensor posterior: Optional[DiagonalGaussianDistribution] = None
def swish(x: Tensor, inplace=False) -> Tensor: """Applies the swish activation function (SiLU) with optional inplace support.""" return F.silu(x, inplace=inplace)
def forward_with_checkpointing(module, *inputs, use_checkpointing=False): """Forward with optional gradient checkpointing.""" def create_custom_forward(module): def custom_forward(*inputs): return module(*inputs) return custom_forward
if use_checkpointing: return torch.utils.checkpoint.checkpoint(create_custom_forward(module), *inputs, use_reentrant=False) else: return module(*inputs)
# Optimized implementation of CogVideoXSafeConv3d# https://github.com/huggingface/diffusers/blob/c9ff360966327ace3faad3807dc871a4e5447501/src/diffusers/models/autoencoders/autoencoder_kl_cogvideox.py#L38class PatchCausalConv3d(nn.Conv3d): r"""Causal Conv3d with efficient patch processing for large tensors.""" def find_split_indices(self, seq_len, part_num): ideal_interval = seq_len / part_num possible_indices = list(range(0, seq_len, self.stride[0])) selected_indices = []
for i in range(1, part_num): closest = min(possible_indices, key=lambda x: abs(x - round(i * ideal_interval))) if closest not in selected_indices: selected_indices.append(closest)
merged_indices = [] prev_idx = 0 for idx in selected_indices: if idx - prev_idx >= self.kernel_size[0]: merged_indices.append(idx) prev_idx = idx
return merged_indices
def forward(self, input): T = input.shape[2] # input: NCTHW memory_count = torch.prod(torch.tensor(input.shape)).item() * 2 / 1024**3 if T > self.kernel_size[0] and memory_count > 0.6: kernel_size = self.kernel_size[0] part_num = int(memory_count / 2) + 1 split_indices = self.find_split_indices(T, part_num) input_chunks = torch.tensor_split(input, split_indices, dim=2) if len(split_indices) > 0 else [input] if kernel_size > 1: input_chunks = [input_chunks[0]] + [ torch.cat((input_chunks[i - 1][:, :, -kernel_size + 1:], input_chunks[i]), dim=2) for i in range(1, len(input_chunks)) ] output_chunks = [] for input_chunk in input_chunks: output_chunks.append(super().forward(input_chunk)) output = torch.cat(output_chunks, dim=2) return output else: return super().forward(input)
class RMS_norm(nn.Module): """Root Mean Square Layer Normalization for Channel-First or Last"""
def __init__(self, dim, channel_first=True, images=True, bias=False): super().__init__() broadcastable_dims = (1, 1, 1) if not images else (1, 1) shape = (dim, *broadcastable_dims) if channel_first else (dim,)
self.channel_first = channel_first self.scale = dim**0.5 self.gamma = nn.Parameter(torch.ones(shape)) self.bias = nn.Parameter(torch.zeros(shape)) if bias else 0.
def forward(self, x): return F.normalize( x, dim=(1 if self.channel_first else -1) ) * self.scale * self.gamma + self.bias
class CausalConv3d(nn.Module): """Causal Conv3d with configurable padding for temporal axis."""
def __init__( self, chan_in, chan_out, kernel_size: Union[int, Tuple[int, int, int]], stride: Union[int, Tuple[int, int, int]] = 1, dilation: Union[int, Tuple[int, int, int]] = 1, pad_mode='replicate', disable_causal=False, enable_patch_conv=False, **kwargs ): super().__init__()
self.pad_mode = pad_mode if disable_causal: padding = (kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2) else: padding = (kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size - 1, 0) # W, H, T self.time_causal_padding = padding
if enable_patch_conv: self.conv = PatchCausalConv3d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs) else: self.conv = nn.Conv3d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs)
def forward(self, x): x = F.pad(x, self.time_causal_padding, mode=self.pad_mode) return self.conv(x)
def prepare_causal_attention_mask(n_frame: int, n_hw: int, dtype, device, batch_size: int = None): """Prepare a causal attention mask for 3D videos.
Args: n_frame (int): Number of frames (temporal length). n_hw (int): Product of height and width. dtype: Desired mask dtype. device: Device for the mask. batch_size (int, optional): If set, expands for batch.
Returns: torch.Tensor: Causal attention mask. """ seq_len = n_frame * n_hw mask = torch.full((seq_len, seq_len), float("-inf"), dtype=dtype, device=device) for i in range(seq_len): i_frame = i // n_hw mask[i, : (i_frame + 1) * n_hw] = 0 if batch_size is not None: mask = mask.unsqueeze(0).expand(batch_size, -1, -1) return mask
class AttnBlock(nn.Module): """Self-attention block for 3D video tensors."""
def __init__(self, in_channels: int): super().__init__() self.in_channels = in_channels
self.norm = RMS_norm(in_channels, images=False)
self.q = Conv3d(in_channels, in_channels, kernel_size=1) self.k = Conv3d(in_channels, in_channels, kernel_size=1) self.v = Conv3d(in_channels, in_channels, kernel_size=1) self.proj_out = Conv3d(in_channels, in_channels, kernel_size=1)
def attention(self, h_: Tensor) -> Tensor: h_ = self.norm(h_) q = self.q(h_) k = self.k(h_) v = self.v(h_)
b, c, f, h, w = q.shape q = rearrange(q, "b c f h w -> b 1 (f h w) c").contiguous() k = rearrange(k, "b c f h w -> b 1 (f h w) c").contiguous() v = rearrange(v, "b c f h w -> b 1 (f h w) c").contiguous() attention_mask = prepare_causal_attention_mask(f, h * w, h_.dtype, h_.device, batch_size=b) h_ = nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask.unsqueeze(1))
return rearrange(h_, "b 1 (f h w) c -> b c f h w", f=f, h=h, w=w, c=c, b=b)
def forward(self, x: Tensor) -> Tensor: return x + self.proj_out(self.attention(x))
class ResnetBlock(nn.Module): """ResNet-style block for 3D video tensors."""
def __init__(self, in_channels: int, out_channels: int): super().__init__() self.in_channels = in_channels out_channels = in_channels if out_channels is None else out_channels self.out_channels = out_channels
self.norm1 = RMS_norm(in_channels, images=False) self.conv1 = CausalConv3d(in_channels, out_channels, kernel_size=3)
self.norm2 = RMS_norm(out_channels, images=False) self.conv2 = CausalConv3d(out_channels, out_channels, kernel_size=3) if self.in_channels != self.out_channels: self.nin_shortcut = Conv3d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
def forward(self, x): h = x h = self.norm1(h) h = swish(h, inplace=True) h = self.conv1(h)
h = self.norm2(h) h = swish(h, inplace=True) h = self.conv2(h)
if self.in_channels != self.out_channels: x = self.nin_shortcut(x) return x + h
class Downsample(nn.Module):
def __init__(self, in_channels: int, out_channels: int, add_temporal_downsample: bool = True): super().__init__() factor = 2 * 2 * 2 if add_temporal_downsample else 1 * 2 * 2 assert out_channels % factor == 0 self.conv = CausalConv3d(in_channels, out_channels // factor, kernel_size=3) self.add_temporal_downsample = add_temporal_downsample self.group_size = factor * in_channels // out_channels
def forward(self, x: Tensor): r1 = 2 if self.add_temporal_downsample else 1 h = self.conv(x) if self.add_temporal_downsample: h_first = h[:, :, :1, :, :] h_first = rearrange(h_first, "b c f (h r2) (w r3) -> b (r2 r3 c) f h w", r2=2, r3=2) h_first = torch.cat([h_first, h_first], dim=1) h_next = h[:, :, 1:, :, :] h_next = rearrange(h_next, "b c (f r1) (h r2) (w r3) -> b (r1 r2 r3 c) f h w", r1=r1, r2=2, r3=2) h = torch.cat([h_first, h_next], dim=2) # shortcut computation x_first = x[:, :, :1, :, :] x_first = rearrange(x_first, "b c f (h r2) (w r3) -> b (r2 r3 c) f h w", r2=2, r3=2) B, C, T, H, W = x_first.shape x_first = x_first.view(B, h.shape[1], self.group_size // 2, T, H, W).mean(dim=2)
x_next = x[:, :, 1:, :, :] x_next = rearrange(x_next, "b c (f r1) (h r2) (w r3) -> b (r1 r2 r3 c) f h w", r1=r1, r2=2, r3=2) B, C, T, H, W = x_next.shape x_next = x_next.view(B, h.shape[1], self.group_size, T, H, W).mean(dim=2) shortcut = torch.cat([x_first, x_next], dim=2) else: h = rearrange(h, "b c (f r1) (h r2) (w r3) -> b (r1 r2 r3 c) f h w", r1=r1, r2=2, r3=2) shortcut = rearrange(x, "b c (f r1) (h r2) (w r3) -> b (r1 r2 r3 c) f h w", r1=r1, r2=2, r3=2) B, C, T, H, W = shortcut.shape shortcut = shortcut.view(B, h.shape[1], self.group_size, T, H, W).mean(dim=2)
return h + shortcut
class Upsample(nn.Module): """Hierarchical upsampling with temporal/ spatial support."""
def __init__(self, in_channels: int, out_channels: int, add_temporal_upsample: bool = True): super().__init__() factor = 2 * 2 * 2 if add_temporal_upsample else 1 * 2 * 2 self.conv = CausalConv3d(in_channels, out_channels * factor, kernel_size=3) self.add_temporal_upsample = add_temporal_upsample self.repeats = factor * out_channels // in_channels
def forward(self, x: Tensor): r1 = 2 if self.add_temporal_upsample else 1 h = self.conv(x) if self.add_temporal_upsample: h_first = h[:, :, :1, :, :] h_first = rearrange(h_first, "b (r2 r3 c) f h w -> b c f (h r2) (w r3)", r2=2, r3=2) h_first = h_first[:, : h_first.shape[1] // 2] h_next = h[:, :, 1:, :, :] h_next = rearrange(h_next, "b (r1 r2 r3 c) f h w -> b c (f r1) (h r2) (w r3)", r1=r1, r2=2, r3=2) h = torch.cat([h_first, h_next], dim=2)
# shortcut computation x_first = x[:, :, :1, :, :] x_first = rearrange(x_first, "b (r2 r3 c) f h w -> b c f (h r2) (w r3)", r2=2, r3=2) x_first = x_first.repeat_interleave(repeats=self.repeats // 2, dim=1)
x_next = x[:, :, 1:, :, :] x_next = rearrange(x_next, "b (r1 r2 r3 c) f h w -> b c (f r1) (h r2) (w r3)", r1=r1, r2=2, r3=2) x_next = x_next.repeat_interleave(repeats=self.repeats, dim=1) shortcut = torch.cat([x_first, x_next], dim=2)
else: h = rearrange(h, "b (r1 r2 r3 c) f h w -> b c (f r1) (h r2) (w r3)", r1=r1, r2=2, r3=2) shortcut = x.repeat_interleave(repeats=self.repeats, dim=1) shortcut = rearrange(shortcut, "b (r1 r2 r3 c) f h w -> b c (f r1) (h r2) (w r3)", r1=r1, r2=2, r3=2) return h + shortcut
class Encoder(nn.Module): """Hierarchical video encoder with temporal and spatial factorization."""
def __init__( self, in_channels: int, z_channels: int, block_out_channels: Tuple[int, ...], num_res_blocks: int, ffactor_spatial: int, ffactor_temporal: int, downsample_match_channel: bool = True, ): super().__init__() assert block_out_channels[-1] % (2 * z_channels) == 0
self.z_channels = z_channels self.block_out_channels = block_out_channels self.num_res_blocks = num_res_blocks
# downsampling self.conv_in = CausalConv3d(in_channels, block_out_channels[0], kernel_size=3)
self.down = nn.ModuleList() block_in = block_out_channels[0] for i_level, ch in enumerate(block_out_channels): block = nn.ModuleList() block_out = ch for _ in range(self.num_res_blocks): block.append(ResnetBlock(in_channels=block_in, out_channels=block_out)) block_in = block_out down = nn.Module() down.block = block
add_spatial_downsample = bool(i_level < np.log2(ffactor_spatial)) add_temporal_downsample = add_spatial_downsample and bool(i_level >= np.log2(ffactor_spatial // ffactor_temporal)) if add_spatial_downsample or add_temporal_downsample: assert i_level < len(block_out_channels) - 1 block_out = block_out_channels[i_level + 1] if downsample_match_channel else block_in down.downsample = Downsample(block_in, block_out, add_temporal_downsample) block_in = block_out self.down.append(down)
# middle self.mid = nn.Module() self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in) self.mid.attn_1 = AttnBlock(block_in) self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
# end self.norm_out = RMS_norm(block_in, images=False) self.conv_out = CausalConv3d(block_in, 2 * z_channels, kernel_size=3)
self.gradient_checkpointing = False
def forward(self, x: Tensor) -> Tensor: """Forward pass through the encoder.""" use_checkpointing = bool(self.training and self.gradient_checkpointing)
# downsampling h = self.conv_in(x) for i_level in range(len(self.block_out_channels)): for i_block in range(self.num_res_blocks): h = forward_with_checkpointing(self.down[i_level].block[i_block], h, use_checkpointing=use_checkpointing) if hasattr(self.down[i_level], "downsample"): h = forward_with_checkpointing(self.down[i_level].downsample, h, use_checkpointing=use_checkpointing)
# middle h = forward_with_checkpointing(self.mid.block_1, h, use_checkpointing=use_checkpointing) h = forward_with_checkpointing(self.mid.attn_1, h, use_checkpointing=use_checkpointing) h = forward_with_checkpointing(self.mid.block_2, h, use_checkpointing=use_checkpointing)
# end group_size = self.block_out_channels[-1] // (2 * self.z_channels) shortcut = rearrange(h, "b (c r) f h w -> b c r f h w", r=group_size).mean(dim=2) h = self.norm_out(h) h = swish(h, inplace=True) h = self.conv_out(h) h += shortcut return h
class Decoder(nn.Module): """Hierarchical video decoder with upsampling factories."""
def __init__( self, z_channels: int, out_channels: int, block_out_channels: Tuple[int, ...], num_res_blocks: int, ffactor_spatial: int, ffactor_temporal: int, upsample_match_channel: bool = True, ): super().__init__() assert block_out_channels[0] % z_channels == 0
self.z_channels = z_channels self.block_out_channels = block_out_channels self.num_res_blocks = num_res_blocks
block_in = block_out_channels[0] self.conv_in = CausalConv3d(z_channels, block_in, kernel_size=3)
# middle self.mid = nn.Module() self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in) self.mid.attn_1 = AttnBlock(block_in) self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)
# upsampling self.up = nn.ModuleList() for i_level, ch in enumerate(block_out_channels): block = nn.ModuleList() block_out = ch for _ in range(self.num_res_blocks + 1): block.append(ResnetBlock(in_channels=block_in, out_channels=block_out)) block_in = block_out up = nn.Module() up.block = block
add_spatial_upsample = bool(i_level < np.log2(ffactor_spatial)) add_temporal_upsample = bool(i_level < np.log2(ffactor_temporal)) if add_spatial_upsample or add_temporal_upsample: assert i_level < len(block_out_channels) - 1 block_out = block_out_channels[i_level + 1] if upsample_match_channel else block_in up.upsample = Upsample(block_in, block_out, add_temporal_upsample) block_in = block_out self.up.append(up)
# end self.norm_out = RMS_norm(block_in, images=False) self.conv_out = CausalConv3d(block_in, out_channels, kernel_size=3)
self.gradient_checkpointing = False
def forward(self, z: Tensor) -> Tensor: """Forward pass through the decoder.""" use_checkpointing = bool(self.training and self.gradient_checkpointing)
# z to block_in repeats = self.block_out_channels[0] // (self.z_channels) h = self.conv_in(z) + z.repeat_interleave(repeats=repeats, dim=1)
# middle h = forward_with_checkpointing(self.mid.block_1, h, use_checkpointing=use_checkpointing) h = forward_with_checkpointing(self.mid.attn_1, h, use_checkpointing=use_checkpointing) h = forward_with_checkpointing(self.mid.block_2, h, use_checkpointing=use_checkpointing)
# upsampling for i_level in range(len(self.block_out_channels)): for i_block in range(self.num_res_blocks + 1): h = forward_with_checkpointing(self.up[i_level].block[i_block], h, use_checkpointing=use_checkpointing) if hasattr(self.up[i_level], "upsample"): h = forward_with_checkpointing(self.up[i_level].upsample, h, use_checkpointing=use_checkpointing)
# end h = self.norm_out(h) h = swish(h, inplace=True) h = self.conv_out(h) return h
class AutoencoderKLConv3D(ModelMixin, ConfigMixin): """KL regularized 3D Conv VAE with advanced tiling and slicing strategies.""" _supports_gradient_checkpointing = True
@register_to_config def __init__( self, in_channels: int, out_channels: int, latent_channels: int, block_out_channels: Tuple[int, ...], layers_per_block: int, ffactor_spatial: int, ffactor_temporal: int, sample_size: int, sample_tsize: int, scaling_factor: float = None, shift_factor: Optional[float] = None, downsample_match_channel: bool = True, upsample_match_channel: bool = True, ): super().__init__() self.ffactor_spatial = ffactor_spatial self.ffactor_temporal = ffactor_temporal self.scaling_factor = scaling_factor self.shift_factor = shift_factor
self.encoder = Encoder( in_channels=in_channels, z_channels=latent_channels, block_out_channels=block_out_channels, num_res_blocks=layers_per_block, ffactor_spatial=ffactor_spatial, ffactor_temporal=ffactor_temporal, downsample_match_channel=downsample_match_channel, ) self.decoder = Decoder( z_channels=latent_channels, out_channels=out_channels, block_out_channels=list(reversed(block_out_channels)), num_res_blocks=layers_per_block, ffactor_spatial=ffactor_spatial, ffactor_temporal=ffactor_temporal, upsample_match_channel=upsample_match_channel, )
self.use_slicing = False self.use_spatial_tiling = False self.use_temporal_tiling = False
# only relevant if vae tiling is enabled self.tile_sample_min_size = sample_size self.tile_latent_min_size = sample_size // ffactor_spatial self.tile_sample_min_tsize = sample_tsize self.tile_latent_min_tsize = sample_tsize // ffactor_temporal self.tile_overlap_factor = 0.25
self._tile_parallelism_enabled = False
def set_tile_sample_min_size(self, sample_size: int, tile_overlap_factor: float = 0.2): self.tile_sample_min_size = sample_size self.tile_latent_min_size = sample_size // self.ffactor_spatial self.tile_overlap_factor = tile_overlap_factor
assert (self.tile_latent_min_size * self.tile_overlap_factor).is_integer(), \ "self.tile_latent_min_size multiplied by tile_overlap_factor must be an integer"
def _set_gradient_checkpointing(self, module, value=False): """Enable or disable gradient checkpointing on encoder and decoder.""" if isinstance(module, (Encoder, Decoder)): module.gradient_checkpointing = value
def enable_temporal_tiling(self, use_tiling: bool = True): raise RuntimeError('Temporal tiling is not supported for this VAE.') self.use_temporal_tiling = use_tiling
def disable_temporal_tiling(self): self.enable_temporal_tiling(False)
def enable_spatial_tiling(self, use_tiling: bool = True): self.use_spatial_tiling = use_tiling
def disable_spatial_tiling(self): self.enable_spatial_tiling(False)
def enable_tiling(self, use_tiling: bool = True): self.enable_spatial_tiling(use_tiling)
def disable_tiling(self): self.disable_spatial_tiling()
def enable_slicing(self): self.use_slicing = True
def disable_slicing(self): self.use_slicing = False
def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int): """Blend tensor b horizontally into a at blend_extent region.""" blend_extent = min(a.shape[-1], b.shape[-1], blend_extent) for x in range(blend_extent): b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (x / blend_extent) return b
def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int): """Blend tensor b vertically into a at blend_extent region.""" blend_extent = min(a.shape[-2], b.shape[-2], blend_extent) for y in range(blend_extent): b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (y / blend_extent) return b
def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int): """Blend tensor b temporally into a at blend_extent region.""" blend_extent = min(a.shape[-3], b.shape[-3], blend_extent) for x in range(blend_extent): b[:, :, x, :, :] = a[:, :, -blend_extent + x, :, :] * (1 - x / blend_extent) + b[:, :, x, :, :] * (x / blend_extent) return b
def spatial_tiled_encode(self, x: torch.Tensor): """Tiled spatial encoding for large inputs via overlapping.""" B, C, T, H, W = x.shape overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor) row_limit = self.tile_latent_min_size - blend_extent
rows = [] for i in range(0, H, overlap_size): row = [] for j in range(0, W, overlap_size): tile = x[:, :, :, i: i + self.tile_sample_min_size, j: j + self.tile_sample_min_size] tile = self.encoder(tile) row.append(tile) rows.append(row) result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent) result_row.append(tile[:, :, :, :row_limit, :row_limit]) result_rows.append(torch.cat(result_row, dim=-1)) moments = torch.cat(result_rows, dim=-2) return moments
def temporal_tiled_encode(self, x: torch.Tensor): """Tiled temporal encoding for large video sequences.""" raise RuntimeError('Temporal tiling is not supported for this VAE.') B, C, T, H, W = x.shape overlap_size = int(self.tile_sample_min_tsize * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_latent_min_tsize * self.tile_overlap_factor) t_limit = self.tile_latent_min_tsize - blend_extent
row = [] for i in range(0, T, overlap_size): tile = x[:, :, i: i + self.tile_sample_min_tsize + 1, :, :] if self.use_spatial_tiling and (tile.shape[-1] > self.tile_sample_min_size or tile.shape[-2] > self.tile_sample_min_size): tile = self.spatial_tiled_encode(tile) else: tile = self.encoder(tile) if i > 0: tile = tile[:, :, 1:, :, :] row.append(tile) result_row = [] for i, tile in enumerate(row): if i > 0: tile = self.blend_t(row[i - 1], tile, blend_extent) result_row.append(tile[:, :, :t_limit, :, :]) else: result_row.append(tile[:, :, :t_limit + 1, :, :]) moments = torch.cat(result_row, dim=-3) return moments
def enable_tile_parallelism(self): self._tile_parallelism_enabled = True def disable_tile_parallelism(self): self._tile_parallelism_enabled = False
def tile_parallel_spatial_tiled_decode(self, z: torch.Tensor): B, C, T, H, W = z.shape overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor) row_limit = self.tile_sample_min_size - blend_extent
rank = get_parallel_state().sp_rank world_size = get_parallel_state().sp
num_rows = math.ceil(H / overlap_size) num_cols = math.ceil(W / overlap_size) total_tiles = num_rows * num_cols tiles_per_rank = math.ceil(total_tiles / world_size)
my_linear_indices = list(range(rank, total_tiles, world_size)) decoded_tiles = [] decoded_metas = [] H_out_std = self.tile_sample_min_size W_out_std = self.tile_sample_min_size for lin_idx in my_linear_indices: ri = lin_idx // num_cols rj = lin_idx % num_cols i = ri * overlap_size j = rj * overlap_size tile = z[:, :, :, i:i + self.tile_latent_min_size, j:j + self.tile_latent_min_size] dec = self.decoder(tile)
pad_h = max(0, H_out_std - dec.shape[-2]) pad_w = max(0, W_out_std - dec.shape[-1]) if pad_h > 0 or pad_w > 0: dec = F.pad(dec, (0, pad_w, 0, pad_h, 0, 0), "constant", 0) decoded_tiles.append(dec) decoded_metas.append(torch.tensor([ri, rj, pad_w, pad_h], device=z.device, dtype=torch.int64)) while len(decoded_tiles) < tiles_per_rank: zero_tile = torch.zeros( [1, 3, (T - 1) * self.ffactor_temporal + 1, self.tile_sample_min_size, self.tile_sample_min_size], device=dec.device, dtype=dec.dtype ) decoded_tiles.append(zero_tile) meta_tensor = torch.tensor( [-1, -1, self.tile_sample_min_size, self.tile_sample_min_size], device=z.device, dtype=torch.int64 ) decoded_metas.append(meta_tensor)
decoded_tiles = torch.stack(decoded_tiles, dim=0) decoded_metas = torch.stack(decoded_metas, dim=0) tiles_gather_list = [torch.empty_like(decoded_tiles) for _ in range(world_size)] metas_gather_list = [torch.empty_like(decoded_metas) for _ in range(world_size)]
dist.all_gather(tiles_gather_list, decoded_tiles, group=get_parallel_state().sp_group) dist.all_gather(metas_gather_list, decoded_metas, group=get_parallel_state().sp_group)
if rank != 0: return torch.empty(0, device=z.device)
rows = [[None for _ in range(num_cols)] for _ in range(num_rows)] for r in range(world_size): gathered_tiles_r = tiles_gather_list[r] # [tiles_per_rank, B, C, T, H, W] gathered_metas_r = metas_gather_list[r] # [tiles_per_rank, 4] for k in range(gathered_tiles_r.shape[0]): ri = int(gathered_metas_r[k][0]) rj = int(gathered_metas_r[k][1]) if ri < 0 or rj < 0: continue if ri < num_rows and rj < num_cols: # remove padding pad_w = int(gathered_metas_r[k][2]) pad_h = int(gathered_metas_r[k][3]) h_end = None if pad_h == 0 else -pad_h w_end = None if pad_w == 0 else -pad_w rows[ri][rj] = gathered_tiles_r[k][:, :, :, :h_end, :w_end]
result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): if tile is None: continue if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent) result_row.append(tile[:, :, :, :row_limit, :row_limit]) result_rows.append(torch.cat(result_row, dim=-1))
dec = torch.cat(result_rows, dim=-2) return dec
def spatial_tiled_decode(self, z: torch.Tensor): if self._tile_parallelism_enabled: return self.tile_parallel_spatial_tiled_decode(z)
B, C, T, H, W = z.shape overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor) row_limit = self.tile_sample_min_size - blend_extent
rows = [] for i in range(0, H, overlap_size): row = [] for j in range(0, W, overlap_size): tile = z[:, :, :, i: i + self.tile_latent_min_size, j: j + self.tile_latent_min_size] decoded = self.decoder(tile) row.append(decoded) rows.append(row)
result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent) result_row.append(tile[:, :, :, :row_limit, :row_limit]) result_rows.append(torch.cat(result_row, dim=-1)) dec = torch.cat(result_rows, dim=-2) return dec
def temporal_tiled_decode(self, z: torch.Tensor): """Tiled temporal decoding for long sequence latents.""" raise RuntimeError('Temporal tiling is not supported for this VAE.') B, C, T, H, W = z.shape overlap_size = int(self.tile_latent_min_tsize * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_sample_min_tsize * self.tile_overlap_factor) t_limit = self.tile_sample_min_tsize - blend_extent assert 0 < overlap_size < self.tile_latent_min_tsize
row = [] for i in range(0, T, overlap_size): tile = z[:, :, i: i + self.tile_latent_min_tsize + 1, :, :] if self.use_spatial_tiling and (tile.shape[-1] > self.tile_latent_min_size or tile.shape[-2] > self.tile_latent_min_size): decoded = self.spatial_tiled_decode(tile) else: decoded = self.decoder(tile) if i > 0: decoded = decoded[:, :, 1:, :, :] row.append(decoded)
result_row = [] for i, tile in enumerate(row): if i > 0: tile = self.blend_t(row[i - 1], tile, blend_extent) result_row.append(tile[:, :, :t_limit, :, :]) else: result_row.append(tile[:, :, :t_limit + 1, :, :]) dec = torch.cat(result_row, dim=-3) return dec
def encode(self, x: Tensor, return_dict: bool = True):
def _encode(x): if self.use_temporal_tiling and x.shape[-3] > self.tile_sample_min_tsize: return self.temporal_tiled_encode(x) if self.use_spatial_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.spatial_tiled_encode(x) return self.encoder(x)
assert len(x.shape) == 5 # (B, C, T, H, W)
if self.use_slicing and x.shape[0] > 1: encoded_slices = [_encode(x_slice) for x_slice in x.split(1)] h = torch.cat(encoded_slices) else: h = _encode(x) posterior = DiagonalGaussianDistribution(h)
if not return_dict: return (posterior,)
return AutoencoderKLOutput(latent_dist=posterior)
def decode(self, z: Tensor, return_dict: bool = True, generator=None):
def _decode(z): if self.use_temporal_tiling and z.shape[-3] > self.tile_latent_min_tsize: return self.temporal_tiled_decode(z) if self.use_spatial_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.spatial_tiled_decode(z) return self.decoder(z)
if self.use_slicing and z.shape[0] > 1: decoded_slices = [_decode(z_slice) for z_slice in z.split(1)] decoded = torch.cat(decoded_slices) else: decoded = _decode(z)
if not return_dict: return (decoded,)
return DecoderOutput(sample=decoded)
def forward( self, sample: torch.Tensor, sample_posterior: bool = False, return_posterior: bool = True, return_dict: bool = True ): """Forward autoencoder pass. Returns both reconstruction and optionally the posterior.""" posterior = self.encode(sample).latent_dist z = posterior.sample() if sample_posterior else posterior.mode() dec = self.decode(z).sample return DecoderOutput(sample=dec, posterior=posterior) if return_dict else (dec, posterior)
@contextmanager def memory_efficient_context(self): original_use_slicing = self.use_slicing original_use_spatial_tiling = self.use_spatial_tiling
self.enable_slicing() self.enable_tiling() yield self.use_slicing = original_use_slicing self.use_spatial_tiling = original_use_spatial_tiling123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911# Modified by the UniVEdit authors from Tencent-Hunyuan/OmniWeaving (HunyuanVideo-1.5).# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import osfrom copy import deepcopyfrom dataclasses import dataclassfrom typing import Optional, Tuple
import torchimport torch.nn as nn
from transformers import ( AutoTokenizer,)from transformers.utils import ModelOutput
from transformers import AutoTokenizer, Qwen2_5_VLForConditionalGenerationdef use_default(value, default): """Utility: return value if not None, else default.""" return value if value is not None else default
# Prompt templates for different models and tasks
__all__ = [ "C_SCALE", "PROMPT_TEMPLATE", "MODEL_BASE",]
# =================== Constant Values =====================# Computation scale factor, 1P = 1_000_000_000_000_000. Tensorboard will display the value in PetaFLOPS to avoid# overflow error when tensorboard logging values.C_SCALE = 1_000_000_000_000_000
PROMPT_TEMPLATE_ENCODE_IMAGE_JSON = [ {"role": "system", "content": "You are a helpful assistant. Describe the image by detailing the following aspects: \ 1. The main content and theme of the image. \ 2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects. \ 3. The background environment, light, style and atmosphere."}, {"role": "user", "content": "{}"}]
PROMPT_TEMPLATE_ENCODE_VIDEO_JSON = [ {"role": "system", "content": "You are a helpful assistant. Describe the video by detailing the following aspects: \ 1. The main content and theme of the video. \ 2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects. \ 3. Actions, events, behaviors temporal relationships, physical movement changes of the objects. \ 4. background environment, light, style and atmosphere. \ 5. camera angles, movements, and transitions used in the video."}, {"role": "user", "content": "{}"}]
PROMPT_TEMPLATE = { "li-dit-encode-image-json": {"template": PROMPT_TEMPLATE_ENCODE_IMAGE_JSON, "crop_start": -1}, # auto-calculate crop_start "li-dit-encode-video-json": {"template": PROMPT_TEMPLATE_ENCODE_VIDEO_JSON, "crop_start": -1}, # auto-calculate crop_start}
system_prompt_1 = {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant. Given a text instruction and an input image, generate an edited image that follows the user's instruction. The edited image should apply the requested changes to the objects, attributes, style, background, scene composition, camera trajectory transformation, or object moving and rotation, while preserving the irrelevant regions, spatial layout, and visual identity of the original image unless the instruction explicitly requires changing them."}]}system_prompt_2 = {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant. Given a text instruction, an input image, and one or more reference images, generate an edited image by applying the relevant subject, style, object, identity, or scene attributes from the reference images to the input image. The edited image should follow the user's instruction, preserve the irrelevant regions and spatial layout of the input image, and incorporate the specified reference attributes accurately and consistently."}]}system_prompt_3 = {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant. Given a text instruction and an input video, you need to analyze the visual content and temporal dynamics of the input video, and then explain how the user's text instruction should modify the video's visual style, objects, or scene composition. Generate an edited video that meets the user's requirements, ensuring the specified modifications are applied consistently across frames while preserving the original motion flow and coherence."}]}system_prompt_4 = {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant. Given a text instruction, a reference image and an input video, you need to analyze the visual content and temporal dynamics of the input video, alongside the scene or subject characteristics of the reference image. Explain how the user's text instruction directs the application of the reference image's visual attributes onto the input video. Generate an edited video that meets the user's requirements, ensuring the specified modifications are applied consistently across frames while preserving the original motion flow and coherence."}]}system_prompt_5 = {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant. Given an observation video of a 3D scene and a text editing instruction, generate an edited observation video of the same 3D scene. Apply the requested edit while preserving the scene’s static structure and 3D geometric consistency. Temporal changes should mainly come from camera motion or viewpoint changes, rather than object motion, unless explicitly required. Preserve object identity, layout, scale, relative positions, appearance, lighting, and geometry. Ensure the edited scene remains consistent across frames, with plausible perspective, parallax, and occlusion."}]}
from qwen_vl_utils import process_vision_infofrom transformers import AutoProcessorfrom univedit.tokens import SPECIAL_TOKENS
MODEL_BASE = os.getenv("MODEL_BASE", "")TEXT_ENCODER_PATH = {}TOKENIZER_PATH = {}
PRECISION_TO_TYPE = { 'fp32': torch.float32, 'fp16': torch.float16, 'bf16': torch.bfloat16,}
def load_text_encoder( text_encoder_type, text_encoder_precision=None, text_encoder_path=None, logger=None, device=None,): if text_encoder_path is None: if text_encoder_type not in TEXT_ENCODER_PATH: raise ValueError(f"Unsupported text encoder type: {text_encoder_type}") text_encoder_path = TEXT_ENCODER_PATH[text_encoder_type]
# Demo patch: load straight into the target precision to halve peak host RAM. text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained( text_encoder_path, low_cpu_mem_usage=True, torch_dtype=PRECISION_TO_TYPE[text_encoder_precision] if text_encoder_precision else None, )
text_encoder.final_layer_norm = text_encoder.model.language_model.norm # from_pretrained will ensure that the model is in eval mode. if text_encoder_precision is not None: text_encoder = text_encoder.to(dtype=PRECISION_TO_TYPE[text_encoder_precision])
text_encoder.requires_grad_(False)
if device is not None: text_encoder = text_encoder.to(device)
return text_encoder, text_encoder_path
def load_tokenizer( tokenizer_type, tokenizer_path=None, padding_side="right", logger=None): processor = None if tokenizer_path is None: if tokenizer_type not in TOKENIZER_PATH: raise ValueError(f"Unsupported tokenizer type: {tokenizer_type}") tokenizer_path = TOKENIZER_PATH[tokenizer_type]
tokenizer = AutoTokenizer.from_pretrained( tokenizer_path, padding_side=padding_side )
return tokenizer, tokenizer_path, processor
def register_modality_tokens(tokenizer, model=None, logger=None): """Register task-modality tags as atomic special tokens.""" num_added = tokenizer.add_special_tokens( {"additional_special_tokens": list(SPECIAL_TOKENS)}, replace_additional_special_tokens=False, )
if model is not None: embedding = model.get_input_embeddings() if embedding is not None and embedding.num_embeddings < len(tokenizer): model.resize_token_embeddings(len(tokenizer), mean_resizing=False)
if logger is not None and num_added: logger.info(f"Registered modality special tokens: {SPECIAL_TOKENS}")
return num_added
@dataclassclass TextEncoderModelOutput(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states.
Args: hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: hidden_states_list (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. text_outputs (`list`, *optional*, returned when `return_texts=True` is passed): List of decoded texts. """
hidden_state: torch.FloatTensor = None attention_mask: Optional[torch.LongTensor] = None hidden_states_list: Optional[Tuple[torch.FloatTensor, ...]] = None text_outputs: Optional[list] = None image_features: Optional[list] = None deepstack_hidden_states: torch.FloatTensor = None
class TextEncoder(nn.Module): def __init__( self, text_encoder_type: str, max_length: int, text_encoder_precision: Optional[str] = None, text_encoder_path: Optional[str] = None, tokenizer_type: Optional[str] = None, tokenizer_path: Optional[str] = None, output_key: Optional[str] = None, use_attention_mask: bool = True, prompt_template: Optional[dict] = None, prompt_template_video: Optional[dict] = None, hidden_state_skip_layer: Optional[int] = None, apply_final_norm: bool = False, reproduce: bool = False, logger=None, device=None, ): super().__init__() self.text_encoder_type = text_encoder_type self.max_length = max_length self.precision = text_encoder_precision self.model_path = text_encoder_path self.tokenizer_type = ( tokenizer_type if tokenizer_type is not None else text_encoder_type ) self.tokenizer_path = ( tokenizer_path if tokenizer_path is not None else text_encoder_path ) self.use_attention_mask = use_attention_mask if prompt_template_video is not None: assert ( use_attention_mask is True ), "Attention mask is True required when training videos." self.prompt_template = prompt_template self.prompt_template_video = prompt_template_video self.hidden_state_skip_layer = hidden_state_skip_layer self.apply_final_norm = apply_final_norm self.reproduce = reproduce self.logger = logger
self.use_template = self.prompt_template is not None if self.use_template: assert ( isinstance(self.prompt_template, dict) and "template" in self.prompt_template ), f"`prompt_template` must be a dictionary with a key 'template', got {self.prompt_template}" assert "{}" in str(self.prompt_template["template"]), ( "`prompt_template['template']` must contain a placeholder `{}` for the input text, " f"got {self.prompt_template['template']}" )
self.use_video_template = self.prompt_template_video is not None if self.use_video_template: if self.prompt_template_video is not None: assert ( isinstance(self.prompt_template_video, dict) and "template" in self.prompt_template_video ), f"`prompt_template_video` must be a dictionary with a key 'template', got {self.prompt_template_video}" assert "{}" in str(self.prompt_template_video["template"]), ( "`prompt_template_video['template']` must contain a placeholder `{}` for the input text, " f"got {self.prompt_template_video['template']}" )
if text_encoder_type != "llm": raise ValueError(f"Unsupported text encoder type: {text_encoder_type}") self.output_key = output_key or "last_hidden_state"
self.model, self.model_path = load_text_encoder( text_encoder_type=self.text_encoder_type, text_encoder_precision=self.precision, text_encoder_path=self.model_path, logger=self.logger, device=device, )
self.tokenizer, self.tokenizer_path, self.processor = load_tokenizer( tokenizer_type=self.tokenizer_type, tokenizer_path=self.tokenizer_path, padding_side="right", logger=self.logger, ) register_modality_tokens(self.tokenizer, self.model, self.logger) self.processor = AutoProcessor.from_pretrained(self.tokenizer_path) if hasattr(self.processor, "tokenizer") and self.processor.tokenizer is not None: register_modality_tokens(self.processor.tokenizer, self.model, self.logger) self.model.requires_grad_(False)
# pre-calculate crop_start for image and video if self.use_template and self.prompt_template is not None: self.text2tokens("a photo of a cat", data_type="image") if self.use_video_template and self.prompt_template_video is not None: self.text2tokens("a photo of a cat", data_type="video")
@property def dtype(self): return self.model.dtype @property def device(self): return self.model.device
def __repr__(self): return f"{self.text_encoder_type} ({self.precision} - {self.model_path})"
@staticmethod def apply_text_to_template(text, template, prevent_empty_text=True): """ Apply text to template.
Args: text (str): Input text. template (str or list): Template string or list of chat conversation. prevent_empty_text (bool): If Ture, we will prevent the user text from being empty by adding a space. Defaults to True. """ if isinstance(template, str): # Will send string to tokenizer. Used for llm return template.format(text) elif isinstance(template, list): # For JSON list template format (chat conversation) # Create a deep copy to avoid modifying the original template template_copy = deepcopy(template) for item in template_copy: if isinstance(item, dict) and "content" in item: # Replace placeholder with text in the content field item["content"] = item["content"].format(text if text else (" " if prevent_empty_text else "")) return template_copy else: raise TypeError(f"Unsupported template type: {type(template)}")
@staticmethod def _normalize_modality_tokens(modality_tokens, batch_size): if modality_tokens is None: return [None] * batch_size if isinstance(modality_tokens, str): modality_tokens = [modality_tokens] * batch_size else: modality_tokens = list(modality_tokens) if len(modality_tokens) != batch_size: raise ValueError( f"Expected {batch_size} modality tokens, got {len(modality_tokens)}." ) invalid_tokens = [ token for token in modality_tokens if token is not None and token not in SPECIAL_TOKENS ] if invalid_tokens: raise ValueError( f"Invalid modality tokens {invalid_tokens}. Expected one of {SPECIAL_TOKENS}." ) return modality_tokens
@staticmethod def _prepend_modality_token_to_serialized_text(text, token): if token is None: return text return f"{token}{text}"
def _has_leading_modality_token(self, batch_encoding): input_ids = batch_encoding.get("input_ids", None) if input_ids is None or input_ids.ndim != 2 or input_ids.shape[1] == 0: return False for token in SPECIAL_TOKENS: token_id = self.tokenizer.convert_tokens_to_ids(token) if token_id is None or token_id == self.tokenizer.unk_token_id: continue if bool((input_ids[:, 0] == token_id).all().item()): return True return False
def calculate_crop_start(self, tokenized_input): """ Automatically calculate the crop_start position based on identifying user tokens. Args: tokenized_input: The output from the tokenizer containing input_ids Returns: int: The position where the actual prompt content begins (after user markers) """ input_ids = tokenized_input["input_ids"][0].tolist() # Get the first example's tokens marker = "<|im_start|>user\n" # Tokenize just the marker to get its token IDs marker_tokens = self.tokenizer(marker, add_special_tokens=False)["input_ids"] # Find the end position of the marker in the input sequence for i in range(len(input_ids) - len(marker_tokens) + 1): if input_ids[i:i+len(marker_tokens)] == marker_tokens: # Return the position after the marker return i + len(marker_tokens) # If marker not found, try to find based on special tokens if hasattr(self.tokenizer, 'special_tokens_map'): # Check for user token or any other special token that might indicate user input start for token_name, token_value in self.tokenizer.special_tokens_map.items(): if 'user' in token_name.lower(): user_token_id = self.tokenizer.convert_tokens_to_ids(token_value) if user_token_id in input_ids: return input_ids.index(user_token_id) + 1 # Default fallback: return 0 (no cropping) return 0
def text2tokens(self, text, data_type="image", max_length=300): """ Tokenize the input text.
Args: text (str or list): Input text. """ tokenize_input_type = "str" if self.use_template or self.use_video_template: if data_type == "image": prompt_template = self.prompt_template["template"] crop_start = self.prompt_template.get("crop_start", -1) elif data_type == "video": prompt_template = self.prompt_template_video["template"] crop_start = self.prompt_template_video.get("crop_start", -1) else: raise ValueError(f"Unsupported data type: {data_type}") if isinstance(text, (list, tuple)): text = [ self.apply_text_to_template(one_text, prompt_template) for one_text in text ] if isinstance(text[0], list): tokenize_input_type = "list" elif isinstance(text, str): text = self.apply_text_to_template(text, prompt_template) if isinstance(text, list): tokenize_input_type = "list" else: raise TypeError(f"Unsupported text type: {type(text)}") # First pass: tokenize with arbitrary max_length to find crop_start if crop_start == -1: # Use temporary max_length for the first pass (large enough) temp_kwargs = dict( truncation=True, max_length=256, # Temporary large value padding="max_length", return_tensors="pt", ) # First tokenization pass to calculate crop_start if tokenize_input_type == "str": temp_tokenized = self.tokenizer( text, return_length=False, return_overflowing_tokens=False, return_attention_mask=True, **temp_kwargs, ) elif tokenize_input_type == "list": temp_tokenized = self.tokenizer.apply_chat_template( text, add_generation_prompt=True, tokenize=True, return_dict=True, **temp_kwargs, ) # Calculate the crop_start from this first pass crop_start = self.calculate_crop_start(temp_tokenized) # Store the calculated crop_start for future use if data_type == "image": self.prompt_template["crop_start"] = crop_start else: self.prompt_template_video["crop_start"] = crop_start else: crop_start = 0 # Second pass: tokenize with the proper max_length using the found crop_start kwargs = dict( truncation=True, max_length=max_length + (crop_start if crop_start > 0 else 0), padding="max_length", return_tensors="pt", ) if tokenize_input_type == "str": tokenized_output = self.tokenizer( text, return_length=False, return_overflowing_tokens=False, return_attention_mask=True, **kwargs, ) elif tokenize_input_type == "list": tokenized_output = self.tokenizer.apply_chat_template( text, add_generation_prompt=True, tokenize=True, return_dict=True, **kwargs, ) else: raise ValueError(f"Unsupported tokenize_input_type: {tokenize_input_type}") return tokenized_output
def encode( self, batch_encoding, use_attention_mask=None, output_hidden_states=False, do_sample=None, hidden_state_skip_layer=None, return_texts=False, data_type="image", device=None, is_uncond=False, deepstack=[], crop_start=None, setclip=False ): """ Args: batch_encoding (dict): Batch encoding from tokenizer. use_attention_mask (bool): Whether to use attention mask. If None, use self.use_attention_mask. Defaults to None. output_hidden_states (bool): Whether to output hidden states. If False, return the value of self.output_key. If True, return the entire output. If set self.hidden_state_skip_layer, output_hidden_states will be set True. Defaults to False. do_sample (bool): Whether to sample from the model. Used for Decoder-Only LLMs. Defaults to None. When self.produce is False, do_sample is set to True by default. hidden_state_skip_layer (int): Number of hidden states to hidden_state_skip_layer. 0 means the last layer. If None, self.output_key will be used. Defaults to None. return_texts (bool): Whether to return the decoded texts. Defaults to False. """ device = self.model.device if device is None else device use_attention_mask = use_default(use_attention_mask, self.use_attention_mask) hidden_state_skip_layer = use_default( hidden_state_skip_layer, self.hidden_state_skip_layer ) do_sample = use_default(do_sample, not self.reproduce)
batch_encoding = batch_encoding.to(device) attention_mask = ( batch_encoding["attention_mask"] if use_attention_mask else None ) deepstack_hidden_state_map = {} deepstack_handles = [] needs_full_hidden_states = output_hidden_states or hidden_state_skip_layer is not None if deepstack is not None and len(deepstack) > 0 and not needs_full_hidden_states: language_model = getattr(getattr(self.model, "model", None), "language_model", None) layers = getattr(language_model, "layers", None) if layers is None or any(iddx <= 0 or iddx >= len(layers) for iddx in deepstack): needs_full_hidden_states = True else: def make_deepstack_hook(stack_idx): def capture_hidden_state(module, inputs): deepstack_hidden_state_map[stack_idx] = inputs[0] return capture_hidden_state
for iddx in deepstack: deepstack_handles.append( layers[iddx].register_forward_pre_hook(make_deepstack_hook(iddx)) ) elif deepstack is not None and len(deepstack) > 0: needs_full_hidden_states = True
try: outputs = self.model.model( **batch_encoding, output_hidden_states=needs_full_hidden_states, ) finally: for handle in deepstack_handles: handle.remove() if hidden_state_skip_layer is not None: last_hidden_state = outputs.hidden_states[-(hidden_state_skip_layer + 1)] # Real last hidden state already has layer norm applied. So here we only apply it # for intermediate layers. if hidden_state_skip_layer > 0 and self.apply_final_norm: last_hidden_state = self.model.final_layer_norm(last_hidden_state) else: last_hidden_state = outputs[self.output_key]
# Remove hidden states of instruction tokens, only keep prompt tokens. input_tensor = batch_encoding["input_ids"] keep_leading_modality_token = self._has_leading_modality_token(batch_encoding) if self.use_template: if crop_start is None: if data_type == "image": crop_start = self.prompt_template.get("crop_start", 0) elif data_type == "video": crop_start = self.prompt_template_video.get("crop_start", 0) else: raise ValueError(f"Unsupported data type: {data_type}") if crop_start > 0: sequence_crop_start = ( crop_start + 1 if keep_leading_modality_token else crop_start ) if keep_leading_modality_token: last_hidden_state = torch.cat( [ last_hidden_state[:, :1], last_hidden_state[:, sequence_crop_start:], ], dim=1, ) attention_mask = ( torch.cat( [ attention_mask[:, :1], attention_mask[:, sequence_crop_start:], ], dim=1, ) if use_attention_mask else None ) input_tensor = torch.cat( [ input_tensor[:, :1], input_tensor[:, sequence_crop_start:], ], dim=1, ) else: last_hidden_state = last_hidden_state[:, crop_start:] attention_mask = ( attention_mask[:, crop_start:] if use_attention_mask else None ) input_tensor = input_tensor[:, crop_start:] if crop_start is None: crop_start = 0 if deepstack is not None and len(deepstack)>0: if needs_full_hidden_states: deepstack_hidden_states = [outputs.hidden_states[iddx] for iddx in deepstack] else: missing_deepstack = [ iddx for iddx in deepstack if iddx not in deepstack_hidden_state_map ] if missing_deepstack: raise RuntimeError(f"Failed to capture deepstack hidden states: {missing_deepstack}") deepstack_hidden_states = [deepstack_hidden_state_map[iddx] for iddx in deepstack] deepstack_hidden_states = torch.stack(deepstack_hidden_states, dim=0) if crop_start > 0 and keep_leading_modality_token: sequence_crop_start = crop_start + 1 deepstack_hidden_states = torch.cat( [ deepstack_hidden_states[:, :, :1, :], deepstack_hidden_states[:, :, sequence_crop_start:, :], ], dim=2, ) else: deepstack_hidden_states = deepstack_hidden_states[:, :, crop_start:, :] deepstack_hidden_states = deepstack_hidden_states * attention_mask.unsqueeze(0).unsqueeze(-1) else: deepstack_hidden_states = None if setclip and 'pixel_values' in batch_encoding: B, L = input_tensor.shape mask = (input_tensor == 151653)
index_range = torch.arange(L, device=input_tensor.device).expand(B, L) masked_indices = torch.where(mask, index_range, torch.tensor(-1, device=input_tensor.device)) last_indices = masked_indices.max(dim=1).values # (B,)
all_last_hidden_state = [] all_attention_mask = [] all_deepstack_hidden_states = [] for kkk in range(B): idx = last_indices[kkk].item() if idx != -1 and idx < L - 1: cur_last_hidden_state = last_hidden_state[kkk, idx + 1:] cur_attention_mask = attention_mask[kkk, idx+1:] if deepstack_hidden_states is not None: cur_deepstack_hidden_states = deepstack_hidden_states[:, kkk, idx+1:] if keep_leading_modality_token: cur_last_hidden_state = torch.cat( [last_hidden_state[kkk, :1], cur_last_hidden_state], dim=0, ) cur_attention_mask = torch.cat( [attention_mask[kkk, :1], cur_attention_mask], dim=0, ) if deepstack_hidden_states is not None: cur_deepstack_hidden_states = torch.cat( [ deepstack_hidden_states[:, kkk, :1], cur_deepstack_hidden_states, ], dim=1, ) else: cur_last_hidden_state = last_hidden_state[kkk] cur_attention_mask = attention_mask[kkk] if deepstack_hidden_states is not None: cur_deepstack_hidden_states = deepstack_hidden_states[:, kkk] all_last_hidden_state.append(cur_last_hidden_state) all_attention_mask.append(cur_attention_mask) if deepstack_hidden_states is not None: all_deepstack_hidden_states.append(cur_deepstack_hidden_states) max_len = max([t.size(0) for t in all_last_hidden_state]) myhidden_size = last_hidden_state.size(-1) mydevice = last_hidden_state.device
padded_last_hidden_state = torch.zeros((B, max_len, myhidden_size), device=mydevice, dtype=last_hidden_state.dtype) padded_attention_mask = torch.zeros((B, max_len), device=mydevice, dtype=attention_mask.dtype) padded_deepstack = None if deepstack_hidden_states is not None: # (Layers, B, L, H) num_layers = deepstack_hidden_states.size(0) padded_deepstack = torch.zeros((num_layers, B, max_len, myhidden_size), device=mydevice, dtype=deepstack_hidden_states.dtype)
for i in range(B): curr_len = all_last_hidden_state[i].size(0)
padded_last_hidden_state[i, :curr_len, :] = all_last_hidden_state[i] padded_attention_mask[i, :curr_len] = all_attention_mask[i] if deepstack_hidden_states is not None: padded_deepstack[:, i, :curr_len, :] = all_deepstack_hidden_states[i]
last_hidden_state = padded_last_hidden_state attention_mask = padded_attention_mask deepstack_hidden_states = padded_deepstack
if output_hidden_states: return TextEncoderModelOutput( last_hidden_state, attention_mask, outputs.hidden_states, deepstack_hidden_states=deepstack_hidden_states ) return TextEncoderModelOutput(last_hidden_state, attention_mask, deepstack_hidden_states=deepstack_hidden_states)
def forward( self, text, use_attention_mask=None, output_hidden_states=False, do_sample=False, hidden_state_skip_layer=None, return_texts=False, ): batch_encoding = self.text2tokens(text, max_length=self.max_length) return self.encode( batch_encoding, use_attention_mask=use_attention_mask, output_hidden_states=output_hidden_states, do_sample=do_sample, hidden_state_skip_layer=hidden_state_skip_layer, return_texts=return_texts, )
def get_task_prompt(self, prompt_mode): # prompt_mode -> (system prompt, number of system-prompt tokens to crop) # 1 = i2i, 2 = ti_i2i, 3 = v2v, 4 = tiv2v, 5 = 3d23d if prompt_mode == 1: return system_prompt_1, 89 if prompt_mode == 2: return system_prompt_2, 90 if prompt_mode == 3: return system_prompt_3, 90 if prompt_mode == 4: return system_prompt_4, 104 if prompt_mode == 5: return system_prompt_5, 121 return None, None
def prepare_input( self, texts, imgs=None, videos=None, num_frames=2, prompt_mode=None, token_per_image=None, add_generation_prompt=True, modality_tokens=None, ): if token_per_image is None: token_per_image = 400 select_prompt = None select_crop_size = None if not prompt_mode: raise ValueError("prompt_mode is required for prepare_input to select the correct system prompt and crop size.") else: select_prompt, select_crop_size = self.get_task_prompt(prompt_mode)
if isinstance(texts, str): texts = [texts] else: texts = list(texts) modality_tokens = self._normalize_modality_tokens( modality_tokens, len(texts), ) modality_prefix_length = int(any(token is not None for token in modality_tokens))
messages = [] if prompt_mode == 4: assert imgs is not None and videos is not None, \ "prompt_mode=4 expects both imgs and videos" crop_size = select_crop_size if select_crop_size is not None else 104
num_frames = len(videos[0]) img_len = token_per_image * (num_frames // 2) + token_per_image + 32 for txt, curimg, video in zip(texts, imgs, videos): if txt is None or txt == '': txt = ' ' # Exactly one reference image per sample (a bare image or a 1-element list). if isinstance(curimg, (list, tuple)): if len(curimg) != 1: raise ValueError( f"prompt_mode=4 expects exactly one reference image per sample, got {len(curimg)}" ) curimg = curimg[0] messages.append([ select_prompt if select_prompt is not None else system_prompt_4, { "role": "user", "content": [ {"type": "text", "text": 'This is the reference image:'}, {"type": "image", "image": curimg}, {"type": "text", "text": 'This is the input video:'}, {"type": "video", "video": video, "max_pixels": 560 * 560}, {"type": "text", "text": txt}, ] } ])
elif prompt_mode in (3, 5): assert videos is not None, f"prompt_mode={prompt_mode} expects videos" assert imgs is None, "imgs and videos cannot be both not None" crop_size = select_crop_size if select_crop_size is not None else 90
num_frames = len(videos[0]) img_len = token_per_image * (num_frames // 2) fallback_prompt = system_prompt_5 if prompt_mode == 5 else system_prompt_3 for txt, video in zip(texts, videos): if txt is None or txt == '': txt = ' ' messages.append([ select_prompt if select_prompt is not None else fallback_prompt, { "role": "user", "content": [ {"type": "video", "video": video, "max_pixels": 560 * 560}, {"type": "text", "text": txt}, ] } ])
elif prompt_mode == 1: assert imgs is not None, "prompt_mode=1 expects imgs" img_len = token_per_image for txt, img in zip(texts, imgs): if txt is None or txt == '': txt = ' ' crop_size = select_crop_size if select_crop_size is not None else 89 messages.append([select_prompt if select_prompt is not None else system_prompt_1, { "role": "user", "content": [ {"type": "image", "image": img[0]}, {"type": "text", "text": txt}, ] }])
elif prompt_mode == 2: assert imgs is not None, "prompt_mode=2 expects imgs" img_len = token_per_image for txt, img in zip(texts, imgs): if txt is None or txt == '': txt = ' ' crop_size = select_crop_size if select_crop_size is not None else 90 messages.append([select_prompt if select_prompt is not None else system_prompt_2, { "role": "user", "content": [ {"type": "text", "text": "This is the reference image:"}, {"type": "image", "image": img[-1]}, {"type": "text", "text": "These are the input images:"}, {"type": "image", "image": img[0]}, {"type": "text", "text": txt}, ] }])
else: raise ValueError(f"Unsupported prompt_mode: {prompt_mode}")
texts = [] for msg, modality_token in zip(messages, modality_tokens): serialized_text = self.processor.apply_chat_template( msg, tokenize=False, add_generation_prompt=add_generation_prompt ) texts.append( self._prepend_modality_token_to_serialized_text( serialized_text, modality_token, ) ) image_inputs, video_inputs = process_vision_info(messages) inputs = self.processor( text=texts, images=image_inputs, videos=video_inputs, return_tensors="pt", truncation=True, max_length=self.max_length + crop_size + img_len + modality_prefix_length, padding="max_length", ) return inputs, crop_size123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import jsonimport torchimport torch.nn as nnfrom transformers import AutoTokenizer, T5ForConditionalGeneration
def load_glyph_byT5_v2(args, device): """ Loads ByT5 tokenizer and encoder model for glyph encoding.
Args: args (dict): Configuration dictionary containing paths and settings. device (str or torch.device): Device to load the model onto.
Returns: dict: Dictionary with keys 'byt5_tokenizer', 'byt5_model', 'byt5_max_length'. """ byt5_tokenizer, byt5_model, byt5_max_length = create_byt5(args, device) byt5_model = byt5_model.to(device=device) return { "byt5_tokenizer": byt5_tokenizer, "byt5_model": byt5_model, "byt5_max_length": byt5_max_length, }
def create_byt5(args, device): """ Create ByT5 tokenizer and encoder, load weights if provided.
Args: args (dict): Configuration dictionary. device (str or torch.device): Device to load the model onto.
Returns: tuple: (byt5_tokenizer, byt5_model, byt5_max_length) """ byt5_max_length = args['byt5_max_length'] byt5_config = dict( byt5_name=args['byT5_google_path'], special_token=True, color_special_token=True, font_special_token=True, color_ann_path=args['multilingual_prompt_format_color_path'], font_ann_path=args['multilingual_prompt_format_font_path'], multilingual=True, ) huggingface_cache_dir = None byt5_model, byt5_tokenizer = load_byt5_and_byt5_tokenizer( **byt5_config, huggingface_cache_dir=huggingface_cache_dir, device=device, )
# Load custom checkpoint if provided if args['byT5_ckpt_path'] is not None: if "cuda" not in str(device): byt5_state_dict = torch.load(args['byT5_ckpt_path'], map_location=device) else: byt5_state_dict = torch.load(args['byT5_ckpt_path'], map_location=device) if 'state_dict' in byt5_state_dict: sd = byt5_state_dict["state_dict"] newsd = {} for k, v in sd.items(): if k.startswith('module.text_tower.encoder.'): newsd[k[len('module.text_tower.encoder.'):]] = v byt5_state_dict = newsd byt5_model.load_state_dict(byt5_state_dict) byt5_model.requires_grad_(False) return byt5_tokenizer, byt5_model, byt5_max_length
def add_special_token( tokenizer, text_encoder, add_color, add_font, color_ann_path, font_ann_path, multilingual=False,): """ Add special tokens for color and font to tokenizer and text encoder.
Args: tokenizer: Huggingface tokenizer. text_encoder: Huggingface T5 encoder. add_color (bool): Whether to add color tokens. add_font (bool): Whether to add font tokens. color_ann_path (str): Path to color annotation JSON. font_ann_path (str): Path to font annotation JSON. multilingual (bool): Whether to use multilingual font tokens. """ with open(font_ann_path, 'r') as f: idx_font_dict = json.load(f) with open(color_ann_path, 'r') as f: idx_color_dict = json.load(f)
if multilingual: font_token = [f'<{font_code[:2]}-font-{idx_font_dict[font_code]}>' for font_code in idx_font_dict] else: font_token = [f'<font-{i}>' for i in range(len(idx_font_dict))] color_token = [f'<color-{i}>' for i in range(len(idx_color_dict))] additional_special_tokens = [] if add_color: additional_special_tokens += color_token if add_font: additional_special_tokens += font_token
tokenizer.add_tokens(additional_special_tokens, special_tokens=True) # Set mean_resizing=False to avoid PyTorch LAPACK dependency text_encoder.resize_token_embeddings(len(tokenizer), mean_resizing=False)
def load_byt5_and_byt5_tokenizer( byt5_name='google/byt5-small', special_token=False, color_special_token=False, font_special_token=False, color_ann_path='assets/color_idx.json', font_ann_path='assets/font_idx_512.json', huggingface_cache_dir=None, multilingual=False, device=None,): """ Load ByT5 encoder and tokenizer from Huggingface, and add special tokens if needed.
Args: byt5_name (str): Model name or path. special_token (bool): Whether to add special tokens. color_special_token (bool): Whether to add color tokens. font_special_token (bool): Whether to add font tokens. color_ann_path (str): Path to color annotation JSON. font_ann_path (str): Path to font annotation JSON. huggingface_cache_dir (str): Huggingface cache directory. multilingual (bool): Whether to use multilingual font tokens. device (str or torch.device): Device to load the model onto.
Returns: tuple: (byt5_text_encoder, byt5_tokenizer) """ byt5_tokenizer = AutoTokenizer.from_pretrained( byt5_name, cache_dir=huggingface_cache_dir, ) byt5_text_encoder = T5ForConditionalGeneration.from_pretrained( byt5_name, cache_dir=huggingface_cache_dir, ).get_encoder()
if "cuda" not in str(device): device = torch.device(device) else: device = torch.device(device) byt5_text_encoder = byt5_text_encoder.to(device)
if special_token: add_special_token( byt5_tokenizer, byt5_text_encoder, add_color=color_special_token, add_font=font_special_token, color_ann_path=color_ann_path, font_ann_path=font_ann_path, multilingual=multilingual, ) return byt5_text_encoder, byt5_tokenizer
class ByT5Mapper(nn.Module): """ ByT5Mapper: Maps ByT5 encoder outputs to a new space, with optional residual connection.
Args: in_dim (int): Input dimension (must equal out_dim if use_residual). out_dim (int): Output dimension after second linear layer. hidden_dim (int): Hidden dimension for intermediate layer. out_dim1 (int): Final output dimension. use_residual (bool): Whether to use residual connection (default: True). """
def __init__(self, in_dim, out_dim, hidden_dim, out_dim1, use_residual=True): super().__init__() if use_residual: assert in_dim == out_dim self.layernorm = nn.LayerNorm(in_dim) self.fc1 = nn.Linear(in_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, out_dim) self.fc3 = nn.Linear(out_dim, out_dim1) self.use_residual = use_residual self.act_fn = nn.GELU()
def forward(self, x): """ Forward pass for ByT5Mapper.
Args: x (Tensor): Input tensor of shape (..., in_dim).
Returns: Tensor: Output tensor of shape (..., out_dim1). """ residual = x x = self.layernorm(x) x = self.fc1(x) x = self.act_fn(x) x = self.fc2(x) x2 = self.act_fn(x) x2 = self.fc3(x2) if self.use_residual: x2 = x2 + residual return x21234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import json
def closest_color(requested_color): import webcolors
min_colors = {} for key, name in webcolors.CSS3_HEX_TO_NAMES.items():
r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_color[0]) ** 2 gd = (g_c - requested_color[1]) ** 2 bd = (b_c - requested_color[2]) ** 2 min_colors[(rd + gd + bd)] = name return min_colors[min(min_colors.keys())]
def convert_rgb_to_names(rgb_tuple): try: import webcolors
color_name = webcolors.rgb_to_name(rgb_tuple) except ValueError: color_name = closest_color(rgb_tuple) return color_name
class MultilingualPromptFormat:
def __init__( self, font_path: str = 'assets/glyph_sdxl_assets/multilingual_10-lang_idx.json', color_path: str = 'assets/glyph_sdxl_assets/color_idx.json', ): with open(font_path, 'r') as f: self.font_dict = json.load(f) with open(color_path, 'r') as f: self.color_dict = json.load(f)
def format_prompt(self, texts, styles): ''' Text "{text}" in {color}, {type}. '''
prompt = "" for text, style in zip(texts, styles): text_prompt = f'Text "{text}"'
attr_list = []
# format color if style["color"] is not None: import webcolors
hex_color = style["color"] rgb_color = webcolors.hex_to_rgb(hex_color) color_name = convert_rgb_to_names(rgb_color) attr_list.append(f"<color-{self.color_dict[color_name]}>")
# format font if style["font-family"] is not None: attr_list.append(f"<{style['font-family'][:2]}-font-{self.font_dict[style['font-family']]}>") attr_suffix = ", ".join(attr_list) text_prompt += " in " + attr_suffix text_prompt += ". " else: text_prompt += ". "
prompt = prompt + text_prompt return prompt1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015# Modified by the UniVEdit authors from Tencent-Hunyuan/OmniWeaving (HunyuanVideo-1.5).# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import osfrom typing import Any, List, Tuple, Optional, Union, Dict
import torchimport torch.nn as nnfrom einops import rearrangefrom loguru import logger
from diffusers.models import ModelMixinfrom diffusers.configuration_utils import ConfigMixin, register_to_config
from hyvideo.commons import maybe_fallback_attn_mode
from .modules.activation_layers import get_activation_layerfrom .modules.norm_layers import get_norm_layerfrom .modules.embed_layers import TimestepEmbedder, PatchEmbed, TextProjection, VisionProjectionfrom .modules.attention import parallel_attentionfrom .modules.posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embedfrom .modules.mlp_layers import MLP, MLPEmbedder, FinalLayer, LinearWarpforSinglefrom .modules.modulate_layers import ModulateDiT, modulate, apply_gatefrom .modules.token_refiner import SingleTokenRefiner
from hyvideo.utils.communications import all_gatherfrom hyvideo.models.text_encoders.byT5 import ByT5Mapperfrom hyvideo.commons.parallel_states import get_parallel_statefrom diffusers.loaders.peft import PeftAdapterMixin
class MMDoubleStreamBlock(nn.Module):
def __init__( self, hidden_size: int, heads_num: int, mlp_width_ratio: float, mlp_act_type: str = "gelu_tanh", attn_mode: str = None, qk_norm: bool = True, qk_norm_type: str = "rms", qkv_bias: bool = False, dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, ): factory_kwargs = {"device": device, "dtype": dtype} super().__init__()
self.deterministic = False self.heads_num = heads_num self.attn_mode = attn_mode
head_dim = hidden_size // heads_num mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
self.img_mod = ModulateDiT( hidden_size, factor=6, act_layer=get_activation_layer("silu"), **factory_kwargs ) self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs) self.img_attn_q = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs) self.img_attn_k = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs) self.img_attn_v = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs)
qk_norm_layer = get_norm_layer(qk_norm_type) self.img_attn_q_norm = ( qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() ) self.img_attn_k_norm = ( qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() ) self.img_attn_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs)
self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs) self.img_mlp = MLP(hidden_size, mlp_hidden_dim, act_layer=get_activation_layer(mlp_act_type), bias=True, **factory_kwargs)
self.txt_mod = ModulateDiT( hidden_size, factor=6, act_layer=get_activation_layer("silu"), **factory_kwargs ) self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs)
self.txt_attn_q = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs) self.txt_attn_k = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs) self.txt_attn_v = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs)
self.txt_attn_q_norm = ( qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() ) self.txt_attn_k_norm = ( qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() ) self.txt_attn_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs) self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs) self.txt_mlp = MLP(hidden_size, mlp_hidden_dim, act_layer=get_activation_layer(mlp_act_type), bias=True, **factory_kwargs)
self.hybrid_seq_parallel_attn = None
def enable_deterministic(self): self.deterministic = True
def disable_deterministic(self): self.deterministic = False
def forward( self, img: torch.Tensor, txt: torch.Tensor, vec: torch.Tensor, freqs_cis: tuple = None, text_mask=None, attn_param=None, is_flash=False, block_idx=None, ) -> Tuple[torch.Tensor, torch.Tensor]: ( img_mod1_shift, img_mod1_scale, img_mod1_gate, img_mod2_shift, img_mod2_scale, img_mod2_gate, ) = self.img_mod(vec).chunk(6, dim=-1)
( txt_mod1_shift, txt_mod1_scale, txt_mod1_gate, txt_mod2_shift, txt_mod2_scale, txt_mod2_gate, ) = self.txt_mod(vec).chunk(6, dim=-1)
img_modulated = self.img_norm1(img) img_modulated = modulate(img_modulated, shift=img_mod1_shift, scale=img_mod1_scale)
img_q = self.img_attn_q(img_modulated) img_k = self.img_attn_k(img_modulated) img_v = self.img_attn_v(img_modulated) img_q = rearrange(img_q, "B L (H D) -> B L H D", H=self.heads_num) img_k = rearrange(img_k, "B L (H D) -> B L H D", H=self.heads_num) img_v = rearrange(img_v, "B L (H D) -> B L H D", H=self.heads_num) img_q = self.img_attn_q_norm(img_q).to(img_v) img_k = self.img_attn_k_norm(img_k).to(img_v)
if freqs_cis is not None: img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False) assert ( img_qq.shape == img_q.shape and img_kk.shape == img_k.shape ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}" img_q, img_k = img_qq, img_kk
txt_modulated = self.txt_norm1(txt) txt_modulated = modulate(txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale) txt_q = self.txt_attn_q(txt_modulated) txt_k = self.txt_attn_k(txt_modulated) txt_v = self.txt_attn_v(txt_modulated) txt_q = rearrange(txt_q, "B L (H D) -> B L H D", H=self.heads_num) txt_k = rearrange(txt_k, "B L (H D) -> B L H D", H=self.heads_num) txt_v = rearrange(txt_v, "B L (H D) -> B L H D", H=self.heads_num) txt_q = self.txt_attn_q_norm(txt_q).to(txt_v) txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
attn_mode = 'flash' if is_flash else self.attn_mode attn = parallel_attention( (img_q, txt_q), (img_k, txt_k), (img_v, txt_v), img_q_len=img_q.shape[1], img_kv_len=img_k.shape[1], text_mask=text_mask, attn_mode=attn_mode, attn_param=attn_param, block_idx=block_idx, )
img_attn, txt_attn = attn[:, :img_q.shape[1]].contiguous(), attn[:, img_q.shape[1]:].contiguous()
img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate) img = img + apply_gate( self.img_mlp( modulate(self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale) ), gate=img_mod2_gate, )
txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate) txt = txt + apply_gate( self.txt_mlp(modulate(self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale)), gate=txt_mod2_gate, )
return img, txt
class MMSingleStreamBlock(nn.Module):
def __init__( self, hidden_size: int, heads_num: int, mlp_width_ratio: float = 4.0, mlp_act_type: str = "gelu_tanh", attn_mode: str = None, qk_norm: bool = True, qk_norm_type: str = "rms", qk_scale: float = None, dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, ): factory_kwargs = {"device": device, "dtype": dtype} super().__init__()
self.deterministic = False self.attn_mode = attn_mode
self.hidden_size = hidden_size self.heads_num = heads_num head_dim = hidden_size // heads_num mlp_hidden_dim = int(hidden_size * mlp_width_ratio) self.mlp_hidden_dim = mlp_hidden_dim self.scale = qk_scale or head_dim ** -0.5
self.linear1_q = nn.Linear(hidden_size, hidden_size, **factory_kwargs) self.linear1_k = nn.Linear(hidden_size, hidden_size, **factory_kwargs) self.linear1_v = nn.Linear(hidden_size, hidden_size, **factory_kwargs) self.linear1_mlp = nn.Linear(hidden_size, mlp_hidden_dim, **factory_kwargs) self.linear2 = LinearWarpforSingle(hidden_size + mlp_hidden_dim, hidden_size, bias=True, **factory_kwargs) self.mlp_act = get_activation_layer(mlp_act_type)()
qk_norm_layer = get_norm_layer(qk_norm_type) self.q_norm = ( qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() ) self.k_norm = ( qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() )
self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs) self.modulation = ModulateDiT(hidden_size, factor=3, act_layer=get_activation_layer("silu"), **factory_kwargs) self.hybrid_seq_parallel_attn = None
def enable_deterministic(self): self.deterministic = True
def disable_deterministic(self): self.deterministic = False
def forward( self, x: torch.Tensor, vec: torch.Tensor, txt_len: int, freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None, text_mask=None, attn_param=None, is_flash=False, ) -> torch.Tensor: """Forward pass for the single stream block.""" mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1) x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
q = self.linear1_q(x_mod) k = self.linear1_k(x_mod) v = self.linear1_v(x_mod)
q = rearrange(q, "B L (H D) -> B L H D", H=self.heads_num) k = rearrange(k, "B L (H D) -> B L H D", H=self.heads_num) v = rearrange(v, "B L (H D) -> B L H D", H=self.heads_num) mlp = self.linear1_mlp(x_mod)
# Apply QK-Norm if needed. q = self.q_norm(q).to(v) k = self.k_norm(k).to(v)
img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :] img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :] img_v, txt_v = v[:, :-txt_len, :, :], v[:, -txt_len:, :, :] img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False) assert ( img_qq.shape == img_q.shape and img_kk.shape == img_k.shape ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}" img_q, img_k = img_qq, img_kk
if is_flash: attn_mode = 'flash' else: attn_mode = self.attn_mode attn = parallel_attention( (img_q, txt_q), (img_k, txt_k), (img_v, txt_v), img_q_len=img_q.shape[1], img_kv_len=img_k.shape[1], text_mask=text_mask, attn_mode=attn_mode, attn_param=attn_param, ) output = self.linear2(attn, self.mlp_act(mlp)) return x + apply_gate(output, gate=mod_gate)
class HunyuanVideo_1_5_DiffusionTransformer(ModelMixin, ConfigMixin, PeftAdapterMixin): """ HunyuanVideo Transformer backbone.
Args: patch_size (list): The size of the patch. in_channels (int): The number of input channels. out_channels (int): The number of output channels. hidden_size (int): The hidden size of the transformer backbone. heads_num (int): The number of attention heads. mlp_width_ratio (float): Width ratio for the transformer MLPs. mlp_act_type (str): Activation type for the transformer MLPs. mm_double_blocks_depth (int): Number of double-stream transformer blocks. mm_single_blocks_depth (int): Number of single-stream transformer blocks. rope_dim_list (list): Rotary embedding dim for t, h, w. qkv_bias (bool): Use bias in qkv projection. qk_norm (bool): Whether to use qk norm. qk_norm_type (str): Type of qk norm. guidance_embed (bool): Use guidance embedding for distillation. text_projection (str): Text input projection. Default is "single_refiner". use_attention_mask (bool): If to use attention mask. text_states_dim (int): Text encoder output dim. text_states_dim_2 (int): Secondary text encoder output dim. text_pool_type (str): Type for text pooling. rope_theta (int): Rotary embedding theta parameter. attn_mode (str): Attention mode identifier. attn_param (dict): Attention parameter dictionary. glyph_byT5_v2 (bool): Use ByT5 glyph module. vision_projection (str): Vision condition embedding mode. vision_states_dim (int): Vision encoder states input dim. is_reshape_temporal_channels (bool): For video VAE adaptation. use_cond_type_embedding (bool): Use condition type embedding. """
@register_to_config def __init__( self, patch_size: list = [1, 2, 2], in_channels: int = 4, concat_condition: bool = True, out_channels: int = None, hidden_size: int = 3072, heads_num: int = 24, mlp_width_ratio: float = 4.0, mlp_act_type: str = "gelu_tanh", mm_double_blocks_depth: int = 20, mm_single_blocks_depth: int = 40, rope_dim_list: list = [16, 56, 56], qkv_bias: bool = True, qk_norm: bool = True, qk_norm_type: str = "rms", guidance_embed: bool = False, use_meanflow: bool = False, text_projection: str = "single_refiner", use_attention_mask: bool = True, text_states_dim: int = 4096, text_states_dim_2: int = 768, text_pool_type: str = None, rope_theta: int = 256, attn_mode: str = "flash", attn_param: dict = None, glyph_byT5_v2: bool = False, vision_projection: str = "none", vision_states_dim: int = 1280, is_reshape_temporal_channels: bool = False, use_cond_type_embedding: bool = False, ideal_resolution: str = None, ideal_task: str = None, deepstack=None, only_give_text=True, ): super().__init__() factory_kwargs = {}
self.patch_size = patch_size self.in_channels = in_channels self.out_channels = in_channels if out_channels is None else out_channels self.unpatchify_channels = self.out_channels self.guidance_embed = guidance_embed self.rope_dim_list = rope_dim_list self.rope_theta = rope_theta # Text projection. Default to linear projection. # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831 self.use_attention_mask = use_attention_mask self.text_projection = text_projection self.attn_mode = attn_mode self.text_pool_type = text_pool_type self.text_states_dim = text_states_dim self.text_states_dim_2 = text_states_dim_2 self.vision_states_dim = vision_states_dim
self.glyph_byT5_v2 = glyph_byT5_v2 if self.glyph_byT5_v2: self.byt5_in = ByT5Mapper( in_dim=1472, out_dim=2048, hidden_dim=2048, out_dim1=hidden_size, use_residual=False )
if hidden_size % heads_num != 0: raise ValueError( f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}" ) pe_dim = hidden_size // heads_num if sum(rope_dim_list) != pe_dim: raise ValueError( f"Got {rope_dim_list} but expected positional dim {pe_dim}" ) self.hidden_size = hidden_size self.heads_num = heads_num
self.img_in = PatchEmbed( self.patch_size, self.in_channels, self.hidden_size, is_reshape_temporal_channels=is_reshape_temporal_channels, concat_condition=concat_condition, **factory_kwargs )
# Vision projection if vision_projection == "linear": self.vision_in = VisionProjection( input_dim=self.vision_states_dim, output_dim=self.hidden_size ) else: self.vision_in = None
# Text projection if self.text_projection == "linear": self.txt_in = TextProjection( text_states_dim, self.hidden_size, get_activation_layer("silu"), **factory_kwargs, ) elif self.text_projection == "single_refiner": self.txt_in = SingleTokenRefiner( text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs, ) else: raise NotImplementedError( f"Unsupported text_projection: {self.text_projection}" )
# time modulation self.time_in = TimestepEmbedder( self.hidden_size, get_activation_layer("silu"), **factory_kwargs ) self.vector_in = ( MLPEmbedder( self.config.text_states_dim_2, self.hidden_size, **factory_kwargs ) if self.text_pool_type is not None else None ) self.guidance_in = ( TimestepEmbedder( self.hidden_size, get_activation_layer("silu"), **factory_kwargs ) if guidance_embed else None )
self.time_r_in = ( TimestepEmbedder(self.hidden_size, get_activation_layer("silu"), **factory_kwargs) if use_meanflow else None )
self.double_blocks = nn.ModuleList( [ MMDoubleStreamBlock( self.hidden_size, self.heads_num, mlp_width_ratio=mlp_width_ratio, mlp_act_type=mlp_act_type, attn_mode=attn_mode, qk_norm=qk_norm, qk_norm_type=qk_norm_type, qkv_bias=qkv_bias, **factory_kwargs, ) for _ in range(mm_double_blocks_depth) ] )
self.single_blocks = nn.ModuleList( [ MMSingleStreamBlock( self.hidden_size, self.heads_num, mlp_width_ratio=mlp_width_ratio, mlp_act_type=mlp_act_type, attn_mode=attn_mode, qk_norm=qk_norm, qk_norm_type=qk_norm_type, **factory_kwargs, ) for _ in range(mm_single_blocks_depth) ] )
self.final_layer = FinalLayer( self.hidden_size, self.patch_size, self.out_channels, get_activation_layer("silu"), **factory_kwargs, )
# STA if attn_param is None: self.attn_param = { # STA 'win_size': [[3, 3, 3]], 'win_type': "fixed", 'win_ratio': 10, 'tile_size': [6, 8, 8], # SSTA 'ssta_topk': 64, 'ssta_threshold': 0.0, 'ssta_lambda': 0.7, 'ssta_sampling_type': 'importance', 'ssta_adaptive_pool': None, # flex-block-attn: "attn_sparse_type": 'ssta', "attn_pad_type": 'zero', "attn_use_text_mask": 1, "attn_mask_share_within_head": 0, } else: self.attn_param = attn_param
if attn_mode == 'flex-block-attn': self.register_to_config(attn_param=self.attn_param)
if use_cond_type_embedding: self.cond_type_embedding = nn.Embedding(3, self.hidden_size) self.cond_type_embedding.weight.data.fill_(0) assert self.glyph_byT5_v2, "text type embedding is only used when glyph_byT5_v2 is True" assert vision_projection is not None, "text type embedding is only used when vision_projection is not None" # 0: text_encoder feature # 1: byt5 feature # 2: vision_encoder feature else: self.cond_type_embedding = None self.freeze_main = True self.deep_stack = deepstack if self.deep_stack is None: self.deep_stack = [] self.deep_stack = list(self.deep_stack) if len(self.deep_stack) > 0: self.mm_in = TextProjection( text_states_dim, self.hidden_size, get_activation_layer("silu"), **factory_kwargs, ) for n, p in self.mm_in.named_parameters(): p.requires_grad = True
def load_hunyuan_state_dict(self, model_path): load_key = "module" bare_model = "unknown"
if model_path.endswith('.safetensors'): from safetensors.torch import load_file state_dict = load_file(model_path, device="cpu") else: state_dict = torch.load( model_path, map_location="cpu", weights_only=True )
if bare_model == "unknown" and ("ema" in state_dict or "module" in state_dict): bare_model = False if bare_model is False: if load_key in state_dict: state_dict = state_dict[load_key] else: raise KeyError( f"Missing key: `{load_key}` in the checkpoint: {model_path}. The keys in the checkpoint " f"are: {list(state_dict.keys())}." )
result = self.load_state_dict(state_dict, strict=False)
if result.missing_keys: logger.info("[load.py] Missing keys when loading state_dict:") for key in result.missing_keys: logger.info(f"[load.py] Missing key: {key}") if result.unexpected_keys: logger.info("[load.py] Unexpected keys when loading state_dict:") for key in result.unexpected_keys: logger.info(f"[load.py] Unexpected key: {key}") if result.missing_keys or result.unexpected_keys: raise ValueError(f"Missing: {result.missing_keys}, Unexpected: {result.unexpected_keys}")
return result
def enable_deterministic(self): for block in self.double_blocks: block.enable_deterministic() for block in self.single_blocks: block.enable_deterministic()
def disable_deterministic(self): for block in self.double_blocks: block.disable_deterministic() for block in self.single_blocks: block.disable_deterministic()
def get_rotary_pos_embed(self, rope_sizes): target_ndim = 3 head_dim = self.hidden_size // self.heads_num rope_dim_list = self.rope_dim_list if rope_dim_list is None: rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)] assert ( sum(rope_dim_list) == head_dim ), "sum(rope_dim_list) should equal to head_dim of attention layer" freqs_cos, freqs_sin = get_nd_rotary_pos_embed( tuple(rope_dim_list), rope_sizes, theta=self.rope_theta, use_real=True, theta_rescale_factor=1, ) return freqs_cos, freqs_sin
def reorder_txt_token(self, byt5_txt, txt, byt5_text_mask, text_mask, zero_feat=False, is_reorder=True): if is_reorder: reorder_txt = [] reorder_mask = [] for i in range(text_mask.shape[0]): byt5_text_mask_i = byt5_text_mask[i].bool() text_mask_i = text_mask[i].bool()
byt5_txt_i = byt5_txt[i] txt_i = txt[i] if zero_feat: # When using block mask with approximate computation, set pad to zero to reduce error pad_byt5 = torch.zeros_like(byt5_txt_i[~byt5_text_mask_i]) pad_text = torch.zeros_like(txt_i[~text_mask_i]) reorder_txt_i = torch.cat( [byt5_txt_i[byt5_text_mask_i], txt_i[text_mask_i], pad_byt5, pad_text], dim=0 ) else: reorder_txt_i = torch.cat( [byt5_txt_i[byt5_text_mask_i], txt_i[text_mask_i], byt5_txt_i[~byt5_text_mask_i], txt_i[~text_mask_i]], dim=0 ) reorder_mask_i = torch.cat( [byt5_text_mask_i[byt5_text_mask_i], text_mask_i[text_mask_i], byt5_text_mask_i[~byt5_text_mask_i], text_mask_i[~text_mask_i]], dim=0 )
reorder_txt.append(reorder_txt_i) reorder_mask.append(reorder_mask_i)
reorder_txt = torch.stack(reorder_txt) reorder_mask = torch.stack(reorder_mask).to(dtype=torch.int64) else: reorder_txt = torch.concat([byt5_txt, txt], dim=1) reorder_mask = torch.concat([byt5_text_mask, text_mask], dim=1).to(dtype=torch.int64)
return reorder_txt, reorder_mask
def forward( self, hidden_states: torch.Tensor, timestep: torch.LongTensor, text_states: torch.Tensor, text_states_2: torch.Tensor, encoder_attention_mask: torch.Tensor, timestep_r=None, vision_states: torch.Tensor = None, output_features=False, output_features_stride=8, attention_kwargs: Optional[Dict[str, Any]] = None, freqs_cos: Optional[torch.Tensor] = None, freqs_sin: Optional[torch.Tensor] = None, return_dict: bool = False, guidance=None, mask_type="t2v", extra_kwargs=None, all_stack_text_states=None, ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
if guidance is None: guidance = torch.tensor( [6016.0], device=hidden_states.device, dtype=torch.bfloat16 )
img = x = hidden_states text_mask = encoder_attention_mask t = timestep txt = text_states bs, _, ot, oh, ow = x.shape tt, th, tw = ( ot // self.patch_size[0], oh // self.patch_size[1], ow // self.patch_size[2], ) self.attn_param['thw'] = [tt, th, tw] if freqs_cos is None and freqs_sin is None: freqs_cos, freqs_sin = self.get_rotary_pos_embed((tt, th, tw))
img = self.img_in(img) parallel_dims = get_parallel_state() sp_enabled = parallel_dims.sp_enabled if sp_enabled: sp_size = parallel_dims.sp sp_rank = parallel_dims.sp_rank if img.shape[1] % sp_size != 0: n_token = img.shape[1] assert n_token > (n_token // sp_size + 1) * (sp_size - 1), f'Too short context length for SP {sp_size}' img = torch.chunk(img, sp_size, dim=1)[sp_rank] freqs_cos = torch.chunk(freqs_cos, sp_size, dim=0)[sp_rank] freqs_sin = torch.chunk(freqs_sin, sp_size, dim=0)[sp_rank]
# Prepare modulation vectors vec = self.time_in(t)
if text_states_2 is not None: vec_2 = self.vector_in(text_states_2) vec = vec + vec_2
if self.guidance_embed: if guidance is None: raise ValueError( "Didn't get guidance strength for guidance distilled model." ) vec = vec + self.guidance_in(guidance)
if timestep_r is not None: vec = vec + self.time_r_in(timestep_r)
# Embed text tokens if self.text_projection == "linear": txt = self.txt_in(txt) elif self.text_projection == "single_refiner": txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None) else: raise NotImplementedError( f"Unsupported text_projection: {self.text_projection}" )
if all_stack_text_states is not None: all_stack_text_states_in = self.mm_in(all_stack_text_states) else: all_stack_text_states_in = None
if self.cond_type_embedding is not None: cond_emb = self.cond_type_embedding( torch.zeros_like(txt[:, :, 0], device=text_mask.device, dtype=torch.long) ) txt = txt + cond_emb
if self.glyph_byT5_v2: byt5_text_states = extra_kwargs["byt5_text_states"] byt5_text_mask = extra_kwargs["byt5_text_mask"] byt5_txt = self.byt5_in(byt5_text_states) if self.cond_type_embedding is not None: cond_emb = self.cond_type_embedding( torch.ones_like(byt5_txt[:, :, 0], device=byt5_txt.device, dtype=torch.long) ) byt5_txt = byt5_txt + cond_emb txt, text_mask = self.reorder_txt_token( byt5_txt, txt, byt5_text_mask, text_mask, zero_feat=True )
if self.vision_in is not None and vision_states is not None: extra_encoder_hidden_states = self.vision_in(vision_states) # If t2v, set extra_attention_mask to 0 to avoid attention to semantic tokens if mask_type == "t2v" and torch.all(vision_states == 0): extra_attention_mask = torch.zeros( (bs, extra_encoder_hidden_states.shape[1]), dtype=text_mask.dtype, device=text_mask.device, ) # Set vision tokens to zero to mitigate potential block mask error in SSTA extra_encoder_hidden_states = extra_encoder_hidden_states * 0.0 else: extra_attention_mask = torch.ones( (bs, extra_encoder_hidden_states.shape[1]), dtype=text_mask.dtype, device=text_mask.device, ) # Ensure valid tokens precede padding tokens if self.cond_type_embedding is not None: cond_emb = self.cond_type_embedding( 2 * torch.ones_like( extra_encoder_hidden_states[:, :, 0], dtype=torch.long, device=extra_encoder_hidden_states.device, ) ) extra_encoder_hidden_states = extra_encoder_hidden_states + cond_emb
txt, text_mask = self.reorder_txt_token( extra_encoder_hidden_states, txt, extra_attention_mask, text_mask )
freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
# Pass through double-stream blocks for index, block in enumerate(self.double_blocks): force_full_attn = ( self.attn_mode in ["flex-block-attn"] and self.attn_param["win_type"] == "hybrid" and self.attn_param["win_ratio"] > 0 and ( (index + 1) % self.attn_param["win_ratio"] == 0 or (index + 1) == len(self.double_blocks) ) ) self.attn_param["layer-name"] = f"double_block_{index+1}" img, txt = block( img=img, txt=txt, vec=vec, freqs_cis=freqs_cis, text_mask=text_mask, attn_param=self.attn_param, is_flash=force_full_attn, block_idx=index, )
if all_stack_text_states_in is not None and index < len(all_stack_text_states_in): if self.freeze_main: n_slice = all_stack_text_states_in[index].shape[-2] n_keep = txt.shape[1] - n_slice
txt_front = txt[:, :n_keep] txt_back = txt[:, -n_slice:]
updated_back = txt_back + all_stack_text_states_in[index].detach()
txt = torch.cat([txt_front, updated_back], dim=1) else: local_this = txt[:, -all_stack_text_states_in[index].shape[-2]:].clone() + all_stack_text_states_in[index] txt[:, -all_stack_text_states_in[index].shape[-2]:] = local_this
txt_seq_len = txt.shape[1] img_seq_len = img.shape[1]
# Merge image and text for single-stream blocks x = torch.cat((img, txt), 1) features_list = [] if output_features else None if len(self.single_blocks) > 0: for index, block in enumerate(self.single_blocks): force_full_attn = ( self.attn_mode in ["flex-block-attn"] and self.attn_param["win_type"] == "hybrid" and self.attn_param["win_ratio"] > 0 and ( (index + 1) % self.attn_param["win_ratio"] == 0 or (index + 1) == len(self.single_blocks) ) ) self.attn_param["layer-name"] = f"single_block_{index+1}" x = block( x=x, vec=vec, txt_len=txt_seq_len, freqs_cis=(freqs_cos, freqs_sin), text_mask=text_mask, attn_param=self.attn_param, is_flash=force_full_attn, ) if output_features and index % output_features_stride == 0: features_list.append(x[:, :img_seq_len, ...]) img = x[:, :img_seq_len, ...]
# Final Layer img = self.final_layer(img, vec) if sp_enabled: img = all_gather(img, dim=1, group=parallel_dims.sp_group) img = self.unpatchify(img, tt, th, tw) assert return_dict is False, "return_dict is not supported." if output_features: features_list = torch.stack(features_list, dim=0) if sp_enabled: features_list = all_gather(features_list, dim=2, group=parallel_dims.sp_group) else: features_list = None return (img, features_list)
def unpatchify(self, x, t, h, w): """ Unpatchify a tensorized input back to frame format.
Args: x (Tensor): Input tensor of shape (N, T, patch_size**2 * C) t (int): Number of time steps h (int): Height in patch units w (int): Width in patch units
Returns: Tensor: Output tensor of shape (N, C, t * pt, h * ph, w * pw) """ c = self.unpatchify_channels pt, ph, pw = self.patch_size assert t * h * w == x.shape[1] x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw)) x = torch.einsum("nthwcopq->nctohpwq", x) imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw)) return imgs
def set_attn_mode(self, attn_mode: str): attn_mode = maybe_fallback_attn_mode(attn_mode) self.attn_mode = attn_mode for block in self.double_blocks: block.attn_mode = attn_mode for block in self.single_blocks: block.attn_mode = attn_mode
def save_lora_adapter( self, save_directory, adapter_name: str = "default", upcast_before_saving: bool = False, safe_serialization: bool = True, weight_name: Optional[str] = None, ): """ Save the LoRA parameters corresponding to the underlying model.
Arguments: save_directory (`str` or `os.PathLike`): Directory to save LoRA parameters to. Will be created if it doesn't exist. adapter_name: (`str`, defaults to "default"): The name of the adapter to serialize. Useful when the underlying model has multiple adapters loaded. upcast_before_saving (`bool`, defaults to `False`): Whether to cast the underlying model to `torch.float32` before serialization. safe_serialization (`bool`, *optional*, defaults to `True`): Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`. weight_name: (`str`, *optional*, defaults to `None`): Name of the file to serialize the state dict with. """ from peft.utils import get_peft_model_state_dict
from diffusers.loaders.lora_base import LORA_WEIGHT_NAME, LORA_WEIGHT_NAME_SAFE try: from diffusers.loaders.lora_base import LORA_ADAPTER_METADATA_KEY except ImportError: LORA_ADAPTER_METADATA_KEY = None from diffusers.utils import get_adapter_name import safetensors import json from pathlib import Path
if adapter_name is None: adapter_name = get_adapter_name(self)
if adapter_name not in getattr(self, "peft_config", {}): raise ValueError(f"Adapter name {adapter_name} not found in the model.")
lora_adapter_metadata = self.peft_config[adapter_name].to_dict()
lora_layers_to_save = get_peft_model_state_dict( self.to(dtype=torch.float32 if upcast_before_saving else None), adapter_name=adapter_name ) if os.path.isfile(save_directory): raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file")
if safe_serialization:
def save_function(weights, filename): # Inject framework format. metadata = {"format": "pt"} if lora_adapter_metadata is not None and LORA_ADAPTER_METADATA_KEY is not None: for key, value in lora_adapter_metadata.items(): if isinstance(value, set): lora_adapter_metadata[key] = list(value) metadata[LORA_ADAPTER_METADATA_KEY] = json.dumps(lora_adapter_metadata, indent=2, sort_keys=True)
return safetensors.torch.save_file(weights, filename, metadata=metadata)
else: save_function = torch.save
os.makedirs(save_directory, exist_ok=True)
if weight_name is None: if safe_serialization: weight_name = LORA_WEIGHT_NAME_SAFE else: weight_name = LORA_WEIGHT_NAME
save_path = Path(save_directory, weight_name).as_posix() lora_layers_to_save = {k:(v.full_tensor() if hasattr(v, 'full_tensor') else v) for k, v in lora_layers_to_save.items()} if os.environ.get('RANK', '0') == '0': save_function(lora_layers_to_save, save_path) logger.info(f"Model weights saved in {save_path}")123456789101112131415161718192021222324252627282930313233343536373839# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import torch.nn as nn
def get_activation_layer(act_type): """get activation layer
Args: act_type (str): the activation type
Returns: torch.nn.functional: the activation layer """ if act_type == "gelu": return lambda: nn.GELU() elif act_type == "gelu_tanh": # Approximate `tanh` requires torch >= 1.13 return lambda: nn.GELU(approximate="tanh") elif act_type == "relu": return nn.ReLU elif act_type == "silu": return nn.SiLU else: raise ValueError(f"Unknown activation type: {act_type}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import einopsimport torchfrom typing import Optionalfrom loguru import loggerimport numpy as npimport torch.nn.functional as F
from hyvideo.commons.parallel_states import get_parallel_statefrom hyvideo.utils.communications import ( all_gather, all_to_all_4D,)from hyvideo.utils.flash_attn_no_pad import ( flash_attn_no_pad, flash_attn_no_pad_v3,)from hyvideo.commons import maybe_fallback_attn_mode
try: from torch.nn.attention.flex_attention import flex_attention
flex_attention = torch.compile(flex_attention, dynamic=False) torch._dynamo.config.cache_size_limit = 192 torch._dynamo.config.accumulated_cache_size_limit = 192 flex_mask_cache = {}except Exception: logger.warning("Could not load Sliding Tile Attention of FlexAttn.")
from hyvideo.models.transformers.modules.ssta_attention import ssta_3d_attention
@torch.compiler.disabledef attention( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, drop_rate: float = 0.0, attn_mask: Optional[torch.Tensor] = None, causal: bool = False, attn_mode: str = "flash",) -> torch.Tensor: """ Compute attention using flash_attn_no_pad or torch scaled_dot_product_attention.
Args: q: Query tensor of shape [B, L, H, D] k: Key tensor of shape [B, L, H, D] v: Value tensor of shape [B, L, H, D] drop_rate: Dropout rate for attention weights. attn_mask: Optional attention mask of shape [B, L]. causal: Whether to apply causal masking. attn_mode: Attention mode, either "flash" or "torch". Defaults to "flash".
Returns: Output tensor after attention of shape [B, L, H*D] """ attn_mode = maybe_fallback_attn_mode(attn_mode)
if attn_mode == "torch": # transpose q,k,v dim to fit scaled_dot_product_attention query = q.transpose(1, 2) # B * H * L * D key = k.transpose(1, 2) # B * H * L * D value = v.transpose(1, 2) # B * H * L * D if attn_mask is not None: if attn_mask.dtype != torch.bool and attn_mask.dtype in [torch.int64, torch.int32]: assert attn_mask.max() <= 1 and attn_mask.min() >= 0, f'Integer attention mask must be between 0 and 1 for torch attention.' attn_mask = attn_mask.to(torch.bool) elif attn_mask.dtype != torch.bool: attn_mask = attn_mask.to(query.dtype) raise NotImplementedError(f'Float attention mask is not implemented for torch attention.') attn_mask1 = einops.rearrange(attn_mask, 'b l -> b 1 l 1') attn_mask2 = einops.rearrange(attn_mask1, 'b 1 l 1 -> b 1 1 l') attn_mask = attn_mask1 & attn_mask2 x = F.scaled_dot_product_attention(query, key, value, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal) # transpose back x = x.transpose(1, 2) # B * L * H * D b, s, h, d = x.shape out = x.reshape(b, s, -1) return out else: # flash mode (default) qkv = torch.stack([q, k, v], dim=2) if attn_mask is not None and attn_mask.dtype != torch.bool: attn_mask = attn_mask.bool() x = flash_attn_no_pad(qkv, attn_mask, causal=causal, dropout_p=drop_rate, softmax_scale=None) b, s, a, d = x.shape out = x.reshape(b, s, -1) return out
@torch.compiler.disabledef parallel_attention(q, k, v, img_q_len, img_kv_len, attn_mode=None, text_mask=None, attn_param=None, block_idx=None, ): return sequence_parallel_attention(q, k, v, img_q_len, img_kv_len, attn_mode, text_mask, attn_param=attn_param, block_idx=block_idx)
def sequence_parallel_attention(q, k, v, img_q_len, img_kv_len, attn_mode=None, text_mask=None, attn_param=None, block_idx=None, ): assert attn_mode is not None query, encoder_query = q key, encoder_key = k value, encoder_value = v
parallel_dims = get_parallel_state() enable_sp = parallel_dims.sp_enabled
if enable_sp: sp_group = parallel_dims.sp_group sp_size = parallel_dims.sp sp_rank = parallel_dims.sp_rank if enable_sp: # batch_size, seq_len, attn_heads, head_dim query = all_to_all_4D(query, sp_group, scatter_dim=2, gather_dim=1) key = all_to_all_4D(key, sp_group, scatter_dim=2, gather_dim=1) value = all_to_all_4D(value, sp_group, scatter_dim=2, gather_dim=1)
def shrink_head(encoder_state, dim): local_heads = encoder_state.shape[dim] // sp_size return encoder_state.narrow( dim, sp_rank * local_heads, local_heads )
encoder_query = shrink_head(encoder_query, dim=2) encoder_key = shrink_head(encoder_key, dim=2) encoder_value = shrink_head(encoder_value, dim=2)
sequence_length = query.size(1) encoder_sequence_length = encoder_query.size(1)
attn_mode = maybe_fallback_attn_mode(attn_mode) if attn_mode == "sageattn": from sageattention import sageattn query = torch.cat([query, encoder_query], dim=1) key = torch.cat([key, encoder_key], dim=1) value = torch.cat([value, encoder_value], dim=1) hidden_states = sageattn(query, key, value, tensor_layout="NHD", is_causal=False) elif attn_mode == "torch": query = torch.cat([query, encoder_query], dim=1) key = torch.cat([key, encoder_key], dim=1) value = torch.cat([value, encoder_value], dim=1) if text_mask is not None: attn_mask = F.pad(text_mask, (sequence_length, 0), value=True) else: attn_mask = None
if attn_mask is not None: if attn_mask.dtype != torch.bool and attn_mask.dtype in [torch.int64, torch.int32]: assert attn_mask.max() <= 1 and attn_mask.min() >= 0, f'Integer attention mask must be between 0 and 1 for torch attention.' attn_mask = attn_mask.to(torch.bool) elif attn_mask.dtype != torch.bool: attn_mask = attn_mask.to(query.dtype) raise NotImplementedError(f'Float attention mask is not implemented for torch attention.') # transpose q,k,v dim to fit scaled_dot_product_attention query = query.transpose(1, 2) # B * Head_num * length * dim key = key.transpose(1, 2) # B * Head_num * length * dim value = value.transpose(1, 2) # B * Head_num * length * dim
def score_mod(score, b, h, q_idx, kv_idx): return torch.where(attn_mask[b, q_idx] & attn_mask[b, kv_idx], score, float('-inf'))
hidden_states = flex_attention(query, key, value, score_mod=score_mod) # transpose back hidden_states = hidden_states.transpose(1, 2) elif attn_mode == "flash2": query = torch.cat([query, encoder_query], dim=1) key = torch.cat([key, encoder_key], dim=1) value = torch.cat([value, encoder_value], dim=1) # B, S, 3, H, D qkv = torch.stack([query, key, value], dim=2)
attn_mask = F.pad(text_mask, (sequence_length, 0), value=True) hidden_states = flash_attn_no_pad(qkv, attn_mask, causal=False, dropout_p=0.0, softmax_scale=None) elif attn_mode == "flash3": query = torch.cat([query, encoder_query], dim=1) key = torch.cat([key, encoder_key], dim=1) value = torch.cat([value, encoder_value], dim=1) # B, S, 3, H, D qkv = torch.stack([query, key, value], dim=2) attn_mask = F.pad(text_mask, (sequence_length, 0), value=True) hidden_states = flash_attn_no_pad_v3(qkv, attn_mask, causal=False, dropout_p=0.0, softmax_scale=None)
elif attn_mode == "flex-block-attn": sparse_type = attn_param["attn_sparse_type"] # sta/block_attn/ssta ssta_threshold = attn_param["ssta_threshold"] ssta_lambda = attn_param["ssta_lambda"] ssta_sampling_type = attn_param["ssta_sampling_type"] ssta_adaptive_pool = attn_param["ssta_adaptive_pool"]
attn_pad_type = attn_param["attn_pad_type"] # repeat/zero attn_use_text_mask = attn_param["attn_use_text_mask"] attn_mask_share_within_head = attn_param["attn_mask_share_within_head"]
ssta_topk = attn_param["ssta_topk"] thw = attn_param["thw"] tile_size = attn_param["tile_size"] win_size = attn_param["win_size"][0].copy()
def get_image_tile(tile_size): block_size = np.prod(tile_size) if block_size == 384: tile_size = (1, 16, 24) elif block_size == 128: tile_size = (1, 16, 8) elif block_size == 64: tile_size = (1, 8, 8) elif block_size == 16: tile_size = (1, 4, 4) else: raise ValueError(f"Error tile_size {tile_size}, only support in [16, 64, 128, 384]") return tile_size
if thw[0] == 1: tile_size = get_image_tile(tile_size) win_size = [1, 1, 1] elif thw[0] <= 31: # 16fps: 5 * 16 / 4 + 1 = 21; 24fps: 5 * 24 / 4 + 1 = 31 ssta_topk = ssta_topk // 2
# Concatenate and permute query, key, value to (B, H, S, D) query = torch.cat([query, encoder_query], dim=1).permute(0, 2, 1, 3) key = torch.cat([key, encoder_key], dim=1).permute(0, 2, 1, 3) value = torch.cat([value, encoder_value], dim=1).permute(0, 2, 1, 3)
assert ( query.shape[-1] == 128 ), "The last dimension of query, key and value must be 128 for flex-block-attn."
hidden_states = ssta_3d_attention( query, key, value, thw, topk=ssta_topk, tile_thw=tile_size, kernel_thw=win_size, text_len=encoder_sequence_length, sparse_type=sparse_type, threshold=ssta_threshold, lambda_=ssta_lambda, pad_type=attn_pad_type, text_mask=text_mask if attn_use_text_mask else None, sampling_type=ssta_sampling_type, adaptive_pool=ssta_adaptive_pool, mask_share_within_head=attn_mask_share_within_head, ) hidden_states, sparse_ratio = hidden_states hidden_states = hidden_states.permute(0, 2, 1, 3)
else: raise NotImplementedError( f'Unsupported attention mode: {attn_mode}. Only torch, flash, flash3, sageattn and flex-block-attn are supported.' )
if enable_sp: hidden_states, encoder_hidden_states = hidden_states.split_with_sizes((sequence_length, encoder_sequence_length), dim=1) hidden_states = all_to_all_4D(hidden_states, sp_group, scatter_dim=1, gather_dim=2) encoder_hidden_states = all_gather(encoder_hidden_states, dim=2, group=sp_group).contiguous() hidden_states = hidden_states.to(query.dtype) encoder_hidden_states = encoder_hidden_states.to(query.dtype) hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)
b, s, a, d = hidden_states.shape hidden_states = hidden_states.reshape(b, s, -1)
return hidden_states123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import mathimport torchimport torch.nn as nn
from hyvideo.commons import to_2tuple
class PatchEmbed(nn.Module): """2D Image to Patch Embedding
Image to Patch Embedding using Conv2d
A convolution based approach to patchifying a 2D image w/ embedding projection.
Based on the impl in https://github.com/google-research/vision_transformer
Hacked together by / Copyright 2020 Ross Wightman
Remove the _assert function in forward function to be compatible with multi-resolution images. """
def __init__( self, patch_size=16, in_chans=3, embed_dim=768, is_reshape_temporal_channels=False, concat_condition=True, norm_layer=None, flatten=True, bias=True, dtype=None, device=None, ): factory_kwargs = {"dtype": dtype, "device": device} super().__init__() patch_size = to_2tuple(patch_size) self.patch_size = patch_size self.flatten = flatten
# Only support concat mode (multitask mask training) orig_in_chans = in_chans if concat_condition: if is_reshape_temporal_channels: in_chans = in_chans + in_chans//2 + 1 else: in_chans = in_chans * 2 + 1
self.proj = nn.Conv3d( in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias, **factory_kwargs, )
nn.init.xavier_uniform_(self.proj.weight[:, :orig_in_chans].view(self.proj.weight[:, :orig_in_chans].size(0), -1)) # Special initialization for concat mode nn.init.zeros_(self.proj.weight[:, orig_in_chans:].view(self.proj.weight[:, orig_in_chans:].size(0), -1))
if bias: nn.init.zeros_(self.proj.bias)
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x): x = self.proj(x) if self.flatten: x = x.flatten(2).transpose(1, 2) # BCHW -> BNC x = self.norm(x) return x
class TextProjection(nn.Module): """ Projects text embeddings. Also handles dropout for classifier-free guidance.
Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py """
def __init__(self, in_channels, hidden_size, act_layer, dtype=None, device=None): factory_kwargs = {"dtype": dtype, "device": device} super().__init__() self.linear_1 = nn.Linear( in_features=in_channels, out_features=hidden_size, bias=True, **factory_kwargs ) self.act_1 = act_layer() self.linear_2 = nn.Linear( in_features=hidden_size, out_features=hidden_size, bias=True, **factory_kwargs )
def forward(self, caption): hidden_states = self.linear_1(caption) hidden_states = self.act_1(hidden_states) hidden_states = self.linear_2(hidden_states) return hidden_states
class VisionProjection(torch.nn.Module):
def __init__(self, input_dim, output_dim): super().__init__()
self.proj = torch.nn.Sequential( torch.nn.LayerNorm(input_dim), torch.nn.Linear(input_dim, input_dim), torch.nn.GELU(), torch.nn.Linear(input_dim, output_dim), torch.nn.LayerNorm(output_dim) )
def forward(self, vision_embeds): return self.proj(vision_embeds)
class ClipVisionProjection(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.up = nn.Linear(in_channels, out_channels * 3) self.down = nn.Linear(out_channels * 3, out_channels) torch.nn.init.zeros_(self.down.weight) torch.nn.init.zeros_(self.down.bias)
def forward(self, x): projected_x = self.down(nn.functional.silu(self.up(x))) return projected_x def timestep_embedding(t, dim, max_period=10000): """ Create sinusoidal timestep embeddings.
Args: t (torch.Tensor): a 1-D Tensor of N indices, one per batch element. These may be fractional. dim (int): the dimension of the output. max_period (int): controls the minimum frequency of the embeddings.
Returns: embedding (torch.Tensor): An (N, D) Tensor of positional embeddings.
.. ref_link: https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py """ half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=t.device) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
class TimestepEmbedder(nn.Module): """ Embeds scalar timesteps into vector representations. """
def __init__( self, hidden_size, act_layer, frequency_embedding_size=256, max_period=10000, out_size=None, dtype=None, device=None, ): factory_kwargs = {"dtype": dtype, "device": device} super().__init__() self.frequency_embedding_size = frequency_embedding_size self.max_period = max_period if out_size is None: out_size = hidden_size
self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True, **factory_kwargs), act_layer(), nn.Linear(hidden_size, out_size, bias=True, **factory_kwargs), ) nn.init.normal_(self.mlp[0].weight, std=0.02) nn.init.normal_(self.mlp[2].weight, std=0.02)
def forward(self, t): t_freq = timestep_embedding( t, self.frequency_embedding_size, self.max_period ).type(self.mlp[0].weight.dtype) t_emb = self.mlp(t_freq) return t_emb123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
# Modified from timm library:# https://github.com/huggingface/pytorch-image-models/blob/648aaa41233ba83eb38faf5ba9d415d574823241/timm/layers/mlp.py#L13
from functools import partial
import torchimport torch.nn as nn
from hyvideo.commons import to_2tuplefrom .modulate_layers import modulate
class MLP(nn.Module): """MLP as used in Vision Transformer, MLP-Mixer and related networks"""
def __init__( self, in_channels, hidden_channels=None, out_features=None, act_layer=nn.GELU, norm_layer=None, bias=True, drop=0.0, use_conv=False, device=None, dtype=None, ): factory_kwargs = {"device": device, "dtype": dtype} super().__init__() out_features = out_features or in_channels hidden_channels = hidden_channels or in_channels bias = to_2tuple(bias) drop_probs = to_2tuple(drop) linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear
self.fc1 = linear_layer(in_channels, hidden_channels, bias=bias[0], **factory_kwargs) self.act = act_layer() self.drop1 = nn.Dropout(drop_probs[0]) self.norm = norm_layer(hidden_channels, **factory_kwargs) if norm_layer is not None else nn.Identity() self.fc2 = linear_layer(hidden_channels, out_features, bias=bias[1], **factory_kwargs) self.drop2 = nn.Dropout(drop_probs[1])
def forward(self, x): x = self.fc1(x) x = self.act(x) x = self.drop1(x) x = self.norm(x) x = self.fc2(x) x = self.drop2(x) return x
class LinearWarpforSingle(nn.Module): def __init__(self, in_dim: int, out_dim: int, bias=False, device=None, dtype=None): factory_kwargs = {"device": device, "dtype": dtype} super().__init__() self.fc = nn.Linear(in_dim, out_dim, bias=bias, **factory_kwargs)
def forward(self, x, y): input = torch.cat([x.contiguous(), y.contiguous()], dim=2).contiguous() return self.fc(input)
#class MLPEmbedder(nn.Module): """copied from https://github.com/black-forest-labs/flux/blob/main/src/flux/modules/layers.py"""
def __init__(self, in_dim: int, hidden_dim: int, device=None, dtype=None): factory_kwargs = {"device": device, "dtype": dtype} super().__init__() self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True, **factory_kwargs) self.silu = nn.SiLU() self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True, **factory_kwargs)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.out_layer(self.silu(self.in_layer(x)))
class FinalLayer(nn.Module): """The final layer of DiT."""
def __init__(self, hidden_size, patch_size, out_channels, act_layer, device=None, dtype=None): factory_kwargs = {"device": device, "dtype": dtype} super().__init__()
# Just use LayerNorm for the final layer self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs) if isinstance(patch_size, int): self.linear = nn.Linear( hidden_size, patch_size * patch_size * out_channels, bias=True, **factory_kwargs, ) else: out_size = ( patch_size[0] * patch_size[1] * patch_size[2] if len(patch_size) == 3 else patch_size[0] * patch_size[1] ) * out_channels self.linear = nn.Linear( hidden_size, out_size, bias=True, ) nn.init.zeros_(self.linear.weight) nn.init.zeros_(self.linear.bias)
# Here we don't distinguish between the modulate types. Just use the simple one. self.adaLN_modulation = nn.Sequential( act_layer(), nn.Linear(hidden_size, 2 * hidden_size, bias=True, **factory_kwargs), ) # Zero-initialize the modulation nn.init.zeros_(self.adaLN_modulation[1].weight) nn.init.zeros_(self.adaLN_modulation[1].bias)
def forward(self, x, c): shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) x = modulate(self.norm_final(x), shift=shift, scale=scale) x = self.linear(x) return x1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
from typing import Callable
import torchimport torch.nn as nn
class ModulateDiT(nn.Module): """Modulation layer for DiT."""
def __init__( self, hidden_size: int, factor: int, act_layer: Callable, dtype=None, device=None, ): factory_kwargs = {"dtype": dtype, "device": device} super().__init__() self.act = act_layer() self.linear = nn.Linear(hidden_size, factor * hidden_size, bias=True, **factory_kwargs) # Zero-initialize the modulation nn.init.zeros_(self.linear.weight) nn.init.zeros_(self.linear.bias)
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.linear(self.act(x))
def modulate(x, shift=None, scale=None): """modulate by shift and scale
Args: x (torch.Tensor): input tensor. shift (torch.Tensor, optional): shift tensor. Defaults to None. scale (torch.Tensor, optional): scale tensor. Defaults to None.
Returns: torch.Tensor: the output tensor after modulate. """ if scale is None and shift is None: return x elif shift is None: return x * (1 + scale.unsqueeze(1)) elif scale is None: return x + shift.unsqueeze(1) else: return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
def apply_gate(x, gate=None, tanh=False): """AI is creating summary for apply_gate
Args: x (torch.Tensor): input tensor. gate (torch.Tensor, optional): gate tensor. Defaults to None. tanh (bool, optional): whether to use tanh function. Defaults to False.
Returns: torch.Tensor: the output tensor after apply gate. """ if gate is None: return x if tanh: return x * gate.unsqueeze(1).tanh() else: return x * gate.unsqueeze(1)
def ckpt_wrapper(module): def ckpt_forward(*inputs): outputs = module(*inputs) return outputs
return ckpt_forward
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import torchimport torch.nn as nn
class RMSNorm(nn.Module): def __init__( self, dim: int, elementwise_affine=True, eps: float = 1e-6, device=None, dtype=None, ): """ Initialize the RMSNorm normalization layer.
Args: dim (int): The dimension of the input tensor. eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
Attributes: eps (float): A small value added to the denominator for numerical stability. weight (nn.Parameter): Learnable scaling parameter.
""" factory_kwargs = {"device": device, "dtype": dtype} super().__init__() self.eps = eps if elementwise_affine: self.weight = nn.Parameter(torch.ones(dim, **factory_kwargs))
def _norm(self, x): """ Apply the RMSNorm normalization to the input tensor.
Args: x (torch.Tensor): The input tensor.
Returns: torch.Tensor: The normalized tensor.
""" return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def reset_parameters(self): if hasattr(self, "weight"): self.weight.fill_(1)
def forward(self, x): """ Forward pass through the RMSNorm layer.
Args: x (torch.Tensor): The input tensor.
Returns: torch.Tensor: The output tensor after applying RMSNorm.
""" output = self._norm(x.float()).type_as(x) if hasattr(self, "weight"): output = output * self.weight return output
def get_norm_layer(norm_layer): """ Get the normalization layer.
Args: norm_layer (str): The type of normalization layer.
Returns: norm_layer (nn.Module): The normalization layer. """ if norm_layer == "layer": return nn.LayerNorm elif norm_layer == "rms": return RMSNorm else: raise NotImplementedError(f"Norm layer {norm_layer} is not implemented")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
from functools import cache
import torchfrom typing import Union, Tuple, List
def _to_tuple(x, dim=2): if isinstance(x, int): return (x,) * dim elif len(x) == dim: return x else: raise ValueError(f"Expected length {dim} or int, but got {x}")
def get_meshgrid_nd(start, *args, dim=2): """ Get n-D meshgrid with start, stop and num.
Args: start (int or tuple): If len(args) == 0, start is num; If len(args) == 1, start is start, args[0] is stop, step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num. For n-dim, start/stop/num should be int or n-tuple. If n-tuple is provided, the meshgrid will be stacked following the dim order in n-tuples. *args: See above. dim (int): Dimension of the meshgrid. Defaults to 2.
Returns: grid (np.ndarray): [dim, ...] """ if len(args) == 0: # start is grid_size num = _to_tuple(start, dim=dim) start = (0,) * dim stop = num elif len(args) == 1: # start is start, args[0] is stop, step is 1 start = _to_tuple(start, dim=dim) stop = _to_tuple(args[0], dim=dim) num = [stop[i] - start[i] for i in range(dim)] elif len(args) == 2: # start is start, args[0] is stop, args[1] is num start = _to_tuple(start, dim=dim) # Left-Top eg: 12,0 stop = _to_tuple(args[0], dim=dim) # Right-Bottom eg: 20,32 num = _to_tuple(args[1], dim=dim) # Target Size eg: 32,124 else: raise ValueError(f"len(args) should be 0, 1 or 2, but got {len(args)}")
# PyTorch implement of np.linspace(start[i], stop[i], num[i], endpoint=False) axis_grid = [] for i in range(dim): a, b, n = start[i], stop[i], num[i] g = torch.linspace(a, b, n + 1, dtype=torch.float32)[:n] axis_grid.append(g) grid = torch.meshgrid(*axis_grid, indexing="ij") # dim x [W, H, D] grid = torch.stack(grid, dim=0) # [dim, W, H, D]
return grid
################################################################################## Rotary Positional Embedding Functions ################################################################################### https://github.com/meta-llama/llama/blob/be327c427cc5e89cc1d3ab3d3fec4484df771245/llama/model.py#L80
def reshape_for_broadcast( freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]], x: torch.Tensor, head_first=False,): """ Reshape frequency tensor for broadcasting it with another tensor.
This function reshapes the frequency tensor to have the same shape as the target tensor 'x' for the purpose of broadcasting the frequency tensor during element-wise operations.
Notes: When using FlashMHAModified, head_first should be False. When using Attention, head_first should be True.
Args: freqs_cis (Union[torch.Tensor, Tuple[torch.Tensor]]): Frequency tensor to be reshaped. x (torch.Tensor): Target tensor for broadcasting compatibility. head_first (bool): head dimension first (except batch dim) or not.
Returns: torch.Tensor: Reshaped frequency tensor.
Raises: AssertionError: If the frequency tensor doesn't match the expected shape. AssertionError: If the target tensor 'x' doesn't have the expected number of dimensions. """ ndim = x.ndim assert 0 <= 1 < ndim
if isinstance(freqs_cis, tuple): # freqs_cis: (cos, sin) in real space if head_first: assert freqs_cis[0].shape == ( x.shape[-2], x.shape[-1], ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}" shape = [ d if i == ndim - 2 or i == ndim - 1 else 1 for i, d in enumerate(x.shape) ] else: assert freqs_cis[0].shape == ( x.shape[1], x.shape[-1], ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}" shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)] return freqs_cis[0].view(*shape), freqs_cis[1].view(*shape) else: # freqs_cis: values in complex space if head_first: assert freqs_cis.shape == ( x.shape[-2], x.shape[-1], ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}" shape = [ d if i == ndim - 2 or i == ndim - 1 else 1 for i, d in enumerate(x.shape) ] else: assert freqs_cis.shape == ( x.shape[1], x.shape[-1], ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}" shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)] return freqs_cis.view(*shape)
def rotate_half(x): x_real, x_imag = ( x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1) ) # [B, S, H, D//2] return torch.stack([-x_imag, x_real], dim=-1).flatten(3)
def apply_rotary_emb( xq: torch.Tensor, xk: torch.Tensor, freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], head_first: bool = False,) -> Tuple[torch.Tensor, torch.Tensor]: """ Apply rotary embeddings to input tensors using the given frequency tensor.
This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are returned as real tensors.
Args: xq (torch.Tensor): Query tensor to apply rotary embeddings. [B, S, H, D] xk (torch.Tensor): Key tensor to apply rotary embeddings. [B, S, H, D] freqs_cis (torch.Tensor or tuple): Precomputed frequency tensor for complex exponential. head_first (bool): head dimension first (except batch dim) or not.
Returns: Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
""" xk_out = None if isinstance(freqs_cis, tuple): cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D] cos, sin = cos.to(xq.device), sin.to(xq.device) # real * cos - imag * sin # imag * cos + real * sin xq_out = (xq.float() * cos + rotate_half(xq.float()) * sin).type_as(xq) xk_out = (xk.float() * cos + rotate_half(xk.float()) * sin).type_as(xk) else: # view_as_complex will pack [..., D/2, 2](real) to [..., D/2](complex) xq_ = torch.view_as_complex( xq.float().reshape(*xq.shape[:-1], -1, 2) ) # [B, S, H, D//2] freqs_cis = reshape_for_broadcast(freqs_cis, xq_, head_first).to( xq.device ) # [S, D//2] --> [1, S, 1, D//2] # (real, imag) * (cos, sin) = (real * cos - imag * sin, imag * cos + real * sin) # view_as_real will expand [..., D/2](complex) to [..., D/2, 2](real) xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3).type_as(xq) xk_ = torch.view_as_complex( xk.float().reshape(*xk.shape[:-1], -1, 2) ) # [B, S, H, D//2] xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3).type_as(xk)
return xq_out, xk_out
@cachedef get_nd_rotary_pos_embed( rope_dim_list, start, *args, theta=10000.0, use_real=False, theta_rescale_factor: Union[float, List[float]] = 1.0, interpolation_factor: Union[float, List[float]] = 1.0,): """ This is a n-d version of precompute_freqs_cis, which is a RoPE for tokens with n-d structure.
Args: rope_dim_list (list of int): Dimension of each rope. len(rope_dim_list) should equal to n. sum(rope_dim_list) should equal to head_dim of attention layer. start (int | tuple of int | list of int): If len(args) == 0, start is num; If len(args) == 1, start is start, args[0] is stop, step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num. *args: See above. theta (float): Scaling factor for frequency computation. Defaults to 10000.0. use_real (bool): If True, return real part and imaginary part separately. Otherwise, return complex numbers. Some libraries such as TensorRT does not support complex64 data type. So it is useful to provide a real part and an imaginary part separately. theta_rescale_factor (float): Rescale factor for theta. Defaults to 1.0.
Returns: pos_embed (torch.Tensor): [HW, D/2] """
grid = get_meshgrid_nd( start, *args, dim=len(rope_dim_list) ) # [3, W, H, D] / [2, W, H]
if isinstance(theta_rescale_factor, int) or isinstance(theta_rescale_factor, float): theta_rescale_factor = [theta_rescale_factor] * len(rope_dim_list) elif isinstance(theta_rescale_factor, list) and len(theta_rescale_factor) == 1: theta_rescale_factor = [theta_rescale_factor[0]] * len(rope_dim_list) assert len(theta_rescale_factor) == len( rope_dim_list ), "len(theta_rescale_factor) should equal to len(rope_dim_list)"
if isinstance(interpolation_factor, int) or isinstance(interpolation_factor, float): interpolation_factor = [interpolation_factor] * len(rope_dim_list) elif isinstance(interpolation_factor, list) and len(interpolation_factor) == 1: interpolation_factor = [interpolation_factor[0]] * len(rope_dim_list) assert len(interpolation_factor) == len( rope_dim_list ), "len(interpolation_factor) should equal to len(rope_dim_list)"
# use 1/ndim of dimensions to encode grid_axis embs = [] for i in range(len(rope_dim_list)): emb = get_1d_rotary_pos_embed( rope_dim_list[i], grid[i].reshape(-1), theta, use_real=use_real, theta_rescale_factor=theta_rescale_factor[i], interpolation_factor=interpolation_factor[i], ) # 2 x [WHD, rope_dim_list[i]] embs.append(emb)
if use_real: cos = torch.cat([emb[0] for emb in embs], dim=1) # (WHD, D/2) sin = torch.cat([emb[1] for emb in embs], dim=1) # (WHD, D/2) return cos, sin else: emb = torch.cat(embs, dim=1) # (WHD, D/2) return emb
@cachedef get_1d_rotary_pos_embed( dim: int, pos: Union[torch.FloatTensor, int], theta: float = 10000.0, use_real: bool = False, theta_rescale_factor: float = 1.0, interpolation_factor: float = 1.0,) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Precompute the frequency tensor for complex exponential (cis) with given dimensions. (Note: `cis` means `cos + i * sin`, where i is the imaginary unit.)
This function calculates a frequency tensor with complex exponential using the given dimension 'dim' and the end index 'end'. The 'theta' parameter scales the frequencies. The returned tensor contains complex values in complex64 data type.
Args: dim (int): Dimension of the frequency tensor. pos (int or torch.FloatTensor): Position indices for the frequency tensor. [S] or scalar theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0. use_real (bool, optional): If True, return real part and imaginary part separately. Otherwise, return complex numbers. theta_rescale_factor (float, optional): Rescale factor for theta. Defaults to 1.0.
Returns: freqs_cis: Precomputed frequency tensor with complex exponential. [S, D/2] freqs_cos, freqs_sin: Precomputed frequency tensor with real and imaginary parts separately. [S, D] """ if isinstance(pos, int): pos = torch.arange(pos).float()
# proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning # has some connection to NTK literature if theta_rescale_factor != 1.0: theta *= theta_rescale_factor ** (dim / (dim - 2))
freqs = 1.0 / ( theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim) ) # [D/2] # assert interpolation_factor == 1.0, f"interpolation_factor: {interpolation_factor}" freqs = torch.outer(pos * interpolation_factor, freqs) # [S, D/2] if use_real: freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D] freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D] return freqs_cos, freqs_sin else: freqs_cis = torch.polar( torch.ones_like(freqs), freqs ) # complex64 # [S, D/2] return freqs_cis123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import mathimport torchimport numpy as npfrom einops import rearrangefrom functools import lru_cache
def tile(x, canvas_thw, tile_thw, sp_size=1): r"""Rearrange tensor into tiles for block-based attention. Args: x: Input tensor with shape (b, head, s, d) where s = t * h * w canvas_thw: Tuple of (t, h, w) representing temporal, height, width dimensions tile_thw: Tuple of (tile_t, tile_h, tile_w) representing tile dimensions sp_size: Spatial size parameter, defaults to 1 Returns: Rearranged tensor organized by tiles """ b, h, s, d = x.shape t, h, w = canvas_thw assert t * h * w == s, f"t:{t} * h:{h} * w:{w} == s:{s}"
tile_t_dim, tile_h_dim, tile_w_dim = tile_thw n_t = int(t/tile_t_dim) n_h = int(h/tile_h_dim) n_w = int(w/tile_w_dim) x = rearrange(x, "b head (sp t h w) d -> b head (t sp h w) d", sp=sp_size, t=t // sp_size, h=h, w=w) return rearrange(x, "b h (n_t ts_t n_h ts_h n_w ts_w) d -> b h (n_t n_h n_w ts_t ts_h ts_w) d", n_t=n_t, n_h=n_h, n_w=n_w, ts_t=tile_t_dim, ts_h=tile_h_dim, ts_w=tile_w_dim)
def untile(x, canvas_thw, tile_thw, sp_size=1): r"""Reverse the tiling operation to restore original tensor layout. Args: x: Tiled tensor canvas_thw: Tuple of (t, h, w) representing temporal, height, width dimensions tile_thw: Tuple of (tile_t, tile_h, tile_w) representing tile dimensions sp_size: Spatial size parameter, defaults to 1 Returns: Restored tensor with original layout """ t, h, w = canvas_thw
tile_t_dim, tile_h_dim, tile_w_dim = tile_thw n_t = int(t/tile_t_dim) n_h = int(h/tile_h_dim) n_w = int(w/tile_w_dim)
x = rearrange(x, "b h (n_t n_h n_w ts_t ts_h ts_w) d -> b h (n_t ts_t n_h ts_h n_w ts_w) d", n_t=n_t, n_h=n_h, n_w=n_w, ts_t=tile_t_dim, ts_h=tile_h_dim, ts_w=tile_w_dim) return rearrange(x, "b head (t sp h w) d -> b head (sp t h w) d", sp=sp_size, t=t // sp_size, h=h, w=w)
def get_tile_t_h_w(tile_id, tile_thw_dim): """Extract temporal, height, and width indices from a flattened tile ID.""" tile_t_dim, tile_h_dim, tile_w_dim = tile_thw_dim tile_t = tile_id // (tile_h_dim * tile_w_dim) tile_h = (tile_id % (tile_h_dim * tile_w_dim)) // tile_w_dim tile_w = tile_id % tile_w_dim
return tile_t, tile_h, tile_wdef importance_sampling(q, k, topk, threshold=0.0, lambda_=0.9, adaptive_pool=None): r"""Select top-k blocks based on importance scores considering both similarity and redundancy. Args: q: Query tensor with shape (B, H, S, D) k: Key tensor with shape (B, H, K, D) topk: Number of top blocks to select threshold: Threshold parameter (not implemented) lambda_: Weight factor balancing similarity and redundancy adaptive_pool: Adaptive pooling parameter (unused) Returns: top_block_indices: Indices of selected blocks with shape (B, H, S, topk) """ if threshold > 0.0: raise NotImplementedError("importance_sampling with threshold not implemented") q = q / q.norm(dim=-1, keepdim=True) k = k / k.norm(dim=-1, keepdim=True) gate_similarity = torch.einsum("bhsd,bhkd->bhsk", q, k) gate_similarity = (gate_similarity + 1.0) / 2.0 gate_unique = torch.einsum("bhsd,bhkd->bhsk", k, k) gate_unique = (gate_unique + 1.0) / 2.0 B, H, K_num, D = k.shape diag_indices = torch.arange(K_num, device=k.device) gate_unique[:, :, diag_indices, diag_indices] = torch.nan mean_redundancy = torch.nanmean(gate_unique, dim=-2, keepdim=True) importance_scores = lambda_ * gate_similarity - (1 - lambda_) * mean_redundancy topk = min(topk, importance_scores.size(-1)) _, top_block_indices = importance_scores.topk(k=topk, dim=-1, sorted=False) return top_block_indices
def similarity_sampling(q, k, topk, threshold=0.0, block_num=None, adaptive_pool=None, temperature=0.01): r"""Select top-k blocks based on similarity scores between query and key averages. Args: q: Query tensor with shape (B, H, S, D) k: Key tensor with shape (B, H, K, D) topk: Number of top blocks to select threshold: Cumulative score threshold for dynamic topk selection block_num: Total number of blocks (unused) adaptive_pool: Adaptive pooling parameter (unused) temperature: Temperature scaling for softmax Returns: top_block_indices: Indices of selected blocks with shape (B, H, S, topk) """ if threshold > 0.0: gate = torch.einsum("bhsd,bhkd->bhsk", q, k) gate = gate / temperature gate_ = torch.softmax(gate, dim=-1) sorted_gate, sorted_indices = torch.sort(gate_, dim=-1, descending=True) cum_scores = torch.cumsum(sorted_gate, dim=-1) above_threshold = cum_scores >= threshold has_any_above = above_threshold.any(dim=-1, keepdim=True) # Find the first position exceeding threshold, add 1 to get the number of blocks to select dynamic_topk = above_threshold.int().argmax(dim=-1, keepdim=True) + 1 dynamic_topk = torch.where(has_any_above, dynamic_topk, torch.full_like(dynamic_topk, topk)) # Generate fixed-shape indices and pad with top1 indices for parts not meeting threshold # Limit minimum k value dynamic_topk = torch.clamp(dynamic_topk, min=8, max=topk) indices = torch.arange(gate.size(-1), device=gate.device).expand(gate.size()) mask = (indices < dynamic_topk).int() # Use top1 to pad to topk to ensure same size top_block_indices = torch.gather(sorted_indices, -1, indices) * mask + (1 - mask) * sorted_indices[..., 0:1] else: gate = torch.einsum("bhsd,bhkd->bhsk", q, k) topk = min(topk, gate.size(-1)) _, top_block_indices = gate.topk(k=topk, dim=-1, sorted=False) return top_block_indices
def create_moba_3d_mask(q, k, canvas_thw, topk, tile_thw, kernel_thw, text_block_num=0, add_text_mask=False, threshold=0.0, lambda_=None, mask_share_within_head=True, q_block_avg_pool=True, adaptive_pool=None, sampling_type=None): r"""Create MOBA (Mixture of Block Attention) 3D mask for sparse attention. Args: q: Query tensor k: Key tensor canvas_thw: Canvas dimensions (t, h, w) topk: Number of top blocks to attend to tile_thw: Tile dimensions kernel_thw: Kernel dimensions text_block_num: Number of text blocks add_text_mask: Whether to add text mask threshold: Threshold for similarity sampling lambda_: Weight factor for importance sampling mask_share_within_head: Whether to share mask across heads q_block_avg_pool: Whether to apply average pooling to query blocks adaptive_pool: Adaptive pooling size sampling_type: Type of sampling ("similarity" or "importance") Returns: moba_3d_mask: 3D attention mask with shape (num_heads, block_num, block_num) """ seq_len = q.size(2) block_size = np.prod(tile_thw) block_num = int(seq_len / block_size)
image_shape = canvas_thw block_shape = tile_thw batch_size, num_heads, seq_len, head_dim = k.shape num_blocks_t = np.ceil(image_shape[0] / block_shape[0]).astype(int) num_blocks_h = np.ceil(image_shape[1] / block_shape[1]).astype(int) num_blocks_w = np.ceil(image_shape[2] / block_shape[2]).astype(int)
def get_block_avg_feat(x: torch.Tensor, adaptive_pool=None, pooling_type="avg") -> torch.Tensor: x_block_means = x.view(batch_size, num_heads, num_blocks_t, num_blocks_h, num_blocks_w, block_shape[0], block_shape[1], block_shape[2], head_dim) if adaptive_pool is not None: x_block_means = x_block_means.view(-1, block_shape[0], block_shape[1], block_shape[2], head_dim) x_block_means = x_block_means.permute(0, 4, 1, 2, 3) if pooling_type == "avg": global_avg = torch.nn.functional.adaptive_avg_pool3d(x_block_means, adaptive_pool) global_avg = global_avg.permute(0, 2, 3, 4, 1) global_avg = global_avg.reshape(batch_size, num_heads, -1, head_dim * adaptive_pool[0] * adaptive_pool[1] * adaptive_pool[2]) x_block_means = global_avg elif pooling_type == "max": max_pool = torch.nn.functional.adaptive_max_pool3d(x_block_means, adaptive_pool) max_pool = max_pool.permute(0, 2, 3, 4, 1) max_pool = max_pool.reshape(batch_size, num_heads, -1, head_dim * adaptive_pool[0] * adaptive_pool[1] * adaptive_pool[2]) x_block_means = max_pool elif pooling_type == "mix": global_avg = torch.nn.functional.adaptive_avg_pool3d(x_block_means, (1, 1, 1)) global_avg = global_avg / (global_avg.norm(dim=1, keepdim=True) + 1e-8) global_avg = global_avg.permute(0, 2, 3, 4, 1) global_avg = global_avg.reshape(batch_size, num_heads, -1, head_dim) max_pool = torch.nn.functional.adaptive_max_pool3d(x_block_means, adaptive_pool) max_pool = max_pool / (max_pool.norm(dim=1, keepdim=True) + 1e-8) max_pool = max_pool.permute(0, 2, 3, 4, 1) max_pool = max_pool.reshape(batch_size, num_heads, -1, head_dim * adaptive_pool[0] * adaptive_pool[1] * adaptive_pool[2]) x_block_means = torch.cat([max_pool, global_avg], dim=-1) else: raise ValueError(f"pooling_type={pooling_type} is not Supported") else: x_block_means = x_block_means.mean(dim=(-2, -3, -4)).view(batch_size, num_heads, -1, head_dim) return x_block_means
if (sampling_type == "similarity" and threshold > 0.0) and adaptive_pool is None: adaptive_pool = (2,2,2) k_block_means = get_block_avg_feat(k, adaptive_pool) if q_block_avg_pool: q = get_block_avg_feat(q, adaptive_pool) q = q.type(torch.float32) k_block_means = k_block_means.type(torch.float32) # float logit for better gate logit perception
if mask_share_within_head: q = q.mean(dim=1, keepdim=True) k_block_means = k_block_means.mean(dim=1, keepdim=True) if sampling_type == "similarity": top_block_indices = similarity_sampling(q, k_block_means, topk, threshold, block_num=block_num, adaptive_pool=adaptive_pool) elif sampling_type == "importance": top_block_indices = importance_sampling(q, k_block_means, topk, threshold, lambda_=lambda_, adaptive_pool=adaptive_pool) else: raise NotImplementedError(f"sampling_type={sampling_type} is not Supported") q = q.type_as(k) # Keep head dimension to dynamically build mask assert top_block_indices.size(0) == 1, "top_block_indices batch size must be 1" top_block_indices = top_block_indices.squeeze(0) # Remove batch dimension [h, s_block, topk] # Create 3D mask template (heads, block_num, block_num) gate_idx_mask = torch.zeros( (top_block_indices.size(0), block_num, block_num), dtype=torch.bool, device=q.device ) # Iterate over each attention head using dim=0 for head_idx in range(top_block_indices.size(0)): # Build index matrix for each head head_mask = torch.zeros( (block_num, block_num), dtype=torch.bool, device=q.device ) # Fill indices for current head head_mask.scatter_( dim=-1, index=top_block_indices[head_idx], value=True ) gate_idx_mask[head_idx] = head_mask
if text_block_num > 0: pad_block_num = block_num + text_block_num moba_3d_mask = torch.full( (gate_idx_mask.size(0), pad_block_num, pad_block_num), False, dtype=torch.bool, device=gate_idx_mask.device ) moba_3d_mask[:, :block_num, :block_num] = gate_idx_mask if add_text_mask: moba_3d_mask[:, :, -text_block_num:] = True moba_3d_mask[:, -text_block_num:, :] = True else: moba_3d_mask = gate_idx_mask
return moba_3d_mask
@lru_cache(maxsize=4096)def create_sta_3d_mask_optimize(canvas_thw, tile_thw, kernel_thw): r"""Create optimized STA (Spatio-Temporal Attention) 3D mask using vectorized operations. Args: canvas_thw: String representation of canvas dimensions "t_h_w" tile_thw: String representation of tile dimensions "t_h_w" kernel_thw: String representation of kernel dimensions "t_h_w" Returns: block_mask: Boolean mask tensor with shape (block_num, block_num) """ canvas_thw = tuple(map(int, canvas_thw.split('_'))) seq_len = np.prod(canvas_thw) tile_thw = tuple(map(int, tile_thw.split('_'))) kernel_thw = tuple(map(int, kernel_thw.split('_')))
kernel_t, kernel_h, kernel_w = kernel_thw
block_size = np.prod(tile_thw) block_num = int(seq_len / block_size)
block_mask = np.full((block_num, block_num), False, dtype=bool) tile_thw_num=(canvas_thw[0] // tile_thw[0], canvas_thw[1] // tile_thw[1], canvas_thw[2] // tile_thw[2]) i_indices = np.arange(block_num) j_indices = np.arange(block_num) i_grid, j_grid = np.meshgrid(i_indices, j_indices, indexing='ij') q_t_tile = i_grid // (tile_thw_num[1] * tile_thw_num[2]) q_h_tile = (i_grid % (tile_thw_num[1] * tile_thw_num[2])) // tile_thw_num[2] q_w_tile = i_grid % tile_thw_num[2] kv_t_tile = j_grid // (tile_thw_num[1] * tile_thw_num[2]) kv_h_tile = (j_grid % (tile_thw_num[1] * tile_thw_num[2])) // tile_thw_num[2] kv_w_tile = j_grid % tile_thw_num[2] kernel_center_t = np.clip(q_t_tile, kernel_t // 2, (tile_thw_num[0] - 1) - kernel_t // 2) kernel_center_h = np.clip(q_h_tile, kernel_h // 2, (tile_thw_num[1] - 1) - kernel_h // 2) kernel_center_w = np.clip(q_w_tile, kernel_w // 2, (tile_thw_num[2] - 1) - kernel_w // 2) time_mask = np.abs(kernel_center_t - kv_t_tile) <= kernel_t // 2 hori_mask = np.abs(kernel_center_h - kv_h_tile) <= kernel_h // 2 vert_mask = np.abs(kernel_center_w - kv_w_tile) <= kernel_w // 2 block_mask = time_mask & hori_mask & vert_mask block_mask = torch.tensor(block_mask, dtype=torch.bool) return block_mask
@torch.no_grad()def create_sta_3d_mask(canvas_thw, tile_thw, kernel_thw, text_block_num=0): r"""Create STA (Spatio-Temporal Attention) 3D mask. Args: canvas_thw: Canvas dimensions (t, h, w) tile_thw: Tile dimensions kernel_thw: Kernel dimensions text_block_num: Number of text blocks to pad Returns: sta_mask: Boolean mask tensor with optional text block padding """ block_mask = create_sta_3d_mask_optimize("_".join([str(x) for x in canvas_thw]), "_".join([str(x) for x in tile_thw]), "_".join([str(x) for x in kernel_thw])) sta_mask = None block_num = block_mask.size(0) if text_block_num > 0: pad_block_num = block_num + text_block_num sta_mask = torch.full( (pad_block_num, pad_block_num), False, dtype=torch.bool, ) sta_mask[:block_num, :block_num] = block_mask sta_mask[:, -text_block_num:] = True sta_mask[-text_block_num:, :] = True else: sta_mask = block_mask return sta_mask
@torch.no_grad()def create_ssta_3d_mask(q, k, canvas_thw, topk, tile_thw, kernel_thw, text_block_num=0, threshold=0.0, lambda_=None, text_mask=None, mask_share_within_head=True, adaptive_pool=None, sampling_type=None): r"""Create SSTA (Sparse Spatio-Temporal Attention) 3D mask combining STA and MOBA masks. Args: q: Query tensor k: Key tensor canvas_thw: Canvas dimensions (t, h, w) topk: Number of top blocks to attend to tile_thw: Tile dimensions kernel_thw: Kernel dimensions text_block_num: Number of text blocks threshold: Threshold for similarity sampling lambda_: Weight factor for importance sampling text_mask: Optional text mask tensor mask_share_within_head: Whether to share mask across heads adaptive_pool: Adaptive pooling size sampling_type: Type of sampling ("similarity" or "importance") Returns: ssta_3d_mask: Combined 3D attention mask """ sta_3d_mask = create_sta_3d_mask(canvas_thw, tile_thw, kernel_thw, text_block_num) sta_3d_mask = sta_3d_mask.to(q.device)
moba_3d_mask = create_moba_3d_mask(q, k, canvas_thw, topk, tile_thw, kernel_thw, text_block_num, threshold=threshold, lambda_=lambda_, mask_share_within_head=mask_share_within_head, adaptive_pool=adaptive_pool, sampling_type=sampling_type) ssta_3d_mask = torch.logical_or(sta_3d_mask.unsqueeze(0), moba_3d_mask) assert len(ssta_3d_mask.size()) == 3, "ssta_3d_mask should be 3D" # set text block mask if text_mask is not None: block_size = np.prod(tile_thw) seq_len = q.size(2) block_num = int(seq_len / block_size) text_mask_index = torch.ceil(text_mask.sum() / block_size).long() text_mask_index = text_mask_index.clamp(min=1).item() assert ssta_3d_mask.shape[-1] == ssta_3d_mask.shape[-2], "ssta_3d_mask should be square" pad_start_index = block_num + text_mask_index ssta_3d_mask[:, pad_start_index:, :] = False ssta_3d_mask[:, :, pad_start_index:] = False eye_mask = torch.eye(ssta_3d_mask.shape[1]-pad_start_index, dtype=torch.bool, device=ssta_3d_mask.device).unsqueeze(0) ssta_3d_mask[:, pad_start_index:, pad_start_index:] = ssta_3d_mask[:, pad_start_index:, pad_start_index:] | eye_mask return ssta_3d_mask
def ssta_3d_attention(all_q, all_k, all_v, canvas_thw, topk=1, tile_thw=(6, 8, 8), kernel_thw=(1, 1, 1), text_len=0, sparse_type='ssta', threshold=0.0, lambda_=None, pad_type="zero", text_mask=None, mask_share_within_head=True, sampling_type=None, adaptive_pool=None): r"""Sparse Spatio-Temporal Attention (SSTA) 3D attention mechanism. Args: all_q: Query tensor with shape (B, H, S, D) all_k: Key tensor with shape (B, H, S, D) all_v: Value tensor with shape (B, H, S, D) canvas_thw: Canvas dimensions (t, h, w) topk: Number of top blocks to attend to tile_thw: Tile dimensions kernel_thw: Kernel dimensions text_len: Length of text sequence sparse_type: Type of sparse attention ('sta', 'block_attn', or 'ssta') threshold: Threshold for similarity sampling lambda_: Weight factor for importance sampling pad_type: Padding type ("zero" or "repeat") text_mask: Optional text mask tensor mask_share_within_head: Whether to share mask across heads sampling_type: Type of sampling ("similarity" or "importance") adaptive_pool: Adaptive pooling size Returns: tuple: (output tensor, sparse_ratio) - output: Attention output with shape (B, H, S, D) - sparse_ratio: Ratio of non-zero attention weights """ try: from flex_block_attn import flex_block_attn_func except ImportError as e: raise Exception("Could not load flex-block-attn. Please install the flex-block-attn package. You can install it via 'pip install flex-block-attn'.") from e assert pad_type in ["zero", "repeat"] assert sampling_type in ["similarity", "importance"] assert (lambda_ is not None and sampling_type=="importance") or sampling_type == "similarity" if text_len > 0: image_q = all_q[:, :, :-text_len, :] image_k = all_k[:, :, :-text_len, :] image_v = all_v[:, :, :-text_len, :]
text_q = all_q[:, :, -text_len:, :] text_k = all_k[:, :, -text_len:, :] text_v = all_v[:, :, -text_len:, :] else: image_q = all_q image_k = all_k image_v = all_v
b, hd, s, d = image_q.shape t, h, w = canvas_thw assert t * h * w == s, f"t:{t} * h:{h} * w:{w} != s:{s}" tile_t, tile_h, tile_w = tile_thw block_size = np.prod(tile_thw)
need_pad = False if t % tile_t != 0 or h % tile_h !=0 or w % tile_w != 0: need_pad = True pad_image_q = image_q.reshape(b, hd, t, h, w, d) pad_image_k = image_k.reshape(b, hd, t, h, w, d) pad_image_v = image_v.reshape(b, hd, t, h, w, d)
pad_t = 0 if t % tile_t == 0 else tile_t - t % tile_t if pad_t > 0: t = t + pad_t repeat_q = pad_image_q[:, :, -1:, :, :, :].expand(-1, -1, pad_t, -1, -1, -1) repeat_k = pad_image_k[:, :, -1:, :, :, :].expand(-1, -1, pad_t, -1, -1, -1) repeat_v = pad_image_v[:, :, -1:, :, :, :].expand(-1, -1, pad_t, -1, -1, -1) if pad_type == "zero": repeat_q = torch.zeros_like(repeat_q) repeat_k = torch.zeros_like(repeat_k) repeat_v = torch.zeros_like(repeat_v) pad_image_q = torch.cat([pad_image_q, repeat_q], dim=2) pad_image_k = torch.cat([pad_image_k, repeat_k], dim=2) pad_image_v = torch.cat([pad_image_v, repeat_v], dim=2)
pad_h = 0 if h % tile_h == 0 else tile_h - h % tile_h if pad_h > 0: h = h + pad_h repeat_q = pad_image_q[:, :, :, -1:, :, :].expand(-1, -1, -1, pad_h, -1, -1) repeat_k = pad_image_k[:, :, :, -1:, :, :].expand(-1, -1, -1, pad_h, -1, -1) repeat_v = pad_image_v[:, :, :, -1:, :, :].expand(-1, -1, -1, pad_h, -1, -1) if pad_type == "zero": repeat_q = torch.zeros_like(repeat_q) repeat_k = torch.zeros_like(repeat_k) repeat_v = torch.zeros_like(repeat_v) pad_image_q = torch.cat([pad_image_q, repeat_q], dim=3) pad_image_k = torch.cat([pad_image_k, repeat_k], dim=3) pad_image_v = torch.cat([pad_image_v, repeat_v], dim=3)
pad_w = 0 if w % tile_w == 0 else tile_w - w % tile_w if pad_w > 0: w = w + pad_w repeat_q = pad_image_q[:, :, :, :, -1:, :].expand(-1, -1, -1, -1, pad_w, -1) repeat_k = pad_image_k[:, :, :, :, -1:, :].expand(-1, -1, -1, -1, pad_w, -1) repeat_v = pad_image_v[:, :, :, :, -1:, :].expand(-1, -1, -1, -1, pad_w, -1) if pad_type == "zero": repeat_q = torch.zeros_like(repeat_q) repeat_k = torch.zeros_like(repeat_k) repeat_v = torch.zeros_like(repeat_v) pad_image_q = torch.cat([pad_image_q, repeat_q], dim=4) pad_image_k = torch.cat([pad_image_k, repeat_k], dim=4) pad_image_v = torch.cat([pad_image_v, repeat_v], dim=4)
image_q = pad_image_q.reshape(b, hd, -1, d) image_k = pad_image_k.reshape(b, hd, -1, d) image_v = pad_image_v.reshape(b, hd, -1, d)
canvas_thw = (t, h, w)
need_pad_text = False text_block_num = math.ceil(text_len / block_size) text_target_size = text_block_num * block_size if text_len % block_size > 0: need_pad_text = True text_pad_size = text_target_size - text_len
pad_text_q = text_q[:, :, -1, :].unsqueeze(2).expand(-1, -1, text_pad_size, -1) pad_text_k = text_k[:, :, -1, :].unsqueeze(2).expand(-1, -1, text_pad_size, -1) pad_text_v = text_v[:, :, -1, :].unsqueeze(2).expand(-1, -1, text_pad_size, -1)
text_q = torch.cat([text_q, pad_text_q], dim=2) text_k = torch.cat([text_k, pad_text_k], dim=2) text_v = torch.cat([text_v, pad_text_v], dim=2)
image_q = tile(image_q, canvas_thw, tile_thw) image_k = tile(image_k, canvas_thw, tile_thw) image_v = tile(image_v, canvas_thw, tile_thw) if text_len > 0: q = torch.cat([image_q, text_q], dim=2) k = torch.cat([image_k, text_k], dim=2) v = torch.cat([image_v, text_v], dim=2) else: q = image_q k = image_k v = image_v
if sparse_type == 'sta': assert text_mask is None, "text_mask do not support in sta sparse_type" block_mask = create_sta_3d_mask(canvas_thw, tile_thw, kernel_thw, text_block_num).to(q.device) o = flex_block_attn_func(q, k, v, block_size, block_size, block_mask) elif sparse_type == 'block_attn': image_q_list = torch.split(image_q, 1, dim=0) image_k_list = torch.split(image_k, 1, dim=0)
mask_list = [] for i in range(b): block_mask = create_moba_3d_mask(image_q_list[i], image_k_list[i], canvas_thw=canvas_thw, topk=topk, tile_thw=tile_thw, kernel_thw=kernel_thw, text_block_num=text_block_num, add_text_mask=True, lambda_=lambda_, threshold=threshold, mask_share_within_head=mask_share_within_head, adaptive_pool=adaptive_pool, sampling_type=sampling_type) mask_list.append(block_mask) block_mask = torch.stack(mask_list, dim=0) o = flex_block_attn_func(q, k, v, block_size, block_size, block_mask)
elif sparse_type == 'ssta': image_q_list = torch.split(image_q, 1, dim=0) image_k_list = torch.split(image_k, 1, dim=0)
mask_list = [] for i in range(b): block_mask = create_ssta_3d_mask( image_q_list[i], image_k_list[i], canvas_thw=canvas_thw, tile_thw=tile_thw, kernel_thw=kernel_thw, text_block_num=text_block_num, topk=topk, threshold=threshold, lambda_=lambda_, text_mask=text_mask[i] if text_mask is not None else None, mask_share_within_head=mask_share_within_head, adaptive_pool=adaptive_pool, sampling_type=sampling_type ) mask_list.append(block_mask) block_mask = torch.stack(mask_list, dim=0) if mask_share_within_head: block_mask = block_mask.unsqueeze(1) # [b, 1, s_block, s_block] o = flex_block_attn_func(q, k, v, block_size, block_size, block_mask) else: raise Exception(f"unsupported sparse_type:{sparse_type}") sparse_ratio = block_mask.float().mean().cpu().item() if text_len > 0: image_o = o[:, :, :-text_target_size, :] if need_pad_text: text_o = o[:, :, -text_target_size : -text_pad_size, :] else: text_o = o[:, :, -text_target_size:, :] else: image_o = o
image_o = untile(image_o, canvas_thw, tile_thw)
if need_pad: # Remove padding from output unpad_image_o = image_o.reshape(b, hd, t, h, w, d) if pad_t > 0: unpad_image_o = unpad_image_o[:, :, :-pad_t, :, :, :] if pad_h > 0: unpad_image_o = unpad_image_o[:, :, :, :-pad_h, :, :] if pad_w > 0: unpad_image_o = unpad_image_o[:, :, :, :, :-pad_w, :] image_o = unpad_image_o.reshape(b, hd, -1, d)
if text_len > 0: o = torch.cat([image_o, text_o], dim=2) else: o = image_o return o, sparse_ratio123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
from typing import Optional
import torchimport torch.nn as nnfrom einops import rearrange
from .activation_layers import get_activation_layerfrom .embed_layers import TextProjection, TimestepEmbedderfrom .mlp_layers import MLPfrom .modulate_layers import apply_gatefrom .norm_layers import get_norm_layerfrom .attention import attention
class IndividualTokenRefinerBlock(nn.Module): """ A single block for token refinement with self-attention and MLP.
Args: hidden_size: Hidden dimension size. heads_num: Number of attention heads. mlp_width_ratio: Expansion ratio for MLP hidden size. mlp_drop_rate: Dropout rate for MLP. act_type: Activation function type. qk_norm: Whether to use QK normalization. qk_norm_type: Type of QK normalization. qkv_bias: Whether to use bias in QKV projections. dtype: Optional torch dtype. device: Optional torch device. """
def __init__( self, hidden_size: int, heads_num: int, mlp_width_ratio: float = 4.0, mlp_drop_rate: float = 0.0, act_type: str = "silu", qk_norm: bool = False, qk_norm_type: str = "layer", qkv_bias: bool = True, dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, ): factory_kwargs = {"device": device, "dtype": dtype} super().__init__() self.heads_num = heads_num head_dim = hidden_size // heads_num mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs) self.self_attn_qkv = nn.Linear(hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs) qk_norm_layer = get_norm_layer(qk_norm_type) self.self_attn_q_norm = ( qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() ) self.self_attn_k_norm = ( qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs) if qk_norm else nn.Identity() ) self.self_attn_proj = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs)
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs) act_layer = get_activation_layer(act_type) self.mlp = MLP( in_channels=hidden_size, hidden_channels=mlp_hidden_dim, act_layer=act_layer, drop=mlp_drop_rate, **factory_kwargs, )
self.adaLN_modulation = nn.Sequential( act_layer(), nn.Linear(hidden_size, 2 * hidden_size, bias=True, **factory_kwargs), ) # Zero-initialize the modulation nn.init.zeros_(self.adaLN_modulation[1].weight) nn.init.zeros_(self.adaLN_modulation[1].bias)
def forward( self, x: torch.Tensor, c: torch.Tensor, # timestep_aware_representations + context_aware_representations attn_mask: Optional[torch.Tensor] = None, ) -> torch.Tensor: """ Forward pass for IndividualTokenRefinerBlock.
Args: x: Input tensor of shape [B, L, C]. c: Conditioning tensor of shape [B, C]. attn_mask: Optional attention mask of shape [B, L].
Returns: Refined tensor of shape [B, L, C]. """ gate_msa, gate_mlp = self.adaLN_modulation(c).chunk(2, dim=1) norm_x = self.norm1(x) qkv = self.self_attn_qkv(norm_x) q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num) q = self.self_attn_q_norm(q).to(v) k = self.self_attn_k_norm(k).to(v) attn = attention(q, k, v, attn_mask=attn_mask) x = x + apply_gate(self.self_attn_proj(attn), gate_msa) x = x + apply_gate(self.mlp(self.norm2(x)), gate_mlp) return x
class IndividualTokenRefiner(nn.Module): """ Stacks multiple IndividualTokenRefinerBlock modules.
Args: hidden_size: Hidden dimension size. heads_num: Number of attention heads. depth: Number of blocks. mlp_width_ratio: Expansion ratio for MLP hidden size. mlp_drop_rate: Dropout rate for MLP. act_type: Activation function type. qk_norm: Whether to use QK normalization. qk_norm_type: Type of QK normalization. qkv_bias: Whether to use bias in QKV projections. dtype: Optional torch dtype. device: Optional torch device. """
def __init__( self, hidden_size: int, heads_num: int, depth: int, mlp_width_ratio: float = 4.0, mlp_drop_rate: float = 0.0, act_type: str = "silu", qk_norm: bool = False, qk_norm_type: str = "layer", qkv_bias: bool = True, dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, ): factory_kwargs = {"device": device, "dtype": dtype} super().__init__() self.blocks = nn.ModuleList( [ IndividualTokenRefinerBlock( hidden_size=hidden_size, heads_num=heads_num, mlp_width_ratio=mlp_width_ratio, mlp_drop_rate=mlp_drop_rate, act_type=act_type, qk_norm=qk_norm, qk_norm_type=qk_norm_type, qkv_bias=qkv_bias, **factory_kwargs, ) for _ in range(depth) ] )
def forward( self, x: torch.Tensor, c: torch.LongTensor, mask: Optional[torch.Tensor] = None, ) -> torch.Tensor: """ Forward pass for IndividualTokenRefiner.
Args: x: Input tensor of shape [B, L, C]. c: Conditioning tensor of shape [B, C]. mask: Optional mask tensor of shape [B, L].
Returns: Refined tensor of shape [B, L, C]. """ if mask is not None: mask = mask.clone().bool() mask[:, 0] = True # Prevent attention weights from becoming NaN for block in self.blocks: x = block(x, c, mask) return x
class SingleTokenRefiner(nn.Module): """ Single token refiner block for LLM text embedding refinement.
Args: in_channels: Input feature dimension. hidden_size: Hidden dimension size. heads_num: Number of attention heads. depth: Number of blocks. mlp_width_ratio: Expansion ratio for MLP hidden size. mlp_drop_rate: Dropout rate for MLP. act_type: Activation function type. qk_norm: Whether to use QK normalization. qk_norm_type: Type of QK normalization. qkv_bias: Whether to use bias in QKV projections. dtype: Optional torch dtype. device: Optional torch device. """
def __init__( self, in_channels: int, hidden_size: int, heads_num: int, depth: int, mlp_width_ratio: float = 4.0, mlp_drop_rate: float = 0.0, act_type: str = "silu", qk_norm: bool = False, qk_norm_type: str = "layer", qkv_bias: bool = True, dtype: Optional[torch.dtype] = None, device: Optional[torch.device] = None, ): factory_kwargs = {"device": device, "dtype": dtype} super().__init__() self.input_embedder = nn.Linear(in_channels, hidden_size, bias=True, **factory_kwargs) act_layer = get_activation_layer(act_type) self.t_embedder = TimestepEmbedder(hidden_size, act_layer, **factory_kwargs) self.c_embedder = TextProjection(in_channels, hidden_size, act_layer, **factory_kwargs) self.individual_token_refiner = IndividualTokenRefiner( hidden_size=hidden_size, heads_num=heads_num, depth=depth, mlp_width_ratio=mlp_width_ratio, mlp_drop_rate=mlp_drop_rate, act_type=act_type, qk_norm=qk_norm, qk_norm_type=qk_norm_type, qkv_bias=qkv_bias, **factory_kwargs, )
def forward( self, x: torch.Tensor, t: torch.LongTensor, mask: Optional[torch.LongTensor] = None, ) -> torch.Tensor: """ Forward pass for SingleTokenRefiner.
Args: x: Input tensor of shape [B, L, in_channels]. t: Timestep tensor of shape [B]. mask: Optional mask tensor of shape [B, L].
Returns: Refined tensor of shape [B, L, hidden_size]. """ timestep_aware_representations = self.t_embedder(t) if mask is None: context_aware_representations = x.mean(dim=1) else: mask_float = mask.float().unsqueeze(-1) # [B, L, 1] context_aware_representations = (x * mask_float).sum(dim=1) / mask_float.sum(dim=1) context_aware_representations = self.c_embedder(context_aware_representations) c = timestep_aware_representations + context_aware_representations x = self.input_embedder(x) x = self.individual_token_refiner(x, c, mask) return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
from dataclasses import dataclassfrom typing import Optional, Tupleimport torchimport torch.nn as nnfrom transformers import SiglipImageProcessor, SiglipVisionModelfrom transformers.utils import ModelOutputimport numpy as npfrom hyvideo.commons import PRECISION_TO_TYPE
VISION_ENCODER_PATH = {}
def use_default(value, default): return value if value is not None else default
def load_vision_encoder( vision_encoder_type, vision_encoder_precision=None, vision_encoder_path=None, logger=None, device=None,): if vision_encoder_path is None: vision_encoder_path = VISION_ENCODER_PATH[vision_encoder_type]
if vision_encoder_type == "siglip": vision_encoder = SiglipVisionModel.from_pretrained( vision_encoder_path, subfolder='image_encoder' ) else: raise ValueError(f"Unsupported vision encoder type: {vision_encoder_type}")
# from_pretrained will ensure that the model is in eval mode. if vision_encoder_precision is not None: vision_encoder = vision_encoder.to(dtype=PRECISION_TO_TYPE[vision_encoder_precision])
vision_encoder.requires_grad_(False)
if device is not None: vision_encoder = vision_encoder.to(device)
return vision_encoder, vision_encoder_path
def load_image_processor( processor_type, processor_path=None, logger=None): if processor_path is None: processor_path = VISION_ENCODER_PATH[processor_type]
if processor_type == "siglip": processor = SiglipImageProcessor.from_pretrained( processor_path, subfolder='feature_extractor' ) else: raise ValueError(f"Unsupported processor type: {processor_type}")
return processor, processor_path
@dataclassclass VisionEncoderModelOutput(ModelOutput): """ Base class for vision encoder model's outputs.
Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*): Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. """
last_hidden_state: torch.FloatTensor = None pooler_output: Optional[torch.FloatTensor] = None hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
class VisionEncoder(nn.Module): def __init__( self, vision_encoder_type: str, vision_encoder_precision: Optional[str] = None, vision_encoder_path: Optional[str] = None, processor_type: Optional[str] = None, processor_path: Optional[str] = None, output_key: Optional[str] = None, logger=None, device=None, ): super().__init__() self.vision_encoder_type = vision_encoder_type self.precision = vision_encoder_precision self.model_path = vision_encoder_path self.processor_type = ( processor_type if processor_type is not None else vision_encoder_type ) self.processor_path = ( processor_path if processor_path is not None else vision_encoder_path ) self.logger = logger
if "siglip" in vision_encoder_type: self.output_key = output_key or "last_hidden_state" else: raise ValueError(f"Unsupported vision encoder type: {vision_encoder_type}")
self.model, self.model_path = load_vision_encoder( vision_encoder_type=self.vision_encoder_type, vision_encoder_precision=self.precision, vision_encoder_path=self.model_path, logger=self.logger, device=device, ) self.dtype = self.model.dtype self.device = self.model.device
self.processor, self.processor_path = load_image_processor( processor_type=self.processor_type, processor_path=self.processor_path, logger=self.logger, )
def __repr__(self): return f"{self.vision_encoder_type} ({self.precision} - {self.model_path})"
def encode_latents_to_images(self, latents, vae, reorg_token=False): """ Convert latents to images using VAE decoder. Args: latents: Input latents tensor vae: VAE model for decoding reorg_token: Whether to reorg the token Returns: images: Decoded images as numpy array """ # Handle both 4D and 5D latents (for video, take first frame) first_image_latents = latents[:, :, 0, ...] if len(latents.shape) == 5 else latents first_image_latents = 1 / vae.config.scaling_factor * first_image_latents first_image = vae.decode(first_image_latents.unsqueeze(2).to(vae.dtype), return_dict=False)[0].cpu() first_image = first_image[:, :, 0, :, :] first_image = (first_image / 2 + 0.5).clamp(0, 1) first_image = (first_image * 255.0).clamp(0, 255.0) first_image = first_image.to(torch.uint8).numpy() first_image = first_image.transpose(0, 2, 3, 1)
assert isinstance(first_image, np.ndarray) assert first_image.ndim == 4 and first_image.shape[3] == 3 assert first_image.dtype == np.uint8
return first_image
def encode_images(self, images): """ Encode images using the vision encoder. Args: images: Input images (numpy array or preprocessed tensor) Returns: VisionEncoderModelOutput with encoded features """ if isinstance(images, np.ndarray): # Preprocess images if they're numpy arrays preprocessed = self.processor.preprocess(images=images, return_tensors="pt").to( device=self.model.device, dtype=self.model.dtype) else: # Assume already preprocessed preprocessed = images
outputs = self.model(**preprocessed) return VisionEncoderModelOutput( last_hidden_state=outputs.last_hidden_state, pooler_output=outputs.pooler_output if hasattr(outputs, 'pooler_output') else None, hidden_states=outputs.hidden_states if hasattr(outputs, 'hidden_states') else None )
def encode_latents(self, latents, vae, reorg_token=False): """ Encode latents by first converting to images, then encoding. This is the main function that replaces sigclip_vision_encode. Args: latents: Input latent tensors vae: VAE model for decoding latents to images Returns: Encoded image features """ # Convert latents to images images = self.encode_latents_to_images(latents, vae, reorg_token) # Encode images outputs = self.encode_images(images) return outputs.last_hidden_state
def forward(self, images): """ Forward pass for direct image encoding. Args: images: Input images Returns: VisionEncoderModelOutput with encoded features """ return self.encode_images(images) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234import mathimport torchtry: from torch.distributed.tensor import DTensor from torch.distributed.tensor.placement_types import ( Partial, Placement, Replicate, Shard, )except ImportError: # handle old pytorch versions Dtensor = None
# This code is modified from the GitHub repository of KellerJordan:# https://github.com/KellerJordan/Muon/blob/master/muon.pydef zeropower_via_newtonschulz5(G, steps = 5): """ Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. We opt to use a quintic iteration whose coefficients are selected to maximize the slope at zero. For the purpose of minimizing steps, it turns out to be empirically effective to keep increasing the slope at zero even beyond the point where the iteration no longer converges all the way to one everywhere on the interval. This iteration therefore does not produce UV^T but rather something like US'V^T where S' is diagonal with S_{ii}' ~ Uniform(0.5, 1.5), which turns out not to hurt model performance at all relative to UV^T, where USV^T = G is the SVD. """ if isinstance(G, DTensor): device_mesh = G.device_mesh G = G.full_tensor() else: device_mesh = None assert len(G.shape) >= 2 a, b, c = (3.4445, -4.7750, 2.0315) X = G if G.size(-2) > G.size(-1): X = X.mT # Ensure spectral norm is at most 1 X = X / (X.norm(dim=(-2, -1), keepdim=True) + 1e-7) # Perform the NS iterations for _ in range(steps): A = X @ X.T B = b * A + c * A @ A # quintic computation strategy adapted from suggestion by @jxbz, @leloykun, and @YouJiacheng X = a * X + B @ X
if G.size(-2) > G.size(-1): X = X.mT if device_mesh != None: return DTensor.from_local(X, device_mesh) else: return X
class Muon(torch.optim.Optimizer): """ Muon - MomentUm Orthogonalized by Newton-schulz
Arguments: muon_params: The parameters to be optimized by Muon. lr: The learning rate. The updates will have spectral norm of `lr`. (0.02 is a good default) momentum: The momentum used by the internal SGD. (0.95 is a good default) nesterov: Whether to use Nesterov-style momentum in the internal SGD. (recommended) ns_steps: The number of Newton-Schulz iterations to run. (6 is probably always enough) adamw_params: The parameters to be optimized by AdamW. Any parameters in `muon_params` which are {0, 1}-D or are detected as being the embed or lm_head will be optimized by AdamW as well. adamw_lr: The learning rate for the internal AdamW. adamw_betas: The betas for the internal AdamW. adamw_eps: The epsilon for the internal AdamW. adamw_wd: The weight decay for the internal AdamW. """
def __init__( self, lr=1e-3, wd=0.1, muon_params=None, momentum=0.95, nesterov=True, ns_steps=5, adamw_params=None, adamw_betas=(0.95, 0.95), adamw_eps=1e-8, ):
defaults = dict( lr=lr, wd=wd, momentum=momentum, nesterov=nesterov, ns_steps=ns_steps, adamw_betas=adamw_betas, adamw_eps=adamw_eps, )
params = list(muon_params) adamw_params = list(adamw_params) if adamw_params is not None else [] params.extend(adamw_params) super().__init__(params, defaults) # Sort parameters into those for which we will use Muon, and those for which we will not for p in muon_params: # Use Muon for every parameter in muon_params which is >= 2D and doesn't look like an embedding or head layer assert p.ndim >= 2, p.ndim self.state[p]["use_muon"] = True for p in adamw_params: # Do not use Muon for parameters in adamw_params self.state[p]["use_muon"] = False
def adjust_lr_for_muon(self, lr, param_shape): A, B = param_shape[:2] # We adjust the learning rate and weight decay based on the size of the parameter matrix # as describted in the paper adjusted_ratio = 0.2 * math.sqrt(max(A, B)) adjusted_lr = lr * adjusted_ratio return adjusted_lr
def step(self, closure=None): """Perform a single optimization step.
Args: closure (Callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure()
for group in self.param_groups:
############################ # Muon # ############################
params = [p for p in group["params"] if self.state[p]["use_muon"]]
lr = group["lr"] wd = group["wd"] momentum = group["momentum"]
# generate weight updates in distributed fashion for p in params: # sanity check g = p.grad if g is None: # For i2v task, vision_in does not have gradients. # Creating a dummy gradient to allow `full_tensor` computation. if isinstance(p, DTensor): g = DTensor.from_local(torch.zeros_like(p.to_local()), p.device_mesh, placements=p.placements) else: g = torch.zeros_like(p) if g.ndim > 2: g = g.view(g.size(0), -1) assert g is not None
# calc update state = self.state[p] if "momentum_buffer" not in state: state["momentum_buffer"] = torch.zeros_like(g) buf = state["momentum_buffer"] buf.mul_(momentum).add_(g) if group["nesterov"]: g = g.add(buf, alpha=momentum) else: g = buf g = g.bfloat16() u = zeropower_via_newtonschulz5(g, steps=group["ns_steps"])
# scale update adjusted_lr = self.adjust_lr_for_muon(lr, p.shape)
# apply weight decay p.data.mul_(1 - lr * wd)
# apply update p.data.add_(u.view(p.shape), alpha=-adjusted_lr)
############################ # AdamW backup # ############################
params = [p for p in group["params"] if not self.state[p]["use_muon"]] lr = group['lr'] beta1, beta2 = group["adamw_betas"] eps = group["adamw_eps"] weight_decay = group["wd"]
for p in params: g = p.grad if g is None: continue state = self.state[p] if "step" not in state: state["step"] = 0 state["moment1"] = torch.zeros_like(g) state["moment2"] = torch.zeros_like(g) state["step"] += 1 step = state["step"] buf1 = state["moment1"] buf2 = state["moment2"] buf1.lerp_(g, 1 - beta1) buf2.lerp_(g.square(), 1 - beta2)
g = buf1 / (eps + buf2.sqrt())
bias_correction1 = 1 - beta1**step bias_correction2 = 1 - beta2**step scale = bias_correction1 / bias_correction2**0.5 p.data.mul_(1 - lr * weight_decay) p.data.add_(g, alpha=-lr / scale)
return loss
# help function to create the Muon optimizerdef get_muon_optimizer(model, lr=1e-3, weight_decay=0.1, momentum=0.95, adamw_betas=(0.95, 0.95), adamw_eps=1e-8): muon_params = [ p for name, p in model.named_parameters() if p.requires_grad and p.ndim >= 2 ] adamw_params = [ p for name, p in model.named_parameters() if p.requires_grad and not (p.ndim >= 2) ]
return Muon( lr=lr, wd=weight_decay, muon_params=muon_params, momentum=momentum, adamw_params=adamw_params, adamw_betas=adamw_betas, adamw_eps=adamw_eps, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
from typing import Optional, Union, Listimport inspectimport torch
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
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_cfg123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.## ==============================================================================# Modified from diffusers# ==============================================================================# Copyright 2024 Stability AI, Katherine Crowson and 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.
import mathfrom dataclasses import dataclassfrom typing import Optional, Tuple, Union
import numpy as npimport torch
from diffusers.configuration_utils import ConfigMixin, register_to_configfrom diffusers.utils import BaseOutput, loggingfrom diffusers.schedulers.scheduling_utils import SchedulerMixin
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@dataclassclass FlowMatchDiscreteSchedulerOutput(BaseOutput): """ Output class for the scheduler's `step` function output.
Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the denoising loop. """
prev_sample: torch.FloatTensor
class FlowMatchDiscreteScheduler(SchedulerMixin, ConfigMixin): """ Euler scheduler.
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic methods the library implements for all schedulers such as loading and saving.
Args: num_train_timesteps (`int`, defaults to 1000): The number of diffusion steps to train the model. timestep_spacing (`str`, defaults to `"linspace"`): The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information. shift (`float`, defaults to 1.0): The shift value for the timestep schedule. reverse (`bool`, defaults to `True`): Whether to reverse the timestep schedule. """
_compatibles = [] order = 1
@register_to_config def __init__( self, num_train_timesteps: int = 1000, shift: float = 1.0, reverse: bool = True, solver: str = "euler", use_flux_shift: bool = False, flux_base_shift: float = 0.5, flux_max_shift: float = 1.15, n_tokens: Optional[int] = None, flux_base_token=256., flux_max_token=4096., flux_shift_factor=1.0, ): sigmas = torch.linspace(1, 0, num_train_timesteps + 1)
if not reverse: sigmas = sigmas.flip(0)
self.sigmas = sigmas # the value fed to model self.timesteps = (sigmas[:-1] * num_train_timesteps).to(dtype=torch.float32)
self._step_index = None self._begin_index = None
self.supported_solver = [ "euler" ] if solver not in self.supported_solver: raise ValueError(f"Solver {solver} not supported. Supported solvers: {self.supported_solver}")
@property def step_index(self): """ The index counter for current timestep. It will increase 1 after each scheduler step. """ return self._step_index
@property def begin_index(self): """ The index for the first timestep. It should be set from pipeline with `set_begin_index` method. """ return self._begin_index
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index def set_begin_index(self, begin_index: int = 0): """ Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
Args: begin_index (`int`): The begin index for the scheduler. """ self._begin_index = begin_index
def _sigma_to_t(self, sigma): return sigma * self.config.num_train_timesteps
def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None, n_tokens: int = None): """ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
Args: num_inference_steps (`int`): The number of diffusion steps used when generating samples with a pre-trained model. device (`str` or `torch.device`, *optional*): The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. n_tokens (`int`, *optional*): Number of tokens in the input sequence. """ self.num_inference_steps = num_inference_steps
sigmas = torch.linspace(1, 0, num_inference_steps + 1)
# Apply timestep shift if self.config.use_flux_shift: assert isinstance(n_tokens, int), "n_tokens should be provided for flux shift" mu = self.get_lin_function(x1=self.config.flux_base_token, x2=self.config.flux_max_token, y1=self.config.flux_base_shift * self.config.flux_shift_factor, y2=self.config.flux_max_shift * self.config.flux_shift_factor)(n_tokens) sigmas = self.flux_time_shift(mu, 1.0, sigmas) elif self.config.shift != 1.: sigmas = self.sd3_time_shift(sigmas)
if not self.config.reverse: sigmas = 1 - sigmas
self.sigmas = sigmas self.timesteps = (sigmas[:-1] * self.config.num_train_timesteps).to(dtype=torch.float32, device=device)
# Reset step index self._step_index = None
def index_for_timestep(self, timestep, schedule_timesteps=None): if schedule_timesteps is None: schedule_timesteps = self.timesteps
indices = (schedule_timesteps == timestep).nonzero()
# The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) pos = 1 if len(indices) > 1 else 0
return indices[pos].item()
def _init_step_index(self, timestep): if self.begin_index is None: if isinstance(timestep, torch.Tensor): timestep = timestep.to(self.timesteps.device) self._step_index = self.index_for_timestep(timestep) else: self._step_index = self._begin_index
def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor: return sample
@staticmethod def get_lin_function(x1: float = 256, y1: float = 0.5, x2: float = 4096, y2: float = 1.15): m = (y2 - y1) / (x2 - x1) b = y1 - m * x1 return lambda x: m * x + b
@staticmethod def flux_time_shift(mu: float, sigma: float, t: torch.Tensor): return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
def sd3_time_shift(self, t: torch.Tensor): return (self.config.shift * t) / (1 + (self.config.shift - 1) * t)
def step( self, model_output: torch.FloatTensor, timestep: Union[float, torch.FloatTensor], sample: torch.FloatTensor, generator: Optional[torch.Generator] = None, n_tokens: Optional[int] = None, return_dict: bool = True, ) -> Union[FlowMatchDiscreteSchedulerOutput, Tuple]: """ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion process from the learned model outputs (most often the predicted noise).
Args: model_output (`torch.FloatTensor`): The direct output from learned diffusion model. timestep (`float`): The current discrete timestep in the diffusion chain. sample (`torch.FloatTensor`): A current instance of a sample created by the diffusion process. generator (`torch.Generator`, *optional*): A random number generator. n_tokens (`int`, *optional*): Number of tokens in the input sequence. return_dict (`bool`): Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or tuple.
Returns: [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`: If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is returned, otherwise a tuple is returned where the first element is the sample tensor. """
if ( isinstance(timestep, int) or isinstance(timestep, torch.IntTensor) or isinstance(timestep, torch.LongTensor) ): raise ValueError( ( "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to" " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass" " one of the `scheduler.timesteps` as a timestep." ), )
if self.step_index is None: self._init_step_index(timestep)
# Upcast to avoid precision issues when computing prev_sample sample = sample.to(torch.float32)
dt = self.sigmas[self.step_index + 1] - self.sigmas[self.step_index]
if self.config.solver == "euler": prev_sample = sample + model_output.float() * dt else: raise ValueError(f"Solver {self.config.solver} not supported. Supported solvers: {self.supported_solver}")
# Cast sample back to model compatible dtype # prev_sample = prev_sample.to(model_output.dtype)
# upon completion increase step index by one self._step_index += 1
if not return_dict: return (prev_sample,)
return FlowMatchDiscreteSchedulerOutput(prev_sample=prev_sample)
def __len__(self): return self.config.num_train_timesteps123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
from typing import Any, Tupleimport torchimport torch.distributed as dist
from torch.nn import functional as F
def broadcast(input_: torch.Tensor, group: dist.ProcessGroup): src = dist.get_global_rank(group, 0) dist.broadcast(input_, src=src, group=group)
def _all_to_all_4D( input: torch.tensor, scatter_idx: int = 2, gather_idx: int = 1, group=None) -> torch.tensor: """ all-to-all for QKV
Args: input (torch.tensor): a tensor sharded along dim scatter dim scatter_idx (int): default 1 gather_idx (int): default 2 group : torch process group
Returns: torch.tensor: resharded tensor (bs, seqlen/P, hc, hs) """ assert ( input.dim() == 4 ), f"input must be 4D tensor, got {input.dim()} and shape {input.shape}"
seq_world_size = dist.get_world_size(group)
if scatter_idx == 2 and gather_idx == 1:
seq_lens = [None] * seq_world_size dist.all_gather_object(seq_lens, input.shape[1], group) # uneven if seq_lens[-1] != seq_lens[0] : assert seq_lens[0] > seq_lens[-1] gap = seq_lens[0] - seq_lens[-1] if dist.get_group_rank(group, dist.get_rank()) == seq_world_size - 1: assert input.shape[1] == seq_lens[-1] input = F.pad(input, (0, 0, 0, 0, 0, gap)) else: gap = 0
# input (torch.tensor): a tensor sharded along dim 1 (bs, seqlen/P, hc, hs) output: (bs, seqlen, hc/P, hs) bs, shard_seqlen, hc, hs = input.shape seqlen = shard_seqlen * seq_world_size assert hc % seq_world_size == 0, f'Invalid Head size: {hc}, which should be divisible by spsize {seq_world_size}' shard_hc = hc // seq_world_size
# transpose groups of heads with the seq-len parallel dimension, so that we can scatter them! # (bs, seqlen/P, hc, hs) -reshape-> (bs, seq_len/P, P, hc/P, hs) -transpose(0,2)-> (P, seq_len/P, bs, hc/P, hs) input_t = ( input.reshape(bs, shard_seqlen, seq_world_size, shard_hc, hs) .transpose(0, 2) .contiguous() )
output = torch.empty_like(input_t) # https://pytorch.org/docs/stable/distributed.html#torch.distributed.all_to_all_single # (P, seq_len/P, bs, hc/P, hs) scatter seqlen -all2all-> (P, seq_len/P, bs, hc/P, hs) scatter head if seq_world_size > 1: dist.all_to_all_single(output, input_t, group=group) else: output = input_t # if scattering the seq-dim, transpose the heads back to the original dimension output = output.reshape(seqlen, bs, shard_hc, hs)
# (seq_len, bs, hc/P, hs) -reshape-> (bs, seq_len, hc/P, hs) output = output.transpose(0, 1).contiguous().reshape(bs, seqlen, shard_hc, hs) if gap > 0: output = output[:, :-gap]
return output
elif scatter_idx == 1 and gather_idx == 2: # input (torch.tensor): a tensor sharded along dim 1 (bs, seqlen, hc/P, hs) output: (bs, seqlen/P, hc, hs) bs, seqlen, shard_hc, hs = input.shape
hc = shard_hc * seq_world_size if seqlen % seq_world_size != 0: new_seqlen = (seqlen // seq_world_size + 1) * seq_world_size gap = new_seqlen - seqlen input = F.pad(input, (0, 0, 0, 0, 0, gap)) bs, seqlen, shard_hc, hs = input.shape else: gap = 0
assert seqlen % seq_world_size == 0
shard_seqlen = seqlen // seq_world_size seq_world_size = dist.get_world_size(group)
# transpose groups of heads with the seq-len parallel dimension, so that we can scatter them! # (bs, seqlen, hc/P, hs) -reshape-> (bs, P, seq_len/P, hc/P, hs) -transpose(0, 3)-> (hc/P, P, seqlen/P, bs, hs) -transpose(0, 1) -> (P, hc/P, seqlen/P, bs, hs) input_t = ( input.reshape(bs, seq_world_size, shard_seqlen, shard_hc, hs) .transpose(0, 3) .transpose(0, 1) .contiguous() .reshape(seq_world_size, shard_hc, shard_seqlen, bs, hs) )
output = torch.empty_like(input_t) # https://pytorch.org/docs/stable/distributed.html#torch.distributed.all_to_all_single # (P, bs x hc/P, seqlen/P, hs) scatter seqlen -all2all-> (P, bs x seq_len/P, hc/P, hs) scatter head if seq_world_size > 1: dist.all_to_all_single(output, input_t, group=group) else: output = input_t
# if scattering the seq-dim, transpose the heads back to the original dimension output = output.reshape(hc, shard_seqlen, bs, hs)
# (hc, seqlen/N, bs, hs) -tranpose(0,2)-> (bs, seqlen/N, hc, hs) output = output.transpose(0, 2).contiguous().reshape(bs, shard_seqlen, hc, hs)
if gap > 0 and dist.get_group_rank(group, dist.get_rank()) == seq_world_size - 1: output = output[:, :-gap]
return output else: raise RuntimeError("scatter_idx must be 1 or 2 and gather_idx must be 1 or 2")
class SeqAllToAll4D(torch.autograd.Function): @staticmethod def forward( ctx: Any, group: dist.ProcessGroup, input: torch.Tensor, scatter_idx: int, gather_idx: int, ) -> torch.Tensor: ctx.group = group ctx.scatter_idx = scatter_idx ctx.gather_idx = gather_idx
return _all_to_all_4D(input, scatter_idx, gather_idx, group=group)
@staticmethod def backward(ctx: Any, *grad_output: torch.Tensor) -> Tuple[None, torch.Tensor, None, None]: return ( None, SeqAllToAll4D.apply( ctx.group, *grad_output, ctx.gather_idx, ctx.scatter_idx ), None, None, )
def all_to_all_4D( input_: torch.Tensor, group: dist.ProcessGroup, scatter_dim: int = 2, gather_dim: int = 1,): return SeqAllToAll4D.apply(group, input_, scatter_dim, gather_dim)
def _all_to_all( input_: torch.Tensor, world_size: int, group: dist.ProcessGroup, scatter_dim: int, gather_dim: int,): input_list = [ t.contiguous() for t in torch.tensor_split(input_, world_size, scatter_dim) ] output_list = [torch.empty_like(input_list[0]) for _ in range(world_size)] dist.all_to_all(output_list, input_list, group=group) return torch.cat(output_list, dim=gather_dim).contiguous()
class _AllToAll(torch.autograd.Function): """All-to-all communication.
Args: input_: input matrix process_group: communication group scatter_dim: scatter dimension gather_dim: gather dimension """
@staticmethod def forward(ctx, input_, process_group, scatter_dim, gather_dim): ctx.process_group = process_group ctx.scatter_dim = scatter_dim ctx.gather_dim = gather_dim ctx.world_size = dist.get_world_size(process_group) output = _all_to_all( input_, ctx.world_size, process_group, scatter_dim, gather_dim ) return output
@staticmethod def backward(ctx, grad_output): grad_output = _all_to_all( grad_output, ctx.world_size, ctx.process_group, ctx.gather_dim, ctx.scatter_dim, ) return ( grad_output, None, None, None, )
def all_to_all( input_: torch.Tensor, group: dist.ProcessGroup, scatter_dim: int = 2, gather_dim: int = 1): return _AllToAll.apply(input_, group, scatter_dim, gather_dim)
class _Reduce_Scatter(torch.autograd.Function):
@staticmethod def forward(ctx, op, group, tensor, *input_tensor_list): ctx.group = group # Need contiguous tensors for collectives. tensor = tensor.contiguous() input_tensor_list = tuple(t.contiguous() for t in input_tensor_list) dist.reduce_scatter(tensor, list(input_tensor_list), op=op, group=group) return tensor
@staticmethod def backward(ctx, grad_output): return (None, None, None) + _AllGather.apply(ctx.group, grad_output)
class _AllGather(torch.autograd.Function): """All-gather communication with autograd support.
Args: input_: input tensor dim: dimension along which to concatenate """
@staticmethod def forward(ctx, input_, dim, group): ctx.dim = dim ctx.group = group world_size = dist.get_world_size(group) input_size = list(input_.size())
sizes = [None] * world_size dist.all_gather_object(sizes, input_.shape, group)
ctx.input_size = input_size[dim]
tensor_list = [torch.empty(sizes[i], dtype=input_.dtype, device=input_.device) for i in range(world_size)] input_ = input_.contiguous() dist.all_gather(tensor_list, input_, group=group)
output = torch.cat(tensor_list, dim=dim) return output
@staticmethod def backward(ctx, grad_output): group = ctx.group world_size = dist.get_world_size(group) global_rank = dist.get_rank() rank = dist.get_group_rank(group, global_rank) dim = ctx.dim input_size = ctx.input_size
sizes = [None] * world_size dist.all_gather_object(sizes, input_size, group=group)
grad_input_list = torch.split(grad_output, sizes, dim=dim) grad_input = grad_input_list[rank]
grad_input = _Reduce_Scatter.apply(dist.ReduceOp.SUM, group, grad_input, *grad_input_list)
return grad_input, None, None
# https://github.com/pytorch/pytorch/issues/138795@torch.compiler.disabledef all_gather(input_: torch.Tensor, dim: int = 1, group=None): """Performs an all-gather operation on the input tensor along the specified dimension.
Args: input_ (torch.Tensor): Input tensor of shape [B, H, S, D]. dim (int, optional): Dimension along which to concatenate. Defaults to 1.
Returns: torch.Tensor: Output tensor after all-gather operation, concatenated along 'dim'. """ return _AllGather.apply(input_, dim, group)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
import numpy as npfrom PIL import Image
def resize_and_center_crop(image, target_width, target_height): if target_height == image.shape[0] and target_width == image.shape[1]: return image
pil_image = Image.fromarray(image) original_width, original_height = pil_image.size scale_factor = max(target_width / original_width, target_height / original_height) resized_width = int(round(original_width * scale_factor)) resized_height = int(round(original_height * scale_factor)) resized_image = pil_image.resize((resized_width, resized_height), Image.LANCZOS) left = (resized_width - target_width) / 2 top = (resized_height - target_height) / 2 right = (resized_width + target_width) / 2 bottom = (resized_height + target_height) / 2 cropped_image = resized_image.crop((left, top, right, bottom)) return np.array(cropped_image)
def get_closest_ratio(height: float, width: float, ratios: list, buckets: list): """ Get the closest ratio in the buckets.
Args: height (float): video height width (float): video width ratios (list): video aspect ratio buckets (list): buckets generated by `generate_crop_size_list`
Returns: the closest size in the buckets and the corresponding ratio """ aspect_ratio = float(height) / float(width) ratios_array = np.array(ratios) closest_ratio_id = np.abs(ratios_array - aspect_ratio).argmin() closest_size = buckets[closest_ratio_id] closest_ratio = ratios_array[closest_ratio_id]
return closest_size, closest_ratio
def generate_crop_size_list(base_size=256, patch_size=16, max_ratio=4.0): num_patches = round((base_size / patch_size) ** 2) assert max_ratio >= 1.0 crop_size_list = [] wp, hp = num_patches, 1 while wp > 0: if max(wp, hp) / min(wp, hp) <= max_ratio: crop_size_list.append((wp * patch_size, hp * patch_size)) if (hp + 1) * wp <= num_patches: hp += 1 else: wp -= 1 return crop_size_list1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent-Hunyuan/HunyuanVideo-1.5/blob/main/LICENSE## Unless and only to the extent required by applicable law, the Tencent Hunyuan works and any# output and results therefrom are provided "AS IS" without any express or implied warranties of# any kind including any warranties of title, merchantability, noninfringement, course of dealing,# usage of trade, or fitness for a particular purpose. You are solely responsible for determining the# appropriateness of using, reproducing, modifying, performing, displaying or distributing any of# the Tencent Hunyuan works or outputs and assume any and all risks associated with your or a# third party's use or distribution of any of the Tencent Hunyuan works or outputs and your exercise# of rights and permissions under this agreement.# See the License for the specific language governing permissions and limitations under the License.
from einops import rearrange
def flash_attn_no_pad( qkv, key_padding_mask, causal=False, dropout_p=0.0, softmax_scale=None, deterministic=False): from flash_attn import flash_attn_varlen_qkvpacked_func from flash_attn.bert_padding import pad_input, unpad_input batch_size = qkv.shape[0] seqlen = qkv.shape[1] nheads = qkv.shape[-2] x = rearrange(qkv, "b s three h d -> b s (three h d)") x_unpad, indices, cu_seqlens, max_s, used_seqlens_in_batch = unpad_input( x, key_padding_mask )
x_unpad = rearrange(x_unpad, "nnz (three h d) -> nnz three h d", three=3, h=nheads) output_unpad = flash_attn_varlen_qkvpacked_func( x_unpad, cu_seqlens, max_s, dropout_p, softmax_scale=softmax_scale, causal=causal, deterministic=deterministic, ) output = rearrange( pad_input( rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, batch_size, seqlen ), "b s (h d) -> b s h d", h=nheads, ) return output
def flash_attn_no_pad_v3( qkv, key_padding_mask, causal=False, dropout_p=0.0, softmax_scale=None, deterministic=False): from flash_attn import flash_attn_varlen_qkvpacked_func from flash_attn.bert_padding import pad_input, unpad_input from flash_attn_interface import flash_attn_varlen_func as flash_attn_varlen_func_v3
if flash_attn_varlen_func_v3 is None: raise ImportError("FlashAttention V3 backend not available") batch_size, seqlen, _, nheads, head_dim = qkv.shape query, key, value = qkv.unbind(dim=2) query_unpad, indices, cu_seqlens_q, max_seqlen_q, _ = unpad_input( rearrange(query, "b s h d -> b s (h d)"), key_padding_mask ) key_unpad, _, cu_seqlens_k, _, _ = unpad_input( rearrange(key, "b s h d -> b s (h d)"), key_padding_mask ) value_unpad, _, _, _, _ = unpad_input( rearrange(value, "b s h d -> b s (h d)"), key_padding_mask ) query_unpad = rearrange(query_unpad, "nnz (h d) -> nnz h d", h=nheads) key_unpad = rearrange(key_unpad, "nnz (h d) -> nnz h d", h=nheads) value_unpad = rearrange(value_unpad, "nnz (h d) -> nnz h d", h=nheads) output_unpad = flash_attn_varlen_func_v3( query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_q, softmax_scale=softmax_scale, causal=causal, deterministic=deterministic ) if isinstance(output_unpad, tuple): # output, softmax_lse output_unpad = output_unpad[0] output = rearrange( pad_input(rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, batch_size, seqlen), "b s (h d) -> b s h d", h=nheads ) return output123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120# Modified by the UniVEdit authors from Tencent-Hunyuan/OmniWeaving (HunyuanVideo-1.5).import torchimport torchvision.transforms as transformsimport numpy as npfrom PIL import Imagefrom decord import VideoReader
def prepare_custom_video(vr, total_subset=161, nframes=8): if isinstance(vr, str): vr = VideoReader(vr) max_frames = min(len(vr), total_subset) sample_indices = np.linspace(0, max_frames - 1, nframes).astype(int) frames = vr.get_batch(sample_indices) if hasattr(frames, 'asnumpy'): frames = frames.asnumpy() # decord NDArray else: frames = frames.numpy() # PyTorch Tensor frame_list = [Image.fromarray(frame) for frame in frames] return frame_list
def get_semantic_images_np(video_path_list, nframes=8): """ Extract first frame from each video in video_path_list and return batchified numpy array. Args: video_path_list: List of video paths Returns: first_images_np: numpy array of shape (B, H, W, C) with dtype uint8 (0-255) Returns None if video_path_list is None or empty """ if video_path_list is None or len(video_path_list) == 0: return None first_frames = [] sampled_frames = [] for video_path in video_path_list: # Read first frame from video if isinstance(video_path, str): video_reader = VideoReader(video_path) else: assert isinstance(video_path, VideoReader), f"video_path must be either str or VideoReader, got {type(video_path)}" video_reader = video_path if len(video_reader) == 0: raise ValueError(f"Video {video_path} has no frames") sample_frame_list = prepare_custom_video(video_reader, nframes=nframes) sampled_frames.append(sample_frame_list) # Get first frame (index 0) first_frame = video_reader.get_batch([0]) # Convert to numpy: shape is (1, H, W, C) if hasattr(first_frame, 'asnumpy'): first_frame_np = first_frame.asnumpy() # decord NDArray else: first_frame_np = first_frame.numpy() # PyTorch Tensor # Remove batch dimension: shape becomes (H, W, C) first_frame_np = first_frame_np[0] first_frames.append(first_frame_np) del video_reader # Stack all first frames into batch: shape becomes (B, H, W, C) first_images_np = np.stack(first_frames, axis=0) # Ensure uint8 format (0-255) first_images_np = first_images_np.astype(np.uint8) return first_images_np, sampled_frames
def get_semantic_images_np2(video_path_list, first_image_pil, vae, F, nframes=8, is_mode=True): """ Extract first frame from each video in video_path_list and return batchified numpy array. Also encode first_image_pil list into cond_latents with values filled at F index=1.
Args: video_path_list: List of video paths or VideoReader objects first_image_pil: List of PIL.Image.Image args: Arguments object containing vae_precision vae: VAE model F: Time dimension for cond_latents (must be >= 2) nframes: Number of frames to sample for each video (default: 8) is_mode: If True, use mode() for latent distribution, else use sample()
Returns: first_images_np: numpy array of shape (B, H, W, C) with dtype uint8 (0-255) sampled_frames: list of sampled frame lists per video cond_latents: tensor of shape (B, C, F, H, W), values at index=1, others 0 first_image_pil_np: numpy array of shape (B, H, W, C) with dtype uint8 (0-255) """ first_images_np, sampled_frames = get_semantic_images_np(video_path_list, nframes=nframes)
if first_image_pil is None or len(first_image_pil) == 0: raise ValueError("first_image_pil must be a non-empty list of PIL images")
if F < 2: raise ValueError(f"F must be >= 2 to fill index=1, got {F}")
first_image_pil_np = np.array([np.array(img, dtype=np.uint8) for img in first_image_pil])
image_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize([0.5], [0.5]) ]) first_images_pixel_values = [image_transform(image).unsqueeze(0) for image in first_image_pil] first_images_pixel_values = torch.cat(first_images_pixel_values).unsqueeze(2).to(vae.device)
with torch.autocast(device_type="cuda", dtype=torch.float16, enabled=True): if is_mode: encoded_latents = vae.encode(first_images_pixel_values).latent_dist.mode() else: encoded_latents = vae.encode(first_images_pixel_values).latent_dist.sample() encoded_latents.mul_(vae.config.scaling_factor)
B = encoded_latents.shape[0] C, H, W = encoded_latents.shape[1], encoded_latents.shape[3], encoded_latents.shape[4] cond_latents = torch.zeros(B, C, F, H, W, dtype=encoded_latents.dtype, device=encoded_latents.device) cond_latents[:, :, 1, :, :] = encoded_latents.squeeze(2)
return first_images_np, sampled_frames, cond_latents, first_image_pil_np1234567891011121314151617181920212223242526diffusers==0.35.0# NOTE: transformers must stay 5.x here: the base image preinstalls# huggingface-hub 1.16.1 (gradio 6.30 / spaces 0.51 need >=1.16), and every# transformers 4.x pins huggingface-hub<1.0 -> ResolutionImpossible.# transformers 5.x removed HybridCache, which peft 0.17 imports at module# scope; app.py shims transformers.HybridCache = StaticCache before the# diffusers/peft import chain runs.transformers[accelerate,tiktoken]==5.9.0acceleratepeft==0.17.0einops==0.8.0loguru==0.7.3qwen-vl-utils==0.0.8imageio==2.37.0imageio-ffmpeg==0.6.0decord==0.6.0safetensors>=0.5.3sentencepiecetorchvisionnumpy<2.3pillowpsutil# Prebuilt flash-attn 2 (FA3/FA4 impossible on sm_120) for ZeroGPU's Blackwell GPU.# The model config asks for attn_mode="flash3"; the repo's own fallback chain# picks FA2 when flash_attn is importable.https://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/flash_attn-2.8.3-cp312-cp312-linux_x86_64.whl1234567891011121314151617torchvisiondiffusers==0.35.2transformers[accelerate,tiktoken]==4.57.1peft==0.17.0acceleratesafetensorssentencepieceqwen-vl-utils==0.0.8einops==0.8.0numpypillowdecord==0.6.0imageio==2.37.0imageio-ffmpeg==0.6.0loguru==0.7.3psutilhttps://huggingface.co/datasets/multimodalart/zerogpu-blackwell-wheels/resolve/main/wheels/pt211-cu130-cp312/flash_attn-2.8.3-cp312-cp312-linux_x86_64.whl
1"""UniVEdit (vendored subset for the demo)."""1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232"""Sample preprocessing: resolution buckets, resize / crop / pad, frameselection, tensor conversion and the per-task sample builders."""
from __future__ import annotations
import randomfrom dataclasses import dataclassfrom typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as npimport PIL.Imageimport torchimport torchvision.transforms.functional as TFfrom PIL import Image, ImageFilterfrom torchvision import transforms
# Resolution buckets as (height, width).IMAGE_BUCKETS = ((624, 352), (576, 432), (480, 480), (432, 576), (352, 624))VIDEO_BUCKETS = ((480, 480), (352, 624), (624, 352))
# Frames of the static clip an image sample is presented as.IMAGE_CLIP_FRAMES = 5
CLIP_SAMPLING_MODES = ("first", "center_clip", "random_clip", "uniform")FRAME_SAMPLING_MODES = CLIP_SAMPLING_MODES + ("uniform_dup4",)
Bucket = Tuple[int, int]Sample = Dict[str, Any]
def choose_bucket(source_size: Tuple[int, int], target_size: Tuple[int, int], buckets: Sequence[Bucket]) -> Bucket: """Bucket (height, width) whose aspect ratio is closest to the mean of the source and target ratios; the two sizes are (width, height).""" ratio = (source_size[0] / source_size[1] + target_size[0] / target_size[1]) / 2.0 return min(buckets, key=lambda bucket: abs(bucket[1] / bucket[0] - ratio))
def _rgb(image: PIL.Image.Image) -> PIL.Image.Image: if not isinstance(image, PIL.Image.Image): raise TypeError(f"Expected a PIL image, got {type(image)}") return image.convert("RGB")
def resize_and_center_crop_image(image: Image.Image, target_height: int, target_width: int) -> Image.Image: """Scale an image to cover the target size and crop the center (source and target).""" width, height = image.size if target_height / height > target_width / width: resize_size = (target_height, int(width * target_height / height)) else: resize_size = (int(height * target_width / width), target_width) resize_crop = transforms.Compose([ transforms.Resize(resize_size, antialias=True), transforms.CenterCrop((target_height, target_width)), ]) return resize_crop(image)
def resize_and_pad_image( image: Image.Image, target_height: int, target_width: int) -> Image.Image: """Scale an image to fit the target size and pad it with a blurred extension of its edges (reference).""" width, height = image.size scale = min(target_width / width, target_height / height) resize_width = max(1, round(width * scale)) resize_height = max(1, round(height * scale)) resized = transforms.Resize((resize_height, resize_width), antialias=True)(image) if resize_width == target_width and resize_height == target_height: return resized
left = (target_width - resize_width) // 2 top = (target_height - resize_height) // 2 pad_right = target_width - resize_width - left pad_bottom = target_height - resize_height - top
arr = np.array(resized.convert("RGB")) padded = np.pad(arr, ((top, pad_bottom), (left, pad_right), (0, 0)), mode="edge") canvas = Image.fromarray(padded)
blur_radius = max(4.0, 0.03 * max(target_height, target_width)) canvas = canvas.filter(ImageFilter.GaussianBlur(radius=blur_radius)) canvas.paste(resized, (left, top)) return canvas
def image_to_tensor(image: PIL.Image.Image) -> torch.Tensor: """PIL RGB -> float tensor [3, H, W] in [-1, 1].""" return TF.normalize(TF.to_tensor(image), [0.5], [0.5])
def video_to_tensor(frames: Sequence[PIL.Image.Image]) -> torch.Tensor: """PIL RGB frames -> float tensor [3, F, H, W] in [-1, 1].""" return torch.stack([image_to_tensor(frame) for frame in frames], dim=1)
def num_frames_for_views(num_views: int) -> int: """Frame count of the 3d23d layout: view 0 once, every other view 4 times.""" return 4 * (num_views - 1) + 1
@dataclass(frozen=True)class FrameSampling: """Which ``num_frames`` frames of a video form a sample. ``uniform_dup4`` is the 3d23d layout; ``window`` is the number of consecutive frames its views span."""
num_frames: int mode: str = "random_clip" window: Optional[int] = None
def __post_init__(self): if self.num_frames < 1 or (self.num_frames - 1) % 4 != 0: raise ValueError(f"num_frames must be 4n+1 for the VAE, got {self.num_frames}") if self.mode not in FRAME_SAMPLING_MODES: raise ValueError(f"Unknown frame sampling mode '{self.mode}'. Expected one of {FRAME_SAMPLING_MODES}.")
def indices(self, total_frames: int, rng=random) -> List[int]: """Frame indices for a video of ``total_frames`` frames; a video shorter than ``num_frames`` returns all of its frames (except ``uniform_dup4``).""" if total_frames <= 0: raise ValueError("Video has no frames.") if self.mode == "uniform_dup4": return self._dup4_indices(total_frames, rng) if total_frames < self.num_frames: return list(range(total_frames)) if self.mode == "first": return list(range(self.num_frames)) if self.mode == "center_clip": start = (total_frames - self.num_frames) // 2 return list(range(start, start + self.num_frames)) if self.mode == "random_clip": start = rng.randint(0, total_frames - self.num_frames) return list(range(start, start + self.num_frames)) if self.num_frames == 1: return [total_frames // 2] return [round(i * (total_frames - 1) / (self.num_frames - 1)) for i in range(self.num_frames)]
def _dup4_indices(self, total_frames: int, rng) -> List[int]: num_views = (self.num_frames - 1) // 4 + 1 span = self.window or self.num_frames if total_frames > span: base = rng.randint(0, total_frames - span) length = span else: base, length = 0, total_frames if length < num_views: offsets = list(range(length)) + [length - 1] * (num_views - length) elif num_views == 1: offsets = [length // 2] else: offsets = [round(i * (length - 1) / (num_views - 1)) for i in range(num_views)] indices = [base + offsets[0]] for offset in offsets[1:]: indices.extend([base + offset] * 4) return indices
def sample_aligned_frames(source: Sequence, target: Sequence, sampling: FrameSampling, rng=random): """Pick the same frames from two frame-aligned videos; a clip shorter than ``sampling.num_frames`` is padded by repeating its last frame.""" if not source or not target: raise ValueError("source or target video has no frames.") if len(source) != len(target): raise ValueError( f"source and target are not frame-aligned: {len(source)} vs {len(target)} frames." ) indices = sampling.indices(len(source), rng) source_frames = [source[i] for i in indices] target_frames = [target[i] for i in indices] padding = sampling.num_frames - len(source_frames) source_frames.extend([source_frames[-1]] * padding) target_frames.extend([target_frames[-1]] * padding) return source_frames, target_frames
def semantic_inputs(source_frames: Sequence[PIL.Image.Image]): """Text-encoder inputs of a source clip: 4 / 6 / 8 uniformly sampled frames (Qwen2.5-VL) and the first frame as uint8 [H, W, 3] (SigLIP).""" total = min(len(source_frames), 161) count = 8 if total >= 24 * 4 else 6 if total >= 24 * 3 else 4 indices = np.linspace(0, total - 1, count).astype(int) source_sampled_frames = [source_frames[i] for i in indices] source_first_frame = np.array(source_frames[0], dtype=np.uint8) return source_sampled_frames, source_first_frame
def build_image_sample( text: str, source: PIL.Image.Image, target: PIL.Image.Image, *, reference: Optional[PIL.Image.Image] = None,) -> Sample: """i2i sample, or ti_i2i when ``reference`` is given: the image pair as a static clip of ``IMAGE_CLIP_FRAMES`` identical frames.""" height, width = choose_bucket(source.size, target.size, IMAGE_BUCKETS) target_pixels = image_to_tensor(resize_and_center_crop_image(_rgb(target), height, width)) sample: Sample = { "text": text, "target_pixels": target_pixels.unsqueeze(1).expand(-1, IMAGE_CLIP_FRAMES, -1, -1), "source_sequence": [resize_and_center_crop_image(_rgb(source), height, width)] * IMAGE_CLIP_FRAMES, } if reference is not None: sample["reference_image"] = resize_and_pad_image(_rgb(reference), height, width) return sample
def build_video_sample( text: str, source: Sequence[PIL.Image.Image], target: Sequence[PIL.Image.Image], sampling: FrameSampling, *, reference: Optional[PIL.Image.Image] = None, rng=random,) -> Sample: """v2v / 3d23d sample, or tiv2v when ``reference`` is given, from two frame-aligned videos.""" source_frames, target_frames = sample_aligned_frames(source, target, sampling, rng) height, width = choose_bucket(source_frames[0].size, target_frames[0].size, VIDEO_BUCKETS) source_frames = [resize_and_center_crop_image(_rgb(frame), height, width) for frame in source_frames] target_frames = [resize_and_center_crop_image(_rgb(frame), height, width) for frame in target_frames] source_sampled_frames, source_first_frame = semantic_inputs(source_frames) sample: Sample = { "text": text, "target_pixels": video_to_tensor(target_frames), "source_sequence": source_frames, "source_sampled_frames": source_sampled_frames, "source_first_frame": source_first_frame, } if reference is not None: sample["reference_image"] = resize_and_pad_image(_rgb(reference), height, width) return sample12345678910111213141516171819202122232425262728293031323334353637383940"""Modality special tokens and the task they belong to: <T_IMG> (i2i, ti_i2i),<T_VID> (v2v, tiv2v) and <T_3D> (3d23d)."""
from typing import Optional
T_IMG = "<T_IMG>"T_VID = "<T_VID>"T_3D = "<T_3D>"
SPECIAL_TOKENS = (T_IMG, T_VID, T_3D)
TASK_TYPE_TO_SPECIAL_TOKEN = { "i2i": T_IMG, "ti_i2i": T_IMG, "v2v": T_VID, "tiv2v": T_VID, "3d23d": T_3D,}
SUPPORTED_TASKS = tuple(TASK_TYPE_TO_SPECIAL_TOKEN)
def get_special_token_from_task( task_type: str, *, strict: bool = False,) -> Optional[str]: """Modality special token of a task type; an unknown task gives None, or ValueError with ``strict``.""" if not isinstance(task_type, str) or not task_type: if strict: raise ValueError("task_type must be a non-empty string.") return None
token = TASK_TYPE_TO_SPECIAL_TOKEN.get(task_type) if token is None and strict: raise ValueError(f"No special token is defined for task '{task_type}'.")
return token.gitattributes+7
License.txtAdded+78
Notice.txtAdded+34
README.md+20-30
app.py+433-435
examples/border_collie_running.mp4Added+3
examples/cat.mp4Added+3
examples/cat_tabby.jpgAdded

Large File Pointer Details
- SHA256: 7d17010bdc32ffc33df0e3fae71660db6e896ae759edb0202857120afda9f296
- Pointer size: 131 Bytes
- Size of remote file: 232 kB
examples/dog.jpgAdded

Large File Pointer Details
- SHA256: 6385da70b7991fc95287c5242c3e2addc982c35bd024582978b7edb2a1370838
- Pointer size: 131 Bytes
- Size of remote file: 114 kB
examples/lighthouse_coast.jpgAdded

Large File Pointer Details
- SHA256: 693c04eb5eaa62570b1fbdd5937f2a8837f34f7fdf20e15a3c21e5e872604096
- Pointer size: 131 Bytes
- Size of remote file: 217 kB
examples/living_room_blue_couch.jpgAdded

Large File Pointer Details
- SHA256: 31509acfb170d47fc181d7a1ead26c35081b53a7dc7ed14b4aedf02dea866dea
- Pointer size: 131 Bytes
- Size of remote file: 112 kB
examples/red_fox.jpgAdded

Large File Pointer Details
- SHA256: 286130138fec79ac754b641c2b8b51cc8709c1ce1202dcc33ef0becdc418064d
- Pointer size: 131 Bytes
- Size of remote file: 167 kB
examples/rubber_ducks.jpgAdded

hyvideo/__init__.pyAdded+44
hyvideo/commons/__init__.pyAdded+176
hyvideo/commons/infer_state.pyAdded+88
hyvideo/commons/parallel_states.pyAdded+93
hyvideo/models/__init__.pyAdded+16
hyvideo/models/autoencoders/__init__.pyAdded+17
hyvideo/models/autoencoders/hunyuanvideo_15_vae.pyAdded+898
hyvideo/models/text_encoders/__init__.pyAdded+911
hyvideo/models/text_encoders/byT5/__init__.pyAdded+229
hyvideo/models/text_encoders/byT5/format_prompt.pyAdded+86
hyvideo/models/transformers/hunyuanvideo_1_5_transformer.pyAdded+1015
hyvideo/models/transformers/modules/activation_layers.pyAdded+39
hyvideo/models/transformers/modules/attention.pyAdded+298
hyvideo/models/transformers/modules/embed_layers.pyAdded+213
hyvideo/models/transformers/modules/mlp_layers.pyAdded+137
hyvideo/models/transformers/modules/modulate_layers.pyAdded+92
hyvideo/models/transformers/modules/norm_layers.pyAdded+97
hyvideo/models/transformers/modules/posemb_layers.pyAdded+330
hyvideo/models/transformers/modules/ssta_attention.pyAdded+700
hyvideo/models/transformers/modules/token_refiner.pyAdded+283
hyvideo/models/vision_encoder/__init__.pyAdded+235
hyvideo/optim/muon.pyAdded+234
hyvideo/pipelines/hunyuan_video_pipeline.pyAdded
hyvideo/pipelines/pipeline_utils.pyAdded+101
hyvideo/schedulers/scheduling_flow_match_discrete.pyAdded+292
hyvideo/utils/communications.pyAdded+314
hyvideo/utils/data_utils.pyAdded+73
hyvideo/utils/flash_attn_no_pad.pyAdded+95
hyvideo/utils/multitask_utils.pyAdded+120
requirements.txt+11-20
univedit/__init__.pyAdded+1
univedit/data/__init__.pyAdded+1
univedit/data/preprocessing.pyAdded+232
univedit/tokens.pyAdded+40