├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── .python-version ├── LICENSE ├── README.md ├── app.py ├── cli.py ├── dia ├── __init__.py ├── audio.py ├── config.py ├── layers.py ├── model.py ├── state.py └── static │ └── images │ └── banner.png ├── docker ├── Dockerfile.cpu └── Dockerfile.gpu ├── example ├── simple.py └── voice_clone.py ├── example_prompt.mp3 ├── pyproject.toml └── uv.lock /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: Continuous Integration 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | lint_and_format: 10 | runs-on: ubuntu-latest 11 | name: Lint and Format 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: astral-sh/ruff-action@v3 15 | with: 16 | version: latest 17 | 18 | - name: Check Lint using Ruff 19 | run: ruff check 20 | 21 | - name: Check Format using Ruff 22 | run: ruff format --check --diff 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Python-generated files 2 | __pycache__/ 3 | *.py[oc] 4 | build/ 5 | dist/ 6 | wheels/ 7 | *.egg-info 8 | 9 | # Virtual environments 10 | .venv 11 | 12 | .gradio 13 | 14 | **/*.pth 15 | **/*.mp3 16 | !example_prompt.mp3 17 | **/*.txt 18 | 19 | .ruff_cache 20 | .ipynb_checkpoints 21 | config.json -------------------------------------------------------------------------------- /.python-version: -------------------------------------------------------------------------------- 1 | 3.10 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2025 Nari Labs 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | 4 | 5 |

6 |

7 | Static Badge 8 | 9 | LICENSE 10 |

11 |

12 | Dataset on HuggingFace 13 | Space on HuggingFace 14 |

