prismaudio-project commited on
Commit
ddb382a
·
1 Parent(s): ac1ae5d
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. README.md +153 -10
  3. ThinkSound/__init__.py +1 -0
  4. ThinkSound/configs/model_configs/prismaudio.json +141 -0
  5. ThinkSound/configs/model_configs/stable_audio_2_0_vae.json +122 -0
  6. ThinkSound/configs/model_configs/thinksound.json +147 -0
  7. ThinkSound/configs/multimodal_dataset_demo.json +52 -0
  8. ThinkSound/configs/multimodal_dataset_demo_prismaudio.json +27 -0
  9. ThinkSound/data/__init__.py +0 -0
  10. ThinkSound/data/datamodule.py +331 -0
  11. ThinkSound/data/dataset.py +1319 -0
  12. ThinkSound/data/utils.py +378 -0
  13. ThinkSound/inference/__init__.py +0 -0
  14. ThinkSound/inference/generation.py +274 -0
  15. ThinkSound/inference/sampling.py +286 -0
  16. ThinkSound/inference/utils.py +35 -0
  17. ThinkSound/interface/__init__.py +0 -0
  18. ThinkSound/interface/aeiou.py +278 -0
  19. ThinkSound/interface/gradio.py +700 -0
  20. ThinkSound/models/__init__.py +1 -0
  21. ThinkSound/models/adp.py +1588 -0
  22. ThinkSound/models/autoencoders.py +800 -0
  23. ThinkSound/models/blocks.py +339 -0
  24. ThinkSound/models/bottleneck.py +355 -0
  25. ThinkSound/models/codebook_patterns.py +545 -0
  26. ThinkSound/models/conditioners.py +1082 -0
  27. ThinkSound/models/diffusion.py +957 -0
  28. ThinkSound/models/diffusion_prior.py +82 -0
  29. ThinkSound/models/discriminators.py +546 -0
  30. ThinkSound/models/dit (1).py +430 -0
  31. ThinkSound/models/dit.py +547 -0
  32. ThinkSound/models/factory.py +156 -0
  33. ThinkSound/models/lm.py +541 -0
  34. ThinkSound/models/lm_backbone.py +159 -0
  35. ThinkSound/models/lm_continuous.py +525 -0
  36. ThinkSound/models/local_attention.py +278 -0
  37. ThinkSound/models/meta_queries/__init__.py +0 -0
  38. ThinkSound/models/meta_queries/metaquery.py +435 -0
  39. ThinkSound/models/meta_queries/model.py +578 -0
  40. ThinkSound/models/meta_queries/models/__init__.py +0 -0
  41. ThinkSound/models/meta_queries/models/process_audio_info.py +94 -0
  42. ThinkSound/models/meta_queries/models/qwen25VL.py +0 -0
  43. ThinkSound/models/meta_queries/models/qwen25omni.py +0 -0
  44. ThinkSound/models/meta_queries/transformer_encoder.py +179 -0
  45. ThinkSound/models/mmdit.py +555 -0
  46. ThinkSound/models/mmmodules/__init__.py +0 -0
  47. ThinkSound/models/mmmodules/ext/__init__.py +1 -0
  48. ThinkSound/models/mmmodules/ext/rotary_embeddings.py +35 -0
  49. ThinkSound/models/mmmodules/ext/stft_converter.py +183 -0
  50. ThinkSound/models/mmmodules/ext/stft_converter_mel.py +234 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.png filter=lfs diff=lfs merge=lfs -text
37
+ *.jpg filter=lfs diff=lfs merge=lfs -text
38
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
- title: PrismAudio
3
- emoji: 📉
4
- colorFrom: purple
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 6.9.0
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h1 align="center">PrismAudio</h1>
2
+
3
+
4
+ <p align="center">
5
+ <img src="https://img.shields.io/badge/ICLR 2026-Main Conference-blue.svg" alt="ICLR 2026"/>
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a href="https://arxiv.org/abs/2511.18833">
10
+ <img src="https://img.shields.io/badge/arXiv-2511.18833-b31b1b.svg" alt="arXiv"/>
11
+ </a>
12
+ &nbsp;
13
+ <a href="http://prismaudio-project.github.io/">
14
+ <img src="https://img.shields.io/badge/Online%20Demo-🌐-blue" alt="Online Demo"/>
15
+ </a>
16
+
17
+ </p>
18
+
19
+ <p align="center">
20
+ If you find this project useful,<br>
21
+ a star ⭐ on GitHub would be greatly appreciated!
22
+ </p>
23
+
24
  ---
25
+
26
+ **PrismAudio** is the first framework to integrate Reinforcement Learning into Video-to-Audio (V2A) generation with specialized Chain-of-Thought (CoT) planning. Building upon [ThinkSound](https://arxiv.org/pdf/2506.21448)'s pioneering CoT-based V2A framework, PrismAudio further decomposes monolithic reasoning into four specialized CoT modules (Semantic, Temporal, Aesthetic, and Spatial), each paired with targeted reward functions, enabling multi-dimensional RL optimization that jointly improves reasoning across all perceptual dimensions.
27
+
28
+
29
+
 
 
 
 
30
  ---
31
 
32
+ ## 📰 News
33
+
34
+ - **2026.03.22** &nbsp; 🔥 We have released **PrismAudio**, our next-generation video-to-audio generation model! For more details, please refer to the [`prismaudio`](https://github.com/liuhuadai/ThinkSound/tree/prismaudio) branch!
35
+ - **2026.01.26** &nbsp; 🎉 PrismAudio has been accepted to the **ICLR 2026 Main Conference**! We plan to release the project in February 2026.
36
+ - **2025.11.25** &nbsp; 🔥 [Online PrismAudio Demo](http://prismaudio-project.github.io/) is live - try it now!
37
+ - **2025.11.25** &nbsp; 🔥 [PrismAudio paper](https://arxiv.org/pdf/2511.18833) released on arXiv, the first multi-dimensional CoT-RL framework for Video-to-Audio Generation!
38
+ - **2025.09.19** &nbsp; 🎉 ThinkSound has been accepted to the **NeurIPS 2025 Main Conference**!
39
+ - **2025.09.01** &nbsp; Our AudioCoT dataset is now open-sourced and available on [Hugging Face](https://huggingface.co/datasets/liuhuadai/AudioCoT)!
40
+ - **2025.07.17** &nbsp; 🧠 Finetuning enabled: training and finetuning code is now publicly available, along with clear usage instructions to help you customize and extend ThinkSound with your own data.
41
+ - **2025.07.15** &nbsp; 📦 Simplified installation and usability: dependencies on PyPI for easy cross-platform setup; Windows `.bat` scripts automate environment creation and script running.
42
+ - **2025.07.08** &nbsp; 🔧 Major update: model lightweighted and optimized memory and GPU usage, now supports high-throughput audio generation at scale!
43
+ - **2025.07.01** &nbsp; Online demo on [Hugging Face Spaces](https://huggingface.co/spaces/FunAudioLLM/ThinkSound) and [ModelScope](https://modelscope.cn/studios/iic/ThinkSound) for interactive experience!
44
+ - **2025.07.01** &nbsp; Released inference scripts and web interface.
45
+ - **2025.06** &nbsp; [ThinkSound paper](https://arxiv.org/pdf/2506.21448) released on arXiv!
46
+ - **2025.06** &nbsp; [Online Demo](http://thinksound-project.github.io/) is live - try it now!
47
+
48
+ ---
49
+
50
+ ## 🚀 Features
51
+
52
+ - **V2A SOTA**: Achieves state-of-the-art results across all four perceptual dimensions on both VGGSound and AudioCanvas benchmarks.
53
+ - **Decomposed CoT Reasoning**: Four specialized CoT modules (Semantic, Temporal, Aesthetic, Spatial) each providing focused, interpretable reasoning for its corresponding perceptual dimension.
54
+ - **Multi-dimensional RL**: Fast-GRPO enables efficient multi-dimensional reward optimization without compromising generation quality.
55
+ - **New Benchmark**: AudioCanvas — a rigorous V2A benchmark with 300 single-event classes and 501 multi-event samples covering diverse and challenging scenarios.
56
+ - **Efficient**: 518M parameters with faster inference than prior SOTAs.
57
+
58
+ ---
59
+
60
+ ## ✨ Method Overview
61
+
62
+ PrismAudio consists of three main components:
63
+
64
+ 1. **CoT-Aware Audio Foundation Model**: Built on a Multimodal Diffusion Transformer with flow matching, enhanced with VideoPrism for video understanding and T5-Gemma for structured CoT text encoding.
65
+ 2. **Decomposed Multi-Dimensional CoT Reasoning**: Four specialized CoT modules — Semantic, Temporal, Aesthetic, and Spatial — each providing targeted reasoning for its corresponding perceptual dimension.
66
+ 3. **Fast-GRPO Multi-Dimensional RL Framework**: A hybrid ODE-SDE sampling strategy that dramatically reduces training overhead while enabling multi-dimensional reward optimization across all perceptual dimensions.
67
+
68
+
69
+ ---
70
+
71
+ ## ⚡ Quick Start
72
+
73
+ ```bash
74
+ git clone -b prismaudio https://github.com/liuhuadai/ThinkSound.git
75
+ cd ThinkSound
76
+
77
+ conda create -n prismaudio python=3.10
78
+ conda activate prismaudio
79
+ chmod +x scripts/PrismAudio/setup/build_env.sh
80
+ ./scripts/PrismAudio/setup/build_env.sh
81
+
82
+ # Download pretrained weights to Directory ckpts/
83
+ # From Hugging Face: https://huggingface.co/liuhuadai/ThinkSound
84
+ # From ModelScope: https://www.modelscope.cn/models/iic/ThinkSound
85
+ git lfs install
86
+ git clone https://huggingface.co/liuhuadai/ThinkSound ckpts
87
+ ```
88
+
89
+ ---
90
+
91
+ ## ▶️ Run Demo
92
+
93
+ ```bash
94
+ chmod +x scripts/PrismAudio/demo.sh
95
+ ./scripts/PrismAudio/demo.sh <path-to-your-demo-video> "<CoT description>"
96
+ ```
97
+
98
+ **Note:**
99
+ - `<path-to-your-demo-video>`: Path to a single input video file.
100
+ - `"<CoT description>"`: A structured CoT description of the audio to generate.
101
+
102
+ ---
103
+
104
+ ## 🏋️ Train the Model
105
+
106
+ See [`Training.md`](docs/PrismAudio/Training.md)
107
+
108
+ ---
109
+
110
+ ## 📄 License
111
+
112
+ This project is released under the Apache 2.0 License.
113
+
114
+ > **Note:**
115
+ > The code, models, and dataset are **for research and educational purposes only**.
116
+ > **Commercial use is NOT permitted.**
117
+ > For commercial licensing, please contact the authors.
118
+
119
+ **📦 Third-Party Components**
120
+
121
+ - **Stable Audio Open VAE** (by Stability AI): Licensed under the [Stability AI Community License](./third_party/LICENSE_StabilityAI.md). **Commercial use and redistribution require prior permission from Stability AI.**
122
+ - 📘 **All other code and models** are released under the Apache License 2.0.
123
+
124
+ ---
125
+
126
+ ## Acknowledgements
127
+
128
+ Many thanks to:
129
+
130
+ - **stable-audio-tools** (by Stability AI): For providing an easy-to-use framework for audio generation, as well as the VAE module and weights.
131
+ - **MMAudio**: For the implementation of the MM-DiT backbone in the audio domain.
132
+ - **ThinkSound**: For the foundational CoT-based V2A generation framework that PrismAudio builds upon.
133
+
134
+ ---
135
+
136
+ ## 📖 Citation
137
+
138
+ If you find PrismAudio useful in your research or work, please cite our paper:
139
+
140
+ ```bibtex
141
+ @misc{liu2025prismaudiodecomposedchainofthoughtsmultidimensional,
142
+ title={PrismAudio: Decomposed Chain-of-Thoughts and Multi-dimensional Rewards for Video-to-Audio Generation},
143
+ author={Huadai Liu and Kaicheng Luo and Wen Wang and Qian Chen and Peiwen Sun and Rongjie Huang and Xiangang Li and Jieping Ye and Wei Xue},
144
+ year={2025},
145
+ eprint={2511.18833},
146
+ archivePrefix={arXiv},
147
+ primaryClass={cs.SD},
148
+ url={https://arxiv.org/abs/2511.18833},
149
+ }
150
+ ```
151
+
152
+ ---
153
+
154
+ ## 📬 Contact
155
+
156
+ ✨ Feel free to [open an issue](https://github.com/liuhuadai/ThinkSound/issues) or contact us via email ([huadai.liu@connect.ust.hk](mailto:huadai.liu@connect.ust.hk)) if you have any questions or suggestions!
ThinkSound/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .models.factory import create_model_from_config, create_model_from_config_path
ThinkSound/configs/model_configs/prismaudio.json ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "diffusion_cond",
3
+ "sample_size": 397312,
4
+ "sample_rate": 44100,
5
+ "audio_channels": 2,
6
+ "model": {
7
+ "pretransform": {
8
+ "type": "autoencoder",
9
+ "iterate_batch": true,
10
+ "config": {
11
+ "encoder": {
12
+ "type": "oobleck",
13
+ "config": {
14
+ "in_channels": 2,
15
+ "channels": 128,
16
+ "c_mults": [1, 2, 4, 8, 16],
17
+ "strides": [2, 4, 4, 8, 8],
18
+ "latent_dim": 128,
19
+ "use_snake": true
20
+ }
21
+ },
22
+ "decoder": {
23
+ "type": "oobleck",
24
+ "config": {
25
+ "out_channels": 2,
26
+ "channels": 128,
27
+ "c_mults": [1, 2, 4, 8, 16],
28
+ "strides": [2, 4, 4, 8, 8],
29
+ "latent_dim": 64,
30
+ "use_snake": true,
31
+ "final_tanh": false
32
+ }
33
+ },
34
+ "bottleneck": {
35
+ "type": "vae"
36
+ },
37
+ "latent_dim": 64,
38
+ "downsampling_ratio": 2048,
39
+ "io_channels": 2
40
+ }
41
+ },
42
+ "conditioning": {
43
+ "configs": [
44
+ {
45
+ "id": "video_features",
46
+ "type": "cond_mlp",
47
+ "config": {
48
+ "dim": 1024,
49
+ "output_dim": 1024
50
+ }
51
+ },
52
+ {
53
+ "id": "text_features",
54
+ "type": "cond_mlp",
55
+ "config": {
56
+ "dim": 1024,
57
+ "output_dim": 1024
58
+ }
59
+ },
60
+ {
61
+ "id": "sync_features",
62
+ "type": "sync_mlp",
63
+ "config": {
64
+ "dim": 768,
65
+ "output_dim": 1024
66
+ }
67
+ }
68
+ ],
69
+ "cond_dim": 768
70
+ },
71
+ "diffusion": {
72
+ "cross_attention_cond_ids": ["video_features","text_features"],
73
+ "add_cond_ids": ["video_features"],
74
+ "sync_cond_ids": ["sync_features"],
75
+ "type": "dit",
76
+ "diffusion_objective": "rectified_flow",
77
+ "config": {
78
+ "io_channels": 64,
79
+ "embed_dim": 1024,
80
+ "depth": 24,
81
+ "num_heads": 16,
82
+ "cond_token_dim": 1024,
83
+ "add_token_dim": 1024,
84
+ "sync_token_dim": 1024,
85
+ "project_cond_tokens": false,
86
+ "transformer_type": "continuous_transformer",
87
+ "attn_kwargs":{
88
+ "qk_norm": "rns"
89
+ },
90
+ "use_gated": true,
91
+ "use_sync_gated": true
92
+ }
93
+ },
94
+ "io_channels": 64
95
+ },
96
+ "training": {
97
+ "use_ema": true,
98
+ "log_loss_info": false,
99
+ "cfg_dropout_prob": 0.1,
100
+ "pre_encoded": true,
101
+ "timestep_sampler": "trunc_logit_normal",
102
+ "optimizer_configs": {
103
+ "diffusion": {
104
+ "optimizer": {
105
+ "type": "AdamW",
106
+ "config": {
107
+ "lr": 1e-4,
108
+ "betas": [0.9, 0.999],
109
+ "weight_decay": 1e-3
110
+ }
111
+ },
112
+ "scheduler": {
113
+ "type": "InverseLR",
114
+ "config": {
115
+ "inv_gamma": 100000,
116
+ "power": 0.5,
117
+ "warmup": 0.99
118
+ }
119
+ }
120
+ }
121
+ },
122
+ "demo": {
123
+ "demo_every": 5000,
124
+ "demo_steps": 24,
125
+ "num_demos": 10,
126
+ "demo_cond": [
127
+ "dataset/videoprism/test/0Cu33yBwAPg_000060.npz",
128
+ "dataset/videoprism/test/bmKtI808DsU_000009.npz",
129
+ "dataset/videoprism/test/VC0c22cJTbM_000424.npz",
130
+ "dataset/videoprism/test/F3gsbUTdc2U_000090.npz",
131
+ "dataset/videoprism/test/WatvT8A8iug_000100.npz",
132
+ "dataset/videoprism/test/0nvBTp-q7tU_000112.npz",
133
+ "dataset/videoprism/test/3-PFuDkTM48_000080.npz",
134
+ "dataset/videoprism/test/luSAuu-BoPs_000232.npz",
135
+ "dataset/videoprism/test/__8UJxW0aOQ_000002.npz",
136
+ "dataset/videoprism/test/_0m_YMpQayA_000168.npz"
137
+ ],
138
+ "demo_cfg_scales": [5]
139
+ }
140
+ }
141
+ }
ThinkSound/configs/model_configs/stable_audio_2_0_vae.json ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "autoencoder",
3
+ "sample_size": 65536,
4
+ "sample_rate": 44100,
5
+ "audio_channels": 2,
6
+ "model": {
7
+ "encoder": {
8
+ "type": "oobleck",
9
+ "config": {
10
+ "in_channels": 2,
11
+ "channels": 128,
12
+ "c_mults": [1, 2, 4, 8, 16],
13
+ "strides": [2, 4, 4, 8, 8],
14
+ "latent_dim": 128,
15
+ "use_snake": true
16
+ }
17
+ },
18
+ "decoder": {
19
+ "type": "oobleck",
20
+ "config": {
21
+ "out_channels": 2,
22
+ "channels": 128,
23
+ "c_mults": [1, 2, 4, 8, 16],
24
+ "strides": [2, 4, 4, 8, 8],
25
+ "latent_dim": 64,
26
+ "use_snake": true,
27
+ "final_tanh": false
28
+ }
29
+ },
30
+ "bottleneck": {
31
+ "type": "vae"
32
+ },
33
+ "latent_dim": 64,
34
+ "downsampling_ratio": 2048,
35
+ "io_channels": 2
36
+ },
37
+ "training": {
38
+ "learning_rate": 1.5e-4,
39
+ "warmup_steps": 0,
40
+ "use_ema": true,
41
+ "optimizer_configs": {
42
+ "autoencoder": {
43
+ "optimizer": {
44
+ "type": "AdamW",
45
+ "config": {
46
+ "betas": [0.8, 0.99],
47
+ "lr": 1.5e-4,
48
+ "weight_decay": 1e-3
49
+ }
50
+ },
51
+ "scheduler": {
52
+ "type": "InverseLR",
53
+ "config": {
54
+ "inv_gamma": 200000,
55
+ "power": 0.5,
56
+ "warmup": 0.999
57
+ }
58
+ }
59
+ },
60
+ "discriminator": {
61
+ "optimizer": {
62
+ "type": "AdamW",
63
+ "config": {
64
+ "betas": [0.8, 0.99],
65
+ "lr": 3e-4,
66
+ "weight_decay": 1e-3
67
+ }
68
+ },
69
+ "scheduler": {
70
+ "type": "InverseLR",
71
+ "config": {
72
+ "inv_gamma": 200000,
73
+ "power": 0.5,
74
+ "warmup": 0.999
75
+ }
76
+ }
77
+ }
78
+ },
79
+ "loss_configs": {
80
+ "discriminator": {
81
+ "type": "encodec",
82
+ "config": {
83
+ "filters": 64,
84
+ "n_ffts": [2048, 1024, 512, 256, 128],
85
+ "hop_lengths": [512, 256, 128, 64, 32],
86
+ "win_lengths": [2048, 1024, 512, 256, 128]
87
+ },
88
+ "weights": {
89
+ "adversarial": 0.1,
90
+ "feature_matching": 5.0
91
+ }
92
+ },
93
+ "spectral": {
94
+ "type": "mrstft",
95
+ "config": {
96
+ "fft_sizes": [2048, 1024, 512, 256, 128, 64, 32],
97
+ "hop_sizes": [512, 256, 128, 64, 32, 16, 8],
98
+ "win_lengths": [2048, 1024, 512, 256, 128, 64, 32],
99
+ "perceptual_weighting": true
100
+ },
101
+ "weights": {
102
+ "mrstft": 1.0
103
+ }
104
+ },
105
+ "time": {
106
+ "type": "l1",
107
+ "weights": {
108
+ "l1": 0.0
109
+ }
110
+ },
111
+ "bottleneck": {
112
+ "type": "kl",
113
+ "weights": {
114
+ "kl": 1e-4
115
+ }
116
+ }
117
+ },
118
+ "demo": {
119
+ "demo_every": 10000
120
+ }
121
+ }
122
+ }
ThinkSound/configs/model_configs/thinksound.json ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "mm_diffusion_cond",
3
+ "sample_size": 397312,
4
+ "sample_rate": 44100,
5
+ "audio_channels": 2,
6
+ "model": {
7
+ "pretransform": {
8
+ "type": "autoencoder",
9
+ "iterate_batch": true,
10
+ "config": {
11
+ "encoder": {
12
+ "type": "oobleck",
13
+ "config": {
14
+ "in_channels": 2,
15
+ "channels": 128,
16
+ "c_mults": [1, 2, 4, 8, 16],
17
+ "strides": [2, 4, 4, 8, 8],
18
+ "latent_dim": 128,
19
+ "use_snake": true
20
+ }
21
+ },
22
+ "decoder": {
23
+ "type": "oobleck",
24
+ "config": {
25
+ "out_channels": 2,
26
+ "channels": 128,
27
+ "c_mults": [1, 2, 4, 8, 16],
28
+ "strides": [2, 4, 4, 8, 8],
29
+ "latent_dim": 64,
30
+ "use_snake": true,
31
+ "final_tanh": false
32
+ }
33
+ },
34
+ "bottleneck": {
35
+ "type": "vae"
36
+ },
37
+ "latent_dim": 64,
38
+ "downsampling_ratio": 2048,
39
+ "io_channels": 2
40
+ }
41
+ },
42
+ "conditioning": {
43
+ "configs": [
44
+ {
45
+ "id": "metaclip_features",
46
+ "type": "mm_unchang",
47
+ "config": {
48
+ "dim": 1024,
49
+ "output_dim": 1024
50
+ }
51
+ },
52
+ {
53
+ "id": "metaclip_text_features",
54
+ "type": "mm_unchang",
55
+ "config": {
56
+ "dim": 1024,
57
+ "output_dim": 1024
58
+ }
59
+ },
60
+ {
61
+ "id": "sync_features",
62
+ "type": "mm_unchang",
63
+ "config": {
64
+ "dim": 768,
65
+ "output_dim": 768
66
+ }
67
+ },
68
+ {
69
+ "id": "t5_features",
70
+ "type": "mm_unchang",
71
+ "config": {
72
+ "dim": 2048,
73
+ "output_dim": 2048
74
+ }
75
+ }
76
+ ],
77
+ "cond_dim": 768
78
+ },
79
+ "diffusion": {
80
+ "mm_cond_ids": ["metaclip_features", "sync_features", "metaclip_text_features","t5_features"],
81
+ "type": "mmdit",
82
+ "diffusion_objective": "rectified_flow",
83
+ "config": {
84
+ "latent_dim":64,
85
+ "clip_dim":1024,
86
+ "sync_dim":768,
87
+ "text_dim":2048,
88
+ "hidden_dim":1024,
89
+ "depth":21,
90
+ "fused_depth":14,
91
+ "num_heads":16,
92
+ "latent_seq_len":194,
93
+ "clip_seq_len":72,
94
+ "sync_seq_len":216,
95
+ "v2": true,
96
+ "kernel_size": 3
97
+ }
98
+ },
99
+ "io_channels": 64
100
+ },
101
+ "training": {
102
+ "use_ema": true,
103
+ "log_loss_info": false,
104
+ "cfg_dropout_prob": 0.2,
105
+ "pre_encoded": true,
106
+ "timestep_sampler": "logit_normal",
107
+ "optimizer_configs": {
108
+ "diffusion": {
109
+ "optimizer": {
110
+ "type": "AdamW",
111
+ "config": {
112
+ "lr": 5e-5,
113
+ "betas": [0.9, 0.95],
114
+ "weight_decay": 1e-4,
115
+ "eps": 1e-6
116
+ }
117
+ },
118
+ "scheduler": {
119
+ "type": "InverseLR",
120
+ "config": {
121
+ "inv_gamma": 1000000,
122
+ "power": 0.5,
123
+ "warmup": 0.99
124
+ }
125
+ }
126
+ }
127
+ },
128
+ "demo": {
129
+ "demo_every": 5000,
130
+ "demo_steps": 24,
131
+ "num_demos": 10,
132
+ "demo_cond": [
133
+ "dataset/vggsound/video_latents_t5_clip_npz/test/0Cu33yBwAPg_000060.npz",
134
+ "dataset/vggsound/video_latents_t5_clip_npz/test/bmKtI808DsU_000009.npz",
135
+ "dataset/vggsound/video_latents_t5_clip_npz/test/VC0c22cJTbM_000424.npz",
136
+ "dataset/vggsound/video_latents_t5_clip_npz/test/F3gsbUTdc2U_000090.npz",
137
+ "dataset/vggsound/video_latents_t5_clip_npz/test/WatvT8A8iug_000100.npz",
138
+ "dataset/vggsound/video_latents_t5_clip_npz/test/0nvBTp-q7tU_000112.npz",
139
+ "dataset/vggsound/video_latents_t5_clip_npz/test/3-PFuDkTM48_000080.npz",
140
+ "dataset/vggsound/video_latents_t5_clip_npz/test/luSAuu-BoPs_000232.npz",
141
+ "dataset/vggsound/video_latents_t5_clip_npz/test/__8UJxW0aOQ_000002.npz",
142
+ "dataset/vggsound/video_latents_t5_clip_npz/test/_0m_YMpQayA_000168.npz"
143
+ ],
144
+ "demo_cfg_scales": [5]
145
+ }
146
+ }
147
+ }
ThinkSound/configs/multimodal_dataset_demo.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_type": "multimodal_dir",
3
+ "video_datasets": [
4
+ {
5
+ "id": "vggsound",
6
+ "path": "dataset/vggsound/video_latents_t5_clip_npz/train",
7
+ "split_path": "dataset/vggsound/split_txt/train_cot.txt"
8
+ }
9
+ ],
10
+ "audio_datasets": [
11
+ {
12
+ "id": "audiostock",
13
+ "path": "dataset/Laion-Audio-630k/audiostock_latents_npz",
14
+ "split_path": "dataset/Laion-Audio-630k/split_txt/cot_audiostock_1.txt"
15
+ },
16
+ {
17
+ "id": "freesound_no_overlap",
18
+ "path": "dataset/Laion-Audio-630k/freesound_no_overlap_latents_npz",
19
+ "split_path": "dataset/Laion-Audio-630k/split_txt/cot_freesound.txt"
20
+ },
21
+ {
22
+ "id": "audioset_sl",
23
+ "path": "dataset/wavcaps/audioset_sl_latents_npz",
24
+ "split_path": "dataset/wavcaps/split_txt/cot_audio_sl_1.txt"
25
+ },
26
+ {
27
+ "id": "audiocaps",
28
+ "path": "dataset/1_audiocaps/audiocaps_latents_npz",
29
+ "split_path": "dataset/1_audiocaps/split_txt/train_cot.txt"
30
+ },
31
+ {
32
+ "id": "bbc",
33
+ "path": "dataset/Laion-Audio-630k/bbc_latents_npz",
34
+ "split_path": "dataset/Laion-Audio-630k/split_txt/cot_bbc_1.txt"
35
+ }
36
+ ],
37
+ "val_datasets": [
38
+ {
39
+ "id": "vggsound",
40
+ "path": "dataset/vggsound/video_latents_t5_clip_npz/test",
41
+ "split_path": "dataset/vggsound/split_txt/test_cot.txt"
42
+ }
43
+ ],
44
+ "test_datasets": [
45
+ {
46
+ "id": "vggsound",
47
+ "path": "cot_coarse"
48
+ }
49
+ ],
50
+ "random_crop": true,
51
+ "input_type": "prompt"
52
+ }
ThinkSound/configs/multimodal_dataset_demo_prismaudio.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_type": "video_dataset",
3
+ "datasets": [
4
+ {
5
+ "id": "vggsound",
6
+ "path": "test",
7
+ "split_path": "test/test.txt"
8
+ }
9
+ ],
10
+ "val_datasets": [
11
+ {
12
+ "id": "vggsound",
13
+ "path": "test",
14
+ "split_path": "test/test.txt"
15
+ }
16
+ ],
17
+ "test_datasets": [
18
+ {
19
+ "id": "vggsound",
20
+ "path": "test",
21
+ "split_path": "test/test.txt"
22
+ }
23
+ ],
24
+ "random_crop": false,
25
+ "input_type": "video",
26
+ "fps": 8
27
+ }
ThinkSound/data/__init__.py ADDED
File without changes
ThinkSound/data/datamodule.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import lightning as L
2
+ from .dataset import LatentDataset, SampleDataset, VideoDataset, AudioDataset, MultiModalDataset, LocalDatasetConfig, collation_fn
3
+ import importlib
4
+ import torch.distributed as dist
5
+ from torch.utils.data import Dataset
6
+ from torch.utils.data import DataLoader,IterableDataset
7
+ import torch
8
+ from itertools import cycle
9
+
10
+ class AlternatingLoader(IterableDataset):
11
+ """
12
+ 一个可迭代的数据集,它包装了两个数据加载器,并按顺序轮流从它们中产出批次。
13
+ 它会持续进行直到两个加载器都耗尽。
14
+
15
+ Args:
16
+ loader1 (DataLoader): 第一个数据加载器。
17
+ loader2 (DataLoader): 第二个数据加载器。
18
+ loader1_name (str): 第一个加载器的名称 (例如 'video')。
19
+ loader2_name (str): 第二个加载器的名称 (例如 'audio')。
20
+ """
21
+ def __init__(self, loader1, loader2, loader1_name='video', loader2_name='audio'):
22
+ super().__init__()
23
+ self.loader1 = loader1
24
+ self.loader2 = loader2
25
+ self.loader1_name = loader1_name
26
+ self.loader2_name = loader2_name
27
+ self.max_len = max(len(loader1), len(loader2))
28
+
29
+ def __iter__(self):
30
+ # 获取 DDP 信息
31
+ try:
32
+ world_size = dist.get_world_size()
33
+ rank = dist.get_rank()
34
+ except (RuntimeError, ValueError):
35
+ # 如果不在分布式环境中,则默认为单进程
36
+ world_size = 1
37
+ rank = 0
38
+
39
+ # 创建两个无限循环迭代器
40
+ iter1 = cycle(self.loader1)
41
+ iter2 = cycle(self.loader2)
42
+
43
+ # 核心修改:只 yield 属于当前 rank 的数据
44
+ # 我们将总的交替流想象成一个大列表,然后对其进行切分
45
+ # 交替流: [v1, a1, v2, a2, v3, a3, ...]
46
+
47
+ # 每个 for 循环迭代产生 2 个 batch (1 个 video, 1 个 audio)
48
+ # 总共会产生 2 * self.max_len 个 batch
49
+
50
+ # for 循环负责驱动迭代
51
+ for i in range(self.max_len):
52
+ # 获取下一个 video batch
53
+ v_batch = next(iter1)
54
+ # 获取下一个 audio batch
55
+ a_batch = next(iter2)
56
+
57
+ # 这是一个交替对,我们根据索引 i 来决定哪个进程处理它
58
+ if i % world_size == rank:
59
+ # 只有当轮次索引 i 属于当前 rank 时,才 yield 数据
60
+ yield v_batch
61
+ yield a_batch
62
+
63
+ def __len__(self):
64
+ # 在 DDP 环境下,__len__ 应该返回单个进程处理的 batch 数量
65
+ # 以便 Lightning 正确显示进度条
66
+
67
+ try:
68
+ world_size = dist.get_world_size()
69
+ except (RuntimeError, ValueError):
70
+ world_size = 1
71
+
72
+ # 每个进程大致处理 1/world_size 的数据对
73
+ # 每个数据对包含 2 个 batch
74
+ num_pairs_per_process = self.max_len // world_size
75
+
76
+ # 如果总数不能整除,最后一个 rank 会多处理一些
77
+ # 为简化起见,我们通常可以用 ceil 来计算
78
+ # (self.max_len + world_size - 1) // world_size 是一种高效的 ceil 写法
79
+ num_pairs_per_process = (self.max_len + world_size - 1) // world_size
80
+
81
+ return 2 * num_pairs_per_process
82
+ def get_configs(audio_configs):
83
+ configs = []
84
+ for config in audio_configs:
85
+ data_dir_path = config.get("path", None)
86
+ audio_dir_path = config.get("audio_dir", None)
87
+ split_path = config.get("split_path", None)
88
+ assert data_dir_path is not None, "Path must be set for local audio directory configuration"
89
+
90
+ custom_metadata_fn = None
91
+ custom_metadata_module_path = config.get("custom_metadata_module", None)
92
+
93
+ if custom_metadata_module_path:
94
+ spec = importlib.util.spec_from_file_location("metadata_module", custom_metadata_module_path)
95
+ metadata_module = importlib.util.module_from_spec(spec)
96
+ spec.loader.exec_module(metadata_module)
97
+ custom_metadata_fn = metadata_module.get_custom_metadata
98
+
99
+ configs.append(
100
+ LocalDatasetConfig(
101
+ id=config["id"],
102
+ path=data_dir_path,
103
+ split_path=split_path,
104
+ custom_metadata_fn=custom_metadata_fn,
105
+ audio_dir=audio_dir_path
106
+ )
107
+ )
108
+ return configs
109
+
110
+ class DataModule(L.LightningDataModule):
111
+ def __init__(self, dataset_config, batch_size, test_batch_size, sample_size, sample_rate, audio_channels=2, num_workers=4):
112
+ super().__init__()
113
+ dataset_type = dataset_config.get("dataset_type", None)
114
+ repeat_num = dataset_config.get("repeat_num", 1)
115
+ self.batch_size = batch_size
116
+ self.num_workers = num_workers
117
+ self.test_batch_size = test_batch_size
118
+ self.repeat_num = repeat_num
119
+ assert dataset_type is not None, "Dataset type must be specified in dataset config"
120
+
121
+ if audio_channels == 1:
122
+ force_channels = "mono"
123
+ elif audio_channels == 2:
124
+ force_channels = "stereo"
125
+ else:
126
+ force_channels = "foa"
127
+ val_dir_configs = dataset_config.get("val_datasets", None)
128
+ test_dir_configs = dataset_config.get("test_datasets", None)
129
+ configs = []
130
+ val_configs = []
131
+ test_configs = []
132
+ if dataset_type == "audio_dir":
133
+ audio_dir_configs = dataset_config.get("datasets", None)
134
+ assert audio_dir_configs is not None, "Directory configuration must be specified in datasets[\"dataset\"]"
135
+ configs = get_configs(audio_dir_configs)
136
+ val_configs = get_configs(val_dir_configs)
137
+ test_configs = get_configs(test_dir_configs)
138
+ elif dataset_type == "latent_dir" or dataset_type == "video_dataset" or dataset_type == "audio_dataset":
139
+ audio_dir_configs = dataset_config.get("datasets", None)
140
+ assert audio_dir_configs is not None, "Directory configuration must be specified in datasets[\"dataset\"]"
141
+ for i, dataset in enumerate((audio_dir_configs, val_dir_configs, test_dir_configs)):
142
+ for config in dataset:
143
+ data_dir_path = config.get("path", None)
144
+ audio_dir_path = config.get("audio_dir", None)
145
+ split_path = config.get("split_path", None)
146
+ assert data_dir_path is not None, "Path must be set for local audio directory configuration"
147
+
148
+ content = LocalDatasetConfig(
149
+ id=config["id"],
150
+ path=data_dir_path,
151
+ split_path=split_path,
152
+ audio_dir=audio_dir_path
153
+ )
154
+ if i == 0:
155
+ configs.append(content)
156
+ elif i == 1:
157
+ val_configs.append(content)
158
+ else:
159
+ test_configs.append(content)
160
+ elif dataset_type in ["multimodal_dir", "alternating_multimodal"]:
161
+ print('##########################')
162
+ print(f'repeat num is: {self.repeat_num}')
163
+ self.audio_configs = []
164
+ self.video_configs = []
165
+ audio_dir_configs = dataset_config.get("audio_datasets", None)
166
+ video_dir_configs = dataset_config.get("video_datasets", None)
167
+ assert audio_dir_configs is not None and video_dir_configs is not None, "Directory configuration must be specified in video_datasets and audio_datasets"
168
+ for i, dataset in enumerate((audio_dir_configs, video_dir_configs, val_dir_configs, test_dir_configs)):
169
+ for config in dataset:
170
+ data_dir_path = config.get("path", None)
171
+ audio_dir_path = config.get("audio_dir", None)
172
+ split_path = config.get("split_path", None)
173
+ assert data_dir_path is not None, "Path must be set for local audio directory configuration"
174
+
175
+ content = LocalDatasetConfig(
176
+ id=config["id"],
177
+ path=data_dir_path,
178
+ split_path=split_path,
179
+ audio_dir=audio_dir_path
180
+ )
181
+ if i == 0:
182
+ self.audio_configs.append(content)
183
+ elif i == 1:
184
+ self.video_configs.append(content)
185
+ elif i == 2:
186
+ val_configs.append(content)
187
+ else:
188
+ test_configs.append(content)
189
+ self.dataset_type = dataset_type
190
+ self.configs = configs
191
+ self.val_configs = val_configs
192
+ self.test_configs = test_configs
193
+ self.sample_rate = sample_rate
194
+ self.sample_size = sample_size
195
+ self.random_crop = dataset_config.get("random_crop", True)
196
+ self.input_type = dataset_config.get("input_type", "video")
197
+ self.fps = dataset_config.get("fps", 4)
198
+ self.force_channels = force_channels
199
+
200
+
201
+ def setup(self, stage: str):
202
+ if self.dataset_type == 'audio_dir':
203
+ dataset_class = SampleDataset
204
+ elif self.dataset_type == 'latent_dir':
205
+ dataset_class = LatentDataset
206
+ elif self.dataset_type == 'video_dataset':
207
+ dataset_class = VideoDataset
208
+ elif self.dataset_type == 'audio_dataset':
209
+ dataset_class = AudioDataset
210
+ elif self.dataset_type in ["multimodal_dir", "alternating_multimodal"]:
211
+ dataset_class = VideoDataset
212
+
213
+ def create_dataset(configs, random_crop):
214
+ return dataset_class(
215
+ configs,
216
+ sample_rate=self.sample_rate,
217
+ sample_size=self.sample_size,
218
+ random_crop=random_crop,
219
+ input_type=self.input_type,
220
+ fps=self.input_type,
221
+ force_channels=self.force_channels
222
+ )
223
+
224
+ if stage == 'fit':
225
+ if self.dataset_type not in ["multimodal_dir", "alternating_multimodal"]:
226
+ self.train_set = create_dataset(self.configs, random_crop=self.random_crop)
227
+ elif self.dataset_type == "multimodal_dir":
228
+ self.video_set = VideoDataset(
229
+ self.video_configs,
230
+ sample_rate=self.sample_rate,
231
+ sample_size=self.sample_size,
232
+ random_crop=self.random_crop,
233
+ input_type=self.input_type,
234
+ fps=self.input_type,
235
+ force_channels=self.force_channels
236
+ )
237
+ self.audio_set = AudioDataset(
238
+ self.audio_configs,
239
+ sample_rate=self.sample_rate,
240
+ sample_size=self.sample_size,
241
+ random_crop=self.random_crop,
242
+ input_type=self.input_type,
243
+ fps=self.input_type,
244
+ force_channels=self.force_channels
245
+ )
246
+ self.train_set = MultiModalDataset([self.video_set]*self.repeat_num, [self.audio_set])
247
+ elif self.dataset_type == "alternating_multimodal":
248
+ self.video_set = VideoDataset(
249
+ self.video_configs,
250
+ sample_rate=self.sample_rate,
251
+ sample_size=self.sample_size,
252
+ random_crop=self.random_crop,
253
+ input_type=self.input_type,
254
+ fps=self.input_type,
255
+ force_channels=self.force_channels
256
+ )
257
+ self.audio_set = AudioDataset(
258
+ self.audio_configs,
259
+ sample_rate=self.sample_rate,
260
+ sample_size=self.sample_size,
261
+ random_crop=self.random_crop,
262
+ input_type=self.input_type,
263
+ fps=self.input_type,
264
+ force_channels=self.force_channels
265
+ )
266
+ self.val_set = create_dataset(self.val_configs, random_crop=False)
267
+ elif stage == 'validate':
268
+ self.val_set = create_dataset(self.val_configs, random_crop=False)
269
+ elif stage == 'predict':
270
+ self.test_set = create_dataset(self.test_configs, random_crop=False)
271
+
272
+
273
+
274
+ def train_dataloader(self):
275
+ if self.dataset_type == "alternating_multimodal":
276
+ # 视频 DataLoader
277
+ video_loader = DataLoader(
278
+ self.video_set,
279
+ batch_size=self.batch_size,
280
+ shuffle=True,
281
+ num_workers=self.num_workers,
282
+ pin_memory=True,
283
+ drop_last=True,
284
+ collate_fn=collation_fn
285
+ )
286
+
287
+ # 音频 DataLoader
288
+ audio_loader = DataLoader(
289
+ self.audio_set,
290
+ batch_size=self.batch_size,
291
+ shuffle=True,
292
+ num_workers=self.num_workers,
293
+ pin_memory=True,
294
+ drop_last=True,
295
+ collate_fn=collation_fn
296
+ )
297
+ alternating_loader = AlternatingLoader(
298
+ video_loader,
299
+ audio_loader,
300
+ loader1_name='video',
301
+ loader2_name='audio'
302
+ )
303
+ return DataLoader(alternating_loader, batch_size=None, num_workers=0)
304
+ else:
305
+ # 如果不是 alternating_multimodal,保持现有逻辑(仅用于兼容性)
306
+ return DataLoader(
307
+ self.train_set,
308
+ batch_size=self.batch_size,
309
+ shuffle=True,
310
+ num_workers=self.num_workers,
311
+ persistent_workers=True,
312
+ pin_memory=True,
313
+ drop_last=True,
314
+ collate_fn=collation_fn
315
+ )
316
+
317
+
318
+ def val_dataloader(self):
319
+ return DataLoader(self.val_set, self.batch_size, shuffle=False,
320
+ num_workers=self.num_workers, persistent_workers=False, pin_memory=False, drop_last=False, collate_fn=collation_fn)
321
+
322
+ def predict_dataloader(self):
323
+ return DataLoader(self.test_set, batch_size=self.test_batch_size, shuffle=False,
324
+ num_workers=self.num_workers, persistent_workers=False, pin_memory=False, drop_last=False, collate_fn=collation_fn)
325
+
326
+ # def predict_dataloader(self):
327
+ # return DataLoader(self.mnist_predict, batch_size=self.batch_size)
328
+
329
+ # def teardown(self, stage: str):
330
+ # # Used to clean-up when the run is finished
331
+ # ...
ThinkSound/data/dataset.py ADDED
@@ -0,0 +1,1319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import numpy as np
3
+ import io
4
+ import os
5
+ import posixpath
6
+ import random
7
+ import re
8
+ import subprocess
9
+ import time
10
+ import torch
11
+ import torchaudio
12
+ import webdataset as wds
13
+ import pandas as pd
14
+ from aeiou.core import is_silence
15
+ from os import path
16
+ from pathlib import Path
17
+ from pedalboard.io import AudioFile
18
+ from torchaudio import transforms as T
19
+ from typing import Optional, Callable, List
20
+ import bisect
21
+
22
+ from .utils import FOA, Stereo, Mono, PhaseFlipper, PadCrop_Normalized_T, PadCrop_Video_Normalized_T, PadCrop_Video_Hiera_Normalized_T, PadCrop_Video_Image_Normalized_T, PadCrop_DualVideo_Normalized_T
23
+
24
+ AUDIO_KEYS = ("flac", "wav", "mp3", "m4a", "ogg", "opus")
25
+
26
+ # fast_scandir implementation by Scott Hawley originally in https://github.com/zqevans/audio-diffusion/blob/main/dataset/dataset.py
27
+
28
+ def fast_scandir(
29
+ dir:str, # top-level directory at which to begin scanning
30
+ ext:list, # list of allowed file extensions,
31
+ #max_size = 1 * 1000 * 1000 * 1000 # Only files < 1 GB
32
+ ):
33
+ "very fast `glob` alternative. from https://stackoverflow.com/a/59803793/4259243"
34
+ subfolders, files = [], []
35
+ ext = ['.'+x if x[0]!='.' else x for x in ext] # add starting period to extensions if needed
36
+ try: # hope to avoid 'permission denied' by this try
37
+ for f in os.scandir(dir):
38
+ try: # 'hope to avoid too many levels of symbolic links' error
39
+ if f.is_dir():
40
+ subfolders.append(f.path)
41
+ elif f.is_file():
42
+ file_ext = os.path.splitext(f.name)[1].lower()
43
+ is_hidden = os.path.basename(f.path).startswith(".")
44
+
45
+ if file_ext in ext and not is_hidden:
46
+ files.append(f.path)
47
+ except:
48
+ pass
49
+ except:
50
+ pass
51
+
52
+ for dir in list(subfolders):
53
+ sf, f = fast_scandir(dir, ext)
54
+ subfolders.extend(sf)
55
+ files.extend(f)
56
+ return subfolders, files
57
+
58
+ def keyword_scandir(
59
+ dir: str, # top-level directory at which to begin scanning
60
+ ext: list, # list of allowed file extensions
61
+ keywords: list, # list of keywords to search for in the file name
62
+ ):
63
+ "very fast `glob` alternative. from https://stackoverflow.com/a/59803793/4259243"
64
+ subfolders, files = [], []
65
+ # make keywords case insensitive
66
+ keywords = [keyword.lower() for keyword in keywords]
67
+ # add starting period to extensions if needed
68
+ ext = ['.'+x if x[0] != '.' else x for x in ext]
69
+ banned_words = ["paxheader", "__macosx"]
70
+ try: # hope to avoid 'permission denied' by this try
71
+ for f in os.scandir(dir):
72
+ try: # 'hope to avoid too many levels of symbolic links' error
73
+ if f.is_dir():
74
+ subfolders.append(f.path)
75
+ elif f.is_file():
76
+ is_hidden = f.name.split("/")[-1][0] == '.'
77
+ has_ext = os.path.splitext(f.name)[1].lower() in ext
78
+ name_lower = f.name.lower()
79
+ has_keyword = any(
80
+ [keyword in name_lower for keyword in keywords])
81
+ has_banned = any(
82
+ [banned_word in name_lower for banned_word in banned_words])
83
+ if has_ext and has_keyword and not has_banned and not is_hidden and not os.path.basename(f.path).startswith("._"):
84
+ files.append(f.path)
85
+ except:
86
+ pass
87
+ except:
88
+ pass
89
+
90
+ for dir in list(subfolders):
91
+ sf, f = keyword_scandir(dir, ext, keywords)
92
+ subfolders.extend(sf)
93
+ files.extend(f)
94
+ return subfolders, files
95
+
96
+ def get_audio_filenames(
97
+ paths: list, # directories in which to search
98
+ keywords=None,
99
+ exts=['.wav', '.mp3', '.flac', '.ogg', '.aif', '.opus']
100
+ ):
101
+ "recursively get a list of audio filenames"
102
+ filenames = []
103
+ if type(paths) is str:
104
+ paths = [paths]
105
+ for path in paths: # get a list of relevant filenames
106
+ if keywords is not None:
107
+ subfolders, files = keyword_scandir(path, exts, keywords)
108
+ else:
109
+ subfolders, files = fast_scandir(path, exts)
110
+ filenames.extend(files)
111
+ return filenames
112
+
113
+
114
+
115
+
116
+
117
+ class LocalDatasetConfig:
118
+ def __init__(
119
+ self,
120
+ id: str,
121
+ path: str,
122
+ split_path: str,
123
+ audio_dir: str = None,
124
+ custom_metadata_fn: Optional[Callable[[str], str]] = None
125
+ ):
126
+ self.id = id
127
+ self.path = path
128
+ self.split_path = split_path
129
+ self.audio_dir = audio_dir
130
+ self.custom_metadata_fn = custom_metadata_fn
131
+
132
+ class SampleDataset(torch.utils.data.Dataset):
133
+ def __init__(
134
+ self,
135
+ configs,
136
+ sample_size=65536,
137
+ sample_rate=48000,
138
+ keywords=None,
139
+ random_crop=True,
140
+ input_type="prompt",
141
+ fps=4,
142
+ force_channels="stereo"
143
+ ):
144
+ super().__init__()
145
+ self.filenames = []
146
+
147
+ self.augs = torch.nn.Sequential(
148
+ PhaseFlipper(),
149
+ )
150
+
151
+ self.root_paths = []
152
+ if input_type == 'video':
153
+ self.pad_crop = PadCrop_Video_Normalized_T(sample_size, sample_rate, fps, randomize=random_crop)
154
+ elif input_type == 'video_hiera':
155
+ self.pad_crop = PadCrop_Video_Hiera_Normalized_T(sample_size, sample_rate, fps, randomize=random_crop)
156
+ elif input_type == 'video_image':
157
+ self.pad_crop = PadCrop_Video_Image_Normalized_T(sample_size, sample_rate, fps, randomize=random_crop)
158
+ elif input_type == 'dual_video':
159
+ self.pad_crop = PadCrop_DualVideo_Normalized_T(sample_size, sample_rate, fps, randomize=random_crop)
160
+ else:
161
+ self.pad_crop = PadCrop_Normalized_T(sample_size, sample_rate, randomize=random_crop)
162
+
163
+ self.force_channels = force_channels
164
+ print('######################')
165
+ print(f'input channels is: {force_channels}')
166
+ print('######################')
167
+ self.encoding = torch.nn.Sequential(
168
+ FOA() if self.force_channels == "foa" else torch.nn.Identity(),
169
+ Stereo() if self.force_channels == "stereo" else torch.nn.Identity(),
170
+ Mono() if self.force_channels == "mono" else torch.nn.Identity(),
171
+ )
172
+ self.input_type = input_type
173
+ self.sr = sample_rate
174
+ self.custom_metadata_fns = {}
175
+
176
+ for config in configs:
177
+ self.root_paths.append(config.path)
178
+ def add_prefix(s):
179
+ return str(os.path.join(config.path,f'{s.strip()}'))
180
+ with open(config.split_path,'r') as f:
181
+ item_names = f.readlines()
182
+ filenames = list(map(add_prefix, item_names))
183
+ self.filenames.extend(filenames)
184
+ # self.filenames.extend(get_audio_filenames(config.path, keywords))
185
+ if config.custom_metadata_fn is not None:
186
+ self.custom_metadata_fns[config.path] = config.custom_metadata_fn
187
+
188
+ print(f'Found {len(self.filenames)} files')
189
+
190
+ def load_file(self, filename):
191
+ ext = filename.split(".")[-1]
192
+ if ext == "mp3":
193
+ with AudioFile(filename) as f:
194
+ audio = f.read(f.frames)
195
+ audio = torch.from_numpy(audio)
196
+ in_sr = f.samplerate
197
+ else:
198
+ audio, in_sr = torchaudio.load(filename, format=ext)
199
+
200
+ if in_sr != self.sr:
201
+ try:
202
+ resample_tf = T.Resample(in_sr, self.sr)
203
+ audio = resample_tf(audio)
204
+ except:
205
+ print(f'{filename} resample errors')
206
+
207
+ assert not (torch.isnan(audio).any() or torch.isinf(audio).any()), f'file-{filename} contains nan or inf number, check it!'
208
+ return audio
209
+
210
+ def __len__(self):
211
+ return len(self.filenames)
212
+
213
+ def __getitem__(self, idx):
214
+ audio_filename = self.filenames[idx]
215
+ assert os.path.exists(audio_filename), f'{audio_filename}: file not exists'
216
+ try:
217
+ start_time = time.time()
218
+ audio = self.load_file(audio_filename)
219
+ info = {}
220
+ info["path"] = audio_filename
221
+
222
+ for root_path in self.root_paths:
223
+ if root_path in audio_filename:
224
+ info["relpath"] = path.relpath(audio_filename, root_path)
225
+
226
+
227
+ for custom_md_path in self.custom_metadata_fns.keys():
228
+ if custom_md_path in audio_filename:
229
+ custom_metadata_fn = self.custom_metadata_fns[custom_md_path]
230
+ custom_metadata = custom_metadata_fn(info, audio)
231
+ info.update(custom_metadata)
232
+
233
+ if "__reject__" in info and info["__reject__"]:
234
+ return self[random.randrange(len(self))]
235
+ if self.input_type == 'video':
236
+ audio, video, t_start, t_end, seconds_start, seconds_total, padding_mask = self.pad_crop(audio, info['video'])
237
+ info['video'] = video
238
+ elif self.input_type == 'dual_video':
239
+ audio, video_360, video_fov, t_start, t_end, seconds_start, seconds_total, padding_mask = self.pad_crop(audio, info['video'], info['video_fov'])
240
+ info['video_360'] = video_360
241
+ info['video_fov'] = video_fov
242
+ else:
243
+ audio, t_start, t_end, seconds_start, seconds_total, padding_mask = self.pad_crop(audio)
244
+ assert not (torch.isnan(audio).any() or torch.isinf(audio).any()), f'file-{filename} contains nan or inf number, check it!'
245
+ # Run augmentations on this sample (including random crop)
246
+ if self.augs is not None:
247
+ audio = self.augs(audio)
248
+
249
+ audio = audio.clamp(-1, 1)
250
+
251
+ # Encode the file to assist in prediction
252
+ if self.encoding is not None:
253
+ audio = self.encoding(audio)
254
+
255
+
256
+
257
+ info["timestamps"] = (t_start, t_end)
258
+ info["seconds_start"] = seconds_start
259
+ info["seconds_total"] = seconds_total
260
+ info["padding_mask"] = padding_mask
261
+
262
+ end_time = time.time()
263
+ info["load_time"] = end_time - start_time
264
+
265
+
266
+ return (audio, info)
267
+ except Exception as e:
268
+ print(f'Couldn\'t load file {audio_filename}: {e}')
269
+ return self[random.randrange(len(self))]
270
+
271
+ class LatentDataset(torch.utils.data.Dataset):
272
+ def __init__(
273
+ self,
274
+ configs,
275
+ sample_size=65536,
276
+ sample_rate=48000,
277
+ keywords=None,
278
+ random_crop=True,
279
+ input_type="prompt",
280
+ fps=4,
281
+ force_channels="stereo"
282
+ ):
283
+ super().__init__()
284
+ self.filenames = []
285
+
286
+ self.augs = torch.nn.Sequential(
287
+ PhaseFlipper(),
288
+ )
289
+
290
+ self.root_paths = []
291
+
292
+ self.force_channels = force_channels
293
+ print('######################')
294
+ print(f'input channels is: {force_channels}')
295
+ print('######################')
296
+ self.encoding = torch.nn.Sequential(
297
+ FOA() if self.force_channels == "foa" else torch.nn.Identity(),
298
+ Stereo() if self.force_channels == "stereo" else torch.nn.Identity(),
299
+ Mono() if self.force_channels == "mono" else torch.nn.Identity(),
300
+ )
301
+ self.input_type = input_type
302
+ self.sr = sample_rate
303
+ for config in configs:
304
+ self.root_paths.append(config.path)
305
+ def add_prefix(s):
306
+ return str(os.path.join(config.path,f'{s.strip()}'))
307
+ with open(config.split_path,'r') as f:
308
+ item_names = f.readlines()
309
+ filenames = list(map(add_prefix, item_names))
310
+ self.filenames.extend(filenames)
311
+ # self.filenames.extend(get_audio_filenames(config.path, keywords))
312
+
313
+
314
+ print(f'Found {len(self.filenames)} files')
315
+
316
+ def load_file(self, filename, info):
317
+ # try:
318
+ npz_file = filename.replace('.pth','.npz')
319
+ if os.path.exists(filename) and '.npz' not in filename:
320
+ data = torch.load(filename, weights_only=False)
321
+ elif os.path.exists(npz_file):
322
+ # print(filename)
323
+ npz_data = np.load(npz_file,allow_pickle=True)
324
+ data = {key: npz_data[key] for key in npz_data.files}
325
+ # print("data.keys()",data.keys())
326
+ for key in data.keys():
327
+ if isinstance(data[key], np.ndarray) and np.issubdtype(data[key].dtype, np.number):
328
+ data[key] = torch.from_numpy(data[key])
329
+ else:
330
+ raise ValueError(f'error load file with file not exists: {filename}')
331
+ info.update(data)
332
+ audio = data['latent']
333
+ # except:
334
+ # print(f'error load file: {filename}')
335
+ return audio
336
+
337
+ def __len__(self):
338
+ return len(self.filenames)
339
+
340
+ def __getitem__(self, idx):
341
+ audio_filename = self.filenames[idx]
342
+ assert os.path.exists(audio_filename) or audio_filename.replace('.pth','.npz'), f'{audio_filename}: file not exists'
343
+ # try:
344
+ start_time = time.time()
345
+ info = {}
346
+ audio = self.load_file(audio_filename, info)
347
+ info["path"] = audio_filename
348
+ info['id'] = Path(audio_filename).stem
349
+ for root_path in self.root_paths:
350
+ if root_path in audio_filename:
351
+ info["relpath"] = path.relpath(audio_filename, root_path)
352
+
353
+ return (audio, info)
354
+
355
+ class AudioDataset(torch.utils.data.Dataset):
356
+ def __init__(
357
+ self,
358
+ configs,
359
+ sample_size=65536,
360
+ sample_rate=48000,
361
+ keywords=None,
362
+ random_crop=True,
363
+ input_type="prompt",
364
+ fps=4,
365
+ force_channels="stereo"
366
+ ):
367
+ super().__init__()
368
+ self.filenames = []
369
+
370
+ self.augs = torch.nn.Sequential(
371
+ PhaseFlipper(),
372
+ )
373
+
374
+ self.root_paths = []
375
+
376
+ self.force_channels = force_channels
377
+ print('######################')
378
+ print(f'input channels is: {force_channels}')
379
+ print('######################')
380
+ self.encoding = torch.nn.Sequential(
381
+ FOA() if self.force_channels == "foa" else torch.nn.Identity(),
382
+ Stereo() if self.force_channels == "stereo" else torch.nn.Identity(),
383
+ Mono() if self.force_channels == "mono" else torch.nn.Identity(),
384
+ )
385
+ self.fake_clip_features = torch.zeros(72, 1024)
386
+ self.fake_sync_features = torch.zeros(216, 768)
387
+ self.video_exist = torch.tensor(0, dtype=torch.bool)
388
+ self.input_type = input_type
389
+ self.sr = sample_rate
390
+ for config in configs:
391
+ self.root_paths.append(config.path)
392
+ def add_prefix(s):
393
+ return str(os.path.join(config.path,f'{s.strip()}'))
394
+ with open(config.split_path,'r') as f:
395
+ item_names = f.readlines()
396
+ filenames = list(map(add_prefix, item_names))
397
+ self.filenames.extend(filenames)
398
+ # self.filenames.extend(get_audio_filenames(config.path, keywords))
399
+
400
+
401
+ print(f'Found {len(self.filenames)} files')
402
+
403
+ def load_file(self, filename, info):
404
+ # try:
405
+ npz_file = filename.replace('.pth','.npz')
406
+ if os.path.exists(filename) and '.npz' not in filename:
407
+ data = torch.load(filename, weights_only=False)
408
+ elif os.path.exists(npz_file):
409
+ # print(filename)
410
+ npz_data = np.load(npz_file,allow_pickle=True)
411
+ data = dict(npz_data)
412
+ # print("data.keys()",data.keys())
413
+ for key in data.keys():
414
+ if isinstance(data[key], np.ndarray) and np.issubdtype(data[key].dtype, np.number):
415
+ data[key] = torch.from_numpy(data[key])
416
+ else:
417
+ raise ValueError(f'error load file: {filename}')
418
+ info.update(data)
419
+ audio = data['latent']
420
+ if 'source_latent' not in data.keys():
421
+ info['source_latent']= audio
422
+ info['video_features'] = self.fake_clip_features
423
+ info['sync_features'] = self.fake_sync_features
424
+ info['video_exist'] = self.video_exist
425
+ # except:
426
+ # print(f'error load file: {filename}')
427
+ return audio
428
+
429
+ def __len__(self):
430
+ return len(self.filenames)
431
+
432
+ def __getitem__(self, idx):
433
+ audio_filename = self.filenames[idx]
434
+ assert os.path.exists(audio_filename) or audio_filename.replace('.pth','.npz'), f'{audio_filename}: file not exists'
435
+ # try:
436
+ start_time = time.time()
437
+ info = {}
438
+ audio = self.load_file(audio_filename, info)
439
+ info["path"] = audio_filename
440
+ assert audio.shape == (64,194), f'{audio.shape} input error, id: {audio_filename}'
441
+ info['id'] = Path(audio_filename).stem
442
+ for root_path in self.root_paths:
443
+ if root_path in audio_filename:
444
+ info["relpath"] = path.relpath(audio_filename, root_path)
445
+
446
+ return (audio, info)
447
+
448
+
449
+
450
+
451
+ class VideoDataset(torch.utils.data.Dataset):
452
+ def __init__(
453
+ self,
454
+ configs,
455
+ sample_size=65536,
456
+ sample_rate=48000,
457
+ keywords=None,
458
+ random_crop=True,
459
+ input_type="prompt",
460
+ fps=4,
461
+ force_channels="stereo"
462
+ ):
463
+ super().__init__()
464
+ self.filenames = []
465
+
466
+ self.augs = torch.nn.Sequential(
467
+ PhaseFlipper(),
468
+ )
469
+
470
+ self.root_paths = []
471
+ self.sample_size = sample_size
472
+ self.force_channels = force_channels
473
+ print('######################')
474
+ print(f'input channels is: {force_channels}')
475
+ print('######################')
476
+ self.encoding = torch.nn.Sequential(
477
+ FOA() if self.force_channels == "foa" else torch.nn.Identity(),
478
+ Stereo() if self.force_channels == "stereo" else torch.nn.Identity(),
479
+ Mono() if self.force_channels == "mono" else torch.nn.Identity(),
480
+ )
481
+ self.input_type = input_type
482
+ self.sr = sample_rate
483
+ self.video_exist = torch.tensor(1, dtype=torch.bool)
484
+ self.audio_files = []
485
+ for config in configs:
486
+ self.root_paths.append(config.path)
487
+ def add_prefix(s):
488
+ return str(os.path.join(config.path,f'{s.strip()}'))
489
+ with open(config.split_path,'r') as f:
490
+ item_names = f.readlines()
491
+ filenames = list(map(add_prefix, item_names))
492
+ self.filenames.extend(filenames)
493
+ if config.audio_dir is not None:
494
+ def add_prefix(s):
495
+ return str(os.path.join(config.audio_dir,f'{Path(s).stem}.wav'))
496
+ filenames = list(map(add_prefix, item_names))
497
+ self.audio_files.extend(filenames)
498
+ # self.filenames.extend(get_audio_filenames(config.path, keywords))
499
+
500
+ print(f'Found {len(self.filenames)} files')
501
+
502
+ def load_audio(self, filename):
503
+ ext = filename.split(".")[-1]
504
+ if ext == "mp3":
505
+ with AudioFile(filename) as f:
506
+ audio = f.read(f.frames)
507
+ audio = torch.from_numpy(audio)
508
+ in_sr = f.samplerate
509
+ else:
510
+ audio, in_sr = torchaudio.load(filename, format=ext)
511
+
512
+ if in_sr != self.sr:
513
+ try:
514
+ resample_tf = T.Resample(in_sr, self.sr)
515
+ audio = resample_tf(audio)
516
+ except:
517
+ print(f'{filename} resample errors')
518
+
519
+ assert not (torch.isnan(audio).any() or torch.isinf(audio).any()), f'file-{filename} contains nan or inf number, check it!'
520
+ return audio
521
+
522
+
523
+
524
+
525
+ def check_audio_file(self, audio_path):
526
+ # 首先检查原始路径是否存在
527
+ if os.path.exists(audio_path):
528
+ return audio_path
529
+ # 如果不存在,尝试替换为.flac扩展名
530
+ name, ext = os.path.splitext(audio_path)
531
+ flac_path = f"{name}.flac"
532
+
533
+ if os.path.exists(flac_path):
534
+ return flac_path
535
+ raise FileNotFoundError(f"音频文件不存在: {audio_path} 和 {flac_path} 都不存在")
536
+
537
+ def load_file(self, filename, info):
538
+ try:
539
+ npz_file = filename.replace('.pth','.npz')
540
+ if os.path.exists(filename) and '.npz' not in filename:
541
+ data = torch.load(filename, weights_only=False)
542
+ elif os.path.exists(npz_file):
543
+ # print(filename)
544
+ npz_data = np.load(npz_file,allow_pickle=True)
545
+ data = {key: npz_data[key] for key in npz_data.files}
546
+ # print("data.keys()",data.keys())
547
+ for key in data.keys():
548
+ if isinstance(data[key], np.ndarray) and np.issubdtype(data[key].dtype, np.number):
549
+ data[key] = torch.from_numpy(data[key])
550
+ else:
551
+ raise ValueError(f'error load file: {filename}')
552
+ info.update(data)
553
+ audio = data['latent']
554
+ info['video_exist'] = self.video_exist
555
+ except Exception as e:
556
+ print(f'error load file: {filename} with error: {e}')
557
+ return None
558
+ return audio
559
+
560
+ def __len__(self):
561
+ return len(self.filenames)
562
+
563
+ def __getitem__(self, idx):
564
+ loop = True
565
+ while loop:
566
+ filename = self.filenames[idx]
567
+ if len(self.audio_files) > 0:
568
+ audio_path = self.audio_files[idx]
569
+ audio_path = self.check_audio_file(audio_path)
570
+ waveform = self.load_audio(audio_path)
571
+ else:
572
+ waveform = None
573
+ assert os.path.exists(filename) or filename.replace('.pth','.npz'), f'{filename}: file not exists'
574
+ # try:
575
+ start_time = time.time()
576
+ info = {}
577
+ audio = self.load_file(filename, info)
578
+ if audio is not None:
579
+ loop = False
580
+ else:
581
+ idx = (idx+1) % len(self.filenames)
582
+
583
+ if waveform is not None:
584
+ padded_waveform = torch.zeros(waveform.shape[0], self.sample_size, dtype=waveform.dtype)
585
+ copy_length = min(waveform.shape[1], self.sample_size)
586
+ padded_waveform[:, :copy_length] = waveform[:, :copy_length]
587
+
588
+ waveform = padded_waveform
589
+ waveform = waveform.clamp(-1, 1)
590
+ # Encode the file to assist in prediction
591
+ if self.encoding is not None:
592
+ waveform = self.encoding(waveform)
593
+ info['waveform'] = waveform
594
+ info["path"] = filename
595
+ info['id'] = Path(filename).stem
596
+ for root_path in self.root_paths:
597
+ if root_path in filename:
598
+ info["relpath"] = path.relpath(filename, root_path)
599
+
600
+
601
+ return (audio, info)
602
+
603
+ # modified from https://pytorch.org/docs/stable/_modules/torch/utils/data/dataset.html#ConcatDataset
604
+ class MultiModalDataset(torch.utils.data.Dataset):
605
+ datasets: list[torch.utils.data.Dataset]
606
+ cumulative_sizes: list[int]
607
+
608
+ @staticmethod
609
+ def cumsum(sequence):
610
+ r, s = [], 0
611
+ for e in sequence:
612
+ l = len(e)
613
+ r.append(l + s)
614
+ s += l
615
+ return r
616
+
617
+ def __init__(self, video_datasets: list[torch.utils.data.Dataset], audio_datasets: list[torch.utils.data.Dataset]):
618
+ super().__init__()
619
+ self.video_datasets = list(video_datasets)
620
+ self.audio_datasets = list(audio_datasets)
621
+ self.datasets = self.video_datasets + self.audio_datasets
622
+
623
+ self.cumulative_sizes = self.cumsum(self.datasets)
624
+ print(f'Found {self.cumulative_sizes[-1]} files')
625
+
626
+ def __len__(self):
627
+ return self.cumulative_sizes[-1]
628
+
629
+ def __getitem__(self, idx):
630
+ if idx < 0:
631
+ if -idx > len(self):
632
+ raise ValueError("absolute value of index should not exceed dataset length")
633
+ idx = len(self) + idx
634
+ dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)
635
+ if dataset_idx == 0:
636
+ sample_idx = idx
637
+ else:
638
+ sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]
639
+ return self.datasets[dataset_idx][sample_idx]
640
+
641
+ def compute_latent_stats(self) -> tuple[torch.Tensor, torch.Tensor]:
642
+ return self.video_datasets[0].compute_latent_stats()
643
+
644
+
645
+ # class MultiModalDataset(torch.utils.data.Dataset):
646
+ # def __init__(
647
+ # self,
648
+ # configs,
649
+ # sample_size=65536,
650
+ # sample_rate=48000,
651
+ # keywords=None,
652
+ # random_crop=True,
653
+ # input_type="prompt",
654
+ # fps=4,
655
+ # force_channels="stereo"
656
+ # ):
657
+ # super().__init__()
658
+ # self.filenames = []
659
+ # self.captions = []
660
+ # self.caption_t5s = []
661
+ # self.ids = []
662
+ # self.augs = torch.nn.Sequential(
663
+ # PhaseFlipper(),
664
+ # )
665
+
666
+ # self.root_paths = []
667
+ # if input_type == 'video':
668
+ # self.pad_crop = PadCrop_Video_Normalized_T(sample_size, sample_rate, fps, randomize=random_crop)
669
+ # elif input_type == 'video_hiera':
670
+ # self.pad_crop = PadCrop_Video_Hiera_Normalized_T(sample_size, sample_rate, fps, randomize=random_crop)
671
+ # elif input_type == 'video_image':
672
+ # self.pad_crop = PadCrop_Video_Image_Normalized_T(sample_size, sample_rate, fps, randomize=random_crop)
673
+ # elif input_type == 'dual_video':
674
+ # self.pad_crop = PadCrop_DualVideo_Normalized_T(sample_size, sample_rate, fps, randomize=random_crop)
675
+ # else:
676
+ # self.pad_crop = PadCrop_Normalized_T(sample_size, sample_rate, randomize=random_crop)
677
+
678
+ # self.force_channels = force_channels
679
+ # print('######################')
680
+ # print(f'input channels is: {force_channels}')
681
+ # print('######################')
682
+ # self.encoding = torch.nn.Sequential(
683
+ # FOA() if self.force_channels == "foa" else torch.nn.Identity(),
684
+ # Stereo() if self.force_channels == "stereo" else torch.nn.Identity(),
685
+ # Mono() if self.force_channels == "mono" else torch.nn.Identity(),
686
+ # )
687
+ # self.input_type = input_type
688
+ # self.sr = sample_rate
689
+ # self.custom_metadata_fns = {}
690
+
691
+ # for config in configs:
692
+ # print(config.split_path)
693
+ # self.root_paths.append(config.path)
694
+ # def add_prefix(s):
695
+ # return str(os.path.join(config.path,f'{s.strip()}'))
696
+ # with open(config.split_path,'r') as f:
697
+ # item_names = f.readlines()
698
+ # csv_path = config.split_path.replace('.txt','.csv')
699
+ # df = pd.read_csv(csv_path)
700
+ # # 检查是否存在 'caption_t5' 列,如果不存在则创建并复制 'caption' 的值
701
+ # if 'caption_t5' not in df.columns:
702
+ # df['caption_t5'] = df['caption']
703
+
704
+ # captions = df['caption'].tolist()
705
+ # caption_t5s = df['caption_t5'].tolist()
706
+ # filenames = list(map(add_prefix, item_names))
707
+ # assert len(captions) == len(caption_t5s) and len(captions) == len(filenames), f'{config.path} has wrong filename and caption'
708
+ # if config.id == 'vggsound':
709
+ # self.filenames.extend(filenames*5)
710
+ # self.captions.extend(captions*5)
711
+ # self.caption_t5s.extend(caption_t5s*5)
712
+ # self.ids.extend(df['id'].tolist()*5)
713
+ # else:
714
+ # self.filenames.extend(filenames)
715
+ # self.captions.extend(captions)
716
+ # self.caption_t5s.extend(caption_t5s)
717
+ # self.ids.extend(df['id'].tolist())
718
+ # # self.filenames.extend(get_audio_filenames(config.path, keywords))
719
+ # if config.custom_metadata_fn is not None:
720
+ # self.custom_metadata_fns[config.path] = config.custom_metadata_fn
721
+
722
+ # assert len(self.ids) == len(self.captions) and len(self.caption_t5s) == len(self.filenames), 'length need to be same'
723
+ # print(f'Found {len(self.filenames)} files')
724
+
725
+
726
+ # def load_file(self, filename):
727
+ # ext = filename.split(".")[-1]
728
+ # if ext == "mp3":
729
+ # with AudioFile(filename) as f:
730
+ # audio = f.read(f.frames)
731
+ # audio = torch.from_numpy(audio)
732
+ # in_sr = f.samplerate
733
+ # else:
734
+ # audio, in_sr = torchaudio.load(filename, format=ext)
735
+
736
+ # if in_sr != self.sr:
737
+ # try:
738
+ # resample_tf = T.Resample(in_sr, self.sr)
739
+ # audio = resample_tf(audio)
740
+ # except:
741
+ # print(f'{filename} resample errors')
742
+
743
+ # assert not (torch.isnan(audio).any() or torch.isinf(audio).any()), f'file-{filename} contains nan or inf number, check it!'
744
+ # return audio
745
+
746
+ # def __len__(self):
747
+ # return len(self.filenames)
748
+
749
+ # def __getitem__(self, idx):
750
+ # audio_filename = self.filenames[idx]
751
+ # id = self.ids[idx]
752
+ # assert str(id) == str(Path(audio_filename).stem), f'audio_file: {audio_filename} needs to be same as {id} '
753
+ # assert os.path.exists(audio_filename), f'{audio_filename}: file not exists'
754
+ # try:
755
+ # start_time = time.time()
756
+ # audio = self.load_file(audio_filename)
757
+ # caption = self.captions[idx]
758
+ # caption_t5 = self.caption_t5s[idx]
759
+ # if pd.isna(caption_t5) or caption_t5 == '':
760
+ # caption_t5 = caption
761
+ # info = {}
762
+ # info["path"] = audio_filename
763
+ # info['caption'] = caption
764
+ # info['caption_t5'] = caption_t5
765
+
766
+ # for root_path in self.root_paths:
767
+ # if root_path in audio_filename:
768
+ # info["relpath"] = path.relpath(audio_filename, root_path)
769
+
770
+
771
+ # for custom_md_path in self.custom_metadata_fns.keys():
772
+ # if custom_md_path in audio_filename:
773
+ # custom_metadata_fn = self.custom_metadata_fns[custom_md_path]
774
+ # custom_metadata = custom_metadata_fn(info, audio)
775
+ # info.update(custom_metadata)
776
+
777
+ # if "__reject__" in info and info["__reject__"]:
778
+ # return self[random.randrange(len(self))]
779
+ # # if self.input_type == 'video':
780
+ # # audio, video, t_start, t_end, seconds_start, seconds_total, padding_mask = self.pad_crop(audio, info['clip_features'])
781
+ # # info['clip_features'] = video
782
+ # # else:
783
+ # if info['flag']:
784
+ # audio, t_start, t_end, seconds_start, seconds_total, padding_mask = self.pad_crop(audio,randomize=False)
785
+ # else:
786
+ # audio, t_start, t_end, seconds_start, seconds_total, padding_mask = self.pad_crop(audio,randomize=True)
787
+ # assert not (torch.isnan(audio).any() or torch.isinf(audio).any()), f'file-{filename} contains nan or inf number, check it!'
788
+ # # Run augmentations on this sample (including random crop)
789
+ # if self.augs is not None:
790
+ # audio = self.augs(audio)
791
+
792
+ # audio = audio.clamp(-1, 1)
793
+
794
+ # # Encode the file to assist in prediction
795
+ # if self.encoding is not None:
796
+ # audio = self.encoding(audio)
797
+
798
+
799
+
800
+ # info["timestamps"] = (t_start, t_end)
801
+ # info["seconds_start"] = seconds_start
802
+ # info["seconds_total"] = seconds_total
803
+ # info["padding_mask"] = padding_mask
804
+
805
+ # end_time = time.time()
806
+ # info["load_time"] = end_time - start_time
807
+
808
+
809
+ # return (audio, info)
810
+ # except Exception as e:
811
+ # print(f'Couldn\'t load file {audio_filename}: {e}')
812
+ # return self[random.randrange(len(self))]
813
+
814
+ def group_by_keys(data, keys=wds.tariterators.base_plus_ext, lcase=True, suffixes=None, handler=None):
815
+ """Return function over iterator that groups key, value pairs into samples.
816
+ :param keys: function that splits the key into key and extension (base_plus_ext)
817
+ :param lcase: convert suffixes to lower case (Default value = True)
818
+ """
819
+ current_sample = None
820
+ for filesample in data:
821
+ assert isinstance(filesample, dict)
822
+ fname, value = filesample["fname"], filesample["data"]
823
+ prefix, suffix = keys(fname)
824
+ if wds.tariterators.trace:
825
+ print(
826
+ prefix,
827
+ suffix,
828
+ current_sample.keys() if isinstance(current_sample, dict) else None,
829
+ )
830
+ if prefix is None:
831
+ continue
832
+ if lcase:
833
+ suffix = suffix.lower()
834
+ if current_sample is None or prefix != current_sample["__key__"]:
835
+ if wds.tariterators.valid_sample(current_sample):
836
+ yield current_sample
837
+ current_sample = dict(__key__=prefix, __url__=filesample["__url__"])
838
+ if suffix in current_sample:
839
+ print(f"{fname}: duplicate file name in tar file {suffix} {current_sample.keys()}")
840
+ if suffixes is None or suffix in suffixes:
841
+ current_sample[suffix] = value
842
+ if wds.tariterators.valid_sample(current_sample):
843
+ yield current_sample
844
+
845
+ wds.tariterators.group_by_keys = group_by_keys
846
+
847
+ # S3 code and WDS preprocessing code based on implementation by Scott Hawley originally in https://github.com/zqevans/audio-diffusion/blob/main/dataset/dataset.py
848
+
849
+ def get_s3_contents(dataset_path, s3_url_prefix=None, filter='', recursive=True, debug=False, profile=None):
850
+ """
851
+ Returns a list of full S3 paths to files in a given S3 bucket and directory path.
852
+ """
853
+ # Ensure dataset_path ends with a trailing slash
854
+ if dataset_path != '' and not dataset_path.endswith('/'):
855
+ dataset_path += '/'
856
+ # Use posixpath to construct the S3 URL path
857
+ bucket_path = posixpath.join(s3_url_prefix or '', dataset_path)
858
+ # Construct the `aws s3 ls` command
859
+ cmd = ['aws', 's3', 'ls', bucket_path]
860
+
861
+ if profile is not None:
862
+ cmd.extend(['--profile', profile])
863
+
864
+ if recursive:
865
+ # Add the --recursive flag if requested
866
+ cmd.append('--recursive')
867
+
868
+ # Run the `aws s3 ls` command and capture the output
869
+ run_ls = subprocess.run(cmd, capture_output=True, check=True)
870
+ # Split the output into lines and strip whitespace from each line
871
+ contents = run_ls.stdout.decode('utf-8').split('\n')
872
+ contents = [x.strip() for x in contents if x]
873
+ # Remove the timestamp from lines that begin with a timestamp
874
+ contents = [re.sub(r'^\S+\s+\S+\s+\d+\s+', '', x)
875
+ if re.match(r'^\S+\s+\S+\s+\d+\s+', x) else x for x in contents]
876
+ # Construct a full S3 path for each file in the contents list
877
+ contents = [posixpath.join(s3_url_prefix or '', x)
878
+ for x in contents if not x.endswith('/')]
879
+ # Apply the filter, if specified
880
+ if filter:
881
+ contents = [x for x in contents if filter in x]
882
+ # Remove redundant directory names in the S3 URL
883
+ if recursive:
884
+ # Get the main directory name from the S3 URL
885
+ main_dir = "/".join(bucket_path.split('/')[3:])
886
+ # Remove the redundant directory names from each file path
887
+ contents = [x.replace(f'{main_dir}', '').replace(
888
+ '//', '/') for x in contents]
889
+ # Print debugging information, if requested
890
+ if debug:
891
+ print("contents = \n", contents)
892
+ # Return the list of S3 paths to files
893
+ return contents
894
+
895
+
896
+ def get_all_s3_urls(
897
+ names=[], # list of all valid [LAION AudioDataset] dataset names
898
+ # list of subsets you want from those datasets, e.g. ['train','valid']
899
+ subsets=[''],
900
+ s3_url_prefix=None, # prefix for those dataset names
901
+ recursive=True, # recursively list all tar files in all subdirs
902
+ filter_str='tar', # only grab files with this substring
903
+ # print debugging info -- note: info displayed likely to change at dev's whims
904
+ debug=False,
905
+ profiles={}, # dictionary of profiles for each item in names, e.g. {'dataset1': 'profile1', 'dataset2': 'profile2'}
906
+ ):
907
+ "get urls of shards (tar files) for multiple datasets in one s3 bucket"
908
+ urls = []
909
+ for name in names:
910
+ # If s3_url_prefix is not specified, assume the full S3 path is included in each element of the names list
911
+ if s3_url_prefix is None:
912
+ contents_str = name
913
+ else:
914
+ # Construct the S3 path using the s3_url_prefix and the current name value
915
+ contents_str = posixpath.join(s3_url_prefix, name)
916
+ if debug:
917
+ print(f"get_all_s3_urls: {contents_str}:")
918
+ for subset in subsets:
919
+ subset_str = posixpath.join(contents_str, subset)
920
+ if debug:
921
+ print(f"subset_str = {subset_str}")
922
+ # Get the list of tar files in the current subset directory
923
+ profile = profiles.get(name, None)
924
+ tar_list = get_s3_contents(
925
+ subset_str, s3_url_prefix=None, recursive=recursive, filter=filter_str, debug=debug, profile=profile)
926
+ for tar in tar_list:
927
+ # Escape spaces and parentheses in the tar filename for use in the shell command
928
+ tar = tar.replace(" ", "\ ").replace(
929
+ "(", "\(").replace(")", "\)")
930
+ # Construct the S3 path to the current tar file
931
+ s3_path = posixpath.join(name, subset, tar) + " -"
932
+ # Construct the AWS CLI command to download the current tar file
933
+ if s3_url_prefix is None:
934
+ request_str = f"pipe:aws s3 --cli-connect-timeout 0 cp {s3_path}"
935
+ else:
936
+ request_str = f"pipe:aws s3 --cli-connect-timeout 0 cp {posixpath.join(s3_url_prefix, s3_path)}"
937
+ if profiles.get(name):
938
+ request_str += f" --profile {profiles.get(name)}"
939
+ if debug:
940
+ print("request_str = ", request_str)
941
+ # Add the constructed URL to the list of URLs
942
+ urls.append(request_str)
943
+ return urls
944
+
945
+
946
+ def log_and_continue(exn):
947
+ """Call in an exception handler to ignore any exception, isssue a warning, and continue."""
948
+ print(f"Handling webdataset error ({repr(exn)}). Ignoring.")
949
+ return True
950
+
951
+
952
+ def is_valid_sample(sample):
953
+ has_json = "json" in sample
954
+ has_audio = "audio" in sample
955
+ is_silent = is_silence(sample["audio"])
956
+ is_rejected = "__reject__" in sample["json"] and sample["json"]["__reject__"]
957
+
958
+ return has_json and has_audio and not is_silent and not is_rejected
959
+
960
+ class S3DatasetConfig:
961
+ def __init__(
962
+ self,
963
+ id: str,
964
+ s3_path: str,
965
+ custom_metadata_fn: Optional[Callable[[str], str]] = None,
966
+ profile: Optional[str] = None,
967
+ ):
968
+ self.id = id
969
+ self.path = s3_path
970
+ self.custom_metadata_fn = custom_metadata_fn
971
+ self.profile = profile
972
+ self.urls = []
973
+
974
+ def load_data_urls(self):
975
+ self.urls = get_all_s3_urls(
976
+ names=[self.path],
977
+ s3_url_prefix=None,
978
+ recursive=True,
979
+ profiles={self.path: self.profile} if self.profile else {},
980
+ )
981
+
982
+ return self.urls
983
+
984
+ class LocalWebDatasetConfig:
985
+ def __init__(
986
+ self,
987
+ id: str,
988
+ path: str,
989
+ custom_metadata_fn: Optional[Callable[[str], str]] = None,
990
+ profile: Optional[str] = None,
991
+ ):
992
+ self.id = id
993
+ self.path = path
994
+ self.custom_metadata_fn = custom_metadata_fn
995
+ self.urls = []
996
+
997
+ def load_data_urls(self):
998
+
999
+ self.urls = fast_scandir(self.path, ["tar"])[1]
1000
+
1001
+ return self.urls
1002
+
1003
+ def audio_decoder(key, value):
1004
+ # Get file extension from key
1005
+ ext = key.split(".")[-1]
1006
+
1007
+ if ext in AUDIO_KEYS:
1008
+ return torchaudio.load(io.BytesIO(value))
1009
+ else:
1010
+ return None
1011
+
1012
+ def collation_fn(samples):
1013
+ batched = list(zip(*samples))
1014
+ result = []
1015
+ for b in batched:
1016
+ if isinstance(b[0], (int, float)):
1017
+ b = np.array(b)
1018
+ elif isinstance(b[0], torch.Tensor):
1019
+ b = torch.stack(b)
1020
+ elif isinstance(b[0], np.ndarray):
1021
+ b = np.array(b)
1022
+ else:
1023
+ b = b
1024
+ result.append(b)
1025
+ return result
1026
+
1027
+ class WebDatasetDataLoader():
1028
+ def __init__(
1029
+ self,
1030
+ datasets: List[S3DatasetConfig],
1031
+ batch_size,
1032
+ sample_size,
1033
+ sample_rate=48000,
1034
+ num_workers=8,
1035
+ epoch_steps=1000,
1036
+ random_crop=True,
1037
+ force_channels="stereo",
1038
+ augment_phase=True,
1039
+ **data_loader_kwargs
1040
+ ):
1041
+
1042
+ self.datasets = datasets
1043
+
1044
+ self.sample_size = sample_size
1045
+ self.sample_rate = sample_rate
1046
+ self.random_crop = random_crop
1047
+ self.force_channels = force_channels
1048
+ self.augment_phase = augment_phase
1049
+
1050
+ urls = [dataset.load_data_urls() for dataset in datasets]
1051
+
1052
+ # Flatten the list of lists of URLs
1053
+ urls = [url for dataset_urls in urls for url in dataset_urls]
1054
+
1055
+ # Shuffle the urls
1056
+ random.shuffle(urls)
1057
+
1058
+ self.dataset = wds.DataPipeline(
1059
+ wds.ResampledShards(urls),
1060
+ wds.tarfile_to_samples(handler=log_and_continue),
1061
+ wds.decode(audio_decoder, handler=log_and_continue),
1062
+ wds.map(self.wds_preprocess, handler=log_and_continue),
1063
+ wds.select(is_valid_sample),
1064
+ wds.to_tuple("audio", "json", handler=log_and_continue),
1065
+ #wds.shuffle(bufsize=1000, initial=5000),
1066
+ wds.batched(batch_size, partial=False, collation_fn=collation_fn),
1067
+ ).with_epoch(epoch_steps//num_workers if num_workers > 0 else epoch_steps)
1068
+
1069
+ self.data_loader = wds.WebLoader(self.dataset, num_workers=num_workers, **data_loader_kwargs)
1070
+
1071
+ def wds_preprocess(self, sample):
1072
+
1073
+ found_key, rewrite_key = '', ''
1074
+ for k, v in sample.items(): # print the all entries in dict
1075
+ for akey in AUDIO_KEYS:
1076
+ if k.endswith(akey):
1077
+ # to rename long/weird key with its simpler counterpart
1078
+ found_key, rewrite_key = k, akey
1079
+ break
1080
+ if '' != found_key:
1081
+ break
1082
+ if '' == found_key: # got no audio!
1083
+ return None # try returning None to tell WebDataset to skip this one
1084
+
1085
+ audio, in_sr = sample[found_key]
1086
+ if in_sr != self.sample_rate:
1087
+ resample_tf = T.Resample(in_sr, self.sample_rate)
1088
+ audio = resample_tf(audio)
1089
+
1090
+ if self.sample_size is not None:
1091
+ # Pad/crop and get the relative timestamp
1092
+ pad_crop = PadCrop_Normalized_T(
1093
+ self.sample_size, randomize=self.random_crop, sample_rate=self.sample_rate)
1094
+ audio, t_start, t_end, seconds_start, seconds_total, padding_mask = pad_crop(
1095
+ audio)
1096
+ sample["json"]["seconds_start"] = seconds_start
1097
+ sample["json"]["seconds_total"] = seconds_total
1098
+ sample["json"]["padding_mask"] = padding_mask
1099
+ else:
1100
+ t_start, t_end = 0, 1
1101
+
1102
+ # Check if audio is length zero, initialize to a single zero if so
1103
+ if audio.shape[-1] == 0:
1104
+ audio = torch.zeros(1, 1)
1105
+
1106
+ # Make the audio stereo and augment by randomly inverting phase
1107
+ augs = torch.nn.Sequential(
1108
+ Stereo() if self.force_channels == "stereo" else torch.nn.Identity(),
1109
+ Mono() if self.force_channels == "mono" else torch.nn.Identity(),
1110
+ PhaseFlipper() if self.augment_phase else torch.nn.Identity()
1111
+ )
1112
+
1113
+ audio = augs(audio)
1114
+
1115
+ sample["json"]["timestamps"] = (t_start, t_end)
1116
+
1117
+ if "text" in sample["json"]:
1118
+ sample["json"]["prompt"] = sample["json"]["text"]
1119
+
1120
+ # Check for custom metadata functions
1121
+ for dataset in self.datasets:
1122
+ if dataset.custom_metadata_fn is None:
1123
+ continue
1124
+
1125
+ if dataset.path in sample["__url__"]:
1126
+ custom_metadata = dataset.custom_metadata_fn(sample["json"], audio)
1127
+ sample["json"].update(custom_metadata)
1128
+
1129
+ if found_key != rewrite_key: # rename long/weird key with its simpler counterpart
1130
+ del sample[found_key]
1131
+
1132
+ sample["audio"] = audio
1133
+
1134
+ # Add audio to the metadata as well for conditioning
1135
+ sample["json"]["audio"] = audio
1136
+
1137
+ return sample
1138
+
1139
+ def create_dataloader_from_config(dataset_config, batch_size, sample_size, sample_rate, audio_channels=2, num_workers=4, shuffle=True):
1140
+
1141
+ dataset_type = dataset_config.get("dataset_type", None)
1142
+
1143
+ assert dataset_type is not None, "Dataset type must be specified in dataset config"
1144
+
1145
+ if audio_channels == 1:
1146
+ force_channels = "mono"
1147
+ elif audio_channels == 2:
1148
+ force_channels = "stereo"
1149
+ else:
1150
+ force_channels = "foa"
1151
+
1152
+ if dataset_type == "audio_dir":
1153
+
1154
+ audio_dir_configs = dataset_config.get("datasets", None)
1155
+
1156
+ assert audio_dir_configs is not None, "Directory configuration must be specified in datasets[\"dataset\"]"
1157
+
1158
+ configs = []
1159
+
1160
+ for audio_dir_config in audio_dir_configs:
1161
+ audio_dir_path = audio_dir_config.get("path", None)
1162
+ split_path = audio_dir_config.get("split_path", None)
1163
+ assert audio_dir_path is not None, "Path must be set for local audio directory configuration"
1164
+ custom_metadata_fn = None
1165
+ custom_metadata_module_path = audio_dir_config.get("custom_metadata_module", None)
1166
+
1167
+ if custom_metadata_module_path is not None:
1168
+ spec = importlib.util.spec_from_file_location("metadata_module", custom_metadata_module_path)
1169
+ metadata_module = importlib.util.module_from_spec(spec)
1170
+ spec.loader.exec_module(metadata_module)
1171
+
1172
+ custom_metadata_fn = metadata_module.get_custom_metadata
1173
+
1174
+ configs.append(
1175
+ LocalDatasetConfig(
1176
+ id=audio_dir_config["id"],
1177
+ path=audio_dir_path,
1178
+ split_path=split_path,
1179
+ custom_metadata_fn=custom_metadata_fn
1180
+ )
1181
+ )
1182
+
1183
+ train_set = SampleDataset(
1184
+ configs,
1185
+ sample_rate=sample_rate,
1186
+ sample_size=sample_size,
1187
+ random_crop=dataset_config.get("random_crop", True),
1188
+ input_type=dataset_config.get("input_type", "video"),
1189
+ fps=dataset_config.get("fps", 4),
1190
+ force_channels=force_channels
1191
+ )
1192
+
1193
+ return torch.utils.data.DataLoader(train_set, batch_size, shuffle=True,
1194
+ num_workers=num_workers, persistent_workers=True, pin_memory=True, drop_last=True, collate_fn=collation_fn)
1195
+
1196
+ elif dataset_type in ["s3", "wds"]: # Support "s3" type for backwards compatibility
1197
+
1198
+ wds_configs = []
1199
+
1200
+ for wds_config in dataset_config["datasets"]:
1201
+
1202
+ custom_metadata_fn = None
1203
+ custom_metadata_module_path = wds_config.get("custom_metadata_module", None)
1204
+
1205
+ if custom_metadata_module_path is not None:
1206
+ spec = importlib.util.spec_from_file_location("metadata_module", custom_metadata_module_path)
1207
+ metadata_module = importlib.util.module_from_spec(spec)
1208
+ spec.loader.exec_module(metadata_module)
1209
+
1210
+ custom_metadata_fn = metadata_module.get_custom_metadata
1211
+
1212
+ if "s3_path" in wds_config:
1213
+
1214
+ wds_configs.append(
1215
+ S3DatasetConfig(
1216
+ id=wds_config["id"],
1217
+ s3_path=wds_config["s3_path"],
1218
+ custom_metadata_fn=custom_metadata_fn,
1219
+ profile=wds_config.get("profile", None),
1220
+ )
1221
+ )
1222
+
1223
+ elif "path" in wds_config:
1224
+
1225
+ wds_configs.append(
1226
+ LocalWebDatasetConfig(
1227
+ id=wds_config["id"],
1228
+ path=wds_config["path"],
1229
+ custom_metadata_fn=custom_metadata_fn
1230
+ )
1231
+ )
1232
+
1233
+ return WebDatasetDataLoader(
1234
+ wds_configs,
1235
+ sample_rate=sample_rate,
1236
+ sample_size=sample_size,
1237
+ batch_size=batch_size,
1238
+ random_crop=dataset_config.get("random_crop", True),
1239
+ num_workers=num_workers,
1240
+ persistent_workers=True,
1241
+ force_channels=force_channels,
1242
+ epoch_steps=dataset_config.get("epoch_steps", 2000)
1243
+ ).data_loader
1244
+
1245
+ elif dataset_type == "latent_dir":
1246
+
1247
+ audio_dir_configs = dataset_config.get("datasets", None)
1248
+
1249
+ assert audio_dir_configs is not None, "Directory configuration must be specified in datasets[\"dataset\"]"
1250
+
1251
+ configs = []
1252
+
1253
+ for audio_dir_config in audio_dir_configs:
1254
+ audio_dir_path = audio_dir_config.get("path", None)
1255
+ split_path = audio_dir_config.get("split_path", None)
1256
+ assert audio_dir_path is not None, "Path must be set for local audio directory configuration"
1257
+
1258
+ configs.append(
1259
+ LocalDatasetConfig(
1260
+ id=audio_dir_config["id"],
1261
+ path=audio_dir_path,
1262
+ split_path=split_path,
1263
+ )
1264
+ )
1265
+
1266
+ train_set = LatentDataset(
1267
+ configs,
1268
+ sample_rate=sample_rate,
1269
+ sample_size=sample_size,
1270
+ random_crop=dataset_config.get("random_crop", True),
1271
+ input_type=dataset_config.get("input_type", "video"),
1272
+ fps=dataset_config.get("fps", 4),
1273
+ force_channels=force_channels
1274
+ )
1275
+
1276
+ return torch.utils.data.DataLoader(train_set, batch_size, shuffle=True,
1277
+ num_workers=num_workers, persistent_workers=True, pin_memory=True, drop_last=True, collate_fn=collation_fn)
1278
+ elif dataset_type == 'multimodal_dir':
1279
+ audio_dir_configs = dataset_config.get("datasets", None)
1280
+
1281
+ assert audio_dir_configs is not None, "Directory configuration must be specified in datasets[\"dataset\"]"
1282
+
1283
+ configs = []
1284
+
1285
+ for audio_dir_config in audio_dir_configs:
1286
+ audio_dir_path = audio_dir_config.get("path", None)
1287
+ split_path = audio_dir_config.get("split_path", None)
1288
+ assert audio_dir_path is not None, "Path must be set for local audio directory configuration"
1289
+ custom_metadata_fn = None
1290
+ custom_metadata_module_path = audio_dir_config.get("custom_metadata_module", None)
1291
+
1292
+ if custom_metadata_module_path is not None:
1293
+ spec = importlib.util.spec_from_file_location("metadata_module", custom_metadata_module_path)
1294
+ metadata_module = importlib.util.module_from_spec(spec)
1295
+ spec.loader.exec_module(metadata_module)
1296
+
1297
+ custom_metadata_fn = metadata_module.get_custom_metadata
1298
+
1299
+ configs.append(
1300
+ LocalDatasetConfig(
1301
+ id=audio_dir_config["id"],
1302
+ path=audio_dir_path,
1303
+ split_path=split_path,
1304
+ custom_metadata_fn=custom_metadata_fn
1305
+ )
1306
+ )
1307
+
1308
+ train_set = MultiModalDataset(
1309
+ configs,
1310
+ sample_rate=sample_rate,
1311
+ sample_size=sample_size,
1312
+ random_crop=dataset_config.get("random_crop", True),
1313
+ input_type=dataset_config.get("input_type", "video"),
1314
+ fps=dataset_config.get("fps", 4),
1315
+ force_channels=force_channels
1316
+ )
1317
+
1318
+ return torch.utils.data.DataLoader(train_set, batch_size, shuffle=shuffle,
1319
+ num_workers=num_workers, persistent_workers=True, pin_memory=True, drop_last=True, collate_fn=collation_fn)
ThinkSound/data/utils.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn
6
+ from typing import Tuple
7
+ import numpy as np
8
+
9
+ class PadCrop(nn.Module):
10
+ def __init__(self, n_samples, randomize=True):
11
+ super().__init__()
12
+ self.n_samples = n_samples
13
+ self.randomize = randomize
14
+
15
+ def __call__(self, signal):
16
+ n, s = signal.shape
17
+ start = 0 if (not self.randomize) else torch.randint(0, max(0, s - self.n_samples) + 1, []).item()
18
+ end = start + self.n_samples
19
+ output = signal.new_zeros([n, self.n_samples])
20
+ output[:, :min(s, self.n_samples)] = signal[:, start:end]
21
+ return output
22
+
23
+ class PadCrop_Normalized_T(nn.Module):
24
+
25
+ def __init__(self, n_samples: int, sample_rate: int, randomize: bool = True):
26
+
27
+ super().__init__()
28
+
29
+ self.n_samples = n_samples
30
+ self.sample_rate = sample_rate
31
+ self.randomize = randomize
32
+
33
+ def __call__(self, source: torch.Tensor, randomize=True) -> Tuple[torch.Tensor, float, float, int, int]:
34
+
35
+ n_channels, n_samples = source.shape
36
+
37
+ # If the audio is shorter than the desired length, pad it
38
+ upper_bound = max(0, n_samples - self.n_samples)
39
+
40
+ # If randomize is False, always start at the beginning of the audio
41
+ offset = 0
42
+ if(randomize and n_samples > self.n_samples):
43
+ offset = random.randint(0, upper_bound)
44
+
45
+ # Calculate the start and end times of the chunk
46
+ t_start = offset / (upper_bound + self.n_samples)
47
+ t_end = (offset + self.n_samples) / (upper_bound + self.n_samples)
48
+
49
+ # Create the chunk
50
+ chunk = source.new_zeros([n_channels, self.n_samples])
51
+
52
+ # Copy the audio into the chunk
53
+ chunk[:, :min(n_samples, self.n_samples)] = source[:, offset:offset + self.n_samples]
54
+
55
+ # Calculate the start and end times of the chunk in seconds
56
+ seconds_start = math.floor(offset / self.sample_rate)
57
+ seconds_total = math.ceil(n_samples / self.sample_rate)
58
+
59
+ # Create a mask the same length as the chunk with 1s where the audio is and 0s where it isn't
60
+ padding_mask = torch.zeros([self.n_samples])
61
+ padding_mask[:min(n_samples, self.n_samples)] = 1
62
+
63
+
64
+ return (
65
+ chunk,
66
+ t_start,
67
+ t_end,
68
+ seconds_start,
69
+ seconds_total,
70
+ padding_mask
71
+ )
72
+
73
+ class PadCrop_Video_Normalized_T(nn.Module):
74
+
75
+ def __init__(self, n_samples: int, sample_rate: int, fps: int, randomize: bool = True):
76
+
77
+ super().__init__()
78
+
79
+ self.n_samples = n_samples
80
+ self.sample_rate = sample_rate
81
+ self.randomize = randomize
82
+ self.fps = fps
83
+ self.n_frames = int(self.fps * self.n_samples / self.sample_rate)
84
+
85
+ def __call__(self, audio: torch.Tensor, video: torch.Tensor) -> Tuple[torch.Tensor, float, float, int, int]:
86
+ n_channels, n_samples = audio.shape
87
+ # print(video.shape)
88
+ n_frames, dim = video.shape
89
+ if not torch.is_tensor(video):
90
+ video = torch.from_numpy(video)
91
+ # If the audio is shorter than the desired length, pad it
92
+ audio_upper_bound = max(0, n_samples - self.n_samples)
93
+ video_upper_bound = int(max(0, n_frames - self.n_frames) * self.sample_rate / self.fps)
94
+ upper_bound = min(audio_upper_bound,video_upper_bound)
95
+
96
+ # If randomize is False, always start at the beginning of the audio
97
+ offset = 0
98
+ if(self.randomize and n_samples > self.n_samples and n_frames > self.n_frames):
99
+ offset = random.randint(0, upper_bound)
100
+
101
+ # Calculate the start and end times of the chunk
102
+ t_start = offset / (upper_bound + self.n_samples)
103
+ t_end = (offset + self.n_samples) / (upper_bound + self.n_samples)
104
+ frame_offset = int(self.fps * offset / self.sample_rate)
105
+ # frame_end = frame_offset + int(self.fps * self.n_samples / self.sample_rate)
106
+ # Create the chunk
107
+ chunk = audio.new_zeros([n_channels, self.n_samples])
108
+ video_chunk = video.new_zeros([self.n_frames, video.shape[1]])
109
+ # Copy the audio into the chunk
110
+ chunk[:, :min(n_samples, self.n_samples)] = audio[:, offset:offset + self.n_samples]
111
+ video_chunk[:min(n_frames, self.n_frames)] = video[frame_offset:frame_offset + self.n_frames,:]
112
+ # Calculate the start and end times of the chunk in seconds
113
+ seconds_start = math.floor(offset / self.sample_rate)
114
+ seconds_total = math.ceil(n_samples / self.sample_rate)
115
+
116
+ # Create a mask the same length as the chunk with 1s where the audio is and 0s where it isn't
117
+ padding_mask = torch.zeros([self.n_samples])
118
+ padding_mask[:min(n_samples, self.n_samples)] = 1
119
+
120
+
121
+ return (
122
+ chunk,
123
+ video_chunk,
124
+ t_start,
125
+ t_end,
126
+ seconds_start,
127
+ seconds_total,
128
+ padding_mask
129
+ )
130
+
131
+ class PadCrop_Video_Image_Normalized_T(nn.Module):
132
+
133
+ def __init__(self, n_samples: int, sample_rate: int, fps: int, randomize: bool = True):
134
+
135
+ super().__init__()
136
+
137
+ self.n_samples = n_samples
138
+ self.sample_rate = sample_rate
139
+ self.randomize = randomize
140
+ self.fps = fps
141
+ self.n_frames = int(self.fps * self.n_samples / self.sample_rate)
142
+
143
+ def __call__(self, audio: torch.Tensor, video: torch.Tensor) -> Tuple[torch.Tensor, float, float, int, int]:
144
+ n_channels, n_samples = audio.shape
145
+ # import ipdb
146
+ # ipdb.set_trace()
147
+ n_frames, channel, width, height= video.shape
148
+ video = torch.from_numpy(video)
149
+ # If the audio is shorter than the desired length, pad it
150
+ audio_upper_bound = max(0, n_samples - self.n_samples)
151
+ video_upper_bound = int(max(0, n_frames - self.n_frames) * self.sample_rate / self.fps)
152
+ upper_bound = min(audio_upper_bound,video_upper_bound)
153
+
154
+ # If randomize is False, always start at the beginning of the audio
155
+ offset = 0
156
+ if(self.randomize and n_samples > self.n_samples and n_frames > self.n_frames):
157
+ offset = random.randint(0, upper_bound)
158
+
159
+ # Calculate the start and end times of the chunk
160
+ t_start = offset / (upper_bound + self.n_samples)
161
+ t_end = (offset + self.n_samples) / (upper_bound + self.n_samples)
162
+ frame_offset = int(self.fps * offset / self.sample_rate)
163
+ # frame_end = frame_offset + int(self.fps * self.n_samples / self.sample_rate)
164
+ # Create the chunk
165
+ chunk = audio.new_zeros([n_channels, self.n_samples])
166
+ video_chunk = video.new_zeros([self.n_frames, channel, width, height])
167
+ # Copy the audio into the chunk
168
+ chunk[:, :min(n_samples, self.n_samples)] = audio[:, offset:offset + self.n_samples]
169
+ video_chunk[:min(n_frames, self.n_frames)] = video[frame_offset:frame_offset + self.n_frames]
170
+ # Calculate the start and end times of the chunk in seconds
171
+ seconds_start = math.floor(offset / self.sample_rate)
172
+ seconds_total = math.ceil(n_samples / self.sample_rate)
173
+
174
+ # Create a mask the same length as the chunk with 1s where the audio is and 0s where it isn't
175
+ padding_mask = torch.zeros([self.n_samples])
176
+ padding_mask[:min(n_samples, self.n_samples)] = 1
177
+
178
+
179
+ return (
180
+ chunk,
181
+ video_chunk,
182
+ t_start,
183
+ t_end,
184
+ seconds_start,
185
+ seconds_total,
186
+ padding_mask
187
+ )
188
+
189
+ class PadCrop_Video_Hiera_Normalized_T(nn.Module):
190
+
191
+ def __init__(self, n_samples: int, sample_rate: int, fps: int, randomize: bool = True):
192
+
193
+ super().__init__()
194
+
195
+ self.n_samples = n_samples
196
+ self.sample_rate = sample_rate
197
+ self.randomize = randomize
198
+ self.fps = fps
199
+ self.n_frames = int(self.fps * self.n_samples / self.sample_rate)
200
+
201
+ def __call__(self, audio: torch.Tensor, video: torch.Tensor) -> Tuple[torch.Tensor, float, float, int, int]:
202
+
203
+ n_channels, n_samples = audio.shape
204
+ n_frames, heigh, width, channel = video.shape
205
+ video = torch.from_numpy(video)
206
+ # If the audio is shorter than the desired length, pad it
207
+ audio_upper_bound = max(0, n_samples - self.n_samples)
208
+ video_upper_bound = int(max(0, n_frames - self.n_frames) * self.sample_rate / self.fps)
209
+ upper_bound = min(audio_upper_bound,video_upper_bound)
210
+
211
+ # If randomize is False, always start at the beginning of the audio
212
+ offset = 0
213
+ if(self.randomize and n_samples > self.n_samples and n_frames > self.n_frames):
214
+ offset = random.randint(0, upper_bound)
215
+
216
+ # Calculate the start and end times of the chunk
217
+ t_start = offset / (upper_bound + self.n_samples)
218
+ t_end = (offset + self.n_samples) / (upper_bound + self.n_samples)
219
+ frame_offset = int(self.fps * offset / self.sample_rate)
220
+ # frame_end = frame_offset + int(self.fps * self.n_samples / self.sample_rate)
221
+ # Create the chunk
222
+ chunk = audio.new_zeros([n_channels, self.n_samples])
223
+ video_chunk = video.new_zeros([self.n_frames, heigh, width, channel])
224
+ # Copy the audio into the chunk
225
+ chunk[:, :min(n_samples, self.n_samples)] = audio[:, offset:offset + self.n_samples]
226
+ video_chunk[:min(n_frames, self.n_frames)] = video[frame_offset:frame_offset + self.n_frames]
227
+ # video_chunk = video_chunk[None].permute(0, 4, 1, 2, 3).contiguous()
228
+ # print(video_chunk.shape)
229
+ # video_chunk = F.interpolate(
230
+ # video_chunk[0],
231
+ # size=(224, 224, 3), # 输出的空间尺寸
232
+ # scale_factor=(target_frames / video_tensor.shape[1], 1, 1), # 时间轴的缩放因子
233
+ # mode='trilinear', # 使用三线性插值
234
+ # align_corners=False
235
+ # )
236
+
237
+ # video_chunk = F.interpolate(video_chunk, size=(64, 224, 224), mode="trilinear")[0]
238
+ # video_chunk = video_chunk.view(3,4,16,224,224).transpose(0,1)
239
+ # Calculate the start and end times of the chunk in seconds
240
+ seconds_start = math.floor(offset / self.sample_rate)
241
+ seconds_total = math.ceil(n_samples / self.sample_rate)
242
+
243
+ # Create a mask the same length as the chunk with 1s where the audio is and 0s where it isn't
244
+ padding_mask = torch.zeros([self.n_samples])
245
+ padding_mask[:min(n_samples, self.n_samples)] = 1
246
+
247
+
248
+ return (
249
+ chunk,
250
+ video_chunk,
251
+ t_start,
252
+ t_end,
253
+ seconds_start,
254
+ seconds_total,
255
+ padding_mask
256
+ )
257
+
258
+ class PadCrop_DualVideo_Normalized_T(nn.Module):
259
+
260
+ def __init__(self, n_samples: int, sample_rate: int, fps: int, randomize: bool = True):
261
+
262
+ super().__init__()
263
+
264
+ self.n_samples = n_samples
265
+ self.sample_rate = sample_rate
266
+ self.randomize = randomize
267
+ self.fps = fps
268
+ self.n_frames = int(self.fps * self.n_samples / self.sample_rate)
269
+
270
+ def __call__(self, audio: torch.Tensor, video_360: torch.Tensor, video_fov: torch.Tensor) -> Tuple[torch.Tensor, float, float, int, int]:
271
+ n_channels, n_samples = audio.shape
272
+ # print(video.shape)
273
+ n_frames, dim = video_360.shape
274
+ video_360 = torch.from_numpy(video_360)
275
+ video_fov = torch.from_numpy(video_fov)
276
+ # If the audio is shorter than the desired length, pad it
277
+ audio_upper_bound = max(0, n_samples - self.n_samples)
278
+ video_upper_bound = int(max(0, n_frames - self.n_frames) * self.sample_rate / self.fps)
279
+ upper_bound = min(audio_upper_bound,video_upper_bound)
280
+
281
+ # If randomize is False, always start at the beginning of the audio
282
+ offset = 0
283
+ if(self.randomize and n_samples > self.n_samples and n_frames > self.n_frames):
284
+ offset = random.randint(0, upper_bound)
285
+
286
+ # Calculate the start and end times of the chunk
287
+ t_start = offset / (upper_bound + self.n_samples)
288
+ t_end = (offset + self.n_samples) / (upper_bound + self.n_samples)
289
+ frame_offset = int(self.fps * offset / self.sample_rate)
290
+ # frame_end = frame_offset + int(self.fps * self.n_samples / self.sample_rate)
291
+ # Create the chunk
292
+ chunk = audio.new_zeros([n_channels, self.n_samples])
293
+ video_360_chunk = video_360.new_zeros([self.n_frames, video_360.shape[1]])
294
+ video_fov_chunk = video_fov.new_zeros([self.n_frames, video_fov.shape[1]])
295
+ # Copy the audio into the chunk
296
+ chunk[:, :min(n_samples, self.n_samples)] = audio[:, offset:offset + self.n_samples]
297
+ video_360_chunk[:min(n_frames, self.n_frames)] = video_360[frame_offset:frame_offset + self.n_frames,:]
298
+ video_fov_chunk[:min(n_frames, self.n_frames)] = video_fov[frame_offset:frame_offset + self.n_frames,:]
299
+ # Calculate the start and end times of the chunk in seconds
300
+ seconds_start = math.floor(offset / self.sample_rate)
301
+ seconds_total = math.ceil(n_samples / self.sample_rate)
302
+
303
+ # Create a mask the same length as the chunk with 1s where the audio is and 0s where it isn't
304
+ padding_mask = torch.zeros([self.n_samples])
305
+ padding_mask[:min(n_samples, self.n_samples)] = 1
306
+
307
+
308
+ return (
309
+ chunk,
310
+ video_360_chunk,
311
+ video_fov_chunk,
312
+ t_start,
313
+ t_end,
314
+ seconds_start,
315
+ seconds_total,
316
+ padding_mask
317
+ )
318
+
319
+ class PhaseFlipper(nn.Module):
320
+ "Randomly invert the phase of a signal"
321
+ def __init__(self, p=0.5):
322
+ super().__init__()
323
+ self.p = p
324
+ def __call__(self, signal):
325
+ return -signal if (random.random() < self.p) else signal
326
+
327
+ class Mono(nn.Module):
328
+ def __call__(self, signal):
329
+ return torch.mean(signal, dim=0, keepdims=True) if len(signal.shape) > 1 else signal
330
+
331
+ class Stereo(nn.Module):
332
+ def __call__(self, signal):
333
+ signal_shape = signal.shape
334
+ # Check if it's mono
335
+ if len(signal_shape) == 1: # s -> 2, s
336
+ signal = signal.unsqueeze(0).repeat(2, 1)
337
+ elif len(signal_shape) == 2:
338
+ if signal_shape[0] == 1: #1, s -> 2, s
339
+ signal = signal.repeat(2, 1)
340
+ elif signal_shape[0] > 2: #?, s -> 2,s
341
+ signal = signal[:2, :]
342
+
343
+ return signal
344
+
345
+ class FOA(nn.Module):
346
+ def __call__(self, signal):
347
+ signal_shape = signal.shape
348
+ # Check if it's mono
349
+ if len(signal_shape) == 1: # s -> (4, s)
350
+ foa = torch.zeros(4, signal_shape[0], device=signal.device) # 与输入信号一致的设备类型
351
+ foa[0, :] = signal # W通道: 全方位声源
352
+ foa[1, :] = 0 # X通道
353
+ foa[2, :] = 0 # Y通道
354
+ foa[3, :] = 0 # Z通道
355
+ elif len(signal_shape) == 2:
356
+ foa = torch.zeros(4, signal_shape[1], device=signal.device) # 与输入信号一致的设备类型
357
+ if signal_shape[0] == 1: # (1, s) -> (4, s)
358
+ foa[0, :] = signal[0] # W通道: 全方位声源
359
+ foa[1, :] = 0 # X通道
360
+ foa[2, :] = 0 # Y通道
361
+ foa[3, :] = 0 # Z通道
362
+ elif signal_shape[0] == 2: # (2, s) -> (4, s)
363
+ left = signal[0]
364
+ right = signal[1]
365
+ # 将立体声信号映射到FOA信号通道
366
+ foa[0, :] = (left + right) / np.sqrt(2) # W通道: 全方位声源
367
+ foa[1, :] = (left - right) / np.sqrt(2) # X通道: 前后方向
368
+ foa[2, :] = 0 # Y通道: 左右方向,简单实现先置零
369
+ foa[3, :] = 0 # Z通道: 垂直方向,这里置零
370
+ else:
371
+ foa = signal
372
+
373
+ else:
374
+ raise ValueError(f"Unsupported signal shape: {signal_shape}")
375
+
376
+ assert foa.shape[0] == 4, f'inputs not FOA format'
377
+
378
+ return foa
ThinkSound/inference/__init__.py ADDED
File without changes
ThinkSound/inference/generation.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import typing as tp
4
+ import math
5
+ from torchaudio import transforms as T
6
+
7
+ from .utils import prepare_audio
8
+ from .sampling import sample, sample_k, sample_rf
9
+ from ..data.utils import PadCrop
10
+
11
+ def generate_diffusion_uncond(
12
+ model,
13
+ steps: int = 250,
14
+ batch_size: int = 1,
15
+ sample_size: int = 2097152,
16
+ seed: int = -1,
17
+ device: str = "cuda",
18
+ init_audio: tp.Optional[tp.Tuple[int, torch.Tensor]] = None,
19
+ init_noise_level: float = 1.0,
20
+ return_latents = False,
21
+ **sampler_kwargs
22
+ ) -> torch.Tensor:
23
+
24
+ # The length of the output in audio samples
25
+ audio_sample_size = sample_size
26
+
27
+ # If this is latent diffusion, change sample_size instead to the downsampled latent size
28
+ if model.pretransform is not None:
29
+ sample_size = sample_size // model.pretransform.downsampling_ratio
30
+
31
+ # Seed
32
+ # The user can explicitly set the seed to deterministically generate the same output. Otherwise, use a random seed.
33
+ seed = seed if seed != -1 else np.random.randint(0, 2**32 - 1, dtype=np.uint32)
34
+ print(seed)
35
+ torch.manual_seed(seed)
36
+ # Define the initial noise immediately after setting the seed
37
+ noise = torch.randn([batch_size, model.io_channels, sample_size], device=device)
38
+
39
+ if init_audio is not None:
40
+ # The user supplied some initial audio (for inpainting or variation). Let us prepare the input audio.
41
+ in_sr, init_audio = init_audio
42
+
43
+ io_channels = model.io_channels
44
+
45
+ # For latent models, set the io_channels to the autoencoder's io_channels
46
+ if model.pretransform is not None:
47
+ io_channels = model.pretransform.io_channels
48
+
49
+ # Prepare the initial audio for use by the model
50
+ init_audio = prepare_audio(init_audio, in_sr=in_sr, target_sr=model.sample_rate, target_length=audio_sample_size, target_channels=io_channels, device=device)
51
+
52
+ # For latent models, encode the initial audio into latents
53
+ if model.pretransform is not None:
54
+ init_audio = model.pretransform.encode(init_audio)
55
+
56
+ init_audio = init_audio.repeat(batch_size, 1, 1)
57
+ else:
58
+ # The user did not supply any initial audio for inpainting or variation. Generate new output from scratch.
59
+ init_audio = None
60
+ init_noise_level = None
61
+
62
+ # Inpainting mask
63
+
64
+ if init_audio is not None:
65
+ # variations
66
+ sampler_kwargs["sigma_max"] = init_noise_level
67
+ mask = None
68
+ else:
69
+ mask = None
70
+
71
+ # Now the generative AI part:
72
+
73
+ diff_objective = model.diffusion_objective
74
+
75
+ if diff_objective == "v":
76
+ # k-diffusion denoising process go!
77
+ sampled = sample_k(model.model, noise, init_audio, mask, steps, **sampler_kwargs, device=device)
78
+ elif diff_objective == "rectified_flow":
79
+ sampled = sample_rf(model.model, noise, init_data=init_audio, steps=steps, **sampler_kwargs, device=device)
80
+
81
+ # Denoising process done.
82
+ # If this is latent diffusion, decode latents back into audio
83
+ if model.pretransform is not None and not return_latents:
84
+ sampled = model.pretransform.decode(sampled)
85
+
86
+ # Return audio
87
+ return sampled
88
+
89
+
90
+ def generate_diffusion_cond(
91
+ model,
92
+ steps: int = 250,
93
+ cfg_scale=6,
94
+ conditioning: dict = None,
95
+ conditioning_tensors: tp.Optional[dict] = None,
96
+ negative_conditioning: dict = None,
97
+ negative_conditioning_tensors: tp.Optional[dict] = None,
98
+ batch_size: int = 1,
99
+ sample_size: int = 2097152,
100
+ sample_rate: int = 48000,
101
+ seed: int = -1,
102
+ device: str = "cuda",
103
+ init_audio: tp.Optional[tp.Tuple[int, torch.Tensor]] = None,
104
+ init_noise_level: float = 1.0,
105
+ mask_args: dict = None,
106
+ return_latents = False,
107
+ **sampler_kwargs
108
+ ) -> torch.Tensor:
109
+ """
110
+ Generate audio from a prompt using a diffusion model.
111
+
112
+ Args:
113
+ model: The diffusion model to use for generation.
114
+ steps: The number of diffusion steps to use.
115
+ cfg_scale: Classifier-free guidance scale
116
+ conditioning: A dictionary of conditioning parameters to use for generation.
117
+ conditioning_tensors: A dictionary of precomputed conditioning tensors to use for generation.
118
+ batch_size: The batch size to use for generation.
119
+ sample_size: The length of the audio to generate, in samples.
120
+ sample_rate: The sample rate of the audio to generate (Deprecated, now pulled from the model directly)
121
+ seed: The random seed to use for generation, or -1 to use a random seed.
122
+ device: The device to use for generation.
123
+ init_audio: A tuple of (sample_rate, audio) to use as the initial audio for generation.
124
+ init_noise_level: The noise level to use when generating from an initial audio sample.
125
+ return_latents: Whether to return the latents used for generation instead of the decoded audio.
126
+ **sampler_kwargs: Additional keyword arguments to pass to the sampler.
127
+ """
128
+
129
+ # The length of the output in audio samples
130
+ audio_sample_size = sample_size
131
+
132
+ # If this is latent diffusion, change sample_size instead to the downsampled latent size
133
+ if model.pretransform is not None:
134
+ sample_size = sample_size // model.pretransform.downsampling_ratio
135
+
136
+ # Seed
137
+ # The user can explicitly set the seed to deterministically generate the same output. Otherwise, use a random seed.
138
+ seed = seed if seed != -1 else np.random.randint(0, 2**32 - 1, dtype=np.uint32)
139
+ print(seed)
140
+ torch.manual_seed(seed)
141
+ # Define the initial noise immediately after setting the seed
142
+ noise = torch.randn([batch_size, model.io_channels, sample_size], device=device)
143
+
144
+ torch.backends.cuda.matmul.allow_tf32 = False
145
+ torch.backends.cudnn.allow_tf32 = False
146
+ torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction = False
147
+ torch.backends.cudnn.benchmark = False
148
+ import ipdb
149
+ # ipdb.set_trace()
150
+ # Conditioning
151
+ assert conditioning is not None or conditioning_tensors is not None, "Must provide either conditioning or conditioning_tensors"
152
+ if conditioning_tensors is None:
153
+ conditioning_tensors = model.conditioner(conditioning, device)
154
+ conditioning_inputs = model.get_conditioning_inputs(conditioning_tensors)
155
+
156
+ if negative_conditioning is not None or negative_conditioning_tensors is not None:
157
+
158
+ if negative_conditioning_tensors is None:
159
+ negative_conditioning_tensors = model.conditioner(negative_conditioning, device)
160
+
161
+ negative_conditioning_tensors = model.get_conditioning_inputs(negative_conditioning_tensors, negative=True)
162
+ else:
163
+ negative_conditioning_tensors = {}
164
+
165
+ if init_audio is not None:
166
+ # The user supplied some initial audio (for inpainting or variation). Let us prepare the input audio.
167
+ in_sr, init_audio = init_audio
168
+
169
+ io_channels = model.io_channels
170
+
171
+ # For latent models, set the io_channels to the autoencoder's io_channels
172
+ if model.pretransform is not None:
173
+ io_channels = model.pretransform.io_channels
174
+
175
+ # Prepare the initial audio for use by the model
176
+ init_audio = prepare_audio(init_audio, in_sr=in_sr, target_sr=model.sample_rate, target_length=audio_sample_size, target_channels=io_channels, device=device)
177
+
178
+ # For latent models, encode the initial audio into latents
179
+ if model.pretransform is not None:
180
+ init_audio = model.pretransform.encode(init_audio)
181
+
182
+ init_audio = init_audio.repeat(batch_size, 1, 1)
183
+ else:
184
+ # The user did not supply any initial audio for inpainting or variation. Generate new output from scratch.
185
+ init_audio = None
186
+ init_noise_level = None
187
+ mask_args = None
188
+
189
+ # Inpainting mask
190
+ if init_audio is not None and mask_args is not None:
191
+ # Cut and paste init_audio according to cropfrom, pastefrom, pasteto
192
+ # This is helpful for forward and reverse outpainting
193
+ cropfrom = math.floor(mask_args["cropfrom"]/100.0 * sample_size)
194
+ pastefrom = math.floor(mask_args["pastefrom"]/100.0 * sample_size)
195
+ pasteto = math.ceil(mask_args["pasteto"]/100.0 * sample_size)
196
+ assert pastefrom < pasteto, "Paste From should be less than Paste To"
197
+ croplen = pasteto - pastefrom
198
+ if cropfrom + croplen > sample_size:
199
+ croplen = sample_size - cropfrom
200
+ cropto = cropfrom + croplen
201
+ pasteto = pastefrom + croplen
202
+ cutpaste = init_audio.new_zeros(init_audio.shape)
203
+ cutpaste[:, :, pastefrom:pasteto] = init_audio[:,:,cropfrom:cropto]
204
+ #print(cropfrom, cropto, pastefrom, pasteto)
205
+ init_audio = cutpaste
206
+ # Build a soft mask (list of floats 0 to 1, the size of the latent) from the given args
207
+ mask = build_mask(sample_size, mask_args)
208
+ mask = mask.to(device)
209
+ elif init_audio is not None and mask_args is None:
210
+ # variations
211
+ sampler_kwargs["sigma_max"] = init_noise_level
212
+ mask = None
213
+ else:
214
+ mask = None
215
+
216
+ model_dtype = next(model.model.parameters()).dtype
217
+ noise = noise.type(model_dtype)
218
+ conditioning_inputs = {k: v.type(model_dtype) if v is not None else v for k, v in conditioning_inputs.items()}
219
+ # Now the generative AI part:
220
+ # k-diffusion denoising process go!
221
+ diff_objective = model.diffusion_objective
222
+ if diff_objective == "v":
223
+ # k-diffusion denoising process go!
224
+ # sampled = sample(model.model, noise, steps, 0, **conditioning_inputs)
225
+ sampled = sample_k(model.model, noise, init_audio, mask, steps, **sampler_kwargs, **conditioning_inputs, **negative_conditioning_tensors, cfg_scale=cfg_scale, batch_cfg=True, rescale_cfg=True, device=device)
226
+ elif diff_objective == "rectified_flow":
227
+
228
+ if "sigma_min" in sampler_kwargs:
229
+ del sampler_kwargs["sigma_min"]
230
+
231
+ if "sampler_type" in sampler_kwargs:
232
+ del sampler_kwargs["sampler_type"]
233
+
234
+ sampled = sample_rf(model.model, noise, init_data=init_audio, steps=steps, **sampler_kwargs, **conditioning_inputs, **negative_conditioning_tensors, cfg_scale=cfg_scale, batch_cfg=True, rescale_cfg=True, device=device)
235
+
236
+ # v-diffusion:
237
+ #sampled = sample(model.model, noise, steps, 0, **conditioning_tensors, embedding_scale=cfg_scale)
238
+ del noise
239
+ del conditioning_tensors
240
+ del conditioning_inputs
241
+ torch.cuda.empty_cache()
242
+ # Denoising process done.
243
+ # If this is latent diffusion, decode latents back into audio
244
+ if model.pretransform is not None and not return_latents:
245
+ #cast sampled latents to pretransform dtype
246
+ sampled = sampled.to(next(model.pretransform.parameters()).dtype)
247
+ sampled = model.pretransform.decode(sampled)
248
+
249
+ # Return audio
250
+ return sampled
251
+
252
+ # builds a softmask given the parameters
253
+ # returns array of values 0 to 1, size sample_size, where 0 means noise / fresh generation, 1 means keep the input audio,
254
+ # and anything between is a mixture of old/new
255
+ # ideally 0.5 is half/half mixture but i haven't figured this out yet
256
+ def build_mask(sample_size, mask_args):
257
+ maskstart = math.floor(mask_args["maskstart"]/100.0 * sample_size)
258
+ maskend = math.ceil(mask_args["maskend"]/100.0 * sample_size)
259
+ softnessL = round(mask_args["softnessL"]/100.0 * sample_size)
260
+ softnessR = round(mask_args["softnessR"]/100.0 * sample_size)
261
+ marination = mask_args["marination"]
262
+ # use hann windows for softening the transition (i don't know if this is correct)
263
+ hannL = torch.hann_window(softnessL*2, periodic=False)[:softnessL]
264
+ hannR = torch.hann_window(softnessR*2, periodic=False)[softnessR:]
265
+ # build the mask.
266
+ mask = torch.zeros((sample_size))
267
+ mask[maskstart:maskend] = 1
268
+ mask[maskstart:maskstart+softnessL] = hannL
269
+ mask[maskend-softnessR:maskend] = hannR
270
+ # marination finishes the inpainting early in the denoising schedule, and lets audio get changed in the final rounds
271
+ if marination > 0:
272
+ mask = mask * (1-marination)
273
+ #print(mask)
274
+ return mask
ThinkSound/inference/sampling.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ from tqdm import trange, tqdm
4
+ import torch.distributions as dist
5
+
6
+ import k_diffusion as K
7
+
8
+ # Define the noise schedule and sampling loop
9
+ def get_alphas_sigmas(t):
10
+ """Returns the scaling factors for the clean image (alpha) and for the
11
+ noise (sigma), given a timestep."""
12
+ return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2)
13
+
14
+ def alpha_sigma_to_t(alpha, sigma):
15
+ """Returns a timestep, given the scaling factors for the clean image and for
16
+ the noise."""
17
+ return torch.atan2(sigma, alpha) / math.pi * 2
18
+
19
+ def t_to_alpha_sigma(t):
20
+ """Returns the scaling factors for the clean image and for the noise, given
21
+ a timestep."""
22
+ return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2)
23
+
24
+ def sample_timesteps_logsnr(batch_size, mean_logsnr=-1.2, std_logsnr=2.0):
25
+ """
26
+ Sample timesteps for diffusion training by sampling logSNR values and converting to t.
27
+
28
+ Args:
29
+ batch_size (int): Number of timesteps to sample
30
+ mean_logsnr (float): Mean of the logSNR Gaussian distribution
31
+ std_logsnr (float): Standard deviation of the logSNR Gaussian distribution
32
+
33
+ Returns:
34
+ torch.Tensor: Tensor of shape (batch_size,) containing timestep values t in [0, 1]
35
+ """
36
+ # Sample logSNR from Gaussian distribution
37
+ logsnr = torch.randn(batch_size) * std_logsnr + mean_logsnr
38
+
39
+ # Convert logSNR to timesteps using the logistic function
40
+ # Since logSNR = ln((1-t)/t), we can solve for t:
41
+ # t = 1 / (1 + exp(logsnr))
42
+ t = torch.sigmoid(-logsnr)
43
+
44
+ # Clamp values to ensure numerical stability
45
+ t = t.clamp(1e-4, 1 - 1e-4)
46
+
47
+ return t
48
+ def truncated_logistic_normal_rescaled(shape, left_trunc=0.075, right_trunc=1):
49
+ """
50
+
51
+ shape: shape of the output tensor
52
+ left_trunc: left truncation point, fraction of probability to be discarded
53
+ right_trunc: right truncation boundary, should be 1 (never seen at test time)
54
+ """
55
+
56
+ # Step 1: Sample from the logistic normal distribution (sigmoid of normal)
57
+ logits = torch.randn(shape)
58
+
59
+ # Step 2: Apply the CDF transformation of the normal distribution
60
+ normal_dist = dist.Normal(0, 1)
61
+ cdf_values = normal_dist.cdf(logits)
62
+
63
+ # Step 3: Define the truncation bounds on the CDF
64
+ lower_bound = normal_dist.cdf(torch.logit(torch.tensor(left_trunc)))
65
+ upper_bound = normal_dist.cdf(torch.logit(torch.tensor(right_trunc)))
66
+
67
+ # Step 4: Rescale linear CDF values into the truncated region (between lower_bound and upper_bound)
68
+ truncated_cdf_values = lower_bound + (upper_bound - lower_bound) * cdf_values
69
+
70
+ # Step 5: Map back to logistic-normal space using inverse CDF
71
+ truncated_samples = torch.sigmoid(normal_dist.icdf(truncated_cdf_values))
72
+
73
+ # Step 6: Rescale values so that min is 0 and max is just below 1
74
+ rescaled_samples = (truncated_samples - left_trunc) / (right_trunc - left_trunc)
75
+
76
+ return rescaled_samples
77
+
78
+ @torch.no_grad()
79
+ def sample_discrete_euler(model, x, steps, sigma_max=1, **extra_args):
80
+ """Draws samples from a model given starting noise. Euler method"""
81
+
82
+ # Make tensor of ones to broadcast the single t values
83
+ ts = x.new_ones([x.shape[0]])
84
+
85
+ # Create the noise schedule
86
+ t = torch.linspace(sigma_max, 0, steps + 1)
87
+
88
+ #alphas, sigmas = 1-t, t
89
+
90
+ for t_curr, t_prev in tqdm(zip(t[:-1], t[1:])):
91
+ # Broadcast the current timestep to the correct shape
92
+ t_curr_tensor = t_curr * torch.ones(
93
+ (x.shape[0],), dtype=x.dtype, device=x.device
94
+ )
95
+ dt = t_prev - t_curr # we solve backwards in our formulation
96
+ x = x + dt * model(x, t_curr_tensor, **extra_args) #.denoise(x, denoiser, t_curr_tensor, cond, uc)
97
+
98
+ # If we are on the last timestep, output the denoised image
99
+ return x
100
+
101
+ @torch.no_grad()
102
+ def sample(model, x, steps, eta, **extra_args):
103
+ """Draws samples from a model given starting noise. v-diffusion"""
104
+ ts = x.new_ones([x.shape[0]])
105
+
106
+ # Create the noise schedule
107
+ t = torch.linspace(1, 0, steps + 1)[:-1]
108
+
109
+ alphas, sigmas = get_alphas_sigmas(t)
110
+
111
+ # The sampling loop
112
+ for i in trange(steps):
113
+
114
+ # Get the model output (v, the predicted velocity)
115
+ with torch.cuda.amp.autocast():
116
+ v = model(x, ts * t[i], **extra_args).float()
117
+
118
+ # Predict the noise and the denoised image
119
+ pred = x * alphas[i] - v * sigmas[i]
120
+ eps = x * sigmas[i] + v * alphas[i]
121
+
122
+ # If we are not on the last timestep, compute the noisy image for the
123
+ # next timestep.
124
+ if i < steps - 1:
125
+ # If eta > 0, adjust the scaling factor for the predicted noise
126
+ # downward according to the amount of additional noise to add
127
+ ddim_sigma = eta * (sigmas[i + 1]**2 / sigmas[i]**2).sqrt() * \
128
+ (1 - alphas[i]**2 / alphas[i + 1]**2).sqrt()
129
+ adjusted_sigma = (sigmas[i + 1]**2 - ddim_sigma**2).sqrt()
130
+
131
+ # Recombine the predicted noise and predicted denoised image in the
132
+ # correct proportions for the next step
133
+ x = pred * alphas[i + 1] + eps * adjusted_sigma
134
+
135
+ # Add the correct amount of fresh noise
136
+ if eta:
137
+ x += torch.randn_like(x) * ddim_sigma
138
+
139
+ # If we are on the last timestep, output the denoised image
140
+ return pred
141
+
142
+ # Soft mask inpainting is just shrinking hard (binary) mask inpainting
143
+ # Given a float-valued soft mask (values between 0 and 1), get the binary mask for this particular step
144
+ def get_bmask(i, steps, mask):
145
+ strength = (i+1)/(steps)
146
+ # convert to binary mask
147
+ bmask = torch.where(mask<=strength,1,0)
148
+ return bmask
149
+
150
+ def make_cond_model_fn(model, cond_fn):
151
+ def cond_model_fn(x, sigma, **kwargs):
152
+ with torch.enable_grad():
153
+ x = x.detach().requires_grad_()
154
+ denoised = model(x, sigma, **kwargs)
155
+ cond_grad = cond_fn(x, sigma, denoised=denoised, **kwargs).detach()
156
+ cond_denoised = denoised.detach() + cond_grad * K.utils.append_dims(sigma**2, x.ndim)
157
+ return cond_denoised
158
+ return cond_model_fn
159
+
160
+ # Uses k-diffusion from https://github.com/crowsonkb/k-diffusion
161
+ # init_data is init_audio as latents (if this is latent diffusion)
162
+ # For sampling, set both init_data and mask to None
163
+ # For variations, set init_data
164
+ # For inpainting, set both init_data & mask
165
+ def sample_k(
166
+ model_fn,
167
+ noise,
168
+ init_data=None,
169
+ mask=None,
170
+ steps=100,
171
+ sampler_type="dpmpp-2m-sde",
172
+ sigma_min=0.5,
173
+ sigma_max=50,
174
+ rho=1.0, device="cuda",
175
+ callback=None,
176
+ cond_fn=None,
177
+ **extra_args
178
+ ):
179
+
180
+ denoiser = K.external.VDenoiser(model_fn)
181
+
182
+ if cond_fn is not None:
183
+ denoiser = make_cond_model_fn(denoiser, cond_fn)
184
+
185
+ # Make the list of sigmas. Sigma values are scalars related to the amount of noise each denoising step has
186
+ sigmas = K.sampling.get_sigmas_polyexponential(steps, sigma_min, sigma_max, rho, device=device)
187
+ # Scale the initial noise by sigma
188
+ noise = noise * sigmas[0]
189
+
190
+ wrapped_callback = callback
191
+
192
+ if mask is None and init_data is not None:
193
+ # VARIATION (no inpainting)
194
+ # set the initial latent to the init_data, and noise it with initial sigma
195
+ x = init_data + noise
196
+ elif mask is not None and init_data is not None:
197
+ # INPAINTING
198
+ bmask = get_bmask(0, steps, mask)
199
+ # initial noising
200
+ input_noised = init_data + noise
201
+ # set the initial latent to a mix of init_data and noise, based on step 0's binary mask
202
+ x = input_noised * bmask + noise * (1-bmask)
203
+ # define the inpainting callback function (Note: side effects, it mutates x)
204
+ # See https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/sampling.py#L596C13-L596C105
205
+ # callback({'x': x, 'i': i, 'sigma': sigmas[i], 'sigma_hat': sigmas[i], 'denoised': denoised})
206
+ # This is called immediately after `denoised = model(x, sigmas[i] * s_in, **extra_args)`
207
+ def inpainting_callback(args):
208
+ i = args["i"]
209
+ x = args["x"]
210
+ sigma = args["sigma"]
211
+ #denoised = args["denoised"]
212
+ # noise the init_data input with this step's appropriate amount of noise
213
+ input_noised = init_data + torch.randn_like(init_data) * sigma
214
+ # shrinking hard mask
215
+ bmask = get_bmask(i, steps, mask)
216
+ # mix input_noise with x, using binary mask
217
+ new_x = input_noised * bmask + x * (1-bmask)
218
+ # mutate x
219
+ x[:,:,:] = new_x[:,:,:]
220
+ # wrap together the inpainting callback and the user-submitted callback.
221
+ if callback is None:
222
+ wrapped_callback = inpainting_callback
223
+ else:
224
+ wrapped_callback = lambda args: (inpainting_callback(args), callback(args))
225
+ else:
226
+ # SAMPLING
227
+ # set the initial latent to noise
228
+ x = noise
229
+
230
+
231
+ with torch.cuda.amp.autocast():
232
+ if sampler_type == "k-heun":
233
+ return K.sampling.sample_heun(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args)
234
+ elif sampler_type == "k-lms":
235
+ return K.sampling.sample_lms(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args)
236
+ elif sampler_type == "k-dpmpp-2s-ancestral":
237
+ return K.sampling.sample_dpmpp_2s_ancestral(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args)
238
+ elif sampler_type == "k-dpm-2":
239
+ return K.sampling.sample_dpm_2(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args)
240
+ elif sampler_type == "k-dpm-fast":
241
+ return K.sampling.sample_dpm_fast(denoiser, x, sigma_min, sigma_max, steps, disable=False, callback=wrapped_callback, extra_args=extra_args)
242
+ elif sampler_type == "k-dpm-adaptive":
243
+ return K.sampling.sample_dpm_adaptive(denoiser, x, sigma_min, sigma_max, rtol=0.01, atol=0.01, disable=False, callback=wrapped_callback, extra_args=extra_args)
244
+ elif sampler_type == "dpmpp-2m-sde":
245
+ return K.sampling.sample_dpmpp_2m_sde(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args)
246
+ elif sampler_type == "dpmpp-3m-sde":
247
+ return K.sampling.sample_dpmpp_3m_sde(denoiser, x, sigmas, disable=False, callback=wrapped_callback, extra_args=extra_args)
248
+
249
+ # Uses discrete Euler sampling for rectified flow models
250
+ # init_data is init_audio as latents (if this is latent diffusion)
251
+ # For sampling, set both init_data and mask to None
252
+ # For variations, set init_data
253
+ # For inpainting, set both init_data & mask
254
+ def sample_rf(
255
+ model_fn,
256
+ noise,
257
+ init_data=None,
258
+ steps=100,
259
+ sigma_max=1,
260
+ device="cuda",
261
+ callback=None,
262
+ cond_fn=None,
263
+ **extra_args
264
+ ):
265
+
266
+ if sigma_max > 1:
267
+ sigma_max = 1
268
+
269
+ if cond_fn is not None:
270
+ denoiser = make_cond_model_fn(denoiser, cond_fn)
271
+
272
+ wrapped_callback = callback
273
+
274
+ if init_data is not None:
275
+ # VARIATION (no inpainting)
276
+ # Interpolate the init data and the noise for init audio
277
+ x = init_data * (1 - sigma_max) + noise * sigma_max
278
+ else:
279
+ # SAMPLING
280
+ # set the initial latent to noise
281
+ x = noise
282
+
283
+ with torch.cuda.amp.autocast():
284
+ # TODO: Add callback support
285
+ #return sample_discrete_euler(model_fn, x, steps, sigma_max, callback=wrapped_callback, **extra_args)
286
+ return sample_discrete_euler(model_fn, x, steps, sigma_max, **extra_args)
ThinkSound/inference/utils.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..data.utils import PadCrop
2
+
3
+ from torchaudio import transforms as T
4
+
5
+ def set_audio_channels(audio, target_channels):
6
+ if target_channels == 1:
7
+ # Convert to mono
8
+ audio = audio.mean(1, keepdim=True)
9
+ elif target_channels == 2:
10
+ # Convert to stereo
11
+ if audio.shape[1] == 1:
12
+ audio = audio.repeat(1, 2, 1)
13
+ elif audio.shape[1] > 2:
14
+ audio = audio[:, :2, :]
15
+ return audio
16
+
17
+ def prepare_audio(audio, in_sr, target_sr, target_length, target_channels, device):
18
+
19
+ audio = audio.to(device)
20
+
21
+ if in_sr != target_sr:
22
+ resample_tf = T.Resample(in_sr, target_sr).to(device)
23
+ audio = resample_tf(audio)
24
+
25
+ audio = PadCrop(target_length, randomize=False)(audio)
26
+
27
+ # Add batch dimension
28
+ if audio.dim() == 1:
29
+ audio = audio.unsqueeze(0).unsqueeze(0)
30
+ elif audio.dim() == 2:
31
+ audio = audio.unsqueeze(0)
32
+
33
+ audio = set_audio_channels(audio, target_channels)
34
+
35
+ return audio
ThinkSound/interface/__init__.py ADDED
File without changes
ThinkSound/interface/aeiou.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://github.com/drscotthawley/aeiou/blob/main/aeiou/viz.py under Apache 2.0 License
2
+ # License can be found in LICENSES/LICENSE_AEIOU.txt
3
+
4
+ from matplotlib.backends.backend_agg import FigureCanvasAgg
5
+ import matplotlib.cm as cm
6
+ from matplotlib.colors import Normalize
7
+ from matplotlib.figure import Figure
8
+ import numpy as np
9
+ from PIL import Image
10
+
11
+ import torch
12
+
13
+ import torchaudio.transforms as T
14
+ from einops import rearrange
15
+
16
+ import numpy as np
17
+
18
+ def embeddings_table(tokens):
19
+ from wandb import Table
20
+ from pandas import DataFrame
21
+
22
+ "make a table of embeddings for use with wandb"
23
+ features, labels = [], []
24
+ embeddings = rearrange(tokens, 'b d n -> b n d') # each demo sample is n vectors in d-dim space
25
+ for i in range(embeddings.size()[0]): # nested for's are slow but sure ;-)
26
+ for j in range(embeddings.size()[1]):
27
+ features.append(embeddings[i,j].detach().cpu().numpy())
28
+ labels.append([f'demo{i}']) # labels does the grouping / color for each point
29
+ features = np.array(features)
30
+ labels = np.concatenate(labels, axis=0)
31
+ cols = [f"dim_{i}" for i in range(features.shape[1])]
32
+ df = DataFrame(features, columns=cols)
33
+ df['LABEL'] = labels
34
+ return Table(columns=df.columns.to_list(), data=df.values)
35
+
36
+ def project_down(tokens, # batched high-dimensional data with dims (b,d,n)
37
+ proj_dims=3, # dimensions to project to
38
+ method='pca', # projection method: 'pca'|'umap'
39
+ n_neighbors=10, # umap parameter for number of neighbors
40
+ min_dist=0.3, # umap param for minimum distance
41
+ debug=False, # print more info while running
42
+ **kwargs, # other params to pass to umap, cf. https://umap-learn.readthedocs.io/en/latest/parameters.html
43
+ ):
44
+ "this projects to lower dimenions, grabbing the first _`proj_dims`_ dimensions"
45
+ method = method.lower()
46
+ A = rearrange(tokens, 'b d n -> (b n) d') # put all the vectors into the same d-dim space
47
+ if A.shape[-1] > proj_dims:
48
+ if method=='umap':
49
+ from umap import UMAP
50
+ proj_data = UMAP(n_components=proj_dims, n_neighbors=n_neighbors, min_dist=min_dist,
51
+ metric='correlation', **kwargs).fit_transform(A.cpu().numpy())
52
+ proj_data = torch.from_numpy(proj_data).to(tokens.device)
53
+ else: # pca
54
+ (U, S, V) = torch.pca_lowrank(A)
55
+ proj_data = torch.matmul(A, V[:, :proj_dims]) # this is the actual PCA projection step
56
+ else:
57
+ proj_data = A
58
+ if debug: print("proj_data.shape =",proj_data.shape)
59
+ return torch.reshape(proj_data, (tokens.size()[0], -1, proj_dims)) # put it in shape [batch, n, proj_dims]
60
+
61
+
62
+ def proj_pca(tokens, proj_dims=3):
63
+ return project_down(do_proj, method='pca', proj_dims=proj_dims)
64
+
65
+ def point_cloud(
66
+ tokens, # embeddings / latent vectors. shape = (b, d, n)
67
+ method='pca', # projection method for 3d mapping: 'pca' | 'umap'
68
+ color_scheme='batch', # 'batch': group by sample; integer n: n groups, sequentially, otherwise color sequentially by time step
69
+ output_type='wandbobj', # plotly | points | wandbobj. NOTE: WandB can do 'plotly' directly!
70
+ mode='markers', # plotly scatter mode. 'lines+markers' or 'markers'
71
+ size=3, # size of the dots
72
+ line=dict(color='rgba(10,10,10,0.01)'), # if mode='lines+markers', plotly line specifier. cf. https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.scatter3d.html#plotly.graph_objects.scatter3d.Line
73
+ ds_preproj=1, # EXPERIMENTAL: downsampling factor before projecting (1=no downsampling). Could screw up colors
74
+ ds_preplot=1, # EXPERIMENTAL: downsampling factor before plotting (1=no downsampling). Could screw up colors
75
+ debug=False, # print more info
76
+ colormap=None, # valid color map to use, None=defaults
77
+ darkmode=False, # dark background, white fonts
78
+ layout_dict=None, # extra plotly layout options such as camera orientation
79
+ rgb_float = False, # if True, color_scheme is RGB float values
80
+ **kwargs, # anything else to pass along
81
+ ):
82
+ "returns a 3D point cloud of the tokens"
83
+ if ds_preproj != 1:
84
+ tokens = tokens[torch.randperm(tokens.size()[0])] # EXPERIMENTAL: to 'correct' for possible weird effects of downsampling
85
+ tokens = tokens[::ds_preproj]
86
+ if debug: print("tokens.shape =",tokens.shape)
87
+
88
+ data = project_down(tokens, method=method, debug=debug, **kwargs).cpu().numpy()
89
+ if debug: print("data.shape =",data.shape)
90
+ if data.shape[-1] < 3: # for data less than 3D, embed it in 3D
91
+ data = np.pad(data, ((0,0),(0,0),(0, 3-data.shape[-1])), mode='constant', constant_values=0)
92
+
93
+ bytime = False
94
+ points = []
95
+ if color_scheme=='batch': # all dots in same batch index same color, each batch-index unique (almost)
96
+ ncolors = data.shape[0]
97
+ cmap, norm = cm.tab20, Normalize(vmin=0, vmax=ncolors)
98
+ elif isinstance(color_scheme, int) or color_scheme.isnumeric(): # n groups, by batch-indices, sequentially
99
+ ncolors = int(color_scheme)
100
+ cmap, norm = cm.tab20, Normalize(vmin=0, vmax=ncolors)
101
+ else: # time steps match up
102
+ bytime, ncolors = True, data.shape[1]
103
+ cmap, norm = cm.viridis, Normalize(vmin=0, vmax=ncolors)
104
+
105
+ cmap = cmap if colormap is None else colormap # overwrite default cmap with user choice if given
106
+
107
+ points = []
108
+ for bi in range(data.shape[0]): # batch index
109
+ if color_scheme=='batch':
110
+ [r, g, b, _] = [int(255*x) for x in cmap(norm(bi+1))]
111
+ elif isinstance(color_scheme, int) or color_scheme.isnumeric():
112
+ grouplen = data.shape[0]//(ncolors)
113
+ #if debug: print(f"bi, grouplen, bi//grouplen = ",bi, grouplen, bi//grouplen)
114
+ [r, g, b, _] = [int(255*x) for x in cmap(norm(bi//grouplen))]
115
+ #if debug: print("r,g,b = ",r,g,b)
116
+
117
+ if rgb_float: [r, g, b] = [x/255 for x in [r, g, b]]
118
+
119
+ for n in range(data.shape[1]): # across time
120
+ if bytime: [r, g, b, _] = [int(255*x) for x in cmap(norm(n))]
121
+ points.append([data[bi,n,0], data[bi,n,1], data[bi,n,2], r, g, b]) # include dot colors with point coordinates
122
+
123
+ point_cloud = np.array(points)
124
+
125
+ if output_type == 'points':
126
+ return point_cloud
127
+ elif output_type =='plotly':
128
+ import plotly.graph_objects as go
129
+
130
+ fig = go.Figure(data=[go.Scatter3d(
131
+ x=point_cloud[::ds_preplot,0], y=point_cloud[::ds_preplot,1], z=point_cloud[::ds_preplot,2],
132
+ marker=dict(size=size, color=point_cloud[:,3:6]),
133
+ mode=mode,
134
+ # show batch index and time index in tooltips:
135
+ text=[ f'bi: {i*ds_preplot}, ti: {j}' for i in range(data.shape[0]//ds_preplot) for j in range(data.shape[1]) ],
136
+ line=line,
137
+ )])
138
+ fig.update_layout(margin=dict(l=0, r=0, b=0, t=0)) # tight layout
139
+ if darkmode:
140
+ fig.layout.template = 'plotly_dark'
141
+ if isinstance(darkmode, str): # 'rgb(12,15,24)'gradio margins in dark mode
142
+ fig.update_layout( paper_bgcolor=darkmode)
143
+ if layout_dict:
144
+ fig.update_layout( **layout_dict )
145
+
146
+ if debug: print("point_cloud: fig made. returning")
147
+ return fig
148
+ else:
149
+ from wandb import Object3D
150
+ return Object3D(point_cloud)
151
+
152
+ def pca_point_cloud(
153
+ tokens, # embeddings / latent vectors. shape = (b, d, n)
154
+ color_scheme='batch', # 'batch': group by sample, otherwise color sequentially
155
+ output_type='wandbobj', # plotly | points | wandbobj. NOTE: WandB can do 'plotly' directly!
156
+ mode='markers', # plotly scatter mode. 'lines+markers' or 'markers'
157
+ size=3, # size of the dots
158
+ line=dict(color='rgba(10,10,10,0.01)'), # if mode='lines+markers', plotly line specifier. cf. https://plotly.github.io/plotly.py-docs/generated/plotly.graph_objects.scatter3d.html#plotly.graph_objects.scatter3d.Line
159
+ **kwargs,
160
+ ):
161
+ return point_cloud(tokens, method='pca', color_scheme=color_scheme, output_type=output_type,
162
+ mode=mode, size=size, line=line, **kwargs)
163
+
164
+ def power_to_db(spec, *, amin = 1e-10):
165
+ magnitude = np.asarray(spec)
166
+
167
+ log_spec = 10.0 * np.log10(np.maximum(amin, magnitude))
168
+ log_spec -= 10.0 * np.log10(np.maximum(amin, 1))
169
+
170
+ log_spec = np.maximum(log_spec, log_spec.max() - 80)
171
+
172
+ return log_spec
173
+
174
+ def mel_spectrogram(waveform, power=2.0, sample_rate=48000, db=False, n_fft=1024, n_mels=128, debug=False):
175
+ "calculates data array for mel spectrogram (in however many channels)"
176
+ win_length = None
177
+ hop_length = n_fft//2 # 512
178
+
179
+ mel_spectrogram_op = T.MelSpectrogram(
180
+ sample_rate=sample_rate, n_fft=n_fft, win_length=win_length,
181
+ hop_length=hop_length, center=True, pad_mode="reflect", power=power,
182
+ norm='slaney', onesided=True, n_mels=n_mels, mel_scale="htk")
183
+
184
+ melspec = mel_spectrogram_op(waveform.float())
185
+ if db:
186
+ amp_to_db_op = T.AmplitudeToDB()
187
+ melspec = amp_to_db_op(melspec)
188
+ if debug:
189
+ print_stats(melspec, print=print)
190
+ print(f"torch.max(melspec) = {torch.max(melspec)}")
191
+ print(f"melspec.shape = {melspec.shape}")
192
+ return melspec
193
+
194
+ def spectrogram_image(
195
+ spec,
196
+ title=None,
197
+ ylabel='freq_bin',
198
+ aspect='auto',
199
+ xmax=None,
200
+ db_range=[35,120],
201
+ justimage=False,
202
+ figsize=(5, 4), # size of plot (if justimage==False)
203
+ ):
204
+ "Modified from PyTorch tutorial https://pytorch.org/tutorials/beginner/audio_feature_extractions_tutorial.html"
205
+ fig = Figure(figsize=figsize, dpi=100) if not justimage else Figure(figsize=(4.145, 4.145), dpi=100, tight_layout=True)
206
+ canvas = FigureCanvasAgg(fig)
207
+ axs = fig.add_subplot()
208
+ spec = spec.squeeze()
209
+ im = axs.imshow(power_to_db(spec), origin='lower', aspect=aspect, vmin=db_range[0], vmax=db_range[1])
210
+ if xmax:
211
+ axs.set_xlim((0, xmax))
212
+ if justimage:
213
+ import matplotlib.pyplot as plt
214
+ axs.axis('off')
215
+ plt.tight_layout()
216
+ else:
217
+ axs.set_ylabel(ylabel)
218
+ axs.set_xlabel('frame')
219
+ axs.set_title(title or 'Spectrogram (dB)')
220
+ fig.colorbar(im, ax=axs)
221
+ canvas.draw()
222
+ rgba = np.asarray(canvas.buffer_rgba())
223
+ im = Image.fromarray(rgba)
224
+ if justimage: # remove tiny white border
225
+ b = 15 # border size
226
+ im = im.crop((b,b, im.size[0]-b, im.size[1]-b))
227
+ #print(f"im.size = {im.size}")
228
+ return im
229
+
230
+ def audio_spectrogram_image(waveform, power=2.0, sample_rate=48000, print=print, db=False, db_range=[35,120], justimage=False, log=False, figsize=(5, 4)):
231
+ "Wrapper for calling above two routines at once, does Mel scale; Modified from PyTorch tutorial https://pytorch.org/tutorials/beginner/audio_feature_extractions_tutorial.html"
232
+ melspec = mel_spectrogram(waveform, power=power, db=db, sample_rate=sample_rate, debug=log)
233
+ melspec = melspec[0] # TODO: only left channel for now
234
+ return spectrogram_image(melspec, title="MelSpectrogram", ylabel='mel bins (log freq)', db_range=db_range, justimage=justimage, figsize=figsize)
235
+
236
+ from matplotlib.ticker import AutoLocator
237
+ def tokens_spectrogram_image(
238
+ tokens, # the embeddings themselves (in some diffusion codes these are called 'tokens')
239
+ aspect='auto', # aspect ratio of plot
240
+ title='Embeddings', # title to put on top
241
+ ylabel='index', # label for y axis of plot
242
+ cmap='coolwarm', # colormap to use. (default used to be 'viridis')
243
+ symmetric=True, # make color scale symmetric about zero, i.e. +/- same extremes
244
+ figsize=(8, 4), # matplotlib size of the figure
245
+ dpi=100, # dpi of figure
246
+ mark_batches=False, # separate batches with dividing lines
247
+ debug=False, # print debugging info
248
+ ):
249
+ "for visualizing embeddings in a spectrogram-like way"
250
+ batch_size, dim, samples = tokens.shape
251
+ embeddings = rearrange(tokens, 'b d n -> (b n) d') # expand batches in time
252
+ vmin, vmax = None, None
253
+ if symmetric:
254
+ vmax = torch.abs(embeddings).max()
255
+ vmin = -vmax
256
+
257
+ fig = Figure(figsize=figsize, dpi=dpi)
258
+ canvas = FigureCanvasAgg(fig)
259
+ ax = fig.add_subplot()
260
+ if symmetric:
261
+ subtitle = f'min={embeddings.min():0.4g}, max={embeddings.max():0.4g}'
262
+ ax.set_title(title+'\n')
263
+ ax.text(x=0.435, y=0.9, s=subtitle, fontsize=11, ha="center", transform=fig.transFigure)
264
+ else:
265
+ ax.set_title(title)
266
+ ax.set_ylabel(ylabel)
267
+ ax.set_xlabel('time frame (samples, in batches)')
268
+ if mark_batches:
269
+ intervals = np.arange(batch_size)*samples
270
+ if debug: print("intervals = ",intervals)
271
+ ax.vlines(intervals, -10, dim+10, color='black', linestyle='dashed', linewidth=1)
272
+
273
+ im = ax.imshow(embeddings.cpu().numpy().T, origin='lower', aspect=aspect, interpolation='none', cmap=cmap, vmin=vmin,vmax=vmax) #.T because numpy is x/y 'backwards'
274
+ fig.colorbar(im, ax=ax)
275
+ fig.tight_layout()
276
+ canvas.draw()
277
+ rgba = np.asarray(canvas.buffer_rgba())
278
+ return Image.fromarray(rgba)
ThinkSound/interface/gradio.py ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import platform
3
+
4
+ import numpy as np
5
+ import gradio as gr
6
+ import json
7
+ import torch
8
+ import torchaudio
9
+
10
+ from aeiou.viz import audio_spectrogram_image
11
+ from einops import rearrange
12
+ from safetensors.torch import load_file
13
+ from torch.nn import functional as F
14
+ from torchaudio import transforms as T
15
+
16
+ from ..inference.generation import generate_diffusion_cond, generate_diffusion_uncond
17
+ from ..models.factory import create_model_from_config
18
+ from ..models.pretrained import get_pretrained_model
19
+ from ..models.utils import load_ckpt_state_dict
20
+ from ..inference.utils import prepare_audio
21
+ from ..training.utils import copy_state_dict
22
+
23
+ model = None
24
+ sample_rate = 32000
25
+ sample_size = 1920000
26
+
27
+ def load_model(model_config=None, model_ckpt_path=None, pretrained_name=None, pretransform_ckpt_path=None, device="cuda", model_half=False):
28
+ global model, sample_rate, sample_size
29
+
30
+ if pretrained_name is not None:
31
+ print(f"Loading pretrained model {pretrained_name}")
32
+ model, model_config = get_pretrained_model(pretrained_name)
33
+
34
+ elif model_config is not None and model_ckpt_path is not None:
35
+ print(f"Creating model from config")
36
+ model = create_model_from_config(model_config)
37
+
38
+ print(f"Loading model checkpoint from {model_ckpt_path}")
39
+ # Load checkpoint
40
+ copy_state_dict(model, load_ckpt_state_dict(model_ckpt_path))
41
+ #model.load_state_dict(load_ckpt_state_dict(model_ckpt_path))
42
+
43
+ sample_rate = model_config["sample_rate"]
44
+ sample_size = model_config["sample_size"]
45
+
46
+ if pretransform_ckpt_path is not None:
47
+ print(f"Loading pretransform checkpoint from {pretransform_ckpt_path}")
48
+ model.pretransform.load_state_dict(load_ckpt_state_dict(pretransform_ckpt_path), strict=False)
49
+ print(f"Done loading pretransform")
50
+
51
+ model.to(device).eval().requires_grad_(False)
52
+
53
+ if model_half:
54
+ model.to(torch.float16)
55
+
56
+ print(f"Done loading model")
57
+
58
+ return model, model_config
59
+
60
+ def generate_cond(
61
+ prompt,
62
+ negative_prompt=None,
63
+ seconds_start=0,
64
+ seconds_total=30,
65
+ cfg_scale=6.0,
66
+ steps=250,
67
+ preview_every=None,
68
+ seed=-1,
69
+ sampler_type="dpmpp-3m-sde",
70
+ sigma_min=0.03,
71
+ sigma_max=1000,
72
+ cfg_rescale=0.0,
73
+ use_init=False,
74
+ init_audio=None,
75
+ init_noise_level=1.0,
76
+ mask_cropfrom=None,
77
+ mask_pastefrom=None,
78
+ mask_pasteto=None,
79
+ mask_maskstart=None,
80
+ mask_maskend=None,
81
+ mask_softnessL=None,
82
+ mask_softnessR=None,
83
+ mask_marination=None,
84
+ batch_size=1
85
+ ):
86
+
87
+ if torch.cuda.is_available():
88
+ torch.cuda.empty_cache()
89
+ gc.collect()
90
+
91
+ print(f"Prompt: {prompt}")
92
+
93
+ global preview_images
94
+ preview_images = []
95
+ if preview_every == 0:
96
+ preview_every = None
97
+
98
+ # Return fake stereo audio
99
+ conditioning = [{"prompt": prompt, "seconds_start": seconds_start, "seconds_total": seconds_total}] * batch_size
100
+
101
+ if negative_prompt:
102
+ negative_conditioning = [{"prompt": negative_prompt, "seconds_start": seconds_start, "seconds_total": seconds_total}] * batch_size
103
+ else:
104
+ negative_conditioning = None
105
+
106
+ #Get the device from the model
107
+ device = next(model.parameters()).device
108
+
109
+ seed = int(seed)
110
+
111
+ if not use_init:
112
+ init_audio = None
113
+
114
+ input_sample_size = sample_size
115
+
116
+ if init_audio is not None:
117
+ in_sr, init_audio = init_audio
118
+ # Turn into torch tensor, converting from int16 to float32
119
+ init_audio = torch.from_numpy(init_audio).float().div(32767)
120
+
121
+ if init_audio.dim() == 1:
122
+ init_audio = init_audio.unsqueeze(0) # [1, n]
123
+ elif init_audio.dim() == 2:
124
+ init_audio = init_audio.transpose(0, 1) # [n, 2] -> [2, n]
125
+
126
+ if in_sr != sample_rate:
127
+ resample_tf = T.Resample(in_sr, sample_rate).to(init_audio.device)
128
+ init_audio = resample_tf(init_audio)
129
+
130
+ audio_length = init_audio.shape[-1]
131
+
132
+ if audio_length > sample_size:
133
+
134
+ input_sample_size = audio_length + (model.min_input_length - (audio_length % model.min_input_length)) % model.min_input_length
135
+
136
+ init_audio = (sample_rate, init_audio)
137
+
138
+ def progress_callback(callback_info):
139
+ global preview_images
140
+ denoised = callback_info["denoised"]
141
+ current_step = callback_info["i"]
142
+ sigma = callback_info["sigma"]
143
+
144
+ if (current_step - 1) % preview_every == 0:
145
+ if model.pretransform is not None:
146
+ denoised = model.pretransform.decode(denoised)
147
+ denoised = rearrange(denoised, "b d n -> d (b n)")
148
+ denoised = denoised.clamp(-1, 1).mul(32767).to(torch.int16).cpu()
149
+ audio_spectrogram = audio_spectrogram_image(denoised, sample_rate=sample_rate)
150
+ preview_images.append((audio_spectrogram, f"Step {current_step} sigma={sigma:.3f})"))
151
+
152
+ # If inpainting, send mask args
153
+ # This will definitely change in the future
154
+ if mask_cropfrom is not None:
155
+ mask_args = {
156
+ "cropfrom": mask_cropfrom,
157
+ "pastefrom": mask_pastefrom,
158
+ "pasteto": mask_pasteto,
159
+ "maskstart": mask_maskstart,
160
+ "maskend": mask_maskend,
161
+ "softnessL": mask_softnessL,
162
+ "softnessR": mask_softnessR,
163
+ "marination": mask_marination,
164
+ }
165
+ else:
166
+ mask_args = None
167
+
168
+ # Do the audio generation
169
+ audio = generate_diffusion_cond(
170
+ model,
171
+ conditioning=conditioning,
172
+ negative_conditioning=negative_conditioning,
173
+ steps=steps,
174
+ cfg_scale=cfg_scale,
175
+ batch_size=batch_size,
176
+ sample_size=input_sample_size,
177
+ sample_rate=sample_rate,
178
+ seed=seed,
179
+ device=device,
180
+ sampler_type=sampler_type,
181
+ sigma_min=sigma_min,
182
+ sigma_max=sigma_max,
183
+ init_audio=init_audio,
184
+ init_noise_level=init_noise_level,
185
+ mask_args = mask_args,
186
+ callback = progress_callback if preview_every is not None else None,
187
+ scale_phi = cfg_rescale
188
+ )
189
+
190
+ # Convert to WAV file
191
+ audio = rearrange(audio, "b d n -> d (b n)")
192
+ audio = audio.to(torch.float32).div(torch.max(torch.abs(audio))).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
193
+ torchaudio.save("output.wav", audio, sample_rate)
194
+
195
+ # Let's look at a nice spectrogram too
196
+ audio_spectrogram = audio_spectrogram_image(audio, sample_rate=sample_rate)
197
+
198
+ return ("output.wav", [audio_spectrogram, *preview_images])
199
+
200
+ def generate_uncond(
201
+ steps=250,
202
+ seed=-1,
203
+ sampler_type="dpmpp-3m-sde",
204
+ sigma_min=0.03,
205
+ sigma_max=1000,
206
+ use_init=False,
207
+ init_audio=None,
208
+ init_noise_level=1.0,
209
+ batch_size=1,
210
+ preview_every=None
211
+ ):
212
+
213
+ global preview_images
214
+
215
+ preview_images = []
216
+
217
+ if torch.cuda.is_available():
218
+ torch.cuda.empty_cache()
219
+ gc.collect()
220
+
221
+ #Get the device from the model
222
+ device = next(model.parameters()).device
223
+
224
+ seed = int(seed)
225
+
226
+ if not use_init:
227
+ init_audio = None
228
+
229
+ input_sample_size = sample_size
230
+
231
+ if init_audio is not None:
232
+ in_sr, init_audio = init_audio
233
+ # Turn into torch tensor, converting from int16 to float32
234
+ init_audio = torch.from_numpy(init_audio).float().div(32767)
235
+
236
+ if init_audio.dim() == 1:
237
+ init_audio = init_audio.unsqueeze(0) # [1, n]
238
+ elif init_audio.dim() == 2:
239
+ init_audio = init_audio.transpose(0, 1) # [n, 2] -> [2, n]
240
+
241
+ if in_sr != sample_rate:
242
+ resample_tf = T.Resample(in_sr, sample_rate).to(init_audio.device)
243
+ init_audio = resample_tf(init_audio)
244
+
245
+ audio_length = init_audio.shape[-1]
246
+
247
+ if audio_length > sample_size:
248
+
249
+ input_sample_size = audio_length + (model.min_input_length - (audio_length % model.min_input_length)) % model.min_input_length
250
+
251
+ init_audio = (sample_rate, init_audio)
252
+
253
+ def progress_callback(callback_info):
254
+ global preview_images
255
+ denoised = callback_info["denoised"]
256
+ current_step = callback_info["i"]
257
+ sigma = callback_info["sigma"]
258
+
259
+ if (current_step - 1) % preview_every == 0:
260
+
261
+ if model.pretransform is not None:
262
+ denoised = model.pretransform.decode(denoised)
263
+
264
+ denoised = rearrange(denoised, "b d n -> d (b n)")
265
+
266
+ denoised = denoised.clamp(-1, 1).mul(32767).to(torch.int16).cpu()
267
+
268
+ audio_spectrogram = audio_spectrogram_image(denoised, sample_rate=sample_rate)
269
+
270
+ preview_images.append((audio_spectrogram, f"Step {current_step} sigma={sigma:.3f})"))
271
+
272
+ audio = generate_diffusion_uncond(
273
+ model,
274
+ steps=steps,
275
+ batch_size=batch_size,
276
+ sample_size=input_sample_size,
277
+ seed=seed,
278
+ device=device,
279
+ sampler_type=sampler_type,
280
+ sigma_min=sigma_min,
281
+ sigma_max=sigma_max,
282
+ init_audio=init_audio,
283
+ init_noise_level=init_noise_level,
284
+ callback = progress_callback if preview_every is not None else None
285
+ )
286
+
287
+ audio = rearrange(audio, "b d n -> d (b n)")
288
+
289
+ audio = audio.to(torch.float32).div(torch.max(torch.abs(audio))).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
290
+
291
+ torchaudio.save("output.wav", audio, sample_rate)
292
+
293
+ audio_spectrogram = audio_spectrogram_image(audio, sample_rate=sample_rate)
294
+
295
+ return ("output.wav", [audio_spectrogram, *preview_images])
296
+
297
+ def generate_lm(
298
+ temperature=1.0,
299
+ top_p=0.95,
300
+ top_k=0,
301
+ batch_size=1,
302
+ ):
303
+
304
+ if torch.cuda.is_available():
305
+ torch.cuda.empty_cache()
306
+ gc.collect()
307
+
308
+ #Get the device from the model
309
+ device = next(model.parameters()).device
310
+
311
+ audio = model.generate_audio(
312
+ batch_size=batch_size,
313
+ max_gen_len = sample_size//model.pretransform.downsampling_ratio,
314
+ conditioning=None,
315
+ temp=temperature,
316
+ top_p=top_p,
317
+ top_k=top_k,
318
+ use_cache=True
319
+ )
320
+
321
+ audio = rearrange(audio, "b d n -> d (b n)")
322
+
323
+ audio = audio.to(torch.float32).div(torch.max(torch.abs(audio))).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
324
+
325
+ torchaudio.save("output.wav", audio, sample_rate)
326
+
327
+ audio_spectrogram = audio_spectrogram_image(audio, sample_rate=sample_rate)
328
+
329
+ return ("output.wav", [audio_spectrogram])
330
+
331
+
332
+ def create_uncond_sampling_ui(model_config):
333
+ generate_button = gr.Button("Generate", variant='primary', scale=1)
334
+
335
+ with gr.Row(equal_height=False):
336
+ with gr.Column():
337
+ with gr.Row():
338
+ # Steps slider
339
+ steps_slider = gr.Slider(minimum=1, maximum=500, step=1, value=100, label="Steps")
340
+
341
+ with gr.Accordion("Sampler params", open=False):
342
+
343
+ # Seed
344
+ seed_textbox = gr.Textbox(label="Seed (set to -1 for random seed)", value="-1")
345
+
346
+ # Sampler params
347
+ with gr.Row():
348
+ sampler_type_dropdown = gr.Dropdown(["dpmpp-2m-sde", "dpmpp-3m-sde", "k-heun", "k-lms", "k-dpmpp-2s-ancestral", "k-dpm-2", "k-dpm-fast"], label="Sampler type", value="dpmpp-3m-sde")
349
+ sigma_min_slider = gr.Slider(minimum=0.0, maximum=2.0, step=0.01, value=0.03, label="Sigma min")
350
+ sigma_max_slider = gr.Slider(minimum=0.0, maximum=1000.0, step=0.1, value=500, label="Sigma max")
351
+
352
+ with gr.Accordion("Init audio", open=False):
353
+ init_audio_checkbox = gr.Checkbox(label="Use init audio")
354
+ init_audio_input = gr.Audio(label="Init audio")
355
+ init_noise_level_slider = gr.Slider(minimum=0.0, maximum=100.0, step=0.01, value=0.1, label="Init noise level")
356
+
357
+ with gr.Column():
358
+ audio_output = gr.Audio(label="Output audio", interactive=False)
359
+ audio_spectrogram_output = gr.Gallery(label="Output spectrogram", show_label=False)
360
+ send_to_init_button = gr.Button("Send to init audio", scale=1)
361
+ send_to_init_button.click(fn=lambda audio: audio, inputs=[audio_output], outputs=[init_audio_input])
362
+
363
+ generate_button.click(fn=generate_uncond,
364
+ inputs=[
365
+ steps_slider,
366
+ seed_textbox,
367
+ sampler_type_dropdown,
368
+ sigma_min_slider,
369
+ sigma_max_slider,
370
+ init_audio_checkbox,
371
+ init_audio_input,
372
+ init_noise_level_slider,
373
+ ],
374
+ outputs=[
375
+ audio_output,
376
+ audio_spectrogram_output
377
+ ],
378
+ api_name="generate")
379
+
380
+ def create_sampling_ui(model_config, inpainting=False):
381
+ with gr.Row():
382
+ with gr.Column(scale=6):
383
+ prompt = gr.Textbox(show_label=False, placeholder="Prompt")
384
+ negative_prompt = gr.Textbox(show_label=False, placeholder="Negative prompt")
385
+ generate_button = gr.Button("Generate", variant='primary', scale=1)
386
+
387
+ model_conditioning_config = model_config["model"].get("conditioning", None)
388
+
389
+ has_seconds_start = False
390
+ has_seconds_total = False
391
+
392
+ if model_conditioning_config is not None:
393
+ for conditioning_config in model_conditioning_config["configs"]:
394
+ if conditioning_config["id"] == "seconds_start":
395
+ has_seconds_start = True
396
+ if conditioning_config["id"] == "seconds_total":
397
+ has_seconds_total = True
398
+
399
+ with gr.Row(equal_height=False):
400
+ with gr.Column():
401
+ with gr.Row(visible = has_seconds_start or has_seconds_total):
402
+ # Timing controls
403
+ seconds_start_slider = gr.Slider(minimum=0, maximum=512, step=1, value=0, label="Seconds start", visible=has_seconds_start)
404
+ seconds_total_slider = gr.Slider(minimum=0, maximum=512, step=1, value=sample_size//sample_rate, label="Seconds total", visible=has_seconds_total)
405
+
406
+ with gr.Row():
407
+ # Steps slider
408
+ steps_slider = gr.Slider(minimum=1, maximum=500, step=1, value=100, label="Steps")
409
+
410
+ # Preview Every slider
411
+ preview_every_slider = gr.Slider(minimum=0, maximum=100, step=1, value=0, label="Preview Every")
412
+
413
+ # CFG scale
414
+ cfg_scale_slider = gr.Slider(minimum=0.0, maximum=25.0, step=0.1, value=7.0, label="CFG scale")
415
+
416
+ with gr.Accordion("Sampler params", open=False):
417
+
418
+ # Seed
419
+ seed_textbox = gr.Textbox(label="Seed (set to -1 for random seed)", value="-1")
420
+
421
+ # Sampler params
422
+ with gr.Row():
423
+ sampler_type_dropdown = gr.Dropdown(["dpmpp-2m-sde", "dpmpp-3m-sde", "k-heun", "k-lms", "k-dpmpp-2s-ancestral", "k-dpm-2", "k-dpm-fast"], label="Sampler type", value="dpmpp-3m-sde")
424
+ sigma_min_slider = gr.Slider(minimum=0.0, maximum=2.0, step=0.01, value=0.03, label="Sigma min")
425
+ sigma_max_slider = gr.Slider(minimum=0.0, maximum=1000.0, step=0.1, value=500, label="Sigma max")
426
+ cfg_rescale_slider = gr.Slider(minimum=0.0, maximum=1, step=0.01, value=0.0, label="CFG rescale amount")
427
+
428
+ if inpainting:
429
+ # Inpainting Tab
430
+ with gr.Accordion("Inpainting", open=False):
431
+ sigma_max_slider.maximum=1000
432
+
433
+ init_audio_checkbox = gr.Checkbox(label="Do inpainting")
434
+ init_audio_input = gr.Audio(label="Init audio")
435
+ init_noise_level_slider = gr.Slider(minimum=0.1, maximum=100.0, step=0.1, value=80, label="Init audio noise level", visible=False) # hide this
436
+
437
+ mask_cropfrom_slider = gr.Slider(minimum=0.0, maximum=100.0, step=0.1, value=0, label="Crop From %")
438
+ mask_pastefrom_slider = gr.Slider(minimum=0.0, maximum=100.0, step=0.1, value=0, label="Paste From %")
439
+ mask_pasteto_slider = gr.Slider(minimum=0.0, maximum=100.0, step=0.1, value=100, label="Paste To %")
440
+
441
+ mask_maskstart_slider = gr.Slider(minimum=0.0, maximum=100.0, step=0.1, value=50, label="Mask Start %")
442
+ mask_maskend_slider = gr.Slider(minimum=0.0, maximum=100.0, step=0.1, value=100, label="Mask End %")
443
+ mask_softnessL_slider = gr.Slider(minimum=0.0, maximum=100.0, step=0.1, value=0, label="Softmask Left Crossfade Length %")
444
+ mask_softnessR_slider = gr.Slider(minimum=0.0, maximum=100.0, step=0.1, value=0, label="Softmask Right Crossfade Length %")
445
+ mask_marination_slider = gr.Slider(minimum=0.0, maximum=1, step=0.0001, value=0, label="Marination level", visible=False) # still working on the usefulness of this
446
+
447
+ inputs = [prompt,
448
+ negative_prompt,
449
+ seconds_start_slider,
450
+ seconds_total_slider,
451
+ cfg_scale_slider,
452
+ steps_slider,
453
+ preview_every_slider,
454
+ seed_textbox,
455
+ sampler_type_dropdown,
456
+ sigma_min_slider,
457
+ sigma_max_slider,
458
+ cfg_rescale_slider,
459
+ init_audio_checkbox,
460
+ init_audio_input,
461
+ init_noise_level_slider,
462
+ mask_cropfrom_slider,
463
+ mask_pastefrom_slider,
464
+ mask_pasteto_slider,
465
+ mask_maskstart_slider,
466
+ mask_maskend_slider,
467
+ mask_softnessL_slider,
468
+ mask_softnessR_slider,
469
+ mask_marination_slider
470
+ ]
471
+ else:
472
+ # Default generation tab
473
+ with gr.Accordion("Init audio", open=False):
474
+ init_audio_checkbox = gr.Checkbox(label="Use init audio")
475
+ init_audio_input = gr.Audio(label="Init audio")
476
+ init_noise_level_slider = gr.Slider(minimum=0.1, maximum=100.0, step=0.01, value=0.1, label="Init noise level")
477
+
478
+ inputs = [prompt,
479
+ negative_prompt,
480
+ seconds_start_slider,
481
+ seconds_total_slider,
482
+ cfg_scale_slider,
483
+ steps_slider,
484
+ preview_every_slider,
485
+ seed_textbox,
486
+ sampler_type_dropdown,
487
+ sigma_min_slider,
488
+ sigma_max_slider,
489
+ cfg_rescale_slider,
490
+ init_audio_checkbox,
491
+ init_audio_input,
492
+ init_noise_level_slider
493
+ ]
494
+
495
+ with gr.Column():
496
+ audio_output = gr.Audio(label="Output audio", interactive=False)
497
+ audio_spectrogram_output = gr.Gallery(label="Output spectrogram", show_label=False)
498
+ send_to_init_button = gr.Button("Send to init audio", scale=1)
499
+ send_to_init_button.click(fn=lambda audio: audio, inputs=[audio_output], outputs=[init_audio_input])
500
+
501
+ generate_button.click(fn=generate_cond,
502
+ inputs=inputs,
503
+ outputs=[
504
+ audio_output,
505
+ audio_spectrogram_output
506
+ ],
507
+ api_name="generate")
508
+
509
+
510
+ def create_txt2audio_ui(model_config):
511
+ with gr.Blocks() as ui:
512
+ with gr.Tab("Generation"):
513
+ create_sampling_ui(model_config)
514
+ with gr.Tab("Inpainting"):
515
+ create_sampling_ui(model_config, inpainting=True)
516
+ return ui
517
+
518
+ def create_diffusion_uncond_ui(model_config):
519
+ with gr.Blocks() as ui:
520
+ create_uncond_sampling_ui(model_config)
521
+
522
+ return ui
523
+
524
+ def autoencoder_process(audio, latent_noise, n_quantizers):
525
+ if torch.cuda.is_available():
526
+ torch.cuda.empty_cache()
527
+ gc.collect()
528
+
529
+ #Get the device from the model
530
+ device = next(model.parameters()).device
531
+
532
+ in_sr, audio = audio
533
+
534
+ audio = torch.from_numpy(audio).float().div(32767).to(device)
535
+
536
+ if audio.dim() == 1:
537
+ audio = audio.unsqueeze(0)
538
+ else:
539
+ audio = audio.transpose(0, 1)
540
+
541
+ audio = model.preprocess_audio_for_encoder(audio, in_sr)
542
+ # Note: If you need to do chunked encoding, to reduce VRAM,
543
+ # then add these arguments to encode_audio and decode_audio: chunked=True, overlap=32, chunk_size=128
544
+ # To turn it off, do chunked=False
545
+ # Optimal overlap and chunk_size values will depend on the model.
546
+ # See encode_audio & decode_audio in autoencoders.py for more info
547
+ # Get dtype of model
548
+ dtype = next(model.parameters()).dtype
549
+
550
+ audio = audio.to(dtype)
551
+
552
+ if n_quantizers > 0:
553
+ latents = model.encode_audio(audio, chunked=False, n_quantizers=n_quantizers)
554
+ else:
555
+ latents = model.encode_audio(audio, chunked=False)
556
+
557
+ if latent_noise > 0:
558
+ latents = latents + torch.randn_like(latents) * latent_noise
559
+
560
+ audio = model.decode_audio(latents, chunked=False)
561
+
562
+ audio = rearrange(audio, "b d n -> d (b n)")
563
+
564
+ audio = audio.to(torch.float32).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
565
+
566
+ torchaudio.save("output.wav", audio, sample_rate)
567
+
568
+ return "output.wav"
569
+
570
+ def create_autoencoder_ui(model_config):
571
+
572
+ is_dac_rvq = "model" in model_config and "bottleneck" in model_config["model"] and model_config["model"]["bottleneck"]["type"] in ["dac_rvq","dac_rvq_vae"]
573
+
574
+ if is_dac_rvq:
575
+ n_quantizers = model_config["model"]["bottleneck"]["config"]["n_codebooks"]
576
+ else:
577
+ n_quantizers = 0
578
+
579
+ with gr.Blocks() as ui:
580
+ input_audio = gr.Audio(label="Input audio")
581
+ output_audio = gr.Audio(label="Output audio", interactive=False)
582
+ n_quantizers_slider = gr.Slider(minimum=1, maximum=n_quantizers, step=1, value=n_quantizers, label="# quantizers", visible=is_dac_rvq)
583
+ latent_noise_slider = gr.Slider(minimum=0.0, maximum=10.0, step=0.001, value=0.0, label="Add latent noise")
584
+ process_button = gr.Button("Process", variant='primary', scale=1)
585
+ process_button.click(fn=autoencoder_process, inputs=[input_audio, latent_noise_slider, n_quantizers_slider], outputs=output_audio, api_name="process")
586
+
587
+ return ui
588
+
589
+ def diffusion_prior_process(audio, steps, sampler_type, sigma_min, sigma_max):
590
+
591
+ if torch.cuda.is_available():
592
+ torch.cuda.empty_cache()
593
+ gc.collect()
594
+
595
+ #Get the device from the model
596
+ device = next(model.parameters()).device
597
+
598
+ in_sr, audio = audio
599
+
600
+ audio = torch.from_numpy(audio).float().div(32767).to(device)
601
+
602
+ if audio.dim() == 1:
603
+ audio = audio.unsqueeze(0) # [1, n]
604
+ elif audio.dim() == 2:
605
+ audio = audio.transpose(0, 1) # [n, 2] -> [2, n]
606
+
607
+ audio = audio.unsqueeze(0)
608
+
609
+ audio = model.stereoize(audio, in_sr, steps, sampler_kwargs={"sampler_type": sampler_type, "sigma_min": sigma_min, "sigma_max": sigma_max})
610
+
611
+ audio = rearrange(audio, "b d n -> d (b n)")
612
+
613
+ audio = audio.to(torch.float32).div(torch.max(torch.abs(audio))).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
614
+
615
+ torchaudio.save("output.wav", audio, sample_rate)
616
+
617
+ return "output.wav"
618
+
619
+ def create_diffusion_prior_ui(model_config):
620
+ with gr.Blocks() as ui:
621
+ input_audio = gr.Audio(label="Input audio")
622
+ output_audio = gr.Audio(label="Output audio", interactive=False)
623
+ # Sampler params
624
+ with gr.Row():
625
+ steps_slider = gr.Slider(minimum=1, maximum=500, step=1, value=100, label="Steps")
626
+ sampler_type_dropdown = gr.Dropdown(["dpmpp-2m-sde", "dpmpp-3m-sde", "k-heun", "k-lms", "k-dpmpp-2s-ancestral", "k-dpm-2", "k-dpm-fast"], label="Sampler type", value="dpmpp-3m-sde")
627
+ sigma_min_slider = gr.Slider(minimum=0.0, maximum=2.0, step=0.01, value=0.03, label="Sigma min")
628
+ sigma_max_slider = gr.Slider(minimum=0.0, maximum=1000.0, step=0.1, value=500, label="Sigma max")
629
+ process_button = gr.Button("Process", variant='primary', scale=1)
630
+ process_button.click(fn=diffusion_prior_process, inputs=[input_audio, steps_slider, sampler_type_dropdown, sigma_min_slider, sigma_max_slider], outputs=output_audio, api_name="process")
631
+
632
+ return ui
633
+
634
+ def create_lm_ui(model_config):
635
+ with gr.Blocks() as ui:
636
+ output_audio = gr.Audio(label="Output audio", interactive=False)
637
+ audio_spectrogram_output = gr.Gallery(label="Output spectrogram", show_label=False)
638
+
639
+ # Sampling params
640
+ with gr.Row():
641
+ temperature_slider = gr.Slider(minimum=0, maximum=5, step=0.01, value=1.0, label="Temperature")
642
+ top_p_slider = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.95, label="Top p")
643
+ top_k_slider = gr.Slider(minimum=0, maximum=100, step=1, value=0, label="Top k")
644
+
645
+ generate_button = gr.Button("Generate", variant='primary', scale=1)
646
+ generate_button.click(
647
+ fn=generate_lm,
648
+ inputs=[
649
+ temperature_slider,
650
+ top_p_slider,
651
+ top_k_slider
652
+ ],
653
+ outputs=[output_audio, audio_spectrogram_output],
654
+ api_name="generate"
655
+ )
656
+
657
+ return ui
658
+
659
+ def create_ui(model_config_path=None, ckpt_path=None, pretrained_name=None, pretransform_ckpt_path=None, model_half=False):
660
+
661
+ assert (pretrained_name is not None) ^ (model_config_path is not None and ckpt_path is not None), "Must specify either pretrained name or provide a model config and checkpoint, but not both"
662
+
663
+ if model_config_path is not None:
664
+ # Load config from json file
665
+ with open(model_config_path) as f:
666
+ model_config = json.load(f)
667
+ else:
668
+ model_config = None
669
+
670
+ try:
671
+ has_mps = platform.system() == "Darwin" and torch.backends.mps.is_available()
672
+ except Exception:
673
+ # In case this version of Torch doesn't even have `torch.backends.mps`...
674
+ has_mps = False
675
+
676
+ if has_mps:
677
+ device = torch.device("mps")
678
+ elif torch.cuda.is_available():
679
+ device = torch.device("cuda")
680
+ else:
681
+ device = torch.device("cpu")
682
+
683
+ print("Using device:", device)
684
+
685
+ _, model_config = load_model(model_config, ckpt_path, pretrained_name=pretrained_name, pretransform_ckpt_path=pretransform_ckpt_path, model_half=model_half, device=device)
686
+
687
+ model_type = model_config["model_type"]
688
+
689
+ if model_type == "diffusion_cond":
690
+ ui = create_txt2audio_ui(model_config)
691
+ elif model_type == "diffusion_uncond":
692
+ ui = create_diffusion_uncond_ui(model_config)
693
+ elif model_type == "autoencoder" or model_type == "diffusion_autoencoder":
694
+ ui = create_autoencoder_ui(model_config)
695
+ elif model_type == "diffusion_prior":
696
+ ui = create_diffusion_prior_ui(model_config)
697
+ elif model_type == "lm":
698
+ ui = create_lm_ui(model_config)
699
+
700
+ return ui
ThinkSound/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .factory import create_model_from_config, create_model_from_config_path
ThinkSound/models/adp.py ADDED
@@ -0,0 +1,1588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied and modified from https://github.com/archinetai/audio-diffusion-pytorch/blob/v0.0.94/audio_diffusion_pytorch/modules.py under MIT License
2
+ # License can be found in LICENSES/LICENSE_ADP.txt
3
+
4
+ import math
5
+ from inspect import isfunction
6
+ from math import ceil, floor, log, pi, log2
7
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, TypeVar, Union
8
+ from packaging import version
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from einops import rearrange, reduce, repeat
13
+ from einops.layers.torch import Rearrange
14
+ from einops_exts import rearrange_many
15
+ from torch import Tensor, einsum
16
+ from torch.backends.cuda import sdp_kernel
17
+ from torch.nn import functional as F
18
+ from dac.nn.layers import Snake1d
19
+
20
+ """
21
+ Utils
22
+ """
23
+
24
+
25
+ class ConditionedSequential(nn.Module):
26
+ def __init__(self, *modules):
27
+ super().__init__()
28
+ self.module_list = nn.ModuleList(*modules)
29
+
30
+ def forward(self, x: Tensor, mapping: Optional[Tensor] = None):
31
+ for module in self.module_list:
32
+ x = module(x, mapping)
33
+ return x
34
+
35
+ T = TypeVar("T")
36
+
37
+ def default(val: Optional[T], d: Union[Callable[..., T], T]) -> T:
38
+ if exists(val):
39
+ return val
40
+ return d() if isfunction(d) else d
41
+
42
+ def exists(val: Optional[T]) -> T:
43
+ return val is not None
44
+
45
+ def closest_power_2(x: float) -> int:
46
+ exponent = log2(x)
47
+ distance_fn = lambda z: abs(x - 2 ** z) # noqa
48
+ exponent_closest = min((floor(exponent), ceil(exponent)), key=distance_fn)
49
+ return 2 ** int(exponent_closest)
50
+
51
+ def group_dict_by_prefix(prefix: str, d: Dict) -> Tuple[Dict, Dict]:
52
+ return_dicts: Tuple[Dict, Dict] = ({}, {})
53
+ for key in d.keys():
54
+ no_prefix = int(not key.startswith(prefix))
55
+ return_dicts[no_prefix][key] = d[key]
56
+ return return_dicts
57
+
58
+ def groupby(prefix: str, d: Dict, keep_prefix: bool = False) -> Tuple[Dict, Dict]:
59
+ kwargs_with_prefix, kwargs = group_dict_by_prefix(prefix, d)
60
+ if keep_prefix:
61
+ return kwargs_with_prefix, kwargs
62
+ kwargs_no_prefix = {k[len(prefix) :]: v for k, v in kwargs_with_prefix.items()}
63
+ return kwargs_no_prefix, kwargs
64
+
65
+ """
66
+ Convolutional Blocks
67
+ """
68
+ import typing as tp
69
+
70
+ # Copied from https://github.com/facebookresearch/audiocraft/blob/main/audiocraft/modules/conv.py under MIT License
71
+ # License available in LICENSES/LICENSE_META.txt
72
+
73
+ def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int,
74
+ padding_total: int = 0) -> int:
75
+ """See `pad_for_conv1d`."""
76
+ length = x.shape[-1]
77
+ n_frames = (length - kernel_size + padding_total) / stride + 1
78
+ ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
79
+ return ideal_length - length
80
+
81
+
82
+ def pad_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int, padding_total: int = 0):
83
+ """Pad for a convolution to make sure that the last window is full.
84
+ Extra padding is added at the end. This is required to ensure that we can rebuild
85
+ an output of the same length, as otherwise, even with padding, some time steps
86
+ might get removed.
87
+ For instance, with total padding = 4, kernel size = 4, stride = 2:
88
+ 0 0 1 2 3 4 5 0 0 # (0s are padding)
89
+ 1 2 3 # (output frames of a convolution, last 0 is never used)
90
+ 0 0 1 2 3 4 5 0 # (output of tr. conv., but pos. 5 is going to get removed as padding)
91
+ 1 2 3 4 # once you removed padding, we are missing one time step !
92
+ """
93
+ extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total)
94
+ return F.pad(x, (0, extra_padding))
95
+
96
+
97
+ def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = 'constant', value: float = 0.):
98
+ """Tiny wrapper around F.pad, just to allow for reflect padding on small input.
99
+ If this is the case, we insert extra 0 padding to the right before the reflection happen.
100
+ """
101
+ length = x.shape[-1]
102
+ padding_left, padding_right = paddings
103
+ assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
104
+ if mode == 'reflect':
105
+ max_pad = max(padding_left, padding_right)
106
+ extra_pad = 0
107
+ if length <= max_pad:
108
+ extra_pad = max_pad - length + 1
109
+ x = F.pad(x, (0, extra_pad))
110
+ padded = F.pad(x, paddings, mode, value)
111
+ end = padded.shape[-1] - extra_pad
112
+ return padded[..., :end]
113
+ else:
114
+ return F.pad(x, paddings, mode, value)
115
+
116
+
117
+ def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]):
118
+ """Remove padding from x, handling properly zero padding. Only for 1d!"""
119
+ padding_left, padding_right = paddings
120
+ assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
121
+ assert (padding_left + padding_right) <= x.shape[-1]
122
+ end = x.shape[-1] - padding_right
123
+ return x[..., padding_left: end]
124
+
125
+
126
+ class Conv1d(nn.Conv1d):
127
+ def __init__(self, *args, **kwargs):
128
+ super().__init__(*args, **kwargs)
129
+
130
+ def forward(self, x: Tensor, causal=False) -> Tensor:
131
+ kernel_size = self.kernel_size[0]
132
+ stride = self.stride[0]
133
+ dilation = self.dilation[0]
134
+ kernel_size = (kernel_size - 1) * dilation + 1 # effective kernel size with dilations
135
+ padding_total = kernel_size - stride
136
+ extra_padding = get_extra_padding_for_conv1d(x, kernel_size, stride, padding_total)
137
+ if causal:
138
+ # Left padding for causal
139
+ x = pad1d(x, (padding_total, extra_padding))
140
+ else:
141
+ # Asymmetric padding required for odd strides
142
+ padding_right = padding_total // 2
143
+ padding_left = padding_total - padding_right
144
+ x = pad1d(x, (padding_left, padding_right + extra_padding))
145
+ return super().forward(x)
146
+
147
+ class ConvTranspose1d(nn.ConvTranspose1d):
148
+ def __init__(self, *args, **kwargs):
149
+ super().__init__(*args, **kwargs)
150
+
151
+ def forward(self, x: Tensor, causal=False) -> Tensor:
152
+ kernel_size = self.kernel_size[0]
153
+ stride = self.stride[0]
154
+ padding_total = kernel_size - stride
155
+
156
+ y = super().forward(x)
157
+
158
+ # We will only trim fixed padding. Extra padding from `pad_for_conv1d` would be
159
+ # removed at the very end, when keeping only the right length for the output,
160
+ # as removing it here would require also passing the length at the matching layer
161
+ # in the encoder.
162
+ if causal:
163
+ padding_right = ceil(padding_total)
164
+ padding_left = padding_total - padding_right
165
+ y = unpad1d(y, (padding_left, padding_right))
166
+ else:
167
+ # Asymmetric padding required for odd strides
168
+ padding_right = padding_total // 2
169
+ padding_left = padding_total - padding_right
170
+ y = unpad1d(y, (padding_left, padding_right))
171
+ return y
172
+
173
+
174
+ def Downsample1d(
175
+ in_channels: int, out_channels: int, factor: int, kernel_multiplier: int = 2
176
+ ) -> nn.Module:
177
+ assert kernel_multiplier % 2 == 0, "Kernel multiplier must be even"
178
+
179
+ return Conv1d(
180
+ in_channels=in_channels,
181
+ out_channels=out_channels,
182
+ kernel_size=factor * kernel_multiplier + 1,
183
+ stride=factor
184
+ )
185
+
186
+
187
+ def Upsample1d(
188
+ in_channels: int, out_channels: int, factor: int, use_nearest: bool = False
189
+ ) -> nn.Module:
190
+
191
+ if factor == 1:
192
+ return Conv1d(
193
+ in_channels=in_channels, out_channels=out_channels, kernel_size=3
194
+ )
195
+
196
+ if use_nearest:
197
+ return nn.Sequential(
198
+ nn.Upsample(scale_factor=factor, mode="nearest"),
199
+ Conv1d(
200
+ in_channels=in_channels,
201
+ out_channels=out_channels,
202
+ kernel_size=3
203
+ ),
204
+ )
205
+ else:
206
+ return ConvTranspose1d(
207
+ in_channels=in_channels,
208
+ out_channels=out_channels,
209
+ kernel_size=factor * 2,
210
+ stride=factor
211
+ )
212
+
213
+
214
+ class ConvBlock1d(nn.Module):
215
+ def __init__(
216
+ self,
217
+ in_channels: int,
218
+ out_channels: int,
219
+ *,
220
+ kernel_size: int = 3,
221
+ stride: int = 1,
222
+ dilation: int = 1,
223
+ num_groups: int = 8,
224
+ use_norm: bool = True,
225
+ use_snake: bool = False
226
+ ) -> None:
227
+ super().__init__()
228
+
229
+ self.groupnorm = (
230
+ nn.GroupNorm(num_groups=num_groups, num_channels=in_channels)
231
+ if use_norm
232
+ else nn.Identity()
233
+ )
234
+
235
+ if use_snake:
236
+ self.activation = Snake1d(in_channels)
237
+ else:
238
+ self.activation = nn.SiLU()
239
+
240
+ self.project = Conv1d(
241
+ in_channels=in_channels,
242
+ out_channels=out_channels,
243
+ kernel_size=kernel_size,
244
+ stride=stride,
245
+ dilation=dilation,
246
+ )
247
+
248
+ def forward(
249
+ self, x: Tensor, scale_shift: Optional[Tuple[Tensor, Tensor]] = None, causal=False
250
+ ) -> Tensor:
251
+ x = self.groupnorm(x)
252
+ if exists(scale_shift):
253
+ scale, shift = scale_shift
254
+ x = x * (scale + 1) + shift
255
+ x = self.activation(x)
256
+ return self.project(x, causal=causal)
257
+
258
+
259
+ class MappingToScaleShift(nn.Module):
260
+ def __init__(
261
+ self,
262
+ features: int,
263
+ channels: int,
264
+ ):
265
+ super().__init__()
266
+
267
+ self.to_scale_shift = nn.Sequential(
268
+ nn.SiLU(),
269
+ nn.Linear(in_features=features, out_features=channels * 2),
270
+ )
271
+
272
+ def forward(self, mapping: Tensor) -> Tuple[Tensor, Tensor]:
273
+ scale_shift = self.to_scale_shift(mapping)
274
+ scale_shift = rearrange(scale_shift, "b c -> b c 1")
275
+ scale, shift = scale_shift.chunk(2, dim=1)
276
+ return scale, shift
277
+
278
+
279
+ class ResnetBlock1d(nn.Module):
280
+ def __init__(
281
+ self,
282
+ in_channels: int,
283
+ out_channels: int,
284
+ *,
285
+ kernel_size: int = 3,
286
+ stride: int = 1,
287
+ dilation: int = 1,
288
+ use_norm: bool = True,
289
+ use_snake: bool = False,
290
+ num_groups: int = 8,
291
+ context_mapping_features: Optional[int] = None,
292
+ ) -> None:
293
+ super().__init__()
294
+
295
+ self.use_mapping = exists(context_mapping_features)
296
+
297
+ self.block1 = ConvBlock1d(
298
+ in_channels=in_channels,
299
+ out_channels=out_channels,
300
+ kernel_size=kernel_size,
301
+ stride=stride,
302
+ dilation=dilation,
303
+ use_norm=use_norm,
304
+ num_groups=num_groups,
305
+ use_snake=use_snake
306
+ )
307
+
308
+ if self.use_mapping:
309
+ assert exists(context_mapping_features)
310
+ self.to_scale_shift = MappingToScaleShift(
311
+ features=context_mapping_features, channels=out_channels
312
+ )
313
+
314
+ self.block2 = ConvBlock1d(
315
+ in_channels=out_channels,
316
+ out_channels=out_channels,
317
+ use_norm=use_norm,
318
+ num_groups=num_groups,
319
+ use_snake=use_snake
320
+ )
321
+
322
+ self.to_out = (
323
+ Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1)
324
+ if in_channels != out_channels
325
+ else nn.Identity()
326
+ )
327
+
328
+ def forward(self, x: Tensor, mapping: Optional[Tensor] = None, causal=False) -> Tensor:
329
+ assert_message = "context mapping required if context_mapping_features > 0"
330
+ assert not (self.use_mapping ^ exists(mapping)), assert_message
331
+
332
+ h = self.block1(x, causal=causal)
333
+
334
+ scale_shift = None
335
+ if self.use_mapping:
336
+ scale_shift = self.to_scale_shift(mapping)
337
+
338
+ h = self.block2(h, scale_shift=scale_shift, causal=causal)
339
+
340
+ return h + self.to_out(x)
341
+
342
+
343
+ class Patcher(nn.Module):
344
+ def __init__(
345
+ self,
346
+ in_channels: int,
347
+ out_channels: int,
348
+ patch_size: int,
349
+ context_mapping_features: Optional[int] = None,
350
+ use_snake: bool = False,
351
+ ):
352
+ super().__init__()
353
+ assert_message = f"out_channels must be divisible by patch_size ({patch_size})"
354
+ assert out_channels % patch_size == 0, assert_message
355
+ self.patch_size = patch_size
356
+
357
+ self.block = ResnetBlock1d(
358
+ in_channels=in_channels,
359
+ out_channels=out_channels // patch_size,
360
+ num_groups=1,
361
+ context_mapping_features=context_mapping_features,
362
+ use_snake=use_snake
363
+ )
364
+
365
+ def forward(self, x: Tensor, mapping: Optional[Tensor] = None, causal=False) -> Tensor:
366
+ x = self.block(x, mapping, causal=causal)
367
+ x = rearrange(x, "b c (l p) -> b (c p) l", p=self.patch_size)
368
+ return x
369
+
370
+
371
+ class Unpatcher(nn.Module):
372
+ def __init__(
373
+ self,
374
+ in_channels: int,
375
+ out_channels: int,
376
+ patch_size: int,
377
+ context_mapping_features: Optional[int] = None,
378
+ use_snake: bool = False
379
+ ):
380
+ super().__init__()
381
+ assert_message = f"in_channels must be divisible by patch_size ({patch_size})"
382
+ assert in_channels % patch_size == 0, assert_message
383
+ self.patch_size = patch_size
384
+
385
+ self.block = ResnetBlock1d(
386
+ in_channels=in_channels // patch_size,
387
+ out_channels=out_channels,
388
+ num_groups=1,
389
+ context_mapping_features=context_mapping_features,
390
+ use_snake=use_snake
391
+ )
392
+
393
+ def forward(self, x: Tensor, mapping: Optional[Tensor] = None, causal=False) -> Tensor:
394
+ x = rearrange(x, " b (c p) l -> b c (l p) ", p=self.patch_size)
395
+ x = self.block(x, mapping, causal=causal)
396
+ return x
397
+
398
+
399
+ """
400
+ Attention Components
401
+ """
402
+ def FeedForward(features: int, multiplier: int) -> nn.Module:
403
+ mid_features = features * multiplier
404
+ return nn.Sequential(
405
+ nn.Linear(in_features=features, out_features=mid_features),
406
+ nn.GELU(),
407
+ nn.Linear(in_features=mid_features, out_features=features),
408
+ )
409
+
410
+ def add_mask(sim: Tensor, mask: Tensor) -> Tensor:
411
+ b, ndim = sim.shape[0], mask.ndim
412
+ if ndim == 3:
413
+ mask = rearrange(mask, "b n m -> b 1 n m")
414
+ if ndim == 2:
415
+ mask = repeat(mask, "n m -> b 1 n m", b=b)
416
+ max_neg_value = -torch.finfo(sim.dtype).max
417
+ sim = sim.masked_fill(~mask, max_neg_value)
418
+ return sim
419
+
420
+ def causal_mask(q: Tensor, k: Tensor) -> Tensor:
421
+ b, i, j, device = q.shape[0], q.shape[-2], k.shape[-2], q.device
422
+ mask = ~torch.ones((i, j), dtype=torch.bool, device=device).triu(j - i + 1)
423
+ mask = repeat(mask, "n m -> b n m", b=b)
424
+ return mask
425
+
426
+ class AttentionBase(nn.Module):
427
+ def __init__(
428
+ self,
429
+ features: int,
430
+ *,
431
+ head_features: int,
432
+ num_heads: int,
433
+ out_features: Optional[int] = None,
434
+ ):
435
+ super().__init__()
436
+ self.scale = head_features**-0.5
437
+ self.num_heads = num_heads
438
+ mid_features = head_features * num_heads
439
+ out_features = default(out_features, features)
440
+
441
+ self.to_out = nn.Linear(
442
+ in_features=mid_features, out_features=out_features
443
+ )
444
+
445
+ self.use_flash = torch.cuda.is_available() and version.parse(torch.__version__) >= version.parse('2.0.0')
446
+
447
+ if not self.use_flash:
448
+ return
449
+
450
+ device_properties = torch.cuda.get_device_properties(torch.device('cuda'))
451
+
452
+ if device_properties.major == 8 and device_properties.minor == 0:
453
+ # Use flash attention for A100 GPUs
454
+ self.sdp_kernel_config = (True, False, False)
455
+ else:
456
+ # Don't use flash attention for other GPUs
457
+ self.sdp_kernel_config = (False, True, True)
458
+
459
+ def forward(
460
+ self, q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor] = None, is_causal: bool = False
461
+ ) -> Tensor:
462
+ # Split heads
463
+ q, k, v = rearrange_many((q, k, v), "b n (h d) -> b h n d", h=self.num_heads)
464
+
465
+ if not self.use_flash:
466
+ if is_causal and not mask:
467
+ # Mask out future tokens for causal attention
468
+ mask = causal_mask(q, k)
469
+
470
+ # Compute similarity matrix and add eventual mask
471
+ sim = einsum("... n d, ... m d -> ... n m", q, k) * self.scale
472
+ sim = add_mask(sim, mask) if exists(mask) else sim
473
+
474
+ # Get attention matrix with softmax
475
+ attn = sim.softmax(dim=-1, dtype=torch.float32)
476
+
477
+ # Compute values
478
+ out = einsum("... n m, ... m d -> ... n d", attn, v)
479
+ else:
480
+ with sdp_kernel(*self.sdp_kernel_config):
481
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, is_causal=is_causal)
482
+
483
+ out = rearrange(out, "b h n d -> b n (h d)")
484
+ return self.to_out(out)
485
+
486
+ class Attention(nn.Module):
487
+ def __init__(
488
+ self,
489
+ features: int,
490
+ *,
491
+ head_features: int,
492
+ num_heads: int,
493
+ out_features: Optional[int] = None,
494
+ context_features: Optional[int] = None,
495
+ causal: bool = False,
496
+ ):
497
+ super().__init__()
498
+ self.context_features = context_features
499
+ self.causal = causal
500
+ mid_features = head_features * num_heads
501
+ context_features = default(context_features, features)
502
+
503
+ self.norm = nn.LayerNorm(features)
504
+ self.norm_context = nn.LayerNorm(context_features)
505
+ self.to_q = nn.Linear(
506
+ in_features=features, out_features=mid_features, bias=False
507
+ )
508
+ self.to_kv = nn.Linear(
509
+ in_features=context_features, out_features=mid_features * 2, bias=False
510
+ )
511
+ self.attention = AttentionBase(
512
+ features,
513
+ num_heads=num_heads,
514
+ head_features=head_features,
515
+ out_features=out_features,
516
+ )
517
+
518
+ def forward(
519
+ self,
520
+ x: Tensor, # [b, n, c]
521
+ context: Optional[Tensor] = None, # [b, m, d]
522
+ context_mask: Optional[Tensor] = None, # [b, m], false is masked,
523
+ causal: Optional[bool] = False,
524
+ ) -> Tensor:
525
+ assert_message = "You must provide a context when using context_features"
526
+ assert not self.context_features or exists(context), assert_message
527
+ # Use context if provided
528
+ context = default(context, x)
529
+ # Normalize then compute q from input and k,v from context
530
+ x, context = self.norm(x), self.norm_context(context)
531
+
532
+ q, k, v = (self.to_q(x), *torch.chunk(self.to_kv(context), chunks=2, dim=-1))
533
+
534
+ if exists(context_mask):
535
+ # Mask out cross-attention for padding tokens
536
+ mask = repeat(context_mask, "b m -> b m d", d=v.shape[-1])
537
+ k, v = k * mask, v * mask
538
+
539
+ # Compute and return attention
540
+ return self.attention(q, k, v, is_causal=self.causal or causal)
541
+
542
+
543
+ def FeedForward(features: int, multiplier: int) -> nn.Module:
544
+ mid_features = features * multiplier
545
+ return nn.Sequential(
546
+ nn.Linear(in_features=features, out_features=mid_features),
547
+ nn.GELU(),
548
+ nn.Linear(in_features=mid_features, out_features=features),
549
+ )
550
+
551
+ """
552
+ Transformer Blocks
553
+ """
554
+
555
+
556
+ class TransformerBlock(nn.Module):
557
+ def __init__(
558
+ self,
559
+ features: int,
560
+ num_heads: int,
561
+ head_features: int,
562
+ multiplier: int,
563
+ context_features: Optional[int] = None,
564
+ ):
565
+ super().__init__()
566
+
567
+ self.use_cross_attention = exists(context_features) and context_features > 0
568
+
569
+ self.attention = Attention(
570
+ features=features,
571
+ num_heads=num_heads,
572
+ head_features=head_features
573
+ )
574
+
575
+ if self.use_cross_attention:
576
+ self.cross_attention = Attention(
577
+ features=features,
578
+ num_heads=num_heads,
579
+ head_features=head_features,
580
+ context_features=context_features
581
+ )
582
+
583
+ self.feed_forward = FeedForward(features=features, multiplier=multiplier)
584
+
585
+ def forward(self, x: Tensor, *, context: Optional[Tensor] = None, context_mask: Optional[Tensor] = None, causal: Optional[bool] = False) -> Tensor:
586
+ x = self.attention(x, causal=causal) + x
587
+ if self.use_cross_attention:
588
+ x = self.cross_attention(x, context=context, context_mask=context_mask) + x
589
+ x = self.feed_forward(x) + x
590
+ return x
591
+
592
+
593
+ """
594
+ Transformers
595
+ """
596
+
597
+
598
+ class Transformer1d(nn.Module):
599
+ def __init__(
600
+ self,
601
+ num_layers: int,
602
+ channels: int,
603
+ num_heads: int,
604
+ head_features: int,
605
+ multiplier: int,
606
+ context_features: Optional[int] = None,
607
+ ):
608
+ super().__init__()
609
+
610
+ self.to_in = nn.Sequential(
611
+ nn.GroupNorm(num_groups=32, num_channels=channels, eps=1e-6, affine=True),
612
+ Conv1d(
613
+ in_channels=channels,
614
+ out_channels=channels,
615
+ kernel_size=1,
616
+ ),
617
+ Rearrange("b c t -> b t c"),
618
+ )
619
+
620
+ self.blocks = nn.ModuleList(
621
+ [
622
+ TransformerBlock(
623
+ features=channels,
624
+ head_features=head_features,
625
+ num_heads=num_heads,
626
+ multiplier=multiplier,
627
+ context_features=context_features,
628
+ )
629
+ for i in range(num_layers)
630
+ ]
631
+ )
632
+
633
+ self.to_out = nn.Sequential(
634
+ Rearrange("b t c -> b c t"),
635
+ Conv1d(
636
+ in_channels=channels,
637
+ out_channels=channels,
638
+ kernel_size=1,
639
+ ),
640
+ )
641
+
642
+ def forward(self, x: Tensor, *, context: Optional[Tensor] = None, context_mask: Optional[Tensor] = None, causal=False) -> Tensor:
643
+ x = self.to_in(x)
644
+ for block in self.blocks:
645
+ x = block(x, context=context, context_mask=context_mask, causal=causal)
646
+ x = self.to_out(x)
647
+ return x
648
+
649
+
650
+ """
651
+ Time Embeddings
652
+ """
653
+
654
+
655
+ class SinusoidalEmbedding(nn.Module):
656
+ def __init__(self, dim: int):
657
+ super().__init__()
658
+ self.dim = dim
659
+
660
+ def forward(self, x: Tensor) -> Tensor:
661
+ device, half_dim = x.device, self.dim // 2
662
+ emb = torch.tensor(log(10000) / (half_dim - 1), device=device)
663
+ emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
664
+ emb = rearrange(x, "i -> i 1") * rearrange(emb, "j -> 1 j")
665
+ return torch.cat((emb.sin(), emb.cos()), dim=-1)
666
+
667
+
668
+ class LearnedPositionalEmbedding(nn.Module):
669
+ """Used for continuous time"""
670
+
671
+ def __init__(self, dim: int):
672
+ super().__init__()
673
+ assert (dim % 2) == 0
674
+ half_dim = dim // 2
675
+ self.weights = nn.Parameter(torch.randn(half_dim))
676
+
677
+ def forward(self, x: Tensor) -> Tensor:
678
+ x = rearrange(x, "b -> b 1")
679
+ freqs = x * rearrange(self.weights, "d -> 1 d") * 2 * pi
680
+ fouriered = torch.cat((freqs.sin(), freqs.cos()), dim=-1)
681
+ fouriered = torch.cat((x, fouriered), dim=-1)
682
+ return fouriered
683
+
684
+
685
+ def TimePositionalEmbedding(dim: int, out_features: int) -> nn.Module:
686
+ return nn.Sequential(
687
+ LearnedPositionalEmbedding(dim),
688
+ nn.Linear(in_features=dim + 1, out_features=out_features),
689
+ )
690
+
691
+
692
+ """
693
+ Encoder/Decoder Components
694
+ """
695
+
696
+
697
+ class DownsampleBlock1d(nn.Module):
698
+ def __init__(
699
+ self,
700
+ in_channels: int,
701
+ out_channels: int,
702
+ *,
703
+ factor: int,
704
+ num_groups: int,
705
+ num_layers: int,
706
+ kernel_multiplier: int = 2,
707
+ use_pre_downsample: bool = True,
708
+ use_skip: bool = False,
709
+ use_snake: bool = False,
710
+ extract_channels: int = 0,
711
+ context_channels: int = 0,
712
+ num_transformer_blocks: int = 0,
713
+ attention_heads: Optional[int] = None,
714
+ attention_features: Optional[int] = None,
715
+ attention_multiplier: Optional[int] = None,
716
+ context_mapping_features: Optional[int] = None,
717
+ context_embedding_features: Optional[int] = None,
718
+ ):
719
+ super().__init__()
720
+ self.use_pre_downsample = use_pre_downsample
721
+ self.use_skip = use_skip
722
+ self.use_transformer = num_transformer_blocks > 0
723
+ self.use_extract = extract_channels > 0
724
+ self.use_context = context_channels > 0
725
+
726
+ channels = out_channels if use_pre_downsample else in_channels
727
+
728
+ self.downsample = Downsample1d(
729
+ in_channels=in_channels,
730
+ out_channels=out_channels,
731
+ factor=factor,
732
+ kernel_multiplier=kernel_multiplier,
733
+ )
734
+
735
+ self.blocks = nn.ModuleList(
736
+ [
737
+ ResnetBlock1d(
738
+ in_channels=channels + context_channels if i == 0 else channels,
739
+ out_channels=channels,
740
+ num_groups=num_groups,
741
+ context_mapping_features=context_mapping_features,
742
+ use_snake=use_snake
743
+ )
744
+ for i in range(num_layers)
745
+ ]
746
+ )
747
+
748
+ if self.use_transformer:
749
+ assert (
750
+ (exists(attention_heads) or exists(attention_features))
751
+ and exists(attention_multiplier)
752
+ )
753
+
754
+ if attention_features is None and attention_heads is not None:
755
+ attention_features = channels // attention_heads
756
+
757
+ if attention_heads is None and attention_features is not None:
758
+ attention_heads = channels // attention_features
759
+
760
+ self.transformer = Transformer1d(
761
+ num_layers=num_transformer_blocks,
762
+ channels=channels,
763
+ num_heads=attention_heads,
764
+ head_features=attention_features,
765
+ multiplier=attention_multiplier,
766
+ context_features=context_embedding_features
767
+ )
768
+
769
+ if self.use_extract:
770
+ num_extract_groups = min(num_groups, extract_channels)
771
+ self.to_extracted = ResnetBlock1d(
772
+ in_channels=out_channels,
773
+ out_channels=extract_channels,
774
+ num_groups=num_extract_groups,
775
+ use_snake=use_snake
776
+ )
777
+
778
+ def forward(
779
+ self,
780
+ x: Tensor,
781
+ *,
782
+ mapping: Optional[Tensor] = None,
783
+ channels: Optional[Tensor] = None,
784
+ embedding: Optional[Tensor] = None,
785
+ embedding_mask: Optional[Tensor] = None,
786
+ causal: Optional[bool] = False
787
+ ) -> Union[Tuple[Tensor, List[Tensor]], Tensor]:
788
+
789
+ if self.use_pre_downsample:
790
+ x = self.downsample(x)
791
+
792
+ if self.use_context and exists(channels):
793
+ x = torch.cat([x, channels], dim=1)
794
+
795
+ skips = []
796
+ for block in self.blocks:
797
+ x = block(x, mapping=mapping, causal=causal)
798
+ skips += [x] if self.use_skip else []
799
+
800
+ if self.use_transformer:
801
+ x = self.transformer(x, context=embedding, context_mask=embedding_mask, causal=causal)
802
+ skips += [x] if self.use_skip else []
803
+
804
+ if not self.use_pre_downsample:
805
+ x = self.downsample(x)
806
+
807
+ if self.use_extract:
808
+ extracted = self.to_extracted(x)
809
+ return x, extracted
810
+
811
+ return (x, skips) if self.use_skip else x
812
+
813
+
814
+ class UpsampleBlock1d(nn.Module):
815
+ def __init__(
816
+ self,
817
+ in_channels: int,
818
+ out_channels: int,
819
+ *,
820
+ factor: int,
821
+ num_layers: int,
822
+ num_groups: int,
823
+ use_nearest: bool = False,
824
+ use_pre_upsample: bool = False,
825
+ use_skip: bool = False,
826
+ use_snake: bool = False,
827
+ skip_channels: int = 0,
828
+ use_skip_scale: bool = False,
829
+ extract_channels: int = 0,
830
+ num_transformer_blocks: int = 0,
831
+ attention_heads: Optional[int] = None,
832
+ attention_features: Optional[int] = None,
833
+ attention_multiplier: Optional[int] = None,
834
+ context_mapping_features: Optional[int] = None,
835
+ context_embedding_features: Optional[int] = None,
836
+ ):
837
+ super().__init__()
838
+
839
+ self.use_extract = extract_channels > 0
840
+ self.use_pre_upsample = use_pre_upsample
841
+ self.use_transformer = num_transformer_blocks > 0
842
+ self.use_skip = use_skip
843
+ self.skip_scale = 2 ** -0.5 if use_skip_scale else 1.0
844
+
845
+ channels = out_channels if use_pre_upsample else in_channels
846
+
847
+ self.blocks = nn.ModuleList(
848
+ [
849
+ ResnetBlock1d(
850
+ in_channels=channels + skip_channels,
851
+ out_channels=channels,
852
+ num_groups=num_groups,
853
+ context_mapping_features=context_mapping_features,
854
+ use_snake=use_snake
855
+ )
856
+ for _ in range(num_layers)
857
+ ]
858
+ )
859
+
860
+ if self.use_transformer:
861
+ assert (
862
+ (exists(attention_heads) or exists(attention_features))
863
+ and exists(attention_multiplier)
864
+ )
865
+
866
+ if attention_features is None and attention_heads is not None:
867
+ attention_features = channels // attention_heads
868
+
869
+ if attention_heads is None and attention_features is not None:
870
+ attention_heads = channels // attention_features
871
+
872
+ self.transformer = Transformer1d(
873
+ num_layers=num_transformer_blocks,
874
+ channels=channels,
875
+ num_heads=attention_heads,
876
+ head_features=attention_features,
877
+ multiplier=attention_multiplier,
878
+ context_features=context_embedding_features,
879
+ )
880
+
881
+ self.upsample = Upsample1d(
882
+ in_channels=in_channels,
883
+ out_channels=out_channels,
884
+ factor=factor,
885
+ use_nearest=use_nearest,
886
+ )
887
+
888
+ if self.use_extract:
889
+ num_extract_groups = min(num_groups, extract_channels)
890
+ self.to_extracted = ResnetBlock1d(
891
+ in_channels=out_channels,
892
+ out_channels=extract_channels,
893
+ num_groups=num_extract_groups,
894
+ use_snake=use_snake
895
+ )
896
+
897
+ def add_skip(self, x: Tensor, skip: Tensor) -> Tensor:
898
+ return torch.cat([x, skip * self.skip_scale], dim=1)
899
+
900
+ def forward(
901
+ self,
902
+ x: Tensor,
903
+ *,
904
+ skips: Optional[List[Tensor]] = None,
905
+ mapping: Optional[Tensor] = None,
906
+ embedding: Optional[Tensor] = None,
907
+ embedding_mask: Optional[Tensor] = None,
908
+ causal: Optional[bool] = False
909
+ ) -> Union[Tuple[Tensor, Tensor], Tensor]:
910
+
911
+ if self.use_pre_upsample:
912
+ x = self.upsample(x)
913
+
914
+ for block in self.blocks:
915
+ x = self.add_skip(x, skip=skips.pop()) if exists(skips) else x
916
+ x = block(x, mapping=mapping, causal=causal)
917
+
918
+ if self.use_transformer:
919
+ x = self.transformer(x, context=embedding, context_mask=embedding_mask, causal=causal)
920
+
921
+ if not self.use_pre_upsample:
922
+ x = self.upsample(x)
923
+
924
+ if self.use_extract:
925
+ extracted = self.to_extracted(x)
926
+ return x, extracted
927
+
928
+ return x
929
+
930
+
931
+ class BottleneckBlock1d(nn.Module):
932
+ def __init__(
933
+ self,
934
+ channels: int,
935
+ *,
936
+ num_groups: int,
937
+ num_transformer_blocks: int = 0,
938
+ attention_heads: Optional[int] = None,
939
+ attention_features: Optional[int] = None,
940
+ attention_multiplier: Optional[int] = None,
941
+ context_mapping_features: Optional[int] = None,
942
+ context_embedding_features: Optional[int] = None,
943
+ use_snake: bool = False,
944
+ ):
945
+ super().__init__()
946
+ self.use_transformer = num_transformer_blocks > 0
947
+
948
+ self.pre_block = ResnetBlock1d(
949
+ in_channels=channels,
950
+ out_channels=channels,
951
+ num_groups=num_groups,
952
+ context_mapping_features=context_mapping_features,
953
+ use_snake=use_snake
954
+ )
955
+
956
+ if self.use_transformer:
957
+ assert (
958
+ (exists(attention_heads) or exists(attention_features))
959
+ and exists(attention_multiplier)
960
+ )
961
+
962
+ if attention_features is None and attention_heads is not None:
963
+ attention_features = channels // attention_heads
964
+
965
+ if attention_heads is None and attention_features is not None:
966
+ attention_heads = channels // attention_features
967
+
968
+ self.transformer = Transformer1d(
969
+ num_layers=num_transformer_blocks,
970
+ channels=channels,
971
+ num_heads=attention_heads,
972
+ head_features=attention_features,
973
+ multiplier=attention_multiplier,
974
+ context_features=context_embedding_features,
975
+ )
976
+
977
+ self.post_block = ResnetBlock1d(
978
+ in_channels=channels,
979
+ out_channels=channels,
980
+ num_groups=num_groups,
981
+ context_mapping_features=context_mapping_features,
982
+ use_snake=use_snake
983
+ )
984
+
985
+ def forward(
986
+ self,
987
+ x: Tensor,
988
+ *,
989
+ mapping: Optional[Tensor] = None,
990
+ embedding: Optional[Tensor] = None,
991
+ embedding_mask: Optional[Tensor] = None,
992
+ causal: Optional[bool] = False
993
+ ) -> Tensor:
994
+ x = self.pre_block(x, mapping=mapping, causal=causal)
995
+ if self.use_transformer:
996
+ x = self.transformer(x, context=embedding, context_mask=embedding_mask, causal=causal)
997
+ x = self.post_block(x, mapping=mapping, causal=causal)
998
+ return x
999
+
1000
+
1001
+ """
1002
+ UNet
1003
+ """
1004
+
1005
+
1006
+ class UNet1d(nn.Module):
1007
+ def __init__(
1008
+ self,
1009
+ in_channels: int,
1010
+ channels: int,
1011
+ multipliers: Sequence[int],
1012
+ factors: Sequence[int],
1013
+ num_blocks: Sequence[int],
1014
+ attentions: Sequence[int],
1015
+ patch_size: int = 1,
1016
+ resnet_groups: int = 8,
1017
+ use_context_time: bool = True,
1018
+ kernel_multiplier_downsample: int = 2,
1019
+ use_nearest_upsample: bool = False,
1020
+ use_skip_scale: bool = True,
1021
+ use_snake: bool = False,
1022
+ use_stft: bool = False,
1023
+ use_stft_context: bool = False,
1024
+ out_channels: Optional[int] = None,
1025
+ context_features: Optional[int] = None,
1026
+ context_features_multiplier: int = 4,
1027
+ context_channels: Optional[Sequence[int]] = None,
1028
+ context_embedding_features: Optional[int] = None,
1029
+ **kwargs,
1030
+ ):
1031
+ super().__init__()
1032
+ out_channels = default(out_channels, in_channels)
1033
+ context_channels = list(default(context_channels, []))
1034
+ num_layers = len(multipliers) - 1
1035
+ use_context_features = exists(context_features)
1036
+ use_context_channels = len(context_channels) > 0
1037
+ context_mapping_features = None
1038
+
1039
+ attention_kwargs, kwargs = groupby("attention_", kwargs, keep_prefix=True)
1040
+
1041
+ self.num_layers = num_layers
1042
+ self.use_context_time = use_context_time
1043
+ self.use_context_features = use_context_features
1044
+ self.use_context_channels = use_context_channels
1045
+ self.use_stft = use_stft
1046
+ self.use_stft_context = use_stft_context
1047
+
1048
+ self.context_features = context_features
1049
+ context_channels_pad_length = num_layers + 1 - len(context_channels)
1050
+ context_channels = context_channels + [0] * context_channels_pad_length
1051
+ self.context_channels = context_channels
1052
+ self.context_embedding_features = context_embedding_features
1053
+
1054
+ if use_context_channels:
1055
+ has_context = [c > 0 for c in context_channels]
1056
+ self.has_context = has_context
1057
+ self.channels_ids = [sum(has_context[:i]) for i in range(len(has_context))]
1058
+
1059
+ assert (
1060
+ len(factors) == num_layers
1061
+ and len(attentions) >= num_layers
1062
+ and len(num_blocks) == num_layers
1063
+ )
1064
+
1065
+ if use_context_time or use_context_features:
1066
+ context_mapping_features = channels * context_features_multiplier
1067
+
1068
+ self.to_mapping = nn.Sequential(
1069
+ nn.Linear(context_mapping_features, context_mapping_features),
1070
+ nn.GELU(),
1071
+ nn.Linear(context_mapping_features, context_mapping_features),
1072
+ nn.GELU(),
1073
+ )
1074
+
1075
+ if use_context_time:
1076
+ assert exists(context_mapping_features)
1077
+ self.to_time = nn.Sequential(
1078
+ TimePositionalEmbedding(
1079
+ dim=channels, out_features=context_mapping_features
1080
+ ),
1081
+ nn.GELU(),
1082
+ )
1083
+
1084
+ if use_context_features:
1085
+ assert exists(context_features) and exists(context_mapping_features)
1086
+ self.to_features = nn.Sequential(
1087
+ nn.Linear(
1088
+ in_features=context_features, out_features=context_mapping_features
1089
+ ),
1090
+ nn.GELU(),
1091
+ )
1092
+
1093
+ if use_stft:
1094
+ stft_kwargs, kwargs = groupby("stft_", kwargs)
1095
+ assert "num_fft" in stft_kwargs, "stft_num_fft required if use_stft=True"
1096
+ stft_channels = (stft_kwargs["num_fft"] // 2 + 1) * 2
1097
+ in_channels *= stft_channels
1098
+ out_channels *= stft_channels
1099
+ context_channels[0] *= stft_channels if use_stft_context else 1
1100
+ assert exists(in_channels) and exists(out_channels)
1101
+ self.stft = STFT(**stft_kwargs)
1102
+
1103
+ assert not kwargs, f"Unknown arguments: {', '.join(list(kwargs.keys()))}"
1104
+
1105
+ self.to_in = Patcher(
1106
+ in_channels=in_channels + context_channels[0],
1107
+ out_channels=channels * multipliers[0],
1108
+ patch_size=patch_size,
1109
+ context_mapping_features=context_mapping_features,
1110
+ use_snake=use_snake
1111
+ )
1112
+
1113
+ self.downsamples = nn.ModuleList(
1114
+ [
1115
+ DownsampleBlock1d(
1116
+ in_channels=channels * multipliers[i],
1117
+ out_channels=channels * multipliers[i + 1],
1118
+ context_mapping_features=context_mapping_features,
1119
+ context_channels=context_channels[i + 1],
1120
+ context_embedding_features=context_embedding_features,
1121
+ num_layers=num_blocks[i],
1122
+ factor=factors[i],
1123
+ kernel_multiplier=kernel_multiplier_downsample,
1124
+ num_groups=resnet_groups,
1125
+ use_pre_downsample=True,
1126
+ use_skip=True,
1127
+ use_snake=use_snake,
1128
+ num_transformer_blocks=attentions[i],
1129
+ **attention_kwargs,
1130
+ )
1131
+ for i in range(num_layers)
1132
+ ]
1133
+ )
1134
+
1135
+ self.bottleneck = BottleneckBlock1d(
1136
+ channels=channels * multipliers[-1],
1137
+ context_mapping_features=context_mapping_features,
1138
+ context_embedding_features=context_embedding_features,
1139
+ num_groups=resnet_groups,
1140
+ num_transformer_blocks=attentions[-1],
1141
+ use_snake=use_snake,
1142
+ **attention_kwargs,
1143
+ )
1144
+
1145
+ self.upsamples = nn.ModuleList(
1146
+ [
1147
+ UpsampleBlock1d(
1148
+ in_channels=channels * multipliers[i + 1],
1149
+ out_channels=channels * multipliers[i],
1150
+ context_mapping_features=context_mapping_features,
1151
+ context_embedding_features=context_embedding_features,
1152
+ num_layers=num_blocks[i] + (1 if attentions[i] else 0),
1153
+ factor=factors[i],
1154
+ use_nearest=use_nearest_upsample,
1155
+ num_groups=resnet_groups,
1156
+ use_skip_scale=use_skip_scale,
1157
+ use_pre_upsample=False,
1158
+ use_skip=True,
1159
+ use_snake=use_snake,
1160
+ skip_channels=channels * multipliers[i + 1],
1161
+ num_transformer_blocks=attentions[i],
1162
+ **attention_kwargs,
1163
+ )
1164
+ for i in reversed(range(num_layers))
1165
+ ]
1166
+ )
1167
+
1168
+ self.to_out = Unpatcher(
1169
+ in_channels=channels * multipliers[0],
1170
+ out_channels=out_channels,
1171
+ patch_size=patch_size,
1172
+ context_mapping_features=context_mapping_features,
1173
+ use_snake=use_snake
1174
+ )
1175
+
1176
+ def get_channels(
1177
+ self, channels_list: Optional[Sequence[Tensor]] = None, layer: int = 0
1178
+ ) -> Optional[Tensor]:
1179
+ """Gets context channels at `layer` and checks that shape is correct"""
1180
+ use_context_channels = self.use_context_channels and self.has_context[layer]
1181
+ if not use_context_channels:
1182
+ return None
1183
+ assert exists(channels_list), "Missing context"
1184
+ # Get channels index (skipping zero channel contexts)
1185
+ channels_id = self.channels_ids[layer]
1186
+ # Get channels
1187
+ channels = channels_list[channels_id]
1188
+ message = f"Missing context for layer {layer} at index {channels_id}"
1189
+ assert exists(channels), message
1190
+ # Check channels
1191
+ num_channels = self.context_channels[layer]
1192
+ message = f"Expected context with {num_channels} channels at idx {channels_id}"
1193
+ assert channels.shape[1] == num_channels, message
1194
+ # STFT channels if requested
1195
+ channels = self.stft.encode1d(channels) if self.use_stft_context else channels # type: ignore # noqa
1196
+ return channels
1197
+
1198
+ def get_mapping(
1199
+ self, time: Optional[Tensor] = None, features: Optional[Tensor] = None
1200
+ ) -> Optional[Tensor]:
1201
+ """Combines context time features and features into mapping"""
1202
+ items, mapping = [], None
1203
+ # Compute time features
1204
+ if self.use_context_time:
1205
+ assert_message = "use_context_time=True but no time features provided"
1206
+ assert exists(time), assert_message
1207
+ items += [self.to_time(time)]
1208
+ # Compute features
1209
+ if self.use_context_features:
1210
+ assert_message = "context_features exists but no features provided"
1211
+ assert exists(features), assert_message
1212
+ items += [self.to_features(features)]
1213
+ # Compute joint mapping
1214
+ if self.use_context_time or self.use_context_features:
1215
+ mapping = reduce(torch.stack(items), "n b m -> b m", "sum")
1216
+ mapping = self.to_mapping(mapping)
1217
+ return mapping
1218
+
1219
+ def forward(
1220
+ self,
1221
+ x: Tensor,
1222
+ time: Optional[Tensor] = None,
1223
+ *,
1224
+ features: Optional[Tensor] = None,
1225
+ channels_list: Optional[Sequence[Tensor]] = None,
1226
+ embedding: Optional[Tensor] = None,
1227
+ embedding_mask: Optional[Tensor] = None,
1228
+ causal: Optional[bool] = False,
1229
+ ) -> Tensor:
1230
+ channels = self.get_channels(channels_list, layer=0)
1231
+ # Apply stft if required
1232
+ x = self.stft.encode1d(x) if self.use_stft else x # type: ignore
1233
+ # Concat context channels at layer 0 if provided
1234
+ x = torch.cat([x, channels], dim=1) if exists(channels) else x
1235
+ # Compute mapping from time and features
1236
+ mapping = self.get_mapping(time, features)
1237
+ x = self.to_in(x, mapping, causal=causal)
1238
+ skips_list = [x]
1239
+
1240
+ for i, downsample in enumerate(self.downsamples):
1241
+ channels = self.get_channels(channels_list, layer=i + 1)
1242
+ x, skips = downsample(
1243
+ x, mapping=mapping, channels=channels, embedding=embedding, embedding_mask=embedding_mask, causal=causal
1244
+ )
1245
+ skips_list += [skips]
1246
+
1247
+ x = self.bottleneck(x, mapping=mapping, embedding=embedding, embedding_mask=embedding_mask, causal=causal)
1248
+
1249
+ for i, upsample in enumerate(self.upsamples):
1250
+ skips = skips_list.pop()
1251
+ x = upsample(x, skips=skips, mapping=mapping, embedding=embedding, embedding_mask=embedding_mask, causal=causal)
1252
+
1253
+ x += skips_list.pop()
1254
+ x = self.to_out(x, mapping, causal=causal)
1255
+ x = self.stft.decode1d(x) if self.use_stft else x
1256
+
1257
+ return x
1258
+
1259
+
1260
+ """ Conditioning Modules """
1261
+
1262
+
1263
+ class FixedEmbedding(nn.Module):
1264
+ def __init__(self, max_length: int, features: int):
1265
+ super().__init__()
1266
+ self.max_length = max_length
1267
+ self.embedding = nn.Embedding(max_length, features)
1268
+
1269
+ def forward(self, x: Tensor) -> Tensor:
1270
+ batch_size, length, device = *x.shape[0:2], x.device
1271
+ assert_message = "Input sequence length must be <= max_length"
1272
+ assert length <= self.max_length, assert_message
1273
+ position = torch.arange(length, device=device)
1274
+ fixed_embedding = self.embedding(position)
1275
+ fixed_embedding = repeat(fixed_embedding, "n d -> b n d", b=batch_size)
1276
+ return fixed_embedding
1277
+
1278
+
1279
+ def rand_bool(shape: Any, proba: float, device: Any = None) -> Tensor:
1280
+ if proba == 1:
1281
+ return torch.ones(shape, device=device, dtype=torch.bool)
1282
+ elif proba == 0:
1283
+ return torch.zeros(shape, device=device, dtype=torch.bool)
1284
+ else:
1285
+ return torch.bernoulli(torch.full(shape, proba, device=device)).to(torch.bool)
1286
+
1287
+
1288
+ class UNetCFG1d(UNet1d):
1289
+
1290
+ """UNet1d with Classifier-Free Guidance"""
1291
+
1292
+ def __init__(
1293
+ self,
1294
+ context_embedding_max_length: int,
1295
+ context_embedding_features: int,
1296
+ use_xattn_time: bool = False,
1297
+ **kwargs,
1298
+ ):
1299
+ super().__init__(
1300
+ context_embedding_features=context_embedding_features, **kwargs
1301
+ )
1302
+
1303
+ self.use_xattn_time = use_xattn_time
1304
+
1305
+ if use_xattn_time:
1306
+ assert exists(context_embedding_features)
1307
+ self.to_time_embedding = nn.Sequential(
1308
+ TimePositionalEmbedding(
1309
+ dim=kwargs["channels"], out_features=context_embedding_features
1310
+ ),
1311
+ nn.GELU(),
1312
+ )
1313
+
1314
+ context_embedding_max_length += 1 # Add one for time embedding
1315
+
1316
+ self.fixed_embedding = FixedEmbedding(
1317
+ max_length=context_embedding_max_length, features=context_embedding_features
1318
+ )
1319
+
1320
+ def forward( # type: ignore
1321
+ self,
1322
+ x: Tensor,
1323
+ time: Tensor,
1324
+ *,
1325
+ embedding: Tensor,
1326
+ embedding_mask: Optional[Tensor] = None,
1327
+ embedding_scale: float = 1.0,
1328
+ embedding_mask_proba: float = 0.0,
1329
+ batch_cfg: bool = False,
1330
+ rescale_cfg: bool = False,
1331
+ scale_phi: float = 0.4,
1332
+ negative_embedding: Optional[Tensor] = None,
1333
+ negative_embedding_mask: Optional[Tensor] = None,
1334
+ **kwargs,
1335
+ ) -> Tensor:
1336
+ b, device = embedding.shape[0], embedding.device
1337
+
1338
+ if self.use_xattn_time:
1339
+ embedding = torch.cat([embedding, self.to_time_embedding(time).unsqueeze(1)], dim=1)
1340
+
1341
+ if embedding_mask is not None:
1342
+ embedding_mask = torch.cat([embedding_mask, torch.ones((b, 1), device=device)], dim=1)
1343
+
1344
+ fixed_embedding = self.fixed_embedding(embedding)
1345
+
1346
+ if embedding_mask_proba > 0.0:
1347
+ # Randomly mask embedding
1348
+ batch_mask = rand_bool(
1349
+ shape=(b, 1, 1), proba=embedding_mask_proba, device=device
1350
+ )
1351
+ embedding = torch.where(batch_mask, fixed_embedding, embedding)
1352
+
1353
+ if embedding_scale != 1.0:
1354
+ if batch_cfg:
1355
+ batch_x = torch.cat([x, x], dim=0)
1356
+ batch_time = torch.cat([time, time], dim=0)
1357
+
1358
+ if negative_embedding is not None:
1359
+ if negative_embedding_mask is not None:
1360
+ negative_embedding_mask = negative_embedding_mask.to(torch.bool).unsqueeze(2)
1361
+
1362
+ negative_embedding = torch.where(negative_embedding_mask, negative_embedding, fixed_embedding)
1363
+
1364
+ batch_embed = torch.cat([embedding, negative_embedding], dim=0)
1365
+
1366
+ else:
1367
+ batch_embed = torch.cat([embedding, fixed_embedding], dim=0)
1368
+
1369
+ batch_mask = None
1370
+ if embedding_mask is not None:
1371
+ batch_mask = torch.cat([embedding_mask, embedding_mask], dim=0)
1372
+
1373
+ batch_features = None
1374
+ features = kwargs.pop("features", None)
1375
+ if self.use_context_features:
1376
+ batch_features = torch.cat([features, features], dim=0)
1377
+
1378
+ batch_channels = None
1379
+ channels_list = kwargs.pop("channels_list", None)
1380
+ if self.use_context_channels:
1381
+ batch_channels = []
1382
+ for channels in channels_list:
1383
+ batch_channels += [torch.cat([channels, channels], dim=0)]
1384
+
1385
+ # Compute both normal and fixed embedding outputs
1386
+ batch_out = super().forward(batch_x, batch_time, embedding=batch_embed, embedding_mask=batch_mask, features=batch_features, channels_list=batch_channels, **kwargs)
1387
+ out, out_masked = batch_out.chunk(2, dim=0)
1388
+
1389
+ else:
1390
+ # Compute both normal and fixed embedding outputs
1391
+ out = super().forward(x, time, embedding=embedding, embedding_mask=embedding_mask, **kwargs)
1392
+ out_masked = super().forward(x, time, embedding=fixed_embedding, embedding_mask=embedding_mask, **kwargs)
1393
+
1394
+ out_cfg = out_masked + (out - out_masked) * embedding_scale
1395
+
1396
+ if rescale_cfg:
1397
+
1398
+ out_std = out.std(dim=1, keepdim=True)
1399
+ out_cfg_std = out_cfg.std(dim=1, keepdim=True)
1400
+
1401
+ return scale_phi * (out_cfg * (out_std/out_cfg_std)) + (1-scale_phi) * out_cfg
1402
+
1403
+ else:
1404
+
1405
+ return out_cfg
1406
+
1407
+ else:
1408
+ return super().forward(x, time, embedding=embedding, embedding_mask=embedding_mask, **kwargs)
1409
+
1410
+
1411
+ class UNetNCCA1d(UNet1d):
1412
+
1413
+ """UNet1d with Noise Channel Conditioning Augmentation"""
1414
+
1415
+ def __init__(self, context_features: int, **kwargs):
1416
+ super().__init__(context_features=context_features, **kwargs)
1417
+ self.embedder = NumberEmbedder(features=context_features)
1418
+
1419
+ def expand(self, x: Any, shape: Tuple[int, ...]) -> Tensor:
1420
+ x = x if torch.is_tensor(x) else torch.tensor(x)
1421
+ return x.expand(shape)
1422
+
1423
+ def forward( # type: ignore
1424
+ self,
1425
+ x: Tensor,
1426
+ time: Tensor,
1427
+ *,
1428
+ channels_list: Sequence[Tensor],
1429
+ channels_augmentation: Union[
1430
+ bool, Sequence[bool], Sequence[Sequence[bool]], Tensor
1431
+ ] = False,
1432
+ channels_scale: Union[
1433
+ float, Sequence[float], Sequence[Sequence[float]], Tensor
1434
+ ] = 0,
1435
+ **kwargs,
1436
+ ) -> Tensor:
1437
+ b, n = x.shape[0], len(channels_list)
1438
+ channels_augmentation = self.expand(channels_augmentation, shape=(b, n)).to(x)
1439
+ channels_scale = self.expand(channels_scale, shape=(b, n)).to(x)
1440
+
1441
+ # Augmentation (for each channel list item)
1442
+ for i in range(n):
1443
+ scale = channels_scale[:, i] * channels_augmentation[:, i]
1444
+ scale = rearrange(scale, "b -> b 1 1")
1445
+ item = channels_list[i]
1446
+ channels_list[i] = torch.randn_like(item) * scale + item * (1 - scale) # type: ignore # noqa
1447
+
1448
+ # Scale embedding (sum reduction if more than one channel list item)
1449
+ channels_scale_emb = self.embedder(channels_scale)
1450
+ channels_scale_emb = reduce(channels_scale_emb, "b n d -> b d", "sum")
1451
+
1452
+ return super().forward(
1453
+ x=x,
1454
+ time=time,
1455
+ channels_list=channels_list,
1456
+ features=channels_scale_emb,
1457
+ **kwargs,
1458
+ )
1459
+
1460
+
1461
+ class UNetAll1d(UNetCFG1d, UNetNCCA1d):
1462
+ def __init__(self, *args, **kwargs):
1463
+ super().__init__(*args, **kwargs)
1464
+
1465
+ def forward(self, *args, **kwargs): # type: ignore
1466
+ return UNetCFG1d.forward(self, *args, **kwargs)
1467
+
1468
+
1469
+ def XUNet1d(type: str = "base", **kwargs) -> UNet1d:
1470
+ if type == "base":
1471
+ return UNet1d(**kwargs)
1472
+ elif type == "all":
1473
+ return UNetAll1d(**kwargs)
1474
+ elif type == "cfg":
1475
+ return UNetCFG1d(**kwargs)
1476
+ elif type == "ncca":
1477
+ return UNetNCCA1d(**kwargs)
1478
+ else:
1479
+ raise ValueError(f"Unknown XUNet1d type: {type}")
1480
+
1481
+ class NumberEmbedder(nn.Module):
1482
+ def __init__(
1483
+ self,
1484
+ features: int,
1485
+ dim: int = 256,
1486
+ ):
1487
+ super().__init__()
1488
+ self.features = features
1489
+ self.embedding = TimePositionalEmbedding(dim=dim, out_features=features)
1490
+
1491
+ def forward(self, x: Union[List[float], Tensor]) -> Tensor:
1492
+ if not torch.is_tensor(x):
1493
+ device = next(self.embedding.parameters()).device
1494
+ x = torch.tensor(x, device=device)
1495
+ assert isinstance(x, Tensor)
1496
+ shape = x.shape
1497
+ x = rearrange(x, "... -> (...)")
1498
+ embedding = self.embedding(x)
1499
+ x = embedding.view(*shape, self.features)
1500
+ return x # type: ignore
1501
+
1502
+
1503
+ """
1504
+ Audio Transforms
1505
+ """
1506
+
1507
+
1508
+ class STFT(nn.Module):
1509
+ """Helper for torch stft and istft"""
1510
+
1511
+ def __init__(
1512
+ self,
1513
+ num_fft: int = 1023,
1514
+ hop_length: int = 256,
1515
+ window_length: Optional[int] = None,
1516
+ length: Optional[int] = None,
1517
+ use_complex: bool = False,
1518
+ ):
1519
+ super().__init__()
1520
+ self.num_fft = num_fft
1521
+ self.hop_length = default(hop_length, floor(num_fft // 4))
1522
+ self.window_length = default(window_length, num_fft)
1523
+ self.length = length
1524
+ self.register_buffer("window", torch.hann_window(self.window_length))
1525
+ self.use_complex = use_complex
1526
+
1527
+ def encode(self, wave: Tensor) -> Tuple[Tensor, Tensor]:
1528
+ b = wave.shape[0]
1529
+ wave = rearrange(wave, "b c t -> (b c) t")
1530
+
1531
+ stft = torch.stft(
1532
+ wave,
1533
+ n_fft=self.num_fft,
1534
+ hop_length=self.hop_length,
1535
+ win_length=self.window_length,
1536
+ window=self.window, # type: ignore
1537
+ return_complex=True,
1538
+ normalized=True,
1539
+ )
1540
+
1541
+ if self.use_complex:
1542
+ # Returns real and imaginary
1543
+ stft_a, stft_b = stft.real, stft.imag
1544
+ else:
1545
+ # Returns magnitude and phase matrices
1546
+ magnitude, phase = torch.abs(stft), torch.angle(stft)
1547
+ stft_a, stft_b = magnitude, phase
1548
+
1549
+ return rearrange_many((stft_a, stft_b), "(b c) f l -> b c f l", b=b)
1550
+
1551
+ def decode(self, stft_a: Tensor, stft_b: Tensor) -> Tensor:
1552
+ b, l = stft_a.shape[0], stft_a.shape[-1] # noqa
1553
+ length = closest_power_2(l * self.hop_length)
1554
+
1555
+ stft_a, stft_b = rearrange_many((stft_a, stft_b), "b c f l -> (b c) f l")
1556
+
1557
+ if self.use_complex:
1558
+ real, imag = stft_a, stft_b
1559
+ else:
1560
+ magnitude, phase = stft_a, stft_b
1561
+ real, imag = magnitude * torch.cos(phase), magnitude * torch.sin(phase)
1562
+
1563
+ stft = torch.stack([real, imag], dim=-1)
1564
+
1565
+ wave = torch.istft(
1566
+ stft,
1567
+ n_fft=self.num_fft,
1568
+ hop_length=self.hop_length,
1569
+ win_length=self.window_length,
1570
+ window=self.window, # type: ignore
1571
+ length=default(self.length, length),
1572
+ normalized=True,
1573
+ )
1574
+
1575
+ return rearrange(wave, "(b c) t -> b c t", b=b)
1576
+
1577
+ def encode1d(
1578
+ self, wave: Tensor, stacked: bool = True
1579
+ ) -> Union[Tensor, Tuple[Tensor, Tensor]]:
1580
+ stft_a, stft_b = self.encode(wave)
1581
+ stft_a, stft_b = rearrange_many((stft_a, stft_b), "b c f l -> b (c f) l")
1582
+ return torch.cat((stft_a, stft_b), dim=1) if stacked else (stft_a, stft_b)
1583
+
1584
+ def decode1d(self, stft_pair: Tensor) -> Tensor:
1585
+ f = self.num_fft // 2 + 1
1586
+ stft_a, stft_b = stft_pair.chunk(chunks=2, dim=1)
1587
+ stft_a, stft_b = rearrange_many((stft_a, stft_b), "b (c f) l -> b c f l", f=f)
1588
+ return self.decode(stft_a, stft_b)
ThinkSound/models/autoencoders.py ADDED
@@ -0,0 +1,800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import math
3
+ import numpy as np
4
+
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+ from torchaudio import transforms as T
8
+ from alias_free_torch import Activation1d
9
+ from dac.nn.layers import WNConv1d, WNConvTranspose1d
10
+ from typing import Literal, Dict, Any
11
+
12
+ from ..inference.sampling import sample
13
+ from ..inference.utils import prepare_audio
14
+ from .blocks import SnakeBeta
15
+ from .bottleneck import Bottleneck, DiscreteBottleneck
16
+ from .diffusion import ConditionedDiffusionModel, DAU1DCondWrapper, UNet1DCondWrapper, DiTWrapper
17
+ from .factory import create_pretransform_from_config, create_bottleneck_from_config
18
+ from .pretransforms import Pretransform
19
+
20
+ def checkpoint(function, *args, **kwargs):
21
+ kwargs.setdefault("use_reentrant", False)
22
+ return torch.utils.checkpoint.checkpoint(function, *args, **kwargs)
23
+
24
+ def get_activation(activation: Literal["elu", "snake", "none"], antialias=False, channels=None) -> nn.Module:
25
+ if activation == "elu":
26
+ act = nn.ELU()
27
+ elif activation == "snake":
28
+ act = SnakeBeta(channels)
29
+ elif activation == "none":
30
+ act = nn.Identity()
31
+ else:
32
+ raise ValueError(f"Unknown activation {activation}")
33
+
34
+ if antialias:
35
+ act = Activation1d(act)
36
+
37
+ return act
38
+
39
+ class ResidualUnit(nn.Module):
40
+ def __init__(self, in_channels, out_channels, dilation, use_snake=False, antialias_activation=False):
41
+ super().__init__()
42
+
43
+ self.dilation = dilation
44
+
45
+ padding = (dilation * (7-1)) // 2
46
+
47
+ self.layers = nn.Sequential(
48
+ get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=out_channels),
49
+ WNConv1d(in_channels=in_channels, out_channels=out_channels,
50
+ kernel_size=7, dilation=dilation, padding=padding),
51
+ get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=out_channels),
52
+ WNConv1d(in_channels=out_channels, out_channels=out_channels,
53
+ kernel_size=1)
54
+ )
55
+
56
+ def forward(self, x):
57
+ res = x
58
+
59
+ #x = checkpoint(self.layers, x)
60
+ x = self.layers(x)
61
+
62
+ return x + res
63
+
64
+ class EncoderBlock(nn.Module):
65
+ def __init__(self, in_channels, out_channels, stride, use_snake=False, antialias_activation=False):
66
+ super().__init__()
67
+
68
+ self.layers = nn.Sequential(
69
+ ResidualUnit(in_channels=in_channels,
70
+ out_channels=in_channels, dilation=1, use_snake=use_snake),
71
+ ResidualUnit(in_channels=in_channels,
72
+ out_channels=in_channels, dilation=3, use_snake=use_snake),
73
+ ResidualUnit(in_channels=in_channels,
74
+ out_channels=in_channels, dilation=9, use_snake=use_snake),
75
+ get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=in_channels),
76
+ WNConv1d(in_channels=in_channels, out_channels=out_channels,
77
+ kernel_size=2*stride, stride=stride, padding=math.ceil(stride/2)),
78
+ )
79
+
80
+ def forward(self, x):
81
+ return self.layers(x)
82
+
83
+ class DecoderBlock(nn.Module):
84
+ def __init__(self, in_channels, out_channels, stride, use_snake=False, antialias_activation=False, use_nearest_upsample=False):
85
+ super().__init__()
86
+
87
+ if use_nearest_upsample:
88
+ upsample_layer = nn.Sequential(
89
+ nn.Upsample(scale_factor=stride, mode="nearest"),
90
+ WNConv1d(in_channels=in_channels,
91
+ out_channels=out_channels,
92
+ kernel_size=2*stride,
93
+ stride=1,
94
+ bias=False,
95
+ padding='same')
96
+ )
97
+ else:
98
+ upsample_layer = WNConvTranspose1d(in_channels=in_channels,
99
+ out_channels=out_channels,
100
+ kernel_size=2*stride, stride=stride, padding=math.ceil(stride/2))
101
+
102
+ self.layers = nn.Sequential(
103
+ get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=in_channels),
104
+ upsample_layer,
105
+ ResidualUnit(in_channels=out_channels, out_channels=out_channels,
106
+ dilation=1, use_snake=use_snake),
107
+ ResidualUnit(in_channels=out_channels, out_channels=out_channels,
108
+ dilation=3, use_snake=use_snake),
109
+ ResidualUnit(in_channels=out_channels, out_channels=out_channels,
110
+ dilation=9, use_snake=use_snake),
111
+ )
112
+
113
+ def forward(self, x):
114
+ return self.layers(x)
115
+
116
+ class OobleckEncoder(nn.Module):
117
+ def __init__(self,
118
+ in_channels=2,
119
+ channels=128,
120
+ latent_dim=32,
121
+ c_mults = [1, 2, 4, 8],
122
+ strides = [2, 4, 8, 8],
123
+ use_snake=False,
124
+ antialias_activation=False
125
+ ):
126
+ super().__init__()
127
+
128
+ c_mults = [1] + c_mults
129
+
130
+ self.depth = len(c_mults)
131
+
132
+ layers = [
133
+ WNConv1d(in_channels=in_channels, out_channels=c_mults[0] * channels, kernel_size=7, padding=3)
134
+ ]
135
+
136
+ for i in range(self.depth-1):
137
+ layers += [EncoderBlock(in_channels=c_mults[i]*channels, out_channels=c_mults[i+1]*channels, stride=strides[i], use_snake=use_snake)]
138
+
139
+ layers += [
140
+ get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=c_mults[-1] * channels),
141
+ WNConv1d(in_channels=c_mults[-1]*channels, out_channels=latent_dim, kernel_size=3, padding=1)
142
+ ]
143
+
144
+ self.layers = nn.Sequential(*layers)
145
+
146
+ def forward(self, x):
147
+ return self.layers(x)
148
+
149
+
150
+ class OobleckDecoder(nn.Module):
151
+ def __init__(self,
152
+ out_channels=2,
153
+ channels=128,
154
+ latent_dim=32,
155
+ c_mults = [1, 2, 4, 8],
156
+ strides = [2, 4, 8, 8],
157
+ use_snake=False,
158
+ antialias_activation=False,
159
+ use_nearest_upsample=False,
160
+ final_tanh=True):
161
+ super().__init__()
162
+
163
+ c_mults = [1] + c_mults
164
+
165
+ self.depth = len(c_mults)
166
+
167
+ layers = [
168
+ WNConv1d(in_channels=latent_dim, out_channels=c_mults[-1]*channels, kernel_size=7, padding=3),
169
+ ]
170
+
171
+ for i in range(self.depth-1, 0, -1):
172
+ layers += [DecoderBlock(
173
+ in_channels=c_mults[i]*channels,
174
+ out_channels=c_mults[i-1]*channels,
175
+ stride=strides[i-1],
176
+ use_snake=use_snake,
177
+ antialias_activation=antialias_activation,
178
+ use_nearest_upsample=use_nearest_upsample
179
+ )
180
+ ]
181
+
182
+ layers += [
183
+ get_activation("snake" if use_snake else "elu", antialias=antialias_activation, channels=c_mults[0] * channels),
184
+ WNConv1d(in_channels=c_mults[0] * channels, out_channels=out_channels, kernel_size=7, padding=3, bias=False),
185
+ nn.Tanh() if final_tanh else nn.Identity()
186
+ ]
187
+
188
+ self.layers = nn.Sequential(*layers)
189
+
190
+ def forward(self, x):
191
+ return self.layers(x)
192
+
193
+
194
+ class DACEncoderWrapper(nn.Module):
195
+ def __init__(self, in_channels=1, **kwargs):
196
+ super().__init__()
197
+
198
+ from dac.model.dac import Encoder as DACEncoder
199
+
200
+ latent_dim = kwargs.pop("latent_dim", None)
201
+
202
+ encoder_out_dim = kwargs["d_model"] * (2 ** len(kwargs["strides"]))
203
+ self.encoder = DACEncoder(d_latent=encoder_out_dim, **kwargs)
204
+ self.latent_dim = latent_dim
205
+
206
+ # Latent-dim support was added to DAC after this was first written, and implemented differently, so this is for backwards compatibility
207
+ self.proj_out = nn.Conv1d(self.encoder.enc_dim, latent_dim, kernel_size=1) if latent_dim is not None else nn.Identity()
208
+
209
+ if in_channels != 1:
210
+ self.encoder.block[0] = WNConv1d(in_channels, kwargs.get("d_model", 64), kernel_size=7, padding=3)
211
+
212
+ def forward(self, x):
213
+ x = self.encoder(x)
214
+ x = self.proj_out(x)
215
+ return x
216
+
217
+ class DACDecoderWrapper(nn.Module):
218
+ def __init__(self, latent_dim, out_channels=1, **kwargs):
219
+ super().__init__()
220
+
221
+ from dac.model.dac import Decoder as DACDecoder
222
+
223
+ self.decoder = DACDecoder(**kwargs, input_channel = latent_dim, d_out=out_channels)
224
+
225
+ self.latent_dim = latent_dim
226
+
227
+ def forward(self, x):
228
+ return self.decoder(x)
229
+
230
+ class AudioAutoencoder(nn.Module):
231
+ def __init__(
232
+ self,
233
+ encoder,
234
+ decoder,
235
+ latent_dim,
236
+ downsampling_ratio,
237
+ sample_rate,
238
+ io_channels=2,
239
+ bottleneck: Bottleneck = None,
240
+ pretransform: Pretransform = None,
241
+ in_channels = None,
242
+ out_channels = None,
243
+ soft_clip = False
244
+ ):
245
+ super().__init__()
246
+
247
+ self.downsampling_ratio = downsampling_ratio
248
+ self.sample_rate = sample_rate
249
+
250
+ self.latent_dim = latent_dim
251
+ self.io_channels = io_channels
252
+ self.in_channels = io_channels
253
+ self.out_channels = io_channels
254
+
255
+ self.min_length = self.downsampling_ratio
256
+
257
+ if in_channels is not None:
258
+ self.in_channels = in_channels
259
+
260
+ if out_channels is not None:
261
+ self.out_channels = out_channels
262
+
263
+ self.bottleneck = bottleneck
264
+
265
+ self.encoder = encoder
266
+
267
+ self.decoder = decoder
268
+
269
+ self.pretransform = pretransform
270
+
271
+ self.soft_clip = soft_clip
272
+
273
+ self.is_discrete = self.bottleneck is not None and self.bottleneck.is_discrete
274
+
275
+ def encode(self, audio, return_info=False, skip_pretransform=False, iterate_batch=False, **kwargs):
276
+
277
+ info = {}
278
+ # import ipdb
279
+ # ipdb.set_trace()
280
+ if self.pretransform is not None and not skip_pretransform:
281
+ if self.pretransform.enable_grad:
282
+ if iterate_batch:
283
+ audios = []
284
+ for i in range(audio.shape[0]):
285
+ audios.append(self.pretransform.encode(audio[i:i+1]))
286
+ audio = torch.cat(audios, dim=0)
287
+ else:
288
+ audio = self.pretransform.encode(audio)
289
+ else:
290
+ with torch.no_grad():
291
+ if iterate_batch:
292
+ audios = []
293
+ for i in range(audio.shape[0]):
294
+ audios.append(self.pretransform.encode(audio[i:i+1]))
295
+ audio = torch.cat(audios, dim=0)
296
+ else:
297
+ audio = self.pretransform.encode(audio)
298
+
299
+ if self.encoder is not None:
300
+ if iterate_batch:
301
+ latents = []
302
+ for i in range(audio.shape[0]):
303
+ latents.append(self.encoder(audio[i:i+1]))
304
+ latents = torch.cat(latents, dim=0)
305
+ else:
306
+ latents = self.encoder(audio)
307
+ else:
308
+ latents = audio
309
+
310
+ if self.bottleneck is not None:
311
+ # TODO: Add iterate batch logic, needs to merge the info dicts
312
+ latents, bottleneck_info = self.bottleneck.encode(latents, return_info=True, **kwargs)
313
+
314
+ info.update(bottleneck_info)
315
+
316
+ if return_info:
317
+ return latents, info
318
+
319
+ return latents
320
+
321
+ def decode(self, latents, iterate_batch=False, **kwargs):
322
+
323
+ if self.bottleneck is not None:
324
+ if iterate_batch:
325
+ decoded = []
326
+ for i in range(latents.shape[0]):
327
+ decoded.append(self.bottleneck.decode(latents[i:i+1]))
328
+ latents = torch.cat(decoded, dim=0)
329
+ else:
330
+ latents = self.bottleneck.decode(latents)
331
+
332
+ if iterate_batch:
333
+ decoded = []
334
+ for i in range(latents.shape[0]):
335
+ decoded.append(self.decoder(latents[i:i+1]))
336
+ decoded = torch.cat(decoded, dim=0)
337
+ else:
338
+ decoded = self.decoder(latents, **kwargs)
339
+
340
+ if self.pretransform is not None:
341
+ if self.pretransform.enable_grad:
342
+ if iterate_batch:
343
+ decodeds = []
344
+ for i in range(decoded.shape[0]):
345
+ decodeds.append(self.pretransform.decode(decoded[i:i+1]))
346
+ decoded = torch.cat(decodeds, dim=0)
347
+ else:
348
+ decoded = self.pretransform.decode(decoded)
349
+ else:
350
+ with torch.no_grad():
351
+ if iterate_batch:
352
+ decodeds = []
353
+ for i in range(latents.shape[0]):
354
+ decodeds.append(self.pretransform.decode(decoded[i:i+1]))
355
+ decoded = torch.cat(decodeds, dim=0)
356
+ else:
357
+ decoded = self.pretransform.decode(decoded)
358
+
359
+ if self.soft_clip:
360
+ decoded = torch.tanh(decoded)
361
+
362
+ return decoded
363
+
364
+ def decode_tokens(self, tokens, **kwargs):
365
+ '''
366
+ Decode discrete tokens to audio
367
+ Only works with discrete autoencoders
368
+ '''
369
+
370
+ assert isinstance(self.bottleneck, DiscreteBottleneck), "decode_tokens only works with discrete autoencoders"
371
+
372
+ latents = self.bottleneck.decode_tokens(tokens, **kwargs)
373
+
374
+ return self.decode(latents, **kwargs)
375
+
376
+
377
+ def preprocess_audio_for_encoder(self, audio, in_sr):
378
+ '''
379
+ Preprocess single audio tensor (Channels x Length) to be compatible with the encoder.
380
+ If the model is mono, stereo audio will be converted to mono.
381
+ Audio will be silence-padded to be a multiple of the model's downsampling ratio.
382
+ Audio will be resampled to the model's sample rate.
383
+ The output will have batch size 1 and be shape (1 x Channels x Length)
384
+ '''
385
+ return self.preprocess_audio_list_for_encoder([audio], [in_sr])
386
+
387
+ def preprocess_audio_list_for_encoder(self, audio_list, in_sr_list):
388
+ '''
389
+ Preprocess a [list] of audio (Channels x Length) into a batch tensor to be compatable with the encoder.
390
+ The audio in that list can be of different lengths and channels.
391
+ in_sr can be an integer or list. If it's an integer it will be assumed it is the input sample_rate for every audio.
392
+ All audio will be resampled to the model's sample rate.
393
+ Audio will be silence-padded to the longest length, and further padded to be a multiple of the model's downsampling ratio.
394
+ If the model is mono, all audio will be converted to mono.
395
+ The output will be a tensor of shape (Batch x Channels x Length)
396
+ '''
397
+ batch_size = len(audio_list)
398
+ if isinstance(in_sr_list, int):
399
+ in_sr_list = [in_sr_list]*batch_size
400
+ assert len(in_sr_list) == batch_size, "list of sample rates must be the same length of audio_list"
401
+ new_audio = []
402
+ max_length = 0
403
+ # resample & find the max length
404
+ for i in range(batch_size):
405
+ audio = audio_list[i]
406
+ in_sr = in_sr_list[i]
407
+ if len(audio.shape) == 3 and audio.shape[0] == 1:
408
+ # batchsize 1 was given by accident. Just squeeze it.
409
+ audio = audio.squeeze(0)
410
+ elif len(audio.shape) == 1:
411
+ # Mono signal, channel dimension is missing, unsqueeze it in
412
+ audio = audio.unsqueeze(0)
413
+ assert len(audio.shape)==2, "Audio should be shape (Channels x Length) with no batch dimension"
414
+ # Resample audio
415
+ if in_sr != self.sample_rate:
416
+ resample_tf = T.Resample(in_sr, self.sample_rate).to(audio.device)
417
+ audio = resample_tf(audio)
418
+ new_audio.append(audio)
419
+ if audio.shape[-1] > max_length:
420
+ max_length = audio.shape[-1]
421
+ # Pad every audio to the same length, multiple of model's downsampling ratio
422
+ padded_audio_length = max_length + (self.min_length - (max_length % self.min_length)) % self.min_length
423
+ for i in range(batch_size):
424
+ # Pad it & if necessary, mixdown/duplicate stereo/mono channels to support model
425
+ new_audio[i] = prepare_audio(new_audio[i], in_sr=in_sr, target_sr=in_sr, target_length=padded_audio_length,
426
+ target_channels=self.in_channels, device=new_audio[i].device).squeeze(0)
427
+ # convert to tensor
428
+ return torch.stack(new_audio)
429
+
430
+ def encode_audio(self, audio, chunked=False, overlap=32, chunk_size=128, **kwargs):
431
+ '''
432
+ Encode audios into latents. Audios should already be preprocesed by preprocess_audio_for_encoder.
433
+ If chunked is True, split the audio into chunks of a given maximum size chunk_size, with given overlap.
434
+ Overlap and chunk_size params are both measured in number of latents (not audio samples)
435
+ # and therefore you likely could use the same values with decode_audio.
436
+ A overlap of zero will cause discontinuity artefacts. Overlap should be => receptive field size.
437
+ Every autoencoder will have a different receptive field size, and thus ideal overlap.
438
+ You can determine it empirically by diffing unchunked vs chunked output and looking at maximum diff.
439
+ The final chunk may have a longer overlap in order to keep chunk_size consistent for all chunks.
440
+ Smaller chunk_size uses less memory, but more compute.
441
+ The chunk_size vs memory tradeoff isn't linear, and possibly depends on the GPU and CUDA version
442
+ For example, on a A6000 chunk_size 128 is overall faster than 256 and 512 even though it has more chunks
443
+ '''
444
+ if not chunked:
445
+ # default behavior. Encode the entire audio in parallel
446
+ return self.encode(audio, **kwargs)
447
+ else:
448
+ # CHUNKED ENCODING
449
+ # samples_per_latent is just the downsampling ratio (which is also the upsampling ratio)
450
+ # import ipdb
451
+ # ipdb.set_trace()
452
+ samples_per_latent = self.downsampling_ratio
453
+ total_size = audio.shape[2] # in samples
454
+ print(f'audio shape: {audio.shape}')
455
+ batch_size = audio.shape[0]
456
+ chunk_size *= samples_per_latent # converting metric in latents to samples
457
+ overlap *= samples_per_latent # converting metric in latents to samples
458
+ hop_size = chunk_size - overlap
459
+ chunks = []
460
+ for i in range(0, total_size - chunk_size + 1, hop_size):
461
+ chunk = audio[:,:,i:i+chunk_size]
462
+ chunks.append(chunk)
463
+ if i+chunk_size != total_size:
464
+ # Final chunk
465
+ chunk = audio[:,:,-chunk_size:]
466
+ chunks.append(chunk)
467
+ chunks = torch.stack(chunks)
468
+ num_chunks = chunks.shape[0]
469
+ # Note: y_size might be a different value from the latent length used in diffusion training
470
+ # because we can encode audio of varying lengths
471
+ # However, the audio should've been padded to a multiple of samples_per_latent by now.
472
+ y_size = total_size // samples_per_latent
473
+ # Create an empty latent, we will populate it with chunks as we encode them
474
+ y_final = torch.zeros((batch_size,self.latent_dim,y_size)).to(audio.device)
475
+ print(f'y_final shape: {y_final.shape}')
476
+ for i in range(num_chunks):
477
+ x_chunk = chunks[i,:]
478
+ # encode the chunk
479
+ y_chunk = self.encode(x_chunk)
480
+ print(f'y_chunk shape: {y_chunk.shape}')
481
+ # figure out where to put the audio along the time domain
482
+ if i == num_chunks-1:
483
+ # final chunk always goes at the end
484
+ t_end = y_size
485
+ t_start = t_end - y_chunk.shape[2]
486
+ else:
487
+ t_start = i * hop_size // samples_per_latent
488
+ t_end = t_start + chunk_size // samples_per_latent
489
+ # remove the edges of the overlaps
490
+ ol = overlap//samples_per_latent//2
491
+ chunk_start = 0
492
+ chunk_end = y_chunk.shape[2]
493
+ if i > 0:
494
+ # no overlap for the start of the first chunk
495
+ t_start += ol
496
+ chunk_start += ol
497
+ if i < num_chunks-1:
498
+ # no overlap for the end of the last chunk
499
+ t_end -= ol
500
+ chunk_end -= ol
501
+ # paste the chunked audio into our y_final output audio
502
+ y_final[:,:,t_start:t_end] = y_chunk[:,:,chunk_start:chunk_end]
503
+ return y_final
504
+
505
+ def decode_audio(self, latents, chunked=False, overlap=32, chunk_size=128, **kwargs):
506
+ '''
507
+ Decode latents to audio.
508
+ If chunked is True, split the latents into chunks of a given maximum size chunk_size, with given overlap, both of which are measured in number of latents.
509
+ A overlap of zero will cause discontinuity artefacts. Overlap should be => receptive field size.
510
+ Every autoencoder will have a different receptive field size, and thus ideal overlap.
511
+ You can determine it empirically by diffing unchunked vs chunked audio and looking at maximum diff.
512
+ The final chunk may have a longer overlap in order to keep chunk_size consistent for all chunks.
513
+ Smaller chunk_size uses less memory, but more compute.
514
+ The chunk_size vs memory tradeoff isn't linear, and possibly depends on the GPU and CUDA version
515
+ For example, on a A6000 chunk_size 128 is overall faster than 256 and 512 even though it has more chunks
516
+ '''
517
+ if not chunked:
518
+ # default behavior. Decode the entire latent in parallel
519
+ return self.decode(latents, **kwargs)
520
+ else:
521
+ # chunked decoding
522
+ hop_size = chunk_size - overlap
523
+ total_size = latents.shape[2]
524
+ batch_size = latents.shape[0]
525
+ chunks = []
526
+ for i in range(0, total_size - chunk_size + 1, hop_size):
527
+ chunk = latents[:,:,i:i+chunk_size]
528
+ chunks.append(chunk)
529
+ if i+chunk_size != total_size:
530
+ # Final chunk
531
+ chunk = latents[:,:,-chunk_size:]
532
+ chunks.append(chunk)
533
+ chunks = torch.stack(chunks)
534
+ num_chunks = chunks.shape[0]
535
+ # samples_per_latent is just the downsampling ratio
536
+ samples_per_latent = self.downsampling_ratio
537
+ # Create an empty waveform, we will populate it with chunks as decode them
538
+ y_size = total_size * samples_per_latent
539
+ y_final = torch.zeros((batch_size,self.out_channels,y_size)).to(latents.device)
540
+ for i in range(num_chunks):
541
+ x_chunk = chunks[i,:]
542
+ # decode the chunk
543
+ y_chunk = self.decode(x_chunk)
544
+ # figure out where to put the audio along the time domain
545
+ if i == num_chunks-1:
546
+ # final chunk always goes at the end
547
+ t_end = y_size
548
+ t_start = t_end - y_chunk.shape[2]
549
+ else:
550
+ t_start = i * hop_size * samples_per_latent
551
+ t_end = t_start + chunk_size * samples_per_latent
552
+ # remove the edges of the overlaps
553
+ ol = (overlap//2) * samples_per_latent
554
+ chunk_start = 0
555
+ chunk_end = y_chunk.shape[2]
556
+ if i > 0:
557
+ # no overlap for the start of the first chunk
558
+ t_start += ol
559
+ chunk_start += ol
560
+ if i < num_chunks-1:
561
+ # no overlap for the end of the last chunk
562
+ t_end -= ol
563
+ chunk_end -= ol
564
+ # paste the chunked audio into our y_final output audio
565
+ y_final[:,:,t_start:t_end] = y_chunk[:,:,chunk_start:chunk_end]
566
+ return y_final
567
+
568
+
569
+ class DiffusionAutoencoder(AudioAutoencoder):
570
+ def __init__(
571
+ self,
572
+ diffusion: ConditionedDiffusionModel,
573
+ diffusion_downsampling_ratio,
574
+ *args,
575
+ **kwargs
576
+ ):
577
+ super().__init__(*args, **kwargs)
578
+
579
+ self.diffusion = diffusion
580
+
581
+ self.min_length = self.downsampling_ratio * diffusion_downsampling_ratio
582
+
583
+ if self.encoder is not None:
584
+ # Shrink the initial encoder parameters to avoid saturated latents
585
+ with torch.no_grad():
586
+ for param in self.encoder.parameters():
587
+ param *= 0.5
588
+
589
+ def decode(self, latents, steps=100):
590
+
591
+ upsampled_length = latents.shape[2] * self.downsampling_ratio
592
+
593
+ if self.bottleneck is not None:
594
+ latents = self.bottleneck.decode(latents)
595
+
596
+ if self.decoder is not None:
597
+ latents = self.decode(latents)
598
+
599
+ # Upsample latents to match diffusion length
600
+ if latents.shape[2] != upsampled_length:
601
+ latents = F.interpolate(latents, size=upsampled_length, mode='nearest')
602
+
603
+ noise = torch.randn(latents.shape[0], self.io_channels, upsampled_length, device=latents.device)
604
+ decoded = sample(self.diffusion, noise, steps, 0, input_concat_cond=latents)
605
+
606
+ if self.pretransform is not None:
607
+ if self.pretransform.enable_grad:
608
+ decoded = self.pretransform.decode(decoded)
609
+ else:
610
+ with torch.no_grad():
611
+ decoded = self.pretransform.decode(decoded)
612
+
613
+ return decoded
614
+
615
+ # AE factories
616
+
617
+ def create_encoder_from_config(encoder_config: Dict[str, Any]):
618
+ encoder_type = encoder_config.get("type", None)
619
+ assert encoder_type is not None, "Encoder type must be specified"
620
+
621
+ if encoder_type == "oobleck":
622
+ encoder = OobleckEncoder(
623
+ **encoder_config["config"]
624
+ )
625
+
626
+ elif encoder_type == "seanet":
627
+ from encodec.modules import SEANetEncoder
628
+ seanet_encoder_config = encoder_config["config"]
629
+
630
+ #SEANet encoder expects strides in reverse order
631
+ seanet_encoder_config["ratios"] = list(reversed(seanet_encoder_config.get("ratios", [2, 2, 2, 2, 2])))
632
+ encoder = SEANetEncoder(
633
+ **seanet_encoder_config
634
+ )
635
+ elif encoder_type == "dac":
636
+ dac_config = encoder_config["config"]
637
+
638
+ encoder = DACEncoderWrapper(**dac_config)
639
+ elif encoder_type == "local_attn":
640
+ from .local_attention import TransformerEncoder1D
641
+
642
+ local_attn_config = encoder_config["config"]
643
+
644
+ encoder = TransformerEncoder1D(
645
+ **local_attn_config
646
+ )
647
+ else:
648
+ raise ValueError(f"Unknown encoder type {encoder_type}")
649
+
650
+ requires_grad = encoder_config.get("requires_grad", True)
651
+ if not requires_grad:
652
+ for param in encoder.parameters():
653
+ param.requires_grad = False
654
+
655
+ return encoder
656
+
657
+ def create_decoder_from_config(decoder_config: Dict[str, Any]):
658
+ decoder_type = decoder_config.get("type", None)
659
+ assert decoder_type is not None, "Decoder type must be specified"
660
+
661
+ if decoder_type == "oobleck":
662
+ decoder = OobleckDecoder(
663
+ **decoder_config["config"]
664
+ )
665
+ elif decoder_type == "seanet":
666
+ from encodec.modules import SEANetDecoder
667
+
668
+ decoder = SEANetDecoder(
669
+ **decoder_config["config"]
670
+ )
671
+ elif decoder_type == "dac":
672
+ dac_config = decoder_config["config"]
673
+
674
+ decoder = DACDecoderWrapper(**dac_config)
675
+ elif decoder_type == "local_attn":
676
+ from .local_attention import TransformerDecoder1D
677
+
678
+ local_attn_config = decoder_config["config"]
679
+
680
+ decoder = TransformerDecoder1D(
681
+ **local_attn_config
682
+ )
683
+ else:
684
+ raise ValueError(f"Unknown decoder type {decoder_type}")
685
+
686
+ requires_grad = decoder_config.get("requires_grad", True)
687
+ if not requires_grad:
688
+ for param in decoder.parameters():
689
+ param.requires_grad = False
690
+
691
+ return decoder
692
+
693
+ def create_autoencoder_from_config(config: Dict[str, Any]):
694
+
695
+ ae_config = config["model"]
696
+
697
+ encoder = create_encoder_from_config(ae_config["encoder"])
698
+ decoder = create_decoder_from_config(ae_config["decoder"])
699
+
700
+ bottleneck = ae_config.get("bottleneck", None)
701
+
702
+ latent_dim = ae_config.get("latent_dim", None)
703
+ assert latent_dim is not None, "latent_dim must be specified in model config"
704
+ downsampling_ratio = ae_config.get("downsampling_ratio", None)
705
+ assert downsampling_ratio is not None, "downsampling_ratio must be specified in model config"
706
+ io_channels = ae_config.get("io_channels", None)
707
+ assert io_channels is not None, "io_channels must be specified in model config"
708
+ sample_rate = config.get("sample_rate", None)
709
+ assert sample_rate is not None, "sample_rate must be specified in model config"
710
+
711
+ in_channels = ae_config.get("in_channels", None)
712
+ out_channels = ae_config.get("out_channels", None)
713
+
714
+ pretransform = ae_config.get("pretransform", None)
715
+
716
+ if pretransform is not None:
717
+ pretransform = create_pretransform_from_config(pretransform, sample_rate)
718
+
719
+ if bottleneck is not None:
720
+ bottleneck = create_bottleneck_from_config(bottleneck)
721
+
722
+ soft_clip = ae_config["decoder"].get("soft_clip", False)
723
+
724
+ return AudioAutoencoder(
725
+ encoder,
726
+ decoder,
727
+ io_channels=io_channels,
728
+ latent_dim=latent_dim,
729
+ downsampling_ratio=downsampling_ratio,
730
+ sample_rate=sample_rate,
731
+ bottleneck=bottleneck,
732
+ pretransform=pretransform,
733
+ in_channels=in_channels,
734
+ out_channels=out_channels,
735
+ soft_clip=soft_clip
736
+ )
737
+
738
+ def create_diffAE_from_config(config: Dict[str, Any]):
739
+
740
+ diffae_config = config["model"]
741
+
742
+ if "encoder" in diffae_config:
743
+ encoder = create_encoder_from_config(diffae_config["encoder"])
744
+ else:
745
+ encoder = None
746
+
747
+ if "decoder" in diffae_config:
748
+ decoder = create_decoder_from_config(diffae_config["decoder"])
749
+ else:
750
+ decoder = None
751
+
752
+ diffusion_model_type = diffae_config["diffusion"]["type"]
753
+
754
+ if diffusion_model_type == "DAU1d":
755
+ diffusion = DAU1DCondWrapper(**diffae_config["diffusion"]["config"])
756
+ elif diffusion_model_type == "adp_1d":
757
+ diffusion = UNet1DCondWrapper(**diffae_config["diffusion"]["config"])
758
+ elif diffusion_model_type == "dit":
759
+ diffusion = DiTWrapper(**diffae_config["diffusion"]["config"])
760
+
761
+ latent_dim = diffae_config.get("latent_dim", None)
762
+ assert latent_dim is not None, "latent_dim must be specified in model config"
763
+ downsampling_ratio = diffae_config.get("downsampling_ratio", None)
764
+ assert downsampling_ratio is not None, "downsampling_ratio must be specified in model config"
765
+ io_channels = diffae_config.get("io_channels", None)
766
+ assert io_channels is not None, "io_channels must be specified in model config"
767
+ sample_rate = config.get("sample_rate", None)
768
+ assert sample_rate is not None, "sample_rate must be specified in model config"
769
+
770
+ bottleneck = diffae_config.get("bottleneck", None)
771
+
772
+ pretransform = diffae_config.get("pretransform", None)
773
+
774
+ if pretransform is not None:
775
+ pretransform = create_pretransform_from_config(pretransform, sample_rate)
776
+
777
+ if bottleneck is not None:
778
+ bottleneck = create_bottleneck_from_config(bottleneck)
779
+
780
+ diffusion_downsampling_ratio = None,
781
+
782
+ if diffusion_model_type == "DAU1d":
783
+ diffusion_downsampling_ratio = np.prod(diffae_config["diffusion"]["config"]["strides"])
784
+ elif diffusion_model_type == "adp_1d":
785
+ diffusion_downsampling_ratio = np.prod(diffae_config["diffusion"]["config"]["factors"])
786
+ elif diffusion_model_type == "dit":
787
+ diffusion_downsampling_ratio = 1
788
+
789
+ return DiffusionAutoencoder(
790
+ encoder=encoder,
791
+ decoder=decoder,
792
+ diffusion=diffusion,
793
+ io_channels=io_channels,
794
+ sample_rate=sample_rate,
795
+ latent_dim=latent_dim,
796
+ downsampling_ratio=downsampling_ratio,
797
+ diffusion_downsampling_ratio=diffusion_downsampling_ratio,
798
+ bottleneck=bottleneck,
799
+ pretransform=pretransform
800
+ )
ThinkSound/models/blocks.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import reduce
2
+ import math
3
+ import numpy as np
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+ from torch.backends.cuda import sdp_kernel
9
+ from packaging import version
10
+
11
+ from dac.nn.layers import Snake1d
12
+
13
+ class ResidualBlock(nn.Module):
14
+ def __init__(self, main, skip=None):
15
+ super().__init__()
16
+ self.main = nn.Sequential(*main)
17
+ self.skip = skip if skip else nn.Identity()
18
+
19
+ def forward(self, input):
20
+ return self.main(input) + self.skip(input)
21
+
22
+ class ResConvBlock(ResidualBlock):
23
+ def __init__(self, c_in, c_mid, c_out, is_last=False, kernel_size=5, conv_bias=True, use_snake=False):
24
+ skip = None if c_in == c_out else nn.Conv1d(c_in, c_out, 1, bias=False)
25
+ super().__init__([
26
+ nn.Conv1d(c_in, c_mid, kernel_size, padding=kernel_size//2, bias=conv_bias),
27
+ nn.GroupNorm(1, c_mid),
28
+ Snake1d(c_mid) if use_snake else nn.GELU(),
29
+ nn.Conv1d(c_mid, c_out, kernel_size, padding=kernel_size//2, bias=conv_bias),
30
+ nn.GroupNorm(1, c_out) if not is_last else nn.Identity(),
31
+ (Snake1d(c_out) if use_snake else nn.GELU()) if not is_last else nn.Identity(),
32
+ ], skip)
33
+
34
+ class SelfAttention1d(nn.Module):
35
+ def __init__(self, c_in, n_head=1, dropout_rate=0.):
36
+ super().__init__()
37
+ assert c_in % n_head == 0
38
+ self.norm = nn.GroupNorm(1, c_in)
39
+ self.n_head = n_head
40
+ self.qkv_proj = nn.Conv1d(c_in, c_in * 3, 1)
41
+ self.out_proj = nn.Conv1d(c_in, c_in, 1)
42
+ self.dropout = nn.Dropout(dropout_rate, inplace=True)
43
+
44
+ self.use_flash = torch.cuda.is_available() and version.parse(torch.__version__) >= version.parse('2.0.0')
45
+
46
+ if not self.use_flash:
47
+ return
48
+
49
+ device_properties = torch.cuda.get_device_properties(torch.device('cuda'))
50
+
51
+ if device_properties.major == 8 and device_properties.minor == 0:
52
+ # Use flash attention for A100 GPUs
53
+ self.sdp_kernel_config = (True, False, False)
54
+ else:
55
+ # Don't use flash attention for other GPUs
56
+ self.sdp_kernel_config = (False, True, True)
57
+
58
+ def forward(self, input):
59
+ n, c, s = input.shape
60
+ qkv = self.qkv_proj(self.norm(input))
61
+ qkv = qkv.view(
62
+ [n, self.n_head * 3, c // self.n_head, s]).transpose(2, 3)
63
+ q, k, v = qkv.chunk(3, dim=1)
64
+ scale = k.shape[3]**-0.25
65
+
66
+ if self.use_flash:
67
+ with sdp_kernel(*self.sdp_kernel_config):
68
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=False).contiguous().view([n, c, s])
69
+ else:
70
+ att = ((q * scale) @ (k.transpose(2, 3) * scale)).softmax(3)
71
+ y = (att @ v).transpose(2, 3).contiguous().view([n, c, s])
72
+
73
+
74
+ return input + self.dropout(self.out_proj(y))
75
+
76
+ class SkipBlock(nn.Module):
77
+ def __init__(self, *main):
78
+ super().__init__()
79
+ self.main = nn.Sequential(*main)
80
+
81
+ def forward(self, input):
82
+ return torch.cat([self.main(input), input], dim=1)
83
+
84
+ class FourierFeatures(nn.Module):
85
+ def __init__(self, in_features, out_features, std=1.):
86
+ super().__init__()
87
+ assert out_features % 2 == 0
88
+ self.weight = nn.Parameter(torch.randn(
89
+ [out_features // 2, in_features]) * std)
90
+
91
+ def forward(self, input):
92
+ f = 2 * math.pi * input @ self.weight.T
93
+ return torch.cat([f.cos(), f.sin()], dim=-1)
94
+
95
+ def expand_to_planes(input, shape):
96
+ return input[..., None].repeat([1, 1, shape[2]])
97
+
98
+ _kernels = {
99
+ 'linear':
100
+ [1 / 8, 3 / 8, 3 / 8, 1 / 8],
101
+ 'cubic':
102
+ [-0.01171875, -0.03515625, 0.11328125, 0.43359375,
103
+ 0.43359375, 0.11328125, -0.03515625, -0.01171875],
104
+ 'lanczos3':
105
+ [0.003689131001010537, 0.015056144446134567, -0.03399861603975296,
106
+ -0.066637322306633, 0.13550527393817902, 0.44638532400131226,
107
+ 0.44638532400131226, 0.13550527393817902, -0.066637322306633,
108
+ -0.03399861603975296, 0.015056144446134567, 0.003689131001010537]
109
+ }
110
+
111
+ class Downsample1d(nn.Module):
112
+ def __init__(self, kernel='linear', pad_mode='reflect', channels_last=False):
113
+ super().__init__()
114
+ self.pad_mode = pad_mode
115
+ kernel_1d = torch.tensor(_kernels[kernel])
116
+ self.pad = kernel_1d.shape[0] // 2 - 1
117
+ self.register_buffer('kernel', kernel_1d)
118
+ self.channels_last = channels_last
119
+
120
+ def forward(self, x):
121
+ if self.channels_last:
122
+ x = x.permute(0, 2, 1)
123
+ x = F.pad(x, (self.pad,) * 2, self.pad_mode)
124
+ weight = x.new_zeros([x.shape[1], x.shape[1], self.kernel.shape[0]])
125
+ indices = torch.arange(x.shape[1], device=x.device)
126
+ weight[indices, indices] = self.kernel.to(weight)
127
+ x = F.conv1d(x, weight, stride=2)
128
+ if self.channels_last:
129
+ x = x.permute(0, 2, 1)
130
+ return x
131
+
132
+
133
+ class Upsample1d(nn.Module):
134
+ def __init__(self, kernel='linear', pad_mode='reflect', channels_last=False):
135
+ super().__init__()
136
+ self.pad_mode = pad_mode
137
+ kernel_1d = torch.tensor(_kernels[kernel]) * 2
138
+ self.pad = kernel_1d.shape[0] // 2 - 1
139
+ self.register_buffer('kernel', kernel_1d)
140
+ self.channels_last = channels_last
141
+
142
+ def forward(self, x):
143
+ if self.channels_last:
144
+ x = x.permute(0, 2, 1)
145
+ x = F.pad(x, ((self.pad + 1) // 2,) * 2, self.pad_mode)
146
+ weight = x.new_zeros([x.shape[1], x.shape[1], self.kernel.shape[0]])
147
+ indices = torch.arange(x.shape[1], device=x.device)
148
+ weight[indices, indices] = self.kernel.to(weight)
149
+ x = F.conv_transpose1d(x, weight, stride=2, padding=self.pad * 2 + 1)
150
+ if self.channels_last:
151
+ x = x.permute(0, 2, 1)
152
+ return x
153
+
154
+ def Downsample1d_2(
155
+ in_channels: int, out_channels: int, factor: int, kernel_multiplier: int = 2
156
+ ) -> nn.Module:
157
+ assert kernel_multiplier % 2 == 0, "Kernel multiplier must be even"
158
+
159
+ return nn.Conv1d(
160
+ in_channels=in_channels,
161
+ out_channels=out_channels,
162
+ kernel_size=factor * kernel_multiplier + 1,
163
+ stride=factor,
164
+ padding=factor * (kernel_multiplier // 2),
165
+ )
166
+
167
+
168
+ def Upsample1d_2(
169
+ in_channels: int, out_channels: int, factor: int, use_nearest: bool = False
170
+ ) -> nn.Module:
171
+
172
+ if factor == 1:
173
+ return nn.Conv1d(
174
+ in_channels=in_channels, out_channels=out_channels, kernel_size=3, padding=1
175
+ )
176
+
177
+ if use_nearest:
178
+ return nn.Sequential(
179
+ nn.Upsample(scale_factor=factor, mode="nearest"),
180
+ nn.Conv1d(
181
+ in_channels=in_channels,
182
+ out_channels=out_channels,
183
+ kernel_size=3,
184
+ padding=1,
185
+ ),
186
+ )
187
+ else:
188
+ return nn.ConvTranspose1d(
189
+ in_channels=in_channels,
190
+ out_channels=out_channels,
191
+ kernel_size=factor * 2,
192
+ stride=factor,
193
+ padding=factor // 2 + factor % 2,
194
+ output_padding=factor % 2,
195
+ )
196
+
197
+ def zero_init(layer):
198
+ nn.init.zeros_(layer.weight)
199
+ if layer.bias is not None:
200
+ nn.init.zeros_(layer.bias)
201
+ return layer
202
+
203
+ def rms_norm(x, scale, eps):
204
+ dtype = reduce(torch.promote_types, (x.dtype, scale.dtype, torch.float32))
205
+ mean_sq = torch.mean(x.to(dtype)**2, dim=-1, keepdim=True)
206
+ scale = scale.to(dtype) * torch.rsqrt(mean_sq + eps)
207
+ return x * scale.to(x.dtype)
208
+
209
+ #rms_norm = torch.compile(rms_norm)
210
+
211
+ class AdaRMSNorm(nn.Module):
212
+ def __init__(self, features, cond_features, eps=1e-6):
213
+ super().__init__()
214
+ self.eps = eps
215
+ self.linear = zero_init(nn.Linear(cond_features, features, bias=False))
216
+
217
+ def extra_repr(self):
218
+ return f"eps={self.eps},"
219
+
220
+ def forward(self, x, cond):
221
+ return rms_norm(x, self.linear(cond)[:, None, :] + 1, self.eps)
222
+
223
+ def normalize(x, eps=1e-4):
224
+ dim = list(range(1, x.ndim))
225
+ n = torch.linalg.vector_norm(x, dim=dim, keepdim=True)
226
+ alpha = np.sqrt(n.numel() / x.numel())
227
+ return x / torch.add(eps, n, alpha=alpha)
228
+
229
+ class ForcedWNConv1d(nn.Module):
230
+ def __init__(self, in_channels, out_channels, kernel_size=1):
231
+ super().__init__()
232
+ self.weight = nn.Parameter(torch.randn([out_channels, in_channels, kernel_size]))
233
+
234
+ def forward(self, x):
235
+ if self.training:
236
+ with torch.no_grad():
237
+ self.weight.copy_(normalize(self.weight))
238
+
239
+ fan_in = self.weight[0].numel()
240
+
241
+ w = normalize(self.weight) / math.sqrt(fan_in)
242
+
243
+ return F.conv1d(x, w, padding='same')
244
+
245
+ # Kernels
246
+
247
+ use_compile = True
248
+
249
+ def compile(function, *args, **kwargs):
250
+ if not use_compile:
251
+ return function
252
+ try:
253
+ return torch.compile(function, *args, **kwargs)
254
+ except RuntimeError:
255
+ return function
256
+
257
+
258
+ @compile
259
+ def linear_geglu(x, weight, bias=None):
260
+ x = x @ weight.mT
261
+ if bias is not None:
262
+ x = x + bias
263
+ x, gate = x.chunk(2, dim=-1)
264
+ return x * F.gelu(gate)
265
+
266
+
267
+ @compile
268
+ def rms_norm(x, scale, eps):
269
+ dtype = reduce(torch.promote_types, (x.dtype, scale.dtype, torch.float32))
270
+ mean_sq = torch.mean(x.to(dtype)**2, dim=-1, keepdim=True)
271
+ scale = scale.to(dtype) * torch.rsqrt(mean_sq + eps)
272
+ return x * scale.to(x.dtype)
273
+
274
+ # Layers
275
+
276
+ class LinearGEGLU(nn.Linear):
277
+ def __init__(self, in_features, out_features, bias=True):
278
+ super().__init__(in_features, out_features * 2, bias=bias)
279
+ self.out_features = out_features
280
+
281
+ def forward(self, x):
282
+ return linear_geglu(x, self.weight, self.bias)
283
+
284
+
285
+ class RMSNorm(nn.Module):
286
+ def __init__(self, shape, fix_scale = False, eps=1e-6):
287
+ super().__init__()
288
+ self.eps = eps
289
+
290
+ if fix_scale:
291
+ self.register_buffer("scale", torch.ones(shape))
292
+ else:
293
+ self.scale = nn.Parameter(torch.ones(shape))
294
+
295
+ def extra_repr(self):
296
+ return f"shape={tuple(self.scale.shape)}, eps={self.eps}"
297
+
298
+ def forward(self, x):
299
+ return rms_norm(x, self.scale, self.eps)
300
+
301
+ def snake_beta(x, alpha, beta):
302
+ return x + (1.0 / (beta + 0.000000001)) * pow(torch.sin(x * alpha), 2)
303
+
304
+ # try:
305
+ # snake_beta = torch.compile(snake_beta)
306
+ # except RuntimeError:
307
+ # pass
308
+
309
+ # Adapted from https://github.com/NVIDIA/BigVGAN/blob/main/activations.py under MIT license
310
+ # License available in LICENSES/LICENSE_NVIDIA.txt
311
+ class SnakeBeta(nn.Module):
312
+
313
+ def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=True):
314
+ super(SnakeBeta, self).__init__()
315
+ self.in_features = in_features
316
+
317
+ # initialize alpha
318
+ self.alpha_logscale = alpha_logscale
319
+ if self.alpha_logscale: # log scale alphas initialized to zeros
320
+ self.alpha = nn.Parameter(torch.zeros(in_features) * alpha)
321
+ self.beta = nn.Parameter(torch.zeros(in_features) * alpha)
322
+ else: # linear scale alphas initialized to ones
323
+ self.alpha = nn.Parameter(torch.ones(in_features) * alpha)
324
+ self.beta = nn.Parameter(torch.ones(in_features) * alpha)
325
+
326
+ self.alpha.requires_grad = alpha_trainable
327
+ self.beta.requires_grad = alpha_trainable
328
+
329
+ self.no_div_by_zero = 0.000000001
330
+
331
+ def forward(self, x):
332
+ alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T]
333
+ beta = self.beta.unsqueeze(0).unsqueeze(-1)
334
+ if self.alpha_logscale:
335
+ alpha = torch.exp(alpha)
336
+ beta = torch.exp(beta)
337
+ x = snake_beta(x, alpha, beta)
338
+
339
+ return x
ThinkSound/models/bottleneck.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn import functional as F
5
+
6
+ from einops import rearrange
7
+ from vector_quantize_pytorch import ResidualVQ, FSQ
8
+ from dac.nn.quantize import ResidualVectorQuantize as DACResidualVQ
9
+
10
+ class Bottleneck(nn.Module):
11
+ def __init__(self, is_discrete: bool = False):
12
+ super().__init__()
13
+
14
+ self.is_discrete = is_discrete
15
+
16
+ def encode(self, x, return_info=False, **kwargs):
17
+ raise NotImplementedError
18
+
19
+ def decode(self, x):
20
+ raise NotImplementedError
21
+
22
+ class DiscreteBottleneck(Bottleneck):
23
+ def __init__(self, num_quantizers, codebook_size, tokens_id):
24
+ super().__init__(is_discrete=True)
25
+
26
+ self.num_quantizers = num_quantizers
27
+ self.codebook_size = codebook_size
28
+ self.tokens_id = tokens_id
29
+
30
+ def decode_tokens(self, codes, **kwargs):
31
+ raise NotImplementedError
32
+
33
+ class TanhBottleneck(Bottleneck):
34
+ def __init__(self):
35
+ super().__init__(is_discrete=False)
36
+ self.tanh = nn.Tanh()
37
+
38
+ def encode(self, x, return_info=False):
39
+ info = {}
40
+
41
+ x = torch.tanh(x)
42
+
43
+ if return_info:
44
+ return x, info
45
+ else:
46
+ return x
47
+
48
+ def decode(self, x):
49
+ return x
50
+
51
+ def vae_sample(mean, scale):
52
+ stdev = nn.functional.softplus(scale) + 1e-4
53
+ var = stdev * stdev
54
+ logvar = torch.log(var)
55
+ latents = torch.randn_like(mean) * stdev + mean
56
+
57
+ kl = (mean * mean + var - logvar - 1).sum(1).mean()
58
+
59
+ return latents, kl
60
+
61
+ class VAEBottleneck(Bottleneck):
62
+ def __init__(self):
63
+ super().__init__(is_discrete=False)
64
+
65
+ def encode(self, x, return_info=False, **kwargs):
66
+ info = {}
67
+
68
+ mean, scale = x.chunk(2, dim=1)
69
+
70
+ x, kl = vae_sample(mean, scale)
71
+
72
+ info["kl"] = kl
73
+
74
+ if return_info:
75
+ return x, info
76
+ else:
77
+ return x
78
+
79
+ def decode(self, x):
80
+ return x
81
+
82
+ def compute_mean_kernel(x, y):
83
+ kernel_input = (x[:, None] - y[None]).pow(2).mean(2) / x.shape[-1]
84
+ return torch.exp(-kernel_input).mean()
85
+
86
+ def compute_mmd(latents):
87
+ latents_reshaped = latents.permute(0, 2, 1).reshape(-1, latents.shape[1])
88
+ noise = torch.randn_like(latents_reshaped)
89
+
90
+ latents_kernel = compute_mean_kernel(latents_reshaped, latents_reshaped)
91
+ noise_kernel = compute_mean_kernel(noise, noise)
92
+ latents_noise_kernel = compute_mean_kernel(latents_reshaped, noise)
93
+
94
+ mmd = latents_kernel + noise_kernel - 2 * latents_noise_kernel
95
+ return mmd.mean()
96
+
97
+ class WassersteinBottleneck(Bottleneck):
98
+ def __init__(self, noise_augment_dim: int = 0, bypass_mmd: bool = False):
99
+ super().__init__(is_discrete=False)
100
+
101
+ self.noise_augment_dim = noise_augment_dim
102
+ self.bypass_mmd = bypass_mmd
103
+
104
+ def encode(self, x, return_info=False):
105
+ info = {}
106
+
107
+ if self.training and return_info:
108
+ if self.bypass_mmd:
109
+ mmd = torch.tensor(0.0)
110
+ else:
111
+ mmd = compute_mmd(x)
112
+
113
+ info["mmd"] = mmd
114
+
115
+ if return_info:
116
+ return x, info
117
+
118
+ return x
119
+
120
+ def decode(self, x):
121
+
122
+ if self.noise_augment_dim > 0:
123
+ noise = torch.randn(x.shape[0], self.noise_augment_dim,
124
+ x.shape[-1]).type_as(x)
125
+ x = torch.cat([x, noise], dim=1)
126
+
127
+ return x
128
+
129
+ class L2Bottleneck(Bottleneck):
130
+ def __init__(self):
131
+ super().__init__(is_discrete=False)
132
+
133
+ def encode(self, x, return_info=False):
134
+ info = {}
135
+
136
+ x = F.normalize(x, dim=1)
137
+
138
+ if return_info:
139
+ return x, info
140
+ else:
141
+ return x
142
+
143
+ def decode(self, x):
144
+ return F.normalize(x, dim=1)
145
+
146
+ class RVQBottleneck(DiscreteBottleneck):
147
+ def __init__(self, **quantizer_kwargs):
148
+ super().__init__(num_quantizers = quantizer_kwargs["num_quantizers"], codebook_size = quantizer_kwargs["codebook_size"], tokens_id = "quantizer_indices")
149
+ self.quantizer = ResidualVQ(**quantizer_kwargs)
150
+ self.num_quantizers = quantizer_kwargs["num_quantizers"]
151
+
152
+ def encode(self, x, return_info=False, **kwargs):
153
+ info = {}
154
+
155
+ x = rearrange(x, "b c n -> b n c")
156
+ x, indices, loss = self.quantizer(x)
157
+ x = rearrange(x, "b n c -> b c n")
158
+
159
+ info["quantizer_indices"] = indices
160
+ info["quantizer_loss"] = loss.mean()
161
+
162
+ if return_info:
163
+ return x, info
164
+ else:
165
+ return x
166
+
167
+ def decode(self, x):
168
+ return x
169
+
170
+ def decode_tokens(self, codes, **kwargs):
171
+ latents = self.quantizer.get_outputs_from_indices(codes)
172
+
173
+ return self.decode(latents, **kwargs)
174
+
175
+ class RVQVAEBottleneck(DiscreteBottleneck):
176
+ def __init__(self, **quantizer_kwargs):
177
+ super().__init__(num_quantizers = quantizer_kwargs["num_quantizers"], codebook_size = quantizer_kwargs["codebook_size"], tokens_id = "quantizer_indices")
178
+ self.quantizer = ResidualVQ(**quantizer_kwargs)
179
+ self.num_quantizers = quantizer_kwargs["num_quantizers"]
180
+
181
+ def encode(self, x, return_info=False):
182
+ info = {}
183
+
184
+ x, kl = vae_sample(*x.chunk(2, dim=1))
185
+
186
+ info["kl"] = kl
187
+
188
+ x = rearrange(x, "b c n -> b n c")
189
+ x, indices, loss = self.quantizer(x)
190
+ x = rearrange(x, "b n c -> b c n")
191
+
192
+ info["quantizer_indices"] = indices
193
+ info["quantizer_loss"] = loss.mean()
194
+
195
+ if return_info:
196
+ return x, info
197
+ else:
198
+ return x
199
+
200
+ def decode(self, x):
201
+ return x
202
+
203
+ def decode_tokens(self, codes, **kwargs):
204
+ latents = self.quantizer.get_outputs_from_indices(codes)
205
+
206
+ return self.decode(latents, **kwargs)
207
+
208
+ class DACRVQBottleneck(DiscreteBottleneck):
209
+ def __init__(self, quantize_on_decode=False, noise_augment_dim=0, **quantizer_kwargs):
210
+ super().__init__(num_quantizers = quantizer_kwargs["n_codebooks"], codebook_size = quantizer_kwargs["codebook_size"], tokens_id = "codes")
211
+ self.quantizer = DACResidualVQ(**quantizer_kwargs)
212
+ self.num_quantizers = quantizer_kwargs["n_codebooks"]
213
+ self.quantize_on_decode = quantize_on_decode
214
+ self.noise_augment_dim = noise_augment_dim
215
+
216
+ def encode(self, x, return_info=False, **kwargs):
217
+ info = {}
218
+
219
+ info["pre_quantizer"] = x
220
+
221
+ if self.quantize_on_decode:
222
+ return x, info if return_info else x
223
+
224
+ z, codes, latents, commitment_loss, codebook_loss = self.quantizer(x, **kwargs)
225
+
226
+ output = {
227
+ "z": z,
228
+ "codes": codes,
229
+ "latents": latents,
230
+ "vq/commitment_loss": commitment_loss,
231
+ "vq/codebook_loss": codebook_loss,
232
+ }
233
+
234
+ output["vq/commitment_loss"] /= self.num_quantizers
235
+ output["vq/codebook_loss"] /= self.num_quantizers
236
+
237
+ info.update(output)
238
+
239
+ if return_info:
240
+ return output["z"], info
241
+
242
+ return output["z"]
243
+
244
+ def decode(self, x):
245
+
246
+ if self.quantize_on_decode:
247
+ x = self.quantizer(x)[0]
248
+
249
+ if self.noise_augment_dim > 0:
250
+ noise = torch.randn(x.shape[0], self.noise_augment_dim,
251
+ x.shape[-1]).type_as(x)
252
+ x = torch.cat([x, noise], dim=1)
253
+
254
+ return x
255
+
256
+ def decode_tokens(self, codes, **kwargs):
257
+ latents, _, _ = self.quantizer.from_codes(codes)
258
+
259
+ return self.decode(latents, **kwargs)
260
+
261
+ class DACRVQVAEBottleneck(DiscreteBottleneck):
262
+ def __init__(self, quantize_on_decode=False, **quantizer_kwargs):
263
+ super().__init__(num_quantizers = quantizer_kwargs["n_codebooks"], codebook_size = quantizer_kwargs["codebook_size"], tokens_id = "codes")
264
+ self.quantizer = DACResidualVQ(**quantizer_kwargs)
265
+ self.num_quantizers = quantizer_kwargs["n_codebooks"]
266
+ self.quantize_on_decode = quantize_on_decode
267
+
268
+ def encode(self, x, return_info=False, n_quantizers: int = None):
269
+ info = {}
270
+
271
+ mean, scale = x.chunk(2, dim=1)
272
+
273
+ x, kl = vae_sample(mean, scale)
274
+
275
+ info["pre_quantizer"] = x
276
+ info["kl"] = kl
277
+
278
+ if self.quantize_on_decode:
279
+ return x, info if return_info else x
280
+
281
+ z, codes, latents, commitment_loss, codebook_loss = self.quantizer(x, n_quantizers=n_quantizers)
282
+
283
+ output = {
284
+ "z": z,
285
+ "codes": codes,
286
+ "latents": latents,
287
+ "vq/commitment_loss": commitment_loss,
288
+ "vq/codebook_loss": codebook_loss,
289
+ }
290
+
291
+ output["vq/commitment_loss"] /= self.num_quantizers
292
+ output["vq/codebook_loss"] /= self.num_quantizers
293
+
294
+ info.update(output)
295
+
296
+ if return_info:
297
+ return output["z"], info
298
+
299
+ return output["z"]
300
+
301
+ def decode(self, x):
302
+
303
+ if self.quantize_on_decode:
304
+ x = self.quantizer(x)[0]
305
+
306
+ return x
307
+
308
+ def decode_tokens(self, codes, **kwargs):
309
+ latents, _, _ = self.quantizer.from_codes(codes)
310
+
311
+ return self.decode(latents, **kwargs)
312
+
313
+ class FSQBottleneck(DiscreteBottleneck):
314
+ def __init__(self, noise_augment_dim=0, **kwargs):
315
+ super().__init__(num_quantizers = kwargs.get("num_codebooks", 1), codebook_size = np.prod(kwargs["levels"]), tokens_id = "quantizer_indices")
316
+
317
+ self.noise_augment_dim = noise_augment_dim
318
+
319
+ self.quantizer = FSQ(**kwargs, allowed_dtypes=[torch.float16, torch.float32, torch.float64])
320
+
321
+ def encode(self, x, return_info=False):
322
+ info = {}
323
+
324
+ orig_dtype = x.dtype
325
+ x = x.float()
326
+
327
+ x = rearrange(x, "b c n -> b n c")
328
+ x, indices = self.quantizer(x)
329
+ x = rearrange(x, "b n c -> b c n")
330
+
331
+ x = x.to(orig_dtype)
332
+
333
+ # Reorder indices to match the expected format
334
+ indices = rearrange(indices, "b n q -> b q n")
335
+
336
+ info["quantizer_indices"] = indices
337
+
338
+ if return_info:
339
+ return x, info
340
+ else:
341
+ return x
342
+
343
+ def decode(self, x):
344
+
345
+ if self.noise_augment_dim > 0:
346
+ noise = torch.randn(x.shape[0], self.noise_augment_dim,
347
+ x.shape[-1]).type_as(x)
348
+ x = torch.cat([x, noise], dim=1)
349
+
350
+ return x
351
+
352
+ def decode_tokens(self, tokens, **kwargs):
353
+ latents = self.quantizer.indices_to_codes(tokens)
354
+
355
+ return self.decode(latents, **kwargs)
ThinkSound/models/codebook_patterns.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from https://github.com/facebookresearch/audiocraft/blob/main/audiocraft/modules/codebooks_patterns.py under MIT License
2
+ # License available in LICENSES/LICENSE_META.txt
3
+
4
+ from collections import namedtuple
5
+ from dataclasses import dataclass
6
+ from functools import lru_cache
7
+ import logging
8
+ import typing as tp
9
+
10
+ from abc import ABC, abstractmethod
11
+ import torch
12
+
13
+ LayoutCoord = namedtuple('LayoutCoord', ['t', 'q']) # (timestep, codebook index)
14
+ PatternLayout = tp.List[tp.List[LayoutCoord]] # Sequence of coordinates
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ @dataclass
19
+ class Pattern:
20
+ """Base implementation of a pattern over a sequence with multiple codebooks.
21
+
22
+ The codebook pattern consists in a layout, defining for each sequence step
23
+ the list of coordinates of each codebook timestep in the resulting interleaved sequence.
24
+ The first item of the pattern is always an empty list in order to properly insert a special token
25
+ to start with. For convenience, we also keep track of ``n_q`` the number of codebooks used for the pattern
26
+ and ``timesteps`` the number of timesteps corresponding to the original sequence.
27
+
28
+ The pattern provides convenient methods to build and revert interleaved sequences from it:
29
+ ``build_pattern_sequence`` maps a given a dense input tensor of multi-codebook sequence from [B, K, T]
30
+ to the interleaved sequence of shape [B, K, S] applying the pattern, with B being the batch size,
31
+ K being the number of codebooks, T the number of original timesteps and S the number of sequence steps
32
+ for the output sequence. The unfilled positions are replaced with a special token and the built sequence
33
+ is returned along with a mask indicating valid tokens.
34
+ ``revert_pattern_sequence`` maps back an interleaved sequence of shape [B, K, S] to the original alignment
35
+ of codebooks across timesteps to an output tensor of shape [B, K, T], using again a special token and a mask
36
+ to fill and specify invalid positions if needed.
37
+ See the dedicated methods for more details.
38
+ """
39
+ # Pattern layout, for each sequence step, we have a list of coordinates
40
+ # corresponding to the original codebook timestep and position.
41
+ # The first list is always an empty list in order to properly insert
42
+ # a special token to start with.
43
+ layout: PatternLayout
44
+ timesteps: int
45
+ n_q: int
46
+
47
+ def __post_init__(self):
48
+ assert len(self.layout) > 0
49
+ self._validate_layout()
50
+ self._build_reverted_sequence_scatter_indexes = lru_cache(100)(self._build_reverted_sequence_scatter_indexes)
51
+ self._build_pattern_sequence_scatter_indexes = lru_cache(100)(self._build_pattern_sequence_scatter_indexes)
52
+ logger.info("New pattern, time steps: %d, sequence steps: %d", self.timesteps, len(self.layout))
53
+
54
+ def _validate_layout(self):
55
+ """Runs checks on the layout to ensure a valid pattern is defined.
56
+ A pattern is considered invalid if:
57
+ - Multiple timesteps for a same codebook are defined in the same sequence step
58
+ - The timesteps for a given codebook are not in ascending order as we advance in the sequence
59
+ (this would mean that we have future timesteps before past timesteps).
60
+ """
61
+ q_timesteps = {q: 0 for q in range(self.n_q)}
62
+ for s, seq_coords in enumerate(self.layout):
63
+ if len(seq_coords) > 0:
64
+ qs = set()
65
+ for coord in seq_coords:
66
+ qs.add(coord.q)
67
+ last_q_timestep = q_timesteps[coord.q]
68
+ assert coord.t >= last_q_timestep, \
69
+ f"Past timesteps are found in the sequence for codebook = {coord.q} at step {s}"
70
+ q_timesteps[coord.q] = coord.t
71
+ # each sequence step contains at max 1 coordinate per codebook
72
+ assert len(qs) == len(seq_coords), \
73
+ f"Multiple entries for a same codebook are found at step {s}"
74
+
75
+ @property
76
+ def num_sequence_steps(self):
77
+ return len(self.layout) - 1
78
+
79
+ @property
80
+ def max_delay(self):
81
+ max_t_in_seq_coords = 0
82
+ for seq_coords in self.layout[1:]:
83
+ for coords in seq_coords:
84
+ max_t_in_seq_coords = max(max_t_in_seq_coords, coords.t + 1)
85
+ return max_t_in_seq_coords - self.timesteps
86
+
87
+ @property
88
+ def valid_layout(self):
89
+ valid_step = len(self.layout) - self.max_delay
90
+ return self.layout[:valid_step]
91
+
92
+ def starts_with_special_token(self):
93
+ return self.layout[0] == []
94
+
95
+ def get_sequence_coords_with_timestep(self, t: int, q: tp.Optional[int] = None):
96
+ """Get codebook coordinates in the layout that corresponds to the specified timestep t
97
+ and optionally to the codebook q. Coordinates are returned as a tuple with the sequence step
98
+ and the actual codebook coordinates.
99
+ """
100
+ assert t <= self.timesteps, "provided timesteps is greater than the pattern's number of timesteps"
101
+ if q is not None:
102
+ assert q <= self.n_q, "provided number of codebooks is greater than the pattern's number of codebooks"
103
+ coords = []
104
+ for s, seq_codes in enumerate(self.layout):
105
+ for code in seq_codes:
106
+ if code.t == t and (q is None or code.q == q):
107
+ coords.append((s, code))
108
+ return coords
109
+
110
+ def get_steps_with_timestep(self, t: int, q: tp.Optional[int] = None) -> tp.List[int]:
111
+ return [step for step, coords in self.get_sequence_coords_with_timestep(t, q)]
112
+
113
+ def get_first_step_with_timesteps(self, t: int, q: tp.Optional[int] = None) -> tp.Optional[int]:
114
+ steps_with_timesteps = self.get_steps_with_timestep(t, q)
115
+ return steps_with_timesteps[0] if len(steps_with_timesteps) > 0 else None
116
+
117
+ def _build_pattern_sequence_scatter_indexes(self, timesteps: int, n_q: int, keep_only_valid_steps: bool,
118
+ device: tp.Union[torch.device, str] = 'cpu'):
119
+ """Build scatter indexes corresponding to the pattern, up to the provided sequence_steps.
120
+
121
+ Args:
122
+ timesteps (int): Maximum number of timesteps steps to consider.
123
+ keep_only_valid_steps (bool): Restrict the pattern layout to match only valid steps.
124
+ device (torch.device or str): Device for created tensors.
125
+ Returns:
126
+ indexes (torch.Tensor): Indexes corresponding to the sequence, of shape [K, S].
127
+ mask (torch.Tensor): Mask corresponding to indexes that matches valid indexes, of shape [K, S].
128
+ """
129
+ assert n_q == self.n_q, f"invalid number of codebooks for the sequence and the pattern: {n_q} != {self.n_q}"
130
+ assert timesteps <= self.timesteps, "invalid number of timesteps used to build the sequence from the pattern"
131
+ # use the proper layout based on whether we limit ourselves to valid steps only or not,
132
+ # note that using the valid_layout will result in a truncated sequence up to the valid steps
133
+ ref_layout = self.valid_layout if keep_only_valid_steps else self.layout
134
+ # single item indexing being super slow with pytorch vs. numpy, so we use numpy here
135
+ indexes = torch.zeros(n_q, len(ref_layout), dtype=torch.long).numpy()
136
+ mask = torch.zeros(n_q, len(ref_layout), dtype=torch.bool).numpy()
137
+ # fill indexes with last sequence step value that will correspond to our special token
138
+ # the last value is n_q * timesteps as we have flattened z and append special token as the last token
139
+ # which will correspond to the index: n_q * timesteps
140
+ indexes[:] = n_q * timesteps
141
+ # iterate over the pattern and fill scattered indexes and mask
142
+ for s, sequence_coords in enumerate(ref_layout):
143
+ for coords in sequence_coords:
144
+ if coords.t < timesteps:
145
+ indexes[coords.q, s] = coords.t + coords.q * timesteps
146
+ mask[coords.q, s] = 1
147
+ indexes = torch.from_numpy(indexes).to(device)
148
+ mask = torch.from_numpy(mask).to(device)
149
+ return indexes, mask
150
+
151
+ def build_pattern_sequence(self, z: torch.Tensor, special_token: int, keep_only_valid_steps: bool = False):
152
+ """Build sequence corresponding to the pattern from the input tensor z.
153
+ The sequence is built using up to sequence_steps if specified, and non-pattern
154
+ coordinates are filled with the special token.
155
+
156
+ Args:
157
+ z (torch.Tensor): Input tensor of multi-codebooks sequence, of shape [B, K, T].
158
+ special_token (int): Special token used to fill non-pattern coordinates in the new sequence.
159
+ keep_only_valid_steps (bool): Build a sequence from the pattern up to valid (= fully defined) steps.
160
+ Steps that are beyond valid steps will be replaced by the special_token in that case.
161
+ Returns:
162
+ values (torch.Tensor): Interleaved sequence matching the pattern, of shape [B, K, S] with S
163
+ corresponding either to the sequence_steps if provided, otherwise to the length of the pattern.
164
+ indexes (torch.Tensor): Indexes corresponding to the interleaved sequence, of shape [K, S].
165
+ mask (torch.Tensor): Mask corresponding to indexes that matches valid indexes of shape [K, S].
166
+ """
167
+ B, K, T = z.shape
168
+ indexes, mask = self._build_pattern_sequence_scatter_indexes(
169
+ T, K, keep_only_valid_steps=keep_only_valid_steps, device=str(z.device)
170
+ )
171
+ z = z.view(B, -1)
172
+ # we append the special token as the last index of our flattened z tensor
173
+ z = torch.cat([z, torch.zeros_like(z[:, :1]) + special_token], dim=1)
174
+ values = z[:, indexes.view(-1)]
175
+ values = values.view(B, K, indexes.shape[-1])
176
+ return values, indexes, mask
177
+
178
+ def _build_reverted_sequence_scatter_indexes(self, sequence_steps: int, n_q: int,
179
+ keep_only_valid_steps: bool = False,
180
+ is_model_output: bool = False,
181
+ device: tp.Union[torch.device, str] = 'cpu'):
182
+ """Builds scatter indexes required to retrieve the original multi-codebook sequence
183
+ from interleaving pattern.
184
+
185
+ Args:
186
+ sequence_steps (int): Sequence steps.
187
+ n_q (int): Number of codebooks.
188
+ keep_only_valid_steps (bool): Build a sequence from the pattern up to valid (= fully defined) steps.
189
+ Steps that are beyond valid steps will be replaced by the special_token in that case.
190
+ is_model_output (bool): Whether to keep the sequence item corresponding to initial special token or not.
191
+ device (torch.device or str): Device for created tensors.
192
+ Returns:
193
+ indexes (torch.Tensor): Indexes for reconstructing the output, of shape [K, T].
194
+ mask (torch.Tensor): Mask corresponding to indexes that matches valid indexes of shape [K, T].
195
+ """
196
+ ref_layout = self.valid_layout if keep_only_valid_steps else self.layout
197
+ # TODO(jade): Do we want to further truncate to only valid timesteps here as well?
198
+ timesteps = self.timesteps
199
+ assert n_q == self.n_q, f"invalid number of codebooks for the sequence and the pattern: {n_q} != {self.n_q}"
200
+ assert sequence_steps <= len(ref_layout), \
201
+ f"sequence to revert is longer than the defined pattern: {sequence_steps} > {len(ref_layout)}"
202
+
203
+ # ensure we take the appropriate indexes to keep the model output from the first special token as well
204
+ if is_model_output and self.starts_with_special_token():
205
+ ref_layout = ref_layout[1:]
206
+
207
+ # single item indexing being super slow with pytorch vs. numpy, so we use numpy here
208
+ indexes = torch.zeros(n_q, timesteps, dtype=torch.long).numpy()
209
+ mask = torch.zeros(n_q, timesteps, dtype=torch.bool).numpy()
210
+ # fill indexes with last sequence step value that will correspond to our special token
211
+ indexes[:] = n_q * sequence_steps
212
+ for s, sequence_codes in enumerate(ref_layout):
213
+ if s < sequence_steps:
214
+ for code in sequence_codes:
215
+ if code.t < timesteps:
216
+ indexes[code.q, code.t] = s + code.q * sequence_steps
217
+ mask[code.q, code.t] = 1
218
+ indexes = torch.from_numpy(indexes).to(device)
219
+ mask = torch.from_numpy(mask).to(device)
220
+ return indexes, mask
221
+
222
+ def revert_pattern_sequence(self, s: torch.Tensor, special_token: int, keep_only_valid_steps: bool = False):
223
+ """Revert a sequence built from the pattern back to the original multi-codebook sequence without interleaving.
224
+ The sequence is reverted using up to timesteps if specified, and non-pattern coordinates
225
+ are filled with the special token.
226
+
227
+ Args:
228
+ s (torch.Tensor): Interleaved sequence tensor obtained from the pattern, of shape [B, K, S].
229
+ special_token (int or float): Special token used to fill non-pattern coordinates in the new sequence.
230
+ Returns:
231
+ values (torch.Tensor): Interleaved sequence matching the pattern, of shape [B, K, T] with T
232
+ corresponding either to the timesteps if provided, or the total timesteps in pattern otherwise.
233
+ indexes (torch.Tensor): Indexes corresponding to the interleaved sequence, of shape [K, T].
234
+ mask (torch.Tensor): Mask corresponding to indexes that matches valid indexes of shape [K, T].
235
+ """
236
+ B, K, S = s.shape
237
+ indexes, mask = self._build_reverted_sequence_scatter_indexes(
238
+ S, K, keep_only_valid_steps, is_model_output=False, device=str(s.device)
239
+ )
240
+ s = s.view(B, -1)
241
+ # we append the special token as the last index of our flattened z tensor
242
+ s = torch.cat([s, torch.zeros_like(s[:, :1]) + special_token], dim=1)
243
+ values = s[:, indexes.view(-1)]
244
+ values = values.view(B, K, indexes.shape[-1])
245
+ return values, indexes, mask
246
+
247
+ def revert_pattern_logits(self, logits: torch.Tensor, special_token: float, keep_only_valid_steps: bool = False):
248
+ """Revert model logits obtained on a sequence built from the pattern
249
+ back to a tensor matching the original sequence.
250
+
251
+ This method is similar to ``revert_pattern_sequence`` with the following specificities:
252
+ 1. It is designed to work with the extra cardinality dimension
253
+ 2. We return the logits for the first sequence item that matches the special_token and
254
+ which matching target in the original sequence is the first item of the sequence,
255
+ while we skip the last logits as there is no matching target
256
+ """
257
+ B, card, K, S = logits.shape
258
+ indexes, mask = self._build_reverted_sequence_scatter_indexes(
259
+ S, K, keep_only_valid_steps, is_model_output=True, device=logits.device
260
+ )
261
+ logits = logits.reshape(B, card, -1)
262
+ # we append the special token as the last index of our flattened z tensor
263
+ logits = torch.cat([logits, torch.zeros_like(logits[:, :, :1]) + special_token], dim=-1) # [B, card, K x S]
264
+ values = logits[:, :, indexes.view(-1)]
265
+ values = values.view(B, card, K, indexes.shape[-1])
266
+ return values, indexes, mask
267
+
268
+
269
+ class CodebooksPatternProvider(ABC):
270
+ """Abstraction around providing pattern for interleaving codebooks.
271
+
272
+ The CodebooksPatternProvider abstraction allows to implement various strategies to
273
+ define interleaving pattern of sequences composed of multiple codebooks. For a given
274
+ number of codebooks `n_q`, the pattern provider can generate a specified pattern
275
+ corresponding to a sequence of `T` timesteps with `n_q` parallel codebooks. This pattern
276
+ can be used to construct a new sequence from the original codes respecting the specified
277
+ pattern. The pattern is defined as a list of list of code coordinates, code coordinate
278
+ being a tuple with the original timestep and codebook to build the new sequence.
279
+ Note that all patterns must start with an empty list that is then used to insert a first
280
+ sequence step of special tokens in the newly generated sequence.
281
+
282
+ Args:
283
+ n_q (int): number of codebooks.
284
+ cached (bool): if True, patterns for a given length are cached. In general
285
+ that should be true for efficiency reason to avoid synchronization points.
286
+ """
287
+ def __init__(self, n_q: int, cached: bool = True):
288
+ assert n_q > 0
289
+ self.n_q = n_q
290
+ self.get_pattern = lru_cache(100)(self.get_pattern) # type: ignore
291
+
292
+ @abstractmethod
293
+ def get_pattern(self, timesteps: int) -> Pattern:
294
+ """Builds pattern with specific interleaving between codebooks.
295
+
296
+ Args:
297
+ timesteps (int): Total number of timesteps.
298
+ """
299
+ raise NotImplementedError()
300
+
301
+
302
+ class DelayedPatternProvider(CodebooksPatternProvider):
303
+ """Provider for delayed pattern across delayed codebooks.
304
+ Codebooks are delayed in the sequence and sequence steps will contain codebooks
305
+ from different timesteps.
306
+
307
+ Example:
308
+ Taking timesteps=4 and n_q=3, delays=None, the multi-codebook sequence:
309
+ [[1, 2, 3, 4],
310
+ [1, 2, 3, 4],
311
+ [1, 2, 3, 4]]
312
+ The resulting sequence obtained from the returned pattern is:
313
+ [[S, 1, 2, 3, 4],
314
+ [S, S, 1, 2, 3],
315
+ [S, S, S, 1, 2]]
316
+ (with S being a special token)
317
+
318
+ Args:
319
+ n_q (int): Number of codebooks.
320
+ delays (list of int, optional): Delay for each of the codebooks.
321
+ If delays not defined, each codebook is delayed by 1 compared to the previous one.
322
+ flatten_first (int): Flatten the first N timesteps.
323
+ empty_initial (int): Prepend with N empty list of coordinates.
324
+ """
325
+ def __init__(self, n_q: int, delays: tp.Optional[tp.List[int]] = None,
326
+ flatten_first: int = 0, empty_initial: int = 0):
327
+ super().__init__(n_q)
328
+ if delays is None:
329
+ delays = list(range(n_q))
330
+ self.delays = delays
331
+ self.flatten_first = flatten_first
332
+ self.empty_initial = empty_initial
333
+ assert len(self.delays) == self.n_q
334
+ assert sorted(self.delays) == self.delays
335
+
336
+ def get_pattern(self, timesteps: int) -> Pattern:
337
+ omit_special_token = self.empty_initial < 0
338
+ out: PatternLayout = [] if omit_special_token else [[]]
339
+ max_delay = max(self.delays)
340
+ if self.empty_initial:
341
+ out += [[] for _ in range(self.empty_initial)]
342
+ if self.flatten_first:
343
+ for t in range(min(timesteps, self.flatten_first)):
344
+ for q in range(self.n_q):
345
+ out.append([LayoutCoord(t, q)])
346
+ for t in range(self.flatten_first, timesteps + max_delay):
347
+ v = []
348
+ for q, delay in enumerate(self.delays):
349
+ t_for_q = t - delay
350
+ if t_for_q >= self.flatten_first:
351
+ v.append(LayoutCoord(t_for_q, q))
352
+ out.append(v)
353
+ return Pattern(out, n_q=self.n_q, timesteps=timesteps)
354
+
355
+
356
+ class ParallelPatternProvider(DelayedPatternProvider):
357
+ """Provider for parallel pattern across codebooks.
358
+ This pattern provider is a special case of the delayed pattern with actually no delay,
359
+ hence delays=repeat(0, n_q).
360
+
361
+ Args:
362
+ n_q (int): Number of codebooks.
363
+ empty_initial (int): Prepend with N empty list of coordinates.
364
+ """
365
+ def __init__(self, n_q: int, empty_initial: int = 0):
366
+ super().__init__(n_q, [0] * n_q, empty_initial=empty_initial)
367
+
368
+
369
+ class UnrolledPatternProvider(CodebooksPatternProvider):
370
+ """Provider for unrolling codebooks pattern.
371
+ This pattern provider enables to represent the codebook flattened completely or only to some extend
372
+ while also specifying a given delay between the flattened codebooks representation, allowing to
373
+ unroll the codebooks in the sequence.
374
+
375
+ Example:
376
+ 1. Flattening of the codebooks.
377
+ By default, the pattern provider will fully flatten the codebooks such as flattening=range(n_q),
378
+ taking n_q = 3 and timesteps = 4:
379
+ [[1, 2, 3, 4],
380
+ [1, 2, 3, 4],
381
+ [1, 2, 3, 4]]
382
+ will result into:
383
+ [[S, S, 1, S, S, 2, S, S, 3, S, S, 4],
384
+ [S, 1, S, S, 2, S, S, 3, S, S, 4, S],
385
+ [1, S, S, 2, S, S, 3, S, S, 4, S, S]]
386
+ 2. Partial flattening of the codebooks. The ``flattening`` parameter allows to specify the inner step
387
+ for each of the codebook, allowing to define which codebook to flatten (or keep in parallel), for example
388
+ taking n_q = 3, timesteps = 4 and flattening = [0, 1, 1]:
389
+ [[1, 2, 3, 4],
390
+ [1, 2, 3, 4],
391
+ [1, 2, 3, 4]]
392
+ will result into:
393
+ [[S, 1, S, S, 2, S, S, 3, S, S, 4, S],
394
+ [S, 1, S, S, 2, S, S, 3, S, S, 4, S],
395
+ [1, S, S, 2, S, S, 3, S, S, 4, S, S]]
396
+ 3. Flattening with delay. The ``delay`` parameter allows to further unroll the sequence of codebooks
397
+ allowing to specify the delay per codebook. Note that the delay between codebooks flattened to the
398
+ same inner timestep should be coherent. For example, taking n_q = 3, timesteps = 4, flattening = [0, 1, 1]
399
+ and delays = [0, 3, 3]:
400
+ [[1, 2, 3, 4],
401
+ [1, 2, 3, 4],
402
+ [1, 2, 3, 4]]
403
+ will result into:
404
+ [[S, S, S, 1, S, 2, S, 3, S, 4],
405
+ [S, S, S, 1, S, 2, S, 3, S, 4],
406
+ [1, 2, 3, S, 4, S, 5, S, 6, S]]
407
+
408
+ Args:
409
+ n_q (int): Number of codebooks.
410
+ flattening (list of int, optional): Flattening schema over the codebooks. If not defined,
411
+ the codebooks will be flattened to 1 codebook per step, meaning that the sequence will
412
+ have n_q extra steps for each timestep.
413
+ delays (list of int, optional): Delay for each of the codebooks. If not defined,
414
+ no delay is added and therefore will default to [0] * ``n_q``.
415
+ Note that two codebooks that will be flattened to the same inner step
416
+ should have the same delay, otherwise the pattern is considered as invalid.
417
+ """
418
+ FlattenedCodebook = namedtuple('FlattenedCodebook', ['codebooks', 'delay'])
419
+
420
+ def __init__(self, n_q: int, flattening: tp.Optional[tp.List[int]] = None,
421
+ delays: tp.Optional[tp.List[int]] = None):
422
+ super().__init__(n_q)
423
+ if flattening is None:
424
+ flattening = list(range(n_q))
425
+ if delays is None:
426
+ delays = [0] * n_q
427
+ assert len(flattening) == n_q
428
+ assert len(delays) == n_q
429
+ assert sorted(flattening) == flattening
430
+ assert sorted(delays) == delays
431
+ self._flattened_codebooks = self._build_flattened_codebooks(delays, flattening)
432
+ self.max_delay = max(delays)
433
+
434
+ def _build_flattened_codebooks(self, delays: tp.List[int], flattening: tp.List[int]):
435
+ """Build a flattened codebooks representation as a dictionary of inner step
436
+ and the actual codebook indices corresponding to the flattened codebook. For convenience, we
437
+ also store the delay associated to the flattened codebook to avoid maintaining an extra mapping.
438
+ """
439
+ flattened_codebooks: dict = {}
440
+ for q, (inner_step, delay) in enumerate(zip(flattening, delays)):
441
+ if inner_step not in flattened_codebooks:
442
+ flat_codebook = UnrolledPatternProvider.FlattenedCodebook(codebooks=[q], delay=delay)
443
+ else:
444
+ flat_codebook = flattened_codebooks[inner_step]
445
+ assert flat_codebook.delay == delay, (
446
+ "Delay and flattening between codebooks is inconsistent: ",
447
+ "two codebooks flattened to the same position should have the same delay."
448
+ )
449
+ flat_codebook.codebooks.append(q)
450
+ flattened_codebooks[inner_step] = flat_codebook
451
+ return flattened_codebooks
452
+
453
+ @property
454
+ def _num_inner_steps(self):
455
+ """Number of inner steps to unroll between timesteps in order to flatten the codebooks.
456
+ """
457
+ return max([inner_step for inner_step in self._flattened_codebooks.keys()]) + 1
458
+
459
+ def num_virtual_steps(self, timesteps: int) -> int:
460
+ return timesteps * self._num_inner_steps + 1
461
+
462
+ def get_pattern(self, timesteps: int) -> Pattern:
463
+ """Builds pattern for delay across codebooks.
464
+
465
+ Args:
466
+ timesteps (int): Total number of timesteps.
467
+ """
468
+ # the PatternLayout is built as a tuple of sequence position and list of coordinates
469
+ # so that it can be reordered properly given the required delay between codebooks of given timesteps
470
+ indexed_out: list = [(-1, [])]
471
+ max_timesteps = timesteps + self.max_delay
472
+ for t in range(max_timesteps):
473
+ # for each timestep, we unroll the flattened codebooks,
474
+ # emitting the sequence step with the corresponding delay
475
+ for step in range(self._num_inner_steps):
476
+ if step in self._flattened_codebooks:
477
+ # we have codebooks at this virtual step to emit
478
+ step_codebooks = self._flattened_codebooks[step]
479
+ t_for_q = t + step_codebooks.delay
480
+ coords = [LayoutCoord(t, q) for q in step_codebooks.codebooks]
481
+ if t_for_q < max_timesteps and t < max_timesteps:
482
+ indexed_out.append((t_for_q, coords))
483
+ else:
484
+ # there is no codebook in this virtual step so we emit an empty list
485
+ indexed_out.append((t, []))
486
+ out = [coords for _, coords in sorted(indexed_out)]
487
+ return Pattern(out, n_q=self.n_q, timesteps=timesteps)
488
+
489
+
490
+ class CoarseFirstPattern(CodebooksPatternProvider):
491
+ """First generates all the codebooks #1 (e.g. coarser), then the remaining ones,
492
+ potentially with delays.
493
+
494
+ ..Warning:: You must always generate the full training duration at test time, for instance,
495
+ 30 seconds, as otherwise, the fine codebooks will start being generated in an unexpected
496
+ location. This is due to the non causality of the remaining codebooks with respect to
497
+ the first ones.
498
+
499
+ Args:
500
+ n_q (int): Number of codebooks.
501
+ delays (list of int, optional): Delay for each of the codebooks.
502
+ If delays not defined, each codebook is delayed by 1 compared to the previous one.
503
+ """
504
+ def __init__(self, n_q: int, delays: tp.Optional[tp.List[int]] = None):
505
+ super().__init__(n_q)
506
+ if delays is None:
507
+ delays = [0] * (n_q - 1)
508
+ self.delays = delays
509
+ assert len(self.delays) == self.n_q - 1
510
+ assert sorted(self.delays) == self.delays
511
+
512
+ def get_pattern(self, timesteps: int) -> Pattern:
513
+ out: PatternLayout = [[]]
514
+ for t in range(timesteps):
515
+ out.append([LayoutCoord(t, 0)])
516
+ max_delay = max(self.delays)
517
+ for t in range(timesteps + max_delay):
518
+ v = []
519
+ for q, delay in enumerate(self.delays):
520
+ t_for_q = t - delay
521
+ if t_for_q >= 0:
522
+ v.append(LayoutCoord(t_for_q, q + 1))
523
+ out.append(v)
524
+ return Pattern(out, n_q=self.n_q, timesteps=timesteps)
525
+
526
+
527
+ class MusicLMPattern(CodebooksPatternProvider):
528
+ """Almost MusicLM style pattern. This is equivalent to full flattening
529
+ but in a different order.
530
+
531
+ Args:
532
+ n_q (int): Number of codebooks.
533
+ group_by (int): Number of codebooks to group together.
534
+ """
535
+ def __init__(self, n_q: int, group_by: int = 2):
536
+ super().__init__(n_q)
537
+ self.group_by = group_by
538
+
539
+ def get_pattern(self, timesteps: int) -> Pattern:
540
+ out: PatternLayout = [[]]
541
+ for offset in range(0, self.n_q, self.group_by):
542
+ for t in range(timesteps):
543
+ for q in range(offset, offset + self.group_by):
544
+ out.append([LayoutCoord(t, q)])
545
+ return Pattern(out, n_q=self.n_q, timesteps=timesteps)
ThinkSound/models/conditioners.py ADDED
@@ -0,0 +1,1082 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Heavily influenced by https://github.com/facebookresearch/audiocraft/blob/main/audiocraft/modules/conditioners.py
2
+
3
+ import torch
4
+ import logging, warnings
5
+ import string
6
+ import typing as tp
7
+ import gc
8
+ from typing import Literal, Optional
9
+ import os
10
+ from .adp import NumberEmbedder
11
+ from ..inference.utils import set_audio_channels
12
+ from .factory import create_pretransform_from_config
13
+ from .pretransforms import Pretransform
14
+ from ..training.utils import copy_state_dict
15
+ from .utils import load_ckpt_state_dict
16
+ import numpy as np
17
+ from einops import rearrange
18
+ from transformers import AutoProcessor, AutoModel
19
+ from torch import nn
20
+ import torch.nn.functional as F
21
+ from .mmmodules.model.low_level import ConvMLP, MLP
22
+ from torch.nn.utils.rnn import pad_sequence
23
+
24
+ class Conditioner(nn.Module):
25
+ def __init__(
26
+ self,
27
+ dim: int,
28
+ output_dim: int,
29
+ project_out: bool = False
30
+ ):
31
+
32
+ super().__init__()
33
+
34
+ self.dim = dim
35
+ self.output_dim = output_dim
36
+ self.proj_out = nn.Linear(dim, output_dim) if (dim != output_dim or project_out) else nn.Identity()
37
+
38
+ def forward(self, x: tp.Any) -> tp.Any:
39
+ raise NotImplementedError()
40
+
41
+ class Cond_MLP(Conditioner):
42
+ def __init__(self, dim, output_dim, dropout = 0.0):
43
+ super().__init__(dim, output_dim)
44
+ self.embedder = nn.Sequential(
45
+ nn.Linear(dim, output_dim, bias=False),
46
+ nn.SiLU(),
47
+ nn.Linear(output_dim, output_dim, bias=False)
48
+ )
49
+ self.dropout = dropout
50
+ def forward(self, x, device: tp.Any = "cuda"):
51
+ x = pad_sequence(x, batch_first=True).to(device)
52
+ # x = torch.stack(x, dim=0).to(device)
53
+
54
+ if self.dropout > 0.0:
55
+ if self.training:
56
+ null_embed = torch.zeros_like(x, device=device)
57
+ dropout_mask = torch.bernoulli(torch.full((x.shape[0], 1, 1), self.dropout, device=device)).to(torch.bool)
58
+ x = torch.where(dropout_mask, null_embed, x)
59
+ elif x.shape[0] < 16: # default test batch size=1
60
+ null_embed = torch.zeros_like(x, device=device)
61
+ x = torch.cat([x, null_embed], dim=0)
62
+
63
+ x = self.embedder(x) # B x 117 x C
64
+ return [x, torch.ones(x.shape[0], 1).to(device)]
65
+
66
+ class Global_MLP(Conditioner):
67
+ def __init__(self, dim, output_dim):
68
+ super().__init__(dim, output_dim)
69
+ self.embedder = nn.Sequential(
70
+ nn.Linear(dim, output_dim, bias=False),
71
+ nn.SiLU(),
72
+ nn.Linear(output_dim, output_dim, bias=False)
73
+ )
74
+ def forward(self, x, device: tp.Any = "cuda"):
75
+ x = torch.stack(x, dim=0).to(device)
76
+ x = x.mean(dim=1)
77
+ x = self.embedder(x) # B x 117 x C
78
+ return [x, torch.ones(x.shape[0], 1).to(device)]
79
+
80
+ class Cond_MLP_1(Conditioner):
81
+ def __init__(self, dim, output_dim):
82
+ super().__init__(dim, output_dim)
83
+ self.embedder = nn.Sequential(
84
+ nn.Linear(dim, output_dim),
85
+ nn.SiLU(),
86
+ MLP(output_dim, output_dim * 4),
87
+ )
88
+ def forward(self, x, device: tp.Any = "cuda"):
89
+ x = torch.stack(x, dim=0).to(device)
90
+
91
+ x = self.embedder(x) # B x 117 x C
92
+ return [x, torch.ones(x.shape[0], 1).to(device)]
93
+
94
+ class Cond_MLP_Global(Conditioner):
95
+ def __init__(self, dim, output_dim, dropout = 0.0):
96
+ super().__init__(dim, output_dim)
97
+ self.embedder = nn.Sequential(
98
+ nn.Linear(dim, output_dim, bias=False),
99
+ nn.SiLU(),
100
+ nn.Linear(output_dim, output_dim, bias=False)
101
+ )
102
+ self.global_embedder = nn.Sequential(
103
+ nn.Linear(output_dim, output_dim, bias=False),
104
+ nn.SiLU(),
105
+ nn.Linear(output_dim, output_dim, bias=False)
106
+ )
107
+ self.dropout = dropout
108
+ def forward(self, x, device: tp.Any = "cuda"):
109
+ x = torch.stack(x, dim=0).to(device)
110
+ if self.dropout > 0 and self.training:
111
+ null_embed = torch.zeros_like(x, device=device)
112
+ dropout_mask = torch.bernoulli(torch.full((x.shape[0], 1, 1), self.dropout, device=device)).to(torch.bool)
113
+ x = torch.where(dropout_mask, null_embed, x)
114
+ x = self.embedder(x) # B x 117 x C
115
+ global_x = self.global_embedder(x[:,0,:])
116
+ return [x, torch.ones(x.shape[0], 1).to(device), global_x, torch.ones(global_x.shape[0], 1).to(device)]
117
+
118
+ class Cond_MLP_Global_1(Conditioner):
119
+ def __init__(self, dim, output_dim):
120
+ super().__init__(dim, output_dim)
121
+ self.embedder = nn.Sequential(
122
+ nn.Linear(dim, output_dim),
123
+ nn.SiLU(),
124
+ MLP(output_dim, output_dim * 4),
125
+ )
126
+ self.global_embedder = nn.Sequential(
127
+ nn.Linear(dim, output_dim),
128
+ MLP(output_dim, output_dim * 4),
129
+ )
130
+ def forward(self, x, device: tp.Any = "cuda"):
131
+ x = torch.stack(x, dim=0).to(device)
132
+
133
+ x = self.embedder(x) # B x 117 x C
134
+ global_x = self.global_embedder(x.mean(dim=1))
135
+ return [x, torch.ones(x.shape[0], 1).to(device), global_x, torch.ones(global_x.shape[0], 1).to(device)]
136
+
137
+ class Cond_MLP_Global_2(Conditioner):
138
+ def __init__(self, dim, output_dim):
139
+ super().__init__(dim, output_dim)
140
+ self.embedder = nn.Sequential(
141
+ nn.Linear(dim, output_dim, bias=False),
142
+ nn.SiLU(),
143
+ nn.Linear(output_dim, output_dim, bias=False)
144
+ )
145
+ self.global_embedder = nn.Sequential(
146
+ nn.Linear(output_dim, output_dim, bias=False),
147
+ )
148
+ def forward(self, x, device: tp.Any = "cuda"):
149
+ x = torch.stack(x, dim=0).to(device)
150
+
151
+ x = self.embedder(x) # B x 117 x C
152
+ global_x = self.global_embedder(x.mean(dim=1))
153
+ return [x, torch.ones(x.shape[0], 1).to(device), global_x, torch.ones(global_x.shape[0], 1).to(device)]
154
+
155
+ class Sync_MLP(Conditioner):
156
+ def __init__(self, dim, output_dim):
157
+ super().__init__(dim, output_dim)
158
+ self.embedder = nn.Sequential(
159
+ nn.Linear(dim, output_dim, bias=False),
160
+ nn.SiLU(),
161
+ nn.Linear(output_dim, output_dim, bias=False)
162
+ )
163
+ self.sync_pos_emb = nn.Parameter(torch.zeros((1, 1, 8, dim)))
164
+ nn.init.constant_(self.sync_pos_emb, 0)
165
+ def forward(self, x, device: tp.Any = "cuda"):
166
+ sync_f = torch.stack(x, dim=0).to(device)
167
+ bs, length, dim = sync_f.shape
168
+ #print(sync_f.shape,flush=True)
169
+ # B * num_segments (24) * 8 * 768
170
+ num_sync_segments = length // 8
171
+ sync_f = sync_f.view(bs, num_sync_segments, 8, -1) + self.sync_pos_emb
172
+ sync_f = sync_f.flatten(1, 2) # (B, VN, D)
173
+ x = self.embedder(sync_f) # B x 117 x C
174
+ x = x.transpose(1,2)
175
+ x = F.interpolate(x, ((int)(194*sync_f.shape[1]/216), ), mode='linear', align_corners=False)
176
+ x = x.transpose(1,2)
177
+ return [x, torch.ones(x.shape[0], 1).to(device)]
178
+
179
+ class Cond_ConvMLP(Conditioner):
180
+ def __init__(self, dim, output_dim):
181
+ super().__init__(dim, output_dim)
182
+ self.embedder = nn.Sequential(
183
+ nn.Linear(dim, output_dim),
184
+ nn.SiLU(),
185
+ ConvMLP(output_dim, output_dim * 4, kernel_size=1, padding=0),
186
+ )
187
+ def forward(self, x, device: tp.Any = "cuda"):
188
+ x = torch.stack(x, dim=0).to(device)
189
+
190
+ x = self.embedder(x) # B x 117 x C
191
+ return [x, torch.ones(x.shape[0], 1).to(device)]
192
+
193
+ class Video_Global(Conditioner):
194
+ """ Transform the video feat encoder"""
195
+
196
+ def __init__(self, dim, output_dim, global_dim=1536):
197
+ super().__init__(dim, output_dim)
198
+ self.embedder = nn.Sequential(nn.Linear(dim, output_dim))
199
+ self.global_proj = nn.Sequential(nn.Linear(output_dim, global_dim))
200
+
201
+ def forward(self, x, device: tp.Any = "cuda"):
202
+ # import ipdb
203
+ # ipdb.set_trace()
204
+ if not isinstance(x[0], torch.Tensor):
205
+ video_feats = []
206
+ for path in x:
207
+ if '.npy' in path:
208
+ video_feats.append(torch.from_numpy(np.load(path)).to(device))
209
+ elif '.pth' in path:
210
+ data = torch.load(path)
211
+ video_feats.append(data['metaclip_features'].to(device))
212
+ else:
213
+ video_feats.append(torch.from_numpy(np.load(path)['feat']).to(device))
214
+ x = torch.stack(video_feats, dim=0).to(device)
215
+ else:
216
+ # Revise the shape here:
217
+ x = torch.stack(x, dim=0).to(device)
218
+
219
+ x = self.embedder(x) # B x 117 x C
220
+ global_x = self.global_proj(x.mean(dim=1))
221
+ return [x, torch.ones(x.shape[0], 1).to(device), global_x, torch.ones(global_x.shape[0], 1).to(device)]
222
+
223
+ class Video_Sync(Conditioner):
224
+ """ Transform the video feat encoder"""
225
+
226
+ def __init__(self, dim, output_dim):
227
+ super().__init__(dim, output_dim)
228
+ self.embedder = nn.Sequential(nn.Linear(dim, output_dim))
229
+
230
+ def forward(self, x, device: tp.Any = "cuda"):
231
+ # import ipdb
232
+ # ipdb.set_trace()
233
+ if not isinstance(x[0], torch.Tensor):
234
+ video_feats = []
235
+ for path in x:
236
+ if '.npy' in path:
237
+ video_feats.append(torch.from_numpy(np.load(path)).to(device))
238
+ elif '.pth' in path:
239
+ video_feats.append(torch.load(path)['sync_features'].to(device))
240
+ else:
241
+ video_feats.append(torch.from_numpy(np.load(path)['feat']).to(device))
242
+ x = torch.stack(video_feats, dim=0).to(device)
243
+ else:
244
+ # Revise the shape here:
245
+ x = torch.stack(x, dim=0).to(device)
246
+
247
+ x = self.embedder(x) # B x 117 x C
248
+ return [x, torch.ones(x.shape[0], 1).to(device)]
249
+
250
+ class Text_Linear(Conditioner):
251
+ """ Transform the video feat encoder"""
252
+
253
+ def __init__(self, dim, output_dim):
254
+ super().__init__(dim, output_dim)
255
+ self.embedder = nn.Sequential(nn.Linear(dim, output_dim))
256
+
257
+ def forward(self, x, device: tp.Any = "cuda"):
258
+ # import ipdb
259
+ # ipdb.set_trace()
260
+ if not isinstance(x[0], torch.Tensor):
261
+ video_feats = []
262
+ for path in x:
263
+ if '.npy' in path:
264
+ video_feats.append(torch.from_numpy(np.load(path)).to(device))
265
+ elif '.pth' in path:
266
+ video_feats.append(torch.load(path)['metaclip_text_features'].to(device))
267
+ else:
268
+ video_feats.append(torch.from_numpy(np.load(path)['feat']).to(device))
269
+ x = torch.stack(video_feats, dim=0).to(device)
270
+ else:
271
+ # Revise the shape here:
272
+ x = torch.stack(x, dim=0).to(device)
273
+
274
+ x = self.embedder(x) # B x 117 x C
275
+ return [x, torch.ones(x.shape[0], 1).to(device)]
276
+
277
+ class mm_unchang(Conditioner):
278
+ """ Transform the video feat encoder"""
279
+
280
+ def __init__(self, dim, output_dim):
281
+ super().__init__(dim, output_dim)
282
+
283
+ def forward(self, x, device: tp.Any = "cuda"):
284
+ # import ipdb
285
+ # ipdb.set_trace()
286
+ if not isinstance(x[0], torch.Tensor):
287
+ video_feats = []
288
+ for path in x:
289
+ if '.npy' in path:
290
+ video_feats.append(torch.from_numpy(np.load(path)).to(device))
291
+ elif '.pth' in path:
292
+ video_feats.append(torch.load(path)['metaclip_features'].to(device))
293
+ else:
294
+ video_feats.append(torch.from_numpy(np.load(path)['feat']).to(device))
295
+ x = torch.stack(video_feats, dim=0).to(device)
296
+ else:
297
+ # Revise the shape here:
298
+ x = torch.stack(x, dim=0).to(device)
299
+ return [x]
300
+
301
+ class CLIPConditioner(Conditioner):
302
+
303
+ CLIP_MODELS = ["metaclip-base", "metaclip-b16", "metaclip-large", "metaclip-huge"]
304
+
305
+ CLIP_MODEL_DIMS = {
306
+ "metaclip-base": 512,
307
+ "metaclip-b16": 512,
308
+ "metaclip-large": 768,
309
+ "metaclip-huge": 1024,
310
+ }
311
+
312
+ def __init__(
313
+ self,
314
+ dim: int,
315
+ output_dim: int,
316
+ clip_model_name: str = "metaclip-huge",
317
+ enable_grad: bool = False,
318
+ project_out: bool = False
319
+ ):
320
+ assert clip_model_name in self.CLIP_MODELS, f"Unknown CLIP model name: {clip_model_name}"
321
+ super().__init__(self.CLIP_MODEL_DIMS[clip_model_name], output_dim, project_out=project_out)
322
+
323
+ self.enable_grad = enable_grad
324
+ model = AutoModel.from_pretrained(f"useful_ckpts/{clip_model_name}").train(enable_grad).requires_grad_(enable_grad).to(torch.float16)
325
+
326
+
327
+
328
+ if self.enable_grad:
329
+ self.model = model
330
+ else:
331
+ self.__dict__["model"] = model
332
+
333
+
334
+ def forward(self, images: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
335
+
336
+ self.model.to(device)
337
+ self.proj_out.to(device)
338
+ # import ipdb
339
+ # ipdb.set_trace()
340
+
341
+ self.model.eval()
342
+ if not isinstance(images[0], torch.Tensor):
343
+ video_feats = []
344
+ for path in images:
345
+ if '.npy' in path:
346
+ video_feats.append(torch.from_numpy(np.load(path)).to(device))
347
+ else:
348
+ video_feats.append(torch.from_numpy(np.load(path)).to(device))
349
+ images = torch.stack(video_feats, dim=0).to(device)
350
+ else:
351
+ images = torch.stack(images, dim=0).to(device)
352
+ bsz, t, c, h, w = images.shape
353
+ # 使用 rearrange 进行维度合并
354
+ images = rearrange(images, 'b t c h w -> (b t) c h w')
355
+ with torch.set_grad_enabled(self.enable_grad):
356
+ image_features = self.model.get_image_features(images)
357
+ image_features = rearrange(image_features, '(b t) d -> b t d', b=bsz, t=t)
358
+ image_features = self.proj_out(image_features)
359
+
360
+
361
+ return [image_features, torch.ones(image_features.shape[0], 1).to(device)]
362
+
363
+ class IntConditioner(Conditioner):
364
+ def __init__(self,
365
+ output_dim: int,
366
+ min_val: int=0,
367
+ max_val: int=512
368
+ ):
369
+ super().__init__(output_dim, output_dim)
370
+
371
+ self.min_val = min_val
372
+ self.max_val = max_val
373
+ self.int_embedder = nn.Embedding(max_val - min_val + 1, output_dim).requires_grad_(True)
374
+
375
+ def forward(self, ints: tp.List[int], device=None) -> tp.Any:
376
+
377
+ #self.int_embedder.to(device)
378
+
379
+ ints = torch.tensor(ints).to(device)
380
+ ints = ints.clamp(self.min_val, self.max_val)
381
+
382
+ int_embeds = self.int_embedder(ints).unsqueeze(1)
383
+
384
+ return [int_embeds, torch.ones(int_embeds.shape[0], 1).to(device)]
385
+
386
+ class NumberConditioner(Conditioner):
387
+ '''
388
+ Conditioner that takes a list of floats, normalizes them for a given range, and returns a list of embeddings
389
+ '''
390
+ def __init__(self,
391
+ output_dim: int,
392
+ min_val: float=0,
393
+ max_val: float=1
394
+ ):
395
+ super().__init__(output_dim, output_dim)
396
+
397
+ self.min_val = min_val
398
+ self.max_val = max_val
399
+
400
+ self.embedder = NumberEmbedder(features=output_dim)
401
+
402
+ def forward(self, floats: tp.List[float], device=None) -> tp.Any:
403
+
404
+ # Cast the inputs to floats
405
+ floats = [float(x) for x in floats]
406
+
407
+ floats = torch.tensor(floats).to(device)
408
+
409
+ floats = floats.clamp(self.min_val, self.max_val)
410
+
411
+ normalized_floats = (floats - self.min_val) / (self.max_val - self.min_val)
412
+
413
+ # Cast floats to same type as embedder
414
+ embedder_dtype = next(self.embedder.parameters()).dtype
415
+ normalized_floats = normalized_floats.to(embedder_dtype)
416
+
417
+ float_embeds = self.embedder(normalized_floats).unsqueeze(1)
418
+
419
+ return [float_embeds, torch.ones(float_embeds.shape[0], 1).to(device)]
420
+
421
+ class CLAPTextConditioner(Conditioner):
422
+ def __init__(self,
423
+ output_dim: int,
424
+ clap_ckpt_path,
425
+ use_text_features = False,
426
+ feature_layer_ix: int = -1,
427
+ audio_model_type="HTSAT-base",
428
+ enable_fusion=True,
429
+ project_out: bool = False,
430
+ finetune: bool = False):
431
+ super().__init__(768 if use_text_features else 512, output_dim, project_out=project_out)
432
+
433
+ self.use_text_features = use_text_features
434
+ self.feature_layer_ix = feature_layer_ix
435
+ self.finetune = finetune
436
+
437
+ # Suppress logging from transformers
438
+ previous_level = logging.root.manager.disable
439
+ logging.disable(logging.ERROR)
440
+ with warnings.catch_warnings():
441
+ warnings.simplefilter("ignore")
442
+ try:
443
+ import laion_clap
444
+ from laion_clap.clap_module.factory import load_state_dict as clap_load_state_dict
445
+
446
+ model = laion_clap.CLAP_Module(enable_fusion=enable_fusion, amodel=audio_model_type, device='cpu')
447
+
448
+ if self.finetune:
449
+ self.model = model
450
+ else:
451
+ self.__dict__["model"] = model
452
+
453
+ state_dict = clap_load_state_dict(clap_ckpt_path)
454
+ self.model.model.load_state_dict(state_dict, strict=False)
455
+
456
+ if self.finetune:
457
+ self.model.model.text_branch.requires_grad_(True)
458
+ self.model.model.text_branch.train()
459
+ else:
460
+ self.model.model.text_branch.requires_grad_(False)
461
+ self.model.model.text_branch.eval()
462
+
463
+ finally:
464
+ logging.disable(previous_level)
465
+
466
+ del self.model.model.audio_branch
467
+
468
+ gc.collect()
469
+ torch.cuda.empty_cache()
470
+
471
+ def get_clap_features(self, prompts, layer_ix=-2, device: tp.Any = "cuda"):
472
+ prompt_tokens = self.model.tokenizer(prompts)
473
+ attention_mask = prompt_tokens["attention_mask"].to(device=device, non_blocking=True)
474
+ prompt_features = self.model.model.text_branch(
475
+ input_ids=prompt_tokens["input_ids"].to(device=device, non_blocking=True),
476
+ attention_mask=attention_mask,
477
+ output_hidden_states=True
478
+ )["hidden_states"][layer_ix]
479
+
480
+ return prompt_features, attention_mask
481
+
482
+ def forward(self, texts: tp.List[str], device: tp.Any = "cuda") -> tp.Any:
483
+ self.model.to(device)
484
+
485
+ if self.use_text_features:
486
+ if len(texts) == 1:
487
+ text_features, text_attention_mask = self.get_clap_features([texts[0], ""], layer_ix=self.feature_layer_ix, device=device)
488
+ text_features = text_features[:1, ...]
489
+ text_attention_mask = text_attention_mask[:1, ...]
490
+ else:
491
+ text_features, text_attention_mask = self.get_clap_features(texts, layer_ix=self.feature_layer_ix, device=device)
492
+ return [self.proj_out(text_features), text_attention_mask]
493
+
494
+ # Fix for CLAP bug when only one text is passed
495
+ if len(texts) == 1:
496
+ text_embedding = self.model.get_text_embedding([texts[0], ""], use_tensor=True)[:1, ...]
497
+ else:
498
+ text_embedding = self.model.get_text_embedding(texts, use_tensor=True)
499
+
500
+ text_embedding = text_embedding.unsqueeze(1).to(device)
501
+
502
+ return [self.proj_out(text_embedding), torch.ones(text_embedding.shape[0], 1).to(device)]
503
+
504
+ class CLAPAudioConditioner(Conditioner):
505
+ def __init__(self,
506
+ output_dim: int,
507
+ clap_ckpt_path,
508
+ audio_model_type="HTSAT-base",
509
+ enable_fusion=True,
510
+ project_out: bool = False):
511
+ super().__init__(512, output_dim, project_out=project_out)
512
+
513
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
514
+
515
+ # Suppress logging from transformers
516
+ previous_level = logging.root.manager.disable
517
+ logging.disable(logging.ERROR)
518
+ with warnings.catch_warnings():
519
+ warnings.simplefilter("ignore")
520
+ try:
521
+ import laion_clap
522
+ from laion_clap.clap_module.factory import load_state_dict as clap_load_state_dict
523
+
524
+ model = laion_clap.CLAP_Module(enable_fusion=enable_fusion, amodel=audio_model_type, device='cpu')
525
+
526
+ self.model = model
527
+
528
+ state_dict = clap_load_state_dict(clap_ckpt_path)
529
+ self.model.model.load_state_dict(state_dict, strict=False)
530
+
531
+ self.model.model.audio_branch.requires_grad_(False)
532
+ self.model.model.audio_branch.eval()
533
+
534
+ finally:
535
+ logging.disable(previous_level)
536
+
537
+ del self.model.model.text_branch
538
+
539
+ gc.collect()
540
+ torch.cuda.empty_cache()
541
+
542
+ def forward(self, audios: tp.Union[torch.Tensor, tp.List[torch.Tensor], tp.Tuple[torch.Tensor]] , device: tp.Any = "cuda") -> tp.Any:
543
+
544
+ self.model.to(device)
545
+
546
+ if isinstance(audios, list) or isinstance(audios, tuple):
547
+ audios = torch.cat(audios, dim=0)
548
+
549
+ # Convert to mono
550
+ mono_audios = audios.mean(dim=1)
551
+
552
+ with torch.cuda.amp.autocast(enabled=False):
553
+ audio_embedding = self.model.get_audio_embedding_from_data(mono_audios.float(), use_tensor=True)
554
+
555
+ audio_embedding = audio_embedding.unsqueeze(1).to(device)
556
+
557
+ return [self.proj_out(audio_embedding), torch.ones(audio_embedding.shape[0], 1).to(device)]
558
+
559
+ class T5Conditioner(Conditioner):
560
+
561
+ T5_MODELS = ["t5-small", "t5-base", "t5-large", "t5-3b", "t5-11b",
562
+ "google/flan-t5-small", "google/flan-t5-base", "google/flan-t5-large",
563
+ "google/flan-t5-xl", "google/flan-t5-xxl", "t5-v1_1-xl", "google/t5-v1_1-xxl"]
564
+
565
+ T5_MODEL_DIMS = {
566
+ "t5-small": 512,
567
+ "t5-base": 768,
568
+ "t5-large": 1024,
569
+ "t5-3b": 1024,
570
+ "t5-11b": 1024,
571
+ "t5-v1_1-xl": 2048,
572
+ "google/t5-v1_1-xxl": 4096,
573
+ "google/flan-t5-small": 512,
574
+ "google/flan-t5-base": 768,
575
+ "google/flan-t5-large": 1024,
576
+ "google/flan-t5-3b": 1024,
577
+ "google/flan-t5-11b": 1024,
578
+ "google/flan-t5-xl": 2048,
579
+ "google/flan-t5-xxl": 4096,
580
+ }
581
+
582
+ def __init__(
583
+ self,
584
+ output_dim: int,
585
+ t5_model_name: str = "t5-base",
586
+ max_length: str = 77,
587
+ enable_grad: bool = False,
588
+ project_out: bool = False
589
+ ):
590
+ assert t5_model_name in self.T5_MODELS, f"Unknown T5 model name: {t5_model_name}"
591
+ super().__init__(self.T5_MODEL_DIMS[t5_model_name], output_dim, project_out=project_out)
592
+
593
+ from transformers import T5EncoderModel, AutoTokenizer
594
+
595
+ self.max_length = max_length
596
+ self.enable_grad = enable_grad
597
+
598
+ # Suppress logging from transformers
599
+ previous_level = logging.root.manager.disable
600
+ logging.disable(logging.ERROR)
601
+ with warnings.catch_warnings():
602
+ warnings.simplefilter("ignore")
603
+ try:
604
+ # self.tokenizer = T5Tokenizer.from_pretrained(t5_model_name, model_max_length = max_length)
605
+ # model = T5EncoderModel.from_pretrained(t5_model_name, max_length=max_length).train(enable_grad).requires_grad_(enable_grad)
606
+ self.tokenizer = AutoTokenizer.from_pretrained(os.path.join('useful_ckpts', t5_model_name))
607
+ model = T5EncoderModel.from_pretrained(os.path.join('useful_ckpts', t5_model_name)).train(enable_grad).requires_grad_(enable_grad).to(torch.float16)
608
+ finally:
609
+ logging.disable(previous_level)
610
+
611
+ if self.enable_grad:
612
+ self.model = model
613
+ else:
614
+ self.__dict__["model"] = model
615
+
616
+
617
+ def forward(self, texts: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
618
+
619
+ self.model.to(device)
620
+ self.proj_out.to(device)
621
+ encoded = self.tokenizer(
622
+ texts,
623
+ truncation=True,
624
+ max_length=self.max_length,
625
+ padding="max_length",
626
+ return_tensors="pt",
627
+ )
628
+
629
+ input_ids = encoded["input_ids"].to(device)
630
+ attention_mask = encoded["attention_mask"].to(device).to(torch.bool)
631
+
632
+ self.model.eval()
633
+
634
+ with torch.cuda.amp.autocast(dtype=torch.float16) and torch.set_grad_enabled(self.enable_grad):
635
+ embeddings = self.model(
636
+ input_ids=input_ids, attention_mask=attention_mask
637
+ )["last_hidden_state"]
638
+
639
+ embeddings = self.proj_out(embeddings.float())
640
+
641
+ embeddings = embeddings * attention_mask.unsqueeze(-1).float()
642
+
643
+ return embeddings, attention_mask
644
+
645
+ def patch_clip(clip_model):
646
+ # a hack to make it output last hidden states
647
+ # https://github.com/mlfoundations/open_clip/blob/fc5a37b72d705f760ebbc7915b84729816ed471f/src/open_clip/model.py#L269
648
+ def new_encode_text(self, text, normalize: bool = False):
649
+ cast_dtype = self.transformer.get_cast_dtype()
650
+
651
+ x = self.token_embedding(text).to(cast_dtype) # [batch_size, n_ctx, d_model]
652
+
653
+ x = x + self.positional_embedding.to(cast_dtype)
654
+ x = self.transformer(x, attn_mask=self.attn_mask)
655
+ x = self.ln_final(x) # [batch_size, n_ctx, transformer.width]
656
+ return F.normalize(x, dim=-1) if normalize else x
657
+
658
+ clip_model.encode_text = new_encode_text.__get__(clip_model)
659
+ return clip_model
660
+
661
+ class CLIPTextConditioner(Conditioner):
662
+ def __init__(
663
+ self,
664
+ output_dim: int,
665
+ max_length: str = 77,
666
+ enable_grad: bool = False,
667
+ project_out: bool = False
668
+ ):
669
+ super().__init__(1024, output_dim, project_out=project_out)
670
+
671
+ from transformers import T5EncoderModel, AutoTokenizer
672
+ import open_clip
673
+ from open_clip import create_model_from_pretrained
674
+
675
+ self.max_length = max_length
676
+ self.enable_grad = enable_grad
677
+
678
+ # Suppress logging from transformers
679
+ previous_level = logging.root.manager.disable
680
+ logging.disable(logging.ERROR)
681
+ with warnings.catch_warnings():
682
+ warnings.simplefilter("ignore")
683
+ try:
684
+ model = create_model_from_pretrained('hf-hub:apple/DFN5B-CLIP-ViT-H-14-384',cache_dir='useful_ckpts/DFN5B-CLIP-ViT-H-14-384',
685
+ return_transform=False).train(enable_grad).requires_grad_(enable_grad).to(torch.float16)
686
+ model = patch_clip(model)
687
+ self.tokenizer = open_clip.get_tokenizer('ViT-H-14-378-quickgelu') # same as 'ViT-H-14'
688
+ finally:
689
+ logging.disable(previous_level)
690
+
691
+ if self.enable_grad:
692
+ self.model = model
693
+ else:
694
+ self.__dict__["model"] = model
695
+
696
+
697
+ def forward(self, texts: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
698
+
699
+ self.model.to(device)
700
+ self.proj_out.to(device)
701
+
702
+ encoded = self.tokenizer(
703
+ texts
704
+ ).to(device)
705
+
706
+ # input_ids = encoded["input_ids"].to(device)
707
+ # attention_mask = encoded["attention_mask"].to(device).to(torch.bool)
708
+
709
+ self.model.eval()
710
+
711
+ with torch.cuda.amp.autocast(dtype=torch.float16) and torch.set_grad_enabled(self.enable_grad):
712
+ embeddings = self.model.encode_text(
713
+ encoded
714
+ )
715
+
716
+ embeddings = self.proj_out(embeddings.float())
717
+
718
+ # embeddings = embeddings * attention_mask.unsqueeze(-1).float()
719
+
720
+ return embeddings, torch.ones(embeddings.shape[0], 1).to(device)
721
+
722
+ def patch_clip(clip_model):
723
+ # a hack to make it output last hidden states
724
+ # https://github.com/mlfoundations/open_clip/blob/fc5a37b72d705f760ebbc7915b84729816ed471f/src/open_clip/model.py#L269
725
+ def new_get_text_features(self, input_ids=None, attention_mask=None, position_ids=None,
726
+ output_attentions: Optional[bool] = None,
727
+ output_hidden_states: Optional[bool] = None,
728
+ return_dict: Optional[bool] = None):
729
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
730
+ output_hidden_states = (
731
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
732
+ )
733
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
734
+
735
+ text_outputs = self.text_model(
736
+ input_ids=input_ids,
737
+ attention_mask=attention_mask,
738
+ position_ids=position_ids,
739
+ output_attentions=output_attentions,
740
+ output_hidden_states=output_hidden_states,
741
+ return_dict=return_dict,
742
+ )
743
+ last_hidden_state = text_outputs[0]
744
+ # pooled_output = text_outputs[1]
745
+ # text_features = self.text_projection(pooled_output)
746
+
747
+ return last_hidden_state
748
+
749
+ clip_model.get_text_features = new_get_text_features.__get__(clip_model)
750
+ return clip_model
751
+
752
+ class MetaCLIPTextConditioner(Conditioner):
753
+ def __init__(
754
+ self,
755
+ output_dim: int,
756
+ max_length: str = 77,
757
+ enable_grad: bool = False,
758
+ project_out: bool = False
759
+ ):
760
+ super().__init__(1024, output_dim, project_out=project_out)
761
+
762
+ from transformers import AutoModel
763
+ from transformers import AutoProcessor
764
+
765
+ self.max_length = max_length
766
+ self.enable_grad = enable_grad
767
+
768
+ # Suppress logging from transformers
769
+ previous_level = logging.root.manager.disable
770
+ logging.disable(logging.ERROR)
771
+ with warnings.catch_warnings():
772
+ warnings.simplefilter("ignore")
773
+ try:
774
+ self.model = AutoModel.from_pretrained("useful_ckpts/metaclip-huge")
775
+ self.model = patch_clip(self.model)
776
+ self.clip_processor = AutoProcessor.from_pretrained("useful_ckpts/metaclip-huge")
777
+ finally:
778
+ logging.disable(previous_level)
779
+
780
+
781
+ def forward(self, texts: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
782
+
783
+ self.model.to(device)
784
+ self.proj_out.to(device)
785
+ encoded = self.clip_processor(text=texts, return_tensors="pt", padding=True).to(device)
786
+
787
+ # input_ids = encoded["input_ids"].to(device)
788
+ attention_mask = encoded["attention_mask"].to(device).to(torch.bool)
789
+
790
+ self.model.eval()
791
+
792
+ with torch.set_grad_enabled(self.enable_grad):
793
+ embeddings = self.model.get_text_features(
794
+ **encoded
795
+ )
796
+
797
+ embeddings = self.proj_out(embeddings.float())
798
+
799
+ # embeddings = embeddings * attention_mask.unsqueeze(-1).float()
800
+
801
+ return embeddings, torch.ones(embeddings.shape[0],1).to(device)
802
+
803
+ class PhonemeConditioner(Conditioner):
804
+ """
805
+ A conditioner that turns text into phonemes and embeds them using a lookup table
806
+ Only works for English text
807
+
808
+ Args:
809
+ output_dim: the dimension of the output embeddings
810
+ max_length: the maximum number of phonemes to embed
811
+ project_out: whether to add another linear projection to the output embeddings
812
+ """
813
+
814
+ def __init__(
815
+ self,
816
+ output_dim: int,
817
+ max_length: int = 1024,
818
+ project_out: bool = False,
819
+ ):
820
+ super().__init__(output_dim, output_dim, project_out=project_out)
821
+
822
+ from g2p_en import G2p
823
+
824
+ self.max_length = max_length
825
+
826
+ self.g2p = G2p()
827
+
828
+ # Reserving 0 for padding, 1 for ignored
829
+ self.phoneme_embedder = nn.Embedding(len(self.g2p.phonemes) + 2, output_dim)
830
+
831
+ def forward(self, texts: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
832
+
833
+ self.phoneme_embedder.to(device)
834
+ self.proj_out.to(device)
835
+
836
+ batch_phonemes = [self.g2p(text) for text in texts] # shape [batch_size, length]
837
+
838
+ phoneme_ignore = [" ", *string.punctuation]
839
+
840
+ # Remove ignored phonemes and cut to max length
841
+ batch_phonemes = [[p if p not in phoneme_ignore else "_" for p in phonemes] for phonemes in batch_phonemes]
842
+
843
+ # Convert to ids
844
+ phoneme_ids = [[self.g2p.p2idx[p] + 2 if p in self.g2p.p2idx else 1 for p in phonemes] for phonemes in batch_phonemes]
845
+
846
+ #Pad to match longest and make a mask tensor for the padding
847
+ longest = max([len(ids) for ids in phoneme_ids])
848
+ phoneme_ids = [ids + [0] * (longest - len(ids)) for ids in phoneme_ids]
849
+
850
+ phoneme_ids = torch.tensor(phoneme_ids).to(device)
851
+
852
+ # Convert to embeddings
853
+ phoneme_embeds = self.phoneme_embedder(phoneme_ids)
854
+
855
+ phoneme_embeds = self.proj_out(phoneme_embeds)
856
+
857
+ return phoneme_embeds, torch.ones(phoneme_embeds.shape[0], phoneme_embeds.shape[1]).to(device)
858
+
859
+ class TokenizerLUTConditioner(Conditioner):
860
+ """
861
+ A conditioner that embeds text using a lookup table on a pretrained tokenizer's vocabulary
862
+
863
+ Args:
864
+ tokenizer_name: the name of the tokenizer from the Hugging Face transformers library
865
+ output_dim: the dimension of the output embeddings
866
+ max_length: the maximum length of the text to embed
867
+ project_out: whether to add another linear projection to the output embeddings
868
+ """
869
+
870
+ def __init__(
871
+ self,
872
+ tokenizer_name: str, # Name of a tokenizer from the Hugging Face transformers library
873
+ output_dim: int,
874
+ max_length: int = 1024,
875
+ project_out: bool = False,
876
+ ):
877
+ super().__init__(output_dim, output_dim, project_out=project_out)
878
+
879
+ from transformers import AutoTokenizer
880
+
881
+ # Suppress logging from transformers
882
+ previous_level = logging.root.manager.disable
883
+ logging.disable(logging.ERROR)
884
+ with warnings.catch_warnings():
885
+ warnings.simplefilter("ignore")
886
+ try:
887
+ self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name)
888
+ finally:
889
+ logging.disable(previous_level)
890
+
891
+ self.max_length = max_length
892
+
893
+ self.token_embedder = nn.Embedding(len(self.tokenizer), output_dim)
894
+
895
+ def forward(self, texts: tp.List[str], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
896
+ self.proj_out.to(device)
897
+
898
+ encoded = self.tokenizer(
899
+ texts,
900
+ truncation=True,
901
+ max_length=self.max_length,
902
+ padding="max_length",
903
+ return_tensors="pt",
904
+ )
905
+
906
+ input_ids = encoded["input_ids"].to(device)
907
+ attention_mask = encoded["attention_mask"].to(device).to(torch.bool)
908
+
909
+ embeddings = self.token_embedder(input_ids)
910
+
911
+ embeddings = self.proj_out(embeddings)
912
+
913
+ embeddings = embeddings * attention_mask.unsqueeze(-1).float()
914
+
915
+ return embeddings, attention_mask
916
+
917
+ class PretransformConditioner(Conditioner):
918
+ """
919
+ A conditioner that uses a pretransform's encoder for conditioning
920
+
921
+ Args:
922
+ pretransform: an instantiated pretransform to use for conditioning
923
+ output_dim: the dimension of the output embeddings
924
+ """
925
+ def __init__(self, pretransform: Pretransform, output_dim: int):
926
+ super().__init__(pretransform.encoded_channels, output_dim)
927
+
928
+ self.pretransform = pretransform
929
+
930
+ def forward(self, audio: tp.Union[torch.Tensor, tp.List[torch.Tensor], tp.Tuple[torch.Tensor]], device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
931
+
932
+ self.pretransform.to(device)
933
+ self.proj_out.to(device)
934
+
935
+ if isinstance(audio, list) or isinstance(audio, tuple):
936
+ audio = torch.cat(audio, dim=0)
937
+
938
+ # Convert audio to pretransform input channels
939
+ audio = set_audio_channels(audio, self.pretransform.io_channels)
940
+
941
+ latents = self.pretransform.encode(audio)
942
+
943
+ latents = self.proj_out(latents)
944
+
945
+ return [latents, torch.ones(latents.shape[0], latents.shape[2]).to(latents.device)]
946
+
947
+ class MultiConditioner(nn.Module):
948
+ """
949
+ A module that applies multiple conditioners to an input dictionary based on the keys
950
+
951
+ Args:
952
+ conditioners: a dictionary of conditioners with keys corresponding to the keys of the conditioning input dictionary (e.g. "prompt")
953
+ default_keys: a dictionary of default keys to use if the key is not in the input dictionary (e.g. {"prompt_t5": "prompt"})
954
+ """
955
+ def __init__(self, conditioners: tp.Dict[str, Conditioner], default_keys: tp.Dict[str, str] = {}):
956
+ super().__init__()
957
+
958
+ self.conditioners = nn.ModuleDict(conditioners)
959
+ self.default_keys = default_keys
960
+
961
+ def forward(self, batch_metadata: tp.List[tp.Dict[str, tp.Any]], device: tp.Union[torch.device, str]) -> tp.Dict[str, tp.Any]:
962
+ output = {}
963
+
964
+ for key, conditioner in self.conditioners.items():
965
+ condition_key = key
966
+
967
+ conditioner_inputs = []
968
+
969
+ for x in batch_metadata:
970
+
971
+ if condition_key not in x:
972
+ if condition_key in self.default_keys:
973
+ condition_key = self.default_keys[condition_key]
974
+ else:
975
+ raise ValueError(f"Conditioner key {condition_key} not found in batch metadata")
976
+
977
+ #Unwrap the condition info if it's a single-element list or tuple, this is to support collation functions that wrap everything in a list
978
+ if isinstance(x[condition_key], list) or isinstance(x[condition_key], tuple) and len(x[condition_key]) == 1:
979
+ conditioner_input = x[condition_key][0]
980
+
981
+ else:
982
+ conditioner_input = x[condition_key]
983
+
984
+ conditioner_inputs.append(conditioner_input)
985
+
986
+ cond_output = conditioner(conditioner_inputs, device)
987
+ if len(cond_output) == 1:
988
+ output[key] = cond_output[0]
989
+ elif len(cond_output) == 2:
990
+ output[key] = cond_output
991
+ elif len(cond_output) == 4:
992
+ output[key] = cond_output[:2]
993
+ output[f'{key}_g'] = cond_output[2:]
994
+
995
+ return output
996
+
997
+ def create_multi_conditioner_from_conditioning_config(config: tp.Dict[str, tp.Any]) -> MultiConditioner:
998
+ """
999
+ Create a MultiConditioner from a conditioning config dictionary
1000
+
1001
+ Args:
1002
+ config: the conditioning config dictionary
1003
+ device: the device to put the conditioners on
1004
+ """
1005
+ conditioners = {}
1006
+ cond_dim = config["cond_dim"]
1007
+
1008
+ default_keys = config.get("default_keys", {})
1009
+
1010
+ for conditioner_info in config["configs"]:
1011
+ id = conditioner_info["id"]
1012
+
1013
+ conditioner_type = conditioner_info["type"]
1014
+
1015
+ conditioner_config = {"output_dim": cond_dim}
1016
+
1017
+ conditioner_config.update(conditioner_info["config"])
1018
+ if conditioner_type == "t5":
1019
+ conditioners[id] = T5Conditioner(**conditioner_config)
1020
+ elif conditioner_type == "clap_text":
1021
+ conditioners[id] = CLAPTextConditioner(**conditioner_config)
1022
+ elif conditioner_type == "clip_text":
1023
+ conditioners[id] = CLIPTextConditioner(**conditioner_config)
1024
+ elif conditioner_type == "metaclip_text":
1025
+ conditioners[id] = MetaCLIPTextConditioner(**conditioner_config)
1026
+ elif conditioner_type == "clap_audio":
1027
+ conditioners[id] = CLAPAudioConditioner(**conditioner_config)
1028
+ elif conditioner_type == "cond_mlp":
1029
+ conditioners[id] = Cond_MLP(**conditioner_config)
1030
+ elif conditioner_type == "global_mlp":
1031
+ conditioners[id] = Global_MLP(**conditioner_config)
1032
+ elif conditioner_type == "sync_mlp":
1033
+ conditioners[id] = Sync_MLP(**conditioner_config)
1034
+ elif conditioner_type == "cond_mlp_1":
1035
+ conditioners[id] = Cond_MLP_1(**conditioner_config)
1036
+ elif conditioner_type == "cond_convmlp":
1037
+ conditioners[id] = Cond_ConvMLP(**conditioner_config)
1038
+ elif conditioner_type == "cond_mlp_global":
1039
+ conditioners[id] = Cond_MLP_Global(**conditioner_config)
1040
+ elif conditioner_type == "cond_mlp_global_1":
1041
+ conditioners[id] = Cond_MLP_Global_1(**conditioner_config)
1042
+ elif conditioner_type == "cond_mlp_global_2":
1043
+ conditioners[id] = Cond_MLP_Global_2(**conditioner_config)
1044
+ elif conditioner_type == "video_linear":
1045
+ conditioners[id] = Video_Linear(**conditioner_config)
1046
+ elif conditioner_type == "video_global":
1047
+ conditioners[id] = Video_Global(**conditioner_config)
1048
+ elif conditioner_type == "video_sync":
1049
+ conditioners[id] = Video_Sync(**conditioner_config)
1050
+ elif conditioner_type == "text_linear":
1051
+ conditioners[id] = Text_Linear(**conditioner_config)
1052
+ elif conditioner_type == "video_clip":
1053
+ conditioners[id] = CLIPConditioner(**conditioner_config)
1054
+ elif conditioner_type == "video_hiera":
1055
+ conditioners[id] = VideoHieraConditioner(**conditioner_config)
1056
+ elif conditioner_type == "meta_query":
1057
+ from .meta_queries.model import MLLMInContext
1058
+ conditioners[id] = MLLMInContext(**conditioner_config)
1059
+ elif conditioner_type == "int":
1060
+ conditioners[id] = IntConditioner(**conditioner_config)
1061
+ elif conditioner_type == "number":
1062
+ conditioners[id] = NumberConditioner(**conditioner_config)
1063
+ elif conditioner_type == "phoneme":
1064
+ conditioners[id] = PhonemeConditioner(**conditioner_config)
1065
+ elif conditioner_type == "lut":
1066
+ conditioners[id] = TokenizerLUTConditioner(**conditioner_config)
1067
+ elif conditioner_type == "pretransform":
1068
+ sample_rate = conditioner_config.pop("sample_rate", None)
1069
+ assert sample_rate is not None, "Sample rate must be specified for pretransform conditioners"
1070
+
1071
+ pretransform = create_pretransform_from_config(conditioner_config.pop("pretransform_config"), sample_rate=sample_rate)
1072
+
1073
+ if conditioner_config.get("pretransform_ckpt_path", None) is not None:
1074
+ pretransform.load_state_dict(load_ckpt_state_dict(conditioner_config.pop("pretransform_ckpt_path")))
1075
+
1076
+ conditioners[id] = PretransformConditioner(pretransform, **conditioner_config)
1077
+ elif conditioner_type == "mm_unchang":
1078
+ conditioners[id] = mm_unchang(**conditioner_config)
1079
+ else:
1080
+ raise ValueError(f"Unknown conditioner type: {conditioner_type}")
1081
+
1082
+ return MultiConditioner(conditioners, default_keys=default_keys)
ThinkSound/models/diffusion.py ADDED
@@ -0,0 +1,957 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from torch.nn import functional as F
4
+ from functools import partial
5
+ import numpy as np
6
+ import typing as tp
7
+
8
+ from .blocks import ResConvBlock, FourierFeatures, Upsample1d, Upsample1d_2, Downsample1d, Downsample1d_2, SelfAttention1d, SkipBlock, expand_to_planes
9
+ from .conditioners import MultiConditioner, create_multi_conditioner_from_conditioning_config
10
+ from .dit import DiffusionTransformer
11
+ #from .mmdit import MMAudio
12
+ from .factory import create_pretransform_from_config
13
+ from .pretransforms import Pretransform
14
+ from ..inference.generation import generate_diffusion_cond
15
+
16
+ from .adp import UNetCFG1d, UNet1d
17
+
18
+ from time import time
19
+
20
+ class Profiler:
21
+
22
+ def __init__(self):
23
+ self.ticks = [[time(), None]]
24
+
25
+ def tick(self, msg):
26
+ self.ticks.append([time(), msg])
27
+
28
+ def __repr__(self):
29
+ rep = 80 * "=" + "\n"
30
+ for i in range(1, len(self.ticks)):
31
+ msg = self.ticks[i][1]
32
+ ellapsed = self.ticks[i][0] - self.ticks[i - 1][0]
33
+ rep += msg + f": {ellapsed*1000:.2f}ms\n"
34
+ rep += 80 * "=" + "\n\n\n"
35
+ return rep
36
+
37
+ class DiffusionModel(nn.Module):
38
+ def __init__(self, *args, **kwargs):
39
+ super().__init__(*args, **kwargs)
40
+
41
+ def forward(self, x, t, **kwargs):
42
+ raise NotImplementedError()
43
+
44
+ class DiffusionModelWrapper(nn.Module):
45
+ def __init__(
46
+ self,
47
+ model: DiffusionModel,
48
+ io_channels,
49
+ sample_size,
50
+ sample_rate,
51
+ min_input_length,
52
+ pretransform: tp.Optional[Pretransform] = None,
53
+ ):
54
+ super().__init__()
55
+ self.io_channels = io_channels
56
+ self.sample_size = sample_size
57
+ self.sample_rate = sample_rate
58
+ self.min_input_length = min_input_length
59
+
60
+ self.model = model
61
+
62
+ if pretransform is not None:
63
+ self.pretransform = pretransform
64
+ else:
65
+ self.pretransform = None
66
+
67
+ def forward(self, x, t, **kwargs):
68
+ return self.model(x, t, **kwargs)
69
+
70
+ class ConditionedDiffusionModel(nn.Module):
71
+ def __init__(self,
72
+ *args,
73
+ supports_cross_attention: bool = False,
74
+ supports_input_concat: bool = False,
75
+ supports_global_cond: bool = False,
76
+ supports_prepend_cond: bool = False,
77
+ **kwargs):
78
+ super().__init__(*args, **kwargs)
79
+ self.supports_cross_attention = supports_cross_attention
80
+ self.supports_input_concat = supports_input_concat
81
+ self.supports_global_cond = supports_global_cond
82
+ self.supports_prepend_cond = supports_prepend_cond
83
+
84
+ def forward(self,
85
+ x: torch.Tensor,
86
+ t: torch.Tensor,
87
+ cross_attn_cond: torch.Tensor = None,
88
+ cross_attn_mask: torch.Tensor = None,
89
+ input_concat_cond: torch.Tensor = None,
90
+ global_embed: torch.Tensor = None,
91
+ prepend_cond: torch.Tensor = None,
92
+ prepend_cond_mask: torch.Tensor = None,
93
+ cfg_scale: float = 1.0,
94
+ cfg_dropout_prob: float = 0.0,
95
+ batch_cfg: bool = False,
96
+ rescale_cfg: bool = False,
97
+ **kwargs):
98
+ raise NotImplementedError()
99
+
100
+ class ConditionedDiffusionModelWrapper(nn.Module):
101
+ """
102
+ A diffusion model that takes in conditioning
103
+ """
104
+ def __init__(
105
+ self,
106
+ model: ConditionedDiffusionModel,
107
+ conditioner: MultiConditioner,
108
+ io_channels,
109
+ sample_rate,
110
+ min_input_length: int,
111
+ diffusion_objective: tp.Literal["v", "rectified_flow"] = "v",
112
+ zero_init: bool = False,
113
+ pretransform: tp.Optional[Pretransform] = None,
114
+ cross_attn_cond_ids: tp.List[str] = [],
115
+ global_cond_ids: tp.List[str] = [],
116
+ input_concat_ids: tp.List[str] = [],
117
+ prepend_cond_ids: tp.List[str] = [],
118
+ add_cond_ids: tp.List[str] = [],
119
+ sync_cond_ids: tp.List[str] = [],
120
+ ):
121
+ super().__init__()
122
+
123
+ self.model = model
124
+ self.conditioner = conditioner
125
+ self.io_channels = io_channels
126
+ self.sample_rate = sample_rate
127
+ self.diffusion_objective = diffusion_objective
128
+ self.pretransform = pretransform
129
+ self.cross_attn_cond_ids = cross_attn_cond_ids
130
+ self.global_cond_ids = global_cond_ids
131
+ self.input_concat_ids = input_concat_ids
132
+ self.prepend_cond_ids = prepend_cond_ids
133
+ self.add_cond_ids = add_cond_ids
134
+ self.sync_cond_ids = sync_cond_ids
135
+ self.min_input_length = min_input_length
136
+ def _basic_init(module):
137
+ if isinstance(module, nn.Linear):
138
+ torch.nn.init.xavier_uniform_(module.weight)
139
+ if module.bias is not None:
140
+ nn.init.constant_(module.bias, 0)
141
+
142
+ if zero_init is True:
143
+ self.conditioner.apply(_basic_init)
144
+ self.model.model.initialize_weights()
145
+
146
+
147
+ def get_conditioning_inputs(self, conditioning_tensors: tp.Dict[str, tp.Any], negative=False):
148
+ cross_attention_input = None
149
+ cross_attention_masks = None
150
+ global_cond = None
151
+ input_concat_cond = None
152
+ prepend_cond = None
153
+ prepend_cond_mask = None
154
+ add_input = None
155
+ sync_input = None
156
+
157
+ if len(self.cross_attn_cond_ids) > 0:
158
+ # Concatenate all cross-attention inputs over the sequence dimension
159
+ # Assumes that the cross-attention inputs are of shape (batch, seq, channels)
160
+ cross_attention_input = []
161
+ cross_attention_masks = []
162
+
163
+ for key in self.cross_attn_cond_ids:
164
+ cross_attn_in, cross_attn_mask = conditioning_tensors[key]
165
+
166
+ # Add sequence dimension if it's not there
167
+ if len(cross_attn_in.shape) == 2:
168
+ cross_attn_in = cross_attn_in.unsqueeze(1)
169
+ # cross_attn_mask = cross_attn_mask.unsqueeze(1)
170
+
171
+ cross_attention_input.append(cross_attn_in)
172
+ cross_attention_masks.append(cross_attn_mask)
173
+ # import ipdb
174
+ # ipdb.set_trace()
175
+ cross_attention_input = torch.cat(cross_attention_input, dim=1)
176
+ cross_attention_masks = torch.cat(cross_attention_masks, dim=1)
177
+
178
+ if len(self.add_cond_ids) > 0:
179
+ # Concatenate all cross-attention inputs over the sequence dimension
180
+ # Assumes that the cross-attention inputs are of shape (batch, seq, channels)
181
+ add_input = []
182
+
183
+ for key in self.add_cond_ids:
184
+ add_in = conditioning_tensors[key][0]
185
+
186
+ # Add sequence dimension if it's not there
187
+ if len(add_in.shape) == 2:
188
+ add_in = add_in.unsqueeze(1)
189
+ # add_in = add_in.transpose(1,2)
190
+ # add_in = F.interpolate(add_in, (194, ), mode='linear', align_corners=False)
191
+ # add_in = add_in.transpose(1,2)
192
+ add_input.append(add_in)
193
+
194
+ add_input = torch.cat(add_input, dim=2)
195
+
196
+ if len(self.sync_cond_ids) > 0:
197
+ # Concatenate all cross-attention inputs over the sequence dimension
198
+ # Assumes that the cross-attention inputs are of shape (batch, seq, channels)
199
+ sync_input = []
200
+
201
+ for key in self.sync_cond_ids:
202
+ sync_in = conditioning_tensors[key][0]
203
+
204
+ # Add sequence dimension if it's not there
205
+ if len(sync_in.shape) == 2:
206
+ sync_in = sync_in.unsqueeze(1)
207
+ sync_input.append(sync_in)
208
+
209
+ sync_input = torch.cat(sync_input, dim=2)
210
+
211
+ if len(self.global_cond_ids) > 0:
212
+ # Concatenate all global conditioning inputs over the channel dimension
213
+ # Assumes that the global conditioning inputs are of shape (batch, channels)
214
+ global_conds = []
215
+ for key in self.global_cond_ids:
216
+ global_cond_input = conditioning_tensors[key][0]
217
+ if len(global_cond_input.shape) == 2:
218
+ global_cond_input = global_cond_input.unsqueeze(1)
219
+ global_conds.append(global_cond_input)
220
+
221
+ # # Concatenate over the channel dimension
222
+ # if global_conds[0].shape[-1] == 768:
223
+ # global_cond = torch.cat(global_conds, dim=-1)
224
+ # else:
225
+ # global_cond = sum(global_conds)
226
+ global_cond = sum(global_conds)
227
+ # global_cond = torch.cat(global_conds, dim=-1)
228
+
229
+ if len(global_cond.shape) == 3:
230
+ global_cond = global_cond.squeeze(1)
231
+
232
+ if len(self.input_concat_ids) > 0:
233
+ # Concatenate all input concat conditioning inputs over the channel dimension
234
+ # Assumes that the input concat conditioning inputs are of shape (batch, channels, seq)
235
+ input_concat_cond = torch.cat([conditioning_tensors[key][0] for key in self.input_concat_ids], dim=1)
236
+
237
+ if len(self.prepend_cond_ids) > 0:
238
+ # Concatenate all prepend conditioning inputs over the sequence dimension
239
+ # Assumes that the prepend conditioning inputs are of shape (batch, seq, channels)
240
+ prepend_conds = []
241
+ prepend_cond_masks = []
242
+
243
+ for key in self.prepend_cond_ids:
244
+ prepend_cond_input, prepend_cond_mask = conditioning_tensors[key]
245
+ if len(prepend_cond_input.shape) == 2:
246
+ prepend_cond_input = prepend_cond_input.unsqueeze(1)
247
+ prepend_conds.append(prepend_cond_input)
248
+ prepend_cond_masks.append(prepend_cond_mask)
249
+
250
+ prepend_cond = torch.cat(prepend_conds, dim=1)
251
+ prepend_cond_mask = torch.cat(prepend_cond_masks, dim=1)
252
+
253
+ if negative:
254
+ return {
255
+ "negative_cross_attn_cond": cross_attention_input,
256
+ "negative_cross_attn_mask": cross_attention_masks,
257
+ "negative_global_cond": global_cond,
258
+ "negative_input_concat_cond": input_concat_cond
259
+ }
260
+ else:
261
+ return {
262
+ "cross_attn_cond": cross_attention_input,
263
+ "cross_attn_mask": cross_attention_masks,
264
+ "global_cond": global_cond,
265
+ "input_concat_cond": input_concat_cond,
266
+ "prepend_cond": prepend_cond,
267
+ "prepend_cond_mask": prepend_cond_mask,
268
+ "add_cond": add_input,
269
+ "sync_cond": sync_input
270
+ }
271
+
272
+ def forward(self, x: torch.Tensor, t: torch.Tensor, cond: tp.Dict[str, tp.Any], **kwargs):
273
+ return self.model(x, t, **self.get_conditioning_inputs(cond), **kwargs)
274
+
275
+ def generate(self, *args, **kwargs):
276
+ return generate_diffusion_cond(self, *args, **kwargs)
277
+
278
+ class UNetCFG1DWrapper(ConditionedDiffusionModel):
279
+ def __init__(
280
+ self,
281
+ *args,
282
+ **kwargs
283
+ ):
284
+ super().__init__(supports_cross_attention=True, supports_global_cond=True, supports_input_concat=True)
285
+
286
+ self.model = UNetCFG1d(*args, **kwargs)
287
+
288
+ with torch.no_grad():
289
+ for param in self.model.parameters():
290
+ param *= 0.5
291
+
292
+ def forward(self,
293
+ x,
294
+ t,
295
+ cross_attn_cond=None,
296
+ cross_attn_mask=None,
297
+ input_concat_cond=None,
298
+ global_cond=None,
299
+ cfg_scale=1.0,
300
+ cfg_dropout_prob: float = 0.0,
301
+ batch_cfg: bool = False,
302
+ rescale_cfg: bool = False,
303
+ negative_cross_attn_cond=None,
304
+ negative_cross_attn_mask=None,
305
+ negative_global_cond=None,
306
+ negative_input_concat_cond=None,
307
+ prepend_cond=None,
308
+ prepend_cond_mask=None,
309
+ **kwargs):
310
+ p = Profiler()
311
+
312
+ p.tick("start")
313
+
314
+ channels_list = None
315
+ if input_concat_cond is not None:
316
+ channels_list = [input_concat_cond]
317
+
318
+ outputs = self.model(
319
+ x,
320
+ t,
321
+ embedding=cross_attn_cond,
322
+ embedding_mask=cross_attn_mask,
323
+ features=global_cond,
324
+ channels_list=channels_list,
325
+ embedding_scale=cfg_scale,
326
+ embedding_mask_proba=cfg_dropout_prob,
327
+ batch_cfg=batch_cfg,
328
+ rescale_cfg=rescale_cfg,
329
+ negative_embedding=negative_cross_attn_cond,
330
+ negative_embedding_mask=negative_cross_attn_mask,
331
+ **kwargs)
332
+
333
+ p.tick("UNetCFG1D forward")
334
+
335
+ #print(f"Profiler: {p}")
336
+ return outputs
337
+
338
+ class UNet1DCondWrapper(ConditionedDiffusionModel):
339
+ def __init__(
340
+ self,
341
+ *args,
342
+ **kwargs
343
+ ):
344
+ super().__init__(supports_cross_attention=False, supports_global_cond=True, supports_input_concat=True)
345
+
346
+ self.model = UNet1d(*args, **kwargs)
347
+
348
+ with torch.no_grad():
349
+ for param in self.model.parameters():
350
+ param *= 0.5
351
+
352
+ def forward(self,
353
+ x,
354
+ t,
355
+ input_concat_cond=None,
356
+ global_cond=None,
357
+ cross_attn_cond=None,
358
+ cross_attn_mask=None,
359
+ prepend_cond=None,
360
+ prepend_cond_mask=None,
361
+ cfg_scale=1.0,
362
+ cfg_dropout_prob: float = 0.0,
363
+ batch_cfg: bool = False,
364
+ rescale_cfg: bool = False,
365
+ negative_cross_attn_cond=None,
366
+ negative_cross_attn_mask=None,
367
+ negative_global_cond=None,
368
+ negative_input_concat_cond=None,
369
+ **kwargs):
370
+
371
+ channels_list = None
372
+ if input_concat_cond is not None:
373
+
374
+ # Interpolate input_concat_cond to the same length as x
375
+ if input_concat_cond.shape[2] != x.shape[2]:
376
+ input_concat_cond = F.interpolate(input_concat_cond, (x.shape[2], ), mode='nearest')
377
+
378
+ channels_list = [input_concat_cond]
379
+
380
+ outputs = self.model(
381
+ x,
382
+ t,
383
+ features=global_cond,
384
+ channels_list=channels_list,
385
+ **kwargs)
386
+
387
+ return outputs
388
+
389
+ class UNet1DUncondWrapper(DiffusionModel):
390
+ def __init__(
391
+ self,
392
+ in_channels,
393
+ *args,
394
+ **kwargs
395
+ ):
396
+ super().__init__()
397
+
398
+ self.model = UNet1d(in_channels=in_channels, *args, **kwargs)
399
+
400
+ self.io_channels = in_channels
401
+
402
+ with torch.no_grad():
403
+ for param in self.model.parameters():
404
+ param *= 0.5
405
+
406
+ def forward(self, x, t, **kwargs):
407
+ return self.model(x, t, **kwargs)
408
+
409
+ class DAU1DCondWrapper(ConditionedDiffusionModel):
410
+ def __init__(
411
+ self,
412
+ *args,
413
+ **kwargs
414
+ ):
415
+ super().__init__(supports_cross_attention=False, supports_global_cond=False, supports_input_concat=True)
416
+
417
+ self.model = DiffusionAttnUnet1D(*args, **kwargs)
418
+
419
+ with torch.no_grad():
420
+ for param in self.model.parameters():
421
+ param *= 0.5
422
+
423
+ def forward(self,
424
+ x,
425
+ t,
426
+ input_concat_cond=None,
427
+ cross_attn_cond=None,
428
+ cross_attn_mask=None,
429
+ global_cond=None,
430
+ cfg_scale=1.0,
431
+ cfg_dropout_prob: float = 0.0,
432
+ batch_cfg: bool = False,
433
+ rescale_cfg: bool = False,
434
+ negative_cross_attn_cond=None,
435
+ negative_cross_attn_mask=None,
436
+ negative_global_cond=None,
437
+ negative_input_concat_cond=None,
438
+ prepend_cond=None,
439
+ **kwargs):
440
+
441
+ return self.model(x, t, cond = input_concat_cond)
442
+
443
+ class DiffusionAttnUnet1D(nn.Module):
444
+ def __init__(
445
+ self,
446
+ io_channels = 2,
447
+ depth=14,
448
+ n_attn_layers = 6,
449
+ channels = [128, 128, 256, 256] + [512] * 10,
450
+ cond_dim = 0,
451
+ cond_noise_aug = False,
452
+ kernel_size = 5,
453
+ learned_resample = False,
454
+ strides = [2] * 13,
455
+ conv_bias = True,
456
+ use_snake = False
457
+ ):
458
+ super().__init__()
459
+
460
+ self.cond_noise_aug = cond_noise_aug
461
+
462
+ self.io_channels = io_channels
463
+
464
+ if self.cond_noise_aug:
465
+ self.rng = torch.quasirandom.SobolEngine(1, scramble=True)
466
+
467
+ self.timestep_embed = FourierFeatures(1, 16)
468
+
469
+ attn_layer = depth - n_attn_layers
470
+
471
+ strides = [1] + strides
472
+
473
+ block = nn.Identity()
474
+
475
+ conv_block = partial(ResConvBlock, kernel_size=kernel_size, conv_bias = conv_bias, use_snake=use_snake)
476
+
477
+ for i in range(depth, 0, -1):
478
+ c = channels[i - 1]
479
+ stride = strides[i-1]
480
+ if stride > 2 and not learned_resample:
481
+ raise ValueError("Must have stride 2 without learned resampling")
482
+
483
+ if i > 1:
484
+ c_prev = channels[i - 2]
485
+ add_attn = i >= attn_layer and n_attn_layers > 0
486
+ block = SkipBlock(
487
+ Downsample1d_2(c_prev, c_prev, stride) if (learned_resample or stride == 1) else Downsample1d("cubic"),
488
+ conv_block(c_prev, c, c),
489
+ SelfAttention1d(
490
+ c, c // 32) if add_attn else nn.Identity(),
491
+ conv_block(c, c, c),
492
+ SelfAttention1d(
493
+ c, c // 32) if add_attn else nn.Identity(),
494
+ conv_block(c, c, c),
495
+ SelfAttention1d(
496
+ c, c // 32) if add_attn else nn.Identity(),
497
+ block,
498
+ conv_block(c * 2 if i != depth else c, c, c),
499
+ SelfAttention1d(
500
+ c, c // 32) if add_attn else nn.Identity(),
501
+ conv_block(c, c, c),
502
+ SelfAttention1d(
503
+ c, c // 32) if add_attn else nn.Identity(),
504
+ conv_block(c, c, c_prev),
505
+ SelfAttention1d(c_prev, c_prev //
506
+ 32) if add_attn else nn.Identity(),
507
+ Upsample1d_2(c_prev, c_prev, stride) if learned_resample else Upsample1d(kernel="cubic")
508
+ )
509
+ else:
510
+ cond_embed_dim = 16 if not self.cond_noise_aug else 32
511
+ block = nn.Sequential(
512
+ conv_block((io_channels + cond_dim) + cond_embed_dim, c, c),
513
+ conv_block(c, c, c),
514
+ conv_block(c, c, c),
515
+ block,
516
+ conv_block(c * 2, c, c),
517
+ conv_block(c, c, c),
518
+ conv_block(c, c, io_channels, is_last=True),
519
+ )
520
+ self.net = block
521
+
522
+ with torch.no_grad():
523
+ for param in self.net.parameters():
524
+ param *= 0.5
525
+
526
+ def forward(self, x, t, cond=None, cond_aug_scale=None):
527
+
528
+ timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), x.shape)
529
+
530
+ inputs = [x, timestep_embed]
531
+
532
+ if cond is not None:
533
+ if cond.shape[2] != x.shape[2]:
534
+ cond = F.interpolate(cond, (x.shape[2], ), mode='linear', align_corners=False)
535
+
536
+ if self.cond_noise_aug:
537
+ # Get a random number between 0 and 1, uniformly sampled
538
+ if cond_aug_scale is None:
539
+ aug_level = self.rng.draw(cond.shape[0])[:, 0].to(cond)
540
+ else:
541
+ aug_level = torch.tensor([cond_aug_scale]).repeat([cond.shape[0]]).to(cond)
542
+
543
+ # Add noise to the conditioning signal
544
+ cond = cond + torch.randn_like(cond) * aug_level[:, None, None]
545
+
546
+ # Get embedding for noise cond level, reusing timestamp_embed
547
+ aug_level_embed = expand_to_planes(self.timestep_embed(aug_level[:, None]), x.shape)
548
+
549
+ inputs.append(aug_level_embed)
550
+
551
+ inputs.append(cond)
552
+
553
+ outputs = self.net(torch.cat(inputs, dim=1))
554
+
555
+ return outputs
556
+
557
+ class DiTWrapper(ConditionedDiffusionModel):
558
+ def __init__(
559
+ self,
560
+ *args,
561
+ **kwargs
562
+ ):
563
+ super().__init__(supports_cross_attention=True, supports_global_cond=False, supports_input_concat=False)
564
+
565
+ self.model = DiffusionTransformer(*args, **kwargs)
566
+ # with torch.no_grad():
567
+ # for param in self.model.parameters():
568
+ # param *= 0.5
569
+
570
+ def forward(self,
571
+ x,
572
+ t,
573
+ cross_attn_cond=None,
574
+ cross_attn_mask=None,
575
+ negative_cross_attn_cond=None,
576
+ negative_cross_attn_mask=None,
577
+ input_concat_cond=None,
578
+ negative_input_concat_cond=None,
579
+ global_cond=None,
580
+ negative_global_cond=None,
581
+ prepend_cond=None,
582
+ prepend_cond_mask=None,
583
+ cfg_scale=1.0,
584
+ cfg_dropout_prob: float = 0.0,
585
+ batch_cfg: bool = True,
586
+ rescale_cfg: bool = False,
587
+ scale_phi: float = 0.0,
588
+ **kwargs):
589
+
590
+ assert batch_cfg, "batch_cfg must be True for DiTWrapper"
591
+ #assert negative_input_concat_cond is None, "negative_input_concat_cond is not supported for DiTWrapper"
592
+
593
+ return self.model(
594
+ x,
595
+ t,
596
+ cross_attn_cond=cross_attn_cond,
597
+ cross_attn_cond_mask=cross_attn_mask,
598
+ negative_cross_attn_cond=negative_cross_attn_cond,
599
+ negative_cross_attn_mask=negative_cross_attn_mask,
600
+ input_concat_cond=input_concat_cond,
601
+ prepend_cond=prepend_cond,
602
+ prepend_cond_mask=prepend_cond_mask,
603
+ cfg_scale=cfg_scale,
604
+ cfg_dropout_prob=cfg_dropout_prob,
605
+ scale_phi=scale_phi,
606
+ global_embed=global_cond,
607
+ **kwargs)
608
+
609
+ class MMDiTWrapper(ConditionedDiffusionModel):
610
+ def __init__(
611
+ self,
612
+ *args,
613
+ **kwargs
614
+ ):
615
+ super().__init__(supports_cross_attention=True, supports_global_cond=False, supports_input_concat=False)
616
+
617
+ self.model = MMAudio(*args, **kwargs)
618
+
619
+ # with torch.no_grad():
620
+ # for param in self.model.parameters():
621
+ # param *= 0.5
622
+
623
+ def forward(self,
624
+ x,
625
+ t,
626
+ clip_f,
627
+ sync_f,
628
+ text_f,
629
+ inpaint_masked_input=None,
630
+ t5_features=None,
631
+ metaclip_global_text_features=None,
632
+ cfg_scale=1.0,
633
+ cfg_dropout_prob: float = 0.0,
634
+ batch_cfg: bool = True,
635
+ rescale_cfg: bool = False,
636
+ scale_phi: float = 0.0,
637
+ **kwargs):
638
+
639
+ # breakpoint()
640
+ assert batch_cfg, "batch_cfg must be True for DiTWrapper"
641
+ #assert negative_input_concat_cond is None, "negative_input_concat_cond is not supported for DiTWrapper"
642
+
643
+ return self.model(
644
+ latent=x,
645
+ t=t,
646
+ clip_f=clip_f,
647
+ sync_f=sync_f,
648
+ text_f=text_f,
649
+ inpaint_masked_input=inpaint_masked_input,
650
+ t5_features=t5_features,
651
+ metaclip_global_text_features=metaclip_global_text_features,
652
+ cfg_scale=cfg_scale,
653
+ cfg_dropout_prob=cfg_dropout_prob,
654
+ scale_phi=scale_phi,
655
+ **kwargs)
656
+
657
+ class MMConditionedDiffusionModelWrapper(ConditionedDiffusionModel):
658
+ """
659
+ A diffusion model that takes in conditioning
660
+ """
661
+ def __init__(
662
+ self,
663
+ model,
664
+ conditioner: MultiConditioner,
665
+ io_channels,
666
+ sample_rate,
667
+ min_input_length: int,
668
+ diffusion_objective: tp.Literal["v", "rectified_flow"] = "v",
669
+ pretransform: tp.Optional[Pretransform] = None,
670
+ cross_attn_cond_ids: tp.List[str] = [],
671
+ global_cond_ids: tp.List[str] = [],
672
+ input_concat_ids: tp.List[str] = [],
673
+ prepend_cond_ids: tp.List[str] = [],
674
+ add_cond_ids: tp.List[str] = [],
675
+ mm_cond_ids: tp.List[str] = [],
676
+ ):
677
+ super().__init__()
678
+
679
+ self.model = model
680
+ self.conditioner = conditioner
681
+ self.io_channels = io_channels
682
+ self.sample_rate = sample_rate
683
+ self.diffusion_objective = diffusion_objective
684
+ self.pretransform = pretransform
685
+ self.cross_attn_cond_ids = cross_attn_cond_ids
686
+ self.global_cond_ids = global_cond_ids
687
+ self.input_concat_ids = input_concat_ids
688
+ self.prepend_cond_ids = prepend_cond_ids
689
+ self.add_cond_ids = add_cond_ids
690
+ self.min_input_length = min_input_length
691
+ self.mm_cond_ids = mm_cond_ids
692
+
693
+ assert len(self.cross_attn_cond_ids) == 0, "cross_attn_cond_ids is not supported for MMDiTWrapper"
694
+ assert len(self.global_cond_ids) == 0, "global_cond_ids is not supported for MMDiTWrapper"
695
+ assert len(self.input_concat_ids) == 0, "input_concat_ids is not supported for MMDiTWrapper"
696
+ assert len(self.prepend_cond_ids) == 0, "prepend_cond_ids is not supported for MMDiTWrapper"
697
+ assert len(self.add_cond_ids) == 0, "add_cond_ids is not supported for MMDiTWrapper"
698
+ assert len(self.mm_cond_ids) > 0, "mm_cond_ids must be specified for MMDiTWrapper"
699
+ assert "metaclip_features" in self.mm_cond_ids, "clip_f must be specified in mm_cond_ids for MMDiTWrapper"
700
+ assert "sync_features" in self.mm_cond_ids, "sync_features must be specified in mm_cond_ids for MMDiTWrapper"
701
+ assert "metaclip_text_features" in self.mm_cond_ids, "metaclip_text_features must be specified in mm_cond_ids for MMDiTWrapper"
702
+ # assert len(self.mm_cond_ids) == 3, "mm_cond_ids must be clip_f sync_f text_f for MMDiTWrapper"
703
+
704
+ def get_conditioning_inputs(self, conditioning_tensors: tp.Dict[str, tp.Any], negative=False):
705
+ assert negative == False, "negative conditioning is not supported for MMDiTWrapper"
706
+ cross_attention_input = None
707
+ cross_attention_masks = None
708
+ global_cond = None
709
+ input_concat_cond = None
710
+ prepend_cond = None
711
+ prepend_cond_mask = None
712
+ add_input = None
713
+ inpaint_masked_input = None
714
+ t5_features = None
715
+ metaclip_global_text_features = None
716
+ clip_f = conditioning_tensors["metaclip_features"]
717
+ sync_f = conditioning_tensors["sync_features"]
718
+ text_f = conditioning_tensors["metaclip_text_features"]
719
+ if 'inpaint_masked_input' in conditioning_tensors.keys():
720
+ inpaint_masked_input = conditioning_tensors["inpaint_masked_input"]
721
+ if 't5_features' in conditioning_tensors.keys():
722
+ t5_features = conditioning_tensors["t5_features"]
723
+ if 'metaclip_global_text_features' in conditioning_tensors.keys():
724
+ metaclip_global_text_features = conditioning_tensors["metaclip_global_text_features"]
725
+ return {
726
+ "clip_f": clip_f,
727
+ "sync_f": sync_f,
728
+ "text_f": text_f,
729
+ "inpaint_masked_input": inpaint_masked_input,
730
+ "t5_features": t5_features,
731
+ "metaclip_global_text_features": metaclip_global_text_features
732
+ }
733
+
734
+ def forward(self, x: torch.Tensor, t: torch.Tensor, cond: tp.Dict[str, tp.Any], **kwargs):
735
+ # breakpoint()
736
+ # print(kwargs)
737
+ return self.model(x=x, t=t, **self.get_conditioning_inputs(cond), **kwargs)
738
+
739
+ def generate(self, *args, **kwargs):
740
+ return generate_diffusion_cond(self, *args, **kwargs)
741
+
742
+ class DiTUncondWrapper(DiffusionModel):
743
+ def __init__(
744
+ self,
745
+ io_channels,
746
+ *args,
747
+ **kwargs
748
+ ):
749
+ super().__init__()
750
+
751
+ self.model = DiffusionTransformer(io_channels=io_channels, *args, **kwargs)
752
+
753
+ self.io_channels = io_channels
754
+
755
+ with torch.no_grad():
756
+ for param in self.model.parameters():
757
+ param *= 0.5
758
+
759
+ def forward(self, x, t, **kwargs):
760
+ return self.model(x, t, **kwargs)
761
+
762
+ def create_diffusion_uncond_from_config(config: tp.Dict[str, tp.Any]):
763
+ diffusion_uncond_config = config["model"]
764
+
765
+ model_type = diffusion_uncond_config.get('type', None)
766
+
767
+ diffusion_config = diffusion_uncond_config.get('config', {})
768
+
769
+ assert model_type is not None, "Must specify model type in config"
770
+
771
+ pretransform = diffusion_uncond_config.get("pretransform", None)
772
+
773
+ sample_size = config.get("sample_size", None)
774
+ assert sample_size is not None, "Must specify sample size in config"
775
+
776
+ sample_rate = config.get("sample_rate", None)
777
+ assert sample_rate is not None, "Must specify sample rate in config"
778
+
779
+ if pretransform is not None:
780
+ pretransform = create_pretransform_from_config(pretransform, sample_rate)
781
+ min_input_length = pretransform.downsampling_ratio
782
+ else:
783
+ min_input_length = 1
784
+
785
+ if model_type == 'DAU1d':
786
+
787
+ model = DiffusionAttnUnet1D(
788
+ **diffusion_config
789
+ )
790
+
791
+ elif model_type == "adp_uncond_1d":
792
+
793
+ model = UNet1DUncondWrapper(
794
+ **diffusion_config
795
+ )
796
+
797
+ elif model_type == "dit":
798
+ model = DiTUncondWrapper(
799
+ **diffusion_config
800
+ )
801
+
802
+ else:
803
+ raise NotImplementedError(f'Unknown model type: {model_type}')
804
+
805
+ return DiffusionModelWrapper(model,
806
+ io_channels=model.io_channels,
807
+ sample_size=sample_size,
808
+ sample_rate=sample_rate,
809
+ pretransform=pretransform,
810
+ min_input_length=min_input_length)
811
+
812
+ def create_diffusion_infill_from_config(config: tp.Dict[str, tp.Any]):
813
+ diffusion_uncond_config = config["model"]
814
+
815
+
816
+ diffusion_config = diffusion_uncond_config.get('diffusion', {})
817
+ model_type = diffusion_config.get('type', None)
818
+ model_config = diffusion_config.get("config",{})
819
+ assert model_type is not None, "Must specify model type in config"
820
+
821
+ pretransform = diffusion_uncond_config.get("pretransform", None)
822
+
823
+ sample_size = config.get("sample_size", None)
824
+ assert sample_size is not None, "Must specify sample size in config"
825
+
826
+ sample_rate = config.get("sample_rate", None)
827
+ assert sample_rate is not None, "Must specify sample rate in config"
828
+
829
+ if pretransform is not None:
830
+ pretransform = create_pretransform_from_config(pretransform, sample_rate)
831
+ min_input_length = pretransform.downsampling_ratio
832
+ else:
833
+ min_input_length = 1
834
+
835
+ if model_type == 'DAU1d':
836
+
837
+ model = DiffusionAttnUnet1D(
838
+ **model_config
839
+ )
840
+
841
+ elif model_type == "adp_uncond_1d":
842
+
843
+ model = UNet1DUncondWrapper(
844
+ io_channels = io_channels,
845
+ **model_config
846
+ )
847
+ elif model_type == "dit":
848
+ model = DiTUncondWrapper(
849
+ **model_config
850
+ )
851
+
852
+ else:
853
+ raise NotImplementedError(f'Unknown model type: {model_type}')
854
+
855
+ return DiffusionModelWrapper(model,
856
+ io_channels=model.io_channels,
857
+ sample_size=sample_size,
858
+ sample_rate=sample_rate,
859
+ pretransform=pretransform,
860
+ min_input_length=min_input_length)
861
+
862
+ def create_diffusion_cond_from_config(config: tp.Dict[str, tp.Any]):
863
+
864
+ model_config = config["model"]
865
+
866
+ model_type = config["model_type"]
867
+
868
+ diffusion_config = model_config.get('diffusion', None)
869
+ assert diffusion_config is not None, "Must specify diffusion config"
870
+
871
+ diffusion_model_type = diffusion_config.get('type', None)
872
+ assert diffusion_model_type is not None, "Must specify diffusion model type"
873
+
874
+ diffusion_model_config = diffusion_config.get('config', None)
875
+ assert diffusion_model_config is not None, "Must specify diffusion model config"
876
+
877
+ if diffusion_model_type == 'adp_cfg_1d':
878
+ diffusion_model = UNetCFG1DWrapper(**diffusion_model_config)
879
+ elif diffusion_model_type == 'adp_1d':
880
+ diffusion_model = UNet1DCondWrapper(**diffusion_model_config)
881
+ elif diffusion_model_type == 'dit':
882
+ diffusion_model = DiTWrapper(**diffusion_model_config)
883
+ elif diffusion_model_type == 'mmdit':
884
+ diffusion_model = MMDiTWrapper(**diffusion_model_config)
885
+
886
+ io_channels = model_config.get('io_channels', None)
887
+ assert io_channels is not None, "Must specify io_channels in model config"
888
+
889
+ sample_rate = config.get('sample_rate', None)
890
+ assert sample_rate is not None, "Must specify sample_rate in config"
891
+
892
+ diffusion_objective = diffusion_config.get('diffusion_objective', 'v')
893
+
894
+ conditioning_config = model_config.get('conditioning', None)
895
+
896
+ conditioner = None
897
+ if conditioning_config is not None:
898
+ conditioner = create_multi_conditioner_from_conditioning_config(conditioning_config)
899
+
900
+ cross_attention_ids = diffusion_config.get('cross_attention_cond_ids', [])
901
+ add_cond_ids = diffusion_config.get('add_cond_ids', [])
902
+ sync_cond_ids = diffusion_config.get('sync_cond_ids', [])
903
+ global_cond_ids = diffusion_config.get('global_cond_ids', [])
904
+ input_concat_ids = diffusion_config.get('input_concat_ids', [])
905
+ prepend_cond_ids = diffusion_config.get('prepend_cond_ids', [])
906
+ mm_cond_ids = diffusion_config.get('mm_cond_ids', [])
907
+ zero_init = diffusion_config.get('zero_init', False)
908
+ pretransform = model_config.get("pretransform", None)
909
+
910
+ if pretransform is not None:
911
+ pretransform = create_pretransform_from_config(pretransform, sample_rate)
912
+ min_input_length = pretransform.downsampling_ratio
913
+ else:
914
+ min_input_length = 1
915
+
916
+ if diffusion_model_type == "adp_cfg_1d" or diffusion_model_type == "adp_1d":
917
+ min_input_length *= np.prod(diffusion_model_config["factors"])
918
+ elif diffusion_model_type == "dit":
919
+ min_input_length *= diffusion_model.model.patch_size
920
+
921
+ # Get the proper wrapper class
922
+
923
+ extra_kwargs = {}
924
+
925
+ if model_type == "mm_diffusion_cond":
926
+ wrapper_fn = MMConditionedDiffusionModelWrapper
927
+ extra_kwargs["diffusion_objective"] = diffusion_objective
928
+ extra_kwargs["mm_cond_ids"] = mm_cond_ids
929
+
930
+ if model_type == "diffusion_cond" or model_type == "diffusion_cond_inpaint" or model_type == 'diffusion_infill':
931
+ wrapper_fn = ConditionedDiffusionModelWrapper
932
+ extra_kwargs["diffusion_objective"] = diffusion_objective
933
+
934
+ elif model_type == "diffusion_prior":
935
+ prior_type = model_config.get("prior_type", None)
936
+ assert prior_type is not None, "Must specify prior_type in diffusion prior model config"
937
+
938
+ if prior_type == "mono_stereo":
939
+ from .diffusion_prior import MonoToStereoDiffusionPrior
940
+ wrapper_fn = MonoToStereoDiffusionPrior
941
+
942
+ return wrapper_fn(
943
+ diffusion_model,
944
+ conditioner,
945
+ min_input_length=min_input_length,
946
+ sample_rate=sample_rate,
947
+ cross_attn_cond_ids=cross_attention_ids,
948
+ global_cond_ids=global_cond_ids,
949
+ input_concat_ids=input_concat_ids,
950
+ prepend_cond_ids=prepend_cond_ids,
951
+ add_cond_ids=add_cond_ids,
952
+ sync_cond_ids=sync_cond_ids,
953
+ pretransform=pretransform,
954
+ io_channels=io_channels,
955
+ zero_init=zero_init,
956
+ **extra_kwargs
957
+ )
ThinkSound/models/diffusion_prior.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ import typing as tp
3
+
4
+ from .diffusion import ConditionedDiffusionModelWrapper
5
+ from ..inference.generation import generate_diffusion_cond
6
+ from ..inference.utils import prepare_audio
7
+
8
+ import torch
9
+ from torch.nn import functional as F
10
+ from torchaudio import transforms as T
11
+
12
+ # Define prior types enum
13
+ class PriorType(Enum):
14
+ MonoToStereo = 1
15
+
16
+ class DiffusionPrior(ConditionedDiffusionModelWrapper):
17
+ def __init__(self, *args, prior_type: PriorType=None, **kwargs):
18
+ super().__init__(*args, **kwargs)
19
+ self.prior_type = prior_type
20
+
21
+ class MonoToStereoDiffusionPrior(DiffusionPrior):
22
+ def __init__(self, *args, **kwargs):
23
+ super().__init__(*args, prior_type=PriorType.MonoToStereo, **kwargs)
24
+
25
+ def stereoize(
26
+ self,
27
+ audio: torch.Tensor, # (batch, channels, time)
28
+ video: torch.Tensor,
29
+ in_sr: int,
30
+ steps: int,
31
+ sampler_kwargs: dict = {},
32
+ ):
33
+ """
34
+ Generate stereo audio from mono audio using a pre-trained diffusion prior
35
+
36
+ Args:
37
+ audio: The mono audio to convert to stereo
38
+ in_sr: The sample rate of the input audio
39
+ steps: The number of diffusion steps to run
40
+ sampler_kwargs: Keyword arguments to pass to the diffusion sampler
41
+ """
42
+
43
+ device = audio.device
44
+
45
+ sample_rate = self.sample_rate
46
+
47
+ # Resample input audio if necessary
48
+ if in_sr != sample_rate:
49
+ resample_tf = T.Resample(in_sr, sample_rate).to(audio.device)
50
+ audio = resample_tf(audio)
51
+
52
+ audio_length = audio.shape[-1]
53
+
54
+ # # Pad input audio to be compatible with the model
55
+ # min_length = self.min_input_length
56
+ # padded_input_length = audio_length + (min_length - (audio_length % min_length)) % min_length
57
+
58
+ # # Pad input audio to be compatible with the model
59
+ # if padded_input_length > audio_length:
60
+ # audio = F.pad(audio, (0, padded_input_length - audio_length))
61
+
62
+ # Make audio mono, duplicate to stereo
63
+ dual_mono = audio.mean(1, keepdim=True).repeat(1, 2, 1)
64
+
65
+ if self.pretransform is not None:
66
+ dual_mono = self.pretransform.encode(dual_mono)
67
+
68
+ conditioning = self.conditioner([{'video':video}], device)
69
+ # Return fake stereo audio
70
+ conditioning["source"] = [dual_mono]
71
+ stereo_audio = generate_diffusion_cond(
72
+ self,
73
+ conditioning_tensors=conditioning,
74
+ steps=steps,
75
+ sample_size=audio_length,
76
+ sample_rate=sample_rate,
77
+ device=device,
78
+ cfg_scale=1,
79
+ **sampler_kwargs,
80
+ )
81
+
82
+ return stereo_audio
ThinkSound/models/discriminators.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+ from functools import reduce
6
+ import typing as tp
7
+ from einops import rearrange
8
+ from audiotools import AudioSignal, STFTParams
9
+ from dac.model.discriminator import WNConv1d, WNConv2d
10
+
11
+ def get_hinge_losses(score_real, score_fake):
12
+ gen_loss = -score_fake.mean()
13
+ dis_loss = torch.relu(1 - score_real).mean() + torch.relu(1 + score_fake).mean()
14
+ return dis_loss, gen_loss
15
+
16
+ class EncodecDiscriminator(nn.Module):
17
+
18
+ def __init__(self, *args, **kwargs):
19
+ super().__init__()
20
+
21
+ from encodec.msstftd import MultiScaleSTFTDiscriminator
22
+
23
+ self.discriminators = MultiScaleSTFTDiscriminator(*args, **kwargs)
24
+
25
+ def forward(self, x):
26
+ logits, features = self.discriminators(x)
27
+ return logits, features
28
+
29
+ def loss(self, x, y):
30
+ feature_matching_distance = 0.
31
+ logits_true, feature_true = self.forward(x)
32
+ logits_fake, feature_fake = self.forward(y)
33
+
34
+ dis_loss = torch.tensor(0.)
35
+ adv_loss = torch.tensor(0.)
36
+
37
+ for i, (scale_true, scale_fake) in enumerate(zip(feature_true, feature_fake)):
38
+
39
+ feature_matching_distance = feature_matching_distance + sum(
40
+ map(
41
+ lambda x, y: abs(x - y).mean(),
42
+ scale_true,
43
+ scale_fake,
44
+ )) / len(scale_true)
45
+
46
+ _dis, _adv = get_hinge_losses(
47
+ logits_true[i],
48
+ logits_fake[i],
49
+ )
50
+
51
+ dis_loss = dis_loss + _dis
52
+ adv_loss = adv_loss + _adv
53
+
54
+ return dis_loss, adv_loss, feature_matching_distance
55
+
56
+ # Discriminators from oobleck
57
+
58
+ IndividualDiscriminatorOut = tp.Tuple[torch.Tensor, tp.Sequence[torch.Tensor]]
59
+
60
+ TensorDict = tp.Dict[str, torch.Tensor]
61
+
62
+ class SharedDiscriminatorConvNet(nn.Module):
63
+
64
+ def __init__(
65
+ self,
66
+ in_size: int,
67
+ convolution: tp.Union[nn.Conv1d, nn.Conv2d],
68
+ out_size: int = 1,
69
+ capacity: int = 32,
70
+ n_layers: int = 4,
71
+ kernel_size: int = 15,
72
+ stride: int = 4,
73
+ activation: tp.Callable[[], nn.Module] = lambda: nn.SiLU(),
74
+ normalization: tp.Callable[[nn.Module], nn.Module] = torch.nn.utils.weight_norm,
75
+ ) -> None:
76
+ super().__init__()
77
+ channels = [in_size]
78
+ channels += list(capacity * 2**np.arange(n_layers))
79
+
80
+ if isinstance(stride, int):
81
+ stride = n_layers * [stride]
82
+
83
+ net = []
84
+ for i in range(n_layers):
85
+ if isinstance(kernel_size, int):
86
+ pad = kernel_size // 2
87
+ s = stride[i]
88
+ else:
89
+ pad = kernel_size[0] // 2
90
+ s = (stride[i], 1)
91
+
92
+ net.append(
93
+ normalization(
94
+ convolution(
95
+ channels[i],
96
+ channels[i + 1],
97
+ kernel_size,
98
+ stride=s,
99
+ padding=pad,
100
+ )))
101
+ net.append(activation())
102
+
103
+ net.append(convolution(channels[-1], out_size, 1))
104
+
105
+ self.net = nn.ModuleList(net)
106
+
107
+ def forward(self, x) -> IndividualDiscriminatorOut:
108
+ features = []
109
+ for layer in self.net:
110
+ x = layer(x)
111
+ if isinstance(layer, nn.modules.conv._ConvNd):
112
+ features.append(x)
113
+ score = x.reshape(x.shape[0], -1).mean(-1)
114
+ return score, features
115
+
116
+
117
+ class MultiScaleDiscriminator(nn.Module):
118
+
119
+ def __init__(self,
120
+ in_channels: int,
121
+ n_scales: int,
122
+ **conv_kwargs) -> None:
123
+ super().__init__()
124
+ layers = []
125
+ for _ in range(n_scales):
126
+ layers.append(SharedDiscriminatorConvNet(in_channels, nn.Conv1d, **conv_kwargs))
127
+ self.layers = nn.ModuleList(layers)
128
+
129
+ def forward(self, x: torch.Tensor) -> IndividualDiscriminatorOut:
130
+ score = 0
131
+ features = []
132
+ for layer in self.layers:
133
+ s, f = layer(x)
134
+ score = score + s
135
+ features.extend(f)
136
+ x = nn.functional.avg_pool1d(x, 2)
137
+ return score, features
138
+
139
+ class MultiPeriodDiscriminator(nn.Module):
140
+
141
+ def __init__(self,
142
+ in_channels: int,
143
+ periods: tp.Sequence[int],
144
+ **conv_kwargs) -> None:
145
+ super().__init__()
146
+ layers = []
147
+ self.periods = periods
148
+
149
+ for _ in periods:
150
+ layers.append(SharedDiscriminatorConvNet(in_channels, nn.Conv2d, **conv_kwargs))
151
+
152
+ self.layers = nn.ModuleList(layers)
153
+
154
+ def forward(self, x: torch.Tensor) -> IndividualDiscriminatorOut:
155
+ score = 0
156
+ features = []
157
+ for layer, n in zip(self.layers, self.periods):
158
+ s, f = layer(self.fold(x, n))
159
+ score = score + s
160
+ features.extend(f)
161
+ return score, features
162
+
163
+ def fold(self, x: torch.Tensor, n: int) -> torch.Tensor:
164
+ pad = (n - (x.shape[-1] % n)) % n
165
+ x = nn.functional.pad(x, (0, pad))
166
+ return x.reshape(*x.shape[:2], -1, n)
167
+
168
+
169
+ class MultiDiscriminator(nn.Module):
170
+ """
171
+ Individual discriminators should take a single tensor as input (NxB C T) and
172
+ return a tuple composed of a score tensor (NxB) and a Sequence of Features
173
+ Sequence[NxB C' T'].
174
+ """
175
+
176
+ def __init__(self, discriminator_list: tp.Sequence[nn.Module],
177
+ keys: tp.Sequence[str]) -> None:
178
+ super().__init__()
179
+ self.discriminators = nn.ModuleList(discriminator_list)
180
+ self.keys = keys
181
+
182
+ def unpack_tensor_to_dict(self, features: torch.Tensor) -> TensorDict:
183
+ features = features.chunk(len(self.keys), 0)
184
+ return {k: features[i] for i, k in enumerate(self.keys)}
185
+
186
+ @staticmethod
187
+ def concat_dicts(dict_a, dict_b):
188
+ out_dict = {}
189
+ keys = set(list(dict_a.keys()) + list(dict_b.keys()))
190
+ for k in keys:
191
+ out_dict[k] = []
192
+ if k in dict_a:
193
+ if isinstance(dict_a[k], list):
194
+ out_dict[k].extend(dict_a[k])
195
+ else:
196
+ out_dict[k].append(dict_a[k])
197
+ if k in dict_b:
198
+ if isinstance(dict_b[k], list):
199
+ out_dict[k].extend(dict_b[k])
200
+ else:
201
+ out_dict[k].append(dict_b[k])
202
+ return out_dict
203
+
204
+ @staticmethod
205
+ def sum_dicts(dict_a, dict_b):
206
+ out_dict = {}
207
+ keys = set(list(dict_a.keys()) + list(dict_b.keys()))
208
+ for k in keys:
209
+ out_dict[k] = 0.
210
+ if k in dict_a:
211
+ out_dict[k] = out_dict[k] + dict_a[k]
212
+ if k in dict_b:
213
+ out_dict[k] = out_dict[k] + dict_b[k]
214
+ return out_dict
215
+
216
+ def forward(self, inputs: TensorDict) -> TensorDict:
217
+ discriminator_input = torch.cat([inputs[k] for k in self.keys], 0)
218
+ all_scores = []
219
+ all_features = []
220
+
221
+ for discriminator in self.discriminators:
222
+ score, features = discriminator(discriminator_input)
223
+ scores = self.unpack_tensor_to_dict(score)
224
+ scores = {f"score_{k}": scores[k] for k in scores.keys()}
225
+ all_scores.append(scores)
226
+
227
+ features = map(self.unpack_tensor_to_dict, features)
228
+ features = reduce(self.concat_dicts, features)
229
+ features = {f"features_{k}": features[k] for k in features.keys()}
230
+ all_features.append(features)
231
+
232
+ all_scores = reduce(self.sum_dicts, all_scores)
233
+ all_features = reduce(self.concat_dicts, all_features)
234
+
235
+ inputs.update(all_scores)
236
+ inputs.update(all_features)
237
+
238
+ return inputs
239
+
240
+ class OobleckDiscriminator(nn.Module):
241
+
242
+ def __init__(
243
+ self,
244
+ in_channels=1,
245
+ ):
246
+ super().__init__()
247
+
248
+ multi_scale_discriminator = MultiScaleDiscriminator(
249
+ in_channels=in_channels,
250
+ n_scales=3,
251
+ )
252
+
253
+ multi_period_discriminator = MultiPeriodDiscriminator(
254
+ in_channels=in_channels,
255
+ periods=[2, 3, 5, 7, 11]
256
+ )
257
+
258
+ # multi_resolution_discriminator = MultiScaleSTFTDiscriminator(
259
+ # filters=32,
260
+ # in_channels = in_channels,
261
+ # out_channels = 1,
262
+ # n_ffts = [2048, 1024, 512, 256, 128],
263
+ # hop_lengths = [512, 256, 128, 64, 32],
264
+ # win_lengths = [2048, 1024, 512, 256, 128]
265
+ # )
266
+
267
+ self.multi_discriminator = MultiDiscriminator(
268
+ [multi_scale_discriminator, multi_period_discriminator], #, multi_resolution_discriminator],
269
+ ["reals", "fakes"]
270
+ )
271
+
272
+ def loss(self, reals, fakes):
273
+ inputs = {
274
+ "reals": reals,
275
+ "fakes": fakes,
276
+ }
277
+
278
+ inputs = self.multi_discriminator(inputs)
279
+
280
+ scores_real = inputs["score_reals"]
281
+ scores_fake = inputs["score_fakes"]
282
+
283
+ features_real = inputs["features_reals"]
284
+ features_fake = inputs["features_fakes"]
285
+
286
+ dis_loss, gen_loss = get_hinge_losses(scores_real, scores_fake)
287
+
288
+ feature_matching_distance = torch.tensor(0.)
289
+
290
+ for _, (scale_real, scale_fake) in enumerate(zip(features_real, features_fake)):
291
+
292
+ feature_matching_distance = feature_matching_distance + sum(
293
+ map(
294
+ lambda real, fake: abs(real - fake).mean(),
295
+ scale_real,
296
+ scale_fake,
297
+ )) / len(scale_real)
298
+
299
+ return dis_loss, gen_loss, feature_matching_distance
300
+
301
+
302
+ ## Discriminators from Descript Audio Codec repo
303
+ ## Copied and modified under MIT license, see LICENSES/LICENSE_DESCRIPT.txt
304
+ class MPD(nn.Module):
305
+ def __init__(self, period, channels=1):
306
+ super().__init__()
307
+
308
+ self.period = period
309
+ self.convs = nn.ModuleList(
310
+ [
311
+ WNConv2d(channels, 32, (5, 1), (3, 1), padding=(2, 0)),
312
+ WNConv2d(32, 128, (5, 1), (3, 1), padding=(2, 0)),
313
+ WNConv2d(128, 512, (5, 1), (3, 1), padding=(2, 0)),
314
+ WNConv2d(512, 1024, (5, 1), (3, 1), padding=(2, 0)),
315
+ WNConv2d(1024, 1024, (5, 1), 1, padding=(2, 0)),
316
+ ]
317
+ )
318
+ self.conv_post = WNConv2d(
319
+ 1024, 1, kernel_size=(3, 1), padding=(1, 0), act=False
320
+ )
321
+
322
+ def pad_to_period(self, x):
323
+ t = x.shape[-1]
324
+ x = F.pad(x, (0, self.period - t % self.period), mode="reflect")
325
+ return x
326
+
327
+ def forward(self, x):
328
+ fmap = []
329
+
330
+ x = self.pad_to_period(x)
331
+ x = rearrange(x, "b c (l p) -> b c l p", p=self.period)
332
+
333
+ for layer in self.convs:
334
+ x = layer(x)
335
+ fmap.append(x)
336
+
337
+ x = self.conv_post(x)
338
+ fmap.append(x)
339
+
340
+ return fmap
341
+
342
+
343
+ class MSD(nn.Module):
344
+ def __init__(self, rate: int = 1, sample_rate: int = 44100, channels=1):
345
+ super().__init__()
346
+
347
+ self.convs = nn.ModuleList(
348
+ [
349
+ WNConv1d(channels, 16, 15, 1, padding=7),
350
+ WNConv1d(16, 64, 41, 4, groups=4, padding=20),
351
+ WNConv1d(64, 256, 41, 4, groups=16, padding=20),
352
+ WNConv1d(256, 1024, 41, 4, groups=64, padding=20),
353
+ WNConv1d(1024, 1024, 41, 4, groups=256, padding=20),
354
+ WNConv1d(1024, 1024, 5, 1, padding=2),
355
+ ]
356
+ )
357
+ self.conv_post = WNConv1d(1024, 1, 3, 1, padding=1, act=False)
358
+ self.sample_rate = sample_rate
359
+ self.rate = rate
360
+
361
+ def forward(self, x):
362
+ x = AudioSignal(x, self.sample_rate)
363
+ x.resample(self.sample_rate // self.rate)
364
+ x = x.audio_data
365
+
366
+ fmap = []
367
+
368
+ for l in self.convs:
369
+ x = l(x)
370
+ fmap.append(x)
371
+ x = self.conv_post(x)
372
+ fmap.append(x)
373
+
374
+ return fmap
375
+
376
+
377
+ BANDS = [(0.0, 0.1), (0.1, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1.0)]
378
+
379
+
380
+ class MRD(nn.Module):
381
+ def __init__(
382
+ self,
383
+ window_length: int,
384
+ hop_factor: float = 0.25,
385
+ sample_rate: int = 44100,
386
+ bands: list = BANDS,
387
+ channels: int = 1
388
+ ):
389
+ """Complex multi-band spectrogram discriminator.
390
+ Parameters
391
+ ----------
392
+ window_length : int
393
+ Window length of STFT.
394
+ hop_factor : float, optional
395
+ Hop factor of the STFT, defaults to ``0.25 * window_length``.
396
+ sample_rate : int, optional
397
+ Sampling rate of audio in Hz, by default 44100
398
+ bands : list, optional
399
+ Bands to run discriminator over.
400
+ """
401
+ super().__init__()
402
+
403
+ self.window_length = window_length
404
+ self.hop_factor = hop_factor
405
+ self.sample_rate = sample_rate
406
+ self.stft_params = STFTParams(
407
+ window_length=window_length,
408
+ hop_length=int(window_length * hop_factor),
409
+ match_stride=True,
410
+ )
411
+
412
+ self.channels = channels
413
+
414
+ n_fft = window_length // 2 + 1
415
+ bands = [(int(b[0] * n_fft), int(b[1] * n_fft)) for b in bands]
416
+ self.bands = bands
417
+
418
+ ch = 32
419
+ convs = lambda: nn.ModuleList(
420
+ [
421
+ WNConv2d(2, ch, (3, 9), (1, 1), padding=(1, 4)),
422
+ WNConv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4)),
423
+ WNConv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4)),
424
+ WNConv2d(ch, ch, (3, 9), (1, 2), padding=(1, 4)),
425
+ WNConv2d(ch, ch, (3, 3), (1, 1), padding=(1, 1)),
426
+ ]
427
+ )
428
+ self.band_convs = nn.ModuleList([convs() for _ in range(len(self.bands))])
429
+ self.conv_post = WNConv2d(ch, 1, (3, 3), (1, 1), padding=(1, 1), act=False)
430
+
431
+ def spectrogram(self, x):
432
+ x = AudioSignal(x, self.sample_rate, stft_params=self.stft_params)
433
+ x = torch.view_as_real(x.stft())
434
+ x = rearrange(x, "b ch f t c -> (b ch) c t f", ch=self.channels)
435
+ # Split into bands
436
+ x_bands = [x[..., b[0] : b[1]] for b in self.bands]
437
+ return x_bands
438
+
439
+ def forward(self, x):
440
+ x_bands = self.spectrogram(x)
441
+ fmap = []
442
+
443
+ x = []
444
+ for band, stack in zip(x_bands, self.band_convs):
445
+ for layer in stack:
446
+ band = layer(band)
447
+ fmap.append(band)
448
+ x.append(band)
449
+
450
+ x = torch.cat(x, dim=-1)
451
+ x = self.conv_post(x)
452
+ fmap.append(x)
453
+
454
+ return fmap
455
+
456
+
457
+ class DACDiscriminator(nn.Module):
458
+ def __init__(
459
+ self,
460
+ channels: int = 1,
461
+ rates: list = [],
462
+ periods: list = [2, 3, 5, 7, 11],
463
+ fft_sizes: list = [2048, 1024, 512],
464
+ sample_rate: int = 44100,
465
+ bands: list = BANDS,
466
+ ):
467
+ """Discriminator that combines multiple discriminators.
468
+
469
+ Parameters
470
+ ----------
471
+ rates : list, optional
472
+ sampling rates (in Hz) to run MSD at, by default []
473
+ If empty, MSD is not used.
474
+ periods : list, optional
475
+ periods (of samples) to run MPD at, by default [2, 3, 5, 7, 11]
476
+ fft_sizes : list, optional
477
+ Window sizes of the FFT to run MRD at, by default [2048, 1024, 512]
478
+ sample_rate : int, optional
479
+ Sampling rate of audio in Hz, by default 44100
480
+ bands : list, optional
481
+ Bands to run MRD at, by default `BANDS`
482
+ """
483
+ super().__init__()
484
+ discs = []
485
+ discs += [MPD(p, channels=channels) for p in periods]
486
+ discs += [MSD(r, sample_rate=sample_rate, channels=channels) for r in rates]
487
+ discs += [MRD(f, sample_rate=sample_rate, bands=bands, channels=channels) for f in fft_sizes]
488
+ self.discriminators = nn.ModuleList(discs)
489
+
490
+ def preprocess(self, y):
491
+ # Remove DC offset
492
+ y = y - y.mean(dim=-1, keepdims=True)
493
+ # Peak normalize the volume of input audio
494
+ y = 0.8 * y / (y.abs().max(dim=-1, keepdim=True)[0] + 1e-9)
495
+ return y
496
+
497
+ def forward(self, x):
498
+ x = self.preprocess(x)
499
+ fmaps = [d(x) for d in self.discriminators]
500
+ return fmaps
501
+
502
+ class DACGANLoss(nn.Module):
503
+ """
504
+ Computes a discriminator loss, given a discriminator on
505
+ generated waveforms/spectrograms compared to ground truth
506
+ waveforms/spectrograms. Computes the loss for both the
507
+ discriminator and the generator in separate functions.
508
+ """
509
+
510
+ def __init__(self, **discriminator_kwargs):
511
+ super().__init__()
512
+ self.discriminator = DACDiscriminator(**discriminator_kwargs)
513
+
514
+ def forward(self, fake, real):
515
+ d_fake = self.discriminator(fake)
516
+ d_real = self.discriminator(real)
517
+ return d_fake, d_real
518
+
519
+ def discriminator_loss(self, fake, real):
520
+ d_fake, d_real = self.forward(fake.clone().detach(), real)
521
+
522
+ loss_d = 0
523
+ for x_fake, x_real in zip(d_fake, d_real):
524
+ loss_d += torch.mean(x_fake[-1] ** 2)
525
+ loss_d += torch.mean((1 - x_real[-1]) ** 2)
526
+ return loss_d
527
+
528
+ def generator_loss(self, fake, real):
529
+ d_fake, d_real = self.forward(fake, real)
530
+
531
+ loss_g = 0
532
+ for x_fake in d_fake:
533
+ loss_g += torch.mean((1 - x_fake[-1]) ** 2)
534
+
535
+ loss_feature = 0
536
+
537
+ for i in range(len(d_fake)):
538
+ for j in range(len(d_fake[i]) - 1):
539
+ loss_feature += F.l1_loss(d_fake[i][j], d_real[i][j].detach())
540
+ return loss_g, loss_feature
541
+
542
+ def loss(self, fake, real):
543
+ gen_loss, feature_distance = self.generator_loss(fake, real)
544
+ dis_loss = self.discriminator_loss(fake, real)
545
+
546
+ return dis_loss, gen_loss, feature_distance
ThinkSound/models/dit (1).py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing as tp
2
+ import math
3
+ import torch
4
+
5
+ from einops import rearrange
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ from .blocks import FourierFeatures
10
+ from .transformer import ContinuousTransformer
11
+
12
+ class DiffusionTransformer(nn.Module):
13
+ def __init__(self,
14
+ io_channels=32,
15
+ patch_size=1,
16
+ embed_dim=768,
17
+ cond_token_dim=0,
18
+ project_cond_tokens=True,
19
+ global_cond_dim=0,
20
+ project_global_cond=True,
21
+ input_concat_dim=0,
22
+ prepend_cond_dim=0,
23
+ depth=12,
24
+ num_heads=8,
25
+ transformer_type: tp.Literal["continuous_transformer"] = "continuous_transformer",
26
+ global_cond_type: tp.Literal["prepend", "adaLN"] = "prepend",
27
+ timestep_cond_type: tp.Literal["global", "input_concat"] = "global",
28
+ timestep_embed_dim=None,
29
+ diffusion_objective: tp.Literal["v", "rectified_flow", "rf_denoiser"] = "v",
30
+ **kwargs):
31
+
32
+ super().__init__()
33
+
34
+ self.cond_token_dim = cond_token_dim
35
+
36
+ # Timestep embeddings
37
+ self.timestep_cond_type = timestep_cond_type
38
+
39
+ timestep_features_dim = 256
40
+
41
+ self.timestep_features = FourierFeatures(1, timestep_features_dim)
42
+
43
+ if timestep_cond_type == "global":
44
+ timestep_embed_dim = embed_dim
45
+ elif timestep_cond_type == "input_concat":
46
+ assert timestep_embed_dim is not None, "timestep_embed_dim must be specified if timestep_cond_type is input_concat"
47
+ input_concat_dim += timestep_embed_dim
48
+
49
+ self.to_timestep_embed = nn.Sequential(
50
+ nn.Linear(timestep_features_dim, timestep_embed_dim, bias=True),
51
+ nn.SiLU(),
52
+ nn.Linear(timestep_embed_dim, timestep_embed_dim, bias=True),
53
+ )
54
+
55
+ self.diffusion_objective = diffusion_objective
56
+
57
+ if cond_token_dim > 0:
58
+ # Conditioning tokens
59
+
60
+ cond_embed_dim = cond_token_dim if not project_cond_tokens else embed_dim
61
+ self.to_cond_embed = nn.Sequential(
62
+ nn.Linear(cond_token_dim, cond_embed_dim, bias=False),
63
+ nn.SiLU(),
64
+ nn.Linear(cond_embed_dim, cond_embed_dim, bias=False)
65
+ )
66
+ else:
67
+ cond_embed_dim = 0
68
+
69
+ if global_cond_dim > 0:
70
+ # Global conditioning
71
+ global_embed_dim = global_cond_dim if not project_global_cond else embed_dim
72
+ self.to_global_embed = nn.Sequential(
73
+ nn.Linear(global_cond_dim, global_embed_dim, bias=False),
74
+ nn.SiLU(),
75
+ nn.Linear(global_embed_dim, global_embed_dim, bias=False)
76
+ )
77
+
78
+ if prepend_cond_dim > 0:
79
+ # Prepend conditioning
80
+ self.to_prepend_embed = nn.Sequential(
81
+ nn.Linear(prepend_cond_dim, embed_dim, bias=False),
82
+ nn.SiLU(),
83
+ nn.Linear(embed_dim, embed_dim, bias=False)
84
+ )
85
+
86
+ self.input_concat_dim = input_concat_dim
87
+
88
+ dim_in = io_channels + self.input_concat_dim
89
+
90
+ self.patch_size = patch_size
91
+
92
+ # Transformer
93
+
94
+ self.transformer_type = transformer_type
95
+
96
+ self.global_cond_type = global_cond_type
97
+
98
+ if self.transformer_type == "continuous_transformer":
99
+
100
+ global_dim = None
101
+
102
+ if self.global_cond_type == "adaLN":
103
+ # The global conditioning is projected to the embed_dim already at this point
104
+ global_dim = embed_dim
105
+
106
+ self.transformer = ContinuousTransformer(
107
+ dim=embed_dim,
108
+ depth=depth,
109
+ dim_heads=embed_dim // num_heads,
110
+ dim_in=dim_in * patch_size,
111
+ dim_out=io_channels * patch_size,
112
+ cross_attend = cond_token_dim > 0,
113
+ cond_token_dim = cond_embed_dim,
114
+ global_cond_dim=global_dim,
115
+ **kwargs
116
+ )
117
+ else:
118
+ raise ValueError(f"Unknown transformer type: {self.transformer_type}")
119
+
120
+ self.preprocess_conv = nn.Conv1d(dim_in, dim_in, 1, bias=False)
121
+ nn.init.zeros_(self.preprocess_conv.weight)
122
+ self.postprocess_conv = nn.Conv1d(io_channels, io_channels, 1, bias=False)
123
+ nn.init.zeros_(self.postprocess_conv.weight)
124
+
125
+ def _forward(
126
+ self,
127
+ x,
128
+ t,
129
+ mask=None,
130
+ cross_attn_cond=None,
131
+ cross_attn_cond_mask=None,
132
+ input_concat_cond=None,
133
+ global_embed=None,
134
+ prepend_cond=None,
135
+ prepend_cond_mask=None,
136
+ return_info=False,
137
+ exit_layer_ix=None,
138
+ **kwargs):
139
+
140
+ if cross_attn_cond is not None:
141
+ cross_attn_cond = self.to_cond_embed(cross_attn_cond)
142
+
143
+ if global_embed is not None:
144
+ # Project the global conditioning to the embedding dimension
145
+ global_embed = self.to_global_embed(global_embed)
146
+
147
+ prepend_inputs = None
148
+ prepend_mask = None
149
+ prepend_length = 0
150
+ if prepend_cond is not None:
151
+ # Project the prepend conditioning to the embedding dimension
152
+ prepend_cond = self.to_prepend_embed(prepend_cond)
153
+
154
+ prepend_inputs = prepend_cond
155
+ if prepend_cond_mask is not None:
156
+ prepend_mask = prepend_cond_mask
157
+
158
+ prepend_length = prepend_cond.shape[1]
159
+
160
+ if input_concat_cond is not None:
161
+ # Interpolate input_concat_cond to the same length as x
162
+ if input_concat_cond.shape[2] != x.shape[2]:
163
+ input_concat_cond = F.interpolate(input_concat_cond, (x.shape[2], ), mode='nearest')
164
+
165
+ x = torch.cat([x, input_concat_cond], dim=1)
166
+
167
+ # Get the batch of timestep embeddings
168
+ timestep_embed = self.to_timestep_embed(self.timestep_features(t[:, None])) # (b, embed_dim)
169
+
170
+ # Timestep embedding is considered a global embedding. Add to the global conditioning if it exists
171
+
172
+ if self.timestep_cond_type == "global":
173
+ if global_embed is not None:
174
+ global_embed = global_embed + timestep_embed
175
+ else:
176
+ global_embed = timestep_embed
177
+ elif self.timestep_cond_type == "input_concat":
178
+ x = torch.cat([x, timestep_embed.unsqueeze(1).expand(-1, -1, x.shape[2])], dim=1)
179
+
180
+ # Add the global_embed to the prepend inputs if there is no global conditioning support in the transformer
181
+ if self.global_cond_type == "prepend" and global_embed is not None:
182
+ if prepend_inputs is None:
183
+ # Prepend inputs are just the global embed, and the mask is all ones
184
+ prepend_inputs = global_embed.unsqueeze(1)
185
+ prepend_mask = torch.ones((x.shape[0], 1), device=x.device, dtype=torch.bool)
186
+ else:
187
+ # Prepend inputs are the prepend conditioning + the global embed
188
+ prepend_inputs = torch.cat([prepend_inputs, global_embed.unsqueeze(1)], dim=1)
189
+ prepend_mask = torch.cat([prepend_mask, torch.ones((x.shape[0], 1), device=x.device, dtype=torch.bool)], dim=1)
190
+
191
+ prepend_length = prepend_inputs.shape[1]
192
+
193
+ x = self.preprocess_conv(x) + x
194
+
195
+ x = rearrange(x, "b c t -> b t c")
196
+
197
+ extra_args = {}
198
+
199
+ if self.global_cond_type == "adaLN":
200
+ extra_args["global_cond"] = global_embed
201
+
202
+ if self.patch_size > 1:
203
+ x = rearrange(x, "b (t p) c -> b t (c p)", p=self.patch_size)
204
+
205
+ if self.transformer_type == "continuous_transformer":
206
+ # Masks not currently implemented for continuous transformer
207
+ output = self.transformer(x, prepend_embeds=prepend_inputs, context=cross_attn_cond, return_info=return_info, exit_layer_ix=exit_layer_ix, **extra_args, **kwargs)
208
+
209
+ if return_info:
210
+ output, info = output
211
+
212
+ # Avoid postprocessing on early exit
213
+ if exit_layer_ix is not None:
214
+ if return_info:
215
+ return output, info
216
+ else:
217
+ return output
218
+
219
+ output = rearrange(output, "b t c -> b c t")[:,:,prepend_length:]
220
+
221
+ if self.patch_size > 1:
222
+ output = rearrange(output, "b (c p) t -> b c (t p)", p=self.patch_size)
223
+
224
+ output = self.postprocess_conv(output) + output
225
+
226
+ if return_info:
227
+ return output, info
228
+
229
+ return output
230
+
231
+ def forward(
232
+ self,
233
+ x,
234
+ t,
235
+ cross_attn_cond=None,
236
+ cross_attn_cond_mask=None,
237
+ negative_cross_attn_cond=None,
238
+ negative_cross_attn_mask=None,
239
+ input_concat_cond=None,
240
+ global_embed=None,
241
+ negative_global_embed=None,
242
+ prepend_cond=None,
243
+ prepend_cond_mask=None,
244
+ cfg_scale=1.0,
245
+ cfg_dropout_prob=0.0,
246
+ cfg_interval = (0, 1),
247
+ causal=False,
248
+ scale_phi=0.0,
249
+ mask=None,
250
+ return_info=False,
251
+ exit_layer_ix=None,
252
+ **kwargs):
253
+
254
+ assert causal == False, "Causal mode is not supported for DiffusionTransformer"
255
+
256
+ model_dtype = next(self.parameters()).dtype
257
+
258
+ x = x.to(model_dtype)
259
+
260
+ t = t.to(model_dtype)
261
+
262
+ if cross_attn_cond is not None:
263
+ cross_attn_cond = cross_attn_cond.to(model_dtype)
264
+
265
+ if negative_cross_attn_cond is not None:
266
+ negative_cross_attn_cond = negative_cross_attn_cond.to(model_dtype)
267
+
268
+ if input_concat_cond is not None:
269
+ input_concat_cond = input_concat_cond.to(model_dtype)
270
+
271
+ if global_embed is not None:
272
+ global_embed = global_embed.to(model_dtype)
273
+
274
+ if negative_global_embed is not None:
275
+ negative_global_embed = negative_global_embed.to(model_dtype)
276
+
277
+ if prepend_cond is not None:
278
+ prepend_cond = prepend_cond.to(model_dtype)
279
+
280
+ if cross_attn_cond_mask is not None:
281
+ cross_attn_cond_mask = cross_attn_cond_mask.bool()
282
+
283
+ cross_attn_cond_mask = None # Temporarily disabling conditioning masks due to kernel issue for flash attention
284
+
285
+ if prepend_cond_mask is not None:
286
+ prepend_cond_mask = prepend_cond_mask.bool()
287
+
288
+ # Early exit bypasses CFG processing
289
+ if exit_layer_ix is not None:
290
+ assert self.transformer_type == "continuous_transformer", "exit_layer_ix is only supported for continuous_transformer"
291
+ return self._forward(
292
+ x,
293
+ t,
294
+ cross_attn_cond=cross_attn_cond,
295
+ cross_attn_cond_mask=cross_attn_cond_mask,
296
+ input_concat_cond=input_concat_cond,
297
+ global_embed=global_embed,
298
+ prepend_cond=prepend_cond,
299
+ prepend_cond_mask=prepend_cond_mask,
300
+ mask=mask,
301
+ return_info=return_info,
302
+ exit_layer_ix=exit_layer_ix,
303
+ **kwargs
304
+ )
305
+
306
+ # CFG dropout
307
+ if cfg_dropout_prob > 0.0 and cfg_scale == 1.0:
308
+ if cross_attn_cond is not None:
309
+ null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device)
310
+ dropout_mask = torch.bernoulli(torch.full((cross_attn_cond.shape[0], 1, 1), cfg_dropout_prob, device=cross_attn_cond.device)).to(torch.bool)
311
+ cross_attn_cond = torch.where(dropout_mask, null_embed, cross_attn_cond)
312
+
313
+ if prepend_cond is not None:
314
+ null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device)
315
+ dropout_mask = torch.bernoulli(torch.full((prepend_cond.shape[0], 1, 1), cfg_dropout_prob, device=prepend_cond.device)).to(torch.bool)
316
+ prepend_cond = torch.where(dropout_mask, null_embed, prepend_cond)
317
+
318
+ if self.diffusion_objective == "v":
319
+ sigma = torch.sin(t * math.pi / 2)
320
+ alpha = torch.cos(t * math.pi / 2)
321
+ elif self.diffusion_objective in ["rectified_flow", "rf_denoiser"]:
322
+ sigma = t
323
+
324
+ if cfg_scale != 1.0 and (cross_attn_cond is not None or prepend_cond is not None) and (cfg_interval[0] <= sigma[0] <= cfg_interval[1]):
325
+
326
+ # Classifier-free guidance
327
+ # Concatenate conditioned and unconditioned inputs on the batch dimension
328
+ batch_inputs = torch.cat([x, x], dim=0)
329
+ batch_timestep = torch.cat([t, t], dim=0)
330
+
331
+ if global_embed is not None:
332
+ batch_global_cond = torch.cat([global_embed, global_embed], dim=0)
333
+ else:
334
+ batch_global_cond = None
335
+
336
+ if input_concat_cond is not None:
337
+ batch_input_concat_cond = torch.cat([input_concat_cond, input_concat_cond], dim=0)
338
+ else:
339
+ batch_input_concat_cond = None
340
+
341
+ batch_cond = None
342
+ batch_cond_masks = None
343
+
344
+ # Handle CFG for cross-attention conditioning
345
+ if cross_attn_cond is not None:
346
+
347
+ null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device)
348
+
349
+ # For negative cross-attention conditioning, replace the null embed with the negative cross-attention conditioning
350
+ if negative_cross_attn_cond is not None:
351
+
352
+ # If there's a negative cross-attention mask, set the masked tokens to the null embed
353
+ if negative_cross_attn_mask is not None:
354
+ negative_cross_attn_mask = negative_cross_attn_mask.to(torch.bool).unsqueeze(2)
355
+
356
+ negative_cross_attn_cond = torch.where(negative_cross_attn_mask, negative_cross_attn_cond, null_embed)
357
+
358
+ batch_cond = torch.cat([cross_attn_cond, negative_cross_attn_cond], dim=0)
359
+
360
+ else:
361
+ batch_cond = torch.cat([cross_attn_cond, null_embed], dim=0)
362
+
363
+ if cross_attn_cond_mask is not None:
364
+ batch_cond_masks = torch.cat([cross_attn_cond_mask, cross_attn_cond_mask], dim=0)
365
+
366
+ batch_prepend_cond = None
367
+ batch_prepend_cond_mask = None
368
+
369
+ if prepend_cond is not None:
370
+
371
+ null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device)
372
+
373
+ batch_prepend_cond = torch.cat([prepend_cond, null_embed], dim=0)
374
+
375
+ if prepend_cond_mask is not None:
376
+ batch_prepend_cond_mask = torch.cat([prepend_cond_mask, prepend_cond_mask], dim=0)
377
+
378
+
379
+ if mask is not None:
380
+ batch_masks = torch.cat([mask, mask], dim=0)
381
+ else:
382
+ batch_masks = None
383
+
384
+ batch_output = self._forward(
385
+ batch_inputs,
386
+ batch_timestep,
387
+ cross_attn_cond=batch_cond,
388
+ cross_attn_cond_mask=batch_cond_masks,
389
+ mask = batch_masks,
390
+ input_concat_cond=batch_input_concat_cond,
391
+ global_embed = batch_global_cond,
392
+ prepend_cond = batch_prepend_cond,
393
+ prepend_cond_mask = batch_prepend_cond_mask,
394
+ return_info = return_info,
395
+ **kwargs)
396
+
397
+ if return_info:
398
+ batch_output, info = batch_output
399
+
400
+ cond_output, uncond_output = torch.chunk(batch_output, 2, dim=0)
401
+ cfg_output = uncond_output + (cond_output - uncond_output) * cfg_scale
402
+
403
+ # CFG Rescale
404
+ if scale_phi != 0.0:
405
+ cond_out_std = cond_output.std(dim=1, keepdim=True)
406
+ out_cfg_std = cfg_output.std(dim=1, keepdim=True)
407
+ output = scale_phi * (cfg_output * (cond_out_std/out_cfg_std)) + (1-scale_phi) * cfg_output
408
+ else:
409
+ output = cfg_output
410
+
411
+ if return_info:
412
+ info["uncond_output"] = uncond_output
413
+ return output, info
414
+
415
+ return output
416
+
417
+ else:
418
+ return self._forward(
419
+ x,
420
+ t,
421
+ cross_attn_cond=cross_attn_cond,
422
+ cross_attn_cond_mask=cross_attn_cond_mask,
423
+ input_concat_cond=input_concat_cond,
424
+ global_embed=global_embed,
425
+ prepend_cond=prepend_cond,
426
+ prepend_cond_mask=prepend_cond_mask,
427
+ mask=mask,
428
+ return_info=return_info,
429
+ **kwargs
430
+ )
ThinkSound/models/dit.py ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing as tp
2
+ import math
3
+ import torch
4
+ # from beartype.typing import Tuple
5
+ from einops import rearrange
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+ from .mmmodules.model.low_level import MLP, ChannelLastConv1d, ConvMLP
9
+ from .blocks import FourierFeatures
10
+ from .transformer import ContinuousTransformer
11
+ from .utils import mask_from_frac_lengths, resample
12
+
13
+ class DiffusionTransformer(nn.Module):
14
+ def __init__(self,
15
+ io_channels=32,
16
+ patch_size=1,
17
+ embed_dim=768,
18
+ cond_token_dim=0,
19
+ project_cond_tokens=True,
20
+ global_cond_dim=0,
21
+ project_global_cond=True,
22
+ input_concat_dim=0,
23
+ prepend_cond_dim=0,
24
+ cond_ctx_dim=0,
25
+ depth=12,
26
+ num_heads=8,
27
+ transformer_type: tp.Literal["continuous_transformer"] = "continuous_transformer",
28
+ global_cond_type: tp.Literal["prepend", "adaLN"] = "prepend",
29
+ timestep_cond_type: tp.Literal["global", "input_concat"] = "global",
30
+ add_token_dim=0,
31
+ sync_token_dim=0,
32
+ use_mlp=False,
33
+ use_zero_init=False,
34
+ **kwargs):
35
+
36
+ super().__init__()
37
+
38
+ self.cond_token_dim = cond_token_dim
39
+
40
+ # Timestep embeddings
41
+ timestep_features_dim = 256
42
+ # Timestep embeddings
43
+ self.timestep_cond_type = timestep_cond_type
44
+ self.timestep_features = FourierFeatures(1, timestep_features_dim)
45
+
46
+ if timestep_cond_type == "global":
47
+ timestep_embed_dim = embed_dim
48
+ elif timestep_cond_type == "input_concat":
49
+ assert timestep_embed_dim is not None, "timestep_embed_dim must be specified if timestep_cond_type is input_concat"
50
+ input_concat_dim += timestep_embed_dim
51
+
52
+ self.to_timestep_embed = nn.Sequential(
53
+ nn.Linear(timestep_features_dim, embed_dim, bias=True),
54
+ nn.SiLU(),
55
+ nn.Linear(embed_dim, embed_dim, bias=True),
56
+ )
57
+ self.use_mlp = use_mlp
58
+ if cond_token_dim > 0:
59
+ # Conditioning tokens
60
+ cond_embed_dim = cond_token_dim if not project_cond_tokens else embed_dim
61
+ self.to_cond_embed = nn.Sequential(
62
+ nn.Linear(cond_token_dim, cond_embed_dim, bias=False),
63
+ nn.SiLU(),
64
+ nn.Linear(cond_embed_dim, cond_embed_dim, bias=False)
65
+ )
66
+ else:
67
+ cond_embed_dim = 0
68
+
69
+ if global_cond_dim > 0:
70
+ # Global conditioning
71
+ global_embed_dim = global_cond_dim if not project_global_cond else embed_dim
72
+ self.to_global_embed = nn.Sequential(
73
+ nn.Linear(global_cond_dim, global_embed_dim, bias=False),
74
+ nn.SiLU(),
75
+ nn.Linear(global_embed_dim, global_embed_dim, bias=False)
76
+ )
77
+ if add_token_dim > 0:
78
+ # Conditioning tokens
79
+ add_embed_dim = add_token_dim if not project_cond_tokens else embed_dim
80
+ self.to_add_embed = nn.Sequential(
81
+ nn.Linear(add_token_dim, add_embed_dim, bias=False),
82
+ nn.SiLU(),
83
+ nn.Linear(add_embed_dim, add_embed_dim, bias=False)
84
+ )
85
+ else:
86
+ add_embed_dim = 0
87
+
88
+ if sync_token_dim > 0:
89
+ # Conditioning tokens
90
+ sync_embed_dim = sync_token_dim if not project_cond_tokens else embed_dim
91
+ self.to_sync_embed = nn.Sequential(
92
+ nn.Linear(sync_token_dim, sync_embed_dim, bias=False),
93
+ nn.SiLU(),
94
+ nn.Linear(sync_embed_dim, sync_embed_dim, bias=False)
95
+ )
96
+ else:
97
+ sync_embed_dim = 0
98
+
99
+
100
+ if prepend_cond_dim > 0:
101
+ # Prepend conditioning
102
+ self.to_prepend_embed = nn.Sequential(
103
+ nn.Linear(prepend_cond_dim, embed_dim, bias=False),
104
+ nn.SiLU(),
105
+ nn.Linear(embed_dim, embed_dim, bias=False)
106
+ )
107
+
108
+ self.input_concat_dim = input_concat_dim
109
+
110
+ dim_in = io_channels + self.input_concat_dim
111
+
112
+ self.patch_size = patch_size
113
+
114
+ # Transformer
115
+
116
+ self.transformer_type = transformer_type
117
+
118
+ self.empty_clip_feat = nn.Parameter(torch.zeros(1, embed_dim), requires_grad=True)
119
+ self.empty_sync_feat = nn.Parameter(torch.zeros(1, embed_dim), requires_grad=True)
120
+ self.global_cond_type = global_cond_type
121
+ print("######################")
122
+ print(f'global type: {global_cond_type}')
123
+ print("######################")
124
+ if self.transformer_type == "continuous_transformer":
125
+
126
+ global_dim = None
127
+
128
+ if self.global_cond_type == "adaLN":
129
+ # The global conditioning is projected to the embed_dim already at this point
130
+ global_dim = embed_dim
131
+
132
+ self.transformer = ContinuousTransformer(
133
+ dim=embed_dim,
134
+ depth=depth,
135
+ dim_heads=embed_dim // num_heads,
136
+ dim_in=dim_in * patch_size,
137
+ dim_out=io_channels * patch_size,
138
+ cross_attend = cond_token_dim > 0,
139
+ cond_token_dim = cond_embed_dim,
140
+ global_cond_dim=global_dim,
141
+ **kwargs
142
+ )
143
+ else:
144
+ raise ValueError(f"Unknown transformer type: {self.transformer_type}")
145
+
146
+ self.preprocess_conv = nn.Conv1d(dim_in, dim_in, 1, bias=False)
147
+ self.postprocess_conv = nn.Conv1d(io_channels, io_channels, 1, bias=False)
148
+ nn.init.zeros_(self.preprocess_conv.weight)
149
+ nn.init.zeros_(self.postprocess_conv.weight)
150
+
151
+
152
+ def initialize_weights(self):
153
+ print("######################")
154
+ print(f'Fine! You are using zero initialization!')
155
+ print("######################")
156
+ def _basic_init(module):
157
+ if isinstance(module, nn.Linear):
158
+ torch.nn.init.xavier_uniform_(module.weight)
159
+ if module.bias is not None:
160
+ nn.init.constant_(module.bias, 0)
161
+
162
+ # if isinstance(module, nn.Conv1d):
163
+ # if module.bias is not None:
164
+ # nn.init.constant_(module.bias, 0)
165
+
166
+ self.apply(_basic_init)
167
+
168
+ # Initialize timestep embedding MLP:
169
+ nn.init.normal_(self.to_timestep_embed[0].weight, std=0.02)
170
+ nn.init.normal_(self.to_timestep_embed[2].weight, std=0.02)
171
+
172
+ # Zero-out output layers:
173
+ if self.global_cond_type == "adaLN":
174
+ for block in self.transformer.layers:
175
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
176
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
177
+
178
+ nn.init.constant_(self.empty_clip_feat, 0)
179
+ nn.init.constant_(self.empty_sync_feat, 0)
180
+
181
+ def _forward(
182
+ self,
183
+ x,
184
+ t,
185
+ mask=None,
186
+ cross_attn_cond=None,
187
+ cross_attn_cond_mask=None,
188
+ input_concat_cond=None,
189
+ global_embed=None,
190
+ prepend_cond=None,
191
+ prepend_cond_mask=None,
192
+ add_cond=None,
193
+ add_masks=None,
194
+ sync_cond=None,
195
+ return_info=False,
196
+ **kwargs):
197
+
198
+ if cross_attn_cond is not None:
199
+ cross_attn_cond = self.to_cond_embed(cross_attn_cond)
200
+
201
+ if global_embed is not None:
202
+ # Project the global conditioning to the embedding dimension
203
+ global_embed = self.to_global_embed(global_embed)
204
+
205
+ prepend_inputs = None
206
+ prepend_mask = None
207
+ prepend_length = 0
208
+ if prepend_cond is not None:
209
+ # Project the prepend conditioning to the embedding dimension
210
+ prepend_cond = self.to_prepend_embed(prepend_cond)
211
+
212
+ prepend_inputs = prepend_cond
213
+ if prepend_cond_mask is not None:
214
+ prepend_mask = prepend_cond_mask
215
+
216
+ if input_concat_cond is not None:
217
+ # reshape from (b, n, c) to (b, c, n)
218
+ if input_concat_cond.shape[1] != x.shape[1]:
219
+ input_concat_cond = input_concat_cond.transpose(1,2)
220
+ # Interpolate input_concat_cond to the same length as x
221
+ # if input_concat_cond.shape[1] != x.shape[2]:
222
+ # input_concat_cond = input_concat_cond.transpose(1,2)
223
+ input_concat_cond = F.interpolate(input_concat_cond, (x.shape[2], ), mode='nearest')
224
+ # input_concat_cond = input_concat_cond.transpose(1,2)
225
+ # if len(global_embed.shape) == 2:
226
+ # global_embed = global_embed.unsqueeze(1)
227
+ # global_embed = global_embed + input_concat_cond
228
+ x = torch.cat([x, input_concat_cond], dim=1)
229
+
230
+ # Get the batch of timestep embeddings
231
+ timestep_embed = self.to_timestep_embed(self.timestep_features(t[:, None])) # (b, embed_dim)
232
+ # import ipdb
233
+ # ipdb.set_trace()
234
+ # Timestep embedding is considered a global embedding. Add to the global conditioning if it exists
235
+ if self.timestep_cond_type == "global":
236
+ if global_embed is not None:
237
+ if len(global_embed.shape) == 3:
238
+ timestep_embed = timestep_embed.unsqueeze(1)
239
+ global_embed = global_embed + timestep_embed
240
+ else:
241
+ global_embed = timestep_embed
242
+ elif self.timestep_cond_type == "input_concat":
243
+ x = torch.cat([x, timestep_embed.unsqueeze(1).expand(-1, -1, x.shape[2])], dim=1)
244
+
245
+ # Add the global_embed to the prepend inputs if there is no global conditioning support in the transformer
246
+ if self.global_cond_type == "prepend" and global_embed is not None:
247
+ if prepend_inputs is None:
248
+ # Prepend inputs are just the global embed, and the mask is all ones
249
+ if len(global_embed.shape) == 2:
250
+ prepend_inputs = global_embed.unsqueeze(1)
251
+ else:
252
+ prepend_inputs = global_embed
253
+ prepend_mask = torch.ones((x.shape[0], 1), device=x.device, dtype=torch.bool)
254
+ else:
255
+ # Prepend inputs are the prepend conditioning + the global embed
256
+ if len(global_embed.shape) == 2:
257
+ prepend_inputs = torch.cat([prepend_inputs, global_embed.unsqueeze(1)], dim=1)
258
+ else:
259
+ prepend_inputs = torch.cat([prepend_inputs, global_embed], dim=1)
260
+ prepend_mask = torch.cat([prepend_mask, torch.ones((x.shape[0], 1), device=x.device, dtype=torch.bool)], dim=1)
261
+
262
+ prepend_length = prepend_inputs.shape[1]
263
+
264
+ x = self.preprocess_conv(x) + x
265
+ x = rearrange(x, "b c t -> b t c")
266
+
267
+ extra_args = {}
268
+
269
+ if self.global_cond_type == "adaLN":
270
+ extra_args["global_cond"] = global_embed
271
+
272
+ if self.patch_size > 1:
273
+ b, seq_len, c = x.shape
274
+
275
+ # 计算需要填充的数量
276
+ pad_amount = (self.patch_size - seq_len % self.patch_size) % self.patch_size
277
+
278
+ if pad_amount > 0:
279
+ # 在时间维度上进行填充
280
+ x = F.pad(x, (0, 0, 0, pad_amount), mode='constant', value=0)
281
+ x = rearrange(x, "b (t p) c -> b t (c p)", p=self.patch_size)
282
+
283
+ if add_cond is not None:
284
+ # Interpolate add_cond to the same length as x
285
+ # if self.use_mlp:
286
+ add_cond = self.to_add_embed(add_cond)
287
+ if add_cond.shape[1] != x.shape[1]:
288
+ add_cond = add_cond.transpose(1,2)
289
+ add_cond = F.interpolate(add_cond, (x.shape[1], ), mode='linear', align_corners=False)
290
+ add_cond = add_cond.transpose(1,2)
291
+ # add_cond = resample(add_cond, x)
292
+
293
+ if sync_cond is not None:
294
+ sync_cond = self.to_sync_embed(sync_cond)
295
+
296
+ if self.transformer_type == "continuous_transformer":
297
+ output = self.transformer(x, prepend_embeds=prepend_inputs, context=cross_attn_cond, add_cond=add_cond, sync_cond=sync_cond, mask=mask, prepend_mask=prepend_mask, return_info=return_info, **extra_args, **kwargs)
298
+
299
+ if return_info:
300
+ output, info = output
301
+
302
+ output = rearrange(output, "b t c -> b c t")[:,:,prepend_length:]
303
+
304
+ if self.patch_size > 1:
305
+ output = rearrange(output, "b (c p) t -> b c (t p)", p=self.patch_size)
306
+ # 移除之前添加的填充
307
+ if pad_amount > 0:
308
+ output = output[:, :, :seq_len]
309
+
310
+ output = self.postprocess_conv(output) + output
311
+
312
+ if return_info:
313
+ return output, info
314
+
315
+ return output
316
+
317
+ def forward(
318
+ self,
319
+ x,
320
+ t,
321
+ cross_attn_cond=None,
322
+ cross_attn_cond_mask=None,
323
+ negative_cross_attn_cond=None,
324
+ negative_cross_attn_mask=None,
325
+ input_concat_cond=None,
326
+ global_embed=None,
327
+ negative_global_embed=None,
328
+ prepend_cond=None,
329
+ prepend_cond_mask=None,
330
+ add_cond=None,
331
+ sync_cond=None,
332
+ cfg_scale=1.0,
333
+ cfg_dropout_prob=0.0,
334
+ causal=False,
335
+ scale_phi=0.0,
336
+ mask=None,
337
+ return_info=False,
338
+ **kwargs):
339
+
340
+ assert causal == False, "Causal mode is not supported for DiffusionTransformer"
341
+ bsz, a, b = x.shape
342
+ model_dtype = next(self.parameters()).dtype
343
+ x = x.to(model_dtype)
344
+ t = t.to(model_dtype)
345
+
346
+ if cross_attn_cond is not None:
347
+ cross_attn_cond = cross_attn_cond.to(model_dtype)
348
+
349
+ if negative_cross_attn_cond is not None:
350
+ negative_cross_attn_cond = negative_cross_attn_cond.to(model_dtype)
351
+
352
+ if input_concat_cond is not None:
353
+ input_concat_cond = input_concat_cond.to(model_dtype)
354
+
355
+ if global_embed is not None:
356
+ global_embed = global_embed.to(model_dtype)
357
+
358
+ if negative_global_embed is not None:
359
+ negative_global_embed = negative_global_embed.to(model_dtype)
360
+
361
+ if prepend_cond is not None:
362
+ prepend_cond = prepend_cond.to(model_dtype)
363
+
364
+ if add_cond is not None:
365
+ add_cond = add_cond.to(model_dtype)
366
+
367
+ if sync_cond is not None:
368
+ sync_cond = sync_cond.to(model_dtype)
369
+
370
+ if cross_attn_cond_mask is not None:
371
+ cross_attn_cond_mask = cross_attn_cond_mask.bool()
372
+
373
+ cross_attn_cond_mask = None # Temporarily disabling conditioning masks due to kernel issue for flash attention
374
+
375
+ if prepend_cond_mask is not None:
376
+ prepend_cond_mask = prepend_cond_mask.bool()
377
+
378
+
379
+ # CFG dropout
380
+ if cfg_dropout_prob > 0.0 and cfg_scale == 1.0:
381
+ if cross_attn_cond is not None:
382
+ null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device)
383
+ dropout_mask = torch.bernoulli(torch.full((cross_attn_cond.shape[0], 1, 1), cfg_dropout_prob, device=cross_attn_cond.device)).to(torch.bool)
384
+ cross_attn_cond = torch.where(dropout_mask, null_embed, cross_attn_cond)
385
+
386
+ if prepend_cond is not None:
387
+ null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device)
388
+ dropout_mask = torch.bernoulli(torch.full((prepend_cond.shape[0], 1, 1), cfg_dropout_prob, device=prepend_cond.device)).to(torch.bool)
389
+ prepend_cond = torch.where(dropout_mask, null_embed, prepend_cond)
390
+
391
+ if add_cond is not None:
392
+ null_embed = torch.zeros_like(add_cond, device=add_cond.device)
393
+ dropout_mask = torch.bernoulli(torch.full((add_cond.shape[0], 1, 1), cfg_dropout_prob, device=add_cond.device)).to(torch.bool)
394
+ add_cond = torch.where(dropout_mask, null_embed, add_cond)
395
+
396
+ if sync_cond is not None:
397
+ null_embed = torch.zeros_like(sync_cond, device=sync_cond.device)
398
+ dropout_mask = torch.bernoulli(torch.full((sync_cond.shape[0], 1, 1), cfg_dropout_prob, device=sync_cond.device)).to(torch.bool)
399
+ sync_cond = torch.where(dropout_mask, null_embed, sync_cond)
400
+
401
+ if cfg_scale != 1.0 and (cross_attn_cond is not None or prepend_cond is not None or add_cond is not None):
402
+ # Classifier-free guidance
403
+ # Concatenate conditioned and unconditioned inputs on the batch dimension
404
+ batch_inputs = torch.cat([x, x], dim=0)
405
+ batch_timestep = torch.cat([t, t], dim=0)
406
+ if global_embed is not None and global_embed.shape[0] == bsz:
407
+ batch_global_cond = torch.cat([global_embed, global_embed], dim=0)
408
+ elif global_embed is not None:
409
+ batch_global_cond = global_embed
410
+ else:
411
+ batch_global_cond = None
412
+
413
+ if input_concat_cond is not None and input_concat_cond.shape[0] == bsz:
414
+ batch_input_concat_cond = torch.cat([input_concat_cond, input_concat_cond], dim=0)
415
+ elif input_concat_cond is not None:
416
+ batch_input_concat_cond = input_concat_cond
417
+ else:
418
+ batch_input_concat_cond = None
419
+
420
+ batch_cond = None
421
+ batch_cond_masks = None
422
+
423
+ # Handle CFG for cross-attention conditioning
424
+ if cross_attn_cond is not None and cross_attn_cond.shape[0] == bsz:
425
+
426
+ null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device)
427
+
428
+ # For negative cross-attention conditioning, replace the null embed with the negative cross-attention conditioning
429
+ if negative_cross_attn_cond is not None:
430
+
431
+ # If there's a negative cross-attention mask, set the masked tokens to the null embed
432
+ if negative_cross_attn_mask is not None:
433
+ negative_cross_attn_mask = negative_cross_attn_mask.to(torch.bool).unsqueeze(2)
434
+
435
+ negative_cross_attn_cond = torch.where(negative_cross_attn_mask, negative_cross_attn_cond, null_embed)
436
+
437
+ batch_cond = torch.cat([cross_attn_cond, negative_cross_attn_cond], dim=0)
438
+
439
+ else:
440
+ batch_cond = torch.cat([cross_attn_cond, null_embed], dim=0)
441
+
442
+ if cross_attn_cond_mask is not None:
443
+ batch_cond_masks = torch.cat([cross_attn_cond_mask, cross_attn_cond_mask], dim=0)
444
+ elif cross_attn_cond is not None:
445
+ batch_cond = cross_attn_cond
446
+ else:
447
+ batch_cond = None
448
+
449
+ batch_prepend_cond = None
450
+ batch_prepend_cond_mask = None
451
+
452
+ if prepend_cond is not None and prepend_cond.shape[0] == bsz:
453
+
454
+ null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device)
455
+
456
+ batch_prepend_cond = torch.cat([prepend_cond, null_embed], dim=0)
457
+
458
+ if prepend_cond_mask is not None:
459
+ batch_prepend_cond_mask = torch.cat([prepend_cond_mask, prepend_cond_mask], dim=0)
460
+ elif prepend_cond is not None:
461
+ batch_prepend_cond = prepend_cond
462
+ else:
463
+ batch_prepend_cond = None
464
+
465
+ batch_add_cond = None
466
+
467
+ # Handle CFG for cross-attention conditioning
468
+ if add_cond is not None and add_cond.shape[0] == bsz:
469
+
470
+ null_embed = torch.zeros_like(add_cond, device=add_cond.device)
471
+
472
+
473
+ batch_add_cond = torch.cat([add_cond, null_embed], dim=0)
474
+ elif add_cond is not None:
475
+ batch_add_cond = add_cond
476
+ else:
477
+ batch_add_cond = None
478
+
479
+ batch_sync_cond = None
480
+
481
+ # Handle CFG for cross-attention conditioning
482
+ if sync_cond is not None and sync_cond.shape[0] == bsz:
483
+
484
+ null_embed = torch.zeros_like(sync_cond, device=sync_cond.device)
485
+
486
+
487
+ batch_sync_cond = torch.cat([sync_cond, null_embed], dim=0)
488
+ elif sync_cond is not None:
489
+ batch_sync_cond = sync_cond
490
+ else:
491
+ batch_sync_cond = None
492
+
493
+ if mask is not None:
494
+ batch_masks = torch.cat([mask, mask], dim=0)
495
+ else:
496
+ batch_masks = None
497
+
498
+ batch_output = self._forward(
499
+ batch_inputs,
500
+ batch_timestep,
501
+ cross_attn_cond=batch_cond,
502
+ cross_attn_cond_mask=batch_cond_masks,
503
+ mask = batch_masks,
504
+ input_concat_cond=batch_input_concat_cond,
505
+ global_embed = batch_global_cond,
506
+ prepend_cond = batch_prepend_cond,
507
+ prepend_cond_mask = batch_prepend_cond_mask,
508
+ add_cond = batch_add_cond,
509
+ sync_cond = batch_sync_cond,
510
+ return_info = return_info,
511
+ **kwargs)
512
+
513
+ if return_info:
514
+ batch_output, info = batch_output
515
+
516
+ cond_output, uncond_output = torch.chunk(batch_output, 2, dim=0)
517
+ cfg_output = uncond_output + (cond_output - uncond_output) * cfg_scale
518
+
519
+ # CFG Rescale
520
+ if scale_phi != 0.0:
521
+ cond_out_std = cond_output.std(dim=1, keepdim=True)
522
+ out_cfg_std = cfg_output.std(dim=1, keepdim=True)
523
+ output = scale_phi * (cfg_output * (cond_out_std/out_cfg_std)) + (1-scale_phi) * cfg_output
524
+ else:
525
+ output = cfg_output
526
+
527
+ if return_info:
528
+ return output, info
529
+
530
+ return output
531
+
532
+ else:
533
+ return self._forward(
534
+ x,
535
+ t,
536
+ cross_attn_cond=cross_attn_cond,
537
+ cross_attn_cond_mask=cross_attn_cond_mask,
538
+ input_concat_cond=input_concat_cond,
539
+ global_embed=global_embed,
540
+ prepend_cond=prepend_cond,
541
+ prepend_cond_mask=prepend_cond_mask,
542
+ add_cond=add_cond,
543
+ sync_cond=sync_cond,
544
+ mask=mask,
545
+ return_info=return_info,
546
+ **kwargs
547
+ )
ThinkSound/models/factory.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ def create_model_from_config(model_config):
4
+ model_type = model_config.get('model_type', None)
5
+
6
+ assert model_type is not None, 'model_type must be specified in model config'
7
+
8
+ if model_type == 'autoencoder':
9
+ from .autoencoders import create_autoencoder_from_config
10
+ return create_autoencoder_from_config(model_config)
11
+ elif model_type == 'diffusion_uncond':
12
+ from .diffusion import create_diffusion_uncond_from_config
13
+ return create_diffusion_uncond_from_config(model_config)
14
+ # elif model_type == 'diffusion_infill':
15
+ # from .diffusion import create_diffusion_infill_from_config
16
+ # return create_diffusion_infill_from_config(model_config)
17
+ elif model_type == 'diffusion_cond' or model_type == 'diffusion_cond_inpaint' or model_type == "diffusion_prior" or model_type == "diffusion_infill" or model_type == "mm_diffusion_cond":
18
+ from .diffusion import create_diffusion_cond_from_config
19
+ return create_diffusion_cond_from_config(model_config)
20
+ elif model_type == 'diffusion_autoencoder':
21
+ from .autoencoders import create_diffAE_from_config
22
+ return create_diffAE_from_config(model_config)
23
+ elif model_type == 'lm':
24
+ from .lm import create_audio_lm_from_config
25
+ return create_audio_lm_from_config(model_config)
26
+ else:
27
+ raise NotImplementedError(f'Unknown model type: {model_type}')
28
+
29
+ def create_model_from_config_path(model_config_path):
30
+ with open(model_config_path) as f:
31
+ model_config = json.load(f)
32
+
33
+ return create_model_from_config(model_config)
34
+
35
+ def create_pretransform_from_config(pretransform_config, sample_rate):
36
+ pretransform_type = pretransform_config.get('type', None)
37
+
38
+ assert pretransform_type is not None, 'type must be specified in pretransform config'
39
+
40
+ if pretransform_type == 'autoencoder':
41
+ from .autoencoders import create_autoencoder_from_config
42
+ from .pretransforms import AutoencoderPretransform
43
+
44
+ # Create fake top-level config to pass sample rate to autoencoder constructor
45
+ # This is a bit of a hack but it keeps us from re-defining the sample rate in the config
46
+ autoencoder_config = {"sample_rate": sample_rate, "model": pretransform_config["config"]}
47
+ autoencoder = create_autoencoder_from_config(autoencoder_config)
48
+
49
+ scale = pretransform_config.get("scale", 1.0)
50
+ model_half = pretransform_config.get("model_half", False)
51
+ iterate_batch = pretransform_config.get("iterate_batch", False)
52
+ chunked = pretransform_config.get("chunked", False)
53
+
54
+ pretransform = AutoencoderPretransform(autoencoder, scale=scale, model_half=model_half, iterate_batch=iterate_batch, chunked=chunked)
55
+ elif pretransform_type == 'wavelet':
56
+ from .pretransforms import WaveletPretransform
57
+
58
+ wavelet_config = pretransform_config["config"]
59
+ channels = wavelet_config["channels"]
60
+ levels = wavelet_config["levels"]
61
+ wavelet = wavelet_config["wavelet"]
62
+
63
+ pretransform = WaveletPretransform(channels, levels, wavelet)
64
+ elif pretransform_type == 'pqmf':
65
+ from .pretransforms import PQMFPretransform
66
+ pqmf_config = pretransform_config["config"]
67
+ pretransform = PQMFPretransform(**pqmf_config)
68
+ elif pretransform_type == 'dac_pretrained':
69
+ from .pretransforms import PretrainedDACPretransform
70
+ pretrained_dac_config = pretransform_config["config"]
71
+ pretransform = PretrainedDACPretransform(**pretrained_dac_config)
72
+ elif pretransform_type == "audiocraft_pretrained":
73
+ from .pretransforms import AudiocraftCompressionPretransform
74
+
75
+ audiocraft_config = pretransform_config["config"]
76
+ pretransform = AudiocraftCompressionPretransform(**audiocraft_config)
77
+ else:
78
+ raise NotImplementedError(f'Unknown pretransform type: {pretransform_type}')
79
+
80
+ enable_grad = pretransform_config.get('enable_grad', False)
81
+ pretransform.enable_grad = enable_grad
82
+
83
+ pretransform.eval().requires_grad_(pretransform.enable_grad)
84
+
85
+ return pretransform
86
+
87
+ def create_bottleneck_from_config(bottleneck_config):
88
+ bottleneck_type = bottleneck_config.get('type', None)
89
+
90
+ assert bottleneck_type is not None, 'type must be specified in bottleneck config'
91
+
92
+ if bottleneck_type == 'tanh':
93
+ from .bottleneck import TanhBottleneck
94
+ bottleneck = TanhBottleneck()
95
+ elif bottleneck_type == 'vae':
96
+ from .bottleneck import VAEBottleneck
97
+ bottleneck = VAEBottleneck()
98
+ elif bottleneck_type == 'rvq':
99
+ from .bottleneck import RVQBottleneck
100
+
101
+ quantizer_params = {
102
+ "dim": 128,
103
+ "codebook_size": 1024,
104
+ "num_quantizers": 8,
105
+ "decay": 0.99,
106
+ "kmeans_init": True,
107
+ "kmeans_iters": 50,
108
+ "threshold_ema_dead_code": 2,
109
+ }
110
+
111
+ quantizer_params.update(bottleneck_config["config"])
112
+
113
+ bottleneck = RVQBottleneck(**quantizer_params)
114
+ elif bottleneck_type == "dac_rvq":
115
+ from .bottleneck import DACRVQBottleneck
116
+
117
+ bottleneck = DACRVQBottleneck(**bottleneck_config["config"])
118
+
119
+ elif bottleneck_type == 'rvq_vae':
120
+ from .bottleneck import RVQVAEBottleneck
121
+
122
+ quantizer_params = {
123
+ "dim": 128,
124
+ "codebook_size": 1024,
125
+ "num_quantizers": 8,
126
+ "decay": 0.99,
127
+ "kmeans_init": True,
128
+ "kmeans_iters": 50,
129
+ "threshold_ema_dead_code": 2,
130
+ }
131
+
132
+ quantizer_params.update(bottleneck_config["config"])
133
+
134
+ bottleneck = RVQVAEBottleneck(**quantizer_params)
135
+
136
+ elif bottleneck_type == 'dac_rvq_vae':
137
+ from .bottleneck import DACRVQVAEBottleneck
138
+ bottleneck = DACRVQVAEBottleneck(**bottleneck_config["config"])
139
+ elif bottleneck_type == 'l2_norm':
140
+ from .bottleneck import L2Bottleneck
141
+ bottleneck = L2Bottleneck()
142
+ elif bottleneck_type == "wasserstein":
143
+ from .bottleneck import WassersteinBottleneck
144
+ bottleneck = WassersteinBottleneck(**bottleneck_config.get("config", {}))
145
+ elif bottleneck_type == "fsq":
146
+ from .bottleneck import FSQBottleneck
147
+ bottleneck = FSQBottleneck(**bottleneck_config["config"])
148
+ else:
149
+ raise NotImplementedError(f'Unknown bottleneck type: {bottleneck_type}')
150
+
151
+ requires_grad = bottleneck_config.get('requires_grad', True)
152
+ if not requires_grad:
153
+ for param in bottleneck.parameters():
154
+ param.requires_grad = False
155
+
156
+ return bottleneck
ThinkSound/models/lm.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import torch
3
+ from tqdm.auto import trange
4
+ import typing as tp
5
+ from einops import rearrange
6
+ from torch import nn
7
+
8
+ from .conditioners import MultiConditioner, create_multi_conditioner_from_conditioning_config
9
+ from .factory import create_pretransform_from_config
10
+ from .lm_backbone import AudioLMBackbone, XTransformersAudioLMBackbone, ContinuousTransformerAudioLMBackbone
11
+ from .pretransforms import Pretransform, AutoencoderPretransform, PretrainedDACPretransform, AudiocraftCompressionPretransform
12
+ from .utils import multinomial, sample_top_k, sample_top_p
13
+
14
+ from .codebook_patterns import (
15
+ CodebooksPatternProvider,
16
+ DelayedPatternProvider,
17
+ MusicLMPattern,
18
+ ParallelPatternProvider,
19
+ UnrolledPatternProvider
20
+ )
21
+
22
+ # Copied and modified from https://github.com/facebookresearch/audiocraft/blob/main/audiocraft/models/lm.py under MIT license
23
+ # License can be found in LICENSES/LICENSE_META.txt
24
+
25
+ @dataclass
26
+ class LMOutput:
27
+ # The logits are already re-aligned with the input codes
28
+ # hence no extra shift is required, e.g. when computing CE
29
+ logits: torch.Tensor # [B, K, T, card]
30
+ mask: torch.Tensor # [B, K, T]
31
+
32
+ # Wrapper for a multi-codebook language model
33
+ # Handles patterns and quantizer heads
34
+ class AudioLanguageModel(nn.Module):
35
+ def __init__(
36
+ self,
37
+ pattern_provider: CodebooksPatternProvider,
38
+ backbone: AudioLMBackbone,
39
+ num_quantizers: int,
40
+ codebook_size: int
41
+ ):
42
+ super().__init__()
43
+
44
+ self.pattern_provider = pattern_provider
45
+ self.backbone = backbone
46
+ self.num_quantizers = num_quantizers
47
+ self.codebook_size = codebook_size
48
+
49
+ self.masked_token_id = codebook_size
50
+
51
+ # Per-quantizer embedders
52
+ # Add one for the mask embed
53
+ self.embeds = nn.ModuleList([nn.Embedding(codebook_size + 1, backbone.embed_dim) for _ in range(num_quantizers)])
54
+
55
+ # Per-quantizer output heads
56
+ self.quantizer_heads = nn.ModuleList([
57
+ nn.Linear(backbone.embed_dim, codebook_size) for _ in range(num_quantizers)
58
+ ])
59
+
60
+ def forward(self,
61
+ sequence: torch.Tensor, #[batch, seq_len,
62
+ prepend_cond=None, #[batch, seq, channels]
63
+ prepend_cond_mask=None,
64
+ cross_attn_cond=None, #[batch, seq, channels],
65
+ **kwargs
66
+ ):
67
+
68
+ batch, num_quantizers, seq_len = sequence.shape
69
+
70
+ assert num_quantizers == self.num_quantizers, "Number of quantizers in sequence must match number of quantizers in model"
71
+
72
+ backbone_input = sum([self.embeds[i](sequence[:, i]) for i in range(num_quantizers)]) # [batch, seq_len, embed_dim]
73
+
74
+ dtype = next(self.parameters()).dtype
75
+
76
+ if cross_attn_cond is not None:
77
+ cross_attn_cond = cross_attn_cond.to(dtype)
78
+
79
+ if prepend_cond is not None:
80
+ prepend_cond = prepend_cond.to(dtype)
81
+
82
+ if prepend_cond_mask is not None:
83
+ prepend_cond_mask = prepend_cond_mask.to(dtype)
84
+
85
+ backbone_input = backbone_input.to(dtype)
86
+
87
+ output = self.backbone(
88
+ backbone_input,
89
+ cross_attn_cond=cross_attn_cond,
90
+ prepend_cond=prepend_cond,
91
+ prepend_cond_mask=prepend_cond_mask,
92
+ **kwargs
93
+ ) # [batch, seq_len, embed_dim]
94
+
95
+ # Run output through quantizer heads
96
+ logits = torch.stack([self.quantizer_heads[i](output) for i in range(num_quantizers)], dim=1) # [batch, num_quantizers, seq_len, codebook_size]
97
+
98
+ return logits
99
+
100
+ def compute_logits(
101
+ self,
102
+ codes, #[batch, num_quantizers, seq_len]
103
+ **kwargs):
104
+ """
105
+ Compute logits for a batch of codes, optionally conditioning on cross-attention and prepend conditioning
106
+ Handles translation between input sequence and pattern-shifted sequence
107
+ Only used during training
108
+ """
109
+
110
+ batch, _, seq_len = codes.shape
111
+
112
+ pattern = self.pattern_provider.get_pattern(seq_len)
113
+
114
+ # Apply the token pattern to the codes, shifting the codes as needed and masking out invalid steps
115
+ shifted_codes, _, _ = pattern.build_pattern_sequence(
116
+ codes,
117
+ self.masked_token_id,
118
+ keep_only_valid_steps=True
119
+ )
120
+
121
+ # Run the model to get logits for each quantizer [batch, num_quantizers, seq_len, codebook_size]
122
+ logits = self(shifted_codes, **kwargs)
123
+
124
+ # Rearrange logits to prepare to revert pattern
125
+ logits = rearrange(logits, "b n s c -> b c n s")
126
+
127
+ # Revert sequence logits back to original sequence length, removing masked steps
128
+ logits, _, logits_mask = pattern.revert_pattern_logits(
129
+ logits, float('nan'), keep_only_valid_steps=True
130
+ )
131
+
132
+ logits = rearrange(logits, "b c n t -> b n t c")
133
+
134
+ logits_mask = logits_mask[None, :, :].expand(batch, -1, -1) # [batch, num_quantizers, seq_len]
135
+
136
+ return LMOutput(logits=logits, mask=logits_mask)
137
+
138
+ # Conditioning and generation wrapper for a multi-codebook language model
139
+ # Handles conditioning, CFG, generation, and encoding/decoding
140
+ class AudioLanguageModelWrapper(nn.Module):
141
+ def __init__(
142
+ self,
143
+ pretransform: Pretransform,
144
+ lm: AudioLanguageModel,
145
+ sample_rate: int,
146
+ min_input_length: int,
147
+ conditioner: MultiConditioner = None,
148
+ cross_attn_cond_ids: tp.List[str] = [],
149
+ prepend_cond_ids: tp.List[str] = [],
150
+ global_cond_ids: tp.List[str] = []
151
+ ):
152
+ super().__init__()
153
+
154
+ assert pretransform.is_discrete, "Pretransform must be discrete"
155
+ self.pretransform = pretransform
156
+
157
+ self.pretransform.requires_grad_(False)
158
+ self.pretransform.eval()
159
+
160
+ if isinstance(self.pretransform, AutoencoderPretransform):
161
+ self.num_quantizers = self.pretransform.model.bottleneck.num_quantizers
162
+ self.codebook_size = self.pretransform.model.bottleneck.codebook_size
163
+ elif isinstance(self.pretransform, PretrainedDACPretransform):
164
+ self.num_quantizers = self.pretransform.model.num_quantizers
165
+ self.codebook_size = self.pretransform.model.codebook_size
166
+ elif isinstance(self.pretransform, AudiocraftCompressionPretransform):
167
+ self.num_quantizers = self.pretransform.num_quantizers
168
+ self.codebook_size = self.pretransform.codebook_size
169
+ else:
170
+ raise NotImplementedError(f"Unrecognized pretransform type {type(self.pretransform)}")
171
+
172
+ self.conditioner = conditioner
173
+
174
+ self.lm = lm
175
+
176
+ self.sample_rate = sample_rate
177
+ self.min_input_length = min_input_length
178
+
179
+ self.cross_attn_cond_ids = cross_attn_cond_ids
180
+ self.prepend_cond_ids = prepend_cond_ids
181
+ self.global_cond_ids = global_cond_ids
182
+
183
+ def get_conditioning_inputs(self, cond: tp.Dict[str, tp.Any], negative=False):
184
+ cross_attention_input = None
185
+ prepend_cond = None
186
+ prepend_cond_mask = None
187
+ global_cond = None
188
+
189
+ if len(self.cross_attn_cond_ids) > 0:
190
+ # Concatenate all cross-attention inputs over the sequence dimension
191
+ # Assumes that the cross-attention inputs are of shape (batch, seq, channels)
192
+ cross_attention_input = torch.cat([cond[key][0] for key in self.cross_attn_cond_ids], dim=1)
193
+
194
+ if len(self.prepend_cond_ids) > 0:
195
+ # Concatenate all prepend conditioning inputs over the sequence dimension
196
+ # Assumes that the prepend conditioning inputs are of shape (batch, seq, channels)
197
+ prepend_cond = torch.cat([cond[key][0] for key in self.prepend_cond_ids], dim=1)
198
+ prepend_cond_mask = torch.cat([cond[key][1] for key in self.prepend_cond_ids], dim=1)
199
+
200
+ if len(self.global_cond_ids) > 0:
201
+ # Concatenate all global conditioning inputs over the channel dimension
202
+ # Assumes that the global conditioning inputs are of shape (batch, channels)
203
+ global_cond = torch.cat([cond[key][0] for key in self.global_cond_ids], dim=-1)
204
+ if len(global_cond.shape) == 3:
205
+ global_cond = global_cond.squeeze(1)
206
+
207
+ if negative:
208
+ return {
209
+ "negative_cross_attn_cond": cross_attention_input,
210
+ "negative_prepend_cond": prepend_cond,
211
+ "negative_prepend_cond_mask": prepend_cond_mask,
212
+ "negative_global_cond": global_cond
213
+ }
214
+ else:
215
+ return {
216
+ "cross_attn_cond": cross_attention_input,
217
+ "prepend_cond": prepend_cond,
218
+ "prepend_cond_mask": prepend_cond_mask,
219
+ "global_cond": global_cond
220
+ }
221
+
222
+ def compute_logits(
223
+ self,
224
+ codes,
225
+ condition_tensors=None,
226
+ cfg_dropout_prob=0.0,
227
+ **kwargs
228
+ ):
229
+ """
230
+ Compute logits for a batch of codes, and translates from conditioning inputs to model inputs
231
+ Handles CFG dropout
232
+ """
233
+
234
+ if condition_tensors is None:
235
+ condition_tensors = {}
236
+
237
+ conditioning_inputs = self.get_conditioning_inputs(condition_tensors)
238
+
239
+ cross_attn_cond = conditioning_inputs["cross_attn_cond"]
240
+ prepend_cond = conditioning_inputs["prepend_cond"]
241
+ prepend_cond_mask = conditioning_inputs["prepend_cond_mask"]
242
+ global_cond = conditioning_inputs["global_cond"]
243
+
244
+ if cfg_dropout_prob > 0.0:
245
+ if cross_attn_cond is not None:
246
+ null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device)
247
+ dropout_mask = torch.bernoulli(torch.full((cross_attn_cond.shape[0], 1, 1), cfg_dropout_prob, device=cross_attn_cond.device)).to(torch.bool)
248
+ cross_attn_cond = torch.where(dropout_mask, null_embed, cross_attn_cond)
249
+
250
+ if prepend_cond is not None:
251
+ null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device)
252
+ dropout_mask = torch.bernoulli(torch.full((prepend_cond.shape[0], 1, 1), cfg_dropout_prob, device=prepend_cond.device)).to(torch.bool)
253
+ prepend_cond = torch.where(dropout_mask, null_embed, prepend_cond)
254
+
255
+ if global_cond is not None:
256
+ null_embed = torch.zeros_like(global_cond, device=global_cond.device)
257
+ dropout_mask = torch.bernoulli(torch.full((global_cond.shape[0], 1), cfg_dropout_prob, device=global_cond.device)).to(torch.bool)
258
+ global_cond = torch.where(dropout_mask, null_embed, global_cond)
259
+
260
+ return self.lm.compute_logits(codes, cross_attn_cond=cross_attn_cond, prepend_cond=prepend_cond, prepend_cond_mask=prepend_cond_mask, global_cond=global_cond, **kwargs)
261
+
262
+ def _sample_next_token(
263
+ self,
264
+ sequence, #[batch, num_quantizers, seq_len]
265
+ conditioning_tensors=None,
266
+ cross_attn_use_cfg=True,
267
+ prepend_use_cfg=True,
268
+ global_use_cfg=True,
269
+ cfg_scale=1.0,
270
+ top_k=250,
271
+ top_p=0.0,
272
+ temp=1.0,
273
+ **kwargs
274
+ ):
275
+ """
276
+ Sample the next token for a batch of codes, and translates from conditioning inputs to model inputs
277
+ Handles CFG inference
278
+ """
279
+
280
+ if conditioning_tensors is None:
281
+ conditioning_tensors = {}
282
+
283
+ conditioning_inputs = self.get_conditioning_inputs(conditioning_tensors)
284
+
285
+ cross_attn_cond = conditioning_inputs["cross_attn_cond"]
286
+ prepend_cond = conditioning_inputs["prepend_cond"]
287
+ prepend_cond_mask = conditioning_inputs["prepend_cond_mask"]
288
+ global_cond = conditioning_inputs["global_cond"]
289
+
290
+ if cfg_scale != 1.0:
291
+
292
+ # Batch size is doubled to account for negative samples
293
+ sequence = torch.cat([sequence, sequence], dim=0)
294
+
295
+ if cross_attn_cond is not None and cross_attn_use_cfg:
296
+ null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device)
297
+
298
+ cross_attn_cond = torch.cat([cross_attn_cond, null_embed], dim=0)
299
+
300
+ if prepend_cond is not None and prepend_use_cfg:
301
+ null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device)
302
+
303
+ prepend_cond = torch.cat([prepend_cond, null_embed], dim=0)
304
+
305
+ if prepend_cond_mask is not None:
306
+ prepend_cond_mask = torch.cat([prepend_cond_mask, prepend_cond_mask], dim=0)
307
+
308
+ if global_cond is not None and global_use_cfg:
309
+ null_embed = torch.zeros_like(global_cond, device=global_cond.device)
310
+
311
+ global_cond = torch.cat([global_cond, null_embed], dim=0)
312
+
313
+ logits = self.lm(sequence, cross_attn_cond=cross_attn_cond, prepend_cond=prepend_cond, prepend_cond_mask=prepend_cond_mask, global_cond=global_cond, **kwargs)
314
+
315
+ if cfg_scale != 1.0:
316
+ cond_logits, uncond_logits = logits.chunk(2, dim=0)
317
+
318
+ logits = uncond_logits + (cond_logits - uncond_logits) * cfg_scale
319
+
320
+ logits = rearrange(logits, "b n s c -> b n c s") # [batch, num_quantizers, codebook_size, seq_len]
321
+
322
+ # Grab the logits for the last step
323
+ logits = logits[:, :, :, -1] # [batch, num_quantizers, codebook_size]
324
+
325
+ # Apply top-k or top-p sampling
326
+
327
+ if temp > 0:
328
+ probs = torch.softmax(logits / temp, dim=-1)
329
+
330
+ if top_p > 0.0:
331
+ next_token = sample_top_p(probs, p=top_p)
332
+ elif top_k > 0:
333
+ next_token = sample_top_k(probs, k=top_k)
334
+ else:
335
+ next_token = multinomial(probs, num_samples=1)
336
+
337
+ else:
338
+ next_token = torch.argmax(logits, dim=-1, keepdim=True) # [batch, num_quantizers, 1]
339
+
340
+ return next_token
341
+
342
+ @torch.no_grad()
343
+ def generate(
344
+ self,
345
+ max_gen_len: int = 256,
346
+ batch_size: tp.Optional[int] = None,
347
+ init_data: tp.Optional[torch.Tensor] = None,
348
+ conditioning: tp.Optional[tp.Dict[str, tp.Any]] = None,
349
+ conditioning_tensors: tp.Optional[tp.Dict[str, tp.Any]] = None,
350
+ callback: tp.Optional[tp.Callable[[int, int], None]] = None,
351
+ use_cache: bool = True,
352
+ cfg_scale: float = 1.0,
353
+ **kwargs
354
+ ):
355
+ device = next(self.parameters()).device
356
+
357
+ if conditioning_tensors is None and conditioning is not None:
358
+ # Convert conditioning inputs to conditioning tensors
359
+ conditioning_tensors = self.conditioner(conditioning, device)
360
+
361
+ # Check that batch size is consistent across inputs
362
+ possible_batch_sizes = []
363
+
364
+ if batch_size is not None:
365
+ possible_batch_sizes.append(batch_size)
366
+ elif init_data is not None:
367
+ possible_batch_sizes.append(init_data.shape[0])
368
+ elif conditioning_tensors is not None:
369
+ # Assume that the first conditioning tensor has the batch dimension
370
+ possible_batch_sizes.append(conditioning_tensors[list(conditioning_tensors.keys())[0]][0].shape[0])
371
+ else:
372
+ possible_batch_sizes.append(1)
373
+
374
+ assert [x == possible_batch_sizes[0] for x in possible_batch_sizes], "Batch size must be consistent across inputs"
375
+
376
+ batch_size = possible_batch_sizes[0]
377
+
378
+ if init_data is None:
379
+ # Initialize with zeros
380
+ assert batch_size > 0
381
+ init_data = torch.zeros((batch_size, self.num_quantizers, 0), device=device, dtype=torch.long)
382
+
383
+ batch_size, num_quantizers, seq_len = init_data.shape
384
+
385
+ start_offset = seq_len
386
+ assert start_offset < max_gen_len, "init data longer than max gen length"
387
+
388
+ pattern = self.lm.pattern_provider.get_pattern(max_gen_len)
389
+
390
+ unknown_token = -1
391
+
392
+ # Initialize the generated codes with the init data, padded with unknown tokens
393
+ gen_codes = torch.full((batch_size, num_quantizers, max_gen_len), unknown_token, device=device, dtype=torch.long)
394
+ gen_codes[:, :, :start_offset] = init_data # [batch, num_quantizers, max_gen_len]
395
+
396
+ gen_sequence, _, mask = pattern.build_pattern_sequence(gen_codes, self.lm.masked_token_id) # [batch, num_quantizers, gen_sequence_len]
397
+
398
+ start_offset_sequence = pattern.get_first_step_with_timesteps(start_offset)
399
+ assert start_offset_sequence is not None
400
+
401
+ # Generation
402
+ prev_offset = 0
403
+ gen_sequence_len = gen_sequence.shape[-1]
404
+
405
+ # Reset generation cache
406
+ if use_cache and self.lm.backbone.use_generation_cache:
407
+ self.lm.backbone.reset_generation_cache(max_gen_len, batch_size if cfg_scale == 1.0 else batch_size * 2)
408
+
409
+ for offset in trange(start_offset_sequence, gen_sequence_len):
410
+
411
+ # Get the full sequence up to the current offset
412
+ curr_sequence = gen_sequence[..., prev_offset:offset]
413
+
414
+ next_token = self._sample_next_token(
415
+ curr_sequence,
416
+ conditioning_tensors=conditioning_tensors,
417
+ use_cache=use_cache,
418
+ cfg_scale=cfg_scale,
419
+ **kwargs
420
+ )
421
+
422
+ valid_mask = mask[..., offset:offset+1].expand(batch_size, -1, -1)
423
+ next_token[~valid_mask] = self.lm.masked_token_id
424
+
425
+ # Update the generated sequence with the next token
426
+ gen_sequence[..., offset:offset+1] = torch.where(
427
+ gen_sequence[..., offset:offset+1] == unknown_token,
428
+ next_token,
429
+ gen_sequence[..., offset:offset+1]
430
+ )
431
+
432
+ if use_cache and self.lm.backbone.use_generation_cache:
433
+ # Only update the offset if caching is being used
434
+ prev_offset = offset
435
+
436
+ self.lm.backbone.update_generation_cache(offset)
437
+
438
+ if callback is not None:
439
+ # Callback to report progress
440
+ # Pass in the offset relative to the start of the sequence, and the length of the current sequence
441
+ callback(1 + offset - start_offset_sequence, gen_sequence_len - start_offset_sequence)
442
+
443
+ assert not (gen_sequence == unknown_token).any(), "Unknown tokens in generated sequence"
444
+
445
+ out_codes, _, out_mask = pattern.revert_pattern_sequence(gen_sequence, special_token=unknown_token)
446
+
447
+ # sanity checks over the returned codes and corresponding masks
448
+ assert (out_codes[..., :max_gen_len] != unknown_token).all()
449
+ assert (out_mask[..., :max_gen_len] == 1).all()
450
+
451
+ #out_codes = out_codes[..., 0:max_gen_len]
452
+
453
+ return out_codes
454
+
455
+
456
+ def generate_audio(
457
+ self,
458
+ **kwargs
459
+ ):
460
+ """
461
+ Generate audio from a batch of codes
462
+ """
463
+
464
+ codes = self.generate(**kwargs)
465
+
466
+ audio = self.pretransform.decode_tokens(codes)
467
+
468
+ return audio
469
+
470
+
471
+ def create_audio_lm_from_config(config):
472
+ model_config = config.get('model', None)
473
+ assert model_config is not None, 'model config must be specified in config'
474
+
475
+ sample_rate = config.get('sample_rate', None)
476
+ assert sample_rate is not None, "Must specify sample_rate in config"
477
+
478
+ lm_config = model_config.get('lm', None)
479
+ assert lm_config is not None, 'lm config must be specified in model config'
480
+
481
+ codebook_pattern = lm_config.get("codebook_pattern", "delay")
482
+
483
+ pattern_providers = {
484
+ 'parallel': ParallelPatternProvider,
485
+ 'delay': DelayedPatternProvider,
486
+ 'unroll': UnrolledPatternProvider,
487
+ 'musiclm': MusicLMPattern,
488
+ }
489
+
490
+ pretransform_config = model_config.get("pretransform", None)
491
+
492
+ pretransform = create_pretransform_from_config(pretransform_config, sample_rate)
493
+
494
+ assert pretransform.is_discrete, "Pretransform must be discrete"
495
+
496
+ min_input_length = pretransform.downsampling_ratio
497
+
498
+ pattern_provider = pattern_providers[codebook_pattern](n_q=pretransform.num_quantizers)
499
+
500
+ conditioning_config = model_config.get('conditioning', None)
501
+
502
+ conditioner = None
503
+ if conditioning_config is not None:
504
+ conditioner = create_multi_conditioner_from_conditioning_config(conditioning_config)
505
+
506
+ cross_attn_cond_ids = lm_config.get('cross_attention_cond_ids', [])
507
+ prepend_cond_ids = lm_config.get('prepend_cond_ids', [])
508
+ global_cond_ids = lm_config.get('global_cond_ids', [])
509
+
510
+ lm_type = lm_config.get("type", None)
511
+ lm_model_config = lm_config.get("config", None)
512
+
513
+ assert lm_type is not None, "Must specify lm type in lm config"
514
+ assert lm_model_config is not None, "Must specify lm model config in lm config"
515
+
516
+ if lm_type == "x-transformers":
517
+ backbone = XTransformersAudioLMBackbone(**lm_model_config)
518
+ elif lm_type == "continuous_transformer":
519
+ backbone = ContinuousTransformerAudioLMBackbone(**lm_model_config)
520
+ else:
521
+ raise NotImplementedError(f"Unrecognized lm type {lm_type}")
522
+
523
+ lm = AudioLanguageModel(
524
+ pattern_provider=pattern_provider,
525
+ backbone=backbone,
526
+ num_quantizers=pretransform.num_quantizers,
527
+ codebook_size=pretransform.codebook_size
528
+ )
529
+
530
+ model = AudioLanguageModelWrapper(
531
+ pretransform=pretransform,
532
+ lm=lm,
533
+ conditioner=conditioner,
534
+ sample_rate=sample_rate,
535
+ min_input_length=min_input_length,
536
+ cross_attn_cond_ids=cross_attn_cond_ids,
537
+ prepend_cond_ids=prepend_cond_ids,
538
+ global_cond_ids=global_cond_ids
539
+ )
540
+
541
+ return model
ThinkSound/models/lm_backbone.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import nn
2
+ from x_transformers import ContinuousTransformerWrapper, Decoder
3
+
4
+ from .transformer import ContinuousTransformer
5
+
6
+ # Interface for backbone of a language model
7
+ # Handles conditioning and cross-attention
8
+ # Does not have to deal with patterns or quantizer heads
9
+ class AudioLMBackbone(nn.Module):
10
+ def __init__(self, embed_dim: int, use_generation_cache=False, **kwargs):
11
+ super().__init__()
12
+
13
+ self.embed_dim = embed_dim
14
+ self.use_generation_cache = use_generation_cache
15
+
16
+ def forward(
17
+ self,
18
+ x,
19
+ cross_attn_cond=None,
20
+ prepend_cond=None,
21
+ prepend_cond_mask=None,
22
+ global_cond=None,
23
+ use_cache=False,
24
+ **kwargs
25
+ ):
26
+ raise NotImplementedError
27
+
28
+ def reset_generation_cache(
29
+ self,
30
+ max_seq_len,
31
+ batch_size,
32
+ dtype=None
33
+ ):
34
+ pass
35
+
36
+ def update_generation_cache(
37
+ self,
38
+ seqlen_offset
39
+ ):
40
+ pass
41
+
42
+ class XTransformersAudioLMBackbone(AudioLMBackbone):
43
+ def __init__(self,
44
+ embed_dim: int,
45
+ cross_attn_cond_dim: int = 0,
46
+ prepend_cond_dim: int = 0,
47
+ **kwargs):
48
+ super().__init__(embed_dim=embed_dim)
49
+
50
+ # Embeddings are done in the AudioLanguageModel, so we use the continuous-input transformer
51
+ self.model = ContinuousTransformerWrapper(
52
+ dim_in=embed_dim,
53
+ dim_out=embed_dim,
54
+ max_seq_len=0, #Not relevant without absolute positional embeds,
55
+ attn_layers=Decoder(
56
+ dim=embed_dim,
57
+ attn_flash = True,
58
+ cross_attend = cross_attn_cond_dim > 0,
59
+ zero_init_branch_output=True,
60
+ use_abs_pos_emb = False,
61
+ rotary_pos_emb=True,
62
+ ff_swish = True,
63
+ ff_glu = True,
64
+ **kwargs
65
+ )
66
+ )
67
+
68
+ if prepend_cond_dim > 0:
69
+ # Prepend conditioning
70
+ self.to_prepend_embed = nn.Sequential(
71
+ nn.Linear(prepend_cond_dim, embed_dim, bias=False),
72
+ nn.SiLU(),
73
+ nn.Linear(embed_dim, embed_dim, bias=False)
74
+ )
75
+
76
+ if cross_attn_cond_dim > 0:
77
+ # Cross-attention conditioning
78
+ self.to_cross_attn_embed = nn.Sequential(
79
+ nn.Linear(cross_attn_cond_dim, embed_dim, bias=False),
80
+ nn.SiLU(),
81
+ nn.Linear(embed_dim, embed_dim, bias=False)
82
+ )
83
+
84
+ def forward(self, x, mask=None, prepend_cond=None, prepend_cond_mask=None, cross_attn_cond=None, global_cond=None, use_cache=False):
85
+
86
+ prepend_length = 0
87
+ if prepend_cond is not None:
88
+ # Project the prepend conditioning to the embedding dimension
89
+ prepend_cond = self.to_prepend_embed(prepend_cond)
90
+ prepend_length = prepend_cond.shape[1]
91
+
92
+ if prepend_cond_mask is not None:
93
+ # Cast mask to bool
94
+ prepend_cond_mask = prepend_cond_mask.bool()
95
+
96
+ if cross_attn_cond is not None:
97
+ # Project the cross-attention conditioning to the embedding dimension
98
+ cross_attn_cond = self.to_cross_attn_embed(cross_attn_cond)
99
+
100
+ return self.model(x, mask=mask, context=cross_attn_cond, prepend_embeds=prepend_cond, prepend_mask=prepend_cond_mask)[:, prepend_length:, :]
101
+
102
+ class ContinuousTransformerAudioLMBackbone(AudioLMBackbone):
103
+ def __init__(self,
104
+ embed_dim: int,
105
+ cross_attn_cond_dim: int = 0,
106
+ prepend_cond_dim: int = 0,
107
+ project_cross_attn_cond: bool = False,
108
+ **kwargs):
109
+ super().__init__(embed_dim=embed_dim)
110
+
111
+ # Embeddings are done in the AudioLanguageModel, so we use the continuous-input transformer
112
+ self.model = ContinuousTransformer(
113
+ dim=embed_dim,
114
+ dim_in=embed_dim,
115
+ dim_out=embed_dim,
116
+ cross_attend = cross_attn_cond_dim > 0,
117
+ cond_token_dim = embed_dim if project_cross_attn_cond else cross_attn_cond_dim,
118
+ causal=True,
119
+ **kwargs
120
+ )
121
+
122
+ if prepend_cond_dim > 0:
123
+ # Prepend conditioning
124
+ self.to_prepend_embed = nn.Sequential(
125
+ nn.Linear(prepend_cond_dim, embed_dim, bias=False),
126
+ nn.SiLU(),
127
+ nn.Linear(embed_dim, embed_dim, bias=False)
128
+ )
129
+
130
+ if cross_attn_cond_dim > 0 and project_cross_attn_cond:
131
+ # Cross-attention conditioning
132
+ self.to_cross_attn_embed = nn.Sequential(
133
+ nn.Linear(cross_attn_cond_dim, embed_dim, bias=False),
134
+ nn.SiLU(),
135
+ nn.Linear(embed_dim, embed_dim, bias=False)
136
+ )
137
+ else:
138
+ self.to_cross_attn_embed = nn.Identity()
139
+
140
+ def forward(self, x, mask=None, prepend_cond=None, prepend_cond_mask=None, cross_attn_cond=None, global_cond=None, use_cache=False):
141
+
142
+ prepend_length = 0
143
+ if prepend_cond is not None:
144
+ # Project the prepend conditioning to the embedding dimension
145
+ prepend_cond = self.to_prepend_embed(prepend_cond)
146
+ prepend_length = prepend_cond.shape[1]
147
+
148
+ if prepend_cond_mask is not None:
149
+ # Cast mask to bool
150
+ prepend_cond_mask = prepend_cond_mask.bool()
151
+
152
+ if cross_attn_cond is not None:
153
+ # Cast cross_attn_cond to same dtype as self.to_cross_attn_embed
154
+ cross_attn_cond = cross_attn_cond.to(self.to_cross_attn_embed[0].weight.dtype)
155
+
156
+ # Project the cross-attention conditioning to the embedding dimension
157
+ cross_attn_cond = self.to_cross_attn_embed(cross_attn_cond)
158
+
159
+ return self.model(x, mask=mask, context=cross_attn_cond, prepend_embeds=prepend_cond, prepend_mask=prepend_cond_mask)[:, prepend_length:, :]
ThinkSound/models/lm_continuous.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import torch
3
+ from tqdm.auto import trange
4
+ import typing as tp
5
+ from einops import rearrange
6
+ from torch import nn
7
+
8
+ from .conditioners import MultiConditioner, create_multi_conditioner_from_conditioning_config
9
+ from .factory import create_pretransform_from_config
10
+ from .lm_backbone import AudioLMBackbone, XTransformersAudioLMBackbone, ContinuousTransformerAudioLMBackbone
11
+ from .pretransforms import Pretransform, AutoencoderPretransform, PretrainedDACPretransform, AudiocraftCompressionPretransform
12
+ from .utils import multinomial, sample_top_k, sample_top_p
13
+ from ..models.diffusion import DiffusionModelWrapper, ConditionedDiffusionModelWrapper, create_diffusion_cond_from_config
14
+
15
+ from .codebook_patterns import (
16
+ CodebooksPatternProvider,
17
+ DelayedPatternProvider,
18
+ MusicLMPattern,
19
+ ParallelPatternProvider,
20
+ UnrolledPatternProvider
21
+ )
22
+
23
+ # Copied and modified from https://github.com/facebookresearch/audiocraft/blob/main/audiocraft/models/lm.py under MIT license
24
+ # License can be found in LICENSES/LICENSE_META.txt
25
+
26
+ @dataclass
27
+ class LMContinuousOutput:
28
+ # The logits are already re-aligned with the input codes
29
+ # hence no extra shift is required, e.g. when computing CE
30
+ logits: torch.Tensor # [B, K, T, card]
31
+ mask: torch.Tensor # [B, K, T]
32
+
33
+ # Wrapper for a multi-codebook language model
34
+ # Handles patterns and quantizer heads
35
+ class AudioLMContinuousModel(nn.Module):
36
+ def __init__(
37
+ self,
38
+ backbone: AudioLMBackbone,
39
+ ):
40
+ super().__init__()
41
+
42
+ self.backbone = backbone
43
+
44
+ def sample_orders(self, bsz):
45
+ # generate a batch of random generation orders
46
+ orders = []
47
+ for _ in range(bsz):
48
+ order = np.array(list(range(self.seq_len)))
49
+ np.random.shuffle(order)
50
+ orders.append(order)
51
+ orders = torch.Tensor(np.array(orders)).cuda().long()
52
+ return orders
53
+
54
+ def random_masking(self, x, orders):
55
+ # generate token mask
56
+ bsz, seq_len, embed_dim = x.shape
57
+ mask_rate = self.mask_ratio_generator.rvs(1)[0]
58
+ num_masked_tokens = int(np.ceil(seq_len * mask_rate))
59
+ mask = torch.zeros(bsz, seq_len, device=x.device)
60
+ mask = torch.scatter(mask, dim=-1, index=orders[:, :num_masked_tokens],
61
+ src=torch.ones(bsz, seq_len, device=x.device))
62
+ return mask
63
+
64
+ def forward(self,
65
+ sequence: torch.Tensor, #[batch, seq_len,
66
+ prepend_cond=None, #[batch, seq, channels]
67
+ prepend_cond_mask=None,
68
+ cross_attn_cond=None, #[batch, seq, channels],
69
+ **kwargs
70
+ ):
71
+
72
+
73
+ batch, seq_len, dim = sequence.shape
74
+
75
+ dtype = next(self.parameters()).dtype
76
+
77
+ if cross_attn_cond is not None:
78
+ cross_attn_cond = cross_attn_cond.to(dtype)
79
+
80
+ if prepend_cond is not None:
81
+ prepend_cond = prepend_cond.to(dtype)
82
+
83
+ if prepend_cond_mask is not None:
84
+ prepend_cond_mask = prepend_cond_mask.to(dtype)
85
+
86
+ x = sequence.to(dtype)
87
+ orders = self.sample_orders(bsz=batch)
88
+ mask = self.random_masking(x, orders)
89
+
90
+ output = self.backbone(
91
+ x,
92
+ mask = mask,
93
+ cross_attn_cond=cross_attn_cond,
94
+ prepend_cond=prepend_cond,
95
+ prepend_cond_mask=prepend_cond_mask,
96
+ **kwargs
97
+ ) # [batch, seq_len, embed_dim]
98
+
99
+
100
+ return output
101
+
102
+ # Conditioning and generation wrapper for a multi-codebook language model
103
+ # Handles conditioning, CFG, generation, and encoding/decoding
104
+ class AudioLanguageModelWrapper(nn.Module):
105
+ def __init__(
106
+ self,
107
+ pretransform: Pretransform,
108
+ lm: AudioLanguageModel,
109
+ diff: ConditionedDiffusionModelWrapper,
110
+ sample_rate: int,
111
+ min_input_length: int,
112
+ conditioner: MultiConditioner = None,
113
+ diffusion_objective: tp.Literal["v", "rectified_flow"] = "v",
114
+ cross_attn_cond_ids: tp.List[str] = [],
115
+ prepend_cond_ids: tp.List[str] = [],
116
+ global_cond_ids: tp.List[str] = []
117
+ ):
118
+ super().__init__()
119
+
120
+ assert pretransform.is_discrete, "Pretransform must be discrete"
121
+ self.pretransform = pretransform
122
+
123
+ self.pretransform.requires_grad_(False)
124
+ self.pretransform.eval()
125
+ self.diffusion_objective = diffusion_objective
126
+ print(f'Training in the {diffusion_objective} formulation')
127
+ if isinstance(self.pretransform, AutoencoderPretransform):
128
+ self.num_quantizers = self.pretransform.model.bottleneck.num_quantizers
129
+ self.codebook_size = self.pretransform.model.bottleneck.codebook_size
130
+ elif isinstance(self.pretransform, PretrainedDACPretransform):
131
+ self.num_quantizers = self.pretransform.model.num_quantizers
132
+ self.codebook_size = self.pretransform.model.codebook_size
133
+ elif isinstance(self.pretransform, AudiocraftCompressionPretransform):
134
+ self.num_quantizers = self.pretransform.num_quantizers
135
+ self.codebook_size = self.pretransform.codebook_size
136
+ else:
137
+ raise NotImplementedError(f"Unrecognized pretransform type {type(self.pretransform)}")
138
+
139
+ self.conditioner = conditioner
140
+
141
+ self.lm = lm
142
+
143
+ self.sample_rate = sample_rate
144
+ self.min_input_length = min_input_length
145
+
146
+ self.cross_attn_cond_ids = cross_attn_cond_ids
147
+ self.prepend_cond_ids = prepend_cond_ids
148
+ self.global_cond_ids = global_cond_ids
149
+
150
+ def get_conditioning_inputs(self, cond: tp.Dict[str, tp.Any], negative=False):
151
+ cross_attention_input = None
152
+ prepend_cond = None
153
+ prepend_cond_mask = None
154
+ global_cond = None
155
+
156
+ if len(self.cross_attn_cond_ids) > 0:
157
+ # Concatenate all cross-attention inputs over the sequence dimension
158
+ # Assumes that the cross-attention inputs are of shape (batch, seq, channels)
159
+ cross_attention_input = torch.cat([cond[key][0] for key in self.cross_attn_cond_ids], dim=1)
160
+
161
+ if len(self.prepend_cond_ids) > 0:
162
+ # Concatenate all prepend conditioning inputs over the sequence dimension
163
+ # Assumes that the prepend conditioning inputs are of shape (batch, seq, channels)
164
+ prepend_cond = torch.cat([cond[key][0] for key in self.prepend_cond_ids], dim=1)
165
+ prepend_cond_mask = torch.cat([cond[key][1] for key in self.prepend_cond_ids], dim=1)
166
+
167
+ if len(self.global_cond_ids) > 0:
168
+ # Concatenate all global conditioning inputs over the channel dimension
169
+ # Assumes that the global conditioning inputs are of shape (batch, channels)
170
+ global_cond = torch.cat([cond[key][0] for key in self.global_cond_ids], dim=-1)
171
+ if len(global_cond.shape) == 3:
172
+ global_cond = global_cond.squeeze(1)
173
+
174
+ if negative:
175
+ return {
176
+ "negative_cross_attn_cond": cross_attention_input,
177
+ "negative_prepend_cond": prepend_cond,
178
+ "negative_prepend_cond_mask": prepend_cond_mask,
179
+ "negative_global_cond": global_cond
180
+ }
181
+ else:
182
+ return {
183
+ "cross_attn_cond": cross_attention_input,
184
+ "prepend_cond": prepend_cond,
185
+ "prepend_cond_mask": prepend_cond_mask,
186
+ "global_cond": global_cond
187
+ }
188
+
189
+ def compute_logits(
190
+ self,
191
+ audios,
192
+ condition_tensors=None,
193
+ cfg_dropout_prob=0.0,
194
+ **kwargs
195
+ ):
196
+ """
197
+ Compute logits for a batch of codes, and translates from conditioning inputs to model inputs
198
+ Handles CFG dropout
199
+ """
200
+
201
+ if condition_tensors is None:
202
+ condition_tensors = {}
203
+
204
+ conditioning_inputs = self.get_conditioning_inputs(condition_tensors)
205
+
206
+ cross_attn_cond = conditioning_inputs["cross_attn_cond"]
207
+ prepend_cond = conditioning_inputs["prepend_cond"]
208
+ prepend_cond_mask = conditioning_inputs["prepend_cond_mask"]
209
+ global_cond = conditioning_inputs["global_cond"]
210
+
211
+ if cfg_dropout_prob > 0.0:
212
+ if cross_attn_cond is not None:
213
+ null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device)
214
+ dropout_mask = torch.bernoulli(torch.full((cross_attn_cond.shape[0], 1, 1), cfg_dropout_prob, device=cross_attn_cond.device)).to(torch.bool)
215
+ cross_attn_cond = torch.where(dropout_mask, null_embed, cross_attn_cond)
216
+
217
+ if prepend_cond is not None:
218
+ null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device)
219
+ dropout_mask = torch.bernoulli(torch.full((prepend_cond.shape[0], 1, 1), cfg_dropout_prob, device=prepend_cond.device)).to(torch.bool)
220
+ prepend_cond = torch.where(dropout_mask, null_embed, prepend_cond)
221
+
222
+ if global_cond is not None:
223
+ null_embed = torch.zeros_like(global_cond, device=global_cond.device)
224
+ dropout_mask = torch.bernoulli(torch.full((global_cond.shape[0], 1), cfg_dropout_prob, device=global_cond.device)).to(torch.bool)
225
+ global_cond = torch.where(dropout_mask, null_embed, global_cond)
226
+
227
+ return self.lm.forward(audios, cross_attn_cond=cross_attn_cond, prepend_cond=prepend_cond, prepend_cond_mask=prepend_cond_mask, global_cond=global_cond, **kwargs)
228
+
229
+ def _sample_next_token(
230
+ self,
231
+ sequence, #[batch, num_quantizers, seq_len]
232
+ conditioning_tensors=None,
233
+ cross_attn_use_cfg=True,
234
+ prepend_use_cfg=True,
235
+ global_use_cfg=True,
236
+ cfg_scale=1.0,
237
+ top_k=250,
238
+ top_p=0.0,
239
+ temp=1.0,
240
+ **kwargs
241
+ ):
242
+ """
243
+ Sample the next token for a batch of codes, and translates from conditioning inputs to model inputs
244
+ Handles CFG inference
245
+ """
246
+
247
+ if conditioning_tensors is None:
248
+ conditioning_tensors = {}
249
+
250
+ conditioning_inputs = self.get_conditioning_inputs(conditioning_tensors)
251
+
252
+ cross_attn_cond = conditioning_inputs["cross_attn_cond"]
253
+ prepend_cond = conditioning_inputs["prepend_cond"]
254
+ prepend_cond_mask = conditioning_inputs["prepend_cond_mask"]
255
+ global_cond = conditioning_inputs["global_cond"]
256
+
257
+ if cfg_scale != 1.0:
258
+
259
+ # Batch size is doubled to account for negative samples
260
+ sequence = torch.cat([sequence, sequence], dim=0)
261
+
262
+ if cross_attn_cond is not None and cross_attn_use_cfg:
263
+ null_embed = torch.zeros_like(cross_attn_cond, device=cross_attn_cond.device)
264
+
265
+ cross_attn_cond = torch.cat([cross_attn_cond, null_embed], dim=0)
266
+
267
+ if prepend_cond is not None and prepend_use_cfg:
268
+ null_embed = torch.zeros_like(prepend_cond, device=prepend_cond.device)
269
+
270
+ prepend_cond = torch.cat([prepend_cond, null_embed], dim=0)
271
+
272
+ if prepend_cond_mask is not None:
273
+ prepend_cond_mask = torch.cat([prepend_cond_mask, prepend_cond_mask], dim=0)
274
+
275
+ if global_cond is not None and global_use_cfg:
276
+ null_embed = torch.zeros_like(global_cond, device=global_cond.device)
277
+
278
+ global_cond = torch.cat([global_cond, null_embed], dim=0)
279
+
280
+ logits = self.lm(sequence, cross_attn_cond=cross_attn_cond, prepend_cond=prepend_cond, prepend_cond_mask=prepend_cond_mask, global_cond=global_cond, **kwargs)
281
+
282
+ if cfg_scale != 1.0:
283
+ cond_logits, uncond_logits = logits.chunk(2, dim=0)
284
+
285
+ logits = uncond_logits + (cond_logits - uncond_logits) * cfg_scale
286
+
287
+ logits = rearrange(logits, "b n s c -> b n c s") # [batch, num_quantizers, codebook_size, seq_len]
288
+
289
+ # Grab the logits for the last step
290
+ logits = logits[:, :, :, -1] # [batch, num_quantizers, codebook_size]
291
+
292
+ # Apply top-k or top-p sampling
293
+
294
+ if temp > 0:
295
+ probs = torch.softmax(logits / temp, dim=-1)
296
+
297
+ if top_p > 0.0:
298
+ next_token = sample_top_p(probs, p=top_p)
299
+ elif top_k > 0:
300
+ next_token = sample_top_k(probs, k=top_k)
301
+ else:
302
+ next_token = multinomial(probs, num_samples=1)
303
+
304
+ else:
305
+ next_token = torch.argmax(logits, dim=-1, keepdim=True) # [batch, num_quantizers, 1]
306
+
307
+ return next_token
308
+
309
+ @torch.no_grad()
310
+ def generate(
311
+ self,
312
+ max_gen_len: int = 256,
313
+ batch_size: tp.Optional[int] = None,
314
+ init_data: tp.Optional[torch.Tensor] = None,
315
+ conditioning: tp.Optional[tp.Dict[str, tp.Any]] = None,
316
+ conditioning_tensors: tp.Optional[tp.Dict[str, tp.Any]] = None,
317
+ callback: tp.Optional[tp.Callable[[int, int], None]] = None,
318
+ use_cache: bool = True,
319
+ cfg_scale: float = 1.0,
320
+ **kwargs
321
+ ):
322
+ device = next(self.parameters()).device
323
+
324
+ if conditioning_tensors is None and conditioning is not None:
325
+ # Convert conditioning inputs to conditioning tensors
326
+ conditioning_tensors = self.conditioner(conditioning, device)
327
+
328
+ # Check that batch size is consistent across inputs
329
+ possible_batch_sizes = []
330
+
331
+ if batch_size is not None:
332
+ possible_batch_sizes.append(batch_size)
333
+ elif init_data is not None:
334
+ possible_batch_sizes.append(init_data.shape[0])
335
+ elif conditioning_tensors is not None:
336
+ # Assume that the first conditioning tensor has the batch dimension
337
+ possible_batch_sizes.append(conditioning_tensors[list(conditioning_tensors.keys())[0]][0].shape[0])
338
+ else:
339
+ possible_batch_sizes.append(1)
340
+
341
+ assert [x == possible_batch_sizes[0] for x in possible_batch_sizes], "Batch size must be consistent across inputs"
342
+
343
+ batch_size = possible_batch_sizes[0]
344
+
345
+ if init_data is None:
346
+ # Initialize with zeros
347
+ assert batch_size > 0
348
+ init_data = torch.zeros((batch_size, self.num_quantizers, 0), device=device, dtype=torch.long)
349
+
350
+ batch_size, num_quantizers, seq_len = init_data.shape
351
+
352
+ start_offset = seq_len
353
+ assert start_offset < max_gen_len, "init data longer than max gen length"
354
+
355
+ pattern = self.lm.pattern_provider.get_pattern(max_gen_len)
356
+
357
+ unknown_token = -1
358
+
359
+ # Initialize the generated codes with the init data, padded with unknown tokens
360
+ gen_codes = torch.full((batch_size, num_quantizers, max_gen_len), unknown_token, device=device, dtype=torch.long)
361
+ gen_codes[:, :, :start_offset] = init_data # [batch, num_quantizers, max_gen_len]
362
+
363
+ gen_sequence, _, mask = pattern.build_pattern_sequence(gen_codes, self.lm.masked_token_id) # [batch, num_quantizers, gen_sequence_len]
364
+
365
+ start_offset_sequence = pattern.get_first_step_with_timesteps(start_offset)
366
+ assert start_offset_sequence is not None
367
+
368
+ # Generation
369
+ prev_offset = 0
370
+ gen_sequence_len = gen_sequence.shape[-1]
371
+
372
+ # Reset generation cache
373
+ if use_cache and self.lm.backbone.use_generation_cache:
374
+ self.lm.backbone.reset_generation_cache(max_gen_len, batch_size if cfg_scale == 1.0 else batch_size * 2)
375
+
376
+ for offset in trange(start_offset_sequence, gen_sequence_len):
377
+
378
+ # Get the full sequence up to the current offset
379
+ curr_sequence = gen_sequence[..., prev_offset:offset]
380
+
381
+ next_token = self._sample_next_token(
382
+ curr_sequence,
383
+ conditioning_tensors=conditioning_tensors,
384
+ use_cache=use_cache,
385
+ cfg_scale=cfg_scale,
386
+ **kwargs
387
+ )
388
+
389
+ valid_mask = mask[..., offset:offset+1].expand(batch_size, -1, -1)
390
+ next_token[~valid_mask] = self.lm.masked_token_id
391
+
392
+ # Update the generated sequence with the next token
393
+ gen_sequence[..., offset:offset+1] = torch.where(
394
+ gen_sequence[..., offset:offset+1] == unknown_token,
395
+ next_token,
396
+ gen_sequence[..., offset:offset+1]
397
+ )
398
+
399
+ if use_cache and self.lm.backbone.use_generation_cache:
400
+ # Only update the offset if caching is being used
401
+ prev_offset = offset
402
+
403
+ self.lm.backbone.update_generation_cache(offset)
404
+
405
+ if callback is not None:
406
+ # Callback to report progress
407
+ # Pass in the offset relative to the start of the sequence, and the length of the current sequence
408
+ callback(1 + offset - start_offset_sequence, gen_sequence_len - start_offset_sequence)
409
+
410
+ assert not (gen_sequence == unknown_token).any(), "Unknown tokens in generated sequence"
411
+
412
+ out_codes, _, out_mask = pattern.revert_pattern_sequence(gen_sequence, special_token=unknown_token)
413
+
414
+ # sanity checks over the returned codes and corresponding masks
415
+ assert (out_codes[..., :max_gen_len] != unknown_token).all()
416
+ assert (out_mask[..., :max_gen_len] == 1).all()
417
+
418
+ #out_codes = out_codes[..., 0:max_gen_len]
419
+
420
+ return out_codes
421
+
422
+
423
+ def generate_audio(
424
+ self,
425
+ **kwargs
426
+ ):
427
+ """
428
+ Generate audio from a batch of codes
429
+ """
430
+
431
+ codes = self.generate(**kwargs)
432
+
433
+ audio = self.pretransform.decode_tokens(codes)
434
+
435
+ return audio
436
+
437
+
438
+ def create_audio_lm_continuous_from_config(config):
439
+ model_config = config.get('model', None)
440
+ assert model_config is not None, 'model config must be specified in config'
441
+
442
+ sample_rate = config.get('sample_rate', None)
443
+ assert sample_rate is not None, "Must specify sample_rate in config"
444
+
445
+ lm_config = model_config.get('lm', None)
446
+ assert lm_config is not None, 'lm config must be specified in model config'
447
+
448
+
449
+
450
+ pretransform_config = model_config.get("pretransform", None)
451
+
452
+ if pretransform is not None:
453
+ pretransform = create_pretransform_from_config(pretransform, sample_rate)
454
+ min_input_length = pretransform.downsampling_ratio
455
+ else:
456
+ min_input_length = 1
457
+
458
+
459
+ conditioning_config = model_config.get('conditioning', None)
460
+
461
+ conditioner = None
462
+ if conditioning_config is not None:
463
+ conditioner = create_multi_conditioner_from_conditioning_config(conditioning_config)
464
+
465
+ cross_attn_cond_ids = lm_config.get('cross_attention_cond_ids', [])
466
+ prepend_cond_ids = lm_config.get('prepend_cond_ids', [])
467
+ global_cond_ids = lm_config.get('global_cond_ids', [])
468
+
469
+ lm_type = lm_config.get("type", None)
470
+ lm_model_config = lm_config.get("config", None)
471
+
472
+ assert lm_type is not None, "Must specify lm type in lm config"
473
+ assert lm_model_config is not None, "Must specify lm model config in lm config"
474
+
475
+ if lm_type == "x-transformers":
476
+ backbone = XTransformersAudioLMBackbone(**lm_model_config)
477
+ elif lm_type == "continuous_transformer":
478
+ backbone = ContinuousTransformerAudioLMBackbone(**lm_model_config)
479
+ else:
480
+ raise NotImplementedError(f"Unrecognized lm type {lm_type}")
481
+
482
+ lm = AudioLanguageModel(
483
+ pattern_provider=pattern_provider,
484
+ backbone=backbone,
485
+ num_quantizers=pretransform.num_quantizers,
486
+ codebook_size=pretransform.codebook_size
487
+ )
488
+
489
+ diff_config = model_config.get("diffusion", None)
490
+ diffusion_model = DiTWrapper(**diff_config)
491
+
492
+ cross_attention_ids = diffusion_config.get('cross_attention_cond_ids', [])
493
+ add_cond_ids = diffusion_config.get('add_cond_ids', [])
494
+ global_cond_ids = diffusion_config.get('global_cond_ids', [])
495
+ input_concat_ids = diffusion_config.get('input_concat_ids', [])
496
+ prepend_cond_ids = diffusion_config.get('prepend_cond_ids', [])
497
+
498
+ diff = ConditionedDiffusionModelWrapper(
499
+ diffusion_model,
500
+ conditioner=None,
501
+ min_input_length=min_input_length,
502
+ sample_rate=sample_rate,
503
+ cross_attn_cond_ids=cross_attention_ids,
504
+ global_cond_ids=global_cond_ids,
505
+ input_concat_ids=input_concat_ids,
506
+ prepend_cond_ids=prepend_cond_ids,
507
+ add_cond_ids=add_cond_ids,
508
+ pretransform=pretransform,
509
+ io_channels=2,
510
+ )
511
+
512
+
513
+ model = AudioLanguageModelWrapper(
514
+ pretransform=pretransform,
515
+ lm=lm,
516
+ diff=diff,
517
+ conditioner=conditioner,
518
+ sample_rate=sample_rate,
519
+ min_input_length=min_input_length,
520
+ cross_attn_cond_ids=cross_attn_cond_ids,
521
+ prepend_cond_ids=prepend_cond_ids,
522
+ global_cond_ids=global_cond_ids
523
+ )
524
+
525
+ return model
ThinkSound/models/local_attention.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from einops import rearrange
4
+ from torch import nn
5
+
6
+ from .blocks import AdaRMSNorm
7
+ from .transformer import Attention, FeedForward, RotaryEmbedding, LayerNorm
8
+
9
+ def checkpoint(function, *args, **kwargs):
10
+ kwargs.setdefault("use_reentrant", False)
11
+ return torch.utils.checkpoint.checkpoint(function, *args, **kwargs)
12
+
13
+ # Adapted from https://github.com/lucidrains/local-attention/blob/master/local_attention/transformer.py
14
+ class ContinuousLocalTransformer(nn.Module):
15
+ def __init__(
16
+ self,
17
+ *,
18
+ dim,
19
+ depth,
20
+ dim_in = None,
21
+ dim_out = None,
22
+ causal = False,
23
+ local_attn_window_size = 64,
24
+ heads = 8,
25
+ ff_mult = 2,
26
+ cond_dim = 0,
27
+ cross_attn_cond_dim = 0,
28
+ **kwargs
29
+ ):
30
+ super().__init__()
31
+
32
+ dim_head = dim//heads
33
+
34
+ self.layers = nn.ModuleList([])
35
+
36
+ self.project_in = nn.Linear(dim_in, dim) if dim_in is not None else nn.Identity()
37
+
38
+ self.project_out = nn.Linear(dim, dim_out) if dim_out is not None else nn.Identity()
39
+
40
+ self.local_attn_window_size = local_attn_window_size
41
+
42
+ self.cond_dim = cond_dim
43
+
44
+ self.cross_attn_cond_dim = cross_attn_cond_dim
45
+
46
+ self.rotary_pos_emb = RotaryEmbedding(max(dim_head // 2, 32))
47
+
48
+ for _ in range(depth):
49
+
50
+ self.layers.append(nn.ModuleList([
51
+ AdaRMSNorm(dim, cond_dim, eps=1e-8) if cond_dim > 0 else LayerNorm(dim),
52
+ Attention(
53
+ dim=dim,
54
+ dim_heads=dim_head,
55
+ causal=causal,
56
+ zero_init_output=True,
57
+ natten_kernel_size=local_attn_window_size,
58
+ ),
59
+ Attention(
60
+ dim=dim,
61
+ dim_heads=dim_head,
62
+ dim_context = cross_attn_cond_dim,
63
+ zero_init_output=True
64
+ ) if self.cross_attn_cond_dim > 0 else nn.Identity(),
65
+ AdaRMSNorm(dim, cond_dim, eps=1e-8) if cond_dim > 0 else LayerNorm(dim),
66
+ FeedForward(dim = dim, mult = ff_mult, no_bias=True)
67
+ ]))
68
+
69
+ def forward(self, x, mask = None, cond = None, cross_attn_cond = None, cross_attn_cond_mask = None, prepend_cond = None):
70
+
71
+ x = checkpoint(self.project_in, x)
72
+
73
+ if prepend_cond is not None:
74
+ x = torch.cat([prepend_cond, x], dim=1)
75
+
76
+ pos_emb = self.rotary_pos_emb.forward_from_seq_len(x.shape[1])
77
+
78
+ for attn_norm, attn, xattn, ff_norm, ff in self.layers:
79
+
80
+ residual = x
81
+ if cond is not None:
82
+ x = checkpoint(attn_norm, x, cond)
83
+ else:
84
+ x = checkpoint(attn_norm, x)
85
+
86
+ x = checkpoint(attn, x, mask = mask, rotary_pos_emb=pos_emb) + residual
87
+
88
+ if cross_attn_cond is not None:
89
+ x = checkpoint(xattn, x, context=cross_attn_cond, context_mask=cross_attn_cond_mask) + x
90
+
91
+ residual = x
92
+
93
+ if cond is not None:
94
+ x = checkpoint(ff_norm, x, cond)
95
+ else:
96
+ x = checkpoint(ff_norm, x)
97
+
98
+ x = checkpoint(ff, x) + residual
99
+
100
+ return checkpoint(self.project_out, x)
101
+
102
+ class TransformerDownsampleBlock1D(nn.Module):
103
+ def __init__(
104
+ self,
105
+ in_channels,
106
+ embed_dim = 768,
107
+ depth = 3,
108
+ heads = 12,
109
+ downsample_ratio = 2,
110
+ local_attn_window_size = 64,
111
+ **kwargs
112
+ ):
113
+ super().__init__()
114
+
115
+ self.downsample_ratio = downsample_ratio
116
+
117
+ self.transformer = ContinuousLocalTransformer(
118
+ dim=embed_dim,
119
+ depth=depth,
120
+ heads=heads,
121
+ local_attn_window_size=local_attn_window_size,
122
+ **kwargs
123
+ )
124
+
125
+ self.project_in = nn.Linear(in_channels, embed_dim, bias=False) if in_channels != embed_dim else nn.Identity()
126
+
127
+ self.project_down = nn.Linear(embed_dim * self.downsample_ratio, embed_dim, bias=False)
128
+
129
+
130
+ def forward(self, x):
131
+
132
+ x = checkpoint(self.project_in, x)
133
+
134
+ # Compute
135
+ x = self.transformer(x)
136
+
137
+ # Trade sequence length for channels
138
+ x = rearrange(x, "b (n r) c -> b n (c r)", r=self.downsample_ratio)
139
+
140
+ # Project back to embed dim
141
+ x = checkpoint(self.project_down, x)
142
+
143
+ return x
144
+
145
+ class TransformerUpsampleBlock1D(nn.Module):
146
+ def __init__(
147
+ self,
148
+ in_channels,
149
+ embed_dim,
150
+ depth = 3,
151
+ heads = 12,
152
+ upsample_ratio = 2,
153
+ local_attn_window_size = 64,
154
+ **kwargs
155
+ ):
156
+ super().__init__()
157
+
158
+ self.upsample_ratio = upsample_ratio
159
+
160
+ self.transformer = ContinuousLocalTransformer(
161
+ dim=embed_dim,
162
+ depth=depth,
163
+ heads=heads,
164
+ local_attn_window_size = local_attn_window_size,
165
+ **kwargs
166
+ )
167
+
168
+ self.project_in = nn.Linear(in_channels, embed_dim, bias=False) if in_channels != embed_dim else nn.Identity()
169
+
170
+ self.project_up = nn.Linear(embed_dim, embed_dim * self.upsample_ratio, bias=False)
171
+
172
+ def forward(self, x):
173
+
174
+ # Project to embed dim
175
+ x = checkpoint(self.project_in, x)
176
+
177
+ # Project to increase channel dim
178
+ x = checkpoint(self.project_up, x)
179
+
180
+ # Trade channels for sequence length
181
+ x = rearrange(x, "b n (c r) -> b (n r) c", r=self.upsample_ratio)
182
+
183
+ # Compute
184
+ x = self.transformer(x)
185
+
186
+ return x
187
+
188
+
189
+ class TransformerEncoder1D(nn.Module):
190
+ def __init__(
191
+ self,
192
+ in_channels,
193
+ out_channels,
194
+ embed_dims = [96, 192, 384, 768],
195
+ heads = [12, 12, 12, 12],
196
+ depths = [3, 3, 3, 3],
197
+ ratios = [2, 2, 2, 2],
198
+ local_attn_window_size = 64,
199
+ **kwargs
200
+ ):
201
+ super().__init__()
202
+
203
+ layers = []
204
+
205
+ for layer in range(len(depths)):
206
+ prev_dim = embed_dims[layer - 1] if layer > 0 else embed_dims[0]
207
+
208
+ layers.append(
209
+ TransformerDownsampleBlock1D(
210
+ in_channels = prev_dim,
211
+ embed_dim = embed_dims[layer],
212
+ heads = heads[layer],
213
+ depth = depths[layer],
214
+ downsample_ratio = ratios[layer],
215
+ local_attn_window_size = local_attn_window_size,
216
+ **kwargs
217
+ )
218
+ )
219
+
220
+ self.layers = nn.Sequential(*layers)
221
+
222
+ self.project_in = nn.Linear(in_channels, embed_dims[0], bias=False)
223
+ self.project_out = nn.Linear(embed_dims[-1], out_channels, bias=False)
224
+
225
+ def forward(self, x):
226
+ x = rearrange(x, "b c n -> b n c")
227
+ x = checkpoint(self.project_in, x)
228
+ x = self.layers(x)
229
+ x = checkpoint(self.project_out, x)
230
+ x = rearrange(x, "b n c -> b c n")
231
+
232
+ return x
233
+
234
+
235
+ class TransformerDecoder1D(nn.Module):
236
+ def __init__(
237
+ self,
238
+ in_channels,
239
+ out_channels,
240
+ embed_dims = [768, 384, 192, 96],
241
+ heads = [12, 12, 12, 12],
242
+ depths = [3, 3, 3, 3],
243
+ ratios = [2, 2, 2, 2],
244
+ local_attn_window_size = 64,
245
+ **kwargs
246
+ ):
247
+
248
+ super().__init__()
249
+
250
+ layers = []
251
+
252
+ for layer in range(len(depths)):
253
+ prev_dim = embed_dims[layer - 1] if layer > 0 else embed_dims[0]
254
+
255
+ layers.append(
256
+ TransformerUpsampleBlock1D(
257
+ in_channels = prev_dim,
258
+ embed_dim = embed_dims[layer],
259
+ heads = heads[layer],
260
+ depth = depths[layer],
261
+ upsample_ratio = ratios[layer],
262
+ local_attn_window_size = local_attn_window_size,
263
+ **kwargs
264
+ )
265
+ )
266
+
267
+ self.layers = nn.Sequential(*layers)
268
+
269
+ self.project_in = nn.Linear(in_channels, embed_dims[0], bias=False)
270
+ self.project_out = nn.Linear(embed_dims[-1], out_channels, bias=False)
271
+
272
+ def forward(self, x):
273
+ x = rearrange(x, "b c n -> b n c")
274
+ x = checkpoint(self.project_in, x)
275
+ x = self.layers(x)
276
+ x = checkpoint(self.project_out, x)
277
+ x = rearrange(x, "b n c -> b c n")
278
+ return x
ThinkSound/models/meta_queries/__init__.py ADDED
File without changes
ThinkSound/models/meta_queries/metaquery.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Optional, Union, List
8
+
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from diffusers.models import AutoencoderKL, AutoencoderDC
13
+ from diffusers.pipelines.pipeline_utils import numpy_to_pil
14
+ from diffusers.schedulers import (
15
+ DDPMScheduler,
16
+ FlowMatchEulerDiscreteScheduler,
17
+ DPMSolverMultistepScheduler,
18
+ )
19
+ from diffusers.utils.torch_utils import randn_tensor
20
+ from transformers import PreTrainedModel
21
+ import PIL
22
+ from tqdm import tqdm
23
+
24
+ from .model import MLLMInContextConfig, MLLMInContext
25
+ from diffusers.training_utils import (
26
+ compute_density_for_timestep_sampling,
27
+ compute_loss_weighting_for_sd3,
28
+ )
29
+
30
+
31
+ class MetaQueryConfig(MLLMInContextConfig):
32
+ model_type = "metaquery"
33
+
34
+ def __init__(
35
+ self,
36
+ vae_id: str = "Efficient-Large-Model/Sana_1600M_512px_diffusers",
37
+ input_size: int = 16,
38
+ in_channels: int = 32,
39
+ vae_downsample_f: int = 32,
40
+ noise_scheduler_id: str = "Efficient-Large-Model/Sana_1600M_512px_diffusers",
41
+ scheduler_id: str = "Efficient-Large-Model/Sana_1600M_512px_diffusers",
42
+ _gradient_checkpointing: bool = True,
43
+ loss_type: str = "flow",
44
+ num_metaqueries: int = 64,
45
+ modules_to_freeze: tuple[str] = (),
46
+ modules_to_unfreeze: tuple[str] = (),
47
+ **kwargs,
48
+ ):
49
+ super().__init__(**kwargs)
50
+ for key, value in kwargs.items():
51
+ setattr(self, key, value)
52
+ self.vae_id = vae_id
53
+ self.input_size = input_size
54
+ self.in_channels = in_channels
55
+ self.vae_downsample_f = vae_downsample_f
56
+ self.noise_scheduler_id = noise_scheduler_id
57
+ self.scheduler_id = scheduler_id
58
+ self._gradient_checkpointing = _gradient_checkpointing
59
+ self.loss_type = loss_type
60
+ self.num_metaqueries = num_metaqueries
61
+ self.modules_to_freeze = modules_to_freeze
62
+ self.modules_to_unfreeze = modules_to_unfreeze
63
+
64
+
65
+ class MetaQuery(PreTrainedModel):
66
+ config_class = MetaQueryConfig
67
+
68
+ def __init__(self, config, *args, **kwargs):
69
+ super().__init__(config, *args, **kwargs)
70
+ self.config = config
71
+
72
+ self.model = MLLMInContext(MLLMInContextConfig(**config.to_dict()))
73
+ self.loss_type = config.loss_type
74
+
75
+ if "Sana" in config.vae_id:
76
+ self.vae = AutoencoderDC.from_pretrained(config.vae_id, subfolder="vae")
77
+ else:
78
+ try:
79
+ self.vae = AutoencoderKL.from_pretrained(config.vae_id)
80
+ except:
81
+ self.vae = AutoencoderKL.from_pretrained(config.vae_id, subfolder="vae")
82
+
83
+ if self.loss_type == "flow":
84
+ self.noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
85
+ config.noise_scheduler_id, subfolder="scheduler"
86
+ )
87
+ elif self.loss_type == "diff":
88
+ self.noise_scheduler = DDPMScheduler.from_pretrained(
89
+ config.noise_scheduler_id, subfolder="scheduler"
90
+ )
91
+ else:
92
+ raise ValueError(f"Unknown loss type {self.loss_type}")
93
+
94
+ self.scheduler = DPMSolverMultistepScheduler.from_pretrained(
95
+ config.scheduler_id, subfolder="scheduler"
96
+ )
97
+
98
+ for module_name in config.modules_to_freeze:
99
+ if "." in module_name:
100
+ module = self
101
+ for sub_module_name in module_name.split("."):
102
+ module = getattr(module, sub_module_name, None)
103
+ if module is None:
104
+ break
105
+ else:
106
+ module.requires_grad_(False)
107
+ else:
108
+ module = getattr(self, module_name, None)
109
+ if module is not None:
110
+ module.requires_grad_(False)
111
+
112
+ for module_name in config.modules_to_unfreeze:
113
+ if "." in module_name:
114
+ module = self
115
+ for sub_module_name in module_name.split("."):
116
+ module = getattr(module, sub_module_name, None)
117
+ if module is None:
118
+ break
119
+ else:
120
+ module.requires_grad_(True)
121
+ else:
122
+ module = getattr(self, module_name, None)
123
+ if module is not None:
124
+ module.requires_grad_(True)
125
+
126
+ def get_sigmas(self, timesteps, device, n_dim=4, dtype=torch.float32):
127
+ sigmas = self.noise_scheduler.sigmas.to(device=device, dtype=dtype)
128
+ schedule_timesteps = self.noise_scheduler.timesteps.to(device)
129
+ timesteps = timesteps.to(device)
130
+ step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
131
+
132
+ sigma = sigmas[step_indices].flatten()
133
+ while len(sigma.shape) < n_dim:
134
+ sigma = sigma.unsqueeze(-1)
135
+ return sigma
136
+
137
+ def get_tokenizer(self):
138
+ return self.model.get_tokenizer()
139
+
140
+ def get_tokenize_fn(self):
141
+ return self.model.get_tokenize_fn()
142
+
143
+ def forward(
144
+ self, target, pixel_values=None, input_ids=None, attention_mask=None, **kwargs
145
+ ):
146
+ if self.vae is not None:
147
+ if isinstance(self.vae, AutoencoderKL):
148
+ latents = self.vae.encode(target).latent_dist.sample()
149
+ elif isinstance(self.vae, AutoencoderDC):
150
+ latents = self.vae.encode(target).latent
151
+ else:
152
+ raise ValueError(f"Unknown vae type {type(self.vae)}")
153
+ if (
154
+ "shift_factor" in self.vae.config
155
+ and self.vae.config.shift_factor is not None
156
+ ):
157
+ latents = latents - self.vae.config.shift_factor
158
+ latents = latents * self.vae.config.scaling_factor
159
+ else:
160
+ latents = target
161
+
162
+ bsz = latents.shape[0]
163
+
164
+ if (
165
+ pixel_values is not None
166
+ and hasattr(self.model, "mllm_type")
167
+ and self.model.mllm_type == "qwenvl"
168
+ ):
169
+ pixel_values = pixel_values.squeeze(0)
170
+
171
+ noise = torch.randn_like(latents, device=latents.device)
172
+
173
+ if self.loss_type == "flow":
174
+ weighting_scheme = "uniform"
175
+ u = compute_density_for_timestep_sampling(
176
+ weighting_scheme=weighting_scheme,
177
+ batch_size=bsz,
178
+ logit_mean=0.0,
179
+ logit_std=1.0,
180
+ mode_scale=1.29,
181
+ )
182
+ indices = (u * self.noise_scheduler.config.num_train_timesteps).long()
183
+ timesteps = self.noise_scheduler.timesteps[indices].to(
184
+ device=latents.device
185
+ )
186
+
187
+ sigmas = self.get_sigmas(
188
+ timesteps, latents.device, n_dim=latents.ndim, dtype=latents.dtype
189
+ )
190
+ noisy_latents = (1.0 - sigmas) * latents + sigmas * noise
191
+ prompt_embeds, attention_mask = self.model.encode_condition(
192
+ input_ids=input_ids,
193
+ attention_mask=attention_mask,
194
+ pixel_values=pixel_values,
195
+ image_sizes=kwargs.get("image_sizes", None),
196
+ )
197
+
198
+ model_pred = self.model(
199
+ x=noisy_latents,
200
+ timestep=timesteps,
201
+ prompt_embeds=prompt_embeds,
202
+ attention_mask=attention_mask,
203
+ )
204
+
205
+ target = noise - latents
206
+ weighting = compute_loss_weighting_for_sd3(
207
+ weighting_scheme=weighting_scheme, sigmas=sigmas
208
+ )
209
+ loss = torch.mean(
210
+ (
211
+ weighting.float() * (model_pred.float() - target.float()) ** 2
212
+ ).reshape(target.shape[0], -1),
213
+ 1,
214
+ )
215
+ loss = loss.mean()
216
+
217
+ elif self.loss_type == "diff":
218
+ # Sample a random timestep for each image
219
+ timesteps = torch.randint(
220
+ 0,
221
+ self.noise_scheduler.config.num_train_timesteps,
222
+ (bsz,),
223
+ device=latents.device,
224
+ )
225
+ timesteps = timesteps.long()
226
+ noisy_latents = self.noise_scheduler.add_noise(latents, noise, timesteps)
227
+
228
+ if self.noise_scheduler.config.prediction_type == "epsilon":
229
+ target = noise
230
+ elif self.noise_scheduler.config.prediction_type == "v_prediction":
231
+ target = self.noise_scheduler.get_velocity(latents, noise, timesteps)
232
+ else:
233
+ raise ValueError(
234
+ f"Unknown prediction type {self.noise_scheduler.config.prediction_type}"
235
+ )
236
+
237
+ prompt_embeds, attention_mask = self.model.encode_condition(
238
+ input_ids=input_ids,
239
+ attention_mask=attention_mask,
240
+ pixel_values=pixel_values,
241
+ image_sizes=kwargs.get("image_sizes", None),
242
+ )
243
+
244
+ noise_pred = self.model(
245
+ x=noisy_latents,
246
+ timestep=timesteps,
247
+ prompt_embeds=prompt_embeds,
248
+ attention_mask=attention_mask,
249
+ )
250
+ loss = F.mse_loss(noise_pred.float(), target.float(), reduction="mean")
251
+
252
+ return {"loss": loss}
253
+
254
+ @torch.no_grad()
255
+ def decode_latents(self, latents, normalize=True, return_tensor=False):
256
+ if self.vae is not None:
257
+ latents = latents / self.vae.config.scaling_factor
258
+ if (
259
+ "shift_factor" in self.vae.config
260
+ and self.vae.config.shift_factor is not None
261
+ ):
262
+ latents = latents + self.vae.config.shift_factor
263
+ samples = self.vae.decode(latents).sample
264
+ else:
265
+ samples = latents
266
+ if normalize:
267
+ samples = (samples / 2 + 0.5).clamp(0, 1)
268
+ else:
269
+ samples = samples.clamp(-1, 1)
270
+ if return_tensor:
271
+ return samples
272
+ samples = samples.cpu().permute(0, 2, 3, 1).float().numpy()
273
+ samples = numpy_to_pil(samples)
274
+ return samples
275
+
276
+ def sample_images(
277
+ self,
278
+ caption="",
279
+ input_images=None,
280
+ guidance_scale: float = 3.0,
281
+ image_guidance_scale: float = 1.5,
282
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
283
+ num_inference_steps: int = 30,
284
+ num_images_per_prompt: int = 1,
285
+ return_tensor=False,
286
+ negative_prompt="",
287
+ enable_progress_bar=False,
288
+ **kwargs,
289
+ ):
290
+ device = next(self.parameters()).device
291
+
292
+ if not isinstance(caption, list):
293
+ caption = [caption]
294
+ if input_images is not None:
295
+ if isinstance(input_images, list) and not isinstance(input_images[0], list):
296
+ input_images = [[img] for img in input_images]
297
+ elif isinstance(input_images, PIL.Image.Image):
298
+ input_images = [[input_images]]
299
+ assert isinstance(input_images, list) and all(
300
+ isinstance(sublist, list) for sublist in input_images
301
+ ), "input_images needs to be a nested list"
302
+
303
+ bsz = len(caption)
304
+ do_image_classifier_free_guidance = image_guidance_scale > 1.0
305
+
306
+ tokenize_func = self.get_tokenize_fn()
307
+ tokenizer = self.get_tokenizer()
308
+
309
+ if input_images is not None:
310
+ if do_image_classifier_free_guidance:
311
+ caption = [negative_prompt] * bsz * 2 + caption
312
+ input_images_null = [
313
+ (
314
+ [
315
+ PIL.Image.new("RGB", (img.size[0], img.size[1]))
316
+ for img in images
317
+ ]
318
+ if images
319
+ else None
320
+ )
321
+ for images in input_images
322
+ ]
323
+ input_images = input_images_null + input_images * 2
324
+ else:
325
+ caption = [negative_prompt] * bsz + caption
326
+ input_images = input_images * 2
327
+ input_ids, attention_mask, pixel_values, image_sizes = tokenize_func(
328
+ tokenizer, caption, input_images
329
+ )
330
+ else:
331
+ do_image_classifier_free_guidance = False
332
+ caption = [negative_prompt] * bsz + caption
333
+ input_ids, attention_mask = tokenize_func(tokenizer, caption)
334
+ pixel_values = None
335
+ image_sizes = None
336
+
337
+ latent_size = self.config.input_size
338
+ latent_channels = self.config.in_channels
339
+
340
+ latents = randn_tensor(
341
+ shape=(
342
+ bsz * num_images_per_prompt,
343
+ latent_channels,
344
+ latent_size,
345
+ latent_size,
346
+ ),
347
+ generator=generator,
348
+ device=device,
349
+ dtype=torch.float32,
350
+ )
351
+
352
+ # set step values
353
+ if isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):
354
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
355
+ self.scheduler.set_timesteps(num_inference_steps, sigmas=sigmas)
356
+ else:
357
+ self.scheduler.set_timesteps(num_inference_steps)
358
+
359
+ # Repeat pixel_values and conditions for each image per prompt
360
+ input_ids = input_ids.to(device=device).repeat_interleave(
361
+ num_images_per_prompt, dim=0
362
+ )
363
+ attention_mask = attention_mask.to(device=device).repeat_interleave(
364
+ num_images_per_prompt, dim=0
365
+ )
366
+ pixel_values = (
367
+ pixel_values.to(device=device)
368
+ .reshape(bsz, -1, *pixel_values.shape[1:])
369
+ .repeat_interleave(num_images_per_prompt, dim=0)
370
+ .flatten(0, 1)
371
+ if pixel_values is not None
372
+ else None
373
+ )
374
+ image_sizes = (
375
+ image_sizes.to(device=device).repeat_interleave(
376
+ num_images_per_prompt, dim=0
377
+ )
378
+ if image_sizes is not None
379
+ else None
380
+ )
381
+
382
+ prompt_embeds, attention_mask = self.model.encode_condition(
383
+ input_ids=input_ids,
384
+ attention_mask=attention_mask,
385
+ pixel_values=pixel_values,
386
+ image_sizes=image_sizes,
387
+ )
388
+ # Convert to float32 before saving
389
+ for t in tqdm(
390
+ self.scheduler.timesteps,
391
+ desc="Sampling images",
392
+ disable=not enable_progress_bar,
393
+ ):
394
+ latent_model_input = torch.cat([latents] * (len(input_ids) // len(latents)))
395
+ latent_model_input = latent_model_input.to(prompt_embeds.dtype)
396
+ if hasattr(self.scheduler, "scale_model_input"):
397
+ latent_model_input = self.scheduler.scale_model_input(
398
+ latent_model_input, t
399
+ )
400
+
401
+ # predict noise model_output
402
+ noise_pred = self.model(
403
+ x=latent_model_input,
404
+ timestep=t.unsqueeze(0)
405
+ .expand(latent_model_input.shape[0])
406
+ .to(latents.device),
407
+ prompt_embeds=prompt_embeds,
408
+ attention_mask=attention_mask,
409
+ )
410
+
411
+ # perform guidance
412
+ if do_image_classifier_free_guidance:
413
+ noise_pred_uncond, noise_pred_uncond_text, noise_pred = (
414
+ noise_pred.chunk(3)
415
+ )
416
+ noise_pred = (
417
+ noise_pred_uncond
418
+ + image_guidance_scale
419
+ * (noise_pred_uncond_text - noise_pred_uncond)
420
+ + guidance_scale * (noise_pred - noise_pred_uncond_text)
421
+ )
422
+ else:
423
+ noise_pred_uncond, noise_pred = noise_pred.chunk(2)
424
+ noise_pred = noise_pred_uncond + guidance_scale * (
425
+ noise_pred - noise_pred_uncond
426
+ )
427
+
428
+ # compute previous image: x_t -> x_t-1
429
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
430
+
431
+ samples = self.decode_latents(
432
+ latents.to(self.vae.dtype) if self.vae is not None else latents,
433
+ return_tensor=return_tensor,
434
+ )
435
+ return samples
ThinkSound/models/meta_queries/model.py ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import random
7
+ import math
8
+ from typing import List
9
+ import typing as tp
10
+ import torch
11
+ import os
12
+ os.environ["TOKENIZERS_PARALLELISM"] = "true"
13
+ USE_AUDIO_IN_VIDEO_RATIO = 1.0
14
+
15
+ from torch import nn
16
+ from torchvision import transforms as v2
17
+
18
+ from transformers import PretrainedConfig, PreTrainedModel, AutoProcessor, Qwen2Config
19
+
20
+ import time
21
+ from diffusers.models.normalization import RMSNorm
22
+
23
+ from transformers.video_utils import load_video
24
+
25
+ from .transformer_encoder import Qwen2Encoder
26
+
27
+ from typing import Any, Dict, List, Mapping, Optional, Tuple, Union
28
+ def to_device(
29
+ data: Any,
30
+ device: Union[str, torch.device, int],
31
+ dtype: Optional[torch.dtype] = None, # 新增
32
+ non_blocking: bool = False
33
+ ) -> Any:
34
+ """Move inputs to a device and optionally convert dtype"""
35
+ if isinstance(data, Mapping):
36
+ return type(data)({
37
+ k: to_device(v, device, dtype, non_blocking)
38
+ for k, v in data.items()
39
+ })
40
+ elif isinstance(data, (tuple, list)):
41
+ return type(data)(
42
+ to_device(v, device, dtype, non_blocking)
43
+ for v in data
44
+ )
45
+ elif isinstance(data, torch.Tensor):
46
+ tensor = data.to(device=device, non_blocking=non_blocking)
47
+ if dtype is not None and tensor.is_floating_point():
48
+ tensor = tensor.to(dtype=dtype)
49
+ return tensor
50
+ else:
51
+ return data
52
+
53
+ VIDEO_MIN_PIXELS=224*224
54
+ VIDEO_MAX_PIXELS=224*224
55
+
56
+ import torch.distributed as dist
57
+ def print_memory_summary(prefix: str = ""):
58
+
59
+ if not torch.cuda.is_available():
60
+ return
61
+
62
+ rank = dist.get_rank() if dist.is_initialized() else 0
63
+ device = torch.cuda.current_device()
64
+
65
+ allocated = torch.cuda.memory_allocated(device) / 1024**3
66
+ total = torch.cuda.get_device_properties(device).total_memory / 1024**3
67
+ usage = (allocated / total * 100) if total > 0 else 0
68
+
69
+ print(f"[Rank {rank}] {prefix} | GPU Memory: {allocated:.2f}/{total:.2f} GB ({usage:.1f}%)")
70
+
71
+
72
+ class MLLMInContextConfig(PretrainedConfig):
73
+ model_type = "mllm-in-context"
74
+
75
+ def __init__(
76
+ self,
77
+ mllm_id: str = "Qwen/Qwen2.5-VL-3B-Instruct",
78
+ diffusion_model_id: str = None,
79
+ num_metaqueries: int = None,
80
+ _gradient_checkpointing: bool = True,
81
+ max_input_text_tokens: int = 2560,
82
+ connector_num_hidden_layers: int = None,
83
+ system_prompt: str = "You will be given an video and its caption. Please describe the content of the video in detail in your own words.",
84
+ **kwargs,
85
+ ):
86
+ super().__init__()
87
+ self.mllm_id = mllm_id
88
+ self.diffusion_model_id = diffusion_model_id
89
+ self.num_metaqueries = num_metaqueries
90
+ self._gradient_checkpointing = _gradient_checkpointing
91
+ self.max_input_text_tokens = max_input_text_tokens
92
+ self.connector_num_hidden_layers = connector_num_hidden_layers
93
+ self.system_prompt = system_prompt
94
+
95
+ import numpy as np
96
+ import torchvision.transforms as T
97
+ import torch.nn.functional as F
98
+
99
+
100
+
101
+ default_config = MLLMInContextConfig()
102
+
103
+ class MLLMInContext(PreTrainedModel):
104
+
105
+ def __init__(
106
+ self,
107
+ output_dim: int,
108
+ query_len: int,
109
+ llm_id = "qwen_omni",
110
+ connection_layers=12,
111
+ config: MLLMInContextConfig = default_config,
112
+ ) -> None:
113
+ super().__init__(config)
114
+ self._gradient_checkpointing = config._gradient_checkpointing
115
+ self.config = config
116
+ config.num_metaqueries = query_len
117
+ config.connector_num_hidden_layers = connection_layers
118
+ print("use meta queries: ",query_len,flush=True)
119
+
120
+ if llm_id == "qwen_vl":
121
+ config.mllm_id = "Qwen/Qwen2.5-VL-3B-Instruct"
122
+ elif llm_id == "qwen_omni":
123
+ config.mllm_id = "Qwen/Qwen2.5-Omni-3B"
124
+ else:
125
+ raise ValueError(f"Unsupported model: {llm_id}")
126
+
127
+ if "Qwen2.5-VL" in config.mllm_id:
128
+ from .models.qwen25VL import (
129
+ Qwen2_5_VLForConditionalGeneration
130
+ )
131
+ self.mllm_type = "qwenvl"
132
+ elif "Qwen2.5-Omni" in config.mllm_id:
133
+ from .models.qwen25omni import (
134
+ Qwen2_5OmniForConditionalGeneration
135
+ )
136
+ self.mllm_type = "qwenomni"
137
+ elif "Qwen" in config.mllm_id:
138
+ self.mllm_type = "qwenlm"
139
+ elif "Llama" in config.mllm_id:
140
+ self.mllm_type = "llamaml"
141
+ else:
142
+ self.mllm_type = "llavaov"
143
+
144
+ if self.mllm_type == "qwenvl":
145
+ self.mllm_backbone = Qwen2_5_VLForConditionalGeneration.from_pretrained(
146
+ config.mllm_id, attn_implementation="flash_attention_2",torch_dtype=torch.bfloat16
147
+ )
148
+ self.mllm_backbone.model.config.use_sliding_window = False
149
+ self.mllm_backbone.model.config.sliding_window = None
150
+ #print(self.mllm_backbone.model)
151
+
152
+
153
+ self._freeze_mllm_backbone()
154
+
155
+ num_embeddings = self.mllm_backbone.get_input_embeddings().num_embeddings
156
+ self.num_embeddings = num_embeddings
157
+ if config.num_metaqueries > 0:
158
+ try:
159
+ self.mllm_backbone.resize_token_embeddings(
160
+ num_embeddings + config.num_metaqueries + 2
161
+ )
162
+ except:
163
+ self.mllm_backbone.resize_token_embeddings(
164
+ num_embeddings + config.num_metaqueries + 2, mean_resizing=False
165
+ )
166
+
167
+ def freeze_hook(grad):
168
+ grad[: self.num_embeddings].zero_()
169
+ return grad
170
+
171
+ self.mllm_backbone.model.embed_tokens.weight.register_hook(freeze_hook)
172
+ self.mllm_hidden_size = self.mllm_backbone.config.hidden_size
173
+ self.mllm_backbone.lm_head = nn.Identity()
174
+
175
+ self.tokenizer = AutoProcessor.from_pretrained(
176
+ config.mllm_id, video_min_pixels=VIDEO_MIN_PIXELS, video_max_pixels=VIDEO_MAX_PIXELS,use_fast=True,min_pixels=224*224,max_pixels=288*288
177
+ )
178
+ self.tokenizer.tokenizer.padding_side = "left"
179
+ self.tokenizer.resize_fn = None
180
+ #self.tokenizer.image_processor.size = {
181
+ # "height": 224,
182
+ # "width": 224
183
+ #}
184
+ # 3B 2048
185
+ # 7B 3584
186
+ self.tokenizer.system_prompt = config.system_prompt
187
+ elif self.mllm_type == "qwenomni":
188
+ self.mllm_backbone = Qwen2_5OmniForConditionalGeneration.from_pretrained(
189
+ config.mllm_id, attn_implementation="flash_attention_2",torch_dtype=torch.bfloat16
190
+ )
191
+ #self.mllm_backbone.disable_talker()
192
+ self.mllm_backbone.thinker.model.config.use_sliding_window = False
193
+ self.mllm_backbone.thinker.model.config.sliding_window = None
194
+ self._freeze_mllm_backbone()
195
+
196
+ num_embeddings = self.mllm_backbone.thinker.get_input_embeddings().num_embeddings
197
+ self.num_embeddings = num_embeddings
198
+ if config.num_metaqueries > 0:
199
+ try:
200
+ self.mllm_backbone.thinker.resize_token_embeddings(
201
+ num_embeddings + config.num_metaqueries + 2
202
+ )
203
+ except:
204
+ self.mllm_backbone.thinker.resize_token_embeddings(
205
+ num_embeddings + config.num_metaqueries + 2, mean_resizing=False
206
+ )
207
+
208
+ def freeze_hook(grad):
209
+ grad[: self.num_embeddings].zero_()
210
+ return grad
211
+
212
+ self.mllm_backbone.thinker.model.embed_tokens.weight.register_hook(freeze_hook)
213
+ self.mllm_hidden_size = self.mllm_backbone.thinker.model.config.hidden_size
214
+ self.mllm_backbone.thinker.lm_head = nn.Identity()
215
+
216
+ self.tokenizer = AutoProcessor.from_pretrained(
217
+ config.mllm_id, video_min_pixels=VIDEO_MIN_PIXELS, video_max_pixels=VIDEO_MAX_PIXELS,use_fast=True,min_pixels=224*224,max_pixels=288*288
218
+ )
219
+ self.tokenizer.tokenizer.padding_side = "left"
220
+ self.tokenizer.resize_fn = None
221
+ self.tokenizer.system_prompt = "You are Qwen, a virtual human developed by the Qwen Team, Alibaba Group, capable of perceiving auditory and visual inputs, as well as generating text and speech."
222
+
223
+ else:
224
+ raise ValueError(f"Unsupported model: {self.mllm_type}")
225
+
226
+
227
+
228
+ self.tokenizer.mllm_type = self.mllm_type
229
+ self.tokenizer.max_input_text_tokens = config.max_input_text_tokens
230
+ self.tokenizer.num_metaqueries = config.num_metaqueries
231
+
232
+ self.pad_token_id = getattr(
233
+ self.tokenizer, "tokenizer", self.tokenizer
234
+ ).pad_token_id
235
+ if config.num_metaqueries > 0:
236
+ tokenizer = getattr(self.tokenizer, "tokenizer", self.tokenizer)
237
+ tokenizer.add_special_tokens(
238
+ {
239
+ "additional_special_tokens": [
240
+ f"<pad_token_{i}>"
241
+ for i in range(num_embeddings - len(tokenizer))
242
+ ]
243
+ }
244
+ )
245
+ tokenizer.add_special_tokens(
246
+ {
247
+ "additional_special_tokens": ["<begin_of_audio>", "<end_of_audio>"]
248
+ + [f"<audio{i}>" for i in range(self.tokenizer.num_metaqueries)]
249
+ }
250
+ )
251
+ self.boi_token_id = tokenizer.convert_tokens_to_ids("<begin_of_audio>")
252
+ self.eoi_token_id = tokenizer.convert_tokens_to_ids("<end_of_audio>")
253
+
254
+ #self.mllm_backbone = torch.compile(self.mllm_backbone)
255
+
256
+ self.connector_in_dim = self.mllm_hidden_size
257
+ self.connector_out_dim = output_dim
258
+
259
+ norm = RMSNorm(self.connector_out_dim, eps=1e-5, elementwise_affine=True)
260
+ with torch.no_grad():
261
+ norm.weight.fill_(1.0)
262
+
263
+ encoder = Qwen2Encoder(
264
+ Qwen2Config(
265
+ hidden_size=self.connector_in_dim,
266
+ intermediate_size=self.connector_in_dim * 4,
267
+ num_hidden_layers=config.connector_num_hidden_layers,
268
+ num_attention_heads=self.connector_in_dim // 64,
269
+ num_key_value_heads=self.connector_in_dim // 64,
270
+ initializer_range=0.014,
271
+ use_cache=False,
272
+ rope=True,
273
+ qk_norm=True,
274
+ ),
275
+ )
276
+ self.connector = nn.Sequential(
277
+ encoder,
278
+ nn.Linear(self.connector_in_dim, self.connector_out_dim),
279
+ nn.GELU(approximate="tanh"),
280
+ nn.Linear(self.connector_out_dim, self.connector_out_dim),
281
+ norm,
282
+ )
283
+
284
+ if config._gradient_checkpointing:
285
+ try:
286
+ self.mllm_backbone.gradient_checkpointing_enable(
287
+ {"use_reentrant": False}
288
+ )
289
+ except:
290
+ pass
291
+ if not isinstance(self.connector, nn.Identity):
292
+ for module in self.connector:
293
+ if isinstance(module, Qwen2Encoder):
294
+ module.gradient_checkpointing_enable({"use_reentrant": False})
295
+
296
+ def _freeze_mllm_backbone(self):
297
+
298
+ print("\nFreeze MLLM backbone...")
299
+
300
+ for param in self.mllm_backbone.parameters():
301
+ param.requires_grad = False
302
+
303
+ if self.config.num_metaqueries > 0:
304
+ if hasattr(self.mllm_backbone,"model"):
305
+ embed_tokens = self.mllm_backbone.model.embed_tokens
306
+ embed_tokens.weight.requires_grad = True
307
+ elif hasattr(self.mllm_backbone,"thinker"):
308
+ embed_tokens = self.mllm_backbone.thinker.model.embed_tokens
309
+ embed_tokens.weight.requires_grad = True
310
+
311
+
312
+
313
+
314
+ def get_tokenizer(self):
315
+ return self.tokenizer
316
+
317
+ def get_tokenize_fn(self):
318
+ return self.tokenize
319
+
320
+ def get_resize_fn(self):
321
+ return self.resize_fn
322
+
323
+ @staticmethod
324
+ @torch.no_grad()
325
+ def tokenize(
326
+ tokenizer, caption, video = None,audio = None, text_response=None, add_generation_prompt=True
327
+ ):
328
+ #print(video)
329
+ if not isinstance(caption, List):
330
+ caption = [caption]
331
+
332
+ if video is not None and not isinstance(video, List):
333
+ video = [video]
334
+ if audio is not None and not isinstance(audio, List):
335
+ audio = [audio]
336
+
337
+ prefix = (
338
+ [
339
+ {
340
+ "role": "system",
341
+ "content": (
342
+ tokenizer.system_prompt
343
+ if tokenizer.mllm_type == "qwenlm"
344
+ else [{"type": "text", "text": tokenizer.system_prompt}]
345
+ ),
346
+ },
347
+ ]
348
+ if tokenizer.system_prompt is not None
349
+ else []
350
+ )
351
+
352
+ if not add_generation_prompt or tokenizer.num_metaqueries <= 0:
353
+ suffix = ""
354
+ elif tokenizer.mllm_type=="qwenvl":
355
+ suffix = (
356
+ "\n<begin_of_audio>"
357
+ + "".join([f"<audio{i}>" for i in range(tokenizer.num_metaqueries)])
358
+ + "<end_of_audio><|im_end|>"
359
+ )
360
+ elif tokenizer.mllm_type=="qwenomni":
361
+ suffix = (
362
+ "\n<begin_of_audio>"
363
+ + "".join([f"<audio{i}>" for i in range(tokenizer.num_metaqueries)])
364
+ + "<end_of_audio><|im_end|>"
365
+ )
366
+
367
+ caption = [
368
+ tokenizer.decode(
369
+ tokenizer(
370
+ text=cap,
371
+ return_tensors="pt",
372
+ padding="max_length",
373
+ max_length=tokenizer.max_input_text_tokens,
374
+ truncation=True
375
+ ).input_ids[0]
376
+ )
377
+ for cap in caption
378
+ ]
379
+
380
+ if audio is not None:
381
+ #print("audio",audio[0].shape,audio)
382
+ # If each batch item is not a list, wrap it in a single-element list (or empty list if None)
383
+ for i, aud in enumerate(audio):
384
+ if aud is not None and not isinstance(aud, list):
385
+ audio[i] = [aud]
386
+
387
+ if video is not None:
388
+ # If each batch item is not a list, wrap it in a single-element list (or empty list if None)
389
+ for i, vid in enumerate(video):
390
+ if vid is not None and not isinstance(vid, list):
391
+ #print("vid shape",vid.shape,flush=True)
392
+ video[i] = [vid]
393
+
394
+ # Resize each image in each batch if resize_fn is not None
395
+ if tokenizer.resize_fn is not None:
396
+ video = [
397
+ [tokenizer.resize_fn(sub_img) for sub_img in imgs] if imgs else None
398
+ for imgs in video
399
+ ]
400
+ if tokenizer.mllm_type == "qwenvl":
401
+ conversations = [
402
+ prefix
403
+ + [
404
+ {
405
+ "role": "user",
406
+ "content": (
407
+ [{"type": "video"} for _ in vids]
408
+ + [{"type": "text", "text": cap}]
409
+ if vids
410
+ else [{"type": "text", "text": cap}]
411
+ ),
412
+ },
413
+ ]
414
+ for cap, vids in zip(caption, video)
415
+ ]
416
+ kwargs = {"videos": [imgs for imgs in video if imgs]}
417
+ if tokenizer.mllm_type == "qwenomni":
418
+ conversations = [
419
+ prefix
420
+ + [
421
+ {
422
+ "role": "user",
423
+ "content": (
424
+ [{"type": "video"} for vid in vids] if vids else []
425
+ + [{"type": "text", "text": cap}]
426
+ ),
427
+ },
428
+ ]
429
+ for cap, vids, auds in zip(caption, video, audio)
430
+ ]
431
+ kwargs = {"videos": [vid for vids in video for vid in vids],
432
+ "audio": [aud for auds in audio for aud in auds]}
433
+ #print("conversations",conversations)
434
+ elif tokenizer.mllm_type in ["qwenlm", "llamaml"]:
435
+ conversations = [
436
+ prefix
437
+ + [
438
+ {
439
+ "role": "user",
440
+ "content": cap,
441
+ },
442
+ ]
443
+ for cap in caption
444
+ ]
445
+ kwargs = dict()
446
+
447
+ else:
448
+ conversations = [
449
+ prefix
450
+ + [
451
+ {
452
+ "role": "user",
453
+ "content": [{"type": "text", "text": cap}],
454
+ },
455
+ ]
456
+ for cap in caption
457
+ ]
458
+ kwargs = dict()
459
+
460
+
461
+ prompts = [
462
+ tokenizer.apply_chat_template(conv, add_generation_prompt=True)
463
+ for conv in conversations
464
+ ]
465
+ if tokenizer.mllm_type=="qwenomni":
466
+ prompts = [item for prompt in prompts for item in prompt]
467
+ #print(prompts,flush=True)
468
+
469
+ if text_response is not None:
470
+ prompts = [p + t.strip() for p, t in zip(prompts, text_response)]
471
+ if tokenizer.num_metaqueries > 0:
472
+ prompts = [p + suffix for p in prompts]
473
+
474
+ #print("prompts",prompts)
475
+ #print("kwargs",kwargs)
476
+ use_audio_in_video = random.random() < USE_AUDIO_IN_VIDEO_RATIO
477
+ #use_audio_in_video = True
478
+ text_inputs = tokenizer(
479
+ text=prompts,
480
+ return_tensors="pt",
481
+ padding=True,
482
+ videos_kwargs={"fps": 1, "use_audio_in_video": use_audio_in_video},
483
+ **kwargs,
484
+ )
485
+ #print("text_inputs",text_inputs,flush=True)
486
+ #print("input_ids",text_inputs["input_ids"].tolist(),flush=True)
487
+
488
+ return text_inputs
489
+
490
+
491
+ def encode_condition(
492
+ self, input_ids, attention_mask, **kwargs
493
+ ):
494
+ if self.mllm_type == "llavaov":
495
+ prompt_embeds = self.mllm_backbone(
496
+ input_ids=input_ids,
497
+ **kwargs,
498
+ attention_mask=attention_mask,
499
+ ).logits
500
+ elif self.mllm_type in ["qwenvl"]:
501
+
502
+ prompt_embeds = self.mllm_backbone(
503
+ input_ids=input_ids,
504
+ **kwargs,
505
+ attention_mask=attention_mask,
506
+ ).logits
507
+
508
+ elif self.mllm_type in ["qwenomni"]:
509
+ prompt_embeds = self.mllm_backbone.thinker(
510
+ input_ids=input_ids,
511
+ **kwargs,
512
+ attention_mask=attention_mask,
513
+ ).logits
514
+ elif self.mllm_type in ["qwenlm", "llamaml"]:
515
+ prompt_embeds = self.mllm_backbone(
516
+ input_ids=input_ids,
517
+ attention_mask=attention_mask,
518
+ ).logits
519
+ else:
520
+ raise ValueError(f"Unsupported model: {self.mllm_type}")
521
+
522
+ if self.tokenizer.num_metaqueries > 0:
523
+ # Get positions for all sequences in batch at once
524
+ boi_pos = torch.where(input_ids == self.boi_token_id)[1]
525
+ eoi_pos = torch.where(input_ids == self.eoi_token_id)[1]
526
+
527
+ # Create mask for selecting tokens between BOI and EOI
528
+ batch_size, seq_len = input_ids.shape
529
+ indices = torch.arange(seq_len, device=input_ids.device)[None, :].expand(
530
+ batch_size, -1
531
+ )
532
+
533
+
534
+
535
+ if boi_pos.shape[0] == batch_size and eoi_pos.shape[0] == batch_size:
536
+ mask = (indices > boi_pos[:, None]) & (indices < eoi_pos[:, None])
537
+ prompt_embeds = prompt_embeds[mask].view(
538
+ batch_size, -1, prompt_embeds.size(-1)
539
+ )
540
+ attention_mask = attention_mask[mask].view(batch_size, -1)
541
+ else:
542
+ print(f"[DEBUG] boi_pos.shape[0]={boi_pos.shape[0]}, eoi_pos.shape[0]={eoi_pos.shape[0]}")
543
+ print(f"[DEBUG] boi_pos={boi_pos}")
544
+ print(f"[DEBUG] eoi_pos={eoi_pos}",flush=True)
545
+ prompt_embeds = torch.zeros(
546
+ batch_size,
547
+ self.tokenizer.num_metaqueries,
548
+ prompt_embeds.size(-1),
549
+ device=prompt_embeds.device,
550
+ dtype=prompt_embeds.dtype,
551
+ requires_grad=True
552
+ )
553
+ attention_mask = None
554
+
555
+ return self.connector(prompt_embeds), attention_mask
556
+
557
+
558
+ def forward(self, conversations, device: tp.Union[torch.device, str]) -> tp.Tuple[torch.Tensor, torch.Tensor]:
559
+ self.mllm_backbone = self.mllm_backbone.to(device)
560
+
561
+ tokenize_func = self.get_tokenize_fn()
562
+ tokenizer = self.get_tokenizer()
563
+ conversations = [con.item() for con in conversations]
564
+ caption = [con["text"] for con in conversations]
565
+ video = [con["video"] for con in conversations]
566
+ audio = [con["audio"] for con in conversations if "audio" in con]
567
+ #start_time = time.time()
568
+ inputs = tokenize_func(
569
+ tokenizer, caption, video, audio
570
+ )
571
+
572
+ inputs = to_device(inputs,device,dtype = torch.bfloat16)
573
+
574
+
575
+ prompt_embeds, attention_mask = self.encode_condition(**inputs)
576
+ #print("prompt_embeds.shape:",prompt_embeds.shape,flush=True)
577
+
578
+ return [prompt_embeds, torch.ones(prompt_embeds.shape[0], 1).to(device)]
ThinkSound/models/meta_queries/models/__init__.py ADDED
File without changes
ThinkSound/models/meta_queries/models/process_audio_info.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ from io import BytesIO
3
+
4
+ import audioread
5
+ import av
6
+ import librosa
7
+ import numpy as np
8
+
9
+
10
+ SAMPLE_RATE=16000
11
+ def _check_if_video_has_audio(video_path):
12
+ container = av.open(video_path)
13
+ audio_streams = [stream for stream in container.streams if stream.type == "audio"]
14
+ if not audio_streams:
15
+ return False
16
+ return True
17
+
18
+
19
+ def process_audio_info(conversations: list[dict] | list[list[dict]], use_audio_in_video: bool):
20
+ """
21
+ Read and process audio info
22
+
23
+ Support dict keys:
24
+
25
+ type = audio
26
+ - audio
27
+ - audio_start
28
+ - audio_end
29
+
30
+ type = video
31
+ - video
32
+ - video_start
33
+ - video_end
34
+ """
35
+ audios = []
36
+ if isinstance(conversations[0], dict):
37
+ conversations = [conversations]
38
+ for conversation in conversations:
39
+ for message in conversation:
40
+ if not isinstance(message["content"], list):
41
+ continue
42
+ for ele in message["content"]:
43
+ if ele["type"] == "audio":
44
+ if "audio" in ele or "audio_url" in ele:
45
+ path = ele.get("audio", ele.get("audio_url"))
46
+ audio_start = ele.get("audio_start", 0.0)
47
+ audio_end = ele.get("audio_end", None)
48
+ if isinstance(path, np.ndarray):
49
+ if path.ndim > 1:
50
+ raise ValueError("Support only mono audio")
51
+ audios.append(
52
+ path[int(SAMPLE_RATE * audio_start) : None if audio_end is None else int(SAMPLE_RATE * audio_end)]
53
+ )
54
+ continue
55
+ elif path.startswith("data:audio"):
56
+ _, base64_data = path.split("base64,", 1)
57
+ data = BytesIO(base64.b64decode(base64_data))
58
+ elif path.startswith("http://") or path.startswith("https://"):
59
+ data = audioread.ffdec.FFmpegAudioFile(path)
60
+ elif path.startswith("file://"):
61
+ data = path[len("file://") :]
62
+ else:
63
+ data = path
64
+ else:
65
+ raise ValueError("Unknown audio {}".format(ele))
66
+ elif use_audio_in_video and ele["type"] == "video":
67
+ if "video" in ele or "video_url" in ele:
68
+ path = ele.get("video", ele.get("video_url"))
69
+ audio_start = ele.get("video_start", 0.0)
70
+ audio_end = ele.get("video_end", None)
71
+ assert _check_if_video_has_audio(
72
+ path
73
+ ), "Video must has audio track when use_audio_in_video=True"
74
+ if path.startswith("http://") or path.startswith("https://"):
75
+ data = audioread.ffdec.FFmpegAudioFile(path)
76
+ elif path.startswith("file://"):
77
+ data = path[len("file://") :]
78
+ else:
79
+ data = path
80
+ else:
81
+ raise ValueError("Unknown video {}".format(ele))
82
+ else:
83
+ continue
84
+ audios.append(
85
+ librosa.load(
86
+ data,
87
+ sr=SAMPLE_RATE,
88
+ offset=audio_start,
89
+ duration=(audio_end - audio_start) if audio_end is not None else None,
90
+ )[0]
91
+ )
92
+ if len(audios) == 0:
93
+ audios = None
94
+ return audios
ThinkSound/models/meta_queries/models/qwen25VL.py ADDED
The diff for this file is too large to render. See raw diff
 
ThinkSound/models/meta_queries/models/qwen25omni.py ADDED
The diff for this file is too large to render. See raw diff
 
ThinkSound/models/meta_queries/transformer_encoder.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from typing import Optional, Tuple
10
+
11
+ from transformers.models.qwen2.configuration_qwen2 import Qwen2Config
12
+ from transformers.models.qwen2.modeling_qwen2 import (
13
+ Qwen2PreTrainedModel,
14
+ Qwen2Attention,
15
+ Qwen2MLP,
16
+ Qwen2RMSNorm,
17
+ Qwen2RotaryEmbedding,
18
+ repeat_kv,
19
+ apply_rotary_pos_emb,
20
+ )
21
+ from transformers.integrations.sdpa_attention import sdpa_attention_forward
22
+ from torch.nn import functional as F
23
+
24
+
25
+ class MultiHeadRMSNorm(nn.Module):
26
+ def __init__(self, dim, heads=1):
27
+ super().__init__()
28
+ self.scale = dim**0.5
29
+ self.gamma = nn.Parameter(torch.ones(heads, 1, dim))
30
+
31
+ def forward(self, x):
32
+ return F.normalize(x, dim=-1) * self.gamma * self.scale
33
+
34
+
35
+ class Qwen2BidirectionalSdpaAttention(Qwen2Attention):
36
+ """
37
+ An SDPA-based attention that does NOT apply causal masking.
38
+ Inherits from Qwen2Attention, but sets self.is_causal = False.
39
+ """
40
+
41
+ def __init__(self, config: Qwen2Config, layer_idx: Optional[int] = None):
42
+ super().__init__(config, layer_idx)
43
+ self.is_causal = False
44
+ self.qk_norm = config.qk_norm
45
+ if self.qk_norm:
46
+ self.q_norm = MultiHeadRMSNorm(
47
+ config.hidden_size // config.num_attention_heads,
48
+ config.num_attention_heads,
49
+ )
50
+ self.k_norm = MultiHeadRMSNorm(
51
+ config.hidden_size // config.num_attention_heads,
52
+ config.num_key_value_heads,
53
+ )
54
+
55
+ def forward(
56
+ self,
57
+ hidden_states: torch.Tensor,
58
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
59
+ ):
60
+ input_shape = hidden_states.shape[:-1]
61
+ hidden_shape = (*input_shape, -1, self.head_dim)
62
+
63
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
64
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
65
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
66
+
67
+ if position_embeddings is not None:
68
+ cos, sin = position_embeddings
69
+ query_states, key_states = apply_rotary_pos_emb(
70
+ query_states, key_states, cos, sin
71
+ )
72
+
73
+ if self.qk_norm:
74
+ query_states = self.q_norm(query_states)
75
+ key_states = self.k_norm(key_states)
76
+
77
+ attn_output, attn_weights = sdpa_attention_forward(
78
+ self,
79
+ query_states,
80
+ key_states,
81
+ value_states,
82
+ attention_mask=None,
83
+ dropout=0.0 if not self.training else self.attention_dropout,
84
+ scaling=self.scaling,
85
+ is_causal=False,
86
+ )
87
+
88
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
89
+ attn_output = self.o_proj(attn_output)
90
+ return attn_output
91
+
92
+
93
+ class Qwen2EncoderLayer(nn.Module):
94
+ def __init__(self, config: Qwen2Config, layer_idx: int):
95
+ super().__init__()
96
+ self.hidden_size = config.hidden_size
97
+ self.self_attn = Qwen2BidirectionalSdpaAttention(config, layer_idx)
98
+ self.mlp = Qwen2MLP(config)
99
+
100
+ self.input_layernorm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
101
+ self.post_attention_layernorm = Qwen2RMSNorm(
102
+ config.hidden_size, eps=config.rms_norm_eps
103
+ )
104
+
105
+ def forward(
106
+ self,
107
+ hidden_states: torch.Tensor,
108
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
109
+ ):
110
+ # Norm + Self-Attn
111
+ residual = hidden_states
112
+ hidden_states = self.input_layernorm(hidden_states)
113
+
114
+ hidden_states = self.self_attn(
115
+ hidden_states=hidden_states,
116
+ position_embeddings=position_embeddings,
117
+ )
118
+ hidden_states = residual + hidden_states
119
+
120
+ # Norm + MLP
121
+ residual = hidden_states
122
+ hidden_states = self.post_attention_layernorm(hidden_states)
123
+ hidden_states = self.mlp(hidden_states)
124
+ hidden_states = residual + hidden_states
125
+
126
+ return hidden_states
127
+
128
+
129
+ class Qwen2Encoder(Qwen2PreTrainedModel):
130
+ supports_gradient_checkpointing = True
131
+
132
+ def __init__(self, config: Qwen2Config):
133
+ super().__init__(config)
134
+ self.layers = nn.ModuleList(
135
+ [Qwen2EncoderLayer(config, i) for i in range(self.config.num_hidden_layers)]
136
+ )
137
+ if config.rope:
138
+ self.rotary_emb = Qwen2RotaryEmbedding(config=config)
139
+ else:
140
+ self.rotary_emb = None
141
+ if hasattr(config, "norm") and config.norm:
142
+ self.norm = Qwen2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
143
+ else:
144
+ self.norm = None
145
+ self.gradient_checkpointing = True
146
+ self.post_init()
147
+
148
+ def _init_weights(self, module):
149
+ std = self.config.initializer_range
150
+ if isinstance(module, nn.Linear):
151
+ module.weight.data.normal_(mean=0.0, std=std)
152
+ if module.bias is not None:
153
+ module.bias.data.zero_()
154
+
155
+ def forward(self, hidden_states):
156
+ bsz, seq_len, _ = hidden_states.size()
157
+ position_ids = torch.arange(seq_len, device=hidden_states.device).unsqueeze(0)
158
+
159
+ # Compute RoPE embeddings once, shared across layers
160
+ if self.rotary_emb is not None:
161
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
162
+ else:
163
+ position_embeddings = None
164
+
165
+ for layer in self.layers:
166
+ if self.gradient_checkpointing and self.training:
167
+ hidden_states = self._gradient_checkpointing_func(
168
+ layer.__call__,
169
+ hidden_states,
170
+ position_embeddings,
171
+ )
172
+ else:
173
+ hidden_states = layer(
174
+ hidden_states,
175
+ position_embeddings=position_embeddings,
176
+ )
177
+ if self.norm:
178
+ hidden_states = self.norm(hidden_states)
179
+ return hidden_states
ThinkSound/models/mmdit.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from dataclasses import dataclass
3
+ from typing import Optional
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ import sys
9
+ from .mmmodules.ext.rotary_embeddings import compute_rope_rotations
10
+ from .mmmodules.model.embeddings import TimestepEmbedder
11
+ from .mmmodules.model.low_level import MLP, ChannelLastConv1d, ConvMLP
12
+ from .mmmodules.model.transformer_layers import (FinalBlock, JointBlock, MMDitSingleBlock)
13
+ from .utils import resample
14
+
15
+ log = logging.getLogger()
16
+
17
+
18
+ @dataclass
19
+ class PreprocessedConditions:
20
+ clip_f: torch.Tensor
21
+ sync_f: torch.Tensor
22
+ text_f: torch.Tensor
23
+ clip_f_c: torch.Tensor
24
+ text_f_c: torch.Tensor
25
+
26
+
27
+ # Partially from https://github.com/facebookresearch/DiT
28
+ class MMAudio(nn.Module):
29
+
30
+ def __init__(self,
31
+ *,
32
+ latent_dim: int,
33
+ clip_dim: int,
34
+ sync_dim: int,
35
+ text_dim: int,
36
+ hidden_dim: int,
37
+ depth: int,
38
+ fused_depth: int,
39
+ num_heads: int,
40
+ mlp_ratio: float = 4.0,
41
+ latent_seq_len: int,
42
+ clip_seq_len: int,
43
+ sync_seq_len: int,
44
+ text_seq_len: int = 77,
45
+ latent_mean: Optional[torch.Tensor] = None,
46
+ latent_std: Optional[torch.Tensor] = None,
47
+ empty_string_feat: Optional[torch.Tensor] = None,
48
+ v2: bool = False,
49
+ kernel_size: int = 7,
50
+ sync_kernel: int = 7,
51
+ use_inpaint: bool = False,
52
+ use_mlp: bool = False,
53
+ cross_attend: bool = False,
54
+ add_video: bool = False,
55
+ triple_fusion: bool = False,
56
+ gated_video: bool = False) -> None:
57
+ super().__init__()
58
+
59
+ self.v2 = v2
60
+ self.latent_dim = latent_dim
61
+ self._latent_seq_len = latent_seq_len
62
+ self._clip_seq_len = clip_seq_len
63
+ self._sync_seq_len = sync_seq_len
64
+ self._text_seq_len = text_seq_len
65
+ self.hidden_dim = hidden_dim
66
+ self.num_heads = num_heads
67
+ self.cross_attend = cross_attend
68
+ self.add_video = add_video
69
+ self.gated_video = gated_video
70
+ self.triple_fusion = triple_fusion
71
+ self.use_inpaint = use_inpaint
72
+ if self.gated_video:
73
+ self.gated_mlp = nn.Sequential(
74
+ nn.LayerNorm(hidden_dim * 2),
75
+ nn.Linear(hidden_dim*2, hidden_dim * 4, bias=False),
76
+ nn.SiLU(),
77
+ nn.Linear(hidden_dim * 4, hidden_dim, bias=False),
78
+ nn.Sigmoid()
79
+ )
80
+ # 初始化最后一层权重为零,促进初始均匀融合
81
+ nn.init.zeros_(self.gated_mlp[3].weight)
82
+ if self.triple_fusion:
83
+ self.gated_mlp_v = nn.Sequential(
84
+ nn.LayerNorm(hidden_dim * 3),
85
+ nn.Linear(hidden_dim*3, hidden_dim * 4, bias=False),
86
+ nn.SiLU(),
87
+ nn.Linear(hidden_dim * 4, hidden_dim, bias=False),
88
+ nn.Sigmoid()
89
+ )
90
+ self.gated_mlp_t = nn.Sequential(
91
+ nn.LayerNorm(hidden_dim * 3),
92
+ nn.Linear(hidden_dim*3, hidden_dim * 4, bias=False),
93
+ nn.SiLU(),
94
+ nn.Linear(hidden_dim * 4, hidden_dim, bias=False),
95
+ nn.Sigmoid()
96
+ )
97
+ # 初始化最后一层权重为零,促进初始均匀融合
98
+ nn.init.zeros_(self.gated_mlp_v[3].weight)
99
+ nn.init.zeros_(self.gated_mlp_t[3].weight)
100
+ if v2:
101
+ padding_size = (kernel_size - 1) // 2
102
+ if use_inpaint:
103
+ self.audio_input_proj = nn.Sequential(
104
+ ChannelLastConv1d(latent_dim*2, hidden_dim, kernel_size=kernel_size, padding=padding_size),
105
+ nn.SiLU(),
106
+ ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=kernel_size, padding=padding_size),
107
+ )
108
+ else:
109
+ self.audio_input_proj = nn.Sequential(
110
+ ChannelLastConv1d(latent_dim, hidden_dim, kernel_size=kernel_size, padding=padding_size),
111
+ nn.SiLU(),
112
+ ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=kernel_size, padding=padding_size),
113
+ )
114
+
115
+ self.clip_input_proj = nn.Sequential(
116
+ nn.Linear(clip_dim, hidden_dim),
117
+ nn.SiLU(),
118
+ ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=3, padding=1),
119
+ )
120
+ sync_pad = (sync_kernel - 1) // 2
121
+ self.sync_input_proj = nn.Sequential(
122
+ ChannelLastConv1d(sync_dim, hidden_dim, kernel_size=sync_kernel, padding=sync_pad),
123
+ nn.SiLU(),
124
+ ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=3, padding=1),
125
+ )
126
+
127
+ self.text_input_proj = nn.Sequential(
128
+ nn.Linear(text_dim, hidden_dim),
129
+ nn.SiLU(),
130
+ MLP(hidden_dim, hidden_dim * 4),
131
+ )
132
+ else:
133
+ self.audio_input_proj = nn.Sequential(
134
+ ChannelLastConv1d(latent_dim, hidden_dim, kernel_size=7, padding=3),
135
+ nn.SELU(),
136
+ ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=7, padding=3),
137
+ )
138
+
139
+ self.clip_input_proj = nn.Sequential(
140
+ nn.Linear(clip_dim, hidden_dim),
141
+ ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=3, padding=1),
142
+ )
143
+
144
+ self.sync_input_proj = nn.Sequential(
145
+ ChannelLastConv1d(sync_dim, hidden_dim, kernel_size=7, padding=3),
146
+ nn.SELU(),
147
+ ConvMLP(hidden_dim, hidden_dim * 4, kernel_size=3, padding=1),
148
+ )
149
+
150
+ self.text_input_proj = nn.Sequential(
151
+ nn.Linear(text_dim, hidden_dim),
152
+ MLP(hidden_dim, hidden_dim * 4),
153
+ )
154
+
155
+ self.clip_cond_proj = nn.Linear(hidden_dim, hidden_dim)
156
+ if use_mlp:
157
+ self.text_cond_proj = nn.Sequential(
158
+ nn.Linear(1024, hidden_dim),
159
+ MLP(hidden_dim, hidden_dim * 4),
160
+ )
161
+ else:
162
+ self.text_cond_proj = nn.Linear(1024, hidden_dim)
163
+ self.global_cond_mlp = MLP(hidden_dim, hidden_dim * 4)
164
+ # each synchformer output segment has 8 feature frames
165
+ self.sync_pos_emb = nn.Parameter(torch.zeros((1, 1, 8, sync_dim)))
166
+
167
+ self.final_layer = FinalBlock(hidden_dim, latent_dim)
168
+
169
+ if v2:
170
+ self.t_embed = TimestepEmbedder(hidden_dim,
171
+ frequency_embedding_size=hidden_dim,
172
+ max_period=1)
173
+ else:
174
+ self.t_embed = TimestepEmbedder(hidden_dim,
175
+ frequency_embedding_size=256,
176
+ max_period=10000)
177
+ self.joint_blocks = nn.ModuleList([
178
+ JointBlock(hidden_dim,
179
+ num_heads,
180
+ mlp_ratio=mlp_ratio,
181
+ pre_only=(i == depth - fused_depth - 1)) for i in range(depth - fused_depth)
182
+ ])
183
+
184
+ self.fused_blocks = nn.ModuleList([
185
+ MMDitSingleBlock(hidden_dim, num_heads, mlp_ratio=mlp_ratio, kernel_size=3, padding=1, cross_attend=cross_attend)
186
+ for i in range(fused_depth)
187
+ ])
188
+
189
+ if empty_string_feat is None:
190
+ empty_string_feat = torch.zeros((77, 1024))
191
+
192
+ empty_t5_feat = torch.zeros((77, 2048))
193
+
194
+ self.empty_string_feat = nn.Parameter(empty_string_feat, requires_grad=False)
195
+ self.empty_t5_feat = nn.Parameter(empty_t5_feat, requires_grad=False)
196
+ self.empty_audio_feat = nn.Parameter(torch.zeros(1, latent_dim), requires_grad=True)
197
+ self.empty_clip_feat = nn.Parameter(torch.zeros(1, clip_dim), requires_grad=True)
198
+ self.empty_sync_feat = nn.Parameter(torch.zeros(1, sync_dim), requires_grad=True)
199
+
200
+ self.initialize_weights()
201
+ self.initialize_rotations()
202
+
203
+ def initialize_rotations(self):
204
+ base_freq = 1.0
205
+ latent_rot = compute_rope_rotations(self._latent_seq_len,
206
+ self.hidden_dim // self.num_heads,
207
+ 10000,
208
+ freq_scaling=base_freq,
209
+ device=self.device)
210
+ clip_rot = compute_rope_rotations(self._clip_seq_len,
211
+ self.hidden_dim // self.num_heads,
212
+ 10000,
213
+ freq_scaling=base_freq * self._latent_seq_len /
214
+ self._clip_seq_len,
215
+ device=self.device)
216
+
217
+ self.latent_rot = nn.Buffer(latent_rot, persistent=False)
218
+ self.clip_rot = nn.Buffer(clip_rot, persistent=False)
219
+
220
+ def update_seq_lengths(self, latent_seq_len: int, clip_seq_len: int, sync_seq_len: int) -> None:
221
+ self._latent_seq_len = latent_seq_len
222
+ self._clip_seq_len = clip_seq_len
223
+ self._sync_seq_len = sync_seq_len
224
+ self.initialize_rotations()
225
+
226
+ def initialize_weights(self):
227
+
228
+ def _basic_init(module):
229
+ if isinstance(module, nn.Linear):
230
+ torch.nn.init.xavier_uniform_(module.weight)
231
+ if module.bias is not None:
232
+ nn.init.constant_(module.bias, 0)
233
+
234
+ self.apply(_basic_init)
235
+
236
+ # Initialize timestep embedding MLP:
237
+ nn.init.normal_(self.t_embed.mlp[0].weight, std=0.02)
238
+ nn.init.normal_(self.t_embed.mlp[2].weight, std=0.02)
239
+
240
+ # Zero-out adaLN modulation layers in DiT blocks:
241
+ for block in self.joint_blocks:
242
+ nn.init.constant_(block.latent_block.adaLN_modulation[-1].weight, 0)
243
+ nn.init.constant_(block.latent_block.adaLN_modulation[-1].bias, 0)
244
+ nn.init.constant_(block.clip_block.adaLN_modulation[-1].weight, 0)
245
+ nn.init.constant_(block.clip_block.adaLN_modulation[-1].bias, 0)
246
+ nn.init.constant_(block.text_block.adaLN_modulation[-1].weight, 0)
247
+ nn.init.constant_(block.text_block.adaLN_modulation[-1].bias, 0)
248
+ for block in self.fused_blocks:
249
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
250
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
251
+
252
+ # Zero-out output layers:
253
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
254
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
255
+ nn.init.constant_(self.final_layer.conv.weight, 0)
256
+ nn.init.constant_(self.final_layer.conv.bias, 0)
257
+
258
+ # empty string feat shall be initialized by a CLIP encoder
259
+ nn.init.constant_(self.sync_pos_emb, 0)
260
+ nn.init.constant_(self.empty_clip_feat, 0)
261
+ nn.init.constant_(self.empty_sync_feat, 0)
262
+
263
+ def preprocess_conditions(self, clip_f: torch.Tensor, sync_f: torch.Tensor,
264
+ text_f: torch.Tensor, t5_features: torch.Tensor, metaclip_global_text_features: torch.Tensor) -> PreprocessedConditions:
265
+ """
266
+ cache computations that do not depend on the latent/time step
267
+ i.e., the features are reused over steps during inference
268
+ """
269
+ # breakpoint()
270
+ assert clip_f.shape[1] == self._clip_seq_len, f'{clip_f.shape=} {self._clip_seq_len=}'
271
+ assert sync_f.shape[1] == self._sync_seq_len, f'{sync_f.shape=} {self._sync_seq_len=}'
272
+ assert text_f.shape[1] == self._text_seq_len, f'{text_f.shape=} {self._text_seq_len=}'
273
+
274
+ bs = clip_f.shape[0]
275
+
276
+ # B * num_segments (24) * 8 * 768
277
+ num_sync_segments = self._sync_seq_len // 8
278
+ sync_f = sync_f.view(bs, num_sync_segments, 8, -1) + self.sync_pos_emb
279
+ sync_f = sync_f.flatten(1, 2) # (B, VN, D)
280
+
281
+ # extend vf to match x
282
+ clip_f = self.clip_input_proj(clip_f) # (B, VN, D)
283
+ sync_f = self.sync_input_proj(sync_f) # (B, VN, D)
284
+
285
+ if t5_features is not None:
286
+
287
+ if metaclip_global_text_features is not None:
288
+ text_f_c = self.text_cond_proj(metaclip_global_text_features) # (B, D)
289
+ else:
290
+ text_f_c = self.text_cond_proj(text_f.mean(dim=1)) # (B, D)
291
+ # 计算填充长度
292
+ padding_size = t5_features.size(2) - text_f.size(2) # 渴望填充的数量
293
+ # 当确实需要填充的时候,确保填充是正数
294
+ if padding_size > 0:
295
+ # 填充 text_f 的特征维度两侧
296
+ text_f = F.pad(text_f, pad=(0, padding_size), mode='constant', value=0) # 在最后一个维度上进行填充
297
+ else:
298
+ text_f = text_f # 如果填充长度不是正数,则不需要填充
299
+ text_concat = torch.cat((text_f, t5_features), dim=1)
300
+ text_f = self.text_input_proj(text_concat) # (B, VN, D)
301
+ else:
302
+ text_f = self.text_input_proj(text_f) # (B, VN, D)
303
+ if metaclip_global_text_features is not None:
304
+ text_f_c = self.text_cond_proj(metaclip_global_text_features) # (B, D)
305
+ else:
306
+ text_f_c = self.text_cond_proj(text_f.mean(dim=1)) # (B, D)
307
+
308
+ # upsample the sync features to match the audio
309
+ sync_f = sync_f.transpose(1, 2) # (B, D, VN)
310
+ # sync_f = resample(sync_f, self._latent_seq_len)
311
+ sync_f = F.interpolate(sync_f, size=self._latent_seq_len, mode='nearest-exact')
312
+ sync_f = sync_f.transpose(1, 2) # (B, N, D)
313
+
314
+ # get conditional features from the clip side
315
+ clip_f_c = self.clip_cond_proj(clip_f.mean(dim=1)) # (B, D)
316
+
317
+ return PreprocessedConditions(clip_f=clip_f,
318
+ sync_f=sync_f,
319
+ text_f=text_f,
320
+ clip_f_c=clip_f_c,
321
+ text_f_c=text_f_c)
322
+
323
+ def predict_flow(self, latent: torch.Tensor, t: torch.Tensor,
324
+ conditions: PreprocessedConditions, inpaint_masked_input=None, cfg_scale:float=1.0,cfg_dropout_prob:float=0.0,scale_phi:float=0.0
325
+ ) -> torch.Tensor:
326
+ """
327
+ for non-cacheable computations
328
+ """
329
+ # print(f'cfg_scale: {cfg_scale}, cfg_dropout_prob: {cfg_dropout_prob}, scale_phi: {scale_phi}')
330
+ assert latent.shape[1] == self._latent_seq_len, f'{latent.shape=} {self._latent_seq_len=}'
331
+ empty_conditions = None
332
+
333
+ clip_f = conditions.clip_f
334
+ sync_f = conditions.sync_f
335
+ text_f = conditions.text_f
336
+ clip_f_c = conditions.clip_f_c
337
+ text_f_c = conditions.text_f_c
338
+
339
+ # breakpoint()
340
+ if inpaint_masked_input is not None:
341
+ if inpaint_masked_input.shape[1] != latent.shape[1]:
342
+ inpaint_masked_input = inpaint_masked_input.transpose(1,2)
343
+ latent = torch.cat([latent,inpaint_masked_input],dim=2)
344
+ latent = self.audio_input_proj(latent) # (B, N, D)
345
+ global_c = self.global_cond_mlp(clip_f_c + text_f_c) # (B, D)
346
+ # global_c = text_f_c
347
+ global_c = self.t_embed(t).unsqueeze(1) + global_c.unsqueeze(1) # (B, D)
348
+ extended_c = global_c + sync_f
349
+
350
+ for block in self.joint_blocks:
351
+ latent, clip_f, text_f = block(latent, clip_f, text_f, global_c, extended_c,
352
+ self.latent_rot, self.clip_rot) # (B, N, D)
353
+ if self.add_video:
354
+ if clip_f.shape[1] != latent.shape[1]:
355
+ clip_f = resample(clip_f, latent)
356
+
357
+ if self.triple_fusion:
358
+ text_f = torch.mean(text_f, dim=1, keepdim=True) # (bsz, 1, D)
359
+ text_f = text_f.expand(-1,latent.shape[1], -1) # (T_audio, D)
360
+ fusion = torch.concat((latent, clip_f, text_f),dim=-1)
361
+ gate_v = self.gated_mlp_v(fusion)
362
+ gate_t = self.gated_mlp_t(fusion)
363
+ # modulated_latent = gate * latent # 非对称设计
364
+ latent = latent + gate_v * clip_f + gate_t * text_f
365
+ elif self.gated_video:
366
+ fusion = torch.concat((latent, clip_f),dim=-1)
367
+ gate = self.gated_mlp(fusion)
368
+ modulated_latent = gate * latent # 非对称设计
369
+ latent = latent + modulated_latent
370
+ else:
371
+ latent = latent + clip_f
372
+
373
+ for block in self.fused_blocks:
374
+ if self.cross_attend:
375
+ latent = block(latent, extended_c, self.latent_rot, context=text_f)
376
+ else:
377
+ latent = block(latent, extended_c, self.latent_rot)
378
+
379
+ # should be extended_c; this is a minor implementation error #55
380
+ flow = self.final_layer(latent, extended_c) # (B, N, out_dim), remove t
381
+ return flow
382
+
383
+ def forward(self, latent: torch.Tensor, t: torch.Tensor, clip_f: torch.Tensor, sync_f: torch.Tensor,
384
+ text_f: torch.Tensor, inpaint_masked_input, t5_features, metaclip_global_text_features, cfg_scale:float,cfg_dropout_prob:float,scale_phi:float,video_dropout_prob:float=0.2) -> torch.Tensor:
385
+ """
386
+ latent: (B, N, C)
387
+ vf: (B, T, C_V)
388
+ t: (B,)
389
+ """
390
+ # breakpoint()
391
+ # print(f'cfg_scale: {cfg_scale}, cfg_dropout_prob: {cfg_dropout_prob}, scale_phi: {scale_phi}')
392
+ if self.use_inpaint and inpaint_masked_input is None:
393
+ inpaint_masked_input = torch.zeros_like(latent, device=latent.device)
394
+ latent = latent.permute(0, 2, 1)
395
+
396
+ if cfg_dropout_prob > 0.0:
397
+ bsz = latent.shape[0]
398
+ if inpaint_masked_input is not None:
399
+ # samples = torch.rand(bsz, device=latent.device)
400
+ # null_audio = (samples < cfg_dropout_prob)
401
+ # inpaint_masked_input = inpaint_masked_input.transpose(1,2)
402
+ # inpaint_masked_input[null_audio] = self.empty_audio_feat
403
+ inpaint_masked_input = inpaint_masked_input.transpose(1,2)
404
+ null_embed = torch.zeros_like(inpaint_masked_input,device=latent.device)
405
+ dropout_mask = torch.bernoulli(torch.full((inpaint_masked_input.shape[0], 1, 1), cfg_dropout_prob, device=latent.device)).to(torch.bool)
406
+ # inpaint_masked_input = torch.where(dropout_mask, self.empty_audio_feat, inpaint_masked_input)
407
+ inpaint_masked_input = torch.where(dropout_mask, null_embed, inpaint_masked_input)
408
+
409
+ # samples = torch.rand(bsz, device=latent.device)
410
+ # null_video = (samples < cfg_dropout_prob)
411
+ # clip_f[null_video] = self.empty_clip_feat
412
+ # sync_f[null_video] = self.empty_sync_feat
413
+ null_embed = torch.zeros_like(clip_f,device=latent.device)
414
+ dropout_mask = torch.bernoulli(torch.full((clip_f.shape[0], 1, 1), cfg_dropout_prob, device=latent.device)).to(torch.bool)
415
+ # clip_f = torch.where(dropout_mask, null_embed, clip_f)
416
+ clip_f = torch.where(dropout_mask, self.empty_clip_feat, clip_f)
417
+ null_embed = torch.zeros_like(sync_f,device=latent.device)
418
+ dropout_mask = torch.bernoulli(torch.full((sync_f.shape[0], 1, 1), video_dropout_prob, device=latent.device)).to(torch.bool)
419
+ # sync_f = torch.where(dropout_mask, null_embed, sync_f)
420
+ sync_f = torch.where(dropout_mask, self.empty_sync_feat, sync_f)
421
+ # samples = torch.rand(bsz, device=latent.device)
422
+ # null_text = (samples < cfg_dropout_prob)
423
+ # text_f[null_text] = self.empty_string_feat
424
+ null_embed = torch.zeros_like(text_f,device=latent.device)
425
+ dropout_mask = torch.bernoulli(torch.full((text_f.shape[0], 1, 1), cfg_dropout_prob, device=latent.device)).to(torch.bool)
426
+ # text_f = torch.where(dropout_mask, null_embed, text_f)
427
+ text_f = torch.where(dropout_mask, self.empty_string_feat, text_f)
428
+ if t5_features is not None:
429
+ # t5_features[null_text] = self.empty_t5_feat
430
+ null_embed = torch.zeros_like(t5_features,device=latent.device)
431
+ dropout_mask = torch.bernoulli(torch.full((t5_features.shape[0], 1, 1), cfg_dropout_prob, device=latent.device)).to(torch.bool)
432
+ # t5_features = torch.where(dropout_mask, null_embed, t5_features)
433
+ t5_features = torch.where(dropout_mask, self.empty_t5_feat, t5_features)
434
+ if metaclip_global_text_features is not None:
435
+ null_embed = torch.zeros_like(metaclip_global_text_features,device=latent.device)
436
+ dropout_mask = torch.bernoulli(torch.full((metaclip_global_text_features.shape[0], 1), cfg_dropout_prob, device=latent.device)).to(torch.bool)
437
+ metaclip_global_text_features = torch.where(dropout_mask, null_embed, metaclip_global_text_features)
438
+ # null_embed = torch.zeros_like(clip_f_c,device=latent.device)
439
+ # dropout_mask = torch.bernoulli(torch.full((clip_f_c.shape[0], 1), cfg_dropout_prob, device=latent.device)).to(torch.bool)
440
+ # clip_f_c = torch.where(dropout_mask, null_embed, clip_f_c)
441
+ # null_embed = torch.zeros_like(text_f_c,device=latent.device)
442
+ # dropout_mask = torch.bernoulli(torch.full((text_f_c.shape[0], 1), cfg_dropout_prob, device=latent.device)).to(torch.bool)
443
+ # text_f_c = torch.where(dropout_mask, null_embed, text_f_c)
444
+
445
+ if cfg_scale != 1.0:
446
+ # empty_conditions = self.get_empty_conditions(latent.shape[0])
447
+ # breakpoint()
448
+ bsz = latent.shape[0]
449
+ latent = torch.cat([latent,latent], dim=0)
450
+ if inpaint_masked_input is not None:
451
+ inpaint_masked_input = inpaint_masked_input.transpose(1,2)
452
+ empty_inpaint_masked_input = torch.zeros_like(inpaint_masked_input, device=latent.device)
453
+ # inpaint_masked_input = torch.cat([inpaint_masked_input,self.get_empty_audio_sequence(bsz)], dim=0)
454
+ inpaint_masked_input = torch.cat([inpaint_masked_input,empty_inpaint_masked_input], dim=0)
455
+ t = torch.cat([t, t], dim=0)
456
+ # empty_clip_f = torch.zeros_like(clip_f, device=latent.device)
457
+ # empty_sync_f = torch.zeros_like(sync_f, device=latent.device)
458
+ # empty_text_f = torch.zeros_like(text_f, device=latent.device)
459
+
460
+ # clip_f = torch.cat([clip_f,empty_clip_f], dim=0)
461
+ # sync_f = torch.cat([sync_f,empty_sync_f], dim=0)
462
+ # text_f = torch.cat([text_f,empty_text_f], dim=0)
463
+ clip_f = torch.cat([clip_f,self.get_empty_clip_sequence(bsz)], dim=0)
464
+ # sync_f = torch.cat([sync_f,sync_f], dim=0)
465
+ sync_f = torch.cat([sync_f,self.get_empty_sync_sequence(bsz)], dim=0)
466
+ text_f = torch.cat([text_f,self.get_empty_string_sequence(bsz)], dim=0)
467
+ if t5_features is not None:
468
+ empty_t5_features = torch.zeros_like(t5_features, device=latent.device)
469
+ # t5_features = torch.cat([t5_features,empty_t5_features], dim=0)
470
+ t5_features = torch.cat([t5_features,self.get_empty_t5_sequence(bsz)], dim=0)
471
+ if metaclip_global_text_features is not None:
472
+ empty_metaclip_global_text_features = torch.zeros_like(metaclip_global_text_features, device=latent.device)
473
+ metaclip_global_text_features = torch.cat([metaclip_global_text_features,empty_metaclip_global_text_features], dim=0)
474
+ # metaclip_global_text_features = torch.cat([metaclip_global_text_features,metaclip_global_text_features], dim=0)
475
+ # clip_f_c = torch.cat([clip_f_c,empty_clip_f_c], dim=0)
476
+ # text_f_c = torch.cat([text_f_c,empty_text_f_c], dim=0)
477
+
478
+
479
+ conditions = self.preprocess_conditions(clip_f, sync_f, text_f, t5_features, metaclip_global_text_features)
480
+ flow = self.predict_flow(latent, t, conditions, inpaint_masked_input, cfg_scale,cfg_dropout_prob,scale_phi)
481
+ if cfg_scale != 1.0:
482
+ cond_output, uncond_output = torch.chunk(flow, 2, dim=0)
483
+ cfg_output = uncond_output + (cond_output - uncond_output) * cfg_scale
484
+ if scale_phi != 0.0:
485
+ cond_out_std = cond_output.std(dim=1, keepdim=True)
486
+ out_cfg_std = cfg_output.std(dim=1, keepdim=True)
487
+ flow = scale_phi * (cfg_output * (cond_out_std/out_cfg_std)) + (1-scale_phi) * cfg_output
488
+ else:
489
+ flow = cfg_output
490
+ flow = flow.permute(0, 2, 1)
491
+ return flow
492
+
493
+ def get_empty_string_sequence(self, bs: int) -> torch.Tensor:
494
+ return self.empty_string_feat.unsqueeze(0).expand(bs, -1, -1)
495
+
496
+ def get_empty_t5_sequence(self, bs: int) -> torch.Tensor:
497
+ return self.empty_t5_feat.unsqueeze(0).expand(bs, -1, -1)
498
+
499
+ def get_empty_audio_sequence(self, bs: int) -> torch.Tensor:
500
+ return self.empty_audio_feat.unsqueeze(0).expand(bs, self._latent_seq_len, -1)
501
+
502
+ def get_empty_clip_sequence(self, bs: int) -> torch.Tensor:
503
+ return self.empty_clip_feat.unsqueeze(0).expand(bs, self._clip_seq_len, -1)
504
+
505
+ def get_empty_sync_sequence(self, bs: int) -> torch.Tensor:
506
+ return self.empty_sync_feat.unsqueeze(0).expand(bs, self._sync_seq_len, -1)
507
+
508
+ def get_empty_conditions(
509
+ self,
510
+ bs: int,
511
+ *,
512
+ negative_text_features: Optional[torch.Tensor] = None) -> PreprocessedConditions:
513
+ if negative_text_features is not None:
514
+ empty_text = negative_text_features
515
+ else:
516
+ empty_text = self.get_empty_string_sequence(1)
517
+
518
+ empty_clip = self.get_empty_clip_sequence(1)
519
+ empty_sync = self.get_empty_sync_sequence(1)
520
+ conditions = self.preprocess_conditions(empty_clip, empty_sync, empty_text)
521
+ conditions.clip_f = conditions.clip_f.expand(bs, -1, -1)
522
+ conditions.sync_f = conditions.sync_f.expand(bs, -1, -1)
523
+ conditions.clip_f_c = conditions.clip_f_c.expand(bs, -1)
524
+ if negative_text_features is None:
525
+ conditions.text_f = conditions.text_f.expand(bs, -1, -1)
526
+ conditions.text_f_c = conditions.text_f_c.expand(bs, -1)
527
+
528
+ return conditions
529
+
530
+ def load_weights(self, src_dict) -> None:
531
+ if 't_embed.freqs' in src_dict:
532
+ del src_dict['t_embed.freqs']
533
+ if 'latent_rot' in src_dict:
534
+ del src_dict['latent_rot']
535
+ if 'clip_rot' in src_dict:
536
+ del src_dict['clip_rot']
537
+
538
+ self.load_state_dict(src_dict, strict=True)
539
+
540
+ @property
541
+ def device(self) -> torch.device:
542
+ return self.empty_clip_feat.device
543
+
544
+ @property
545
+ def latent_seq_len(self) -> int:
546
+ return self._latent_seq_len
547
+
548
+ @property
549
+ def clip_seq_len(self) -> int:
550
+ return self._clip_seq_len
551
+
552
+ @property
553
+ def sync_seq_len(self) -> int:
554
+ return self._sync_seq_len
555
+
ThinkSound/models/mmmodules/__init__.py ADDED
File without changes
ThinkSound/models/mmmodules/ext/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
ThinkSound/models/mmmodules/ext/rotary_embeddings.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ import torch
4
+ from einops import rearrange
5
+ from torch import Tensor
6
+
7
+ # Ref: https://github.com/black-forest-labs/flux/blob/main/src/flux/math.py
8
+ # Ref: https://github.com/lucidrains/rotary-embedding-torch
9
+
10
+
11
+ def compute_rope_rotations(length: int,
12
+ dim: int,
13
+ theta: int,
14
+ *,
15
+ freq_scaling: float = 1.0,
16
+ device: Union[torch.device, str] = 'cpu') -> Tensor:
17
+ assert dim % 2 == 0
18
+
19
+ with torch.amp.autocast(device_type='cuda', enabled=False):
20
+ pos = torch.arange(length, dtype=torch.float32, device=device)
21
+ freqs = 1.0 / (theta**(torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
22
+ freqs *= freq_scaling
23
+
24
+ rot = torch.einsum('..., f -> ... f', pos, freqs)
25
+ rot = torch.stack([torch.cos(rot), -torch.sin(rot), torch.sin(rot), torch.cos(rot)], dim=-1)
26
+ rot = rearrange(rot, 'n d (i j) -> 1 n d i j', i=2, j=2)
27
+ return rot
28
+
29
+
30
+ def apply_rope(x: Tensor, rot: Tensor) -> tuple[Tensor, Tensor]:
31
+ with torch.amp.autocast(device_type='cuda', enabled=False):
32
+ _x = x.float()
33
+ _x = _x.view(*_x.shape[:-1], -1, 1, 2)
34
+ x_out = rot[..., 0] * _x[..., 0] + rot[..., 1] * _x[..., 1]
35
+ return x_out.reshape(*x.shape).to(dtype=x.dtype)
ThinkSound/models/mmmodules/ext/stft_converter.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reference: # https://github.com/bytedance/Make-An-Audio-2
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torchaudio
6
+ from einops import rearrange
7
+ from librosa.filters import mel as librosa_mel_fn
8
+
9
+
10
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5, norm_fn=torch.log10):
11
+ return norm_fn(torch.clamp(x, min=clip_val) * C)
12
+
13
+
14
+ def spectral_normalize_torch(magnitudes, norm_fn):
15
+ output = dynamic_range_compression_torch(magnitudes, norm_fn=norm_fn)
16
+ return output
17
+
18
+
19
+ class STFTConverter(nn.Module):
20
+
21
+ def __init__(
22
+ self,
23
+ *,
24
+ sampling_rate: float = 16_000,
25
+ n_fft: int = 1024,
26
+ num_mels: int = 128,
27
+ hop_size: int = 256,
28
+ win_size: int = 1024,
29
+ fmin: float = 0,
30
+ fmax: float = 8_000,
31
+ norm_fn=torch.log,
32
+ ):
33
+ super().__init__()
34
+ self.sampling_rate = sampling_rate
35
+ self.n_fft = n_fft
36
+ self.num_mels = num_mels
37
+ self.hop_size = hop_size
38
+ self.win_size = win_size
39
+ self.fmin = fmin
40
+ self.fmax = fmax
41
+ self.norm_fn = norm_fn
42
+
43
+ mel = librosa_mel_fn(sr=self.sampling_rate,
44
+ n_fft=self.n_fft,
45
+ n_mels=self.num_mels,
46
+ fmin=self.fmin,
47
+ fmax=self.fmax)
48
+ mel_basis = torch.from_numpy(mel).float()
49
+ hann_window = torch.hann_window(self.win_size)
50
+
51
+ self.register_buffer('mel_basis', mel_basis)
52
+ self.register_buffer('hann_window', hann_window)
53
+
54
+ @property
55
+ def device(self):
56
+ return self.hann_window.device
57
+
58
+ def forward(self, waveform: torch.Tensor) -> torch.Tensor:
59
+ # input: batch_size * length
60
+ bs = waveform.shape[0]
61
+ waveform = waveform.clamp(min=-1., max=1.)
62
+
63
+ spec = torch.stft(waveform,
64
+ self.n_fft,
65
+ hop_length=self.hop_size,
66
+ win_length=self.win_size,
67
+ window=self.hann_window,
68
+ center=True,
69
+ pad_mode='reflect',
70
+ normalized=False,
71
+ onesided=True,
72
+ return_complex=True)
73
+
74
+ spec = torch.view_as_real(spec)
75
+ # print('After stft', spec.shape, spec.min(), spec.max(), spec.mean())
76
+
77
+ power = spec.pow(2).sum(-1)
78
+ angle = torch.atan2(spec[..., 1], spec[..., 0])
79
+
80
+ print('power', power.shape, power.min(), power.max(), power.mean())
81
+ print('angle', angle.shape, angle.min(), angle.max(), angle.mean())
82
+
83
+ # print('mel', self.mel_basis.shape, self.mel_basis.min(), self.mel_basis.max(),
84
+ # self.mel_basis.mean())
85
+
86
+ # spec = rearrange(spec, 'b f t c -> (b c) f t')
87
+
88
+ # spec = self.mel_transform(spec)
89
+
90
+ # spec = torch.matmul(self.mel_basis, spec)
91
+
92
+ # print('After mel', spec.shape, spec.min(), spec.max(), spec.mean())
93
+
94
+ # spec = spectral_normalize_torch(spec, self.norm_fn)
95
+
96
+ # print('After norm', spec.shape, spec.min(), spec.max(), spec.mean())
97
+
98
+ # compute magnitude
99
+ # magnitude = torch.sqrt((spec**2).sum(-1))
100
+ # normalize by magnitude
101
+ # scaled_magnitude = torch.log10(magnitude.clamp(min=1e-5)) * 10
102
+ # spec = spec / magnitude.unsqueeze(-1) * scaled_magnitude.unsqueeze(-1)
103
+
104
+ # power = torch.log10(power.clamp(min=1e-5)) * 10
105
+ power = torch.log10(power.clamp(min=1e-5))
106
+
107
+ print('After scaling', power.shape, power.min(), power.max(), power.mean())
108
+
109
+ spec = torch.stack([power, angle], dim=-1)
110
+
111
+ # spec = rearrange(spec, '(b c) f t -> b c f t', b=bs)
112
+ spec = rearrange(spec, 'b f t c -> b c f t', b=bs)
113
+
114
+ # spec[:, :, 400:] = 0
115
+
116
+ return spec
117
+
118
+ def invert(self, spec: torch.Tensor, length: int) -> torch.Tensor:
119
+ bs = spec.shape[0]
120
+
121
+ # spec = rearrange(spec, 'b c f t -> (b c) f t')
122
+ # print(spec.shape, self.mel_basis.shape)
123
+ # spec = torch.linalg.lstsq(self.mel_basis.unsqueeze(0), spec).solution
124
+ # spec = torch.linalg.pinv(self.mel_basis.unsqueeze(0)) @ spec
125
+
126
+ # spec = self.invmel_transform(spec)
127
+
128
+ spec = rearrange(spec, 'b c f t -> b f t c', b=bs).contiguous()
129
+
130
+ # spec[..., 0] = 10**(spec[..., 0] / 10)
131
+
132
+ power = spec[..., 0]
133
+ power = 10**power
134
+
135
+ # print('After unscaling', spec[..., 0].shape, spec[..., 0].min(), spec[..., 0].max(),
136
+ # spec[..., 0].mean())
137
+
138
+ unit_vector = torch.stack([
139
+ torch.cos(spec[..., 1]),
140
+ torch.sin(spec[..., 1]),
141
+ ], dim=-1)
142
+
143
+ spec = torch.sqrt(power) * unit_vector
144
+
145
+ # spec = rearrange(spec, '(b c) f t -> b f t c', b=bs).contiguous()
146
+ spec = torch.view_as_complex(spec)
147
+
148
+ waveform = torch.istft(
149
+ spec,
150
+ self.n_fft,
151
+ length=length,
152
+ hop_length=self.hop_size,
153
+ win_length=self.win_size,
154
+ window=self.hann_window,
155
+ center=True,
156
+ normalized=False,
157
+ onesided=True,
158
+ return_complex=False,
159
+ )
160
+
161
+ return waveform
162
+
163
+
164
+ if __name__ == '__main__':
165
+
166
+ converter = STFTConverter(sampling_rate=16000)
167
+
168
+ signal = torchaudio.load('./output/ZZ6GRocWW38_000090.wav')[0]
169
+ # resample signal at 44100 Hz
170
+ # signal = torchaudio.transforms.Resample(16_000, 44_100)(signal)
171
+
172
+ L = signal.shape[1]
173
+ print('Input signal', signal.shape)
174
+ spec = converter(signal)
175
+
176
+ print('Final spec', spec.shape)
177
+
178
+ signal_recon = converter.invert(spec, length=L)
179
+ print('Output signal', signal_recon.shape, signal_recon.min(), signal_recon.max(),
180
+ signal_recon.mean())
181
+
182
+ print('MSE', torch.nn.functional.mse_loss(signal, signal_recon))
183
+ torchaudio.save('./output/ZZ6GRocWW38_000090_recon.wav', signal_recon, 16000)
ThinkSound/models/mmmodules/ext/stft_converter_mel.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reference: # https://github.com/bytedance/Make-An-Audio-2
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torchaudio
6
+ from einops import rearrange
7
+ from librosa.filters import mel as librosa_mel_fn
8
+
9
+
10
+ def dynamic_range_compression_torch(x, C=1, clip_val=1e-5, norm_fn=torch.log10):
11
+ return norm_fn(torch.clamp(x, min=clip_val) * C)
12
+
13
+
14
+ def spectral_normalize_torch(magnitudes, norm_fn):
15
+ output = dynamic_range_compression_torch(magnitudes, norm_fn=norm_fn)
16
+ return output
17
+
18
+
19
+ class STFTConverter(nn.Module):
20
+
21
+ def __init__(
22
+ self,
23
+ *,
24
+ sampling_rate: float = 16_000,
25
+ n_fft: int = 1024,
26
+ num_mels: int = 128,
27
+ hop_size: int = 256,
28
+ win_size: int = 1024,
29
+ fmin: float = 0,
30
+ fmax: float = 8_000,
31
+ norm_fn=torch.log,
32
+ ):
33
+ super().__init__()
34
+ self.sampling_rate = sampling_rate
35
+ self.n_fft = n_fft
36
+ self.num_mels = num_mels
37
+ self.hop_size = hop_size
38
+ self.win_size = win_size
39
+ self.fmin = fmin
40
+ self.fmax = fmax
41
+ self.norm_fn = norm_fn
42
+
43
+ mel = librosa_mel_fn(sr=self.sampling_rate,
44
+ n_fft=self.n_fft,
45
+ n_mels=self.num_mels,
46
+ fmin=self.fmin,
47
+ fmax=self.fmax)
48
+ mel_basis = torch.from_numpy(mel).float()
49
+ hann_window = torch.hann_window(self.win_size)
50
+
51
+ self.register_buffer('mel_basis', mel_basis)
52
+ self.register_buffer('hann_window', hann_window)
53
+
54
+ @property
55
+ def device(self):
56
+ return self.hann_window.device
57
+
58
+ def forward(self, waveform: torch.Tensor) -> torch.Tensor:
59
+ # input: batch_size * length
60
+ bs = waveform.shape[0]
61
+ waveform = waveform.clamp(min=-1., max=1.)
62
+
63
+ spec = torch.stft(waveform,
64
+ self.n_fft,
65
+ hop_length=self.hop_size,
66
+ win_length=self.win_size,
67
+ window=self.hann_window,
68
+ center=True,
69
+ pad_mode='reflect',
70
+ normalized=False,
71
+ onesided=True,
72
+ return_complex=True)
73
+
74
+ spec = torch.view_as_real(spec)
75
+ # print('After stft', spec.shape, spec.min(), spec.max(), spec.mean())
76
+
77
+ power = (spec.pow(2).sum(-1))**(0.5)
78
+ angle = torch.atan2(spec[..., 1], spec[..., 0])
79
+
80
+ print('power 1', power.shape, power.min(), power.max(), power.mean())
81
+ print('angle 1', angle.shape, angle.min(), angle.max(), angle.mean(), angle[:, :2, :2])
82
+
83
+ # print('mel', self.mel_basis.shape, self.mel_basis.min(), self.mel_basis.max(),
84
+ # self.mel_basis.mean())
85
+
86
+ # spec = self.mel_transform(spec)
87
+
88
+ # power = torch.matmul(self.mel_basis, power)
89
+
90
+ spec = rearrange(spec, 'b f t c -> (b c) f t')
91
+ spec = self.mel_basis.unsqueeze(0) @ spec
92
+ spec = rearrange(spec, '(b c) f t -> b f t c', b=bs)
93
+
94
+ power = (spec.pow(2).sum(-1))**(0.5)
95
+ angle = torch.atan2(spec[..., 1], spec[..., 0])
96
+
97
+ print('power', power.shape, power.min(), power.max(), power.mean())
98
+ print('angle', angle.shape, angle.min(), angle.max(), angle.mean(), angle[:, :2, :2])
99
+
100
+ # print('After mel', spec.shape, spec.min(), spec.max(), spec.mean())
101
+
102
+ # spec = spectral_normalize_torch(spec, self.norm_fn)
103
+
104
+ # print('After norm', spec.shape, spec.min(), spec.max(), spec.mean())
105
+
106
+ # compute magnitude
107
+ # magnitude = torch.sqrt((spec**2).sum(-1))
108
+ # normalize by magnitude
109
+ # scaled_magnitude = torch.log10(magnitude.clamp(min=1e-5)) * 10
110
+ # spec = spec / magnitude.unsqueeze(-1) * scaled_magnitude.unsqueeze(-1)
111
+
112
+ # power = torch.log10(power.clamp(min=1e-5)) * 10
113
+ power = torch.log10(power.clamp(min=1e-8))
114
+
115
+ print('After scaling', power.shape, power.min(), power.max(), power.mean())
116
+
117
+ # spec = torch.stack([power, angle], dim=-1)
118
+
119
+ # spec = rearrange(spec, '(b c) f t -> b c f t', b=bs)
120
+ # spec = rearrange(spec, 'b f t c -> b c f t', b=bs)
121
+
122
+ # spec[:, :, 400:] = 0
123
+
124
+ return power, angle
125
+ # return spec[..., 0], spec[..., 1]
126
+
127
+ def invert(self, spec: torch.Tensor, length: int) -> torch.Tensor:
128
+
129
+ power, angle = spec
130
+
131
+ bs = power.shape[0]
132
+
133
+ # spec = rearrange(spec, 'b c f t -> (b c) f t')
134
+ # print(spec.shape, self.mel_basis.shape)
135
+ # spec = torch.linalg.lstsq(self.mel_basis.unsqueeze(0), spec).solution
136
+ # spec = torch.linalg.pinv(self.mel_basis.unsqueeze(0)) @ spec
137
+
138
+ # spec = self.invmel_transform(spec)
139
+
140
+ # spec = rearrange(spec, 'b c f t -> b f t c', b=bs).contiguous()
141
+
142
+ # spec[..., 0] = 10**(spec[..., 0] / 10)
143
+
144
+ # power = spec[..., 0]
145
+ power = 10**power
146
+
147
+ # print('After unscaling', spec[..., 0].shape, spec[..., 0].min(), spec[..., 0].max(),
148
+ # spec[..., 0].mean())
149
+
150
+ unit_vector = torch.stack([
151
+ torch.cos(angle),
152
+ torch.sin(angle),
153
+ ], dim=-1)
154
+
155
+ spec = power.unsqueeze(-1) * unit_vector
156
+
157
+ # power = torch.linalg.lstsq(self.mel_basis.unsqueeze(0), power).solution
158
+ spec = rearrange(spec, 'b f t c -> (b c) f t')
159
+ spec = torch.linalg.pinv(self.mel_basis.unsqueeze(0)) @ spec
160
+ # spec = torch.linalg.lstsq(self.mel_basis.unsqueeze(0), spec).solution
161
+ spec = rearrange(spec, '(b c) f t -> b f t c', b=bs).contiguous()
162
+
163
+ power = (spec.pow(2).sum(-1))**(0.5)
164
+ angle = torch.atan2(spec[..., 1], spec[..., 0])
165
+
166
+ print('power 2', power.shape, power.min(), power.max(), power.mean())
167
+ print('angle 2', angle.shape, angle.min(), angle.max(), angle.mean(), angle[:, :2, :2])
168
+
169
+ # spec = rearrange(spec, '(b c) f t -> b f t c', b=bs).contiguous()
170
+ spec = torch.view_as_complex(spec)
171
+
172
+ waveform = torch.istft(
173
+ spec,
174
+ self.n_fft,
175
+ length=length,
176
+ hop_length=self.hop_size,
177
+ win_length=self.win_size,
178
+ window=self.hann_window,
179
+ center=True,
180
+ normalized=False,
181
+ onesided=True,
182
+ return_complex=False,
183
+ )
184
+
185
+ return waveform
186
+
187
+
188
+ if __name__ == '__main__':
189
+
190
+ converter = STFTConverter(sampling_rate=16000)
191
+
192
+ signal = torchaudio.load('./output/ZZ6GRocWW38_000090.wav')[0]
193
+ # resample signal at 44100 Hz
194
+ # signal = torchaudio.transforms.Resample(16_000, 44_100)(signal)
195
+
196
+ L = signal.shape[1]
197
+ print('Input signal', signal.shape)
198
+ spec = converter(signal)
199
+
200
+ power, angle = spec
201
+
202
+ # print(power.shape, angle.shape)
203
+ # print(power, power.min(), power.max(), power.mean())
204
+ # power = power.clamp(-1, 1)
205
+ # angle = angle.clamp(-1, 1)
206
+
207
+ import matplotlib.pyplot as plt
208
+
209
+ # Visualize power
210
+ plt.figure()
211
+ plt.imshow(power[0].detach().numpy(), aspect='auto', origin='lower')
212
+ plt.colorbar()
213
+ plt.title('Power')
214
+ plt.xlabel('Time')
215
+ plt.ylabel('Frequency')
216
+ plt.savefig('./output/power.png')
217
+
218
+ # Visualize angle
219
+ plt.figure()
220
+ plt.imshow(angle[0].detach().numpy(), aspect='auto', origin='lower')
221
+ plt.colorbar()
222
+ plt.title('Angle')
223
+ plt.xlabel('Time')
224
+ plt.ylabel('Frequency')
225
+ plt.savefig('./output/angle.png')
226
+
227
+ # print('Final spec', spec.shape)
228
+
229
+ signal_recon = converter.invert(spec, length=L)
230
+ print('Output signal', signal_recon.shape, signal_recon.min(), signal_recon.max(),
231
+ signal_recon.mean())
232
+
233
+ print('MSE', torch.nn.functional.mse_loss(signal, signal_recon))
234
+ torchaudio.save('./output/ZZ6GRocWW38_000090_recon.wav', signal_recon, 16000)