├── .gitignore ├── LICENSE.md ├── README.md ├── assets ├── aud-sample-vs-1.wav ├── float-abstract.png ├── fps.png ├── sam_altman.webp ├── sam_altman_512x512.jpg └── sam_altman_result.mp4 ├── checkpoints └── checkpoints_here ├── download_checkpoints.sh ├── environments.sh ├── generate.py ├── models ├── __init__.py ├── float │ ├── FLOAT.py │ ├── FMT.py │ ├── encoder.py │ ├── generator.py │ └── styledecoder.py ├── wav2vec2.py └── wav2vec2_ser.py ├── options └── base_options.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | .DS_Store 3 | 4 | results/ 5 | experiments/ 6 | tmp/ 7 | *.pth 8 | *.pt 9 | wav2vec2-base-960h/ 10 | wav2vec-english-speech-emotion-recognition/ 11 | results/ 12 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # Attribution-NonCommercial 4.0 International 2 | 3 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 4 | 5 | ### Using Creative Commons Public Licenses 6 | 7 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 8 | 9 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 10 | 11 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 12 | 13 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 14 | 15 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 16 | 17 | ### Section 1 – Definitions. 18 | 19 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 20 | 21 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 22 | 23 | c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 24 | 25 | d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 26 | 27 | e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 28 | 29 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 30 | 31 | g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 32 | 33 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 34 | 35 | i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 36 | 37 | j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 38 | 39 | k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 40 | 41 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 42 | 43 | ### Section 2 – Scope. 44 | 45 | a. ___License grant.___ 46 | 47 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 48 | 49 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 50 | 51 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 52 | 53 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 54 | 55 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 56 | 57 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 58 | 59 | 5. __Downstream recipients.__ 60 | 61 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 62 | 63 | B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 64 | 65 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 66 | 67 | b. ___Other rights.___ 68 | 69 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 70 | 71 | 2. Patent and trademark rights are not licensed under this Public License. 72 | 73 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 74 | 75 | ### Section 3 – License Conditions. 76 | 77 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 78 | 79 | a. ___Attribution.___ 80 | 81 | 1. If You Share the Licensed Material (including in modified form), You must: 82 | 83 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 84 | 85 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 86 | 87 | ii. a copyright notice; 88 | 89 | iii. a notice that refers to this Public License; 90 | 91 | iv. a notice that refers to the disclaimer of warranties; 92 | 93 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 94 | 95 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 96 | 97 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 98 | 99 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 100 | 101 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 102 | 103 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 104 | 105 | ### Section 4 – Sui Generis Database Rights. 106 | 107 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 108 | 109 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 110 | 111 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 112 | 113 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 114 | 115 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 116 | 117 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 118 | 119 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 120 | 121 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 122 | 123 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 124 | 125 | ### Section 6 – Term and Termination. 126 | 127 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 128 | 129 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 130 | 131 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 132 | 133 | 2. upon express reinstatement by the Licensor. 134 | 135 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 136 | 137 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 138 | 139 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 140 | 141 | ### Section 7 – Other Terms and Conditions. 142 | 143 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 144 | 145 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 146 | 147 | ### Section 8 – Interpretation. 148 | 149 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 150 | 151 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 152 | 153 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 154 | 155 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 156 | 157 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 158 | > 159 | > Creative Commons may be contacted at creativecommons.org 160 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FLOAT: Generative Motion Latent Flow Matching for Audio-driven Talking Portrait 2 | Official Pytorch Implementation of FLOAT; Flow Matching for Audio-driven Talking Portrait Video Generation 3 | 4 | ![preview](./assets/float-abstract.png) 5 | 6 | **FLOAT: Generative Motion Latent Flow Matching for Audio-driven Talking Portrait**
7 | [Taekyung Ki](https://taekyungki.github.io), [Dongchan Min](https://kevinmin95.github.io), [Gyeongsu Chae](https://www.aistudios.com/ko) 8 | 9 | Project Page: https://deepbrainai-research.github.io/float/ 10 | 11 | **Abstract**: *With the rapid advancement of diffusion-based generative models, portrait image animation has achieved remarkable results. However, it still faces challenges in temporally consistent video generation and fast sampling due to its iterative sampling nature. This paper presents FLOAT, an audio-driven talking portrait video generation method based on flow matching generative model. We shift the generative modeling from the pixel-based latent space to a learned motion latent space, enabling efficient design of temporally consistent motion. To achieve this, we introduce a transformer-based vector field predictor with a simple yet effective frame-wise conditioning mechanism. Additionally, our method supports speech-driven emotion enhancement, enabling a natural incorporation of expressive motions. Extensive experiments demonstrate that our method outperforms state-of-the-art audio-driven talking portrait methods in terms of visual quality, motion fidelity, and efficiency.* 12 | 13 | **TL:DR: FLOAT is a flow matching based audio-driven talking portrait video generation method, which can enhance the speech-driven emotional motion.** 14 | 15 | ## Generation Results 16 | 17 | | Result 1 | Result 2 | 18 | |---------------|---------| 19 | | | | 20 | 21 | | Result 3 | Result 4 | 22 | |--------|-----------| 23 | | | | 24 | 25 |
26 | Our method runs faster than current diffusion-based methods with fewer sampling steps and lower memory cost. For more details, please refer to the paper. 27 |
28 | 29 |
30 | 31 | 32 | 33 | ## Updates 34 | - [2025.02.17] The inference code and checkpoints are released under a **[Non-commercial License](https://creativecommons.org/licenses/by-nc-nd/4.0/)**. 35 | - [2024.12.03] Selected as a [HuggingFace Daily Papers](https://huggingface.co/papers?date=2024-12-03) on December 3, 2024. 36 | - [2024.12.02] The paper is publicly available on [ArXiv](https://arxiv.org/abs/2412.01064). 37 | 38 | 39 | ## Getting Started 40 | ### Requirements 41 | ```.bash 42 | # 1. Create Conda Environment 43 | conda create -n FLOAT python=3.8.5 44 | conda activate FLOAT 45 | 46 | # 2. Install torch and requirements 47 | sh environments.sh 48 | 49 | # or manual installation 50 | pip install torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu118 51 | pip install -r requirements.txt 52 | ``` 53 | - Test on Linux, A100 GPU, and V100 GPU. 54 | 55 | ### Preparing checkpoints 56 | 57 | 1. Download checkpints automatically 58 | 59 | ```.bash 60 | sh download_checkpoints.sh 61 | ``` 62 | 63 | or download checkpoints manually from this [google-drive](https://drive.google.com/file/d/1rvWuM12cyvNvBQNCLmG4Fr2L1rpjQBF0/view?usp=sharing). 64 | 65 | 2. The checkpoints should be organized as follows: 66 | ```.bash 67 | ./checkpints 68 | |-- checkpoints_here 69 | |-- float.pth # main model 70 | |-- wav2vec2-base-960h/ # audio encoder 71 | | |-- .gitattributes 72 | | |-- config.json 73 | | |-- feature_extractor_config.json 74 | | |-- model.safetensors 75 | | |-- preprocessor_config.json 76 | | |-- pytorch_model.bin 77 | | |-- README.md 78 | | |-- special_tokens_map.json 79 | | |-- tf_model.h5 80 | | |-- tokenizer_config.json 81 | | '-- vocab.json 82 | '-- wav2vec-english-speech-emotion-recognition/ # emotion encoder 83 | |-- .gitattributes 84 | |-- config.json 85 | |-- preprocessor_config.json 86 | |-- pytorch_model.bin 87 | |-- README.md 88 | '-- training_args.bin 89 | ``` 90 | - W2V based models could be found in the links: [wav2vec2-base-960h](https://huggingface.co/facebook/wav2vec2-base-960h) and [wav2vec-english-speech-emotion-recognition](https://huggingface.co/r-f/wav2vec-english-speech-emotion-recognition). 91 | 92 | 93 | ### Generating Talking Portait Video from Single Image and Audio 94 | 1. Pre-process;❗ **Important** ❗ for better quality. Please read this. 95 | - FLOAT is trained on the frontal head pose distributions. Non-frontal image may lead to suboptimal results. 96 | - The performance of taking portrait methods often depends on their training preprocess strategies, e.g., the field-of-view. The inference code includes an automatic face-cropping function, which may involve black **padding** regions. You can manually disable the cropping process in `generate.py`, however it may lead to suboptimal performance. 97 | - If your audio contains heavy background music, please use [ClearVoice](https://github.com/modelscope/ClearerVoice-Studio) to extract the vocals for better performance. 98 | 99 | 100 | 1. Generating video 1 (Emotion from Audio) 101 | 102 | You can generate a video with an emotion from audio without specifying `--emo`. You can adjust the intensity of the emotion using `--e_cfg_scale` (default 1). For more emotion intensive video, try large value from 5 to 10 for `--e_cfg_scale`. 103 | ```.bash 104 | CUDA_VISIBLE_DEVICES=0 python generate.py 105 | --ref_path path/to/reference/image \ 106 | --aud_path path/to/audio \ 107 | --seed 15 \ 108 | --a_cfg_scale 2 \ 109 | --e_cfg_scale 1 \ 110 | --ckpt_path ./checkpoints/float.pth 111 | --no_crop # [optional] skip cropping 112 | ``` 113 | 114 | 2. Generate video 2 (Redirecting Emotion) 115 | You can generate a video of other emotion by specifying `--emo`. It supports seven basic emotions: ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']. You can adjust the intensity of the emotion using `--e_cfg_scale` (default 1). For more emotion intensive video, try large value from 5 to 10 for `--e_cfg_scale`. 116 | ```.bash 117 | CUDA_VISIBLE_DEVICES=0 python generate.py\ 118 | --ref_path path/to/reference/image \ 119 | --aud_path path/to/audio \ 120 | --emo 'happy' \ # Seven emotions ['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise'] 121 | --seed 15 \ 122 | --a_cfg_scale 2 \ 123 | --e_cfg_scale 1 \ 124 | --ckpt_path ./checkpoints/float.pth \ 125 | --no_crop # [optional] skip cropping 126 | ``` 127 | 128 | 129 | 130 | 131 | 3. Running example and results 132 | ```.bash 133 | CUDA_VISIBLE_DEVICES=0 python generate.py \ 134 | --ref_path assets/sam_altman.webp \ 135 | --aud_path assets/aud-sample-vs-1.wav \ 136 | --seed 15 \ 137 | --a_cfg_scale 2 \ 138 | --e_cfg_scale 1 \ 139 | --ckpt_path ./checkpoints/float.pth 140 | ``` 141 | 142 | 143 | | Before Crop | After Crop | Result | 144 | |---------------|---------|--------| 145 | | ![](assets/sam_altman.webp) | ![](assets/sam_altman_512x512.jpg) | | 146 | 147 |
148 | 149 | ## ❗License❗ 150 | This work is licensed under a [Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License](https://creativecommons.org/licenses/by-nc-nd/4.0/). You may not use this work for commercial purposes and may use it only for research purposes. **For any commercial inquiries or collaboration opportunities**, please contact daniel@deepbrain.io. 151 | 152 | 153 | ## Development 154 | This repository is a research demonstration implementation and is provided as a one-time code drop. For any research-related inquiries, please contact the first author [Taekyung Ki](https://github.com/TaekyungKi). This work was done during the first author's South Korean Alternative Military Service at DeepBrain AI. This repository includes only the inference code; the training code will not be released. 155 | 156 | ## Citation 157 | ```bibtex 158 | @article{ki2024float, 159 | title={FLOAT: Generative Motion Latent Flow Matching for Audio-driven Talking Portrait}, 160 | author={Ki, Taekyung and Min, Dongchan and Chae, Gyeongsu}, 161 | journal={arXiv preprint arXiv:2412.01064}, 162 | year={2024} 163 | } 164 | ``` 165 | 166 | ## Related Works 167 | - [StyleLipSync: Style-based Personalized Lip-sync Video Generation](https://arxiv.org/abs/2305.00521)
168 | - [StyleTalker: One-shot Style-based Audo-driven Talking Head Video Generation](https://arxiv.org/abs/2208.10922)
169 | - [Export3D: Learning to Generate Conditional Tri-plane for 3D-aware Expression Controllable Portrait Animation](https://arxiv.org/abs/2404.00636)
170 | 171 | ## Acknowledgements 172 | 173 | The source images and audio are collected from the internet and other baselines, such as SadTalker, EMO, VASA-1, Hallo, LivePortrait, Loopy, and others. We appreciate their valuable contributions to this field. We employ Wav2Vec2.0-based speech emotion recognizer by [Rob Field](https://huggingface.co/r-f/wav2vec-english-speech-emotion-recognition). We appreciate this good work. 174 | -------------------------------------------------------------------------------- /assets/aud-sample-vs-1.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepbrainai-research/float/98bdbcab20ea1f4a31d9dc5fd13ea6f0e1b961c8/assets/aud-sample-vs-1.wav -------------------------------------------------------------------------------- /assets/float-abstract.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepbrainai-research/float/98bdbcab20ea1f4a31d9dc5fd13ea6f0e1b961c8/assets/float-abstract.png -------------------------------------------------------------------------------- /assets/fps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepbrainai-research/float/98bdbcab20ea1f4a31d9dc5fd13ea6f0e1b961c8/assets/fps.png -------------------------------------------------------------------------------- /assets/sam_altman.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepbrainai-research/float/98bdbcab20ea1f4a31d9dc5fd13ea6f0e1b961c8/assets/sam_altman.webp -------------------------------------------------------------------------------- /assets/sam_altman_512x512.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepbrainai-research/float/98bdbcab20ea1f4a31d9dc5fd13ea6f0e1b961c8/assets/sam_altman_512x512.jpg -------------------------------------------------------------------------------- /assets/sam_altman_result.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepbrainai-research/float/98bdbcab20ea1f4a31d9dc5fd13ea6f0e1b961c8/assets/sam_altman_result.mp4 -------------------------------------------------------------------------------- /checkpoints/checkpoints_here: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepbrainai-research/float/98bdbcab20ea1f4a31d9dc5fd13ea6f0e1b961c8/checkpoints/checkpoints_here -------------------------------------------------------------------------------- /download_checkpoints.sh: -------------------------------------------------------------------------------- 1 | pip install gdown 2 | 3 | gdown --id 1rvWuM12cyvNvBQNCLmG4Fr2L1rpjQBF0 4 | 5 | mv float.pth checkpoints/ 6 | -------------------------------------------------------------------------------- /environments.sh: -------------------------------------------------------------------------------- 1 | pip install torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu118 2 | 3 | pip install -r requirements.txt 4 | -------------------------------------------------------------------------------- /generate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Inference Stage 2 3 | """ 4 | 5 | import os, torch, random, cv2, torchvision, subprocess, librosa, datetime, tempfile, face_alignment 6 | import numpy as np 7 | import albumentations as A 8 | import albumentations.pytorch.transforms as A_pytorch 9 | 10 | from tqdm import tqdm 11 | from pathlib import Path 12 | from transformers import Wav2Vec2FeatureExtractor 13 | 14 | from models.float.FLOAT import FLOAT 15 | from options.base_options import BaseOptions 16 | 17 | 18 | class DataProcessor: 19 | def __init__(self, opt): 20 | self.opt = opt 21 | self.fps = opt.fps 22 | self.sampling_rate = opt.sampling_rate 23 | self.input_size = opt.input_size 24 | 25 | self.fa = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, flip_input=False) 26 | 27 | # wav2vec2 audio preprocessor 28 | self.wav2vec_preprocessor = Wav2Vec2FeatureExtractor.from_pretrained(opt.wav2vec_model_path, local_files_only=True) 29 | 30 | # image transform 31 | self.transform = A.Compose([ 32 | A.Resize(height=opt.input_size, width=opt.input_size, interpolation=cv2.INTER_AREA), 33 | A.Normalize(mean=(0.5,0.5,0.5), std=(0.5,0.5,0.5)), 34 | A_pytorch.ToTensorV2(), 35 | ]) 36 | 37 | @torch.no_grad() 38 | def process_img(self, img:np.ndarray) -> np.ndarray: 39 | mult = 360. / img.shape[0] 40 | 41 | resized_img = cv2.resize(img, dsize=(0, 0), fx = mult, fy = mult, interpolation=cv2.INTER_AREA if mult < 1. else cv2.INTER_CUBIC) 42 | bboxes = self.fa.face_detector.detect_from_image(resized_img) 43 | bboxes = [(int(x1 / mult), int(y1 / mult), int(x2 / mult), int(y2 / mult), score) for (x1, y1, x2, y2, score) in bboxes if score > 0.95] 44 | bboxes = bboxes[0] # Just use first bbox 45 | 46 | bsy = int((bboxes[3] - bboxes[1]) / 2) 47 | bsx = int((bboxes[2] - bboxes[0]) / 2) 48 | my = int((bboxes[1] + bboxes[3]) / 2) 49 | mx = int((bboxes[0] + bboxes[2]) / 2) 50 | 51 | bs = int(max(bsy, bsx) * 1.6) 52 | img = cv2.copyMakeBorder(img, bs, bs, bs, bs, cv2.BORDER_CONSTANT, value=0) 53 | my, mx = my + bs, mx + bs # BBox center y, bbox center x 54 | 55 | crop_img = img[my - bs:my + bs,mx - bs:mx + bs] 56 | crop_img = cv2.resize(crop_img, dsize = (self.input_size, self.input_size), interpolation = cv2.INTER_AREA if mult < 1. else cv2.INTER_CUBIC) 57 | return crop_img 58 | 59 | def default_img_loader(self, path) -> np.ndarray: 60 | img = cv2.imread(path) 61 | return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 62 | 63 | def default_aud_loader(self, path: str) -> torch.Tensor: 64 | speech_array, sampling_rate = librosa.load(path, sr = self.sampling_rate) 65 | return self.wav2vec_preprocessor(speech_array, sampling_rate = sampling_rate, return_tensors = 'pt').input_values[0] 66 | 67 | 68 | def preprocess(self, ref_path:str, audio_path:str, no_crop:bool) -> dict: 69 | s = self.default_img_loader(ref_path) 70 | if not no_crop: 71 | s = self.process_img(s) 72 | s = self.transform(image=s)['image'].unsqueeze(0) 73 | a = self.default_aud_loader(audio_path).unsqueeze(0) 74 | return {'s': s, 'a': a, 'p': None, 'e': None} 75 | 76 | 77 | class InferenceAgent: 78 | def __init__(self, opt): 79 | torch.cuda.empty_cache() 80 | self.opt = opt 81 | self.rank = opt.rank 82 | 83 | # Load Model 84 | self.load_model() 85 | self.load_weight(opt.ckpt_path, rank=self.rank) 86 | self.G.to(self.rank) 87 | self.G.eval() 88 | 89 | # Load Data Processor 90 | self.data_processor = DataProcessor(opt) 91 | 92 | def load_model(self) -> None: 93 | self.G = FLOAT(self.opt) 94 | 95 | def load_weight(self, checkpoint_path: str, rank: int) -> None: 96 | state_dict = torch.load(checkpoint_path, map_location='cpu', weights_only=True) 97 | with torch.no_grad(): 98 | for model_name, model_param in self.G.named_parameters(): 99 | if model_name in state_dict: 100 | model_param.copy_(state_dict[model_name].to(rank)) 101 | elif "wav2vec2" in model_name: pass 102 | else: 103 | print(f"! Warning; {model_name} not found in state_dict.") 104 | 105 | del state_dict 106 | 107 | def save_video(self, vid_target_recon: torch.Tensor, video_path: str, audio_path: str) -> str: 108 | with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video: 109 | temp_filename = temp_video.name 110 | vid = vid_target_recon.permute(0, 2, 3, 1) 111 | vid = vid.detach().clamp(-1, 1).cpu() 112 | vid = ((vid + 1) / 2 * 255).type('torch.ByteTensor') 113 | torchvision.io.write_video(temp_filename, vid, fps=self.opt.fps) 114 | if audio_path is not None: 115 | with open(os.devnull, 'wb') as f: 116 | command = "ffmpeg -i {} -i {} -c:v copy -c:a aac {} -y".format(temp_filename, audio_path, video_path) 117 | subprocess.call(command, shell=True, stdout=f, stderr=f) 118 | if os.path.exists(video_path): 119 | os.remove(temp_filename) 120 | else: 121 | os.rename(temp_filename, video_path) 122 | return video_path 123 | 124 | @torch.no_grad() 125 | def run_inference( 126 | self, 127 | res_video_path: str, 128 | ref_path: str, 129 | audio_path: str, 130 | a_cfg_scale: float = 2.0, 131 | r_cfg_scale: float = 1.0, 132 | e_cfg_scale: float = 1.0, 133 | emo: str = 'S2E', 134 | nfe: int = 10, 135 | no_crop: bool = False, 136 | seed: int = 25, 137 | verbose: bool = False 138 | ) -> str: 139 | 140 | data = self.data_processor.preprocess(ref_path, audio_path, no_crop = no_crop) 141 | if verbose: print(f"> [Done] Preprocess.") 142 | 143 | # inference 144 | d_hat = self.G.inference( 145 | data = data, 146 | a_cfg_scale = a_cfg_scale, 147 | r_cfg_scale = r_cfg_scale, 148 | e_cfg_scale = e_cfg_scale, 149 | emo = emo, 150 | nfe = nfe, 151 | seed = seed 152 | )['d_hat'] 153 | 154 | res_video_path = self.save_video(d_hat, res_video_path, audio_path) 155 | if verbose: print(f"> [Done] result saved at {res_video_path}") 156 | return res_video_path 157 | 158 | 159 | class InferenceOptions(BaseOptions): 160 | def __init__(self): 161 | super().__init__() 162 | 163 | def initialize(self, parser): 164 | super().initialize(parser) 165 | parser.add_argument("--ref_path", 166 | default=None, type=str,help='ref') 167 | parser.add_argument('--aud_path', 168 | default=None, type=str, help='audio') 169 | parser.add_argument('--emo', 170 | default=None, type=str, help='emotion', choices=['angry', 'disgust', 'fear', 'happy', 'neutral', 'sad', 'surprise']) 171 | parser.add_argument('--no_crop', 172 | action = 'store_true', help = 'not using crop') 173 | parser.add_argument('--res_video_path', 174 | default=None, type=str, help='res video path') 175 | parser.add_argument('--ckpt_path', 176 | default="/home/nvadmin/workspace/taek/float-pytorch/checkpoints/float.pth", type=str, help='checkpoint path') 177 | parser.add_argument('--res_dir', 178 | default="./results", type=str, help='result dir') 179 | return parser 180 | 181 | 182 | if __name__ == '__main__': 183 | opt = InferenceOptions().parse() 184 | opt.rank, opt.ngpus = 0,1 185 | agent = InferenceAgent(opt) 186 | os.makedirs(opt.res_dir, exist_ok = True) 187 | 188 | # -------------- input ------------- 189 | ref_path = opt.ref_path 190 | aud_path = opt.aud_path 191 | # ---------------------------------- 192 | 193 | if opt.res_video_path is None: 194 | video_name = os.path.splitext(os.path.basename(ref_path))[0] 195 | audio_name = os.path.splitext(os.path.basename(aud_path))[0] 196 | call_time = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S") 197 | res_video_path = os.path.join(opt.res_dir, "%s-%s-%s-nfe%s-seed%s-acfg%s-ecfg%s-%s.mp4" \ 198 | % (call_time, video_name, audio_name, opt.nfe, opt.seed, opt.a_cfg_scale, opt.e_cfg_scale, opt.emo)) 199 | else: 200 | res_video_path = opt.res_video_path 201 | 202 | agent.run_inference( 203 | res_video_path, 204 | ref_path, 205 | aud_path, 206 | a_cfg_scale = opt.a_cfg_scale, 207 | r_cfg_scale = opt.r_cfg_scale, 208 | e_cfg_scale = opt.e_cfg_scale, 209 | emo = opt.emo, 210 | nfe = opt.nfe, 211 | no_crop = opt.no_crop, 212 | seed = opt.seed 213 | ) 214 | 215 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from transformers import Wav2Vec2Config, Wav2Vec2Model 5 | from transformers.modeling_outputs import BaseModelOutput 6 | 7 | 8 | from torch import Tensor 9 | from typing import Type, Any, Callable, Union, List, Optional 10 | 11 | 12 | class BaseModel(torch.nn.Module): 13 | def __init__(self): 14 | super().__init__() 15 | 16 | def print_architecture(self, verbose=False): 17 | name = type(self).__name__ 18 | result = '-------------------%s---------------------\n' % name 19 | total_num_params = 0 20 | for i, (name, child) in enumerate(self.named_children()): 21 | if 'loss' in name: 22 | continue 23 | num_params = sum([p.numel() for p in child.parameters()]) 24 | total_num_params += num_params 25 | if verbose: 26 | result += "%s: %3.3fM\n" % (name, (num_params / 1e6)) 27 | for i, (name, grandchild) in enumerate(child.named_children()): 28 | num_params = sum([p.numel() for p in grandchild.parameters()]) 29 | if verbose: 30 | result += "\t%s: %3.3fM\n" % (name, (num_params / 1e6)) 31 | result += '[Network %s] Total number of parameters : %.3f M\n' % (name, total_num_params / 1e6) 32 | result += '-----------------------------------------------\n' 33 | print(result) 34 | 35 | def set_requires_grad(self, requires_grad): 36 | for param in self.parameters(): 37 | param.requires_grad = requires_grad 38 | 39 | def get_parameters_for_train(self): 40 | return self.parameters() 41 | 42 | def forward(self): 43 | raise NotImplementedError() 44 | 45 | 46 | 47 | # def linear_interpolation(features, seq_len): 48 | # features = features.transpose(1, 2) 49 | # output_features = F.interpolate(features, size=seq_len, align_corners=True, mode='linear') 50 | # return output_features.transpose(1, 2) 51 | 52 | 53 | # class Wav2Vec2Model(Wav2Vec2Model): 54 | # def __init__(self, config: Wav2Vec2Config): 55 | # super().__init__(config) 56 | 57 | # def forward( 58 | # self, 59 | # input_values, 60 | # seq_len, 61 | # attention_mask=None, 62 | # mask_time_indices=None, 63 | # output_attentions=None, 64 | # output_hidden_states=None, 65 | # return_dict=None, 66 | # ): 67 | # self.config.output_attentions = True 68 | 69 | # output_hidden_states = ( 70 | # output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states 71 | # ) 72 | # return_dict = return_dict if return_dict is not None else self.config.use_return_dict 73 | 74 | # extract_features = self.feature_extractor(input_values) 75 | # extract_features = extract_features.transpose(1, 2) 76 | # extract_features = linear_interpolation(extract_features, seq_len=seq_len) 77 | 78 | # if attention_mask is not None: 79 | # # compute reduced attention_mask corresponding to feature vectors 80 | # attention_mask = self._get_feature_vector_attention_mask( 81 | # extract_features.shape[1], attention_mask, add_adapter=False 82 | # ) 83 | 84 | # hidden_states, extract_features = self.feature_projection(extract_features) 85 | # hidden_states = self._mask_hidden_states( 86 | # hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask 87 | # ) 88 | 89 | # encoder_outputs = self.encoder( 90 | # hidden_states, 91 | # attention_mask=attention_mask, 92 | # output_attentions=output_attentions, 93 | # output_hidden_states=output_hidden_states, 94 | # return_dict=return_dict, 95 | # ) 96 | 97 | # hidden_states = encoder_outputs[0] 98 | 99 | # if self.adapter is not None: 100 | # hidden_states = self.adapter(hidden_states) 101 | 102 | # if not return_dict: 103 | # return (hidden_states, ) + encoder_outputs[1:] 104 | # return BaseModelOutput( 105 | # last_hidden_state=hidden_states, 106 | # hidden_states=encoder_outputs.hidden_states, 107 | # attentions=encoder_outputs.attentions, 108 | # ) 109 | 110 | 111 | # def feature_extract( 112 | # self, 113 | # input_values, 114 | # seq_len, 115 | # ): 116 | # extract_features = self.feature_extractor(input_values) 117 | # extract_features = extract_features.transpose(1, 2) 118 | # extract_features = linear_interpolation(extract_features, seq_len=seq_len) 119 | 120 | # return extract_features 121 | 122 | # def encode( 123 | # self, 124 | # extract_features, 125 | # attention_mask=None, 126 | # mask_time_indices=None, 127 | # output_attentions=None, 128 | # output_hidden_states=None, 129 | # return_dict=None, 130 | # ): 131 | # self.config.output_attentions = True 132 | 133 | # output_hidden_states = ( 134 | # output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states 135 | # ) 136 | # return_dict = return_dict if return_dict is not None else self.config.use_return_dict 137 | 138 | # if attention_mask is not None: 139 | # # compute reduced attention_mask corresponding to feature vectors 140 | # attention_mask = self._get_feature_vector_attention_mask( 141 | # extract_features.shape[1], attention_mask, add_adapter=False 142 | # ) 143 | 144 | 145 | # hidden_states, extract_features = self.feature_projection(extract_features) 146 | # hidden_states = self._mask_hidden_states( 147 | # hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask 148 | # ) 149 | 150 | # encoder_outputs = self.encoder( 151 | # hidden_states, 152 | # attention_mask=attention_mask, 153 | # output_attentions=output_attentions, 154 | # output_hidden_states=output_hidden_states, 155 | # return_dict=return_dict, 156 | # ) 157 | 158 | # hidden_states = encoder_outputs[0] 159 | 160 | # if self.adapter is not None: 161 | # hidden_states = self.adapter(hidden_states) 162 | 163 | # if not return_dict: 164 | # return (hidden_states, ) + encoder_outputs[1:] 165 | # return BaseModelOutput( 166 | # last_hidden_state=hidden_states, 167 | # hidden_states=encoder_outputs.hidden_states, 168 | # attentions=encoder_outputs.attentions, 169 | # ) 170 | 171 | 172 | 173 | 174 | 175 | def conv3x3(in_planes, out_planes, stride=1): 176 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) 177 | 178 | def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d: 179 | return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) 180 | 181 | 182 | class SELayer(nn.Module): 183 | def __init__(self, channel, reduction=16): 184 | super(SELayer, self).__init__() 185 | self.avg_pool = nn.AdaptiveAvgPool2d(1) 186 | self.fc = nn.Sequential( 187 | nn.Linear(channel, channel // reduction, bias=False), 188 | nn.ReLU(inplace=True), 189 | nn.Linear(channel // reduction, channel, bias=False), 190 | nn.Sigmoid() 191 | ) 192 | 193 | def forward(self, x): 194 | b, c, _, _ = x.size() 195 | y = self.avg_pool(x).view(b, c) 196 | y = self.fc(y).view(b, c, 1, 1) 197 | return x * y.expand_as(x) 198 | 199 | 200 | class SEBasicBlock(nn.Module): 201 | expansion = 1 202 | 203 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 204 | base_width=64, dilation=1, norm_layer=None, 205 | *, reduction=16): 206 | super(SEBasicBlock, self).__init__() 207 | if norm_layer is None: 208 | norm_layer = nn.BatchNorm2d 209 | self.conv1 = conv3x3(inplanes, planes, stride) 210 | self.bn1 = norm_layer(planes) 211 | self.relu = nn.ReLU(inplace=True) 212 | self.conv2 = conv3x3(planes, planes, 1) 213 | self.bn2 = norm_layer(planes) 214 | self.se = SELayer(planes, reduction) 215 | self.downsample = downsample 216 | self.stride = stride 217 | 218 | def forward(self, x): 219 | residual = x 220 | out = self.conv1(x) 221 | out = self.bn1(out) 222 | out = self.relu(out) 223 | 224 | out = self.conv2(out) 225 | out = self.bn2(out) 226 | out = self.se(out) 227 | 228 | if self.downsample is not None: 229 | residual = self.downsample(x) 230 | 231 | out += residual 232 | out = self.relu(out) 233 | 234 | return out 235 | 236 | 237 | class SEBottleneck(nn.Module): 238 | expansion = 4 239 | 240 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 241 | base_width=64, dilation=1, norm_layer=None, 242 | *, reduction=16): 243 | super(SEBottleneck, self).__init__() 244 | if norm_layer is None: 245 | norm_layer= nn.BatchNorm2d 246 | self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) 247 | self.bn1 = norm_layer(planes) 248 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 249 | self.bn2 = norm_layer(planes) 250 | self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False) 251 | self.bn3 = norm_layer(planes * 4) 252 | self.relu = nn.ReLU(inplace=True) 253 | self.se = SELayer(planes * 4, reduction) 254 | self.downsample = downsample 255 | self.stride = stride 256 | 257 | def forward(self, x): 258 | residual = x 259 | 260 | out = self.conv1(x) 261 | out = self.bn1(out) 262 | out = self.relu(out) 263 | 264 | out = self.conv2(out) 265 | out = self.bn2(out) 266 | out = self.relu(out) 267 | 268 | out = self.conv3(out) 269 | out = self.bn3(out) 270 | out = self.se(out) 271 | 272 | if self.downsample is not None: 273 | residual = self.downsample(x) 274 | 275 | out += residual 276 | out = self.relu(out) 277 | 278 | return out 279 | 280 | 281 | class ResNet(nn.Module): 282 | def __init__( 283 | self, 284 | block: Type[Union[SEBasicBlock, SEBottleneck]], 285 | layers: List[int], 286 | num_classes: int = 1000, 287 | zero_init_residual: bool = False, 288 | groups: int = 1, 289 | width_per_group: int = 64, 290 | replace_stride_with_dilation: Optional[List[bool]] = None, 291 | norm_layer: Optional[Callable[..., nn.Module]] = None, 292 | ) -> None: 293 | super().__init__() 294 | if norm_layer is None: 295 | norm_layer = nn.BatchNorm2d 296 | self._norm_layer = norm_layer 297 | 298 | self.inplanes = 64 299 | self.dilation = 1 300 | if replace_stride_with_dilation is None: 301 | # each element in the tuple indicates if we should replace 302 | # the 2x2 stride with a dilated convolution instead 303 | replace_stride_with_dilation = [False, False, False] 304 | if len(replace_stride_with_dilation) != 3: 305 | raise ValueError( 306 | "replace_stride_with_dilation should be None " 307 | f"or a 3-element tuple, got {replace_stride_with_dilation}" 308 | ) 309 | self.groups = groups 310 | self.base_width = width_per_group 311 | 312 | self.stem = nn.Sequential( 313 | nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False), 314 | norm_layer(self.inplanes), 315 | nn.ReLU(inplace=True), 316 | nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 317 | ) 318 | 319 | self.layer1 = self._make_layer(block, 64, layers[0]) 320 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0]) 321 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1]) 322 | self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2]) 323 | 324 | self.fc = nn.Sequential( 325 | nn.AdaptiveAvgPool2d((1, 1)), 326 | nn.Flatten(), 327 | nn.Linear(512 * block.expansion, num_classes) 328 | ) 329 | 330 | for m in self.modules(): 331 | if isinstance(m, nn.Conv2d): 332 | nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu") 333 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 334 | nn.init.constant_(m.weight, 1) 335 | nn.init.constant_(m.bias, 0) 336 | 337 | # Zero-initialize the last BN in each residual branch, 338 | # so that the residual branch starts with zeros, and each residual block behaves like an identity. 339 | # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 340 | if zero_init_residual: 341 | for m in self.modules(): 342 | if isinstance(m, SEBottleneck): 343 | nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type] 344 | elif isinstance(m, SEBasicBlock): 345 | nn.init.constant_(m.bn2.weight, 0) # type: ignore[arg-type] 346 | 347 | def _make_layer( 348 | self, 349 | block: Type[Union[SEBasicBlock, SEBottleneck]], 350 | planes: int, 351 | blocks: int, 352 | stride: int = 1, 353 | dilate: bool = False, 354 | ) -> nn.Sequential: 355 | norm_layer = self._norm_layer 356 | downsample = None 357 | previous_dilation = self.dilation 358 | if dilate: 359 | self.dilation *= stride 360 | stride = 1 361 | if stride != 1 or self.inplanes != planes * block.expansion: 362 | downsample = nn.Sequential( 363 | conv1x1(self.inplanes, planes * block.expansion, stride), 364 | norm_layer(planes * block.expansion), 365 | ) 366 | 367 | layers = [] 368 | layers.append( 369 | block( 370 | self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer 371 | ) 372 | ) 373 | self.inplanes = planes * block.expansion 374 | for _ in range(1, blocks): 375 | layers.append( 376 | block( 377 | self.inplanes, 378 | planes, 379 | groups=self.groups, 380 | base_width=self.base_width, 381 | dilation=self.dilation, 382 | norm_layer=norm_layer, 383 | ) 384 | ) 385 | 386 | return nn.Sequential(*layers) 387 | 388 | def _forward_impl(self, x: Tensor) -> Tensor: 389 | x = self.stem(x) 390 | 391 | x = self.layer1(x) 392 | x = self.layer2(x) 393 | x = self.layer3(x) 394 | x = self.layer4(x) 395 | 396 | x = self.fc(x) 397 | return x 398 | 399 | def forward(self, x: Tensor) -> Tensor: 400 | return self._forward_impl(x) 401 | 402 | 403 | 404 | 405 | def se_resnet18(num_classes=1000, norm_layer=None): 406 | """Constructs a ResNet-18 model. 407 | Args: 408 | pretrained (bool): If True, returns a model pre-trained on ImageNet 409 | """ 410 | model = ResNet(SEBasicBlock, [2, 2, 2, 2], num_classes=num_classes, norm_layer=norm_layer) 411 | return model 412 | 413 | 414 | def se_resnet34(num_classes=1000, norm_layer=None): 415 | """Constructs a ResNet-34 model. 416 | Args: 417 | pretrained (bool): If True, returns a model pre-trained on ImageNet 418 | """ 419 | model = ResNet(SEBasicBlock, [3, 4, 6, 3], num_classes=num_classes, norm_layer=norm_layer) 420 | return model 421 | 422 | 423 | def se_resnet50(num_classes=1000, pretrained=False): 424 | """Constructs a ResNet-50 model. 425 | Args: 426 | pretrained (bool): If True, returns a model pre-trained on ImageNet 427 | """ 428 | model = ResNet(SEBottleneck, [3, 4, 6, 3], num_classes=num_classes) 429 | return model 430 | 431 | 432 | def se_resnet101(num_classes=1000): 433 | """Constructs a ResNet-101 model. 434 | Args: 435 | pretrained (bool): If True, returns a model pre-trained on ImageNet 436 | """ 437 | model = ResNet(SEBottleneck, [3, 4, 23, 3], num_classes=num_classes) 438 | return model 439 | 440 | 441 | def se_resnet152(num_classes=1000): 442 | """Constructs a ResNet-152 model. 443 | Args: 444 | pretrained (bool): If True, returns a model pre-trained on ImageNet 445 | """ 446 | model = ResNet(SEBottleneck, [3, 8, 36, 3], num_classes=num_classes) 447 | return model -------------------------------------------------------------------------------- /models/float/FLOAT.py: -------------------------------------------------------------------------------- 1 | import torch, math 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from torchdiffeq import odeint 6 | from transformers import Wav2Vec2Config 7 | from transformers.modeling_outputs import BaseModelOutput 8 | 9 | from models.wav2vec2 import Wav2VecModel 10 | from models.wav2vec2_ser import Wav2Vec2ForSpeechClassification 11 | 12 | from models import BaseModel 13 | from models.float.generator import Generator 14 | from models.float.FMT import FlowMatchingTransformer 15 | 16 | ######## Main Phase 2 model ######## 17 | class FLOAT(BaseModel): 18 | def __init__(self, opt): 19 | super().__init__() 20 | self.opt = opt 21 | 22 | self.num_frames_for_clip = int(self.opt.wav2vec_sec * self.opt.fps) 23 | self.num_prev_frames = int(self.opt.num_prev_frames) 24 | 25 | # motion latent auto-encoder 26 | self.motion_autoencoder = Generator(size = opt.input_size, style_dim = opt.dim_w, motion_dim = opt.dim_m) 27 | self.motion_autoencoder.requires_grad_(False) 28 | 29 | # condition encoders 30 | self.audio_encoder = AudioEncoder(opt) 31 | self.emotion_encoder = Audio2Emotion(opt) 32 | 33 | # FMT; Flow Matching Transformer 34 | self.fmt = FlowMatchingTransformer(opt) 35 | 36 | # ODE options 37 | self.odeint_kwargs = { 38 | 'atol': self.opt.ode_atol, 39 | 'rtol': self.opt.ode_rtol, 40 | 'method': self.opt.torchdiffeq_ode_method 41 | } 42 | 43 | ######## Motion Encoder - Decoder ######## 44 | @torch.no_grad() 45 | def encode_image_into_latent(self, x: torch.Tensor) -> list: 46 | x_r, _, x_r_feats = self.motion_autoencoder.enc(x, input_target=None) 47 | x_r_lambda = self.motion_autoencoder.enc.fc(x_r) 48 | return x_r, x_r_lambda, x_r_feats 49 | 50 | @torch.no_grad() 51 | def encode_identity_into_motion(self, x_r: torch.Tensor) -> torch.Tensor: 52 | x_r_lambda = self.motion_autoencoder.enc.fc(x_r) 53 | r_x = self.motion_autoencoder.dec.direction(x_r_lambda) 54 | return r_x 55 | 56 | @torch.no_grad() 57 | def decode_latent_into_image(self, s_r: torch.Tensor , s_r_feats: list, r_d: torch.Tensor) -> dict: 58 | T = r_d.shape[1] 59 | d_hat = [] 60 | for t in range(T): 61 | s_r_d_t = s_r + r_d[:, t] 62 | img_t, _ = self.motion_autoencoder.dec(s_r_d_t, alpha = None, feats = s_r_feats) 63 | d_hat.append(img_t) 64 | d_hat = torch.stack(d_hat, dim=1).squeeze() 65 | return {'d_hat': d_hat} 66 | 67 | 68 | ######## Motion Sampling and Inference ######## 69 | @torch.no_grad() 70 | def sample( 71 | self, 72 | data: dict, 73 | a_cfg_scale: float = 1.0, 74 | r_cfg_scale: float = 1.0, 75 | e_cfg_scale: float = 1.0, 76 | emo: str = None, 77 | nfe: int = 10, 78 | seed: int = None 79 | ) -> torch.Tensor: 80 | 81 | r_s, a = data['r_s'], data['a'] 82 | B = a.shape[0] 83 | 84 | # make time 85 | time = torch.linspace(0, 1, self.opt.nfe, device=self.opt.rank) 86 | 87 | # encoding audio first with whole audio 88 | a = a.to(self.opt.rank) 89 | T = math.ceil(a.shape[-1] * self.opt.fps / self.opt.sampling_rate) 90 | wa = self.audio_encoder.inference(a, seq_len=T) 91 | 92 | # encoding emotion first 93 | emo_idx = self.emotion_encoder.label2id.get(str(emo).lower(), None) 94 | if emo_idx is None: 95 | we = self.emotion_encoder.predict_emotion(a).unsqueeze(1) 96 | else: 97 | we = F.one_hot(torch.tensor(emo_idx, device = a.device), num_classes = self.opt.dim_e).unsqueeze(0).unsqueeze(0) 98 | 99 | sample = [] 100 | # sampleing chunk by chunk 101 | for t in range(0, int(math.ceil(T / self.num_frames_for_clip))): 102 | if self.opt.fix_noise_seed: 103 | seed = self.opt.seed if seed is None else seed 104 | g = torch.Generator(self.opt.rank) 105 | g.manual_seed(seed) 106 | x0 = torch.randn(B, self.num_frames_for_clip, self.opt.dim_w, device = self.opt.rank, generator = g) 107 | else: 108 | x0 = torch.randn(B, self.num_frames_for_clip, self.opt.dim_w, device = self.opt.rank) 109 | 110 | if t == 0: # should define the previous 111 | prev_x_t = torch.zeros(B, self.num_prev_frames, self.opt.dim_w).to(self.opt.rank) 112 | prev_wa_t = torch.zeros(B, self.num_prev_frames, self.opt.dim_w).to(self.opt.rank) 113 | else: 114 | prev_x_t = sample_t[:, -self.num_prev_frames:] 115 | prev_wa_t = wa_t[:, -self.num_prev_frames:] 116 | 117 | wa_t = wa[:, t * self.num_frames_for_clip: (t+1)*self.num_frames_for_clip] 118 | 119 | if wa_t.shape[1] < self.num_frames_for_clip: # padding by replicate 120 | wa_t = F.pad(wa_t, (0, 0, 0, self.num_frames_for_clip - wa_t.shape[1]), mode='replicate') 121 | 122 | def sample_chunk(tt, zt): 123 | out = self.fmt.forward_with_cfv( 124 | t = tt.unsqueeze(0), 125 | x = zt, 126 | wa = wa_t, 127 | wr = r_s, 128 | we = we, 129 | prev_x = prev_x_t, 130 | prev_wa = prev_wa_t, 131 | a_cfg_scale = a_cfg_scale, 132 | r_cfg_scale = r_cfg_scale, 133 | e_cfg_scale = e_cfg_scale 134 | ) 135 | 136 | out_current = out[:, self.num_prev_frames:] 137 | return out_current 138 | 139 | # solve ODE 140 | trajectory_t = odeint(sample_chunk, x0, time, **self.odeint_kwargs) 141 | sample_t = trajectory_t[-1] 142 | sample.append(sample_t) 143 | sample = torch.cat(sample, dim=1)[:, :T] 144 | return sample 145 | 146 | @torch.no_grad() 147 | def inference( 148 | self, 149 | data: dict, 150 | a_cfg_scale = None, 151 | r_cfg_scale = None, 152 | e_cfg_scale = None, 153 | emo = None, 154 | nfe = 10, 155 | seed = None, 156 | ) -> dict: 157 | 158 | s, a = data['s'], data['a'] 159 | s_r, r_s_lambda, s_r_feats = self.encode_image_into_latent(s.to(self.opt.rank)) 160 | if 's_r' in data: 161 | r_s = self.encode_identity_into_motion(s_r) 162 | else: 163 | r_s = self.motion_autoencoder.dec.direction(r_s_lambda) 164 | data['r_s'] = r_s 165 | 166 | # set conditions 167 | if a_cfg_scale is None: a_cfg_scale = self.opt.a_cfg_scale 168 | if r_cfg_scale is None: r_cfg_scale = self.opt.r_cfg_scale 169 | if e_cfg_scale is None: e_cfg_scale = self.opt.e_cfg_scale 170 | 171 | sample = self.sample(data, a_cfg_scale = a_cfg_scale, r_cfg_scale = r_cfg_scale, e_cfg_scale = e_cfg_scale, emo = emo, nfe = nfe, seed = seed) 172 | data_out = self.decode_latent_into_image(s_r = s_r, s_r_feats = s_r_feats, r_d = sample) 173 | return data_out 174 | 175 | 176 | 177 | 178 | ################ Condition Encoders ################ 179 | class AudioEncoder(BaseModel): 180 | def __init__(self, opt): 181 | super().__init__() 182 | self.opt = opt 183 | self.only_last_features = opt.only_last_features 184 | 185 | self.num_frames_for_clip = int(opt.wav2vec_sec * self.opt.fps) 186 | self.num_prev_frames = int(opt.num_prev_frames) 187 | 188 | self.wav2vec2 = Wav2VecModel.from_pretrained(opt.wav2vec_model_path, local_files_only = True) 189 | self.wav2vec2.feature_extractor._freeze_parameters() 190 | 191 | for name, param in self.wav2vec2.named_parameters(): 192 | param.requires_grad = False 193 | 194 | audio_input_dim = 768 if opt.only_last_features else 12 * 768 195 | 196 | self.audio_projection = nn.Sequential( 197 | nn.Linear(audio_input_dim, opt.dim_w), 198 | nn.LayerNorm(opt.dim_w), 199 | nn.SiLU() 200 | ) 201 | 202 | def get_wav2vec2_feature(self, a: torch.Tensor, seq_len:int) -> torch.Tensor: 203 | a = self.wav2vec2(a, seq_len=seq_len, output_hidden_states = not self.only_last_features) 204 | if self.only_last_features: 205 | a = a.last_hidden_state 206 | else: 207 | a = torch.stack(a.hidden_states[1:], dim=1).permute(0, 2, 1, 3) 208 | a = a.reshape(a.shape[0], a.shape[1], -1) 209 | return a 210 | 211 | def forward(self, a:torch.Tensor, prev_a:torch.Tensor = None) -> torch.Tensor: 212 | if prev_a is not None: 213 | a = torch.cat([prev_a, a], dim = 1) 214 | if a.shape[1] % int( (self.num_frames_for_clip + self.num_prev_frames) * self.opt.sampling_rate / self.opt.fps) != 0: 215 | a = F.pad(a, (0, int((self.num_frames_for_clip + self.num_prev_frames) * self.opt.sampling_rate / self.opt.fps) - a.shape[1]), mode='replicate') 216 | a = self.get_wav2vec2_feature(a, seq_len = self.num_frames_for_clip + self.num_prev_frames) 217 | else: 218 | if a.shape[1] % int( self.num_frames_for_clip * self.opt.sampling_rate / self.opt.fps) != 0: 219 | a = F.pad(a, (0, int(self.num_frames_for_clip * self.opt.sampling_rate / self.opt.fps) - a.shape[1]), mode = 'replicate') 220 | a = self.get_wav2vec2_feature(a, seq_len = self.num_frames_for_clip) 221 | 222 | return self.audio_projection(a) # frame by frame 223 | 224 | @torch.no_grad() 225 | def inference(self, a: torch.Tensor, seq_len:int) -> torch.Tensor: 226 | if a.shape[1] % int(seq_len * self.opt.sampling_rate / self.opt.fps) != 0: 227 | a = F.pad(a, (0, int(seq_len * self.opt.sampling_rate / self.opt.fps) - a.shape[1]), mode = 'replicate') 228 | a = self.get_wav2vec2_feature(a, seq_len=seq_len) 229 | return self.audio_projection(a) 230 | 231 | 232 | 233 | class Audio2Emotion(nn.Module): 234 | def __init__(self, opt): 235 | super().__init__() 236 | self.wav2vec2_for_emotion = Wav2Vec2ForSpeechClassification.from_pretrained(opt.audio2emotion_path, local_files_only=True) 237 | self.wav2vec2_for_emotion.eval() 238 | 239 | # seven labels 240 | self.id2label = {0: "angry", 1: "disgust", 2: "fear", 3: "happy", 241 | 4: "neutral", 5: "sad", 6: "surprise"} 242 | 243 | self.label2id = {v: k for k, v in self.id2label.items()} 244 | 245 | @torch.no_grad() 246 | def predict_emotion(self, a: torch.Tensor, prev_a: torch.Tensor = None) -> torch.Tensor: 247 | if prev_a is not None: 248 | a = torch.cat([prev_a, a], dim=1) 249 | logits = self.wav2vec2_for_emotion.forward(a).logits 250 | return F.softmax(logits, dim=1) # scores 251 | 252 | ####################################################### -------------------------------------------------------------------------------- /models/float/FMT.py: -------------------------------------------------------------------------------- 1 | import os, math, torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from torchdiffeq import odeint 6 | from models import BaseModel 7 | 8 | from timm.layers import use_fused_attn 9 | from timm.models.vision_transformer import Mlp 10 | 11 | 12 | def enc_dec_mask(T, S, frame_width = 1, expansion = 2): 13 | mask = torch.ones(T, S) 14 | for i in range(T): 15 | mask[i, max(0, (i - expansion) * frame_width):(i + expansion + 1) * frame_width] = 0 16 | return mask == 1 17 | 18 | 19 | def get_sinusoid_encoding_table(n_position, d_hid, padding_idx=None): 20 | """ 21 | Sinusoidal position encoding table. 22 | Args: 23 | n_position (int): the length of the input sequence 24 | d_hid (int): the dimension of the hidden state 25 | """ 26 | def cal_angle(position, hid_idx): 27 | return position / (10000 ** (2 * (hid_idx // 2) / d_hid)) 28 | 29 | def get_posi_angle_vec(position): 30 | return [cal_angle(position, hid_j) for hid_j in range(d_hid)] 31 | 32 | sinusoid_table = torch.Tensor([get_posi_angle_vec(pos_i) for pos_i in range(n_position)]) 33 | sinusoid_table[:, 0::2] = torch.sin(sinusoid_table[:, 0::2]) # dim 2i 34 | sinusoid_table[:, 1::2] = torch.cos(sinusoid_table[:, 1::2]) # dim 2i+1 35 | if padding_idx is not None: sinusoid_table[padding_idx] = 0. 36 | return sinusoid_table 37 | 38 | 39 | class Attention(nn.Module): 40 | def __init__( 41 | self, 42 | dim: int, 43 | num_heads: int = 8, 44 | qkv_bias: bool = False, 45 | qk_norm: bool = False, 46 | attn_drop: float = 0., 47 | proj_drop: float = 0., 48 | norm_layer: nn.Module = nn.LayerNorm, 49 | ) -> None: 50 | 51 | super().__init__() 52 | assert dim % num_heads == 0, 'dim should be divisible by num_heads' 53 | self.num_heads = num_heads 54 | self.head_dim = dim // num_heads 55 | self.scale = self.head_dim ** -0.5 56 | self.fused_attn = use_fused_attn() 57 | 58 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 59 | self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() 60 | self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() 61 | self.attn_drop = nn.Dropout(attn_drop) 62 | self.proj = nn.Linear(dim, dim) 63 | self.proj_drop = nn.Dropout(proj_drop) 64 | 65 | def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor: 66 | B, N, C = x.shape 67 | qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) 68 | q, k, v = qkv.unbind(0) 69 | q, k = self.q_norm(q), self.k_norm(k) 70 | 71 | if self.fused_attn: 72 | x = F.scaled_dot_product_attention( 73 | q, k, v, 74 | attn_mask = ~mask, 75 | dropout_p=self.attn_drop.p if self.training else 0., 76 | ) 77 | else: 78 | q = q * self.scale 79 | attn = q @ k.transpose(-2, -1) 80 | attn = attn.softmax(dim=-1) 81 | attn = self.attn_drop(attn) 82 | x = attn @ v 83 | 84 | x = x.transpose(1, 2).reshape(B, N, C) 85 | x = self.proj(x) 86 | x = self.proj_drop(x) 87 | return x 88 | 89 | class TimestepEmbedder(nn.Module): 90 | """ 91 | Embeds scalar timesteps into vector representations. 92 | """ 93 | def __init__(self, hidden_size, frequency_embedding_size = 256): 94 | super().__init__() 95 | self.mlp = nn.Sequential( 96 | nn.Linear(frequency_embedding_size, hidden_size, bias=True), 97 | nn.SiLU(), 98 | nn.Linear(hidden_size, hidden_size, bias=True), 99 | ) 100 | self.frequency_embedding_size = frequency_embedding_size 101 | 102 | @staticmethod 103 | def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor: 104 | """ 105 | Create sinusoidal timestep embeddings. 106 | :param t: a 1-D Tensor of N indices, one per batch element. 107 | These may be fractional. 108 | :param dim: the dimension of the output. 109 | :param max_period: controls the minimum frequency of the embeddings. 110 | :return: an (N, D) Tensor of positional embeddings. 111 | """ 112 | # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py 113 | half = dim // 2 114 | freqs = torch.exp( 115 | -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half 116 | ).to(device=t.device) 117 | args = t[:, None].float() * freqs[None] 118 | embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) 119 | if dim % 2: 120 | embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) 121 | return embedding 122 | 123 | def forward(self, t: torch.Tensor) -> torch.Tensor: 124 | t_freq = self.timestep_embedding(t, self.frequency_embedding_size) 125 | t_emb = self.mlp(t_freq) 126 | return t_emb 127 | 128 | class SequenceEmbed(nn.Module): 129 | def __init__( 130 | self, 131 | dim_w, 132 | dim_h, 133 | norm_layer=None, 134 | bias=True, 135 | ): 136 | super().__init__() 137 | 138 | self.proj = nn.Linear(dim_w, dim_h, bias=bias) 139 | self.norm = norm_layer(dim_h) if norm_layer else nn.Identity() 140 | 141 | def forward(self, x: torch.Tensor) -> torch.Tensor: 142 | return self.norm(self.proj(x)) 143 | 144 | 145 | class FMTBlock(nn.Module): 146 | """ 147 | A FMT block inspried by DiT Block 148 | """ 149 | def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs) -> None: 150 | super().__init__() 151 | self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) 152 | self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs) 153 | self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) 154 | mlp_hidden_dim = int(hidden_size * mlp_ratio) 155 | approx_gelu = lambda: nn.GELU(approximate="tanh") 156 | self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0) 157 | self.adaLN_modulation = nn.Sequential( 158 | nn.SiLU(), 159 | nn.Linear(hidden_size, 6 * hidden_size, bias=True) 160 | ) 161 | 162 | def framewise_modulate(self, x, shift, scale) -> torch.Tensor: 163 | return x * (1 + scale) + shift 164 | 165 | def forward(self, x, c, mask=None) -> torch.Tensor: 166 | assert mask is not None 167 | shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=-1) 168 | x = x + gate_msa * self.attn(self.framewise_modulate(self.norm1(x), shift_msa, scale_msa), mask = mask) 169 | x = x + gate_mlp * self.mlp(self.framewise_modulate(self.norm2(x), shift_mlp, scale_mlp)) 170 | return x 171 | 172 | class Decoder(nn.Module): 173 | """ 174 | The final decoder of FlowMatchingTransformer. 175 | """ 176 | def __init__(self, hidden_size, dim_w): 177 | super().__init__() 178 | self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) 179 | self.adaLN_modulation = nn.Sequential( 180 | nn.SiLU(), 181 | nn.Linear(hidden_size, 2 * hidden_size, bias=True) 182 | ) 183 | self.linear = nn.Linear(hidden_size, dim_w, bias=True) 184 | 185 | def framewise_modulate(self, x, shift, scale) -> torch.Tensor: 186 | return x * (1 + scale) + shift 187 | 188 | def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor: 189 | shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1) 190 | x = self.framewise_modulate(self.norm_final(x), shift, scale) 191 | return self.linear(x) 192 | 193 | 194 | class FlowMatchingTransformer(BaseModel): 195 | """ 196 | Flow Matching Transformer (FMT) 197 | """ 198 | def __init__(self, opt) -> None: 199 | super().__init__() 200 | self.opt = opt 201 | 202 | self.num_frames_for_clip = int(self.opt.wav2vec_sec * self.opt.fps) 203 | self.num_prev_frames = int(opt.num_prev_frames) 204 | self.num_total_frames = self.num_prev_frames + self.num_frames_for_clip 205 | 206 | self.hidden_size = opt.dim_h 207 | self.mlp_ratio = opt.mlp_ratio 208 | self.fmt_depth = opt.fmt_depth 209 | self.num_heads = opt.num_heads 210 | 211 | self.x_embedder = SequenceEmbed(opt.dim_w, self.hidden_size) 212 | 213 | # video time position encoding 214 | self.pos_embed = nn.Parameter(torch.zeros(1, self.num_total_frames, self.hidden_size), requires_grad=False) 215 | 216 | # flow trajectory time encoding 217 | self.t_embedder = TimestepEmbedder(self.hidden_size) 218 | self.c_embedder = nn.Linear(opt.dim_w + opt.dim_a + opt.dim_e, self.hidden_size) 219 | 220 | # define FMT blocks 221 | self.blocks = nn.ModuleList([FMTBlock(self.hidden_size, self.num_heads, mlp_ratio=self.mlp_ratio) for _ in range(self.fmt_depth)]) 222 | self.decoder = Decoder(self.hidden_size, self.opt.dim_w) 223 | self.initialize_weights() 224 | 225 | # define alignment mask 226 | alignment_mask = enc_dec_mask(self.num_total_frames, self.num_total_frames, 1, expansion=opt.attention_window).to(opt.rank) 227 | self.register_buffer('alignment_mask', alignment_mask) 228 | 229 | 230 | def initialize_weights(self) -> None: 231 | def _basic_init(module): 232 | if isinstance(module, nn.Linear): 233 | torch.nn.init.xavier_uniform_(module.weight) 234 | if module.bias is not None: 235 | nn.init.constant_(module.bias, 0) 236 | 237 | self.apply(_basic_init) 238 | 239 | pos_embed = get_sinusoid_encoding_table(self.num_total_frames, self.hidden_size) 240 | self.pos_embed.data.copy_(pos_embed.unsqueeze(0)) 241 | 242 | w = self.x_embedder.proj.weight.data 243 | nn.init.xavier_uniform_(w.view([w.shape[0], -1])) 244 | nn.init.constant_(self.x_embedder.proj.bias, 0) 245 | 246 | # Initialize timestep embedding MLP: 247 | nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) 248 | nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) 249 | 250 | # Zero-out adaLN modulation layers in FMT blocks: 251 | for block in self.blocks: 252 | nn.init.constant_(block.adaLN_modulation[-1].weight, 0) 253 | nn.init.constant_(block.adaLN_modulation[-1].bias, 0) 254 | 255 | # Zero-out output layers: 256 | nn.init.constant_(self.decoder.adaLN_modulation[-1].weight, 0) 257 | nn.init.constant_(self.decoder.adaLN_modulation[-1].bias, 0) 258 | nn.init.constant_(self.decoder.linear.weight, 0) 259 | nn.init.constant_(self.decoder.linear.bias, 0) 260 | 261 | def sequence_embedder(self, sequence, dropout_prob, train=False) -> torch.Tensor: 262 | if train: 263 | batch_id_for_drop = torch.where(torch.rand(sequence.shape[0], device=sequence.device) < dropout_prob) 264 | sequence[batch_id_for_drop] = 0 265 | return sequence 266 | 267 | 268 | def forward(self, t, x, wa, wr, we, prev_x = None, prev_wa = None, train = True, **kwargs) -> torch.Tensor: 269 | """ 270 | Forward pass of ConditionalFlowMatchingTransformer. 271 | 272 | t: (B,) tensor of diffusion timesteps [0, 1] 273 | x: (B, L, 512) : tensor of sequence of motion latent 274 | 275 | wa: (B, L, 512) / tensor sequence of wa latent 276 | wp: (B, L, 6) / tensor sequence of wp latent 277 | wr: (B, 512) / tensor of reference motion latent (i.e., r -> s) 278 | we: (B, 1, 7) / tensor of emotion latent 279 | 280 | prev_x: (B, L', 512) / previous x for auto-regressive generation 281 | prev_wa: (B, L', 512) / previous audio for auto-regressive generation 282 | """ 283 | 284 | # time encoding 285 | t = self.t_embedder(t).unsqueeze(1) # (N, D) 286 | 287 | # condition encoding 288 | wa = self.sequence_embedder(wa, dropout_prob = self.opt.audio_dropout_prob, train=train) 289 | wr = self.sequence_embedder(wr.unsqueeze(1), dropout_prob = self.opt.ref_dropout_prob, train=train) 290 | we = self.sequence_embedder(we, dropout_prob = self.opt.emotion_dropout_prob, train=train) 291 | 292 | # previous condition encoding 293 | if prev_x is not None: 294 | prev_x = self.sequence_embedder(prev_x, dropout_prob=0.5, train=train) 295 | prev_wa = self.sequence_embedder(prev_wa, dropout_prob=0.5, train=train) 296 | 297 | x = torch.cat([prev_x, x], dim=1) 298 | wa = torch.cat([prev_wa, wa], dim=1) 299 | 300 | x = self.x_embedder(x) 301 | x = x + self.pos_embed # (N, L + L', D), where T = opt.wav2vec_sec * opt.fps, D = dim_w 302 | 303 | wr = wr.repeat(1, wa.shape[1], 1) 304 | we = we.repeat(1, wa.shape[1], 1) 305 | 306 | c = torch.cat([wr, wa, we], dim=-1) 307 | c = self.c_embedder(c) 308 | c = t + c 309 | 310 | # forwarding FMT Blocks 311 | for block in self.blocks: 312 | x = block(x, c, self.alignment_mask) # (N, T, D) 313 | return self.decoder(x, c) 314 | 315 | @torch.no_grad() 316 | def forward_with_cfv(self, t, x, wa, wr, we, prev_x, prev_wa, a_cfg_scale=1.0, r_cfg_scale=1.0, e_cfg_scale=1.0, **kwargs) -> torch.Tensor: 317 | if a_cfg_scale != 1.0 or r_cfg_scale != 1.0 or e_cfg_scale != 1.0: 318 | null_wa = torch.zeros_like(wa) 319 | null_we = torch.zeros_like(we) 320 | null_wr = torch.zeros_like(wr) 321 | 322 | audio_cat = torch.cat([null_wa, wa, wa], dim=0) # concat along batch 323 | ref_cat = torch.cat([wr, wr, wr], dim=0) # concat along batch 324 | emotion_cat = torch.cat([null_we, we, null_we], dim=0) # concat along batch 325 | x = torch.cat([x, x, x], dim=0) # concat along batch 326 | 327 | prev_x_cat = torch.cat([prev_x, prev_x, prev_x], dim=0) 328 | prev_wa_cat = torch.cat([prev_wa, prev_wa, prev_wa], dim=0) 329 | 330 | model_output = self.forward(t, x, audio_cat, ref_cat, emotion_cat, prev_x_cat, prev_wa_cat, train=False) 331 | uncond, all_cond, audio_uncond_emotion = torch.chunk(model_output, chunks=3, dim=0) 332 | 333 | # Classifier-free vector field (cfv) incremental manner 334 | return uncond + a_cfg_scale * (audio_uncond_emotion - uncond) + e_cfg_scale * (all_cond - audio_uncond_emotion) 335 | else: 336 | return self.forward(t, x, wa, wr, we, prev_x, prev_wa, train = False) 337 | 338 | -------------------------------------------------------------------------------- /models/float/encoder.py: -------------------------------------------------------------------------------- 1 | import math, torch 2 | import numpy as np 3 | 4 | from torch import nn 5 | from torch.nn import functional as F 6 | 7 | 8 | def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): 9 | return F.leaky_relu(input + bias, negative_slope) * scale 10 | 11 | 12 | def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): 13 | _, minor, in_h, in_w = input.shape 14 | kernel_h, kernel_w = kernel.shape 15 | 16 | out = input.view(-1, minor, in_h, 1, in_w, 1) 17 | out = F.pad(out, [0, up_x - 1, 0, 0, 0, up_y - 1, 0, 0]) 18 | out = out.view(-1, minor, in_h * up_y, in_w * up_x) 19 | 20 | out = F.pad(out, [max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) 21 | out = out[:, :, max(-pad_y0, 0): out.shape[2] - max(-pad_y1, 0), 22 | max(-pad_x0, 0): out.shape[3] - max(-pad_x1, 0), ] 23 | 24 | out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) 25 | w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) 26 | out = F.conv2d(out, w) 27 | out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, 28 | in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1, ) 29 | return out[:, :, ::down_y, ::down_x] 30 | 31 | 32 | def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): 33 | return upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) 34 | 35 | 36 | def make_kernel(k): 37 | k = torch.tensor(k, dtype=torch.float32) 38 | if k.ndim == 1: 39 | k = k[None, :] * k[:, None] 40 | k /= k.sum() 41 | return k 42 | 43 | 44 | class FusedLeakyReLU(nn.Module): 45 | def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5): 46 | super().__init__() 47 | self.bias = nn.Parameter(torch.zeros(1, channel, 1, 1)) 48 | self.negative_slope = negative_slope 49 | self.scale = scale 50 | 51 | def forward(self, input): 52 | out = fused_leaky_relu(input, self.bias, self.negative_slope, self.scale) 53 | return out 54 | 55 | 56 | class Blur(nn.Module): 57 | def __init__(self, kernel, pad, upsample_factor=1): 58 | super().__init__() 59 | 60 | kernel = make_kernel(kernel) 61 | 62 | if upsample_factor > 1: 63 | kernel = kernel * (upsample_factor ** 2) 64 | 65 | self.register_buffer('kernel', kernel) 66 | 67 | self.pad = pad 68 | 69 | def forward(self, input): 70 | return upfirdn2d(input, self.kernel, pad=self.pad) 71 | 72 | 73 | class ScaledLeakyReLU(nn.Module): 74 | def __init__(self, negative_slope=0.2): 75 | super().__init__() 76 | 77 | self.negative_slope = negative_slope 78 | 79 | def forward(self, input): 80 | return F.leaky_relu(input, negative_slope=self.negative_slope) 81 | 82 | 83 | class EqualConv2d(nn.Module): 84 | def __init__(self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True): 85 | super().__init__() 86 | 87 | self.weight = nn.Parameter(torch.randn(out_channel, in_channel, kernel_size, kernel_size)) 88 | self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2) 89 | 90 | self.stride = stride 91 | self.padding = padding 92 | 93 | if bias: 94 | self.bias = nn.Parameter(torch.zeros(out_channel)) 95 | else: 96 | self.bias = None 97 | 98 | def forward(self, input): 99 | 100 | return F.conv2d(input, self.weight * self.scale, bias=self.bias, stride=self.stride, padding=self.padding) 101 | 102 | def __repr__(self): 103 | return ( 104 | f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},' 105 | f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})' 106 | ) 107 | 108 | 109 | class EqualLinear(nn.Module): 110 | def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None): 111 | super().__init__() 112 | 113 | self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul)) 114 | 115 | if bias: 116 | self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init)) 117 | else: 118 | self.bias = None 119 | 120 | self.activation = activation 121 | 122 | self.scale = (1 / math.sqrt(in_dim)) * lr_mul 123 | self.lr_mul = lr_mul 124 | 125 | def forward(self, input): 126 | 127 | if self.activation: 128 | out = F.linear(input, self.weight * self.scale) 129 | out = fused_leaky_relu(out, self.bias * self.lr_mul) 130 | else: 131 | out = F.linear(input, self.weight * self.scale, bias=self.bias * self.lr_mul) 132 | 133 | return out 134 | 135 | def __repr__(self): 136 | return (f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})') 137 | 138 | 139 | class ConvLayer(nn.Sequential): 140 | def __init__( 141 | self, 142 | in_channel, 143 | out_channel, 144 | kernel_size, 145 | downsample=False, 146 | blur_kernel=[1, 3, 3, 1], 147 | bias=True, 148 | activate=True, 149 | ): 150 | layers = [] 151 | 152 | if downsample: 153 | factor = 2 154 | p = (len(blur_kernel) - factor) + (kernel_size - 1) 155 | pad0 = (p + 1) // 2 156 | pad1 = p // 2 157 | 158 | layers.append(Blur(blur_kernel, pad=(pad0, pad1))) 159 | 160 | stride = 2 161 | self.padding = 0 162 | 163 | else: 164 | stride = 1 165 | self.padding = kernel_size // 2 166 | 167 | layers.append(EqualConv2d(in_channel, out_channel, kernel_size, padding=self.padding, stride=stride, 168 | bias=bias and not activate)) 169 | 170 | if activate: 171 | if bias: 172 | layers.append(FusedLeakyReLU(out_channel)) 173 | else: 174 | layers.append(ScaledLeakyReLU(0.2)) 175 | 176 | super().__init__(*layers) 177 | 178 | 179 | class ResBlock(nn.Module): 180 | def __init__(self, in_channel, out_channel, blur_kernel=[1, 3, 3, 1]): 181 | super().__init__() 182 | 183 | self.conv1 = ConvLayer(in_channel, in_channel, 3) 184 | self.conv2 = ConvLayer(in_channel, out_channel, 3, downsample=True) 185 | 186 | self.skip = ConvLayer(in_channel, out_channel, 1, downsample=True, activate=False, bias=False) 187 | 188 | def forward(self, input): 189 | out = self.conv1(input) 190 | out = self.conv2(out) 191 | 192 | skip = self.skip(input) 193 | out = (out + skip) / math.sqrt(2) 194 | 195 | return out 196 | 197 | 198 | class EncoderApp(nn.Module): 199 | def __init__(self, size, w_dim=512): 200 | super(EncoderApp, self).__init__() 201 | 202 | channels = { 203 | 4: 512, 204 | 8: 512, 205 | 16: 512, 206 | 32: 512, 207 | 64: 256, 208 | 128: 128, 209 | 256: 64, 210 | 512: 32, 211 | 1024: 16 212 | } 213 | 214 | self.w_dim = w_dim 215 | log_size = int(math.log(size, 2)) 216 | 217 | self.convs = nn.ModuleList() 218 | self.convs.append(ConvLayer(3, channels[size], 1)) 219 | 220 | in_channel = channels[size] 221 | for i in range(log_size, 2, -1): 222 | out_channel = channels[2 ** (i - 1)] 223 | self.convs.append(ResBlock(in_channel, out_channel)) 224 | in_channel = out_channel 225 | 226 | self.convs.append(EqualConv2d(in_channel, self.w_dim, 4, padding=0, bias=False)) 227 | 228 | def forward(self, x): 229 | 230 | res = [] 231 | h = x 232 | for conv in self.convs: 233 | h = conv(h) 234 | res.append(h) 235 | 236 | return res[-1].squeeze(-1).squeeze(-1), res[::-1][2:] 237 | 238 | 239 | class Encoder(nn.Module): 240 | def __init__(self, size, dim=512, dim_motion=20): 241 | super(Encoder, self).__init__() 242 | 243 | # appearance netmork 244 | self.net_app = EncoderApp(size, dim) 245 | 246 | # motion network 247 | fc = [EqualLinear(dim, dim)] 248 | for i in range(3): 249 | fc.append(EqualLinear(dim, dim)) 250 | 251 | fc.append(EqualLinear(dim, dim_motion)) 252 | self.fc = nn.Sequential(*fc) 253 | 254 | def enc_app(self, x): 255 | 256 | h_source = self.net_app(x) 257 | 258 | return h_source 259 | 260 | def enc_motion(self, x): 261 | 262 | h, _ = self.net_app(x) 263 | h_motion = self.fc(h) 264 | 265 | return h_motion 266 | 267 | def forward(self, input_source, input_target, h_start=None): 268 | 269 | if input_target is not None: 270 | 271 | h_source, feats = self.net_app(input_source) 272 | h_target, _ = self.net_app(input_target) 273 | 274 | h_motion_target = self.fc(h_target) 275 | 276 | if h_start is not None: 277 | h_motion_source = self.fc(h_source) 278 | h_motion = [h_motion_target, h_motion_source, h_start] 279 | else: 280 | h_motion = [h_motion_target] 281 | 282 | return h_source, h_motion, feats 283 | else: 284 | h_source, feats = self.net_app(input_source) 285 | 286 | return h_source, None, feats 287 | -------------------------------------------------------------------------------- /models/float/generator.py: -------------------------------------------------------------------------------- 1 | from torch import nn 2 | from .encoder import Encoder 3 | from .styledecoder import Synthesis 4 | 5 | from models import BaseModel 6 | 7 | class Generator(BaseModel): 8 | def __init__(self, size, style_dim=512, motion_dim=20, channel_multiplier=1, blur_kernel=[1, 3, 3, 1]): 9 | super().__init__() 10 | 11 | self.enc = Encoder(size, style_dim, motion_dim) 12 | self.dec = Synthesis(size, style_dim, motion_dim, blur_kernel, channel_multiplier) 13 | 14 | def get_direction(self): 15 | return self.dec.direction(None) 16 | 17 | def synthesis(self, wa, alpha, feat): 18 | img, flow = self.dec(wa, alpha, feat) 19 | return img 20 | 21 | def forward(self, img_source, img_drive, h_start=None): 22 | wa, alpha, feats = self.enc(img_source, img_drive, h_start) 23 | img_recon, flow = self.dec(wa, alpha, feats) 24 | return {'d_hat': img_recon, 'flow': flow} 25 | -------------------------------------------------------------------------------- /models/float/styledecoder.py: -------------------------------------------------------------------------------- 1 | import math, torch 2 | import numpy as np 3 | 4 | from torch import nn 5 | from torch.nn import functional as F 6 | 7 | 8 | def fused_leaky_relu(input, bias, negative_slope=0.2, scale=2 ** 0.5): 9 | return F.leaky_relu(input + bias, negative_slope) * scale 10 | 11 | 12 | def upfirdn2d_native(input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1): 13 | _, minor, in_h, in_w = input.shape 14 | kernel_h, kernel_w = kernel.shape 15 | 16 | out = input.view(-1, minor, in_h, 1, in_w, 1) 17 | out = F.pad(out, [0, up_x - 1, 0, 0, 0, up_y - 1, 0, 0]) 18 | out = out.view(-1, minor, in_h * up_y, in_w * up_x) 19 | 20 | out = F.pad(out, [max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]) 21 | out = out[:, :, max(-pad_y0, 0): out.shape[2] - max(-pad_y1, 0), 22 | max(-pad_x0, 0): out.shape[3] - max(-pad_x1, 0), ] 23 | 24 | out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]) 25 | w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w) 26 | out = F.conv2d(out, w) 27 | out = out.reshape(-1, minor, in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1, 28 | in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1, ) 29 | return out[:, :, ::down_y, ::down_x] 30 | 31 | 32 | def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)): 33 | return upfirdn2d_native(input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]) 34 | 35 | 36 | def make_kernel(k): 37 | k = torch.tensor(k, dtype=torch.float32) 38 | if k.ndim == 1: 39 | k = k[None, :] * k[:, None] 40 | k /= k.sum() 41 | return k 42 | 43 | 44 | class FusedLeakyReLU(nn.Module): 45 | def __init__(self, channel, negative_slope=0.2, scale=2 ** 0.5): 46 | super().__init__() 47 | self.bias = nn.Parameter(torch.zeros(1, channel, 1, 1)) 48 | self.negative_slope = negative_slope 49 | self.scale = scale 50 | 51 | def forward(self, input): 52 | return fused_leaky_relu(input, self.bias, self.negative_slope, self.scale) 53 | 54 | 55 | class PixelNorm(nn.Module): 56 | def __init__(self): 57 | super().__init__() 58 | 59 | def forward(self, input): 60 | return input * torch.rsqrt(torch.mean(input ** 2, dim=1, keepdim=True) + 1e-8) 61 | 62 | 63 | class MotionPixelNorm(nn.Module): 64 | def __init__(self): 65 | super().__init__() 66 | 67 | def forward(self, input): 68 | return input * torch.rsqrt(torch.mean(input ** 2, dim=2, keepdim=True) + 1e-8) 69 | 70 | class Upsample(nn.Module): 71 | def __init__(self, kernel, factor=2): 72 | super().__init__() 73 | 74 | self.factor = factor 75 | kernel = make_kernel(kernel) * (factor ** 2) 76 | self.register_buffer('kernel', kernel) 77 | 78 | p = kernel.shape[0] - factor 79 | 80 | pad0 = (p + 1) // 2 + factor - 1 81 | pad1 = p // 2 82 | 83 | self.pad = (pad0, pad1) 84 | 85 | def forward(self, input): 86 | return upfirdn2d(input, self.kernel, up=self.factor, down=1, pad=self.pad) 87 | 88 | 89 | class Downsample(nn.Module): 90 | def __init__(self, kernel, factor=2): 91 | super().__init__() 92 | 93 | self.factor = factor 94 | kernel = make_kernel(kernel) 95 | self.register_buffer('kernel', kernel) 96 | 97 | p = kernel.shape[0] - factor 98 | 99 | pad0 = (p + 1) // 2 100 | pad1 = p // 2 101 | 102 | self.pad = (pad0, pad1) 103 | 104 | def forward(self, input): 105 | return upfirdn2d(input, self.kernel, up=1, down=self.factor, pad=self.pad) 106 | 107 | 108 | class Blur(nn.Module): 109 | def __init__(self, kernel, pad, upsample_factor=1): 110 | super().__init__() 111 | 112 | kernel = make_kernel(kernel) 113 | 114 | if upsample_factor > 1: 115 | kernel = kernel * (upsample_factor ** 2) 116 | 117 | self.register_buffer('kernel', kernel) 118 | 119 | self.pad = pad 120 | 121 | def forward(self, input): 122 | return upfirdn2d(input, self.kernel, pad=self.pad) 123 | 124 | 125 | class EqualConv2d(nn.Module): 126 | def __init__(self, in_channel, out_channel, kernel_size, stride=1, padding=0, bias=True): 127 | super().__init__() 128 | 129 | self.weight = nn.Parameter(torch.randn(out_channel, in_channel, kernel_size, kernel_size)) 130 | self.scale = 1 / math.sqrt(in_channel * kernel_size ** 2) 131 | 132 | self.stride = stride 133 | self.padding = padding 134 | 135 | if bias: 136 | self.bias = nn.Parameter(torch.zeros(out_channel)) 137 | else: 138 | self.bias = None 139 | 140 | def forward(self, input): 141 | 142 | return F.conv2d(input, self.weight * self.scale, bias=self.bias, stride=self.stride, padding=self.padding, ) 143 | 144 | def __repr__(self): 145 | return ( 146 | f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]},' 147 | f' {self.weight.shape[2]}, stride={self.stride}, padding={self.padding})' 148 | ) 149 | 150 | 151 | class EqualLinear(nn.Module): 152 | def __init__(self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None): 153 | super().__init__() 154 | 155 | self.weight = nn.Parameter(torch.randn(out_dim, in_dim).div_(lr_mul)) 156 | 157 | if bias: 158 | self.bias = nn.Parameter(torch.zeros(out_dim).fill_(bias_init)) 159 | else: 160 | self.bias = None 161 | 162 | self.activation = activation 163 | 164 | self.scale = (1 / math.sqrt(in_dim)) * lr_mul 165 | self.lr_mul = lr_mul 166 | 167 | def forward(self, input): 168 | 169 | if self.activation: 170 | out = F.linear(input, self.weight * self.scale) 171 | out = fused_leaky_relu(out, self.bias * self.lr_mul) 172 | else: 173 | out = F.linear(input, self.weight * self.scale, bias=self.bias * self.lr_mul) 174 | 175 | return out 176 | 177 | def __repr__(self): 178 | return (f'{self.__class__.__name__}({self.weight.shape[1]}, {self.weight.shape[0]})') 179 | 180 | 181 | class ScaledLeakyReLU(nn.Module): 182 | def __init__(self, negative_slope=0.2): 183 | super().__init__() 184 | 185 | self.negative_slope = negative_slope 186 | 187 | def forward(self, input): 188 | return F.leaky_relu(input, negative_slope=self.negative_slope) 189 | 190 | 191 | class ModulatedConv2d(nn.Module): 192 | def __init__(self, in_channel, out_channel, kernel_size, style_dim, demodulate=True, upsample=False, 193 | downsample=False, blur_kernel=[1, 3, 3, 1], ): 194 | super().__init__() 195 | 196 | self.eps = 1e-8 197 | self.kernel_size = kernel_size 198 | self.in_channel = in_channel 199 | self.out_channel = out_channel 200 | self.upsample = upsample 201 | self.downsample = downsample 202 | 203 | if upsample: 204 | factor = 2 205 | p = (len(blur_kernel) - factor) - (kernel_size - 1) 206 | pad0 = (p + 1) // 2 + factor - 1 207 | pad1 = p // 2 + 1 208 | 209 | self.blur = Blur(blur_kernel, pad=(pad0, pad1), upsample_factor=factor) 210 | 211 | if downsample: 212 | factor = 2 213 | p = (len(blur_kernel) - factor) + (kernel_size - 1) 214 | pad0 = (p + 1) // 2 215 | pad1 = p // 2 216 | 217 | self.blur = Blur(blur_kernel, pad=(pad0, pad1)) 218 | 219 | fan_in = in_channel * kernel_size ** 2 220 | self.scale = 1 / math.sqrt(fan_in) 221 | self.padding = kernel_size // 2 222 | 223 | self.weight = nn.Parameter(torch.randn(1, out_channel, in_channel, kernel_size, kernel_size)) 224 | 225 | self.modulation = EqualLinear(style_dim, in_channel, bias_init=1) 226 | self.demodulate = demodulate 227 | 228 | def __repr__(self): 229 | return ( 230 | f'{self.__class__.__name__}({self.in_channel}, {self.out_channel}, {self.kernel_size}, ' 231 | f'upsample={self.upsample}, downsample={self.downsample})' 232 | ) 233 | 234 | def forward(self, input, style): 235 | batch, in_channel, height, width = input.shape 236 | 237 | style = self.modulation(style).view(batch, 1, in_channel, 1, 1) 238 | weight = self.scale * self.weight * style 239 | 240 | if self.demodulate: 241 | demod = torch.rsqrt(weight.pow(2).sum([2, 3, 4]) + 1e-8) 242 | weight = weight * demod.view(batch, self.out_channel, 1, 1, 1) 243 | 244 | weight = weight.view(batch * self.out_channel, in_channel, self.kernel_size, self.kernel_size) 245 | 246 | if self.upsample: 247 | input = input.view(1, batch * in_channel, height, width) 248 | weight = weight.view(batch, self.out_channel, in_channel, self.kernel_size, self.kernel_size) 249 | weight = weight.transpose(1, 2).reshape(batch * in_channel, self.out_channel, self.kernel_size, 250 | self.kernel_size) 251 | out = F.conv_transpose2d(input, weight, padding=0, stride=2, groups=batch) 252 | _, _, height, width = out.shape 253 | out = out.view(batch, self.out_channel, height, width) 254 | out = self.blur(out) 255 | elif self.downsample: 256 | input = self.blur(input) 257 | _, _, height, width = input.shape 258 | input = input.view(1, batch * in_channel, height, width) 259 | out = F.conv2d(input, weight, padding=0, stride=2, groups=batch) 260 | _, _, height, width = out.shape 261 | out = out.view(batch, self.out_channel, height, width) 262 | else: 263 | input = input.view(1, batch * in_channel, height, width) 264 | out = F.conv2d(input, weight, padding=self.padding, groups=batch) 265 | _, _, height, width = out.shape 266 | out = out.view(batch, self.out_channel, height, width) 267 | 268 | return out 269 | 270 | 271 | class NoiseInjection(nn.Module): 272 | def __init__(self): 273 | super().__init__() 274 | 275 | self.weight = nn.Parameter(torch.zeros(1)) 276 | 277 | def forward(self, image, noise=None): 278 | 279 | if noise is None: 280 | return image 281 | else: 282 | return image + self.weight * noise 283 | 284 | 285 | class ConstantInput(nn.Module): 286 | def __init__(self, channel, size=4): 287 | super().__init__() 288 | 289 | self.input = nn.Parameter(torch.randn(1, channel, size, size)) 290 | 291 | def forward(self, input): 292 | batch = input.shape[0] 293 | out = self.input.repeat(batch, 1, 1, 1) 294 | 295 | return out 296 | 297 | 298 | class StyledConv(nn.Module): 299 | def __init__(self, in_channel, out_channel, kernel_size, style_dim, upsample=False, blur_kernel=[1, 3, 3, 1], 300 | demodulate=True): 301 | super().__init__() 302 | 303 | self.conv = ModulatedConv2d( 304 | in_channel, 305 | out_channel, 306 | kernel_size, 307 | style_dim, 308 | upsample=upsample, 309 | blur_kernel=blur_kernel, 310 | demodulate=demodulate, 311 | ) 312 | 313 | self.noise = NoiseInjection() 314 | self.activate = FusedLeakyReLU(out_channel) 315 | 316 | def forward(self, input, style, noise=None): 317 | out = self.conv(input, style) 318 | out = self.noise(out, noise=noise) 319 | out = self.activate(out) 320 | 321 | return out 322 | 323 | 324 | class ConvLayer(nn.Sequential): 325 | def __init__( 326 | self, 327 | in_channel, 328 | out_channel, 329 | kernel_size, 330 | downsample=False, 331 | blur_kernel=[1, 3, 3, 1], 332 | bias=True, 333 | activate=True, 334 | ): 335 | layers = [] 336 | 337 | if downsample: 338 | factor = 2 339 | p = (len(blur_kernel) - factor) + (kernel_size - 1) 340 | pad0 = (p + 1) // 2 341 | pad1 = p // 2 342 | 343 | layers.append(Blur(blur_kernel, pad=(pad0, pad1))) 344 | 345 | stride = 2 346 | self.padding = 0 347 | 348 | else: 349 | stride = 1 350 | self.padding = kernel_size // 2 351 | 352 | layers.append(EqualConv2d(in_channel, out_channel, kernel_size, padding=self.padding, stride=stride, 353 | bias=bias and not activate)) 354 | 355 | if activate: 356 | if bias: 357 | layers.append(FusedLeakyReLU(out_channel)) 358 | else: 359 | layers.append(ScaledLeakyReLU(0.2)) 360 | 361 | super().__init__(*layers) 362 | 363 | 364 | class ToRGB(nn.Module): 365 | def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]): 366 | super().__init__() 367 | 368 | if upsample: 369 | self.upsample = Upsample(blur_kernel) 370 | 371 | self.conv = ConvLayer(in_channel, 3, 1) 372 | self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) 373 | 374 | def forward(self, input, skip=None): 375 | out = self.conv(input) 376 | out = out + self.bias 377 | 378 | if skip is not None: 379 | skip = self.upsample(skip) 380 | out = out + skip 381 | 382 | return out 383 | 384 | 385 | class ToFlow(nn.Module): 386 | def __init__(self, in_channel, style_dim, upsample=True, blur_kernel=[1, 3, 3, 1]): 387 | super().__init__() 388 | 389 | if upsample: 390 | self.upsample = Upsample(blur_kernel) 391 | 392 | self.conv = ModulatedConv2d(in_channel, 3, 1, style_dim, demodulate=False) 393 | self.bias = nn.Parameter(torch.zeros(1, 3, 1, 1)) 394 | 395 | def forward(self, input, style, feat, skip=None): 396 | out = self.conv(input, style) 397 | out = out + self.bias 398 | 399 | # warping 400 | xs = np.linspace(-1, 1, input.size(2)) 401 | xs = np.meshgrid(xs, xs) 402 | xs = np.stack(xs, 2) 403 | 404 | xs = torch.tensor(xs, requires_grad=False).float().unsqueeze(0).repeat(input.size(0), 1, 1, 1).cuda() 405 | 406 | if skip is not None: 407 | skip = self.upsample(skip) 408 | out = out + skip 409 | 410 | sampler = torch.tanh(out[:, 0:2, :, :]) 411 | mask = torch.sigmoid(out[:, 2:3, :, :]) 412 | flow = sampler.permute(0, 2, 3, 1) + xs # B x h x w 2 413 | feat_warp = F.grid_sample(feat, flow, align_corners=False) * mask 414 | 415 | return feat_warp, feat_warp + input * (1.0 - mask), out, flow 416 | 417 | 418 | class Direction(nn.Module): 419 | def __init__(self, motion_dim): 420 | super(Direction, self).__init__() 421 | 422 | self.weight = nn.Parameter(torch.randn(512, motion_dim)) 423 | 424 | def forward(self, input): 425 | weight = self.weight + 1e-8 426 | Q, R = torch.linalg.qr(weight) # get eignvector, orthogonal [n1, n2, n3, n4] 427 | 428 | if input is None: 429 | return Q 430 | else: 431 | input_diag = torch.diag_embed(input) # alpha, diagonal matrix 432 | out = torch.matmul(input_diag, Q.T) 433 | out = torch.sum(out, dim=1) 434 | return out 435 | 436 | 437 | class Synthesis(nn.Module): 438 | def __init__(self, size, style_dim, motion_dim, blur_kernel=[1, 3, 3, 1], channel_multiplier=1): 439 | super(Synthesis, self).__init__() 440 | 441 | self.size = size 442 | self.style_dim = style_dim 443 | self.motion_dim = motion_dim 444 | 445 | self.direction = Direction(motion_dim) 446 | 447 | self.channels = { 448 | 4: 512, 449 | 8: 512, 450 | 16: 512, 451 | 32: 512, 452 | 64: 256 * channel_multiplier, 453 | 128: 128 * channel_multiplier, 454 | 256: 64 * channel_multiplier, 455 | 512: 32 * channel_multiplier, 456 | 1024: 16 * channel_multiplier, 457 | } 458 | 459 | self.input = ConstantInput(self.channels[4]) 460 | self.conv1 = StyledConv(self.channels[4], self.channels[4], 3, style_dim, blur_kernel=blur_kernel) 461 | self.to_rgb1 = ToRGB(self.channels[4], style_dim, upsample=False) 462 | 463 | self.log_size = int(math.log(size, 2)) 464 | self.num_layers = (self.log_size - 2) * 2 + 1 465 | 466 | self.convs = nn.ModuleList() 467 | self.upsamples = nn.ModuleList() 468 | self.to_rgbs = nn.ModuleList() 469 | self.to_flows = nn.ModuleList() 470 | 471 | in_channel = self.channels[4] 472 | 473 | for i in range(3, self.log_size + 1): 474 | out_channel = self.channels[2 ** i] 475 | 476 | self.convs.append(StyledConv(in_channel, out_channel, 3, style_dim, upsample=True, 477 | blur_kernel=blur_kernel)) 478 | self.convs.append(StyledConv(out_channel, out_channel, 3, style_dim, blur_kernel=blur_kernel)) 479 | self.to_rgbs.append(ToRGB(out_channel, style_dim)) 480 | 481 | self.to_flows.append(ToFlow(out_channel, style_dim)) 482 | 483 | in_channel = out_channel 484 | 485 | self.n_latent = self.log_size * 2 - 2 486 | 487 | def forward(self, wa, alpha, feats): 488 | bs = wa.shape[0] 489 | 490 | if alpha is not None: 491 | if len(alpha) > 1: 492 | directions_target = self.direction(alpha[0]) # target 493 | directions_source = self.direction(alpha[1]) # source 494 | directions_start = self.direction(alpha[2]) # start 495 | latent = wa + (directions_target - directions_start) + directions_source 496 | else: 497 | directions = self.direction(alpha[0]) 498 | latent = wa + directions # wa + directions 499 | else: 500 | latent = wa 501 | 502 | inject_index = self.n_latent 503 | latent = latent.unsqueeze(1).repeat(1, inject_index, 1) 504 | 505 | out = self.input(latent) 506 | out = self.conv1(out, latent[:, 0]) 507 | 508 | i = 1 509 | for conv1, conv2, to_rgb, to_flow, feat in zip(self.convs[::2], self.convs[1::2], self.to_rgbs, 510 | self.to_flows, feats): 511 | out = conv1(out, latent[:, i]) 512 | out = conv2(out, latent[:, i + 1]) 513 | if out.size(2) == 8: 514 | out_warp, out, skip_flow, _ = to_flow(out, latent[:, i + 2], feat) 515 | skip = to_rgb(out_warp) 516 | elif out.size(2) == 64: 517 | out_warp, out, skip_flow, flow = to_flow(out, latent[:, i + 2], feat, skip_flow) 518 | skip = to_rgb(out_warp, skip) 519 | else: 520 | out_warp, out, skip_flow, _ = to_flow(out, latent[:, i + 2], feat, skip_flow) 521 | skip = to_rgb(out_warp, skip) 522 | i += 2 523 | 524 | img = skip 525 | 526 | return img, flow 527 | 528 | def synthesis(self, wa, feats): 529 | bs = wa.shape[0] 530 | 531 | if alpha is not None: 532 | if len(alpha) > 1: 533 | directions_target = self.direction(alpha[0]) # target 534 | directions_source = self.direction(alpha[1]) # source 535 | directions_start = self.direction(alpha[2]) # start 536 | latent = wa + (directions_target - directions_start) + directions_source 537 | else: 538 | directions = self.direction(alpha[0]) 539 | latent = wa + directions # wa + directions 540 | else: 541 | latent = wa 542 | 543 | inject_index = self.n_latent 544 | latent = latent.unsqueeze(1).repeat(1, inject_index, 1) 545 | 546 | out = self.input(latent) 547 | out = self.conv1(out, latent[:, 0]) 548 | 549 | i = 1 550 | for conv1, conv2, to_rgb, to_flow, feat in zip(self.convs[::2], self.convs[1::2], self.to_rgbs, 551 | self.to_flows, feats): 552 | out = conv1(out, latent[:, i]) 553 | out = conv2(out, latent[:, i + 1]) 554 | if out.size(2) == 8: 555 | out_warp, out, skip_flow, _ = to_flow(out, latent[:, i + 2], feat) 556 | skip = to_rgb(out_warp) 557 | elif out.size(2) == 64: 558 | out_warp, out, skip_flow, flow = to_flow(out, latent[:, i + 2], feat, skip_flow) 559 | skip = to_rgb(out_warp, skip) 560 | else: 561 | out_warp, out, skip_flow, _ = to_flow(out, latent[:, i + 2], feat, skip_flow) 562 | skip = to_rgb(out_warp, skip) 563 | i += 2 564 | 565 | img = skip 566 | 567 | return img, flow -------------------------------------------------------------------------------- /models/wav2vec2.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | from transformers import Wav2Vec2Model 4 | from transformers.modeling_outputs import BaseModelOutput 5 | 6 | 7 | class Wav2VecModel(Wav2Vec2Model): 8 | """ 9 | Wav2VecModel is a custom model class that extends the Wav2Vec2Model class from the transformers library. 10 | It inherits all the functionality of the Wav2Vec2Model and adds additional methods for feature extraction and encoding. 11 | ... 12 | 13 | Attributes: 14 | base_model (Wav2Vec2Model): The base Wav2Vec2Model object. 15 | 16 | Methods: 17 | forward(input_values, seq_len, attention_mask=None, mask_time_indices=None 18 | , output_attentions=None, output_hidden_states=None, return_dict=None): 19 | Forward pass of the Wav2VecModel. 20 | It takes input_values, seq_len, and other optional parameters as input and returns the output of the base model. 21 | 22 | feature_extract(input_values, seq_len): 23 | Extracts features from the input_values using the base model. 24 | 25 | encode(extract_features, attention_mask=None, mask_time_indices=None, output_attentions=None, output_hidden_states=None, return_dict=None): 26 | Encodes the extracted features using the base model and returns the encoded features. 27 | """ 28 | def forward( 29 | self, 30 | input_values, 31 | seq_len, 32 | attention_mask=None, 33 | mask_time_indices=None, 34 | output_attentions=None, 35 | output_hidden_states=None, 36 | return_dict=None, 37 | ): 38 | """ 39 | Forward pass of the Wav2Vec model. 40 | 41 | Args: 42 | self: The instance of the model. 43 | input_values: The input values (waveform) to the model. 44 | seq_len: The sequence length of the input values. 45 | attention_mask: Attention mask to be used for the model. 46 | mask_time_indices: Mask indices to be used for the model. 47 | output_attentions: If set to True, returns attentions. 48 | output_hidden_states: If set to True, returns hidden states. 49 | return_dict: If set to True, returns a BaseModelOutput instead of a tuple. 50 | 51 | Returns: 52 | The output of the Wav2Vec model. 53 | """ 54 | self.config.output_attentions = True 55 | 56 | output_hidden_states = ( 57 | output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states 58 | ) 59 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict 60 | with torch.no_grad(): 61 | extract_features = self.feature_extractor(input_values) 62 | extract_features = extract_features.transpose(1, 2) 63 | extract_features = linear_interpolation(extract_features, seq_len=seq_len) 64 | 65 | if attention_mask is not None: 66 | # compute reduced attention_mask corresponding to feature vectors 67 | attention_mask = self._get_feature_vector_attention_mask( 68 | extract_features.shape[1], attention_mask, add_adapter=False 69 | ) 70 | 71 | hidden_states, extract_features = self.feature_projection(extract_features) 72 | hidden_states1 = self._mask_hidden_states( 73 | hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask 74 | ) 75 | 76 | encoder_outputs = self.encoder( 77 | hidden_states, 78 | attention_mask=attention_mask, 79 | output_attentions=output_attentions, 80 | output_hidden_states=output_hidden_states, 81 | return_dict=return_dict, 82 | ) 83 | 84 | hidden_states = encoder_outputs[0] 85 | 86 | if self.adapter is not None: 87 | hidden_states = self.adapter(hidden_states) 88 | 89 | if not return_dict: 90 | return (hidden_states, ) + encoder_outputs[1:] 91 | 92 | return BaseModelOutput( 93 | last_hidden_state=hidden_states, 94 | hidden_states=encoder_outputs.hidden_states, 95 | attentions=encoder_outputs.attentions) 96 | 97 | def feature_extract( 98 | self, 99 | input_values, 100 | seq_len, 101 | ): 102 | """ 103 | Extracts features from the input values and returns the extracted features. 104 | 105 | Parameters: 106 | input_values (torch.Tensor): The input values to be processed. 107 | seq_len (torch.Tensor): The sequence lengths of the input values. 108 | 109 | Returns: 110 | extracted_features (torch.Tensor): The extracted features from the input values. 111 | """ 112 | extract_features = self.feature_extractor(input_values) 113 | extract_features = extract_features.transpose(1, 2) 114 | extract_features = linear_interpolation(extract_features, seq_len=seq_len) 115 | 116 | return extract_features 117 | 118 | def encode( 119 | self, 120 | extract_features, 121 | attention_mask=None, 122 | mask_time_indices=None, 123 | output_attentions=None, 124 | output_hidden_states=None, 125 | return_dict=None, 126 | ): 127 | """ 128 | Encodes the input features into the output space. 129 | 130 | Args: 131 | extract_features (torch.Tensor): The extracted features from the audio signal. 132 | attention_mask (torch.Tensor, optional): Attention mask to be used for padding. 133 | mask_time_indices (torch.Tensor, optional): Masked indices for the time dimension. 134 | output_attentions (bool, optional): If set to True, returns the attention weights. 135 | output_hidden_states (bool, optional): If set to True, returns all hidden states. 136 | return_dict (bool, optional): If set to True, returns a BaseModelOutput instead of the tuple. 137 | 138 | Returns: 139 | The encoded output features. 140 | """ 141 | self.config.output_attentions = True 142 | 143 | output_hidden_states = ( 144 | output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states 145 | ) 146 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict 147 | 148 | if attention_mask is not None: 149 | # compute reduced attention_mask corresponding to feature vectors 150 | attention_mask = self._get_feature_vector_attention_mask( 151 | extract_features.shape[1], attention_mask, add_adapter=False 152 | ) 153 | 154 | hidden_states, extract_features = self.feature_projection(extract_features) 155 | hidden_states = self._mask_hidden_states( 156 | hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask 157 | ) 158 | 159 | encoder_outputs = self.encoder( 160 | hidden_states, 161 | attention_mask=attention_mask, 162 | output_attentions=output_attentions, 163 | output_hidden_states=output_hidden_states, 164 | return_dict=return_dict, 165 | ) 166 | 167 | hidden_states = encoder_outputs[0] 168 | 169 | if self.adapter is not None: 170 | hidden_states = self.adapter(hidden_states) 171 | 172 | if not return_dict: 173 | return (hidden_states, ) + encoder_outputs[1:] 174 | return BaseModelOutput( 175 | last_hidden_state=hidden_states, 176 | hidden_states=encoder_outputs.hidden_states, 177 | attentions=encoder_outputs.attentions, 178 | ) 179 | 180 | 181 | def linear_interpolation(features, seq_len): 182 | """ 183 | Transpose the features to interpolate linearly. 184 | 185 | Args: 186 | features (torch.Tensor): The extracted features to be interpolated. 187 | seq_len (torch.Tensor): The sequence lengths of the features. 188 | 189 | Returns: 190 | torch.Tensor: The interpolated features. 191 | """ 192 | features = features.transpose(1, 2) 193 | output_features = F.interpolate(features, size=seq_len, align_corners=True, mode='linear') 194 | return output_features.transpose(1, 2) 195 | -------------------------------------------------------------------------------- /models/wav2vec2_ser.py: -------------------------------------------------------------------------------- 1 | import os, torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | 5 | from dataclasses import dataclass 6 | from typing import Optional, Tuple 7 | 8 | from transformers.file_utils import ModelOutput 9 | from transformers import Wav2Vec2FeatureExtractor 10 | from transformers.models.wav2vec2.modeling_wav2vec2 import Wav2Vec2PreTrainedModel, Wav2Vec2Model 11 | 12 | 13 | @dataclass 14 | class SpeechClassifierOutput(ModelOutput): 15 | loss: Optional[torch.FloatTensor] = None 16 | logits: torch.FloatTensor = None 17 | hidden_states: Optional[Tuple[torch.FloatTensor]] = None 18 | attentions: Optional[Tuple[torch.FloatTensor]] = None 19 | 20 | 21 | class Wav2Vec2ClassificationHead(nn.Module): 22 | """Head for wav2vec classification task.""" 23 | 24 | def __init__(self, config): 25 | super().__init__() 26 | self.dense = nn.Linear(config.hidden_size, config.hidden_size) 27 | self.dropout = nn.Dropout(config.final_dropout) 28 | self.out_proj = nn.Linear(config.hidden_size, config.num_labels) 29 | 30 | def forward(self, features, **kwargs): 31 | x = features 32 | x = self.dropout(x) 33 | x = self.dense(x) 34 | x = torch.tanh(x) 35 | x = self.dropout(x) 36 | x = self.out_proj(x) 37 | return x 38 | 39 | 40 | class Wav2Vec2ForSpeechClassification(Wav2Vec2PreTrainedModel): 41 | def __init__(self, config): 42 | super().__init__(config) 43 | self.num_labels = config.num_labels 44 | self.pooling_mode = config.pooling_mode 45 | self.config = config 46 | 47 | self.wav2vec2 = Wav2Vec2Model(config) 48 | self.classifier = Wav2Vec2ClassificationHead(config) 49 | 50 | self.init_weights() 51 | 52 | def freeze_feature_extractor(self): 53 | self.wav2vec2.feature_extractor._freeze_parameters() 54 | 55 | def merged_strategy( 56 | self, 57 | hidden_states, 58 | mode="mean" 59 | ): 60 | if mode == "mean": 61 | outputs = torch.mean(hidden_states, dim=1) 62 | elif mode == "sum": 63 | outputs = torch.sum(hidden_states, dim=1) 64 | elif mode == "max": 65 | outputs = torch.max(hidden_states, dim=1)[0] 66 | else: 67 | raise Exception( 68 | "The pooling method hasn't been defined! Your pooling mode must be one of these ['mean', 'sum', 'max']") 69 | 70 | return outputs 71 | 72 | def forward( 73 | self, 74 | input_values, 75 | attention_mask=None, 76 | output_attentions=None, 77 | output_hidden_states=None, 78 | return_dict=None, 79 | labels=None, 80 | ): 81 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict 82 | outputs = self.wav2vec2( 83 | input_values, 84 | attention_mask=attention_mask, 85 | output_attentions=output_attentions, 86 | output_hidden_states=output_hidden_states, 87 | return_dict=return_dict, 88 | ) 89 | hidden_states = outputs[0] 90 | hidden_states = self.merged_strategy(hidden_states, mode=self.pooling_mode) 91 | logits = self.classifier(hidden_states) 92 | 93 | loss = None 94 | if labels is not None: 95 | if self.config.problem_type is None: 96 | if self.num_labels == 1: 97 | self.config.problem_type = "regression" 98 | elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): 99 | self.config.problem_type = "single_label_classification" 100 | else: 101 | self.config.problem_type = "multi_label_classification" 102 | 103 | if self.config.problem_type == "regression": 104 | loss_fct = MSELoss() 105 | loss = loss_fct(logits.view(-1, self.num_labels), labels) 106 | elif self.config.problem_type == "single_label_classification": 107 | loss_fct = CrossEntropyLoss() 108 | loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) 109 | elif self.config.problem_type == "multi_label_classification": 110 | loss_fct = BCEWithLogitsLoss() 111 | loss = loss_fct(logits, labels) 112 | 113 | if not return_dict: 114 | output = (logits,) + outputs[2:] 115 | return ((loss,) + output) if loss is not None else output 116 | 117 | return SpeechClassifierOutput( 118 | loss=loss, 119 | logits=logits, 120 | hidden_states=outputs.hidden_states, 121 | attentions=outputs.attentions, 122 | ) 123 | 124 | 125 | -------------------------------------------------------------------------------- /options/base_options.py: -------------------------------------------------------------------------------- 1 | import os, argparse, json 2 | 3 | class BaseOptions(): 4 | def parse(self): 5 | parser = argparse.ArgumentParser() 6 | self.parser = self.initialize(parser) 7 | self.opt = self.parser.parse_args() 8 | return self.opt 9 | 10 | def initialize(self, parser): 11 | parser.add_argument('--pretrained_dir', type=str, default='./checkpoints') 12 | parser.add_argument('--seed', default=15, type=int) 13 | parser.add_argument('--fix_noise_seed', action='store_true') 14 | 15 | # video 16 | parser.add_argument('--input_size', type=int, default=512, help='input image size') 17 | parser.add_argument('--input_nc', type=int, default=3, help='input image channel') 18 | parser.add_argument('--fps', type=float, default=25.) 19 | 20 | # audio 21 | parser.add_argument('--sampling_rate', type=int, default=16000) 22 | parser.add_argument('--audio_marcing', type=int, default=2, help='number of adjacent frames. For value v, t -> [t-v, ..., t, ..., t+v]') 23 | parser.add_argument('--wav2vec_sec', default=2, type=float, help='window length L (seconds), 50 frames') 24 | parser.add_argument('--wav2vec_model_path', default='./checkpoints/wav2vec2-base-960h') 25 | parser.add_argument('--audio2emotion_path', default='./checkpoints/wav2vec-english-speech-emotion-recognition') 26 | parser.add_argument('--attention_window', default=2, type=int, help='attention window size, e.g., if 1, attend frames of t-1, t, t+1 for frame t') 27 | 28 | parser.add_argument('--only_last_features', action='store_true') 29 | parser.add_argument('--average_emotion', action='store_true', help='averaging emotion or not.') 30 | 31 | # dropout 32 | parser.add_argument('--audio_dropout_prob', default=0.1, type=float) 33 | parser.add_argument('--ref_dropout_prob', default=0.1, type=float) 34 | parser.add_argument('--emotion_dropout_prob', default=0.1, type=float) 35 | 36 | # model Hyper Parameters 37 | parser.add_argument('--style_dim', type=int, default=512, help='w latent dimension') 38 | parser.add_argument('--dim_a', type=int, default=512, help='audio dimension') 39 | parser.add_argument('--dim_w', type=int, default=512, help='face dimension') 40 | parser.add_argument('--dim_h', type=int, default=1024, help='hidden dimension') 41 | parser.add_argument('--dim_m', type=int, default=20, help='dimension of orthogonal basis') 42 | parser.add_argument('--dim_e', type=int, default=7, help='emotion dimension') 43 | 44 | # option for FMT 45 | parser.add_argument('--fmt_depth', default=8, type=int) 46 | parser.add_argument('--num_heads', default=8, type=int) 47 | parser.add_argument('--mlp_ratio', default=4.0, type=float) 48 | parser.add_argument('--no_learned_pe', action='store_true') 49 | parser.add_argument('--num_prev_frames', type=int, default=10) 50 | parser.add_argument('--max_grad_norm', default=1, type=float, help='max grad norm for training transformers') 51 | 52 | parser.add_argument('--ode_atol', default=1e-5, type=float) 53 | parser.add_argument('--ode_rtol', default=1e-5, type=float) 54 | parser.add_argument('--nfe', default=10, type=int, 55 | help='Number of Function Evaluateions (NFEs) for ODE solver') 56 | parser.add_argument('--torchdiffeq_ode_method', default='euler', 57 | help='ODE solver') 58 | parser.add_argument('--a_cfg_scale', default=2.0, type=float, 59 | help='audio classifier-free guidance (vector field) scale') 60 | parser.add_argument('--e_cfg_scale', default=1.0, type=float, 61 | help='emotion classifier-free guidance (vector field) scale') 62 | parser.add_argument('--r_cfg_scale', default=1.0, type=float, 63 | help='reference classifier-free guidance (vector field) scale') 64 | 65 | # option for Diffusion (ablation) 66 | parser.add_argument('--n_diff_steps', type=int, default=500, help='number of diffusion steps') 67 | parser.add_argument('--diff_schedule', type=str, default='cosine', choices=['linear', 'cosine', 'quadratic', 'sigmoid']) 68 | parser.add_argument('--diffusion_mode', type=str, default='sample', choices=['sample', 'noise']) 69 | return parser 70 | 71 | 72 | def print_options(self): 73 | """Print and save options 74 | 75 | It will print both current options and default values(if different). 76 | It will save options into a text file / [checkpoints_dir] / opt.txt 77 | """ 78 | message = '' 79 | message += '----------------- Options ---------------\n' 80 | for k, v in sorted(vars(self.opt).items()): 81 | comment = '' 82 | default = self.parser.get_default(k) 83 | if v != default: 84 | comment = '\t[default: %s]' % str(default) 85 | message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment) 86 | message += '----------------- End -------------------' 87 | print(message) 88 | 89 | 90 | def save_options(opt, save_path): 91 | with open(save_path, 'wt') as f: 92 | json.dump(vars(opt), f, indent=4) 93 | 94 | 95 | def load_options(opt, load_path): 96 | with open(load_path, 'rt') as f: 97 | _update = json.loads(f) 98 | opt.update(_update) 99 | return opt 100 | 101 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyyaml 2 | opencv-python 3 | pandas 4 | tqdm 5 | matplotlib 6 | flow-vis 7 | librosa 8 | transformers==4.30.2 9 | albumentations==1.4.15 10 | albucore==0.0.16 11 | torchdiffeq==0.2.5 12 | timm==1.0.9 13 | face_alignment==1.4.1 14 | av==12.0.0 15 | --------------------------------------------------------------------------------