15 | 16 | Dia is a 1.6B parameter text to speech model created by Nari Labs. 17 | 18 | Dia **directly generates highly realistic dialogue from a transcript**. You can condition the output on audio, enabling emotion and tone control. The model can also produce nonverbal communications like laughter, coughing, clearing throat, etc. 19 | 20 | To accelerate research, we are providing access to pretrained model checkpoints and inference code. The model weights are hosted on [Hugging Face](https://huggingface.co/nari-labs/Dia-1.6B). The model only supports English generation at the moment. 21 | 22 | We also provide a [demo page](https://yummy-fir-7a4.notion.site/dia) comparing our model to [ElevenLabs Studio](https://elevenlabs.io/studio) and [Sesame CSM-1B](https://github.com/SesameAILabs/csm). 23 | 24 | - (Update) We have a ZeroGPU Space running! Try it now [here](https://huggingface.co/spaces/nari-labs/Dia-1.6B). Thanks to the HF team for the support :) 25 | - Join our [discord server](https://discord.gg/pgdB5YRe) for community support and access to new features. 26 | - Play with a larger version of Dia: generate fun conversations, remix content, and share with friends. 🔮 Join the [waitlist](https://tally.so/r/meokbo) for early access. 27 | 28 | ## ⚡️ Quickstart 29 | 30 | ### Install via pip 31 | 32 | ```bash 33 | # Install directly from GitHub 34 | pip install git+https://github.com/nari-labs/dia.git 35 | ``` 36 | 37 | ### Run the Gradio UI 38 | 39 | This will open a Gradio UI that you can work on. 40 | 41 | ```bash 42 | git clone https://github.com/nari-labs/dia.git 43 | cd dia && uv run app.py 44 | ``` 45 | 46 | or if you do not have `uv` pre-installed: 47 | 48 | ```bash 49 | git clone https://github.com/nari-labs/dia.git 50 | cd dia 51 | python -m venv .venv 52 | source .venv/bin/activate 53 | pip install -e . 54 | python app.py 55 | ``` 56 | 57 | Note that the model was not fine-tuned on a specific voice. Hence, you will get different voices every time you run the model. 58 | You can keep speaker consistency by either adding an audio prompt (a guide coming VERY soon - try it with the second example on Gradio for now), or fixing the seed. 59 | 60 | ## Features 61 | 62 | - Generate dialogue via `[S1]` and `[S2]` tag 63 | - Generate non-verbal like `(laughs)`, `(coughs)`, etc. 64 | - Below verbal tags will be recognized, but might result in unexpected output. 65 | - `(laughs), (clears throat), (sighs), (gasps), (coughs), (singing), (sings), (mumbles), (beep), (groans), (sniffs), (claps), (screams), (inhales), (exhales), (applause), (burps), (humming), (sneezes), (chuckle), (whistles)` 66 | - Voice cloning. See [`example/voice_clone.py`](example/voice_clone.py) for more information. 67 | - In the Hugging Face space, you can upload the audio you want to clone and place its transcript before your script. Make sure the transcript follows the required format. The model will then output only the content of your script. 68 | 69 | ## ⚙️ Usage 70 | 71 | ### As a Python Library 72 | 73 | ```python 74 | import soundfile as sf 75 | 76 | from dia.model import Dia 77 | 78 | 79 | model = Dia.from_pretrained("nari-labs/Dia-1.6B") 80 | 81 | text = "[S1] Dia is an open weights text to dialogue model. [S2] You get full control over scripts and voices. [S1] Wow. Amazing. (laughs) [S2] Try it now on Git hub or Hugging Face." 82 | 83 | output = model.generate(text) 84 | 85 | sf.write("simple.mp3", output, 44100) 86 | ``` 87 | 88 | A pypi package and a working CLI tool will be available soon. 89 | 90 | ## 💻 Hardware and Inference Speed 91 | 92 | Dia has been tested on only GPUs (pytorch 2.0+, CUDA 12.6). CPU support is to be added soon. 93 | The initial run will take longer as the Descript Audio Codec also needs to be downloaded. 94 | 95 | On enterprise GPUs, Dia can generate audio in real-time. On older GPUs, inference time will be slower. 96 | For reference, on a A4000 GPU, Dia roughly generates 40 tokens/s (86 tokens equals 1 second of audio). 97 | `torch.compile` will increase speeds for supported GPUs. 98 | 99 | The full version of Dia requires around 12-13GB of VRAM to run. We will be adding a quantized version in the future. 100 | 101 | If you don't have hardware available or if you want to play with bigger versions of our models, join the waitlist [here](https://tally.so/r/meokbo). 102 | 103 | ## 🪪 License 104 | 105 | This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details. 106 | 107 | ## ⚠️ Disclaimer 108 | 109 | This project offers a high-fidelity speech generation model intended for research and educational use. The following uses are **strictly forbidden**: 110 | 111 | - **Identity Misuse**: Do not produce audio resembling real individuals without permission. 112 | - **Deceptive Content**: Do not use this model to generate misleading content (e.g. fake news) 113 | - **Illegal or Malicious Use**: Do not use this model for activities that are illegal or intended to cause harm. 114 | 115 | By using this model, you agree to uphold relevant legal standards and ethical responsibilities. We **are not responsible** for any misuse and firmly oppose any unethical usage of this technology. 116 | 117 | ## 🔭 TODO / Future Work 118 | 119 | - Docker support for ARM architecture and MacOS. 120 | - Optimize inference speed. 121 | - Add quantization for memory efficiency. 122 | 123 | ## 🤝 Contributing 124 | 125 | We are a tiny team of 1 full-time and 1 part-time research-engineers. We are extra-welcome to any contributions! 126 | Join our [Discord Server](https://discord.gg/pgdB5YRe) for discussions. 127 | 128 | ## 🤗 Acknowledgements 129 | 130 | - We thank the [Google TPU Research Cloud program](https://sites.research.google/trc/about/) for providing computation resources. 131 | - Our work was heavily inspired by [SoundStorm](https://arxiv.org/abs/2305.09636), [Parakeet](https://jordandarefsky.com/blog/2024/parakeet/), and [Descript Audio Codec](https://github.com/descriptinc/descript-audio-codec). 132 | - Hugging Face for providing the ZeroGPU Grant. 133 | - "Nari" is a pure Korean word for lily. 134 | - We thank Jason Y. for providing help with data filtering. 135 | 136 | 137 | ## ⭐ Star History 138 | 139 | 140 | 141 | 142 | 143 | Star History Chart 144 | 145 | 146 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import tempfile 3 | import time 4 | from pathlib import Path 5 | from typing import Optional, Tuple 6 | 7 | import gradio as gr 8 | import numpy as np 9 | import soundfile as sf 10 | import torch 11 | 12 | from dia.model import Dia 13 | 14 | 15 | # --- Global Setup --- 16 | parser = argparse.ArgumentParser(description="Gradio interface for Nari TTS") 17 | parser.add_argument("--device", type=str, default=None, help="Force device (e.g., 'cuda', 'mps', 'cpu')") 18 | parser.add_argument("--share", action="store_true", help="Enable Gradio sharing") 19 | 20 | args = parser.parse_args() 21 | 22 | 23 | # Determine device 24 | if args.device: 25 | device = torch.device(args.device) 26 | elif torch.cuda.is_available(): 27 | device = torch.device("cuda") 28 | # Simplified MPS check for broader compatibility 29 | elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): 30 | # Basic check is usually sufficient, detailed check can be problematic 31 | device = torch.device("mps") 32 | else: 33 | device = torch.device("cpu") 34 | 35 | print(f"Using device: {device}") 36 | 37 | # Load Nari model and config 38 | print("Loading Nari model...") 39 | try: 40 | # Use the function from inference.py 41 | model = Dia.from_pretrained("nari-labs/Dia-1.6B", device=device) 42 | except Exception as e: 43 | print(f"Error loading Nari model: {e}") 44 | raise 45 | 46 | 47 | def run_inference( 48 | text_input: str, 49 | audio_prompt_input: Optional[Tuple[int, np.ndarray]], 50 | max_new_tokens: int, 51 | cfg_scale: float, 52 | temperature: float, 53 | top_p: float, 54 | cfg_filter_top_k: int, 55 | speed_factor: float, 56 | ): 57 | """ 58 | Runs Nari inference using the globally loaded model and provided inputs. 59 | Uses temporary files for text and audio prompt compatibility with inference.generate. 60 | """ 61 | global model, device # Access global model, config, device 62 | 63 | if not text_input or text_input.isspace(): 64 | raise gr.Error("Text input cannot be empty.") 65 | 66 | temp_txt_file_path = None 67 | temp_audio_prompt_path = None 68 | output_audio = (44100, np.zeros(1, dtype=np.float32)) 69 | 70 | try: 71 | prompt_path_for_generate = None 72 | if audio_prompt_input is not None: 73 | sr, audio_data = audio_prompt_input 74 | # Check if audio_data is valid 75 | if audio_data is None or audio_data.size == 0 or audio_data.max() == 0: # Check for silence/empty 76 | gr.Warning("Audio prompt seems empty or silent, ignoring prompt.") 77 | else: 78 | # Save prompt audio to a temporary WAV file 79 | with tempfile.NamedTemporaryFile(mode="wb", suffix=".wav", delete=False) as f_audio: 80 | temp_audio_prompt_path = f_audio.name # Store path for cleanup 81 | 82 | # Basic audio preprocessing for consistency 83 | # Convert to float32 in [-1, 1] range if integer type 84 | if np.issubdtype(audio_data.dtype, np.integer): 85 | max_val = np.iinfo(audio_data.dtype).max 86 | audio_data = audio_data.astype(np.float32) / max_val 87 | elif not np.issubdtype(audio_data.dtype, np.floating): 88 | gr.Warning(f"Unsupported audio prompt dtype {audio_data.dtype}, attempting conversion.") 89 | # Attempt conversion, might fail for complex types 90 | try: 91 | audio_data = audio_data.astype(np.float32) 92 | except Exception as conv_e: 93 | raise gr.Error(f"Failed to convert audio prompt to float32: {conv_e}") 94 | 95 | # Ensure mono (average channels if stereo) 96 | if audio_data.ndim > 1: 97 | if audio_data.shape[0] == 2: # Assume (2, N) 98 | audio_data = np.mean(audio_data, axis=0) 99 | elif audio_data.shape[1] == 2: # Assume (N, 2) 100 | audio_data = np.mean(audio_data, axis=1) 101 | else: 102 | gr.Warning( 103 | f"Audio prompt has unexpected shape {audio_data.shape}, taking first channel/axis." 104 | ) 105 | audio_data = ( 106 | audio_data[0] if audio_data.shape[0] < audio_data.shape[1] else audio_data[:, 0] 107 | ) 108 | audio_data = np.ascontiguousarray(audio_data) # Ensure contiguous after slicing/mean 109 | 110 | # Write using soundfile 111 | try: 112 | sf.write( 113 | temp_audio_prompt_path, audio_data, sr, subtype="FLOAT" 114 | ) # Explicitly use FLOAT subtype 115 | prompt_path_for_generate = temp_audio_prompt_path 116 | print(f"Created temporary audio prompt file: {temp_audio_prompt_path} (orig sr: {sr})") 117 | except Exception as write_e: 118 | print(f"Error writing temporary audio file: {write_e}") 119 | raise gr.Error(f"Failed to save audio prompt: {write_e}") 120 | 121 | # 3. Run Generation 122 | 123 | start_time = time.time() 124 | 125 | # Use torch.inference_mode() context manager for the generation call 126 | with torch.inference_mode(): 127 | output_audio_np = model.generate( 128 | text_input, 129 | max_tokens=max_new_tokens, 130 | cfg_scale=cfg_scale, 131 | temperature=temperature, 132 | top_p=top_p, 133 | cfg_filter_top_k=cfg_filter_top_k, # Pass the value here 134 | use_torch_compile=False, # Keep False for Gradio stability 135 | audio_prompt=prompt_path_for_generate, 136 | ) 137 | 138 | end_time = time.time() 139 | print(f"Generation finished in {end_time - start_time:.2f} seconds.") 140 | 141 | # 4. Convert Codes to Audio 142 | if output_audio_np is not None: 143 | # Get sample rate from the loaded DAC model 144 | output_sr = 44100 145 | 146 | # --- Slow down audio --- 147 | original_len = len(output_audio_np) 148 | # Ensure speed_factor is positive and not excessively small/large to avoid issues 149 | speed_factor = max(0.1, min(speed_factor, 5.0)) 150 | target_len = int(original_len / speed_factor) # Target length based on speed_factor 151 | if target_len != original_len and target_len > 0: # Only interpolate if length changes and is valid 152 | x_original = np.arange(original_len) 153 | x_resampled = np.linspace(0, original_len - 1, target_len) 154 | resampled_audio_np = np.interp(x_resampled, x_original, output_audio_np) 155 | output_audio = ( 156 | output_sr, 157 | resampled_audio_np.astype(np.float32), 158 | ) # Use resampled audio 159 | print(f"Resampled audio from {original_len} to {target_len} samples for {speed_factor:.2f}x speed.") 160 | else: 161 | output_audio = ( 162 | output_sr, 163 | output_audio_np, 164 | ) # Keep original if calculation fails or no change 165 | print(f"Skipping audio speed adjustment (factor: {speed_factor:.2f}).") 166 | # --- End slowdown --- 167 | 168 | print(f"Audio conversion successful. Final shape: {output_audio[1].shape}, Sample Rate: {output_sr}") 169 | 170 | # Explicitly convert to int16 to prevent Gradio warning 171 | if output_audio[1].dtype == np.float32 or output_audio[1].dtype == np.float64: 172 | audio_for_gradio = np.clip(output_audio[1], -1.0, 1.0) 173 | audio_for_gradio = (audio_for_gradio * 32767).astype(np.int16) 174 | output_audio = (output_sr, audio_for_gradio) 175 | print("Converted audio to int16 for Gradio output.") 176 | 177 | else: 178 | print("\nGeneration finished, but no valid tokens were produced.") 179 | # Return default silence 180 | gr.Warning("Generation produced no output.") 181 | 182 | except Exception as e: 183 | print(f"Error during inference: {e}") 184 | import traceback 185 | 186 | traceback.print_exc() 187 | # Re-raise as Gradio error to display nicely in the UI 188 | raise gr.Error(f"Inference failed: {e}") 189 | 190 | finally: 191 | # 5. Cleanup Temporary Files defensively 192 | if temp_txt_file_path and Path(temp_txt_file_path).exists(): 193 | try: 194 | Path(temp_txt_file_path).unlink() 195 | print(f"Deleted temporary text file: {temp_txt_file_path}") 196 | except OSError as e: 197 | print(f"Warning: Error deleting temporary text file {temp_txt_file_path}: {e}") 198 | if temp_audio_prompt_path and Path(temp_audio_prompt_path).exists(): 199 | try: 200 | Path(temp_audio_prompt_path).unlink() 201 | print(f"Deleted temporary audio prompt file: {temp_audio_prompt_path}") 202 | except OSError as e: 203 | print(f"Warning: Error deleting temporary audio prompt file {temp_audio_prompt_path}: {e}") 204 | 205 | return output_audio 206 | 207 | 208 | # --- Create Gradio Interface --- 209 | css = """ 210 | #col-container {max-width: 90%; margin-left: auto; margin-right: auto;} 211 | """ 212 | # Attempt to load default text from example.txt 213 | default_text = "[S1] Dia is an open weights text to dialogue model. \n[S2] You get full control over scripts and voices. \n[S1] Wow. Amazing. (laughs) \n[S2] Try it now on Git hub or Hugging Face." 214 | example_txt_path = Path("./example.txt") 215 | if example_txt_path.exists(): 216 | try: 217 | default_text = example_txt_path.read_text(encoding="utf-8").strip() 218 | if not default_text: # Handle empty example file 219 | default_text = "Example text file was empty." 220 | except Exception as e: 221 | print(f"Warning: Could not read example.txt: {e}") 222 | 223 | 224 | # Build Gradio UI 225 | with gr.Blocks(css=css) as demo: 226 | gr.Markdown("# Nari Text-to-Speech Synthesis") 227 | 228 | with gr.Row(equal_height=False): 229 | with gr.Column(scale=1): 230 | text_input = gr.Textbox( 231 | label="Input Text", 232 | placeholder="Enter text here...", 233 | value=default_text, 234 | lines=5, # Increased lines 235 | ) 236 | audio_prompt_input = gr.Audio( 237 | label="Audio Prompt (Optional)", 238 | show_label=True, 239 | sources=["upload", "microphone"], 240 | type="numpy", 241 | ) 242 | with gr.Accordion("Generation Parameters", open=False): 243 | max_new_tokens = gr.Slider( 244 | label="Max New Tokens (Audio Length)", 245 | minimum=860, 246 | maximum=3072, 247 | value=model.config.data.audio_length, # Use config default if available, else fallback 248 | step=50, 249 | info="Controls the maximum length of the generated audio (more tokens = longer audio).", 250 | ) 251 | cfg_scale = gr.Slider( 252 | label="CFG Scale (Guidance Strength)", 253 | minimum=1.0, 254 | maximum=5.0, 255 | value=3.0, # Default from inference.py 256 | step=0.1, 257 | info="Higher values increase adherence to the text prompt.", 258 | ) 259 | temperature = gr.Slider( 260 | label="Temperature (Randomness)", 261 | minimum=1.0, 262 | maximum=1.5, 263 | value=1.3, # Default from inference.py 264 | step=0.05, 265 | info="Lower values make the output more deterministic, higher values increase randomness.", 266 | ) 267 | top_p = gr.Slider( 268 | label="Top P (Nucleus Sampling)", 269 | minimum=0.80, 270 | maximum=1.0, 271 | value=0.95, # Default from inference.py 272 | step=0.01, 273 | info="Filters vocabulary to the most likely tokens cumulatively reaching probability P.", 274 | ) 275 | cfg_filter_top_k = gr.Slider( 276 | label="CFG Filter Top K", 277 | minimum=15, 278 | maximum=50, 279 | value=30, 280 | step=1, 281 | info="Top k filter for CFG guidance.", 282 | ) 283 | speed_factor_slider = gr.Slider( 284 | label="Speed Factor", 285 | minimum=0.8, 286 | maximum=1.0, 287 | value=0.94, 288 | step=0.02, 289 | info="Adjusts the speed of the generated audio (1.0 = original speed).", 290 | ) 291 | 292 | run_button = gr.Button("Generate Audio", variant="primary") 293 | 294 | with gr.Column(scale=1): 295 | audio_output = gr.Audio( 296 | label="Generated Audio", 297 | type="numpy", 298 | autoplay=False, 299 | ) 300 | 301 | # Link button click to function 302 | run_button.click( 303 | fn=run_inference, 304 | inputs=[ 305 | text_input, 306 | audio_prompt_input, 307 | max_new_tokens, 308 | cfg_scale, 309 | temperature, 310 | top_p, 311 | cfg_filter_top_k, 312 | speed_factor_slider, 313 | ], 314 | outputs=[audio_output], # Add status_output here if using it 315 | api_name="generate_audio", 316 | ) 317 | 318 | # Add examples (ensure the prompt path is correct or remove it if example file doesn't exist) 319 | example_prompt_path = "./example_prompt.mp3" # Adjust if needed 320 | examples_list = [ 321 | [ 322 | "[S1] Oh fire! Oh my goodness! What's the procedure? What to we do people? The smoke could be coming through an air duct! \n[S2] Oh my god! Okay.. it's happening. Everybody stay calm! \n[S1] What's the procedure... \n[S2] Everybody stay fucking calm!!!... Everybody fucking calm down!!!!! \n[S1] No! No! If you touch the handle, if its hot there might be a fire down the hallway! ", 323 | None, 324 | 3072, 325 | 3.0, 326 | 1.3, 327 | 0.95, 328 | 35, 329 | 0.94, 330 | ], 331 | [ 332 | "[S1] Open weights text to dialogue model. \n[S2] You get full control over scripts and voices. \n[S1] I'm biased, but I think we clearly won. \n[S2] Hard to disagree. (laughs) \n[S1] Thanks for listening to this demo. \n[S2] Try it now on Git hub and Hugging Face. \n[S1] If you liked our model, please give us a star and share to your friends. \n[S2] This was Nari Labs.", 333 | example_prompt_path if Path(example_prompt_path).exists() else None, 334 | 3072, 335 | 3.0, 336 | 1.3, 337 | 0.95, 338 | 35, 339 | 0.94, 340 | ], 341 | ] 342 | 343 | if examples_list: 344 | gr.Examples( 345 | examples=examples_list, 346 | inputs=[ 347 | text_input, 348 | audio_prompt_input, 349 | max_new_tokens, 350 | cfg_scale, 351 | temperature, 352 | top_p, 353 | cfg_filter_top_k, 354 | speed_factor_slider, 355 | ], 356 | outputs=[audio_output], 357 | fn=run_inference, 358 | cache_examples=False, 359 | label="Examples (Click to Run)", 360 | ) 361 | else: 362 | gr.Markdown("_(No examples configured or example prompt file missing)_") 363 | 364 | # --- Launch the App --- 365 | if __name__ == "__main__": 366 | print("Launching Gradio interface...") 367 | 368 | # set `GRADIO_SERVER_NAME`, `GRADIO_SERVER_PORT` env vars to override default values 369 | # use `GRADIO_SERVER_NAME=0.0.0.0` for Docker 370 | demo.launch(share=args.share) 371 | -------------------------------------------------------------------------------- /cli.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import random 4 | 5 | import numpy as np 6 | import soundfile as sf 7 | import torch 8 | 9 | from dia.model import Dia 10 | 11 | 12 | def set_seed(seed: int): 13 | """Sets the random seed for reproducibility.""" 14 | random.seed(seed) 15 | np.random.seed(seed) 16 | torch.manual_seed(seed) 17 | if torch.cuda.is_available(): 18 | torch.cuda.manual_seed(seed) 19 | torch.cuda.manual_seed_all(seed) 20 | # Ensure deterministic behavior for cuDNN (if used) 21 | torch.backends.cudnn.deterministic = True 22 | torch.backends.cudnn.benchmark = False 23 | 24 | 25 | def main(): 26 | parser = argparse.ArgumentParser(description="Generate audio using the Dia model.") 27 | 28 | parser.add_argument("text", type=str, help="Input text for speech generation.") 29 | parser.add_argument( 30 | "--output", type=str, required=True, help="Path to save the generated audio file (e.g., output.wav)." 31 | ) 32 | 33 | parser.add_argument( 34 | "--repo-id", 35 | type=str, 36 | default="nari-labs/Dia-1.6B", 37 | help="Hugging Face repository ID (e.g., nari-labs/Dia-1.6B).", 38 | ) 39 | parser.add_argument( 40 | "--local-paths", action="store_true", help="Load model from local config and checkpoint files." 41 | ) 42 | 43 | parser.add_argument( 44 | "--config", type=str, help="Path to local config.json file (required if --local-paths is set)." 45 | ) 46 | parser.add_argument( 47 | "--checkpoint", type=str, help="Path to local model checkpoint .pth file (required if --local-paths is set)." 48 | ) 49 | parser.add_argument( 50 | "--audio-prompt", type=str, default=None, help="Path to an optional audio prompt WAV file for voice cloning." 51 | ) 52 | 53 | gen_group = parser.add_argument_group("Generation Parameters") 54 | gen_group.add_argument( 55 | "--max-tokens", 56 | type=int, 57 | default=None, 58 | help="Maximum number of audio tokens to generate (defaults to config value).", 59 | ) 60 | gen_group.add_argument( 61 | "--cfg-scale", type=float, default=3.0, help="Classifier-Free Guidance scale (default: 3.0)." 62 | ) 63 | gen_group.add_argument( 64 | "--temperature", type=float, default=1.3, help="Sampling temperature (higher is more random, default: 0.7)." 65 | ) 66 | gen_group.add_argument("--top-p", type=float, default=0.95, help="Nucleus sampling probability (default: 0.95).") 67 | 68 | infra_group = parser.add_argument_group("Infrastructure") 69 | infra_group.add_argument("--seed", type=int, default=None, help="Random seed for reproducibility.") 70 | infra_group.add_argument( 71 | "--device", 72 | type=str, 73 | default="cuda" if torch.cuda.is_available() else "cpu", 74 | help="Device to run inference on (e.g., 'cuda', 'cpu', default: auto).", 75 | ) 76 | 77 | args = parser.parse_args() 78 | 79 | # Validation for local paths 80 | if args.local_paths: 81 | if not args.config: 82 | parser.error("--config is required when --local-paths is set.") 83 | if not args.checkpoint: 84 | parser.error("--checkpoint is required when --local-paths is set.") 85 | if not os.path.exists(args.config): 86 | parser.error(f"Config file not found: {args.config}") 87 | if not os.path.exists(args.checkpoint): 88 | parser.error(f"Checkpoint file not found: {args.checkpoint}") 89 | 90 | # Set seed if provided 91 | if args.seed is not None: 92 | set_seed(args.seed) 93 | print(f"Using random seed: {args.seed}") 94 | 95 | # Determine device 96 | device = torch.device(args.device) 97 | print(f"Using device: {device}") 98 | 99 | # Load model 100 | print("Loading model...") 101 | if args.local_paths: 102 | print(f"Loading from local paths: config='{args.config}', checkpoint='{args.checkpoint}'") 103 | try: 104 | model = Dia.from_local(args.config, args.checkpoint, device=device) 105 | except Exception as e: 106 | print(f"Error loading local model: {e}") 107 | exit(1) 108 | else: 109 | print(f"Loading from Hugging Face Hub: repo_id='{args.repo_id}'") 110 | try: 111 | model = Dia.from_pretrained(args.repo_id, device=device) 112 | except Exception as e: 113 | print(f"Error loading model from Hub: {e}") 114 | exit(1) 115 | print("Model loaded.") 116 | 117 | # Generate audio 118 | print("Generating audio...") 119 | try: 120 | sample_rate = 44100 # Default assumption 121 | 122 | output_audio = model.generate( 123 | text=args.text, 124 | audio_prompt=args.audio_prompt, 125 | max_tokens=args.max_tokens, 126 | cfg_scale=args.cfg_scale, 127 | temperature=args.temperature, 128 | top_p=args.top_p, 129 | ) 130 | print("Audio generation complete.") 131 | 132 | print(f"Saving audio to {args.output}...") 133 | os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True) 134 | 135 | sf.write(args.output, output_audio, sample_rate) 136 | print(f"Audio successfully saved to {args.output}") 137 | 138 | except Exception as e: 139 | print(f"Error during audio generation or saving: {e}") 140 | exit(1) 141 | 142 | 143 | if __name__ == "__main__": 144 | main() 145 | -------------------------------------------------------------------------------- /dia/__init__.py: -------------------------------------------------------------------------------- 1 | from .model import Dia 2 | 3 | 4 | __all__ = [ 5 | "Dia", 6 | ] 7 | -------------------------------------------------------------------------------- /dia/audio.py: -------------------------------------------------------------------------------- 1 | import typing as tp 2 | 3 | import torch 4 | 5 | 6 | def build_delay_indices(B: int, T: int, C: int, delay_pattern: tp.List[int]) -> tp.Tuple[torch.Tensor, torch.Tensor]: 7 | """ 8 | Precompute (t_idx_BxTxC, indices_BTCx3) so that out[t, c] = in[t - delay[c], c]. 9 | Negative t_idx => BOS; t_idx >= T => PAD. 10 | """ 11 | delay_arr = torch.tensor(delay_pattern, dtype=torch.int32) 12 | 13 | t_idx_BxT = torch.broadcast_to( 14 | torch.arange(T, dtype=torch.int32)[None, :], 15 | [B, T], 16 | ) 17 | t_idx_BxTx1 = t_idx_BxT[..., None] 18 | t_idx_BxTxC = t_idx_BxTx1 - delay_arr.view(1, 1, C) 19 | 20 | b_idx_BxTxC = torch.broadcast_to( 21 | torch.arange(B, dtype=torch.int32).view(B, 1, 1), 22 | [B, T, C], 23 | ) 24 | c_idx_BxTxC = torch.broadcast_to( 25 | torch.arange(C, dtype=torch.int32).view(1, 1, C), 26 | [B, T, C], 27 | ) 28 | 29 | # We must clamp time indices to [0..T-1] so gather_nd equivalent won't fail 30 | t_clamped_BxTxC = torch.clamp(t_idx_BxTxC, 0, T - 1) 31 | 32 | indices_BTCx3 = torch.stack( 33 | [ 34 | b_idx_BxTxC.reshape(-1), 35 | t_clamped_BxTxC.reshape(-1), 36 | c_idx_BxTxC.reshape(-1), 37 | ], 38 | dim=1, 39 | ).long() # Ensure indices are long type for indexing 40 | 41 | return t_idx_BxTxC, indices_BTCx3 42 | 43 | 44 | def apply_audio_delay( 45 | audio_BxTxC: torch.Tensor, 46 | pad_value: int, 47 | bos_value: int, 48 | precomp: tp.Tuple[torch.Tensor, torch.Tensor], 49 | ) -> torch.Tensor: 50 | """ 51 | Applies the delay pattern to batched audio tokens using precomputed indices, 52 | inserting BOS where t_idx < 0 and PAD where t_idx >= T. 53 | 54 | Args: 55 | audio_BxTxC: [B, T, C] int16 audio tokens (or int32/float) 56 | pad_value: the padding token 57 | bos_value: the BOS token 58 | precomp: (t_idx_BxTxC, indices_BTCx3) from build_delay_indices 59 | 60 | Returns: 61 | result_BxTxC: [B, T, C] delayed audio tokens 62 | """ 63 | device = audio_BxTxC.device # Get device from input tensor 64 | t_idx_BxTxC, indices_BTCx3 = precomp 65 | t_idx_BxTxC = t_idx_BxTxC.to(device) # Move precomputed indices to device 66 | indices_BTCx3 = indices_BTCx3.to(device) 67 | 68 | # Equivalent of tf.gather_nd using advanced indexing 69 | # Ensure indices are long type if not already (build_delay_indices should handle this) 70 | gathered_flat = audio_BxTxC[indices_BTCx3[:, 0], indices_BTCx3[:, 1], indices_BTCx3[:, 2]] 71 | gathered_BxTxC = gathered_flat.view(audio_BxTxC.shape) 72 | 73 | # Create masks on the correct device 74 | mask_bos = t_idx_BxTxC < 0 # => place bos_value 75 | mask_pad = t_idx_BxTxC >= audio_BxTxC.shape[1] # => place pad_value 76 | 77 | # Create scalar tensors on the correct device 78 | bos_tensor = torch.tensor(bos_value, dtype=audio_BxTxC.dtype, device=device) 79 | pad_tensor = torch.tensor(pad_value, dtype=audio_BxTxC.dtype, device=device) 80 | 81 | # If mask_bos, BOS; else if mask_pad, PAD; else original gather 82 | # All tensors should now be on the same device 83 | result_BxTxC = torch.where(mask_bos, bos_tensor, torch.where(mask_pad, pad_tensor, gathered_BxTxC)) 84 | 85 | return result_BxTxC 86 | 87 | 88 | def build_revert_indices(B: int, T: int, C: int, delay_pattern: tp.List[int]) -> tp.Tuple[torch.Tensor, torch.Tensor]: 89 | """ 90 | Precompute indices for the revert operation using PyTorch. 91 | 92 | Returns: 93 | A tuple (t_idx_BxTxC, indices_BTCx3) where: 94 | - t_idx_BxTxC is a tensor of shape [B, T, C] computed as time indices plus the delay. 95 | - indices_BTCx3 is a tensor of shape [B*T*C, 3] used for gathering, computed from: 96 | batch indices, clamped time indices, and channel indices. 97 | """ 98 | # Use default device unless specified otherwise; assumes inputs might define device later 99 | device = None # Or determine dynamically if needed, e.g., from a model parameter 100 | 101 | delay_arr = torch.tensor(delay_pattern, dtype=torch.int32, device=device) 102 | 103 | t_idx_BT1 = torch.broadcast_to(torch.arange(T, device=device).unsqueeze(0), [B, T]) 104 | t_idx_BT1 = t_idx_BT1.unsqueeze(-1) 105 | 106 | t_idx_BxTxC = torch.minimum( 107 | t_idx_BT1 + delay_arr.view(1, 1, C), 108 | torch.tensor(T - 1, device=device), 109 | ) 110 | b_idx_BxTxC = torch.broadcast_to(torch.arange(B, device=device).view(B, 1, 1), [B, T, C]) 111 | c_idx_BxTxC = torch.broadcast_to(torch.arange(C, device=device).view(1, 1, C), [B, T, C]) 112 | 113 | indices_BTCx3 = torch.stack( 114 | [ 115 | b_idx_BxTxC.reshape(-1), 116 | t_idx_BxTxC.reshape(-1), 117 | c_idx_BxTxC.reshape(-1), 118 | ], 119 | axis=1, 120 | ).long() # Ensure indices are long type 121 | 122 | return t_idx_BxTxC, indices_BTCx3 123 | 124 | 125 | def revert_audio_delay( 126 | audio_BxTxC: torch.Tensor, 127 | pad_value: int, 128 | precomp: tp.Tuple[torch.Tensor, torch.Tensor], 129 | T: int, 130 | ) -> torch.Tensor: 131 | """ 132 | Reverts a delay pattern from batched audio tokens using precomputed indices (PyTorch version). 133 | 134 | Args: 135 | audio_BxTxC: Input delayed audio tensor 136 | pad_value: Padding value for out-of-bounds indices 137 | precomp: Precomputed revert indices tuple containing: 138 | - t_idx_BxTxC: Time offset indices tensor 139 | - indices_BTCx3: Gather indices tensor for original audio 140 | T: Original sequence length before padding 141 | 142 | Returns: 143 | Reverted audio tensor with same shape as input 144 | """ 145 | t_idx_BxTxC, indices_BTCx3 = precomp 146 | device = audio_BxTxC.device # Get device from input tensor 147 | 148 | # Move precomputed indices to the same device as audio_BxTxC if they aren't already 149 | t_idx_BxTxC = t_idx_BxTxC.to(device) 150 | indices_BTCx3 = indices_BTCx3.to(device) 151 | 152 | # Using PyTorch advanced indexing (equivalent to tf.gather_nd or np equivalent) 153 | gathered_flat = audio_BxTxC[indices_BTCx3[:, 0], indices_BTCx3[:, 1], indices_BTCx3[:, 2]] 154 | gathered_BxTxC = gathered_flat.view(audio_BxTxC.size()) # Use .size() for robust reshaping 155 | 156 | # Create pad_tensor on the correct device 157 | pad_tensor = torch.tensor(pad_value, dtype=audio_BxTxC.dtype, device=device) 158 | # Create T tensor on the correct device for comparison 159 | T_tensor = torch.tensor(T, device=device) 160 | 161 | result_BxTxC = torch.where(t_idx_BxTxC >= T_tensor, pad_tensor, gathered_BxTxC) # Changed np.where to torch.where 162 | 163 | return result_BxTxC 164 | 165 | 166 | @torch.no_grad() 167 | @torch.inference_mode() 168 | def decode( 169 | model, 170 | audio_codes, 171 | ): 172 | """ 173 | Decodes the given frames into an output audio waveform 174 | """ 175 | if len(audio_codes) != 1: 176 | raise ValueError(f"Expected one frame, got {len(audio_codes)}") 177 | 178 | try: 179 | audio_values = model.quantizer.from_codes(audio_codes) 180 | audio_values = model.decode(audio_values[0]) 181 | 182 | return audio_values 183 | except Exception as e: 184 | print(f"Error in decode method: {str(e)}") 185 | raise 186 | -------------------------------------------------------------------------------- /dia/config.py: -------------------------------------------------------------------------------- 1 | """Configuration management module for the Dia model. 2 | 3 | This module provides comprehensive configuration management for the Dia model, 4 | utilizing Pydantic for validation. It defines configurations for data processing, 5 | model architecture (encoder and decoder), and training settings. 6 | 7 | Key components: 8 | - DataConfig: Parameters for data loading and preprocessing. 9 | - EncoderConfig: Architecture details for the encoder module. 10 | - DecoderConfig: Architecture details for the decoder module. 11 | - ModelConfig: Combined model architecture settings. 12 | - TrainingConfig: Training hyperparameters and settings. 13 | - DiaConfig: Master configuration combining all components. 14 | """ 15 | 16 | import os 17 | from typing import Annotated 18 | 19 | from pydantic import BaseModel, BeforeValidator, Field 20 | 21 | 22 | class DataConfig(BaseModel, frozen=True): 23 | """Configuration for data loading and preprocessing. 24 | 25 | Attributes: 26 | text_length: Maximum length of text sequences (must be multiple of 128). 27 | audio_length: Maximum length of audio sequences (must be multiple of 128). 28 | channels: Number of audio channels. 29 | text_pad_value: Value used for padding text sequences. 30 | audio_eos_value: Value representing the end of audio sequences. 31 | audio_bos_value: Value representing the beginning of audio sequences. 32 | audio_pad_value: Value used for padding audio sequences. 33 | delay_pattern: List of delay values for each audio channel. 34 | """ 35 | 36 | text_length: Annotated[int, BeforeValidator(lambda x: (x + 127) // 128 * 128)] = Field(gt=0, multiple_of=128) 37 | audio_length: Annotated[int, BeforeValidator(lambda x: (x + 127) // 128 * 128)] = Field(gt=0, multiple_of=128) 38 | channels: int = Field(default=9, gt=0, multiple_of=1) 39 | text_pad_value: int = Field(default=0) 40 | audio_eos_value: int = Field(default=1024) 41 | audio_pad_value: int = Field(default=1025) 42 | audio_bos_value: int = Field(default=1026) 43 | delay_pattern: list[Annotated[int, Field(ge=0)]] = Field(default_factory=lambda: [0, 8, 9, 10, 11, 12, 13, 14, 15]) 44 | 45 | def __hash__(self) -> int: 46 | """Generate a hash based on all fields of the config.""" 47 | return hash( 48 | ( 49 | self.text_length, 50 | self.audio_length, 51 | self.channels, 52 | self.text_pad_value, 53 | self.audio_pad_value, 54 | self.audio_bos_value, 55 | self.audio_eos_value, 56 | tuple(self.delay_pattern), 57 | ) 58 | ) 59 | 60 | 61 | class EncoderConfig(BaseModel, frozen=True): 62 | """Configuration for the encoder component of the Dia model. 63 | 64 | Attributes: 65 | n_layer: Number of transformer layers. 66 | n_embd: Embedding dimension. 67 | n_hidden: Hidden dimension size in the MLP layers. 68 | n_head: Number of attention heads. 69 | head_dim: Dimension per attention head. 70 | """ 71 | 72 | n_layer: int = Field(gt=0) 73 | n_embd: int = Field(gt=0) 74 | n_hidden: int = Field(gt=0) 75 | n_head: int = Field(gt=0) 76 | head_dim: int = Field(gt=0) 77 | 78 | 79 | class DecoderConfig(BaseModel, frozen=True): 80 | """Configuration for the decoder component of the Dia model. 81 | 82 | Attributes: 83 | n_layer: Number of transformer layers. 84 | n_embd: Embedding dimension. 85 | n_hidden: Hidden dimension size in the MLP layers. 86 | gqa_query_heads: Number of query heads for grouped-query self-attention. 87 | kv_heads: Number of key/value heads for grouped-query self-attention. 88 | gqa_head_dim: Dimension per query head for grouped-query self-attention. 89 | cross_query_heads: Number of query heads for cross-attention. 90 | cross_head_dim: Dimension per cross-attention head. 91 | """ 92 | 93 | n_layer: int = Field(gt=0) 94 | n_embd: int = Field(gt=0) 95 | n_hidden: int = Field(gt=0) 96 | gqa_query_heads: int = Field(gt=0) 97 | kv_heads: int = Field(gt=0) 98 | gqa_head_dim: int = Field(gt=0) 99 | cross_query_heads: int = Field(gt=0) 100 | cross_head_dim: int = Field(gt=0) 101 | 102 | 103 | class ModelConfig(BaseModel, frozen=True): 104 | """Main configuration container for the Dia model architecture. 105 | 106 | Attributes: 107 | encoder: Configuration for the encoder component. 108 | decoder: Configuration for the decoder component. 109 | src_vocab_size: Size of the source (text) vocabulary. 110 | tgt_vocab_size: Size of the target (audio code) vocabulary. 111 | dropout: Dropout probability applied within the model. 112 | normalization_layer_epsilon: Epsilon value for normalization layers (e.g., LayerNorm). 113 | weight_dtype: Data type for model weights (e.g., "float32", "bfloat16"). 114 | rope_min_timescale: Minimum timescale for Rotary Positional Embeddings (RoPE). 115 | rope_max_timescale: Maximum timescale for Rotary Positional Embeddings (RoPE). 116 | """ 117 | 118 | encoder: EncoderConfig 119 | decoder: DecoderConfig 120 | src_vocab_size: int = Field(default=128, gt=0) 121 | tgt_vocab_size: int = Field(default=1028, gt=0) 122 | dropout: float = Field(default=0.0, ge=0.0, lt=1.0) 123 | normalization_layer_epsilon: float = Field(default=1.0e-5, ge=0.0) 124 | weight_dtype: str = Field(default="float32", description="Weight precision") 125 | rope_min_timescale: int = Field(default=1, description="Timescale For global Attention") 126 | rope_max_timescale: int = Field(default=10_000, description="Timescale For global Attention") 127 | 128 | 129 | class TrainingConfig(BaseModel, frozen=True): 130 | pass 131 | 132 | 133 | class DiaConfig(BaseModel, frozen=True): 134 | """Master configuration for the Dia model. 135 | 136 | Combines all sub-configurations into a single validated object. 137 | 138 | Attributes: 139 | version: Configuration version string. 140 | model: Model architecture configuration. 141 | training: Training process configuration (precision settings). 142 | data: Data loading and processing configuration. 143 | """ 144 | 145 | version: str = Field(default="1.0") 146 | model: ModelConfig 147 | # TODO: remove training. this is just for backwards-compatability 148 | training: TrainingConfig 149 | data: DataConfig 150 | 151 | def save(self, path: str) -> None: 152 | """Save the current configuration instance to a JSON file. 153 | 154 | Ensures the parent directory exists and the file has a .json extension. 155 | 156 | Args: 157 | path: The target file path to save the configuration. 158 | 159 | Raises: 160 | ValueError: If the path is not a file with a .json extension. 161 | """ 162 | os.makedirs(os.path.dirname(path), exist_ok=True) 163 | config_json = self.model_dump_json(indent=2) 164 | with open(path, "w") as f: 165 | f.write(config_json) 166 | 167 | @classmethod 168 | def load(cls, path: str) -> "DiaConfig | None": 169 | """Load and validate a Dia configuration from a JSON file. 170 | 171 | Args: 172 | path: The path to the configuration file. 173 | 174 | Returns: 175 | A validated DiaConfig instance if the file exists and is valid, 176 | otherwise None if the file is not found. 177 | 178 | Raises: 179 | ValueError: If the path does not point to an existing .json file. 180 | pydantic.ValidationError: If the JSON content fails validation against the DiaConfig schema. 181 | """ 182 | try: 183 | with open(path, "r") as f: 184 | content = f.read() 185 | return cls.model_validate_json(content) 186 | except FileNotFoundError: 187 | return None 188 | -------------------------------------------------------------------------------- /dia/layers.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from torch import Tensor 5 | from torch.nn import RMSNorm 6 | 7 | from .config import DiaConfig 8 | from .state import DecoderInferenceState, EncoderInferenceState, KVCache 9 | 10 | 11 | def _normalize_axes(axes: tuple[int, ...], ndim: int) -> tuple[int, ...]: 12 | return tuple(ax if ax >= 0 else ndim + ax for ax in axes) 13 | 14 | 15 | class DenseGeneral(nn.Module): 16 | """ 17 | PyTorch equivalent of flax.linen.DenseGeneral with shapes defined at init. 18 | 19 | Stores weights (`kernel`) in the same layout as Jax and uses torch.tensordot 20 | for the generalized matrix multiplication. Weight/bias shapes are calculated 21 | and parameters created during initialization based on config. 22 | `load_weights` validates shapes and copies data. 23 | 24 | Attributes: 25 | axis (Tuple[int, ...]): Input axis or axes to contract. 26 | in_shapes (Tuple[int, ...]): Sizes of the input dimensions specified by `axis`. 27 | out_features (Tuple[int, ...]): Shape of the output features (non-contracted dims). 28 | use_bias (bool): Whether to add a bias term. 29 | weight (nn.Parameter): The kernel parameter. 30 | bias (Optional[nn.Parameter]): The bias parameter (if use_bias=True). 31 | """ 32 | 33 | def __init__( 34 | self, 35 | in_shapes: tuple[int, ...], 36 | out_features: tuple[int, ...], 37 | axis: tuple[int, ...] = (-1,), 38 | weight_dtype: torch.dtype | None = None, 39 | device: torch.device | None = None, 40 | ): 41 | super().__init__() 42 | self.in_shapes = in_shapes 43 | self.out_features = out_features 44 | self.axis = axis 45 | self.kernel_shape = self.in_shapes + self.out_features 46 | 47 | factory_kwargs = {"device": device, "dtype": weight_dtype} 48 | self.weight = nn.Parameter(torch.empty(self.kernel_shape, **factory_kwargs)) 49 | self.register_parameter("bias", None) 50 | 51 | def forward(self, inputs: Tensor) -> Tensor: 52 | norm_axis = _normalize_axes(self.axis, inputs.ndim) 53 | kernel_contract_axes = tuple(range(len(norm_axis))) 54 | 55 | output = torch.tensordot( 56 | inputs.to(self.weight.dtype), 57 | self.weight, 58 | dims=(norm_axis, kernel_contract_axes), 59 | ).to(inputs.dtype) 60 | return output 61 | 62 | 63 | class MlpBlock(nn.Module): 64 | """MLP block using DenseGeneral.""" 65 | 66 | def __init__(self, embed_dim: int, intermediate_dim: int, compute_dtype: torch.dtype): 67 | super().__init__() 68 | self.dtype = compute_dtype 69 | 70 | self.wi_fused = DenseGeneral( 71 | in_shapes=(embed_dim,), 72 | out_features=(2, intermediate_dim), 73 | axis=(-1,), 74 | weight_dtype=compute_dtype, 75 | ) 76 | 77 | self.wo = DenseGeneral( 78 | in_shapes=(intermediate_dim,), 79 | out_features=(embed_dim,), 80 | axis=(-1,), 81 | weight_dtype=compute_dtype, 82 | ) 83 | 84 | def forward(self, x: torch.Tensor) -> torch.Tensor: 85 | """Forward pass.""" 86 | fused_x = self.wi_fused(x) 87 | 88 | gate = fused_x[..., 0, :] 89 | up = fused_x[..., 1, :] 90 | 91 | hidden = torch.mul(F.silu(gate), up).to(self.dtype) 92 | 93 | output = self.wo(hidden) 94 | return output 95 | 96 | 97 | class RotaryEmbedding(nn.Module): 98 | """Rotary Position Embedding (RoPE) implementation in PyTorch.""" 99 | 100 | def __init__( 101 | self, 102 | embedding_dims: int, 103 | min_timescale: int = 1, 104 | max_timescale: int = 10000, 105 | dtype: torch.dtype = torch.float32, 106 | ): 107 | super().__init__() 108 | if embedding_dims % 2 != 0: 109 | raise ValueError("Embedding dim must be even for RoPE.") 110 | self.embedding_dims = embedding_dims 111 | self.min_timescale = min_timescale 112 | self.max_timescale = max_timescale 113 | self.dtype = dtype 114 | 115 | half_embedding_dim = embedding_dims // 2 116 | fraction = (2.0 * torch.arange(0, half_embedding_dim)) / embedding_dims 117 | self.register_buffer( 118 | "timescale", 119 | self.min_timescale * (self.max_timescale / self.min_timescale) ** fraction, 120 | persistent=False, 121 | ) 122 | 123 | def extra_repr(self) -> str: 124 | s = f"{self.timescale.shape}" 125 | return s 126 | 127 | def forward(self, inputs: torch.Tensor, position: torch.Tensor): 128 | """Applies RoPE.""" 129 | position = position.unsqueeze(-1).unsqueeze(-1) 130 | timescale = self.timescale.to(inputs.device) 131 | sinusoid_inp = position / timescale 132 | sin = torch.sin(sinusoid_inp).to(inputs.dtype) 133 | cos = torch.cos(sinusoid_inp).to(inputs.dtype) 134 | first_half, second_half = torch.chunk(inputs, 2, dim=-1) 135 | first_part = first_half * cos - second_half * sin 136 | second_part = second_half * cos + first_half * sin 137 | return torch.cat((first_part, second_part), dim=-1) 138 | 139 | 140 | class Attention(nn.Module): 141 | """Attention using DenseGeneral.""" 142 | 143 | def __init__( 144 | self, 145 | config: DiaConfig, 146 | q_embed_dim: int, 147 | kv_embed_dim: int, 148 | num_query_heads: int, 149 | num_kv_heads: int, 150 | head_dim: int, 151 | compute_dtype: torch.dtype, 152 | is_cross_attn: bool = False, 153 | out_embed_dim: int | None = None, 154 | ): 155 | super().__init__() 156 | self.num_query_heads = num_query_heads 157 | self.num_kv_heads = num_kv_heads 158 | self.head_dim = head_dim 159 | self.is_cross_attn = is_cross_attn 160 | self.output_dim = out_embed_dim if out_embed_dim is not None else q_embed_dim 161 | self.projected_query_dim = num_query_heads * head_dim 162 | if num_query_heads % num_kv_heads != 0: 163 | raise ValueError(f"num_query_heads ({num_query_heads}) must be divisible by num_kv_heads ({num_kv_heads})") 164 | self.num_gqa_groups = num_query_heads // num_kv_heads 165 | 166 | # --- Projection Layers using DenseGeneral --- 167 | self.q_proj = DenseGeneral( 168 | in_shapes=(q_embed_dim,), 169 | out_features=(num_query_heads, head_dim), 170 | axis=(-1,), 171 | weight_dtype=compute_dtype, 172 | ) 173 | self.k_proj = DenseGeneral( 174 | in_shapes=(kv_embed_dim,), 175 | out_features=(num_kv_heads, head_dim), 176 | axis=(-1,), 177 | weight_dtype=compute_dtype, 178 | ) 179 | self.v_proj = DenseGeneral( 180 | in_shapes=(kv_embed_dim,), 181 | out_features=(num_kv_heads, head_dim), 182 | axis=(-1,), 183 | weight_dtype=compute_dtype, 184 | ) 185 | self.o_proj = DenseGeneral( 186 | in_shapes=(num_query_heads, head_dim), 187 | out_features=(self.output_dim,), 188 | axis=(-2, -1), 189 | weight_dtype=compute_dtype, 190 | ) 191 | 192 | # --- Rotary Embedding --- 193 | self.rotary_emb = RotaryEmbedding( 194 | embedding_dims=self.head_dim, 195 | min_timescale=config.model.rope_min_timescale, 196 | max_timescale=config.model.rope_max_timescale, 197 | dtype=compute_dtype, 198 | ) 199 | 200 | def forward( 201 | self, 202 | Xq: torch.Tensor, # (B, T, D) T = 1 in AR generation 203 | Xkv: torch.Tensor, # (B, S, E) S = 1 in AR generation 204 | q_positions: torch.Tensor, # (B, T) 205 | kv_positions: torch.Tensor | None = None, # (B, S) 206 | attn_mask: torch.Tensor | None = None, # None in Decoder Self Attention, Valid mask in Others 207 | cache: KVCache | None = None, # None in Encoder, KVCache in Decoder 208 | prefill: bool = False, 209 | is_causal: bool = False, 210 | ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor] | None]: 211 | """ 212 | Performs attention calculation with optional KV caching. 213 | 214 | Args: 215 | Xq: Query tensor (B, T, D). T=1 during single-step decoding. 216 | Xkv: Key/Value source tensor (B, S, E). S=1 during single-step decoding for self-attn. 217 | q_positions: Positions for queries (B, T). 218 | kv_positions: Positions for keys/values (B, S). If None, uses q_positions. 219 | attn_mask: Attention mask. 220 | cache: KVCache. 221 | prefill: If True, use prefill mode. 222 | 223 | Returns: 224 | A tuple containing: 225 | - output: The attention output tensor (B, T, output_dim). 226 | - present_kv: The K/V state to be cached for the next step ((B, N, S_new, H), (B, N, S_new, H)). For self-attn, S_new = S_past + S. For cross-attn, S_new = S_kv. 227 | """ 228 | if kv_positions is None: 229 | kv_positions = q_positions 230 | original_dtype = Xq.dtype 231 | 232 | Xq_BxTxNxH = self.q_proj(Xq) 233 | Xq_BxTxNxH = self.rotary_emb(Xq_BxTxNxH, position=q_positions) 234 | Xq_BxNxTxH = Xq_BxTxNxH.transpose(1, 2) 235 | 236 | attn_k: torch.Tensor | None = None 237 | attn_v: torch.Tensor | None = None 238 | 239 | if self.is_cross_attn: 240 | attn_k, attn_v = cache.k, cache.v 241 | else: 242 | Xk_BxSxKxH = self.k_proj(Xkv) # (B, S, K, H) 243 | Xv_BxSxKxH = self.v_proj(Xkv) # (B, S, K, H) 244 | Xk_BxSxKxH = self.rotary_emb(Xk_BxSxKxH, position=kv_positions) # (B, S, K, H) 245 | 246 | Xk_BxKxSxH = Xk_BxSxKxH.transpose(1, 2) # (B, K, S, H) 247 | Xv_BxKxSxH = Xv_BxSxKxH.transpose(1, 2) # (B, K, S, H) 248 | 249 | if cache is None: 250 | attn_k = Xk_BxKxSxH 251 | attn_v = Xv_BxKxSxH 252 | else: 253 | if prefill: 254 | attn_k, attn_v = Xk_BxKxSxH, Xv_BxKxSxH 255 | cache.prefill(attn_k, attn_v) 256 | else: 257 | attn_k, attn_v = cache.update(Xk_BxKxSxH, Xv_BxKxSxH) 258 | 259 | attn_output = F.scaled_dot_product_attention( 260 | Xq_BxNxTxH, 261 | attn_k, 262 | attn_v, 263 | attn_mask=attn_mask, 264 | scale=1.0, 265 | enable_gqa=self.num_gqa_groups > 1, 266 | is_causal=is_causal, 267 | ) 268 | 269 | attn_output = attn_output.transpose(1, 2).contiguous() # (B, T, N, H) 270 | output = self.o_proj(attn_output) 271 | 272 | return output.to(original_dtype) 273 | 274 | 275 | class EncoderLayer(nn.Module): 276 | """Transformer Encoder Layer using DenseGeneral.""" 277 | 278 | def __init__(self, config: DiaConfig, compute_dtype: torch.dtype): 279 | super().__init__() 280 | self.config = config 281 | model_config = config.model 282 | enc_config = config.model.encoder 283 | embed_dim = enc_config.n_embd 284 | 285 | self.pre_sa_norm = RMSNorm( 286 | embed_dim, 287 | eps=model_config.normalization_layer_epsilon, 288 | dtype=torch.float32, 289 | ) 290 | self.self_attention = Attention( 291 | config, 292 | q_embed_dim=embed_dim, 293 | kv_embed_dim=embed_dim, 294 | num_query_heads=enc_config.n_head, 295 | num_kv_heads=enc_config.n_head, 296 | head_dim=enc_config.head_dim, 297 | compute_dtype=compute_dtype, 298 | is_cross_attn=False, 299 | out_embed_dim=embed_dim, 300 | ) 301 | self.post_sa_norm = RMSNorm( 302 | embed_dim, 303 | eps=model_config.normalization_layer_epsilon, 304 | dtype=torch.float32, 305 | ) 306 | self.mlp = MlpBlock(embed_dim=embed_dim, intermediate_dim=enc_config.n_hidden, compute_dtype=compute_dtype) 307 | 308 | def forward( 309 | self, 310 | x: torch.Tensor, 311 | state: EncoderInferenceState, 312 | ) -> torch.Tensor: 313 | residual = x 314 | x_norm = self.pre_sa_norm(x) 315 | sa_out = self.self_attention( 316 | Xq=x_norm, 317 | Xkv=x_norm, 318 | q_positions=state.positions, 319 | kv_positions=state.positions, 320 | attn_mask=state.attn_mask, 321 | ) 322 | x = residual + sa_out 323 | 324 | residual = x 325 | x_norm = self.post_sa_norm(x) 326 | mlp_out = self.mlp(x_norm) 327 | x = residual + mlp_out 328 | 329 | return x 330 | 331 | 332 | class Encoder(nn.Module): 333 | """Transformer Encoder Stack using DenseGeneral.""" 334 | 335 | def __init__(self, config: DiaConfig, compute_dtype: torch.dtype): 336 | super().__init__() 337 | self.config = config 338 | model_config = config.model 339 | enc_config = config.model.encoder 340 | 341 | self.embedding = nn.Embedding( 342 | model_config.src_vocab_size, 343 | enc_config.n_embd, 344 | dtype=compute_dtype, 345 | ) 346 | self.layers = nn.ModuleList([EncoderLayer(config, compute_dtype) for _ in range(enc_config.n_layer)]) 347 | self.norm = RMSNorm( 348 | enc_config.n_embd, 349 | eps=model_config.normalization_layer_epsilon, 350 | dtype=torch.float32, 351 | ) 352 | 353 | def forward( 354 | self, 355 | x_ids: torch.Tensor, 356 | state: EncoderInferenceState, 357 | ) -> torch.Tensor: 358 | x = self.embedding(x_ids) 359 | 360 | for layer in self.layers: 361 | x = layer(x, state) 362 | 363 | x = self.norm(x) 364 | return x 365 | 366 | 367 | class DecoderLayer(nn.Module): 368 | """Transformer Decoder Layer using DenseGeneral.""" 369 | 370 | def __init__(self, config: DiaConfig, compute_dtype: torch.dtype): 371 | super().__init__() 372 | self.config = config 373 | model_config = config.model 374 | dec_config = config.model.decoder 375 | enc_config = config.model.encoder 376 | dec_embed_dim = dec_config.n_embd 377 | enc_embed_dim = enc_config.n_embd 378 | 379 | # Norms 380 | self.pre_sa_norm = RMSNorm( 381 | dec_embed_dim, 382 | eps=model_config.normalization_layer_epsilon, 383 | dtype=torch.float32, 384 | ) 385 | self.pre_ca_norm = RMSNorm( 386 | dec_embed_dim, 387 | eps=model_config.normalization_layer_epsilon, 388 | dtype=torch.float32, 389 | ) 390 | self.pre_mlp_norm = RMSNorm( 391 | dec_embed_dim, 392 | eps=model_config.normalization_layer_epsilon, 393 | dtype=torch.float32, 394 | ) 395 | 396 | # Self-Attention (GQA) with Causal Masking 397 | self.self_attention = Attention( 398 | config, 399 | q_embed_dim=dec_embed_dim, 400 | kv_embed_dim=dec_embed_dim, 401 | num_query_heads=dec_config.gqa_query_heads, 402 | num_kv_heads=dec_config.kv_heads, 403 | head_dim=dec_config.gqa_head_dim, 404 | compute_dtype=compute_dtype, 405 | is_cross_attn=False, 406 | out_embed_dim=dec_embed_dim, 407 | ) 408 | # Cross-Attention (MHA) 409 | self.cross_attention = Attention( 410 | config=config, 411 | q_embed_dim=dec_embed_dim, 412 | kv_embed_dim=enc_embed_dim, # Note kv_embed_dim 413 | num_query_heads=dec_config.cross_query_heads, 414 | num_kv_heads=dec_config.cross_query_heads, 415 | head_dim=dec_config.cross_head_dim, 416 | compute_dtype=compute_dtype, 417 | is_cross_attn=True, 418 | out_embed_dim=dec_embed_dim, 419 | ) 420 | # MLP 421 | self.mlp = MlpBlock( 422 | embed_dim=dec_embed_dim, 423 | intermediate_dim=dec_config.n_hidden, 424 | compute_dtype=compute_dtype, 425 | ) 426 | 427 | def forward( 428 | self, 429 | x: torch.Tensor, 430 | state: DecoderInferenceState, 431 | self_attn_cache: KVCache | None = None, 432 | cross_attn_cache: KVCache | None = None, 433 | prefill: bool = False, 434 | ) -> torch.Tensor: 435 | residual = x 436 | x_norm = self.pre_sa_norm(x) 437 | 438 | sa_out = self.self_attention( 439 | Xq=x_norm, # (2, 1, D) 440 | Xkv=x_norm, # (2, 1, D) 441 | q_positions=state.dec_positions, # (2, 1) 442 | kv_positions=state.dec_positions, # (2, 1) 443 | attn_mask=None, 444 | cache=self_attn_cache, 445 | prefill=prefill, 446 | is_causal=prefill, 447 | ) 448 | 449 | x = residual + sa_out 450 | 451 | residual = x 452 | x_norm = self.pre_ca_norm(x) 453 | ca_out = self.cross_attention( 454 | Xq=x_norm, 455 | Xkv=state.enc_out, 456 | q_positions=state.dec_positions, 457 | kv_positions=state.enc_positions, 458 | attn_mask=state.dec_cross_attn_mask, 459 | cache=cross_attn_cache, 460 | ) 461 | x = residual + ca_out 462 | 463 | residual = x 464 | x_norm = self.pre_mlp_norm(x) 465 | mlp_out = self.mlp(x_norm) 466 | x = residual + mlp_out 467 | 468 | return x 469 | 470 | 471 | class Decoder(nn.Module): 472 | """Transformer Decoder Stack using DenseGeneral.""" 473 | 474 | def __init__(self, config: DiaConfig, compute_dtype: torch.dtype): 475 | super().__init__() 476 | self.config = config 477 | model_config = config.model 478 | dec_config = config.model.decoder 479 | data_config = config.data 480 | self.num_channels = data_config.channels 481 | self.num_layers = dec_config.n_layer 482 | 483 | self.embeddings = nn.ModuleList( 484 | [ 485 | nn.Embedding(model_config.tgt_vocab_size, dec_config.n_embd, dtype=compute_dtype) 486 | for _ in range(self.num_channels) 487 | ] 488 | ) 489 | self.layers = nn.ModuleList( 490 | [DecoderLayer(config=config, compute_dtype=compute_dtype) for _ in range(self.num_layers)] 491 | ) 492 | 493 | self.norm = RMSNorm( 494 | dec_config.n_embd, 495 | eps=model_config.normalization_layer_epsilon, 496 | dtype=torch.float32, 497 | ) 498 | 499 | self.logits_dense = DenseGeneral( 500 | in_shapes=(dec_config.n_embd,), 501 | out_features=(self.num_channels, model_config.tgt_vocab_size), 502 | axis=(-1,), 503 | weight_dtype=compute_dtype, 504 | ) 505 | 506 | def precompute_cross_attn_cache( 507 | self, 508 | enc_out: torch.Tensor, # (B, S, E) 509 | enc_positions: torch.Tensor, # (B, S) 510 | ) -> list[KVCache]: 511 | """ 512 | Computes the Key and Value tensors for cross-attention for each layer from the encoder output. 513 | """ 514 | per_layer_kv_cache: list[KVCache] = [] 515 | 516 | for layer in self.layers: 517 | cross_attn_module = layer.cross_attention 518 | k_proj = cross_attn_module.k_proj(enc_out) 519 | v_proj = cross_attn_module.v_proj(enc_out) 520 | 521 | k_proj = cross_attn_module.rotary_emb(k_proj, position=enc_positions) 522 | k = k_proj.transpose(1, 2) 523 | v = v_proj.transpose(1, 2) 524 | 525 | per_layer_kv_cache.append(KVCache.from_kv(k, v)) 526 | 527 | return per_layer_kv_cache 528 | 529 | def decode_step( 530 | self, 531 | tgt_ids_Bx1xC: torch.Tensor, # [B, 1, C] 532 | state: DecoderInferenceState, 533 | ) -> torch.Tensor: 534 | """ 535 | Performs a single decoding step, managing KV caches layer by layer. 536 | 537 | Returns: 538 | A tuple containing: 539 | - logits_Bx1xCV: The final output logits for the current step (B, 1, C*V), cast to float32. 540 | """ 541 | 542 | x = None 543 | for i in range(self.num_channels): 544 | channel_tokens = tgt_ids_Bx1xC[..., i] 545 | channel_embed = self.embeddings[i](channel_tokens) 546 | x = channel_embed if x is None else x + channel_embed 547 | 548 | for i, layer in enumerate(self.layers): 549 | self_cache = state.self_attn_cache[i] 550 | cross_cache = state.cross_attn_cache[i] 551 | x = layer( 552 | x, # (2, 1, D) 553 | state, 554 | self_attn_cache=self_cache, 555 | cross_attn_cache=cross_cache, 556 | ) 557 | 558 | x = self.norm(x) 559 | logits_Bx1xCxV = self.logits_dense(x) 560 | 561 | return logits_Bx1xCxV.to(torch.float32) 562 | 563 | def forward(self, tgt_ids_BxTxC: torch.Tensor, state: DecoderInferenceState) -> torch.Tensor: 564 | """ 565 | Forward pass for the Decoder stack, managing KV caches. 566 | 567 | Args: 568 | tgt_ids_BxTxC: Target token IDs (B, T, C). 569 | encoder_out: Output from the encoder (B, S, E). 570 | tgt_positions: Positions for target sequence (B, T). 571 | src_positions: Positions for source sequence (B, S). 572 | self_attn_mask: Mask for self-attention. 573 | cross_attn_mask: Mask for cross-attention. 574 | past_key_values: List containing the self-attention KV cache for each layer 575 | from the previous decoding step. `len(past_key_values)` should 576 | equal `num_layers`. 577 | precomputed_cross_attn_kv: A single tuple containing the pre-computed K/V cache 578 | derived from `encoder_out`. This is passed identically 579 | to all layers. 580 | 581 | Returns: 582 | A tuple containing: 583 | - logits: The final output logits (B, T, C * V), cast to float32. 584 | - present_key_values: A list containing the updated self-attention KV cache 585 | for each layer for the *current* decoding step. 586 | """ 587 | _, _, num_channels_in = tgt_ids_BxTxC.shape 588 | assert num_channels_in == self.num_channels, "Input channels mismatch" 589 | 590 | # Embeddings 591 | x = None 592 | for i in range(self.num_channels): 593 | channel_tokens = tgt_ids_BxTxC[..., i] 594 | channel_embed = self.embeddings[i](channel_tokens) 595 | x = channel_embed if x is None else x + channel_embed 596 | 597 | for i, layer in enumerate(self.layers): 598 | self_cache = state.self_attn_cache[i] 599 | cross_cache = state.cross_attn_cache[i] 600 | x = layer(x, state, self_attn_cache=self_cache, cross_attn_cache=cross_cache, prefill=True) 601 | 602 | # Final Norm 603 | x = self.norm(x) 604 | logits_BxTxCxV = self.logits_dense(x) 605 | 606 | return logits_BxTxCxV.to(torch.float32) 607 | 608 | 609 | class DiaModel(nn.Module): 610 | """PyTorch Dia Model using DenseGeneral.""" 611 | 612 | def __init__(self, config: DiaConfig, compute_dtype: torch.dtype): 613 | super().__init__() 614 | self.config = config 615 | self.encoder = Encoder(config, compute_dtype) 616 | self.decoder = Decoder(config, compute_dtype) 617 | -------------------------------------------------------------------------------- /dia/model.py: -------------------------------------------------------------------------------- 1 | import time 2 | from enum import Enum 3 | 4 | import dac 5 | import numpy as np 6 | import torch 7 | import torchaudio 8 | from huggingface_hub import hf_hub_download 9 | 10 | from .audio import apply_audio_delay, build_delay_indices, build_revert_indices, decode, revert_audio_delay 11 | from .config import DiaConfig 12 | from .layers import DiaModel 13 | from .state import DecoderInferenceState, DecoderOutput, EncoderInferenceState 14 | 15 | 16 | DEFAULT_SAMPLE_RATE = 44100 17 | 18 | 19 | def _get_default_device(): 20 | if torch.cuda.is_available(): 21 | return torch.device("cuda") 22 | elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): 23 | return torch.device("mps") 24 | return torch.device("cpu") 25 | 26 | 27 | def _sample_next_token( 28 | logits_BCxV: torch.Tensor, 29 | temperature: float, 30 | top_p: float, 31 | cfg_filter_top_k: int | None = None, 32 | ) -> torch.Tensor: 33 | if temperature == 0.0: 34 | return torch.argmax(logits_BCxV, dim=-1) 35 | 36 | logits_BCxV = logits_BCxV / temperature 37 | if cfg_filter_top_k is not None: 38 | _, top_k_indices_BCxV = torch.topk(logits_BCxV, k=cfg_filter_top_k, dim=-1) 39 | mask = torch.ones_like(logits_BCxV, dtype=torch.bool) 40 | mask.scatter_(dim=-1, index=top_k_indices_BCxV, value=False) 41 | logits_BCxV = logits_BCxV.masked_fill(mask, -torch.inf) 42 | 43 | if top_p < 1.0: 44 | probs_BCxV = torch.softmax(logits_BCxV, dim=-1) 45 | sorted_probs_BCxV, sorted_indices_BCxV = torch.sort(probs_BCxV, dim=-1, descending=True) 46 | cumulative_probs_BCxV = torch.cumsum(sorted_probs_BCxV, dim=-1) 47 | 48 | sorted_indices_to_remove_BCxV = cumulative_probs_BCxV > top_p 49 | sorted_indices_to_remove_BCxV[..., 1:] = sorted_indices_to_remove_BCxV[..., :-1].clone() 50 | sorted_indices_to_remove_BCxV[..., 0] = 0 51 | 52 | indices_to_remove_BCxV = torch.zeros_like(sorted_indices_to_remove_BCxV) 53 | indices_to_remove_BCxV.scatter_(dim=-1, index=sorted_indices_BCxV, src=sorted_indices_to_remove_BCxV) 54 | logits_BCxV = logits_BCxV.masked_fill(indices_to_remove_BCxV, -torch.inf) 55 | 56 | final_probs_BCxV = torch.softmax(logits_BCxV, dim=-1) 57 | 58 | sampled_indices_BC = torch.multinomial(final_probs_BCxV, num_samples=1) 59 | sampled_indices_C = sampled_indices_BC.squeeze(-1) 60 | return sampled_indices_C 61 | 62 | 63 | class ComputeDtype(str, Enum): 64 | FLOAT32 = "float32" 65 | FLOAT16 = "float16" 66 | BFLOAT16 = "bfloat16" 67 | 68 | def to_dtype(self) -> torch.dtype: 69 | if self == ComputeDtype.FLOAT32: 70 | return torch.float32 71 | elif self == ComputeDtype.FLOAT16: 72 | return torch.float16 73 | elif self == ComputeDtype.BFLOAT16: 74 | return torch.bfloat16 75 | else: 76 | raise ValueError(f"Unsupported compute dtype: {self}") 77 | 78 | 79 | class Dia: 80 | def __init__( 81 | self, 82 | config: DiaConfig, 83 | compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32, 84 | device: torch.device | None = None, 85 | ): 86 | """Initializes the Dia model. 87 | 88 | Args: 89 | config: The configuration object for the model. 90 | device: The device to load the model onto. If None, will automatically select the best available device. 91 | 92 | Raises: 93 | RuntimeError: If there is an error loading the DAC model. 94 | """ 95 | super().__init__() 96 | self.config = config 97 | self.device = device if device is not None else _get_default_device() 98 | if isinstance(compute_dtype, str): 99 | compute_dtype = ComputeDtype(compute_dtype) 100 | self.compute_dtype = compute_dtype.to_dtype() 101 | self.model = DiaModel(config, self.compute_dtype) 102 | self.dac_model = None 103 | 104 | @classmethod 105 | def from_local( 106 | cls, 107 | config_path: str, 108 | checkpoint_path: str, 109 | compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32, 110 | device: torch.device | None = None, 111 | ) -> "Dia": 112 | """Loads the Dia model from local configuration and checkpoint files. 113 | 114 | Args: 115 | config_path: Path to the configuration JSON file. 116 | checkpoint_path: Path to the model checkpoint (.pth) file. 117 | device: The device to load the model onto. If None, will automatically select the best available device. 118 | 119 | Returns: 120 | An instance of the Dia model loaded with weights and set to eval mode. 121 | 122 | Raises: 123 | FileNotFoundError: If the config or checkpoint file is not found. 124 | RuntimeError: If there is an error loading the checkpoint. 125 | """ 126 | config = DiaConfig.load(config_path) 127 | if config is None: 128 | raise FileNotFoundError(f"Config file not found at {config_path}") 129 | 130 | dia = cls(config, compute_dtype, device) 131 | 132 | try: 133 | state_dict = torch.load(checkpoint_path, map_location=dia.device) 134 | dia.model.load_state_dict(state_dict) 135 | except FileNotFoundError: 136 | raise FileNotFoundError(f"Checkpoint file not found at {checkpoint_path}") 137 | except Exception as e: 138 | raise RuntimeError(f"Error loading checkpoint from {checkpoint_path}") from e 139 | 140 | dia.model.to(dia.device) 141 | dia.model.eval() 142 | dia._load_dac_model() 143 | return dia 144 | 145 | @classmethod 146 | def from_pretrained( 147 | cls, 148 | model_name: str = "nari-labs/Dia-1.6B", 149 | compute_dtype: str | ComputeDtype = ComputeDtype.FLOAT32, 150 | device: torch.device | None = None, 151 | ) -> "Dia": 152 | """Loads the Dia model from a Hugging Face Hub repository. 153 | 154 | Downloads the configuration and checkpoint files from the specified 155 | repository ID and then loads the model. 156 | 157 | Args: 158 | model_name: The Hugging Face Hub repository ID (e.g., "NariLabs/Dia-1.6B"). 159 | device: The device to load the model onto. If None, will automatically select the best available device. 160 | 161 | Returns: 162 | An instance of the Dia model loaded with weights and set to eval mode. 163 | 164 | Raises: 165 | FileNotFoundError: If config or checkpoint download/loading fails. 166 | RuntimeError: If there is an error loading the checkpoint. 167 | """ 168 | config_path = hf_hub_download(repo_id=model_name, filename="config.json") 169 | checkpoint_path = hf_hub_download(repo_id=model_name, filename="dia-v0_1.pth") 170 | return cls.from_local(config_path, checkpoint_path, compute_dtype, device) 171 | 172 | def _load_dac_model(self): 173 | try: 174 | dac_model_path = dac.utils.download() 175 | dac_model = dac.DAC.load(dac_model_path).to(self.device) 176 | except Exception as e: 177 | raise RuntimeError("Failed to load DAC model") from e 178 | self.dac_model = dac_model 179 | 180 | def _prepare_text_input(self, text: str) -> torch.Tensor: 181 | """Encodes text prompt, pads, and creates attention mask and positions.""" 182 | text_pad_value = self.config.data.text_pad_value 183 | max_len = self.config.data.text_length 184 | 185 | byte_text = text.encode("utf-8") 186 | replaced_bytes = byte_text.replace(b"[S1]", b"\x01").replace(b"[S2]", b"\x02") 187 | text_tokens = list(replaced_bytes) 188 | 189 | current_len = len(text_tokens) 190 | padding_needed = max_len - current_len 191 | if padding_needed <= 0: 192 | text_tokens = text_tokens[:max_len] 193 | padded_text_np = np.array(text_tokens, dtype=np.uint8) 194 | else: 195 | padded_text_np = np.pad( 196 | text_tokens, 197 | (0, padding_needed), 198 | mode="constant", 199 | constant_values=text_pad_value, 200 | ).astype(np.uint8) 201 | 202 | src_tokens = torch.from_numpy(padded_text_np).to(torch.long).to(self.device).unsqueeze(0) # [1, S] 203 | return src_tokens 204 | 205 | def _prepare_audio_prompt(self, audio_prompt: torch.Tensor | None) -> tuple[torch.Tensor, int]: 206 | num_channels = self.config.data.channels 207 | audio_bos_value = self.config.data.audio_bos_value 208 | audio_pad_value = self.config.data.audio_pad_value 209 | delay_pattern = self.config.data.delay_pattern 210 | max_delay_pattern = max(delay_pattern) 211 | 212 | prefill = torch.full( 213 | (1, num_channels), 214 | fill_value=audio_bos_value, 215 | dtype=torch.int, 216 | device=self.device, 217 | ) 218 | 219 | prefill_step = 1 220 | 221 | if audio_prompt is not None: 222 | prefill_step += audio_prompt.shape[0] 223 | prefill = torch.cat([prefill, audio_prompt], dim=0) 224 | 225 | delay_pad_tensor = torch.full( 226 | (max_delay_pattern, num_channels), fill_value=-1, dtype=torch.int, device=self.device 227 | ) 228 | prefill = torch.cat([prefill, delay_pad_tensor], dim=0) 229 | 230 | delay_precomp = build_delay_indices( 231 | B=1, 232 | T=prefill.shape[0], 233 | C=num_channels, 234 | delay_pattern=delay_pattern, 235 | ) 236 | 237 | prefill = apply_audio_delay( 238 | audio_BxTxC=prefill.unsqueeze(0), 239 | pad_value=audio_pad_value, 240 | bos_value=audio_bos_value, 241 | precomp=delay_precomp, 242 | ).squeeze(0) 243 | 244 | return prefill, prefill_step 245 | 246 | def _prepare_generation(self, text: str, audio_prompt: str | torch.Tensor | None, verbose: bool): 247 | enc_input_cond = self._prepare_text_input(text) 248 | enc_input_uncond = torch.zeros_like(enc_input_cond) 249 | enc_input = torch.cat([enc_input_uncond, enc_input_cond], dim=0) 250 | 251 | if isinstance(audio_prompt, str): 252 | audio_prompt = self.load_audio(audio_prompt) 253 | prefill, prefill_step = self._prepare_audio_prompt(audio_prompt) 254 | 255 | if verbose: 256 | print("generate: data loaded") 257 | 258 | enc_state = EncoderInferenceState.new(self.config, enc_input_cond) 259 | encoder_out = self.model.encoder(enc_input, enc_state) 260 | 261 | dec_cross_attn_cache = self.model.decoder.precompute_cross_attn_cache(encoder_out, enc_state.positions) 262 | dec_state = DecoderInferenceState.new( 263 | self.config, enc_state, encoder_out, dec_cross_attn_cache, self.compute_dtype 264 | ) 265 | dec_output = DecoderOutput.new(self.config, self.device) 266 | dec_output.prefill(prefill, prefill_step) 267 | 268 | dec_step = prefill_step - 1 269 | if dec_step > 0: 270 | dec_state.prepare_step(0, dec_step) 271 | tokens_BxTxC = dec_output.get_tokens_at(0, dec_step).unsqueeze(0).expand(2, -1, -1) 272 | self.model.decoder.forward(tokens_BxTxC, dec_state) 273 | 274 | return dec_state, dec_output 275 | 276 | def _decoder_step( 277 | self, 278 | tokens_Bx1xC: torch.Tensor, 279 | dec_state: DecoderInferenceState, 280 | cfg_scale: float, 281 | temperature: float, 282 | top_p: float, 283 | cfg_filter_top_k: int, 284 | ) -> torch.Tensor: 285 | audio_eos_value = self.config.data.audio_eos_value 286 | logits_Bx1xCxV = self.model.decoder.decode_step(tokens_Bx1xC, dec_state) 287 | 288 | logits_last_BxCxV = logits_Bx1xCxV[:, -1, :, :] 289 | uncond_logits_CxV = logits_last_BxCxV[0, :, :] 290 | cond_logits_CxV = logits_last_BxCxV[1, :, :] 291 | 292 | logits_CxV = cond_logits_CxV + cfg_scale * (cond_logits_CxV - uncond_logits_CxV) 293 | logits_CxV[:, audio_eos_value + 1 :] = -torch.inf 294 | logits_CxV[1:, audio_eos_value:] = -torch.inf 295 | 296 | pred_C = _sample_next_token( 297 | logits_CxV.float(), 298 | temperature=temperature, 299 | top_p=top_p, 300 | cfg_filter_top_k=cfg_filter_top_k, 301 | ) 302 | return pred_C 303 | 304 | def _generate_output(self, generated_codes: torch.Tensor) -> np.ndarray: 305 | num_channels = self.config.data.channels 306 | seq_length = generated_codes.shape[0] 307 | delay_pattern = self.config.data.delay_pattern 308 | audio_pad_value = self.config.data.audio_pad_value 309 | max_delay_pattern = max(delay_pattern) 310 | 311 | revert_precomp = build_revert_indices( 312 | B=1, 313 | T=seq_length, 314 | C=num_channels, 315 | delay_pattern=delay_pattern, 316 | ) 317 | 318 | codebook = revert_audio_delay( 319 | audio_BxTxC=generated_codes.unsqueeze(0), 320 | pad_value=audio_pad_value, 321 | precomp=revert_precomp, 322 | T=seq_length, 323 | )[:, :-max_delay_pattern, :] 324 | 325 | min_valid_index = 0 326 | max_valid_index = 1023 327 | invalid_mask = (codebook < min_valid_index) | (codebook > max_valid_index) 328 | codebook[invalid_mask] = 0 329 | 330 | audio = decode(self.dac_model, codebook.transpose(1, 2)) 331 | 332 | return audio.squeeze().cpu().numpy() 333 | 334 | def load_audio(self, audio_path: str) -> torch.Tensor: 335 | audio, sr = torchaudio.load(audio_path, channels_first=True) # C, T 336 | if sr != DEFAULT_SAMPLE_RATE: 337 | audio = torchaudio.functional.resample(audio, sr, DEFAULT_SAMPLE_RATE) 338 | audio = audio.to(self.device).unsqueeze(0) # 1, C, T 339 | audio_data = self.dac_model.preprocess(audio, DEFAULT_SAMPLE_RATE) 340 | _, encoded_frame, _, _, _ = self.dac_model.encode(audio_data) # 1, C, T 341 | return encoded_frame.squeeze(0).transpose(0, 1) 342 | 343 | def save_audio(self, path: str, audio: np.ndarray): 344 | import soundfile as sf 345 | 346 | sf.write(path, audio, DEFAULT_SAMPLE_RATE) 347 | 348 | @torch.inference_mode() 349 | def generate( 350 | self, 351 | text: str, 352 | max_tokens: int | None = None, 353 | cfg_scale: float = 3.0, 354 | temperature: float = 1.3, 355 | top_p: float = 0.95, 356 | use_torch_compile: bool = False, 357 | cfg_filter_top_k: int = 35, 358 | audio_prompt: str | torch.Tensor | None = None, 359 | audio_prompt_path: str | None = None, 360 | use_cfg_filter: bool | None = None, 361 | verbose: bool = False, 362 | ) -> np.ndarray: 363 | audio_eos_value = self.config.data.audio_eos_value 364 | audio_pad_value = self.config.data.audio_pad_value 365 | delay_pattern = self.config.data.delay_pattern 366 | max_tokens = self.config.data.audio_length if max_tokens is None else max_tokens 367 | max_delay_pattern = max(delay_pattern) 368 | self.model.eval() 369 | 370 | if audio_prompt_path: 371 | print("Warning: audio_prompt_path is deprecated. Use audio_prompt instead.") 372 | audio_prompt = audio_prompt_path 373 | if use_cfg_filter is not None: 374 | print("Warning: use_cfg_filter is deprecated.") 375 | 376 | if verbose: 377 | total_start_time = time.time() 378 | 379 | dec_state, dec_output = self._prepare_generation(text, audio_prompt, verbose) 380 | dec_step = dec_output.prefill_step - 1 381 | 382 | bos_countdown = max_delay_pattern 383 | eos_detected = False 384 | eos_countdown = -1 385 | 386 | if use_torch_compile: 387 | step_fn = torch.compile(self._decoder_step, mode="default") 388 | else: 389 | step_fn = self._decoder_step 390 | 391 | if verbose: 392 | print("generate: starting generation loop") 393 | if use_torch_compile: 394 | print("generate: by using use_torch_compile=True, the first step would take long") 395 | start_time = time.time() 396 | 397 | while dec_step < max_tokens: 398 | dec_state.prepare_step(dec_step) 399 | tokens_Bx1xC = dec_output.get_tokens_at(dec_step).unsqueeze(0).expand(2, -1, -1) 400 | pred_C = step_fn( 401 | tokens_Bx1xC, 402 | dec_state, 403 | cfg_scale, 404 | temperature, 405 | top_p, 406 | cfg_filter_top_k, 407 | ) 408 | 409 | if (not eos_detected and pred_C[0] == audio_eos_value) or dec_step == max_tokens - max_delay_pattern - 1: 410 | eos_detected = True 411 | eos_countdown = max_delay_pattern 412 | 413 | if eos_countdown > 0: 414 | step_after_eos = max_delay_pattern - eos_countdown 415 | for i, d in enumerate(delay_pattern): 416 | if step_after_eos == d: 417 | pred_C[i] = audio_eos_value 418 | elif step_after_eos > d: 419 | pred_C[i] = audio_pad_value 420 | eos_countdown -= 1 421 | 422 | bos_countdown = max(0, bos_countdown - 1) 423 | dec_output.update_one(pred_C, dec_step + 1, bos_countdown > 0) 424 | 425 | if eos_countdown == 0: 426 | break 427 | 428 | dec_step += 1 429 | if verbose and dec_step % 86 == 0: 430 | duration = time.time() - start_time 431 | print( 432 | f"generate step {dec_step}: speed={86 / duration:.3f} tokens/s, realtime factor={1 / duration:.3f}x" 433 | ) 434 | start_time = time.time() 435 | 436 | if dec_output.prefill_step >= dec_step + 1: 437 | print("Warning: Nothing generated") 438 | return None 439 | 440 | generated_codes = dec_output.generated_tokens[dec_output.prefill_step : dec_step + 1, :] 441 | 442 | if verbose: 443 | total_step = dec_step + 1 - dec_output.prefill_step 444 | total_duration = time.time() - total_start_time 445 | print(f"generate: total step={total_step}, total duration={total_duration:.3f}s") 446 | 447 | return self._generate_output(generated_codes) 448 | -------------------------------------------------------------------------------- /dia/state.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | import torch 4 | 5 | from .config import DiaConfig 6 | 7 | 8 | def create_attn_mask( 9 | q_padding_mask_1d: torch.Tensor, 10 | k_padding_mask_1d: torch.Tensor, 11 | device: torch.device, 12 | is_causal: bool = False, 13 | ) -> torch.Tensor: 14 | """ 15 | Creates the attention mask (self or cross) mimicking JAX segment ID logic. 16 | """ 17 | B1, Tq = q_padding_mask_1d.shape 18 | B2, Tk = k_padding_mask_1d.shape 19 | assert B1 == B2, "Query and key batch dimensions must match" 20 | 21 | p_mask_q = q_padding_mask_1d.unsqueeze(2) # Shape [B, Tq, 1] 22 | p_mask_k = k_padding_mask_1d.unsqueeze(1) # Shape [B, 1, Tk] 23 | 24 | # Condition A: Non-padding query attends to non-padding key 25 | non_pad_attends_non_pad = p_mask_q & p_mask_k # Shape [B, Tq, Tk] 26 | 27 | # Condition B: Padding query attends to padding key 28 | pad_attends_pad = (~p_mask_q) & (~p_mask_k) # Shape [B, Tq, Tk] 29 | 30 | # Combine: True if padding status is compatible (both non-pad OR both pad) 31 | mask = non_pad_attends_non_pad | pad_attends_pad # Shape [B, Tq, Tk] 32 | 33 | if is_causal: 34 | assert Tq == Tk, "Causal mask requires query and key sequence lengths to be equal" 35 | causal_mask_2d = torch.tril(torch.ones((Tq, Tk), dtype=torch.bool, device=device)) # Shape [Tq, Tk] 36 | causal_mask = mask & causal_mask_2d # Shape [B, Tq, Tk] 37 | return causal_mask.unsqueeze(1) # Shape [B, 1, Tq, Tk] 38 | else: 39 | return mask.unsqueeze(1) # Shape [B, 1, Tq, Tk] 40 | 41 | 42 | @dataclass 43 | class EncoderInferenceState: 44 | """Parameters specifically for encoder inference.""" 45 | 46 | max_seq_len: int 47 | device: torch.device 48 | positions: torch.Tensor 49 | padding_mask: torch.Tensor 50 | attn_mask: torch.Tensor 51 | 52 | @classmethod 53 | def new(cls, config: DiaConfig, cond_src: torch.Tensor) -> "EncoderInferenceState": 54 | """Creates EtorchrInferenceParams from DiaConfig and a device.""" 55 | device = cond_src.device 56 | 57 | positions = torch.arange(config.data.text_length, device=device).to(torch.long).unsqueeze(0).expand(2, -1) 58 | padding_mask = (cond_src != config.data.text_pad_value).to(device).expand(2, -1) 59 | attn_mask = create_attn_mask(padding_mask, padding_mask, device, is_causal=False) 60 | 61 | return cls( 62 | max_seq_len=config.data.text_length, 63 | device=device, 64 | positions=positions, 65 | padding_mask=padding_mask, 66 | attn_mask=attn_mask, 67 | ) 68 | 69 | 70 | class KVCache: 71 | def __init__( 72 | self, 73 | num_heads: int, 74 | max_len: int, 75 | head_dim: int, 76 | dtype: torch.dtype, 77 | device: torch.device, 78 | k: torch.Tensor | None = None, 79 | v: torch.Tensor | None = None, 80 | ): 81 | self.k = torch.zeros((2, num_heads, max_len, head_dim), dtype=dtype, device=device) if k is None else k 82 | self.v = torch.zeros((2, num_heads, max_len, head_dim), dtype=dtype, device=device) if v is None else v 83 | self.current_idx = torch.tensor(0) 84 | 85 | @classmethod 86 | def from_kv(cls, k: torch.Tensor, v: torch.Tensor) -> "KVCache": 87 | return cls( 88 | num_heads=k.shape[1], 89 | max_len=k.shape[2], 90 | head_dim=k.shape[3], 91 | dtype=k.dtype, 92 | device=k.device, 93 | k=k, 94 | v=v, 95 | ) 96 | 97 | def update(self, k: torch.Tensor, v: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: 98 | self.k[:, :, self.current_idx : self.current_idx + 1, :] = k 99 | self.v[:, :, self.current_idx : self.current_idx + 1, :] = v 100 | self.current_idx += 1 101 | return self.k[:, :, : self.current_idx, :], self.v[:, :, : self.current_idx, :] 102 | 103 | def prefill(self, k: torch.Tensor, v: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: 104 | prefill_len = k.shape[2] 105 | self.k[:, :, :prefill_len, :] = k 106 | self.v[:, :, :prefill_len, :] = v 107 | self.current_idx = prefill_len - 1 108 | 109 | 110 | @dataclass 111 | class DecoderInferenceState: 112 | """Parameters specifically for decoder inference.""" 113 | 114 | device: torch.device 115 | dtype: torch.dtype 116 | enc_out: torch.Tensor 117 | enc_positions: torch.Tensor 118 | dec_positions: torch.Tensor 119 | dec_cross_attn_mask: torch.Tensor 120 | self_attn_cache: list[KVCache] 121 | cross_attn_cache: list[KVCache] 122 | 123 | @classmethod 124 | def new( 125 | cls, 126 | config: DiaConfig, 127 | enc_state: EncoderInferenceState, 128 | enc_out: torch.Tensor, 129 | dec_cross_attn_cache: list[KVCache], 130 | compute_dtype: torch.dtype, 131 | ) -> "DecoderInferenceState": 132 | """Creates DecoderInferenceParams from DiaConfig and a device.""" 133 | device = enc_out.device 134 | max_audio_len = config.data.audio_length 135 | 136 | dec_positions = torch.full((2, 1), fill_value=0, dtype=torch.long, device=device) 137 | tgt_padding_mask = torch.ones((2, 1), dtype=torch.bool, device=device) 138 | dec_cross_attn_mask = create_attn_mask(tgt_padding_mask, enc_state.padding_mask, device, is_causal=False) 139 | 140 | self_attn_cache = [ 141 | KVCache( 142 | config.model.decoder.kv_heads, 143 | max_audio_len, 144 | config.model.decoder.gqa_head_dim, 145 | compute_dtype, 146 | device, 147 | ) 148 | for _ in range(config.model.decoder.n_layer) 149 | ] 150 | 151 | return cls( 152 | device=device, 153 | dtype=compute_dtype, 154 | enc_out=enc_out, 155 | enc_positions=enc_state.positions, 156 | dec_positions=dec_positions, 157 | dec_cross_attn_mask=dec_cross_attn_mask, 158 | self_attn_cache=self_attn_cache, 159 | cross_attn_cache=dec_cross_attn_cache, 160 | ) 161 | 162 | def prepare_step(self, step_from: int, step_to: int | None = None) -> None: 163 | if step_to is None: 164 | step_to = step_from + 1 165 | self.dec_positions = torch.arange(step_from, step_to, device=self.device).unsqueeze(0).expand(2, -1) 166 | 167 | 168 | @dataclass 169 | class DecoderOutput: 170 | generated_tokens: torch.Tensor 171 | prefill_step: int 172 | 173 | @classmethod 174 | def new(cls, config: DiaConfig, device: torch.device) -> "DecoderOutput": 175 | max_audio_len = config.data.audio_length 176 | return cls( 177 | generated_tokens=torch.full( 178 | (max_audio_len, config.data.channels), 179 | fill_value=-1, 180 | dtype=torch.int, 181 | device=device, 182 | ), 183 | prefill_step=0, 184 | ) 185 | 186 | def get_tokens_at(self, step_from: int, step_to: int | None = None) -> torch.Tensor: 187 | if step_to is None: 188 | step_to = step_from + 1 189 | return self.generated_tokens[step_from:step_to, :] 190 | 191 | def update_one(self, dec_out: torch.Tensor, step: int, apply_mask: bool = False): 192 | if apply_mask: 193 | mask = self.generated_tokens[step : step + 1, :] == -1 194 | self.generated_tokens[step : step + 1, :] = torch.where( 195 | mask, dec_out, self.generated_tokens[step : step + 1, :] 196 | ) 197 | else: 198 | self.generated_tokens[step : step + 1, :] = dec_out 199 | 200 | def prefill(self, dec_out: torch.Tensor, prefill_step: int): 201 | length = dec_out.shape[0] 202 | self.generated_tokens[0:length, :] = dec_out 203 | self.prefill_step = prefill_step 204 | -------------------------------------------------------------------------------- /dia/static/images/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nari-labs/dia/355a2a849d468630e88895196a6fd648849611f6/dia/static/images/banner.png -------------------------------------------------------------------------------- /docker/Dockerfile.cpu: -------------------------------------------------------------------------------- 1 | # Dockerfile.cpu - CPU-only deployment for DIA 2 | # -------------------------------------------------- 3 | # Build: docker build . -f docker/Dockerfile.cpu -t dia-cpu 4 | # Run: docker run --rm -p 7860:7860 dia-cpu 5 | 6 | FROM python:3.10-slim 7 | 8 | # Set non-interactive frontend 9 | ENV DEBIAN_FRONTEND=noninteractive 10 | 11 | # Install venv, and system dependencies 12 | RUN apt-get update && apt-get install -y \ 13 | python3-venv \ 14 | libsndfile1 \ 15 | ffmpeg \ 16 | curl \ 17 | && apt-get clean && rm -rf /var/lib/apt/lists/* 18 | 19 | # Create non-root user and set up directories 20 | RUN useradd -m -u 1001 appuser && \ 21 | mkdir -p /app/outputs /app && \ 22 | chown -R appuser:appuser /app 23 | 24 | USER appuser 25 | WORKDIR /app 26 | 27 | # Copy all code (including pyproject.toml) 28 | COPY --chown=appuser:appuser . . 29 | 30 | # Create and activate virtual environment 31 | RUN python3 -m venv /app/venv 32 | ENV PATH="/app/venv/bin:$PATH" 33 | 34 | # Install all project dependencies (CPU-only PyTorch) 35 | RUN pip install --upgrade pip && \ 36 | pip install torch torchaudio --index-url https://download.pytorch.org/whl/cpu && \ 37 | pip install --no-cache-dir -e .[dev] 38 | 39 | # Set environment variables 40 | ENV PYTHONUNBUFFERED=1 \ 41 | PYTHONPATH=/app 42 | 43 | # Expose Gradio default port 44 | ENV GRADIO_SERVER_NAME="0.0.0.0" 45 | EXPOSE 7860 46 | 47 | # Entrypoint 48 | CMD ["python3", "app.py"] 49 | -------------------------------------------------------------------------------- /docker/Dockerfile.gpu: -------------------------------------------------------------------------------- 1 | # Dockerfile.gpu - GPU deployment for DIA 2 | # -------------------------------------------------- 3 | # Build: docker build . -f docker/Dockerfile.gpu -t dia-gpu 4 | # Run: docker run --rm --gpus all -p 7860:7860 dia-gpu 5 | # Requires NVIDIA Container Toolkit on host. 6 | 7 | FROM pytorch/pytorch:2.1.2-cuda12.1-cudnn8-runtime 8 | 9 | # Set non-interactive frontend 10 | ENV DEBIAN_FRONTEND=noninteractive 11 | 12 | # Install venv, and system dependencies 13 | RUN apt-get update && apt-get install -y \ 14 | python3-venv \ 15 | libsndfile1 \ 16 | ffmpeg \ 17 | curl \ 18 | && apt-get clean && rm -rf /var/lib/apt/lists/* 19 | 20 | # Create non-root user and set up directories 21 | RUN useradd -m -u 1001 appuser && \ 22 | mkdir -p /app/outputs /app && \ 23 | chown -R appuser:appuser /app 24 | 25 | USER appuser 26 | WORKDIR /app 27 | 28 | # Copy all code (including pyproject.toml) 29 | COPY --chown=appuser:appuser . . 30 | 31 | # Create and activate virtual environment 32 | RUN python3 -m venv /app/venv 33 | ENV PATH="/app/venv/bin:$PATH" 34 | 35 | # Install all project dependencies 36 | RUN pip install --upgrade pip && pip install --no-cache-dir . 37 | 38 | # Set environment variables 39 | ENV PYTHONUNBUFFERED=1 \ 40 | PYTHONPATH=/app \ 41 | USE_GPU=true \ 42 | LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/local/cuda-12.1/lib64:${LD_LIBRARY_PATH} 43 | 44 | # Expose Gradio default port 45 | ENV GRADIO_SERVER_NAME="0.0.0.0" 46 | EXPOSE 7860 47 | 48 | # Entrypoint 49 | CMD ["python3", "app.py"] 50 | -------------------------------------------------------------------------------- /example/simple.py: -------------------------------------------------------------------------------- 1 | from dia.model import Dia 2 | 3 | 4 | model = Dia.from_pretrained("nari-labs/Dia-1.6B", compute_dtype="float16") 5 | 6 | text = "[S1] Dia is an open weights text to dialogue model. [S2] You get full control over scripts and voices. [S1] Wow. Amazing. (laughs) [S2] Try it now on Git hub or Hugging Face." 7 | 8 | output = model.generate(text, use_torch_compile=True, verbose=True) 9 | 10 | model.save_audio("simple.mp3", output) 11 | -------------------------------------------------------------------------------- /example/voice_clone.py: -------------------------------------------------------------------------------- 1 | from dia.model import Dia 2 | 3 | 4 | model = Dia.from_pretrained("nari-labs/Dia-1.6B", compute_dtype="float16") 5 | 6 | # You should put the transcript of the voice you want to clone 7 | # We will use the audio created by running simple.py as an example. 8 | # Note that you will be REQUIRED TO RUN simple.py for the script to work as-is. 9 | clone_from_text = "[S1] Dia is an open weights text to dialogue model. [S2] You get full control over scripts and voices. [S1] Wow. Amazing. (laughs) [S2] Try it now on Git hub or Hugging Face." 10 | clone_from_audio = "simple.mp3" 11 | 12 | # For your custom needs, replace above with below and add your audio file to this directory: 13 | # clone_from_text = "[S1] ... [S2] ... [S1] ... corresponding to your_audio_name.mp3" 14 | # clone_from_audio = "your_audio_name.mp3" 15 | 16 | # Text to generate 17 | text_to_generate = "[S1] Hello, how are you? [S2] I'm good, thank you. [S1] What's your name? [S2] My name is Dia. [S1] Nice to meet you. [S2] Nice to meet you too." 18 | 19 | # It will only return the audio from the text_to_generate 20 | output = model.generate( 21 | clone_from_text + text_to_generate, audio_prompt=clone_from_audio, use_torch_compile=True, verbose=True 22 | ) 23 | 24 | model.save_audio("voice_clone.mp3", output) 25 | -------------------------------------------------------------------------------- /example_prompt.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nari-labs/dia/355a2a849d468630e88895196a6fd648849611f6/example_prompt.mp3 -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "nari-tts" 3 | version = "0.1.0" 4 | description = "Dia - A text-to-speech model for dialogue generation" 5 | readme = "README.md" 6 | requires-python = ">=3.10" 7 | license = {file = "LICENSE"} 8 | authors = [ 9 | {name = "Nari Labs", email = "contact@narilabs.ai"} 10 | ] 11 | dependencies = [ 12 | "descript-audio-codec>=1.0.0", 13 | "gradio>=5.25.2", 14 | "huggingface-hub>=0.30.2", 15 | "numpy>=2.2.4", 16 | "pydantic>=2.11.3", 17 | "soundfile>=0.13.1", 18 | "torch>=2.6.0", 19 | "torchaudio>=2.6.0", 20 | "triton>=3.2.0 ; sys_platform == 'linux'", 21 | "triton-windows>=3.2.0.post18 ; sys_platform == 'win32'", 22 | ] 23 | 24 | [build-system] 25 | requires = ["hatchling"] 26 | build-backend = "hatchling.build" 27 | 28 | [project.urls] 29 | "Homepage" = "https://github.com/nari-labs/dia" 30 | "Bug Tracker" = "https://github.com/nari-labs/dia/issues" 31 | 32 | [tool.hatch.build.targets.wheel] 33 | packages = ["dia"] 34 | 35 | [tool.ruff] 36 | # Never enforce `E501` (line length violations). 37 | lint.ignore = ["C901", "E501", "E741", "W605"] 38 | lint.select = ["C", "E", "F", "I", "W"] 39 | line-length = 119 40 | 41 | # Ignore import violations in all `__init__.py` files. 42 | [tool.ruff.lint.per-file-ignores] 43 | "__init__.py" = ["E402", "F401", "F403", "F811"] 44 | 45 | [tool.ruff.lint.isort] 46 | lines-after-imports = 2 47 | 48 | [tool.uv.sources] 49 | torch = [ 50 | { index = "pytorch-cu126", marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, 51 | ] 52 | torchaudio = [ 53 | { index = "pytorch-cu126", marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, 54 | ] 55 | 56 | [[tool.uv.index]] 57 | name = "pytorch-cu126" 58 | url = "https://download.pytorch.org/whl/cu126" 59 | explicit = true 60 | --------------------------------------------------------------------------------