[
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Unit Test\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n  lint:\n    name: Lint\n    runs-on: ubuntu-22.04\n    steps:\n      - name: Checkout code \n        uses: actions/checkout@v4\n\n      - name: Check Code Formatting with Ruff\n        run: |\n            echo \"python version: $(python --version)\"\n            pip install ruff==0.12.2  # Ensure ruff is installed\n            ruff format --check .\n"
  },
  {
    "path": ".gitignore",
    "content": "# Temporary files generated in training\ndpo_samples*\nscoring_results\nresults/\nhf_slurm_logs/\nslurm_results/\nenroot_images/\nslurm*.out\ncache_*\nmlruns/\nlocal_download_dir/\naudioverse/data\n# the folder pattern is sft_{year}.\nsft_20*\ndata/\naudioverse/cache\n# vim ipython plugin generated files\n.jukit\n\n# node\nnode_modules\npackage.json\npackage-lock.json\n\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\n!tests/*\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n/.conda_env*\n/.env*\n/.higgs_audio_env*\n/.venv*\n/conda_env*\n/env*\n/ENV*\n/higgs_audio_env*\n/venv*\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n#.idea/\n\n*.jsonl\ndownload\n.DS_Store\n*entry.py\n\n# Pytorch\ntorch_compile_debug/\n\n# Out Dir\nresult/\n\n# Ruff\n.ruff_cache/"
  },
  {
    "path": ".gitmodules",
    "content": ""
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability."
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\">Higgs Audio: Redefining Expressiveness in Audio Generation</h1>\n\n<div align=\"center\" style=\"display: flex; justify-content: center; margin-top: 10px;\">\n  <a href=\"https://boson.ai/blog/higgs-audio-v2\"><img src='https://img.shields.io/badge/🚀-V2 Blogpost-228B22' style=\"margin-right: 5px;\"></a>\n  <a href=\"https://www.boson.ai/blog/higgs-audio-v2.5\"><img src='https://img.shields.io/badge/🚀-V2.5 Blogpost-228B22' style=\"margin-right: 5px;\"></a>\n  <a href=\"https://boson.ai/demo/tts\"><img src=\"https://img.shields.io/badge/🕹️-Boson%20AI%20Playground-9C276A\" style=\"margin-right: 5px;\"></a>\n  <a href=\"https://huggingface.co/spaces/smola/higgs_audio_v2\"><img src=\"https://img.shields.io/badge/🎮-HF%20Space%20Playground-8A2BE2\" style=\"margin-right: 5px;\"></a>\n  <a href=\"https://huggingface.co/bosonai/higgs-audio-v2-generation-3B-base\"><img src=\"https://img.shields.io/badge/🤗-Checkpoints (3.6B LLM + 2.2B audio adapter)-ED5A22.svg\" style=\"margin-right: 5px;\"></a>\n</div>\n\n## NEWS！\n\nWe are proud to launch **Higgs-Audio V2.5**, the latest iteration of Boson AI’s Audio model, designed to bring high-fidelity generation into production environments. Building on Higgs-Audio V2, this release combines improved efficiency with the stability required for real-world deployment.\n\nWith V2.5, we condensed the model architecture to 1B parameters while surpassing speed and accuracy of the prior 3B model. The result is achieved through a new alignment strategy using Group Relative Policy Optimization (GRPO) on our curated Voice Bank dataset, combined with improved voice cloning and finer-grained style control.\n\nFor detailed model performance, key improvements, and usage, please check our [blog](https://www.boson.ai/blog/higgs-audio-v2.5).\n\n\n## Higgs Audio V2\n\n\nWe are open-sourcing Higgs Audio v2, a powerful audio foundation model pretrained on over 10 million hours of audio data and a diverse set of text data. Despite having no post-training or fine-tuning, Higgs Audio v2 excels in expressive audio generation, thanks to its deep language and acoustic understanding.\n\nOn [EmergentTTS-Eval](https://github.com/boson-ai/emergenttts-eval-public), it achieves win rates of **75.7%** and **55.7%** over \"gpt-4o-mini-tts\" on the \"Emotions\" and \"Questions\" categories, respectively. It also obtains state-of-the-art performance on traditional TTS benchmarks like Seed-TTS Eval and Emotional Speech Dataset (ESD). Moreover, the model demonstrates capabilities rarely seen in previous systems, including generating natural multi-speaker dialogues in multiple languages, automatic prosody adaptation during narration, melodic humming with the cloned voice, and simultaneous generation of speech and background music.\n\n<p align=\"center\">\n    <img src=\"figures/emergent-tts-emotions-win-rate.png\" width=900>\n</p>\n\nHere's the demo video that shows some of its emergent capabilities (remember to unmute):\n\n<video src=\"https://github.com/user-attachments/assets/0fd73fad-097f-48a9-9f3f-bc2a63b3818d\" type=\"video/mp4\" width=\"80%\" controls>\n</video>\n\nHere's another demo video that show-cases the model's multilingual capability and how it enabled live translation (remember to unmute):\n\n<video src=\"https://github.com/user-attachments/assets/2b9b01ff-67fc-4bd9-9714-7c7df09e38d6\" type=\"video/mp4\" width=\"80%\" controls>\n</video>\n\n## Installation\n\nWe recommend to use NVIDIA Deep Learning Container to manage the CUDA environment. Following are two docker images that we have verified:\n- nvcr.io/nvidia/pytorch:25.02-py3\n- nvcr.io/nvidia/pytorch:25.01-py3\n\nHere's an example command for launching a docker container environment. Please also check the [official NVIDIA documentations](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/pytorch).\n\n```bash\ndocker run --gpus all --ipc=host --net=host --ulimit memlock=-1 --ulimit stack=67108864 -it --rm nvcr.io/nvidia/pytorch:25.02-py3 bash\n```\n\n### Option 1: Direct installation\n\n\n```bash\ngit clone https://github.com/boson-ai/higgs-audio.git\ncd higgs-audio\n\npip install -r requirements.txt\npip install -e .\n```\n\n### Option 2: Using venv\n\n```bash\ngit clone https://github.com/boson-ai/higgs-audio.git\ncd higgs-audio\n\npython3 -m venv higgs_audio_env\nsource higgs_audio_env/bin/activate\npip install -r requirements.txt\npip install -e .\n```\n\n\n### Option 3: Using conda\n```bash\ngit clone https://github.com/boson-ai/higgs-audio.git\ncd higgs-audio\n\nconda create -y --prefix ./conda_env --override-channels --strict-channel-priority --channel \"conda-forge\" \"python==3.10.*\"\nconda activate ./conda_env\npip install -r requirements.txt\npip install -e .\n\n# Uninstalling environment:\nconda deactivate\nconda remove -y --prefix ./conda_env --all\n```\n\n### Option 4: Using uv\n```bash\ngit clone https://github.com/boson-ai/higgs-audio.git\ncd higgs-audio\n\nuv venv --python 3.10\nsource .venv/bin/activate\nuv pip install -r requirements.txt\nuv pip install -e .\n```\n\n### Option 5: Using vllm\n\nFor advanced usage with higher throughput, we also built OpenAI compatible API server backed by vLLM engine for you to use.\nPlease refer to [examples/vllm](./examples/vllm) for more details.\n\n\n## Usage\n\n> [!TIP]\n> For optimal performance, run the generation examples on a machine equipped with GPU with at least 24GB memory!\n\n### Get Started\n\nHere's a basic python snippet to help you get started.\n\n```python\nfrom boson_multimodal.serve.serve_engine import HiggsAudioServeEngine, HiggsAudioResponse\nfrom boson_multimodal.data_types import ChatMLSample, Message, AudioContent\n\nimport torch\nimport torchaudio\nimport time\nimport click\n\nMODEL_PATH = \"bosonai/higgs-audio-v2-generation-3B-base\"\nAUDIO_TOKENIZER_PATH = \"bosonai/higgs-audio-v2-tokenizer\"\n\nsystem_prompt = (\n    \"Generate audio following instruction.\\n\\n<|scene_desc_start|>\\nAudio is recorded from a quiet room.\\n<|scene_desc_end|>\"\n)\n\nmessages = [\n    Message(\n        role=\"system\",\n        content=system_prompt,\n    ),\n    Message(\n        role=\"user\",\n        content=\"The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.\",\n    ),\n]\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\nserve_engine = HiggsAudioServeEngine(MODEL_PATH, AUDIO_TOKENIZER_PATH, device=device)\n\noutput: HiggsAudioResponse = serve_engine.generate(\n    chat_ml_sample=ChatMLSample(messages=messages),\n    max_new_tokens=1024,\n    temperature=0.3,\n    top_p=0.95,\n    top_k=50,\n    stop_strings=[\"<|end_of_text|>\", \"<|eot_id|>\"],\n)\ntorchaudio.save(f\"output.wav\", torch.from_numpy(output.audio)[None, :], output.sampling_rate)\n```\n\nWe also provide a list of examples under [examples](./examples). In the following we highlight a few examples to help you use Higgs Audio v2.\n\n### Zero-Shot Voice Cloning\nGenerate audio that sounds similar as the provided [reference audio](./examples/voice_prompts/belinda.wav).\n\n```bash\npython3 examples/generation.py \\\n--transcript \"The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.\" \\\n--ref_audio belinda \\\n--temperature 0.3 \\\n--out_path generation.wav\n```\n\nThe generation script will automatically use `cuda:0` if it founds cuda is available. To change the device id, specify `--device_id`:\n\n```bash\npython3 examples/generation.py \\\n--transcript \"The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.\" \\\n--ref_audio belinda \\\n--temperature 0.3 \\\n--device_id 0 \\\n--out_path generation.wav\n```\n\nYou can also try other voices. Check more example voices in [examples/voice_prompts](./examples/voice_prompts). You can also add your own voice to the folder.\n\n```bash\npython3 examples/generation.py \\\n--transcript \"The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.\" \\\n--ref_audio broom_salesman \\\n--temperature 0.3 \\\n--out_path generation.wav\n```\n\n### Single-speaker Generation with Smart Voice\nIf you do not specify reference voice, the model will decide the voice based on the transcript it sees.\n\n```bash\npython3 examples/generation.py \\\n--transcript \"The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.\" \\\n--temperature 0.3 \\\n--out_path generation.wav\n```\n\n\n### Multi-speaker Dialog with Smart Voice\nGenerate multi-speaker dialog. The model will decide the voices based on the transcript it sees.\n\n```bash\npython3 examples/generation.py \\\n--transcript examples/transcript/multi_speaker/en_argument.txt \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n### Multi-speaker Dialog with Voice Clone\n\nGenerate multi-speaker dialog with the voices you picked.\n\n```bash\npython3 examples/generation.py \\\n--transcript examples/transcript/multi_speaker/en_argument.txt \\\n--ref_audio belinda,broom_salesman \\\n--ref_audio_in_system_message \\\n--chunk_method speaker \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n\n## Technical Details\n<img src=\"figures/higgs_audio_v2_architecture_combined.png\" width=900>\n\n\nHiggs Audio v2 adopts the \"generation variant\" depicted in the architecture figure above. Its strong performance is driven by three key technical innovations:\n- We developed an automated annotation pipeline that leverages multiple ASR models, sound event classification models, and our in-house audio understanding model. Using this pipeline, we cleaned and annotated 10 million hours audio data, which we refer to as **AudioVerse**. The in-house understanding model is finetuned on top of [Higgs Audio v1 Understanding](https://www.boson.ai/blog/higgs-audio), which adopts the \"understanding variant\" shown in the architecture figure.\n- We trained a unified audio tokenizer from scratch that captures both semantic and acoustic features. We also open-sourced our evaluation set on [HuggingFace](https://huggingface.co/datasets/bosonai/AudioTokenBench). Learn more in the [tokenizer blog](./tech_blogs/TOKENIZER_BLOG.md).\n- We proposed the DualFFN architecture, which enhances the LLM’s ability to model acoustics tokens with minimal computational overhead. See the [architecture blog](./tech_blogs/ARCHITECTURE_BLOG.md).\n\n## Evaluation\n\nHere's the performance of Higgs Audio v2 on four benchmarks,  [Seed-TTS Eval](https://github.com/BytedanceSpeech/seed-tts-eval), [Emotional Speech Dataset (ESD)](https://paperswithcode.com/dataset/esd), [EmergentTTS-Eval](https://arxiv.org/abs/2505.23009), and Multi-speaker Eval:\n\n#### Seed-TTS Eval & ESD\n\nWe prompt Higgs Audio v2 with the reference text, reference audio, and target text for zero-shot TTS. We use the standard evaluation metrics from Seed-TTS Eval and ESD.\n\n|                              | SeedTTS-Eval| | ESD   |                 |\n|------------------------------|--------|--------|---------|-------------------|\n|                              | WER ↓ | SIM ↑ | WER ↓ | SIM (emo2vec) ↑ |\n| Cosyvoice2                   | 2.28   | 65.49  | 2.71    | 80.48             |\n| Qwen2.5-omni†                | 2.33   | 64.10  | -       | -                 |\n| ElevenLabs Multilingual V2   | **1.43**   | 50.00  | 1.66    | 65.87             |\n| Higgs Audio v1                | 2.18   | 66.27  | **1.49**    | 82.84             |\n| Higgs Audio v2 (base)         | 2.44   | **67.70**  | 1.78    | **86.13**         |\n\n\n#### EmergentTTS-Eval (\"Emotions\" and \"Questions\")\n\nFollowing the [EmergentTTS-Eval Paper](https://arxiv.org/abs/2505.23009), we report the win-rate over \"gpt-4o-mini-tts\" with the \"alloy\" voice. The judge model is Gemini 2.5 Pro.\n\n| Model                              | Emotions (%) ↑ | Questions (%) ↑ |\n|------------------------------------|--------------|----------------|\n| Higgs Audio v2 (base)               | **75.71%**   | **55.71%**         |\n| [gpt-4o-audio-preview†](https://platform.openai.com/docs/models/gpt-4o-audio-preview)       | 61.64%       | 47.85%         |\n| [Hume.AI](https://www.hume.ai/research)                            | 61.60%       | 43.21%         |\n| **BASELINE:** [gpt-4o-mini-tts](https://platform.openai.com/docs/models/gpt-4o-mini-tts)  | 50.00%       | 50.00%         |\n| [Qwen 2.5 Omni†](https://github.com/QwenLM/Qwen2.5-Omni)      | 41.60%       | 51.78%         |\n| [minimax/speech-02-hd](https://replicate.com/minimax/speech-02-hd)               | 40.86%        | 47.32%         |\n| [ElevenLabs Multilingual v2](https://elevenlabs.io/blog/eleven-multilingual-v2)         | 30.35%       | 39.46%         |\n| [DeepGram Aura-2](https://deepgram.com/learn/introducing-aura-2-enterprise-text-to-speech)                    | 29.28%       | 48.21%         |\n| [Sesame csm-1B](https://github.com/SesameAILabs/csm)                      | 15.96%       | 31.78%         |\n\n<sup><sub>'†' means using the strong-prompting method described in the paper.</sub></sup>\n\n\n#### Multi-speaker Eval\n\nWe also designed a multi-speaker evaluation benchmark to evaluate the capability of Higgs Audio v2 for multi-speaker dialog generation. The benchmark contains three subsets\n\n- `two-speaker-conversation`: 1000 synthetic dialogues involving two speakers. We fix two reference audio clips to evaluate the model's ability in double voice cloning for utterances ranging from 4 to 10 dialogues between two randomly chosen persona.\n- `small talk (no ref)`: 250 synthetic dialogues curated in the same way as above, but are characterized by short utterances and a limited number of turns (4–6), we do not fix reference audios in this case and this set is designed to evaluate the model's ability to automatically assign appropriate voices to speakers.\n- `small talk (ref)`: 250 synthetic dialogues similar to above, but contains even shorter utterances as this set is meant to include reference clips in it's context, similar to `two-speaker-conversation`.\n\n\nWe report the word-error-rate (WER) and the geometric mean between intra-speaker similarity and inter-speaker dis-similarity on these three subsets. Other than Higgs Audio v2, we also evaluated [MoonCast](https://github.com/jzq2000/MoonCast) and [nari-labs/Dia-1.6B-0626](https://huggingface.co/nari-labs/Dia-1.6B-0626), two of the most popular open-source models capable of multi-speaker dialog generation. Results are summarized in the following table. We are not able to run [nari-labs/Dia-1.6B-0626](https://huggingface.co/nari-labs/Dia-1.6B-0626) on our \"two-speaker-conversation\" subset due to its strict limitation on the length of the utterances and output audio.\n\n|                                                | two-speaker-conversation |                |small talk |                | small talk (no ref) |                |\n| ---------------------------------------------- | -------------- | ------------------ | ---------- | -------------- | ------------------- | -------------- |\n|                                                | WER ↓                      | Mean Sim & Dis-sim ↑ | WER ↓       |  Mean Sim & Dis-sim ↑ | WER ↓               | Mean Sim & Dis-sim ↑ |\n| [MoonCast](https://github.com/jzq2000/MoonCast) | 38.77                    | 46.02         | **8.33**       | 63.68          | 24.65               | 53.94 |\n| [nari-labs/Dia-1.6B-0626](https://huggingface.co/nari-labs/Dia-1.6B-0626)         | \\-                       | \\-             | 17.62      | 63.15          | 19.46               | **61.14**          |\n| Higgs Audio v2 (base)     | **18.88**                    | **51.95**          | 11.89      | **67.92**              | **14.65**               | 55.28              |\n\n## Contribution and Support\n\nFor contribution and support guidelines, please see the support guidelines at [SUPPORT_GUIDELINES.md](SUPPORT_GUIDELINES.md).\n\n## Citation\n\nIf you feel the repository is helpful, please kindly cite as:\n\n```\n@misc{higgsaudio2025,\n  author       = {{Boson AI}},\n  title        = {{Higgs Audio V2: Redefining Expressiveness in Audio Generation}},\n  year         = {2025},\n  howpublished = {\\url{https://github.com/boson-ai/higgs-audio}},\n  note         = {GitHub repository. Release blog available at \\url{https://www.boson.ai/blog/higgs-audio-v2}},\n}\n```\n\n## Third-Party Licenses\n\nThe `boson_multimodal/audio_processing/` directory contains code derived from third-party repositories, primarily from [xcodec](https://github.com/zhenye234/xcodec). Please see the [`LICENSE`](boson_multimodal/audio_processing/LICENSE) in that directory for complete attribution and licensing information.\n\n## We Are Hiring!\n\nIf you are passionate about multimodal AI, speech/audio models, or large-scale systems, \ncheck out our open positions at [Boson AI Careers](https://jobs.lever.co/bosonai).\n"
  },
  {
    "path": "SUPPORT_GUIDELINES.md",
    "content": "# Contribution & Support Guidelines\n\nThank you for your interest in this project! Before opening an issue, please take a moment to read the following guidelines:\n\n## Self-Check First\n- Write your question in **English** or include an English translation so the community can understand and assist you better.\n- Verify that you have **installed the correct version** of the package.\n- Check the GitHub [README](README.md), [Hugging Face Space](https://huggingface.co/spaces/smola/higgs_audio_v2), [Model Card](https://huggingface.co/bosonai/higgs-audio-v2-generation-3B-base) and existing issues — many questions already have answers.\n- Ensure your problem can be **reproduced** and is directly related to this project.\n\n## Asking Properly\n- Provide **clear reproduction steps / minimal code examples / error logs**.\n- Keep the issue title **concise and descriptive**, and include enough context in the body.\n- Avoid vague questions like *“It doesn’t work, what should I do?”* or *“Can you debug this for me?”*.\n\n## About Support\n- This is a **community-driven open source project**. Maintainers will respond when time allows.\n- There is **no obligation** to answer every request — please be patient and understanding.\n- For more reliable or timely support, consider:\n  - Submitting a **Pull Request** to improve code or documentation.\n  - Providing detailed context so that the community can help.\n\n## Code of Conduct\n- Be **respectful and polite**.\n- Do not spam or repeatedly demand responses.\n- Off-topic, vague, or inappropriate questions may be closed.\n"
  },
  {
    "path": "boson_multimodal/__init__.py",
    "content": ""
  },
  {
    "path": "boson_multimodal/audio_processing/LICENSE",
    "content": "Third-Party License Attribution for Audio Processing Module\n===========================================================\n\nThis directory contains code derived from multiple open-source projects. \nThe following sections detail the licenses and attributions for third-party code.\n\n## XCodec Repository\nThe code in this directory is derived from:\nhttps://github.com/zhenye234/xcodec\n\n## Individual File Attributions\n\n### Quantization Module (quantization/)\n- Several files contain code derived from Meta Platforms, Inc. and the vector-quantize-pytorch repository\n- Individual files contain their own license headers where applicable\n- The vector-quantize-pytorch portions are licensed under the MIT License\n\n## License Terms\n\n### MIT License (for applicable portions)\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n## Attribution Requirements\nWhen using this code, please ensure proper attribution to:\n1. The original xcodec repository: https://github.com/zhenye234/xcodec\n2. Any other repositories mentioned in individual file headers\n3. This derivative work and its modifications\n\n## Disclaimer\nThis directory contains modified versions of the original code. Please refer to\nthe original repositories for the canonical implementations and their specific\nlicense terms.\n\nFor any questions about licensing or attribution, please check the individual\nfile headers and the original source repositories. "
  },
  {
    "path": "boson_multimodal/audio_processing/descriptaudiocodec/__init__.py",
    "content": ""
  },
  {
    "path": "boson_multimodal/audio_processing/descriptaudiocodec/dac/model/base.py",
    "content": "import math\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Union\n\nimport numpy as np\nimport torch\nimport tqdm\nfrom audiotools import AudioSignal\nfrom torch import nn\n\nSUPPORTED_VERSIONS = [\"1.0.0\"]\n\n\n@dataclass\nclass DACFile:\n    codes: torch.Tensor\n\n    # Metadata\n    chunk_length: int\n    original_length: int\n    input_db: float\n    channels: int\n    sample_rate: int\n    padding: bool\n    dac_version: str\n\n    def save(self, path):\n        artifacts = {\n            \"codes\": self.codes.numpy().astype(np.uint16),\n            \"metadata\": {\n                \"input_db\": self.input_db.numpy().astype(np.float32),\n                \"original_length\": self.original_length,\n                \"sample_rate\": self.sample_rate,\n                \"chunk_length\": self.chunk_length,\n                \"channels\": self.channels,\n                \"padding\": self.padding,\n                \"dac_version\": SUPPORTED_VERSIONS[-1],\n            },\n        }\n        path = Path(path).with_suffix(\".dac\")\n        with open(path, \"wb\") as f:\n            np.save(f, artifacts)\n        return path\n\n    @classmethod\n    def load(cls, path):\n        artifacts = np.load(path, allow_pickle=True)[()]\n        codes = torch.from_numpy(artifacts[\"codes\"].astype(int))\n        if artifacts[\"metadata\"].get(\"dac_version\", None) not in SUPPORTED_VERSIONS:\n            raise RuntimeError(f\"Given file {path} can't be loaded with this version of descript-audio-codec.\")\n        return cls(codes=codes, **artifacts[\"metadata\"])\n\n\nclass CodecMixin:\n    @property\n    def padding(self):\n        if not hasattr(self, \"_padding\"):\n            self._padding = True\n        return self._padding\n\n    @padding.setter\n    def padding(self, value):\n        assert isinstance(value, bool)\n\n        layers = [l for l in self.modules() if isinstance(l, (nn.Conv1d, nn.ConvTranspose1d))]\n\n        for layer in layers:\n            if value:\n                if hasattr(layer, \"original_padding\"):\n                    layer.padding = layer.original_padding\n            else:\n                layer.original_padding = layer.padding\n                layer.padding = tuple(0 for _ in range(len(layer.padding)))\n\n        self._padding = value\n\n    def get_delay(self):\n        # Any number works here, delay is invariant to input length\n        l_out = self.get_output_length(0)\n        L = l_out\n\n        layers = []\n        for layer in self.modules():\n            if isinstance(layer, (nn.Conv1d, nn.ConvTranspose1d)):\n                layers.append(layer)\n\n        for layer in reversed(layers):\n            d = layer.dilation[0]\n            k = layer.kernel_size[0]\n            s = layer.stride[0]\n\n            if isinstance(layer, nn.ConvTranspose1d):\n                L = ((L - d * (k - 1) - 1) / s) + 1\n            elif isinstance(layer, nn.Conv1d):\n                L = (L - 1) * s + d * (k - 1) + 1\n\n            L = math.ceil(L)\n\n        l_in = L\n\n        return (l_in - l_out) // 2\n\n    def get_output_length(self, input_length):\n        L = input_length\n        # Calculate output length\n        for layer in self.modules():\n            if isinstance(layer, (nn.Conv1d, nn.ConvTranspose1d)):\n                d = layer.dilation[0]\n                k = layer.kernel_size[0]\n                s = layer.stride[0]\n\n                if isinstance(layer, nn.Conv1d):\n                    L = ((L - d * (k - 1) - 1) / s) + 1\n                elif isinstance(layer, nn.ConvTranspose1d):\n                    L = (L - 1) * s + d * (k - 1) + 1\n\n                L = math.floor(L)\n        return L\n\n    @torch.no_grad()\n    def compress(\n        self,\n        audio_path_or_signal: Union[str, Path, AudioSignal],\n        win_duration: float = 1.0,\n        verbose: bool = False,\n        normalize_db: float = -16,\n        n_quantizers: int = None,\n    ) -> DACFile:\n        \"\"\"Processes an audio signal from a file or AudioSignal object into\n        discrete codes. This function processes the signal in short windows,\n        using constant GPU memory.\n\n        Parameters\n        ----------\n        audio_path_or_signal : Union[str, Path, AudioSignal]\n            audio signal to reconstruct\n        win_duration : float, optional\n            window duration in seconds, by default 5.0\n        verbose : bool, optional\n            by default False\n        normalize_db : float, optional\n            normalize db, by default -16\n\n        Returns\n        -------\n        DACFile\n            Object containing compressed codes and metadata\n            required for decompression\n        \"\"\"\n        audio_signal = audio_path_or_signal\n        if isinstance(audio_signal, (str, Path)):\n            audio_signal = AudioSignal.load_from_file_with_ffmpeg(str(audio_signal))\n\n        self.eval()\n        original_padding = self.padding\n        original_device = audio_signal.device\n\n        audio_signal = audio_signal.clone()\n        original_sr = audio_signal.sample_rate\n\n        resample_fn = audio_signal.resample\n        loudness_fn = audio_signal.loudness\n\n        # If audio is > 10 minutes long, use the ffmpeg versions\n        if audio_signal.signal_duration >= 10 * 60 * 60:\n            resample_fn = audio_signal.ffmpeg_resample\n            loudness_fn = audio_signal.ffmpeg_loudness\n\n        original_length = audio_signal.signal_length\n        resample_fn(self.sample_rate)\n        input_db = loudness_fn()\n\n        if normalize_db is not None:\n            audio_signal.normalize(normalize_db)\n        audio_signal.ensure_max_of_audio()\n\n        nb, nac, nt = audio_signal.audio_data.shape\n        audio_signal.audio_data = audio_signal.audio_data.reshape(nb * nac, 1, nt)\n        win_duration = audio_signal.signal_duration if win_duration is None else win_duration\n\n        if audio_signal.signal_duration <= win_duration:\n            # Unchunked compression (used if signal length < win duration)\n            self.padding = True\n            n_samples = nt\n            hop = nt\n        else:\n            # Chunked inference\n            self.padding = False\n            # Zero-pad signal on either side by the delay\n            audio_signal.zero_pad(self.delay, self.delay)\n            n_samples = int(win_duration * self.sample_rate)\n            # Round n_samples to nearest hop length multiple\n            n_samples = int(math.ceil(n_samples / self.hop_length) * self.hop_length)\n            hop = self.get_output_length(n_samples)\n\n        codes = []\n        range_fn = range if not verbose else tqdm.trange\n\n        for i in range_fn(0, nt, hop):\n            x = audio_signal[..., i : i + n_samples]\n            x = x.zero_pad(0, max(0, n_samples - x.shape[-1]))\n\n            audio_data = x.audio_data.to(self.device)\n            audio_data = self.preprocess(audio_data, self.sample_rate)\n            _, c, _, _, _ = self.encode(audio_data, n_quantizers)\n            codes.append(c.to(original_device))\n            chunk_length = c.shape[-1]\n\n        codes = torch.cat(codes, dim=-1)\n\n        dac_file = DACFile(\n            codes=codes,\n            chunk_length=chunk_length,\n            original_length=original_length,\n            input_db=input_db,\n            channels=nac,\n            sample_rate=original_sr,\n            padding=self.padding,\n            dac_version=SUPPORTED_VERSIONS[-1],\n        )\n\n        if n_quantizers is not None:\n            codes = codes[:, :n_quantizers, :]\n\n        self.padding = original_padding\n        return dac_file\n\n    @torch.no_grad()\n    def decompress(\n        self,\n        obj: Union[str, Path, DACFile],\n        verbose: bool = False,\n    ) -> AudioSignal:\n        \"\"\"Reconstruct audio from a given .dac file\n\n        Parameters\n        ----------\n        obj : Union[str, Path, DACFile]\n            .dac file location or corresponding DACFile object.\n        verbose : bool, optional\n            Prints progress if True, by default False\n\n        Returns\n        -------\n        AudioSignal\n            Object with the reconstructed audio\n        \"\"\"\n        self.eval()\n        if isinstance(obj, (str, Path)):\n            obj = DACFile.load(obj)\n\n        original_padding = self.padding\n        self.padding = obj.padding\n\n        range_fn = range if not verbose else tqdm.trange\n        codes = obj.codes\n        original_device = codes.device\n        chunk_length = obj.chunk_length\n        recons = []\n\n        for i in range_fn(0, codes.shape[-1], chunk_length):\n            c = codes[..., i : i + chunk_length].to(self.device)\n            z = self.quantizer.from_codes(c)[0]\n            r = self.decode(z)\n            recons.append(r.to(original_device))\n\n        recons = torch.cat(recons, dim=-1)\n        recons = AudioSignal(recons, self.sample_rate)\n\n        resample_fn = recons.resample\n        loudness_fn = recons.loudness\n\n        # If audio is > 10 minutes long, use the ffmpeg versions\n        if recons.signal_duration >= 10 * 60 * 60:\n            resample_fn = recons.ffmpeg_resample\n            loudness_fn = recons.ffmpeg_loudness\n\n        recons.normalize(obj.input_db)\n        resample_fn(obj.sample_rate)\n        recons = recons[..., : obj.original_length]\n        loudness_fn()\n        recons.audio_data = recons.audio_data.reshape(-1, obj.channels, obj.original_length)\n\n        self.padding = original_padding\n        return recons\n"
  },
  {
    "path": "boson_multimodal/audio_processing/descriptaudiocodec/dac/model/dac.py",
    "content": "import math\nfrom typing import List\nfrom typing import Union\n\nimport numpy as np\nimport torch\nfrom audiotools import AudioSignal\nfrom audiotools.ml import BaseModel\nfrom torch import nn\n\nfrom .base import CodecMixin\nfrom dac.nn.layers import Snake1d\nfrom dac.nn.layers import WNConv1d\nfrom dac.nn.layers import WNConvTranspose1d\nfrom dac.nn.quantize import ResidualVectorQuantize\n\n\ndef init_weights(m):\n    if isinstance(m, nn.Conv1d):\n        nn.init.trunc_normal_(m.weight, std=0.02)\n        nn.init.constant_(m.bias, 0)\n\n\nclass ResidualUnit(nn.Module):\n    def __init__(self, dim: int = 16, dilation: int = 1):\n        super().__init__()\n        pad = ((7 - 1) * dilation) // 2\n        self.block = nn.Sequential(\n            Snake1d(dim),\n            WNConv1d(dim, dim, kernel_size=7, dilation=dilation, padding=pad),\n            Snake1d(dim),\n            WNConv1d(dim, dim, kernel_size=1),\n        )\n\n    def forward(self, x):\n        y = self.block(x)\n        pad = (x.shape[-1] - y.shape[-1]) // 2\n        if pad > 0:\n            x = x[..., pad:-pad]\n        return x + y\n\n\nclass EncoderBlock(nn.Module):\n    def __init__(self, dim: int = 16, stride: int = 1):\n        super().__init__()\n        self.block = nn.Sequential(\n            ResidualUnit(dim // 2, dilation=1),\n            ResidualUnit(dim // 2, dilation=3),\n            ResidualUnit(dim // 2, dilation=9),\n            Snake1d(dim // 2),\n            WNConv1d(\n                dim // 2,\n                dim,\n                kernel_size=2 * stride,\n                stride=stride,\n                padding=math.ceil(stride / 2),\n            ),\n        )\n\n    def forward(self, x):\n        return self.block(x)\n\n\nclass Encoder(nn.Module):\n    def __init__(\n        self,\n        d_model: int = 64,\n        strides: list = [2, 4, 8, 8],\n        d_latent: int = 256,\n    ):\n        super().__init__()\n        # Create first convolution\n        self.block = [WNConv1d(1, d_model, kernel_size=7, padding=3)]\n\n        # Create EncoderBlocks that double channels as they downsample by `stride`\n        for stride in strides:\n            d_model *= 2\n            self.block += [EncoderBlock(d_model, stride=stride)]\n\n        # Create last convolution\n        self.block += [\n            Snake1d(d_model),\n            WNConv1d(d_model, d_latent, kernel_size=3, padding=1),\n        ]\n\n        # Wrap black into nn.Sequential\n        self.block = nn.Sequential(*self.block)\n        self.enc_dim = d_model\n\n    def forward(self, x):\n        return self.block(x)\n\n\nclass DecoderBlock(nn.Module):\n    def __init__(self, input_dim: int = 16, output_dim: int = 8, stride: int = 1, out_pad=0):\n        super().__init__()\n        self.block = nn.Sequential(\n            Snake1d(input_dim),\n            WNConvTranspose1d(\n                input_dim,\n                output_dim,\n                kernel_size=2 * stride,\n                stride=stride,\n                padding=math.ceil(stride / 2),\n                output_padding=stride % 2,  # out_pad,\n            ),\n            ResidualUnit(output_dim, dilation=1),\n            ResidualUnit(output_dim, dilation=3),\n            ResidualUnit(output_dim, dilation=9),\n        )\n\n    def forward(self, x):\n        return self.block(x)\n\n\nclass Decoder(nn.Module):\n    def __init__(\n        self,\n        input_channel,\n        channels,\n        rates,\n        d_out: int = 1,\n    ):\n        super().__init__()\n\n        # Add first conv layer\n        layers = [WNConv1d(input_channel, channels, kernel_size=7, padding=3)]\n\n        # Add upsampling + MRF blocks\n        for i, stride in enumerate(rates):\n            input_dim = channels // 2**i\n            output_dim = channels // 2 ** (i + 1)\n            if i == 1:\n                out_pad = 1\n            else:\n                out_pad = 0\n            layers += [DecoderBlock(input_dim, output_dim, stride, out_pad)]\n\n        # Add final conv layer\n        layers += [\n            Snake1d(output_dim),\n            WNConv1d(output_dim, d_out, kernel_size=7, padding=3),\n            # nn.Tanh(),\n        ]\n\n        self.model = nn.Sequential(*layers)\n\n    def forward(self, x):\n        return self.model(x)\n\n\nclass DAC(BaseModel, CodecMixin):\n    def __init__(\n        self,\n        encoder_dim: int = 64,\n        encoder_rates: List[int] = [2, 4, 8, 8],\n        latent_dim: int = None,\n        decoder_dim: int = 1536,\n        decoder_rates: List[int] = [8, 8, 4, 2],\n        n_codebooks: int = 9,\n        codebook_size: int = 1024,\n        codebook_dim: Union[int, list] = 8,\n        quantizer_dropout: bool = False,\n        sample_rate: int = 44100,\n    ):\n        super().__init__()\n\n        self.encoder_dim = encoder_dim\n        self.encoder_rates = encoder_rates\n        self.decoder_dim = decoder_dim\n        self.decoder_rates = decoder_rates\n        self.sample_rate = sample_rate\n\n        if latent_dim is None:\n            latent_dim = encoder_dim * (2 ** len(encoder_rates))\n\n        self.latent_dim = latent_dim\n\n        self.hop_length = np.prod(encoder_rates)\n        self.encoder = Encoder(encoder_dim, encoder_rates, latent_dim)\n\n        self.n_codebooks = n_codebooks\n        self.codebook_size = codebook_size\n        self.codebook_dim = codebook_dim\n        self.quantizer = ResidualVectorQuantize(\n            input_dim=latent_dim,\n            n_codebooks=n_codebooks,\n            codebook_size=codebook_size,\n            codebook_dim=codebook_dim,\n            quantizer_dropout=quantizer_dropout,\n        )\n\n        self.decoder = Decoder(\n            latent_dim,\n            decoder_dim,\n            decoder_rates,\n        )\n        self.sample_rate = sample_rate\n        self.apply(init_weights)\n\n        self.delay = self.get_delay()\n\n    def preprocess(self, audio_data, sample_rate):\n        if sample_rate is None:\n            sample_rate = self.sample_rate\n        assert sample_rate == self.sample_rate\n\n        length = audio_data.shape[-1]\n        right_pad = math.ceil(length / self.hop_length) * self.hop_length - length\n        audio_data = nn.functional.pad(audio_data, (0, right_pad))\n\n        return audio_data\n\n    def encode(\n        self,\n        audio_data: torch.Tensor,\n        n_quantizers: int = None,\n    ):\n        \"\"\"Encode given audio data and return quantized latent codes\n\n        Parameters\n        ----------\n        audio_data : Tensor[B x 1 x T]\n            Audio data to encode\n        n_quantizers : int, optional\n            Number of quantizers to use, by default None\n            If None, all quantizers are used.\n\n        Returns\n        -------\n        dict\n            A dictionary with the following keys:\n            \"z\" : Tensor[B x D x T]\n                Quantized continuous representation of input\n            \"codes\" : Tensor[B x N x T]\n                Codebook indices for each codebook\n                (quantized discrete representation of input)\n            \"latents\" : Tensor[B x N*D x T]\n                Projected latents (continuous representation of input before quantization)\n            \"vq/commitment_loss\" : Tensor[1]\n                Commitment loss to train encoder to predict vectors closer to codebook\n                entries\n            \"vq/codebook_loss\" : Tensor[1]\n                Codebook loss to update the codebook\n            \"length\" : int\n                Number of samples in input audio\n        \"\"\"\n        z = self.encoder(audio_data)\n        z, codes, latents, commitment_loss, codebook_loss = self.quantizer(z, n_quantizers)\n        return z, codes, latents, commitment_loss, codebook_loss\n\n    def decode(self, z: torch.Tensor):\n        \"\"\"Decode given latent codes and return audio data\n\n        Parameters\n        ----------\n        z : Tensor[B x D x T]\n            Quantized continuous representation of input\n        length : int, optional\n            Number of samples in output audio, by default None\n\n        Returns\n        -------\n        dict\n            A dictionary with the following keys:\n            \"audio\" : Tensor[B x 1 x length]\n                Decoded audio data.\n        \"\"\"\n        return self.decoder(z)\n\n    def forward(\n        self,\n        audio_data: torch.Tensor,\n        sample_rate: int = None,\n        n_quantizers: int = None,\n    ):\n        \"\"\"Model forward pass\n\n        Parameters\n        ----------\n        audio_data : Tensor[B x 1 x T]\n            Audio data to encode\n        sample_rate : int, optional\n            Sample rate of audio data in Hz, by default None\n            If None, defaults to `self.sample_rate`\n        n_quantizers : int, optional\n            Number of quantizers to use, by default None.\n            If None, all quantizers are used.\n\n        Returns\n        -------\n        dict\n            A dictionary with the following keys:\n            \"z\" : Tensor[B x D x T]\n                Quantized continuous representation of input\n            \"codes\" : Tensor[B x N x T]\n                Codebook indices for each codebook\n                (quantized discrete representation of input)\n            \"latents\" : Tensor[B x N*D x T]\n                Projected latents (continuous representation of input before quantization)\n            \"vq/commitment_loss\" : Tensor[1]\n                Commitment loss to train encoder to predict vectors closer to codebook\n                entries\n            \"vq/codebook_loss\" : Tensor[1]\n                Codebook loss to update the codebook\n            \"length\" : int\n                Number of samples in input audio\n            \"audio\" : Tensor[B x 1 x length]\n                Decoded audio data.\n        \"\"\"\n        length = audio_data.shape[-1]\n        audio_data = self.preprocess(audio_data, sample_rate)\n        z, codes, latents, commitment_loss, codebook_loss = self.encode(audio_data, n_quantizers)\n\n        x = self.decode(z)\n        return {\n            \"audio\": x[..., :length],\n            \"z\": z,\n            \"codes\": codes,\n            \"latents\": latents,\n            \"vq/commitment_loss\": commitment_loss,\n            \"vq/codebook_loss\": codebook_loss,\n        }\n\n\nif __name__ == \"__main__\":\n    import numpy as np\n    from functools import partial\n\n    model = DAC().to(\"cpu\")\n\n    for n, m in model.named_modules():\n        o = m.extra_repr()\n        p = sum([np.prod(p.size()) for p in m.parameters()])\n        fn = lambda o, p: o + f\" {p / 1e6:<.3f}M params.\"\n        setattr(m, \"extra_repr\", partial(fn, o=o, p=p))\n    print(model)\n    print(\"Total # of params: \", sum([np.prod(p.size()) for p in model.parameters()]))\n\n    length = 88200 * 2\n    x = torch.randn(1, 1, length).to(model.device)\n    x.requires_grad_(True)\n    x.retain_grad()\n\n    # Make a forward pass\n    out = model(x)[\"audio\"]\n    print(\"Input shape:\", x.shape)\n    print(\"Output shape:\", out.shape)\n\n    # Create gradient variable\n    grad = torch.zeros_like(out)\n    grad[:, :, grad.shape[-1] // 2] = 1\n\n    # Make a backward pass\n    out.backward(grad)\n\n    # Check non-zero values\n    gradmap = x.grad.squeeze(0)\n    gradmap = (gradmap != 0).sum(0)  # sum across features\n    rf = (gradmap != 0).sum()\n\n    print(f\"Receptive field: {rf.item()}\")\n\n    x = AudioSignal(torch.randn(1, 1, 44100 * 60), 44100)\n    model.decompress(model.compress(x, verbose=True), verbose=True)\n"
  },
  {
    "path": "boson_multimodal/audio_processing/descriptaudiocodec/dac/nn/layers.py",
    "content": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom einops import rearrange\nfrom torch.nn.utils import weight_norm\n\n\ndef WNConv1d(*args, **kwargs):\n    return weight_norm(nn.Conv1d(*args, **kwargs))\n\n\ndef WNConvTranspose1d(*args, **kwargs):\n    return weight_norm(nn.ConvTranspose1d(*args, **kwargs))\n\n\n# Scripting this brings model speed up 1.4x\n@torch.jit.script\ndef snake(x, alpha):\n    shape = x.shape\n    x = x.reshape(shape[0], shape[1], -1)\n    x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)\n    x = x.reshape(shape)\n    return x\n\n\nclass Snake1d(nn.Module):\n    def __init__(self, channels):\n        super().__init__()\n        self.alpha = nn.Parameter(torch.ones(1, channels, 1))\n\n    def forward(self, x):\n        return snake(x, self.alpha)\n"
  },
  {
    "path": "boson_multimodal/audio_processing/descriptaudiocodec/dac/nn/quantize.py",
    "content": "from typing import Union\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom einops import rearrange\nfrom torch.nn.utils import weight_norm\n\nfrom dac.nn.layers import WNConv1d\n\n\nclass VectorQuantize(nn.Module):\n    \"\"\"\n    Implementation of VQ similar to Karpathy's repo:\n    https://github.com/karpathy/deep-vector-quantization\n    Additionally uses following tricks from Improved VQGAN\n    (https://arxiv.org/pdf/2110.04627.pdf):\n        1. Factorized codes: Perform nearest neighbor lookup in low-dimensional space\n            for improved codebook usage\n        2. l2-normalized codes: Converts euclidean distance to cosine similarity which\n            improves training stability\n    \"\"\"\n\n    def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int):\n        super().__init__()\n        self.codebook_size = codebook_size\n        self.codebook_dim = codebook_dim\n\n        self.in_proj = WNConv1d(input_dim, codebook_dim, kernel_size=1)\n        self.out_proj = WNConv1d(codebook_dim, input_dim, kernel_size=1)\n        self.codebook = nn.Embedding(codebook_size, codebook_dim)\n\n    def forward(self, z):\n        \"\"\"Quantized the input tensor using a fixed codebook and returns\n        the corresponding codebook vectors\n\n        Parameters\n        ----------\n        z : Tensor[B x D x T]\n\n        Returns\n        -------\n        Tensor[B x D x T]\n            Quantized continuous representation of input\n        Tensor[1]\n            Commitment loss to train encoder to predict vectors closer to codebook\n            entries\n        Tensor[1]\n            Codebook loss to update the codebook\n        Tensor[B x T]\n            Codebook indices (quantized discrete representation of input)\n        Tensor[B x D x T]\n            Projected latents (continuous representation of input before quantization)\n        \"\"\"\n\n        # Factorized codes (ViT-VQGAN) Project input into low-dimensional space\n        z_e = self.in_proj(z)  # z_e : (B x D x T)\n        z_q, indices = self.decode_latents(z_e)\n\n        commitment_loss = F.mse_loss(z_e, z_q.detach(), reduction=\"none\").mean([1, 2])\n        codebook_loss = F.mse_loss(z_q, z_e.detach(), reduction=\"none\").mean([1, 2])\n\n        z_q = z_e + (z_q - z_e).detach()  # noop in forward pass, straight-through gradient estimator in backward pass\n\n        z_q = self.out_proj(z_q)\n\n        return z_q, commitment_loss, codebook_loss, indices, z_e\n\n    def embed_code(self, embed_id):\n        return F.embedding(embed_id, self.codebook.weight)\n\n    def decode_code(self, embed_id):\n        return self.embed_code(embed_id).transpose(1, 2)\n\n    def decode_latents(self, latents):\n        encodings = rearrange(latents, \"b d t -> (b t) d\")\n        codebook = self.codebook.weight  # codebook: (N x D)\n\n        # L2 normalize encodings and codebook (ViT-VQGAN)\n        encodings = F.normalize(encodings)\n        codebook = F.normalize(codebook)\n\n        # Compute euclidean distance with codebook\n        dist = (\n            encodings.pow(2).sum(1, keepdim=True)\n            - 2 * encodings @ codebook.t()\n            + codebook.pow(2).sum(1, keepdim=True).t()\n        )\n        indices = rearrange((-dist).max(1)[1], \"(b t) -> b t\", b=latents.size(0))\n        z_q = self.decode_code(indices)\n        return z_q, indices\n\n\nclass ResidualVectorQuantize(nn.Module):\n    \"\"\"\n    Introduced in SoundStream: An end2end neural audio codec\n    https://arxiv.org/abs/2107.03312\n    \"\"\"\n\n    def __init__(\n        self,\n        input_dim: int = 512,\n        n_codebooks: int = 9,\n        codebook_size: int = 1024,\n        codebook_dim: Union[int, list] = 8,\n        quantizer_dropout: float = 0.0,\n    ):\n        super().__init__()\n        if isinstance(codebook_dim, int):\n            codebook_dim = [codebook_dim for _ in range(n_codebooks)]\n\n        self.n_codebooks = n_codebooks\n        self.codebook_dim = codebook_dim\n        self.codebook_size = codebook_size\n\n        self.quantizers = nn.ModuleList(\n            [VectorQuantize(input_dim, codebook_size, codebook_dim[i]) for i in range(n_codebooks)]\n        )\n        self.quantizer_dropout = quantizer_dropout\n\n    def forward(self, z, n_quantizers: int = None):\n        \"\"\"Quantized the input tensor using a fixed set of `n` codebooks and returns\n        the corresponding codebook vectors\n        Parameters\n        ----------\n        z : Tensor[B x D x T]\n        n_quantizers : int, optional\n            No. of quantizers to use\n            (n_quantizers < self.n_codebooks ex: for quantizer dropout)\n            Note: if `self.quantizer_dropout` is True, this argument is ignored\n                when in training mode, and a random number of quantizers is used.\n        Returns\n        -------\n        dict\n            A dictionary with the following keys:\n\n            \"z\" : Tensor[B x D x T]\n                Quantized continuous representation of input\n            \"codes\" : Tensor[B x N x T]\n                Codebook indices for each codebook\n                (quantized discrete representation of input)\n            \"latents\" : Tensor[B x N*D x T]\n                Projected latents (continuous representation of input before quantization)\n            \"vq/commitment_loss\" : Tensor[1]\n                Commitment loss to train encoder to predict vectors closer to codebook\n                entries\n            \"vq/codebook_loss\" : Tensor[1]\n                Codebook loss to update the codebook\n        \"\"\"\n        z_q = 0\n        residual = z\n        commitment_loss = 0\n        codebook_loss = 0\n\n        codebook_indices = []\n        latents = []\n\n        if n_quantizers is None:\n            n_quantizers = self.n_codebooks\n        if self.training:\n            n_quantizers = torch.ones((z.shape[0],)) * self.n_codebooks + 1\n            dropout = torch.randint(1, self.n_codebooks + 1, (z.shape[0],))\n            n_dropout = int(z.shape[0] * self.quantizer_dropout)\n            n_quantizers[:n_dropout] = dropout[:n_dropout]\n            n_quantizers = n_quantizers.to(z.device)\n\n        for i, quantizer in enumerate(self.quantizers):\n            if self.training is False and i >= n_quantizers:\n                break\n\n            z_q_i, commitment_loss_i, codebook_loss_i, indices_i, z_e_i = quantizer(residual)\n\n            # Create mask to apply quantizer dropout\n            mask = torch.full((z.shape[0],), fill_value=i, device=z.device) < n_quantizers\n            z_q = z_q + z_q_i * mask[:, None, None]\n            residual = residual - z_q_i\n\n            # Sum losses\n            commitment_loss += (commitment_loss_i * mask).mean()\n            codebook_loss += (codebook_loss_i * mask).mean()\n\n            codebook_indices.append(indices_i)\n            latents.append(z_e_i)\n\n        codes = torch.stack(codebook_indices, dim=1)\n        latents = torch.cat(latents, dim=1)\n\n        return z_q, codes, latents, commitment_loss, codebook_loss\n\n    def from_codes(self, codes: torch.Tensor):\n        \"\"\"Given the quantized codes, reconstruct the continuous representation\n        Parameters\n        ----------\n        codes : Tensor[B x N x T]\n            Quantized discrete representation of input\n        Returns\n        -------\n        Tensor[B x D x T]\n            Quantized continuous representation of input\n        \"\"\"\n        z_q = 0.0\n        z_p = []\n        n_codebooks = codes.shape[1]\n        for i in range(n_codebooks):\n            z_p_i = self.quantizers[i].decode_code(codes[:, i, :])\n            z_p.append(z_p_i)\n\n            z_q_i = self.quantizers[i].out_proj(z_p_i)\n            z_q = z_q + z_q_i\n        return z_q, torch.cat(z_p, dim=1), codes\n\n    def from_latents(self, latents: torch.Tensor):\n        \"\"\"Given the unquantized latents, reconstruct the\n        continuous representation after quantization.\n\n        Parameters\n        ----------\n        latents : Tensor[B x N x T]\n            Continuous representation of input after projection\n\n        Returns\n        -------\n        Tensor[B x D x T]\n            Quantized representation of full-projected space\n        Tensor[B x D x T]\n            Quantized representation of latent space\n        \"\"\"\n        z_q = 0\n        z_p = []\n        codes = []\n        dims = np.cumsum([0] + [q.codebook_dim for q in self.quantizers])\n\n        n_codebooks = np.where(dims <= latents.shape[1])[0].max(axis=0, keepdims=True)[0]\n        for i in range(n_codebooks):\n            j, k = dims[i], dims[i + 1]\n            z_p_i, codes_i = self.quantizers[i].decode_latents(latents[:, j:k, :])\n            z_p.append(z_p_i)\n            codes.append(codes_i)\n\n            z_q_i = self.quantizers[i].out_proj(z_p_i)\n            z_q = z_q + z_q_i\n\n        return z_q, torch.cat(z_p, dim=1), torch.stack(codes, dim=1)\n\n\nif __name__ == \"__main__\":\n    rvq = ResidualVectorQuantize(quantizer_dropout=True)\n    x = torch.randn(16, 512, 80)\n    y = rvq(x)\n    print(y[\"latents\"].shape)\n"
  },
  {
    "path": "boson_multimodal/audio_processing/higgs_audio_tokenizer.py",
    "content": "# Based on code from: https://github.com/zhenye234/xcodec\n# Licensed under MIT License\n# Modifications by BosonAI\n\nimport math\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom typing import Optional, Union, Sequence\nimport numpy as np\nfrom transformers import AutoModel\nimport torchaudio\nimport json\nimport librosa\nfrom huggingface_hub import snapshot_download\n\nfrom vector_quantize_pytorch import ResidualFSQ\nfrom .descriptaudiocodec.dac.model import dac as dac2\nfrom .quantization.vq import ResidualVectorQuantizer\nfrom .semantic_module import Encoder, Decoder\n\n\nclass EncodedResult:\n    def __init__(self, audio_codes):\n        self.audio_codes = audio_codes\n\n\nclass HiggsAudioFeatureExtractor(nn.Module):\n    def __init__(self, sampling_rate=16000):\n        super().__init__()\n        self.sampling_rate = sampling_rate\n\n    def forward(self, raw_audio, sampling_rate=16000, return_tensors=\"pt\"):\n        # Convert from librosa to torch\n        audio_signal = torch.tensor(raw_audio)\n        audio_signal = audio_signal.unsqueeze(0)\n        if len(audio_signal.shape) < 3:\n            audio_signal = audio_signal.unsqueeze(0)\n        return {\"input_values\": audio_signal}\n\n\nclass HiggsAudioTokenizer(nn.Module):\n    def __init__(\n        self,\n        n_filters: int = 32,\n        D: int = 128,\n        target_bandwidths: Sequence[Union[int, float]] = [1, 1.5, 2, 4, 6],\n        ratios: Sequence[int] = [8, 5, 4, 2],  #  downsampling by 320\n        sample_rate: int = 16000,\n        bins: int = 1024,\n        n_q: int = 8,\n        codebook_dim: int = None,\n        normalize: bool = False,\n        causal: bool = False,\n        semantic_techer: str = \"hubert_base_general\",\n        last_layer_semantic: bool = True,\n        merge_mode: str = \"concat\",\n        downsample_mode: str = \"step_down\",\n        semantic_mode: str = \"classic\",\n        vq_scale: int = 1,\n        semantic_sample_rate: int = None,\n        device: str = \"cuda\",\n    ):\n        super().__init__()\n        self.hop_length = np.prod(ratios)\n        self.semantic_techer = semantic_techer\n\n        self.frame_rate = math.ceil(sample_rate / np.prod(ratios))  # 50 Hz\n\n        self.target_bandwidths = target_bandwidths\n        self.n_q = n_q\n        self.sample_rate = sample_rate\n        self.encoder = dac2.Encoder(64, ratios, D)\n\n        self.decoder_2 = dac2.Decoder(D, 1024, ratios)\n        self.last_layer_semantic = last_layer_semantic\n        self.device = device\n        if semantic_techer == \"hubert_base\":\n            self.semantic_model = AutoModel.from_pretrained(\"facebook/hubert-base-ls960\")\n            self.semantic_sample_rate = 16000\n            self.semantic_dim = 768\n            self.encoder_semantic_dim = 768\n\n        elif semantic_techer == \"wavlm_base_plus\":\n            self.semantic_model = AutoModel.from_pretrained(\"microsoft/wavlm-base-plus\")\n            self.semantic_sample_rate = 16000\n            self.semantic_dim = 768\n            self.encoder_semantic_dim = 768\n\n        elif semantic_techer == \"hubert_base_general\":\n            self.semantic_model = AutoModel.from_pretrained(\"bosonai/hubert_base\", trust_remote_code=True)\n            self.semantic_sample_rate = 16000\n            self.semantic_dim = 768\n            self.encoder_semantic_dim = 768\n\n        # Overwrite semantic model sr to ensure semantic_downsample_factor is an integer\n        if semantic_sample_rate is not None:\n            self.semantic_sample_rate = semantic_sample_rate\n\n        self.semantic_model.eval()\n\n        # make the semantic model parameters do not need gradient\n        for param in self.semantic_model.parameters():\n            param.requires_grad = False\n\n        self.semantic_downsample_factor = int(self.hop_length / (self.sample_rate / self.semantic_sample_rate) / 320)\n\n        self.quantizer_dim = int((D + self.encoder_semantic_dim) // vq_scale)\n        self.encoder_semantic = Encoder(input_channels=self.semantic_dim, encode_channels=self.encoder_semantic_dim)\n        self.decoder_semantic = Decoder(\n            code_dim=self.encoder_semantic_dim, output_channels=self.semantic_dim, decode_channels=self.semantic_dim\n        )\n\n        # out_D=D+768\n        if isinstance(bins, int):  # RVQ\n            self.quantizer = ResidualVectorQuantizer(\n                dimension=self.quantizer_dim, codebook_dim=codebook_dim, n_q=n_q, bins=bins\n            )\n            self.quantizer_type = \"RVQ\"\n        else:  # RFSQ\n            self.quantizer = ResidualFSQ(dim=self.quantizer_dim, levels=bins, num_quantizers=n_q)\n            self.quantizer_type = \"RFSQ\"\n\n        self.fc_prior = nn.Linear(D + self.encoder_semantic_dim, self.quantizer_dim)\n        self.fc_post1 = nn.Linear(self.quantizer_dim, self.encoder_semantic_dim)\n        self.fc_post2 = nn.Linear(self.quantizer_dim, D)\n\n        self.downsample_mode = downsample_mode\n        if downsample_mode == \"avg\":\n            self.semantic_pooling = nn.AvgPool1d(\n                kernel_size=self.semantic_downsample_factor, stride=self.semantic_downsample_factor\n            )\n\n        self.audio_tokenizer_feature_extractor = HiggsAudioFeatureExtractor(sampling_rate=self.sample_rate)\n\n    @property\n    def tps(self):\n        return self.frame_rate\n\n    @property\n    def sampling_rate(self):\n        return self.sample_rate\n\n    @property\n    def num_codebooks(self):\n        return self.n_q\n\n    @property\n    def codebook_size(self):\n        return self.quantizer_dim\n\n    def get_last_layer(self):\n        return self.decoder.layers[-1].weight\n\n    def calculate_rec_loss(self, rec, target):\n        target = target / target.norm(dim=-1, keepdim=True)\n        rec = rec / rec.norm(dim=-1, keepdim=True)\n        rec_loss = (1 - (target * rec).sum(-1)).mean()\n\n        return rec_loss\n\n    @torch.no_grad()\n    def get_regress_target(self, x):\n        x = torchaudio.functional.resample(x, self.sample_rate, self.semantic_sample_rate)\n\n        if (\n            self.semantic_techer == \"hubert_base\"\n            or self.semantic_techer == \"hubert_base_general\"\n            or self.semantic_techer == \"wavlm_base_plus\"\n        ):\n            x = x[:, 0, :]\n            x = F.pad(x, (160, 160))\n            target = self.semantic_model(x, output_hidden_states=True).hidden_states\n            target = torch.stack(target, dim=1)  # .transpose(-1, -2)#.flatten(start_dim=1, end_dim=2)\n\n            # average for all layers\n            target = target.mean(1)\n            # target = target[9]\n            # if self.hop_length > 320:\n            #     target = self.semantic_pooling(target.transpose(1, 2)).transpose(1, 2)\n\n        elif self.semantic_techer == \"w2v_bert2\":\n            target = self.semantic_model(x)\n\n        elif self.semantic_techer.startswith(\"whisper\"):\n            if self.last_layer_semantic:\n                target = self.semantic_model(x, avg_layers=False)\n            else:\n                target = self.semantic_model(x, avg_layers=True)\n\n        elif self.semantic_techer.startswith(\"mert_music\"):\n            if self.last_layer_semantic:\n                target = self.semantic_model(x, avg_layers=False)\n            else:\n                target = self.semantic_model(x, avg_layers=True)\n\n        elif self.semantic_techer.startswith(\"qwen_audio_omni\"):\n            target = self.semantic_model(x)\n\n        if self.downsample_mode == \"step_down\":\n            if self.semantic_downsample_factor > 1:\n                target = target[:, :: self.semantic_downsample_factor, :]\n\n        elif self.downsample_mode == \"avg\":\n            target = self.semantic_pooling(target.transpose(1, 2)).transpose(1, 2)\n        return target\n\n    def forward(self, x: torch.Tensor, bw: int):\n        e_semantic_input = self.get_regress_target(x).detach()\n\n        e_semantic = self.encoder_semantic(e_semantic_input.transpose(1, 2))\n        e_acoustic = self.encoder(x)\n\n        e = torch.cat([e_acoustic, e_semantic], dim=1)\n\n        e = self.fc_prior(e.transpose(1, 2))\n\n        if self.quantizer_type == \"RVQ\":\n            e = e.transpose(1, 2)\n            quantized, codes, bandwidth, commit_loss = self.quantizer(e, self.frame_rate, bw)\n            quantized = quantized.transpose(1, 2)\n        else:\n            quantized, codes = self.quantizer(e)\n            commit_loss = torch.tensor(0.0)\n\n        quantized_semantic = self.fc_post1(quantized).transpose(1, 2)\n        quantized_acoustic = self.fc_post2(quantized).transpose(1, 2)\n\n        o = self.decoder_2(quantized_acoustic)\n\n        o_semantic = self.decoder_semantic(quantized_semantic)\n        semantic_recon_loss = F.mse_loss(e_semantic_input.transpose(1, 2).detach(), o_semantic)\n\n        return o, commit_loss, semantic_recon_loss, None\n\n    def encode(self, audio_path_or_wv, sr=None, loudness_normalize=False, loudness_threshold=-23.0):\n        if isinstance(audio_path_or_wv, str):\n            wv, sr = librosa.load(audio_path_or_wv, mono=True, sr=None)\n        else:\n            wv = audio_path_or_wv\n            assert sr is not None\n        if loudness_normalize:\n            import pyloudnorm as pyln\n\n            meter = pyln.Meter(sr)\n            l = meter.integrated_loudness(wv)\n            wv = pyln.normalize.loudness(wv, l, loudness_threshold)\n        if sr != self.sampling_rate:\n            wv = librosa.resample(wv, orig_sr=sr, target_sr=self.sampling_rate)\n        if self.audio_tokenizer_feature_extractor is not None:\n            inputs = self.audio_tokenizer_feature_extractor(\n                raw_audio=wv, sampling_rate=self.audio_tokenizer_feature_extractor.sampling_rate, return_tensors=\"pt\"\n            )\n            input_values = inputs[\"input_values\"].to(self.device)\n        else:\n            input_values = torch.from_numpy(wv).float().unsqueeze(0)\n        with torch.no_grad():\n            encoder_outputs = self._xcodec_encode(input_values)\n            vq_code = encoder_outputs.audio_codes[0]\n        return vq_code\n\n    def _xcodec_encode(self, x: torch.Tensor, target_bw: Optional[int] = None) -> torch.Tensor:\n        bw = target_bw\n\n        e_semantic_input = self.get_regress_target(x).detach()\n\n        e_semantic = self.encoder_semantic(e_semantic_input.transpose(1, 2))\n        e_acoustic = self.encoder(x)\n\n        if e_acoustic.shape[2] != e_semantic.shape[2]:\n            pad_size = 160 * self.semantic_downsample_factor\n            e_acoustic = self.encoder(F.pad(x[:, 0, :], (pad_size, pad_size)).unsqueeze(0))\n\n        if e_acoustic.shape[2] != e_semantic.shape[2]:\n            if e_acoustic.shape[2] > e_semantic.shape[2]:\n                e_acoustic = e_acoustic[:, :, : e_semantic.shape[2]]\n            else:\n                e_semantic = e_semantic[:, :, : e_acoustic.shape[2]]\n\n        e = torch.cat([e_acoustic, e_semantic], dim=1)\n\n        e = self.fc_prior(e.transpose(1, 2))\n\n        if self.quantizer_type == \"RVQ\":\n            e = e.transpose(1, 2)\n            quantized, codes, bandwidth, commit_loss = self.quantizer(e, self.frame_rate, bw)\n            codes = codes.permute(1, 0, 2)\n        else:\n            quantized, codes = self.quantizer(e)\n            codes = codes.permute(0, 2, 1)\n\n        # return codes\n        return EncodedResult(codes)\n\n    def decode(self, vq_code: torch.Tensor) -> torch.Tensor:\n        vq_code = vq_code.to(self.device)\n\n        if self.quantizer_type == \"RVQ\":\n            vq_code = vq_code.permute(1, 0, 2)\n            quantized = self.quantizer.decode(vq_code)\n            quantized = quantized.transpose(1, 2)\n        else:\n            vq_code = vq_code.permute(0, 2, 1)\n            quantized = self.quantizer.get_output_from_indices(vq_code)\n        quantized_acoustic = self.fc_post2(quantized).transpose(1, 2)\n\n        o = self.decoder_2(quantized_acoustic)\n        return o.detach().cpu().numpy()\n\n\ndef load_higgs_audio_tokenizer(tokenizer_name_or_path, device=\"cuda\"):\n    is_local = os.path.exists(tokenizer_name_or_path)\n    if not is_local:\n        tokenizer_path = snapshot_download(tokenizer_name_or_path)\n    else:\n        tokenizer_path = tokenizer_name_or_path\n    config_path = os.path.join(tokenizer_path, \"config.json\")\n    model_path = os.path.join(tokenizer_path, \"model.pth\")\n    config = json.load(open(config_path))\n    model = HiggsAudioTokenizer(\n        **config,\n        device=device,\n    )\n    parameter_dict = torch.load(model_path, map_location=device)\n    model.load_state_dict(parameter_dict, strict=False)\n    model.to(device)\n    model.eval()\n    return model\n"
  },
  {
    "path": "boson_multimodal/audio_processing/quantization/__init__.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# flake8: noqa\nfrom .vq import QuantizedResult, ResidualVectorQuantizer\n"
  },
  {
    "path": "boson_multimodal/audio_processing/quantization/ac.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"Arithmetic coder.\"\"\"\n\nimport io\nimport math\nimport random\nimport typing as tp\nimport torch\n\nfrom ..binary import BitPacker, BitUnpacker\n\n\ndef build_stable_quantized_cdf(\n    pdf: torch.Tensor, total_range_bits: int, roundoff: float = 1e-8, min_range: int = 2, check: bool = True\n) -> torch.Tensor:\n    \"\"\"Turn the given PDF into a quantized CDF that splits\n    [0, 2 ** self.total_range_bits - 1] into chunks of size roughly proportional\n    to the PDF.\n\n    Args:\n        pdf (torch.Tensor): probability distribution, shape should be `[N]`.\n        total_range_bits (int): see `ArithmeticCoder`, the typical range we expect\n            during the coding process is `[0, 2 ** total_range_bits - 1]`.\n        roundoff (float): will round the pdf up to that level to remove difference coming\n        from e.g. evaluating the Language Model on different architectures.\n        min_range (int): minimum range width. Should always be at least 2 for numerical\n            stability. Use this to avoid pathological behavior is a value\n            that is expected to be rare actually happens in real life.\n        check (bool): if True, checks that nothing bad happened, can be deactivated for speed.\n    \"\"\"\n    pdf = pdf.detach()\n    if roundoff:\n        pdf = (pdf / roundoff).floor() * roundoff\n    # interpolate with uniform distribution to achieve desired minimum probability.\n    total_range = 2**total_range_bits\n    cardinality = len(pdf)\n    alpha = min_range * cardinality / total_range\n    assert alpha <= 1, \"you must reduce min_range\"\n    ranges = (((1 - alpha) * total_range) * pdf).floor().long()\n    ranges += min_range\n    quantized_cdf = torch.cumsum(ranges, dim=-1)\n    if min_range < 2:\n        raise ValueError(\"min_range must be at least 2.\")\n    if check:\n        assert quantized_cdf[-1] <= 2**total_range_bits, quantized_cdf[-1]\n        if ((quantized_cdf[1:] - quantized_cdf[:-1]) < min_range).any() or quantized_cdf[0] < min_range:\n            raise ValueError(\"You must increase your total_range_bits.\")\n    return quantized_cdf\n\n\nclass ArithmeticCoder:\n    \"\"\"ArithmeticCoder,\n    Let us take a distribution `p` over `N` symbols, and assume we have a stream\n    of random variables `s_t` sampled from `p`. Let us assume that we have a budget\n    of `B` bits that we can afford to write on device. There are `2**B` possible numbers,\n    corresponding to the range `[0, 2 ** B - 1]`. We can map each of those number to a single\n    sequence `(s_t)` by doing the following:\n\n    1) Initialize the current range to` [0 ** 2 B - 1]`.\n    2) For each time step t, split the current range into contiguous chunks,\n        one for each possible outcome, with size roughly proportional to `p`.\n        For instance, if `p = [0.75, 0.25]`, and the range is `[0, 3]`, the chunks\n        would be `{[0, 2], [3, 3]}`.\n    3) Select the chunk corresponding to `s_t`, and replace the current range with this.\n    4) When done encoding all the values, just select any value remaining in the range.\n\n    You will notice that this procedure can fail: for instance if at any point in time\n    the range is smaller than `N`, then we can no longer assign a non-empty chunk to each\n    possible outcome. Intuitively, the more likely a value is, the less the range width\n    will reduce, and the longer we can go on encoding values. This makes sense: for any efficient\n    coding scheme, likely outcomes would take less bits, and more of them can be coded\n    with a fixed budget.\n\n    In practice, we do not know `B` ahead of time, but we have a way to inject new bits\n    when the current range decreases below a given limit (given by `total_range_bits`), without\n    having to redo all the computations. If we encode mostly likely values, we will seldom\n    need to inject new bits, but a single rare value can deplete our stock of entropy!\n\n    In this explanation, we assumed that the distribution `p` was constant. In fact, the present\n    code works for any sequence `(p_t)` possibly different for each timestep.\n    We also assume that `s_t ~ p_t`, but that doesn't need to be true, although the smaller\n    the KL between the true distribution and `p_t`, the most efficient the coding will be.\n\n    Args:\n        fo (IO[bytes]): file-like object to which the bytes will be written to.\n        total_range_bits (int): the range `M` described above is `2 ** total_range_bits.\n            Any time the current range width fall under this limit, new bits will\n            be injected to rescale the initial range.\n    \"\"\"\n\n    def __init__(self, fo: tp.IO[bytes], total_range_bits: int = 24):\n        assert total_range_bits <= 30\n        self.total_range_bits = total_range_bits\n        self.packer = BitPacker(bits=1, fo=fo)  # we push single bits at a time.\n        self.low: int = 0\n        self.high: int = 0\n        self.max_bit: int = -1\n        self._dbg: tp.List[tp.Any] = []\n        self._dbg2: tp.List[tp.Any] = []\n\n    @property\n    def delta(self) -> int:\n        \"\"\"Return the current range width.\"\"\"\n        return self.high - self.low + 1\n\n    def _flush_common_prefix(self):\n        # If self.low and self.high start with the sames bits,\n        # those won't change anymore as we always just increase the range\n        # by powers of 2, and we can flush them out to the bit stream.\n        assert self.high >= self.low, (self.low, self.high)\n        assert self.high < 2 ** (self.max_bit + 1)\n        while self.max_bit >= 0:\n            b1 = self.low >> self.max_bit\n            b2 = self.high >> self.max_bit\n            if b1 == b2:\n                self.low -= b1 << self.max_bit\n                self.high -= b1 << self.max_bit\n                assert self.high >= self.low, (self.high, self.low, self.max_bit)\n                assert self.low >= 0\n                self.max_bit -= 1\n                self.packer.push(b1)\n            else:\n                break\n\n    def push(self, symbol: int, quantized_cdf: torch.Tensor):\n        \"\"\"Push the given symbol on the stream, flushing out bits\n        if possible.\n\n        Args:\n            symbol (int): symbol to encode with the AC.\n            quantized_cdf (torch.Tensor): use `build_stable_quantized_cdf`\n                to build this from your pdf estimate.\n        \"\"\"\n        while self.delta < 2**self.total_range_bits:\n            self.low *= 2\n            self.high = self.high * 2 + 1\n            self.max_bit += 1\n\n        range_low = 0 if symbol == 0 else quantized_cdf[symbol - 1].item()\n        range_high = quantized_cdf[symbol].item() - 1\n        effective_low = int(math.ceil(range_low * (self.delta / (2**self.total_range_bits))))\n        effective_high = int(math.floor(range_high * (self.delta / (2**self.total_range_bits))))\n        assert self.low <= self.high\n        self.high = self.low + effective_high\n        self.low = self.low + effective_low\n        assert self.low <= self.high, (effective_low, effective_high, range_low, range_high)\n        self._dbg.append((self.low, self.high))\n        self._dbg2.append((self.low, self.high))\n        outs = self._flush_common_prefix()\n        assert self.low <= self.high\n        assert self.max_bit >= -1\n        assert self.max_bit <= 61, self.max_bit\n        return outs\n\n    def flush(self):\n        \"\"\"Flush the remaining information to the stream.\"\"\"\n        while self.max_bit >= 0:\n            b1 = (self.low >> self.max_bit) & 1\n            self.packer.push(b1)\n            self.max_bit -= 1\n        self.packer.flush()\n\n\nclass ArithmeticDecoder:\n    \"\"\"ArithmeticDecoder, see `ArithmeticCoder` for a detailed explanation.\n\n    Note that this must be called with **exactly** the same parameters and sequence\n    of quantized cdf as the arithmetic encoder or the wrong values will be decoded.\n\n    If the AC encoder current range is [L, H], with `L` and `H` having the some common\n    prefix (i.e. the same most significant bits), then this prefix will be flushed to the stream.\n    For instances, having read 3 bits `b1 b2 b3`, we know that `[L, H]` is contained inside\n    `[b1 b2 b3 0 ... 0 b1 b3 b3 1 ... 1]`. Now this specific sub-range can only be obtained\n    for a specific sequence of symbols and a binary-search allows us to decode those symbols.\n    At some point, the prefix `b1 b2 b3` will no longer be sufficient to decode new symbols,\n    and we will need to read new bits from the stream and repeat the process.\n\n    \"\"\"\n\n    def __init__(self, fo: tp.IO[bytes], total_range_bits: int = 24):\n        self.total_range_bits = total_range_bits\n        self.low: int = 0\n        self.high: int = 0\n        self.current: int = 0\n        self.max_bit: int = -1\n        self.unpacker = BitUnpacker(bits=1, fo=fo)  # we pull single bits at a time.\n        # Following is for debugging\n        self._dbg: tp.List[tp.Any] = []\n        self._dbg2: tp.List[tp.Any] = []\n        self._last: tp.Any = None\n\n    @property\n    def delta(self) -> int:\n        return self.high - self.low + 1\n\n    def _flush_common_prefix(self):\n        # Given the current range [L, H], if both have a common prefix,\n        # we know we can remove it from our representation to avoid handling large numbers.\n        while self.max_bit >= 0:\n            b1 = self.low >> self.max_bit\n            b2 = self.high >> self.max_bit\n            if b1 == b2:\n                self.low -= b1 << self.max_bit\n                self.high -= b1 << self.max_bit\n                self.current -= b1 << self.max_bit\n                assert self.high >= self.low\n                assert self.low >= 0\n                self.max_bit -= 1\n            else:\n                break\n\n    def pull(self, quantized_cdf: torch.Tensor) -> tp.Optional[int]:\n        \"\"\"Pull a symbol, reading as many bits from the stream as required.\n        This returns `None` when the stream has been exhausted.\n\n        Args:\n            quantized_cdf (torch.Tensor): use `build_stable_quantized_cdf`\n                to build this from your pdf estimate. This must be **exatly**\n                the same cdf as the one used at encoding time.\n        \"\"\"\n        while self.delta < 2**self.total_range_bits:\n            bit = self.unpacker.pull()\n            if bit is None:\n                return None\n            self.low *= 2\n            self.high = self.high * 2 + 1\n            self.current = self.current * 2 + bit\n            self.max_bit += 1\n\n        def bin_search(low_idx: int, high_idx: int):\n            # Binary search is not just for coding interviews :)\n            if high_idx < low_idx:\n                raise RuntimeError(\"Binary search failed\")\n            mid = (low_idx + high_idx) // 2\n            range_low = quantized_cdf[mid - 1].item() if mid > 0 else 0\n            range_high = quantized_cdf[mid].item() - 1\n            effective_low = int(math.ceil(range_low * (self.delta / (2**self.total_range_bits))))\n            effective_high = int(math.floor(range_high * (self.delta / (2**self.total_range_bits))))\n            low = effective_low + self.low\n            high = effective_high + self.low\n            if self.current >= low:\n                if self.current <= high:\n                    return (mid, low, high, self.current)\n                else:\n                    return bin_search(mid + 1, high_idx)\n            else:\n                return bin_search(low_idx, mid - 1)\n\n        self._last = (self.low, self.high, self.current, self.max_bit)\n        sym, self.low, self.high, self.current = bin_search(0, len(quantized_cdf) - 1)\n        self._dbg.append((self.low, self.high, self.current))\n        self._flush_common_prefix()\n        self._dbg2.append((self.low, self.high, self.current))\n\n        return sym\n\n\ndef test():\n    torch.manual_seed(1234)\n    random.seed(1234)\n    for _ in range(4):\n        pdfs = []\n        cardinality = random.randrange(4000)\n        steps = random.randrange(100, 500)\n        fo = io.BytesIO()\n        encoder = ArithmeticCoder(fo)\n        symbols = []\n        for step in range(steps):\n            pdf = torch.softmax(torch.randn(cardinality), dim=0)\n            pdfs.append(pdf)\n            q_cdf = build_stable_quantized_cdf(pdf, encoder.total_range_bits)\n            symbol = torch.multinomial(pdf, 1).item()\n            symbols.append(symbol)\n            encoder.push(symbol, q_cdf)\n        encoder.flush()\n\n        fo.seek(0)\n        decoder = ArithmeticDecoder(fo)\n        for idx, (pdf, symbol) in enumerate(zip(pdfs, symbols)):\n            q_cdf = build_stable_quantized_cdf(pdf, encoder.total_range_bits)\n            decoded_symbol = decoder.pull(q_cdf)\n            assert decoded_symbol == symbol, idx\n        assert decoder.pull(torch.zeros(1)) is None\n\n\nif __name__ == \"__main__\":\n    test()\n"
  },
  {
    "path": "boson_multimodal/audio_processing/quantization/core_vq.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n# This implementation is inspired from\n# https://github.com/lucidrains/vector-quantize-pytorch\n# which is released under MIT License. Hereafter, the original license:\n# MIT License\n#\n# Copyright (c) 2020 Phil Wang\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"Core vector quantization implementation.\"\"\"\n\nimport typing as tp\n\nfrom einops import rearrange, repeat\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nfrom xcodec.quantization.distrib import broadcast_tensors, rank\n\n\ndef default(val: tp.Any, d: tp.Any) -> tp.Any:\n    return val if val is not None else d\n\n\ndef ema_inplace(moving_avg, new, decay: float):\n    moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))\n\n\ndef laplace_smoothing(x, n_categories: int, epsilon: float = 1e-5):\n    return (x + epsilon) / (x.sum() + n_categories * epsilon)\n\n\ndef uniform_init(*shape: int):\n    t = torch.empty(shape)\n    nn.init.kaiming_uniform_(t)\n    return t\n\n\ndef sample_vectors(samples, num: int):\n    num_samples, device = samples.shape[0], samples.device\n\n    if num_samples >= num:\n        indices = torch.randperm(num_samples, device=device)[:num]\n    else:\n        indices = torch.randint(0, num_samples, (num,), device=device)\n\n    return samples[indices]\n\n\ndef kmeans(samples, num_clusters: int, num_iters: int = 10):\n    dim, dtype = samples.shape[-1], samples.dtype\n\n    means = sample_vectors(samples, num_clusters)\n\n    for _ in range(num_iters):\n        diffs = rearrange(samples, \"n d -> n () d\") - rearrange(means, \"c d -> () c d\")\n        dists = -(diffs**2).sum(dim=-1)\n\n        buckets = dists.max(dim=-1).indices\n        bins = torch.bincount(buckets, minlength=num_clusters)\n        zero_mask = bins == 0\n        bins_min_clamped = bins.masked_fill(zero_mask, 1)\n\n        new_means = buckets.new_zeros(num_clusters, dim, dtype=dtype)\n        new_means.scatter_add_(0, repeat(buckets, \"n -> n d\", d=dim), samples)\n        new_means = new_means / bins_min_clamped[..., None]\n\n        means = torch.where(zero_mask[..., None], means, new_means)\n\n    return means, bins\n\n\nclass EuclideanCodebook(nn.Module):\n    \"\"\"Codebook with Euclidean distance.\n    Args:\n        dim (int): Dimension.\n        codebook_size (int): Codebook size.\n        kmeans_init (bool): Whether to use k-means to initialize the codebooks.\n            If set to true, run the k-means algorithm on the first training batch and use\n            the learned centroids as initialization.\n        kmeans_iters (int): Number of iterations used for k-means algorithm at initialization.\n        decay (float): Decay for exponential moving average over the codebooks.\n        epsilon (float): Epsilon value for numerical stability.\n        threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes\n            that have an exponential moving average cluster size less than the specified threshold with\n            randomly selected vector from the current batch.\n    \"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        codebook_size: int,\n        kmeans_init: int = False,\n        kmeans_iters: int = 10,\n        decay: float = 0.99,\n        epsilon: float = 1e-5,\n        threshold_ema_dead_code: int = 2,\n    ):\n        super().__init__()\n        self.decay = decay\n        init_fn: tp.Union[tp.Callable[..., torch.Tensor], tp.Any] = uniform_init if not kmeans_init else torch.zeros\n        embed = init_fn(codebook_size, dim)\n\n        self.codebook_size = codebook_size\n\n        self.kmeans_iters = kmeans_iters\n        self.epsilon = epsilon\n        self.threshold_ema_dead_code = threshold_ema_dead_code\n\n        self.register_buffer(\"inited\", torch.Tensor([not kmeans_init]))\n        self.register_buffer(\"cluster_size\", torch.zeros(codebook_size))\n        self.register_buffer(\"embed\", embed)\n        self.register_buffer(\"embed_avg\", embed.clone())\n\n    @torch.jit.ignore\n    def init_embed_(self, data):\n        if self.inited:\n            return\n\n        embed, cluster_size = kmeans(data, self.codebook_size, self.kmeans_iters)\n        self.embed.data.copy_(embed)\n        self.embed_avg.data.copy_(embed.clone())\n        self.cluster_size.data.copy_(cluster_size)\n        self.inited.data.copy_(torch.Tensor([True]))\n        # Make sure all buffers across workers are in sync after initialization\n        broadcast_tensors(self.buffers())\n\n    def replace_(self, samples, mask):\n        modified_codebook = torch.where(mask[..., None], sample_vectors(samples, self.codebook_size), self.embed)\n        self.embed.data.copy_(modified_codebook)\n\n    def expire_codes_(self, batch_samples):\n        if self.threshold_ema_dead_code == 0:\n            return\n\n        expired_codes = self.cluster_size < self.threshold_ema_dead_code\n        if not torch.any(expired_codes):\n            return\n\n        batch_samples = rearrange(batch_samples, \"... d -> (...) d\")\n        self.replace_(batch_samples, mask=expired_codes)\n        broadcast_tensors(self.buffers())\n\n    def preprocess(self, x):\n        x = rearrange(x, \"... d -> (...) d\")\n        return x\n\n    def quantize(self, x):\n        embed = self.embed.t()\n        dist = -(x.pow(2).sum(1, keepdim=True) - 2 * x @ embed + embed.pow(2).sum(0, keepdim=True))\n        embed_ind = dist.max(dim=-1).indices\n        return embed_ind\n\n    def postprocess_emb(self, embed_ind, shape):\n        return embed_ind.view(*shape[:-1])\n\n    def dequantize(self, embed_ind):\n        quantize = F.embedding(embed_ind, self.embed)  # get embedding based on index\n        return quantize\n\n    def encode(self, x):\n        shape = x.shape\n        # pre-process\n        x = self.preprocess(x)\n        # quantize\n        embed_ind = self.quantize(x)  # get index based on Euclidean distance\n        # post-process\n        embed_ind = self.postprocess_emb(embed_ind, shape)\n        return embed_ind\n\n    def decode(self, embed_ind):\n        quantize = self.dequantize(embed_ind)\n        return quantize\n\n    def forward(self, x):\n        shape, dtype = x.shape, x.dtype\n        x = self.preprocess(x)\n\n        self.init_embed_(x)\n\n        embed_ind = self.quantize(x)\n        embed_onehot = F.one_hot(embed_ind, self.codebook_size).type(dtype)\n        embed_ind = self.postprocess_emb(embed_ind, shape)\n        quantize = self.dequantize(embed_ind)\n\n        if self.training:\n            # We do the expiry of code at that point as buffers are in sync\n            # and all the workers will take the same decision.\n            self.expire_codes_(x)\n            ema_inplace(self.cluster_size, embed_onehot.sum(0), self.decay)\n            embed_sum = x.t() @ embed_onehot\n            ema_inplace(self.embed_avg, embed_sum.t(), self.decay)\n            cluster_size = (\n                laplace_smoothing(self.cluster_size, self.codebook_size, self.epsilon) * self.cluster_size.sum()\n            )\n            embed_normalized = self.embed_avg / cluster_size.unsqueeze(1)\n            self.embed.data.copy_(embed_normalized)\n\n        return quantize, embed_ind\n\n\nclass VectorQuantization(nn.Module):\n    \"\"\"Vector quantization implementation.\n    Currently supports only euclidean distance.\n    Args:\n        dim (int): Dimension\n        codebook_size (int): Codebook size\n        codebook_dim (int): Codebook dimension. If not defined, uses the specified dimension in dim.\n        decay (float): Decay for exponential moving average over the codebooks.\n        epsilon (float): Epsilon value for numerical stability.\n        kmeans_init (bool): Whether to use kmeans to initialize the codebooks.\n        kmeans_iters (int): Number of iterations used for kmeans initialization.\n        threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes\n            that have an exponential moving average cluster size less than the specified threshold with\n            randomly selected vector from the current batch.\n        commitment_weight (float): Weight for commitment loss.\n    \"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        codebook_size: int,\n        codebook_dim: tp.Optional[int] = None,\n        decay: float = 0.99,\n        epsilon: float = 1e-5,\n        kmeans_init: bool = True,\n        kmeans_iters: int = 50,\n        threshold_ema_dead_code: int = 2,\n        commitment_weight: float = 1.0,\n    ):\n        super().__init__()\n        _codebook_dim: int = default(codebook_dim, dim)\n\n        requires_projection = _codebook_dim != dim\n        self.project_in = nn.Linear(dim, _codebook_dim) if requires_projection else nn.Identity()\n        self.project_out = nn.Linear(_codebook_dim, dim) if requires_projection else nn.Identity()\n\n        self.epsilon = epsilon\n        self.commitment_weight = commitment_weight\n\n        self._codebook = EuclideanCodebook(\n            dim=_codebook_dim,\n            codebook_size=codebook_size,\n            kmeans_init=kmeans_init,\n            kmeans_iters=kmeans_iters,\n            decay=decay,\n            epsilon=epsilon,\n            threshold_ema_dead_code=threshold_ema_dead_code,\n        )\n        self.codebook_size = codebook_size\n\n    @property\n    def codebook(self):\n        return self._codebook.embed\n\n    def encode(self, x):\n        x = rearrange(x, \"b d n -> b n d\")\n        x = self.project_in(x)\n        embed_in = self._codebook.encode(x)\n        return embed_in\n\n    def decode(self, embed_ind):\n        quantize = self._codebook.decode(embed_ind)\n        quantize = self.project_out(quantize)\n        quantize = rearrange(quantize, \"b n d -> b d n\")\n        return quantize\n\n    def forward(self, x):\n        device = x.device\n        x = rearrange(x, \"b d n -> b n d\")\n        x = self.project_in(x)\n\n        quantize, embed_ind = self._codebook(x)\n\n        if self.training:\n            quantize = x + (quantize - x).detach()\n\n        loss = torch.tensor([0.0], device=device, requires_grad=self.training)\n\n        if self.training:\n            if self.commitment_weight > 0:\n                commit_loss = F.mse_loss(quantize.detach(), x)\n                loss = loss + commit_loss * self.commitment_weight\n\n        quantize = self.project_out(quantize)\n        quantize = rearrange(quantize, \"b n d -> b d n\")\n        return quantize, embed_ind, loss\n\n\nclass ResidualVectorQuantization(nn.Module):\n    \"\"\"Residual vector quantization implementation.\n    Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf\n    \"\"\"\n\n    def __init__(self, *, num_quantizers, **kwargs):\n        super().__init__()\n        self.layers = nn.ModuleList([VectorQuantization(**kwargs) for _ in range(num_quantizers)])\n\n    def forward(self, x, n_q: tp.Optional[int] = None):\n        quantized_out = 0.0\n        residual = x\n\n        all_losses = []\n        all_indices = []\n\n        n_q = n_q or len(self.layers)\n\n        for layer in self.layers[:n_q]:\n            quantized, indices, loss = layer(residual)\n            residual = residual - quantized\n            quantized_out = quantized_out + quantized\n\n            all_indices.append(indices)\n            all_losses.append(loss)\n\n        out_losses, out_indices = map(torch.stack, (all_losses, all_indices))\n        return quantized_out, out_indices, out_losses\n\n    def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None) -> torch.Tensor:\n        residual = x\n        all_indices = []\n        n_q = n_q or len(self.layers)\n        for layer in self.layers[:n_q]:\n            indices = layer.encode(residual)\n            quantized = layer.decode(indices)\n            residual = residual - quantized\n            all_indices.append(indices)\n        out_indices = torch.stack(all_indices)\n        return out_indices\n\n    def decode(self, q_indices: torch.Tensor) -> torch.Tensor:\n        quantized_out = torch.tensor(0.0, device=q_indices.device)\n        for i, indices in enumerate(q_indices):\n            layer = self.layers[i]\n            quantized = layer.decode(indices)\n            quantized_out = quantized_out + quantized\n        return quantized_out\n"
  },
  {
    "path": "boson_multimodal/audio_processing/quantization/core_vq_lsx_version.py",
    "content": "# Copyright (c)\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n# This implementation is inspired from\n# https://github.com/rosinality/vq-vae-2-pytorch/blob/master/vqvae.py and\n# https://github.com/clementchadebec/benchmark_VAE/blob/dfa0dcf6c79172df5d27769c09c860c42008baaa/src/pythae/models/vq_vae/vq_vae_utils.py#L81\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n# This implementation is inspired from\n# https://github.com/lucidrains/vector-quantize-pytorch\n# which is released under MIT License. Hereafter, the original license:\n# MIT License\n#\n# Copyright (c) 2020 Phil Wang\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"Core vector quantization implementation.\"\"\"\n\nimport typing as tp\n\nfrom einops import rearrange\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport torch.distributed as dist\n\nfrom .distrib import broadcast_tensors, is_distributed\nfrom .ddp_utils import SyncFunction\n\n\ndef default(val: tp.Any, d: tp.Any) -> tp.Any:\n    return val if val is not None else d\n\n\ndef ema_inplace(moving_avg, new, decay: float):\n    moving_avg.data.mul_(decay).add_(new, alpha=(1 - decay))\n\n\ndef laplace_smoothing(x, n_categories: int, epsilon: float = 1e-5):\n    return (x + epsilon) / (x.sum() + n_categories * epsilon)\n\n\ndef uniform_init(*shape: int):\n    t = torch.empty(shape)\n    nn.init.kaiming_uniform_(t)\n    return t\n\n\ndef sample_vectors(samples, num: int):\n    num_samples, device = samples.shape[0], samples.device\n\n    if num_samples >= num:\n        indices = torch.randperm(num_samples, device=device)[:num]\n    else:\n        indices = torch.randint(0, num_samples, (num,), device=device)\n\n    return samples[indices]\n\n\ndef kmeans(samples, num_clusters: int, num_iters: int = 10, frames_to_use: int = 10_000, batch_size: int = 64):\n    \"\"\"\n    Memory-efficient K-means clustering.\n    Args:\n        samples (tensor): shape [N, D]\n        num_clusters (int): number of centroids.\n        num_iters (int): number of iterations.\n        frames_to_use (int): subsample size from total samples.\n        batch_size (int): batch size used in distance computation.\n    Returns:\n        means: [num_clusters, D]\n        bins: [num_clusters] (number of points per cluster)\n    \"\"\"\n    N, D = samples.shape\n    dtype, device = samples.dtype, samples.device\n\n    if frames_to_use < N:\n        indices = torch.randperm(N, device=device)[:frames_to_use]\n        samples = samples[indices]\n\n    means = sample_vectors(samples, num_clusters)\n\n    for _ in range(num_iters):\n        # Store cluster assignments\n        all_assignments = []\n\n        for i in range(0, samples.shape[0], batch_size):\n            batch = samples[i : i + batch_size]  # [B, D]\n            dists = torch.cdist(batch, means, p=2)  # [B, C]\n            assignments = dists.argmin(dim=1)  # [B]\n            all_assignments.append(assignments)\n\n        buckets = torch.cat(all_assignments, dim=0)  # [N]\n        bins = torch.bincount(buckets, minlength=num_clusters)\n        zero_mask = bins == 0\n        bins_min_clamped = bins.masked_fill(zero_mask, 1)\n\n        # Compute new means\n        new_means = torch.zeros_like(means)\n        for i in range(num_clusters):\n            mask = buckets == i\n            if mask.any():\n                new_means[i] = samples[mask].mean(dim=0)\n\n        means = torch.where(zero_mask[:, None], means, new_means)\n\n    return means, bins\n\n\nclass EuclideanCodebook(nn.Module):\n    \"\"\"Codebook with Euclidean distance.\n    Args:\n        dim (int): Dimension.\n        codebook_size (int): Codebook size.\n        kmeans_init (bool): Whether to use k-means to initialize the codebooks.\n            If set to true, run the k-means algorithm on the first training batch and use\n            the learned centroids as initialization.\n        kmeans_iters (int): Number of iterations used for k-means algorithm at initialization.\n        decay (float): Decay for exponential moving average over the codebooks.\n        epsilon (float): Epsilon value for numerical stability.\n        threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes\n            that have an exponential moving average cluster size less than the specified threshold with\n            randomly selected vector from the current batch.\n    \"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        codebook_size: int,\n        kmeans_init: int = False,\n        kmeans_iters: int = 10,\n        decay: float = 0.99,\n        epsilon: float = 1e-5,\n        threshold_ema_dead_code: int = 2,\n    ):\n        super().__init__()\n        self.decay = decay\n        init_fn: tp.Union[tp.Callable[..., torch.Tensor], tp.Any] = uniform_init if not kmeans_init else torch.zeros\n        embed = init_fn(codebook_size, dim)\n\n        self.codebook_size = codebook_size\n\n        self.kmeans_iters = kmeans_iters\n        self.epsilon = epsilon\n        self.threshold_ema_dead_code = threshold_ema_dead_code\n\n        # Flag variable to indicate whether the codebook is initialized\n        self.register_buffer(\"inited\", torch.Tensor([not kmeans_init]))\n        # Runing EMA cluster size/count: N_i^t in eq. (6) in vqvae paper\n        self.register_buffer(\"cluster_size\", torch.zeros(codebook_size))\n        # Codebook\n        self.register_buffer(\"embed\", embed)\n        # EMA codebook: eq. (7) in vqvae paper\n        self.register_buffer(\"embed_avg\", embed.clone())\n\n    @torch.jit.ignore\n    def init_embed_(self, data):\n        \"\"\"Initialize codebook.\n        Args:\n            data (tensor): [B * T, D].\n        \"\"\"\n        if self.inited:\n            return\n\n        ## NOTE (snippet added by Songxiang Liu): gather data from all gpus\n        if dist.is_available() and dist.is_initialized():\n            # [B * T * world_size, D]\n            data = SyncFunction.apply(data)\n\n        embed, cluster_size = kmeans(data, self.codebook_size, self.kmeans_iters)\n        self.embed.data.copy_(embed)\n        self.embed_avg.data.copy_(embed.clone())\n        self.cluster_size.data.copy_(cluster_size)\n        self.inited.data.copy_(torch.Tensor([True]))\n        # Make sure all buffers across workers are in sync after initialization\n        broadcast_tensors(self.buffers())\n\n    def replace_(self, samples, mask):\n        modified_codebook = torch.where(mask[..., None], sample_vectors(samples, self.codebook_size), self.embed)\n        self.embed.data.copy_(modified_codebook)\n\n    def expire_codes_(self, batch_samples):\n        if self.threshold_ema_dead_code == 0:\n            return\n\n        expired_codes = self.cluster_size < self.threshold_ema_dead_code\n        if not torch.any(expired_codes):\n            return\n\n        ## NOTE (snippet added by Songxiang Liu): gather data from all gpus\n        if is_distributed():\n            # [B * T * world_size, D]\n            batch_samples = SyncFunction.apply(batch_samples)\n\n        batch_samples = rearrange(batch_samples, \"... d -> (...) d\")\n        self.replace_(batch_samples, mask=expired_codes)\n        broadcast_tensors(self.buffers())\n\n    def preprocess(self, x):\n        x = rearrange(x, \"... d -> (...) d\")\n        return x\n\n    def quantize(self, x):\n        embed = self.embed.t()\n        dist = -(x.pow(2).sum(1, keepdim=True) - 2 * x @ embed + embed.pow(2).sum(0, keepdim=True))\n        embed_ind = dist.max(dim=-1).indices\n        return embed_ind\n\n    def postprocess_emb(self, embed_ind, shape):\n        return embed_ind.view(*shape[:-1])\n\n    def dequantize(self, embed_ind):\n        quantize = F.embedding(embed_ind, self.embed)\n        return quantize\n\n    def encode(self, x):\n        shape = x.shape\n        # pre-process\n        x = self.preprocess(x)  # [B, T, D] -> [B*T, D]\n        # quantize\n        embed_ind = self.quantize(x)\n        # post-process\n        embed_ind = self.postprocess_emb(embed_ind, shape)\n        return embed_ind\n\n    def decode(self, embed_ind):\n        quantize = self.dequantize(embed_ind)\n        return quantize\n\n    def forward(self, x):\n        # shape: [B, T, D]\n        shape, dtype = x.shape, x.dtype\n        x = self.preprocess(x)  # [B, T, D] -> [B*T, D]\n\n        # Initialize codebook\n        self.init_embed_(x)\n\n        embed_ind = self.quantize(x)  # [B*T,]\n        embed_onehot = F.one_hot(embed_ind, self.codebook_size).type(dtype)  # [B*T, cb-size]\n        embed_ind = self.postprocess_emb(embed_ind, shape)  # [B, T]\n        quantize = self.dequantize(embed_ind)  # [B, T, D]\n\n        if self.training:\n            ### Update codebook by EMA\n            embed_onehot_sum = embed_onehot.sum(0)  # [cb-size,]\n            embed_sum = x.t() @ embed_onehot  # [D, cb-size]\n            if is_distributed():\n                dist.all_reduce(embed_onehot_sum)\n                dist.all_reduce(embed_sum)\n            # Update ema cluster count N_i^t, eq. (6) in vqvae paper\n            self.cluster_size.data.mul_(self.decay).add_(embed_onehot_sum, alpha=1 - self.decay)\n            # Update ema embed: eq. (7) in vqvae paper\n            self.embed_avg.data.mul_(self.decay).add_(embed_sum.t(), alpha=1 - self.decay)\n            # apply laplace smoothing\n            n = self.cluster_size.sum()\n            cluster_size = (self.cluster_size + self.epsilon) / (n + self.codebook_size * self.epsilon) * n\n            # Update ema embed: eq. (8) in vqvae paper\n            embed_normalized = self.embed_avg / cluster_size.unsqueeze(1)\n            self.embed.data.copy_(embed_normalized)\n\n            # We do the expiry of code at that point as buffers are in sync\n            # and all the workers will take the same decision.\n            self.expire_codes_(x)\n\n        return quantize, embed_ind\n\n\nclass VectorQuantization(nn.Module):\n    \"\"\"Vector quantization implementation.\n    Currently supports only euclidean distance.\n    Args:\n        dim (int): Dimension\n        codebook_size (int): Codebook size\n        codebook_dim (int): Codebook dimension. If not defined, uses the specified dimension in dim.\n        decay (float): Decay for exponential moving average over the codebooks.\n        epsilon (float): Epsilon value for numerical stability.\n        kmeans_init (bool): Whether to use kmeans to initialize the codebooks.\n        kmeans_iters (int): Number of iterations used for kmeans initialization.\n        threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes\n            that have an exponential moving average cluster size less than the specified threshold with\n            randomly selected vector from the current batch.\n        commitment_weight (float): Weight for commitment loss.\n    \"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        codebook_size: int,\n        codebook_dim: tp.Optional[int] = None,\n        decay: float = 0.99,\n        epsilon: float = 1e-5,\n        kmeans_init: bool = True,\n        kmeans_iters: int = 50,\n        threshold_ema_dead_code: int = 2,\n        commitment_weight: float = 1.0,\n    ):\n        super().__init__()\n        _codebook_dim: int = default(codebook_dim, dim)\n\n        requires_projection = _codebook_dim != dim\n        self.project_in = nn.Linear(dim, _codebook_dim) if requires_projection else nn.Identity()\n        self.project_out = nn.Linear(_codebook_dim, dim) if requires_projection else nn.Identity()\n\n        self.epsilon = epsilon\n        self.commitment_weight = commitment_weight\n\n        self._codebook = EuclideanCodebook(\n            dim=_codebook_dim,\n            codebook_size=codebook_size,\n            kmeans_init=kmeans_init,\n            kmeans_iters=kmeans_iters,\n            decay=decay,\n            epsilon=epsilon,\n            threshold_ema_dead_code=threshold_ema_dead_code,\n        )\n        self.codebook_size = codebook_size\n\n    @property\n    def codebook(self):\n        return self._codebook.embed\n\n    def encode(self, x):\n        x = rearrange(x, \"b d n -> b n d\")\n        x = self.project_in(x)\n        embed_in = self._codebook.encode(x)\n        return embed_in\n\n    def decode(self, embed_ind):\n        quantize = self._codebook.decode(embed_ind)\n        quantize = self.project_out(quantize)\n        quantize = rearrange(quantize, \"b n d -> b d n\")\n        return quantize\n\n    def forward(self, x):\n        device = x.device\n        x = x.transpose(1, 2).contiguous()  # [b d n] -> [b n d]\n        x = self.project_in(x)\n\n        quantize, embed_ind = self._codebook(x)\n\n        if self.training:\n            quantize = x + (quantize - x).detach()\n\n        loss = torch.tensor([0.0], device=device, requires_grad=self.training)\n\n        if self.training:\n            if self.commitment_weight > 0:\n                commit_loss = F.mse_loss(quantize.detach(), x)\n                loss = loss + commit_loss * self.commitment_weight\n\n        quantize = self.project_out(quantize)\n        quantize = quantize.transpose(1, 2).contiguous()  # [b n d] -> [b d n]\n        return quantize, embed_ind, loss\n\n\nclass ResidualVectorQuantization(nn.Module):\n    \"\"\"Residual vector quantization implementation.\n    Follows Algorithm 1. in https://arxiv.org/pdf/2107.03312.pdf\n    \"\"\"\n\n    def __init__(self, *, num_quantizers, **kwargs):\n        super().__init__()\n        self.layers = nn.ModuleList([VectorQuantization(**kwargs) for _ in range(num_quantizers)])\n\n    def forward(self, x, n_q: tp.Optional[int] = None):\n        quantized_out = 0.0\n        residual = x\n\n        all_losses = []\n        all_indices = []\n\n        n_q = n_q or len(self.layers)\n\n        for layer in self.layers[:n_q]:\n            quantized, indices, loss = layer(residual)\n            residual = residual - quantized\n            quantized_out = quantized_out + quantized\n\n            all_indices.append(indices)\n            all_losses.append(loss)\n\n        out_losses, out_indices = map(torch.stack, (all_losses, all_indices))\n        return quantized_out, out_indices, out_losses\n\n    def encode(self, x: torch.Tensor, n_q: tp.Optional[int] = None) -> torch.Tensor:\n        residual = x\n        all_indices = []\n        n_q = n_q or len(self.layers)\n        for layer in self.layers[:n_q]:\n            indices = layer.encode(residual)\n            quantized = layer.decode(indices)\n            residual = residual - quantized\n            all_indices.append(indices)\n        out_indices = torch.stack(all_indices)\n        return out_indices\n\n    def decode(self, q_indices: torch.Tensor) -> torch.Tensor:\n        quantized_out = torch.tensor(0.0, device=q_indices.device)\n        for i, indices in enumerate(q_indices):\n            layer = self.layers[i]\n            quantized = layer.decode(indices)\n            quantized_out = quantized_out + quantized\n        return quantized_out\n"
  },
  {
    "path": "boson_multimodal/audio_processing/quantization/ddp_utils.py",
    "content": "import logging\nimport random\nimport subprocess\nfrom datetime import datetime\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.nn.parallel.distributed import _find_tensors\nimport torch.optim\nimport torch.utils.data\nfrom packaging import version\nfrom omegaconf import OmegaConf\n\n\ndef set_random_seed(seed):\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n\n\ndef is_logging_process():\n    return not dist.is_initialized() or dist.get_rank() == 0\n\n\ndef get_logger(cfg, name=None):\n    # log_file_path is used when unit testing\n    if is_logging_process():\n        logging.config.dictConfig(OmegaConf.to_container(cfg.job_logging_config, resolve=True))\n        return logging.getLogger(name)\n\n\n# from https://github.com/Lightning-AI/lightning-bolts/blob/5d61197cd2f491f69e238137a5edabe80ae14ad9/pl_bolts/models/self_supervised/simclr/simclr_module.py#L20\nclass SyncFunction(torch.autograd.Function):\n    @staticmethod\n    # @torch.no_grad()\n    def forward(ctx, tensor):\n        ctx.batch_size = tensor.shape[0]\n\n        gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]\n\n        torch.distributed.all_gather(gathered_tensor, tensor)\n        gathered_tensor = torch.cat(gathered_tensor, 0)\n\n        return gathered_tensor\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        grad_input = grad_output.clone()\n        torch.distributed.all_reduce(grad_input, op=torch.distributed.ReduceOp.SUM, async_op=False)\n\n        idx_from = torch.distributed.get_rank() * ctx.batch_size\n        idx_to = (torch.distributed.get_rank() + 1) * ctx.batch_size\n        return grad_input[idx_from:idx_to]\n\n\ndef get_timestamp():\n    return datetime.now().strftime(\"%y%m%d-%H%M%S\")\n\n\ndef get_commit_hash():\n    message = subprocess.check_output([\"git\", \"rev-parse\", \"--short\", \"HEAD\"])\n    return message.strip().decode(\"utf-8\")\n\n\nclass DDP(DistributedDataParallel):\n    \"\"\"\n    Override the forward call in lightning so it goes to training and validation step respectively\n    \"\"\"\n\n    def forward(self, *inputs, **kwargs):  # pragma: no cover\n        if version.parse(torch.__version__[:6]) < version.parse(\"1.11\"):\n            self._sync_params()\n            inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)\n            assert len(self.device_ids) == 1\n            if self.module.training:\n                output = self.module.training_step(*inputs[0], **kwargs[0])\n            elif self.module.testing:\n                output = self.module.test_step(*inputs[0], **kwargs[0])\n            else:\n                output = self.module.validation_step(*inputs[0], **kwargs[0])\n            if torch.is_grad_enabled():\n                # We'll return the output object verbatim since it is a freeform\n                # object. We need to find any tensors in this object, though,\n                # because we need to figure out which parameters were used during\n                # this forward pass, to ensure we short circuit reduction for any\n                # unused parameters. Only if `find_unused_parameters` is set.\n                if self.find_unused_parameters:\n                    self.reducer.prepare_for_backward(list(_find_tensors(output)))\n                else:\n                    self.reducer.prepare_for_backward([])\n        else:\n            from torch.nn.parallel.distributed import (\n                logging,\n                Join,\n                _DDPSink,\n                _tree_flatten_with_rref,\n                _tree_unflatten_with_rref,\n            )\n\n            with torch.autograd.profiler.record_function(\"DistributedDataParallel.forward\"):\n                if torch.is_grad_enabled() and self.require_backward_grad_sync:\n                    self.logger.set_runtime_stats_and_log()\n                    self.num_iterations += 1\n                    self.reducer.prepare_for_forward()\n\n                # Notify the join context that this process has not joined, if\n                # needed\n                work = Join.notify_join_context(self)\n                if work:\n                    self.reducer._set_forward_pass_work_handle(work, self._divide_by_initial_world_size)\n\n                # Calling _rebuild_buckets before forward compuation,\n                # It may allocate new buckets before deallocating old buckets\n                # inside _rebuild_buckets. To save peak memory usage,\n                # call _rebuild_buckets before the peak memory usage increases\n                # during forward computation.\n                # This should be called only once during whole training period.\n                if torch.is_grad_enabled() and self.reducer._rebuild_buckets():\n                    logging.info(\"Reducer buckets have been rebuilt in this iteration.\")\n                    self._has_rebuilt_buckets = True\n\n                # sync params according to location (before/after forward) user\n                # specified as part of hook, if hook was specified.\n                buffer_hook_registered = hasattr(self, \"buffer_hook\")\n                if self._check_sync_bufs_pre_fwd():\n                    self._sync_buffers()\n\n                if self._join_config.enable:\n                    # Notify joined ranks whether they should sync in backwards pass or not.\n                    self._check_global_requires_backward_grad_sync(is_joined_rank=False)\n\n                inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)\n                if self.module.training:\n                    output = self.module.training_step(*inputs[0], **kwargs[0])\n                elif self.module.testing:\n                    output = self.module.test_step(*inputs[0], **kwargs[0])\n                else:\n                    output = self.module.validation_step(*inputs[0], **kwargs[0])\n\n                # sync params according to location (before/after forward) user\n                # specified as part of hook, if hook was specified.\n                if self._check_sync_bufs_post_fwd():\n                    self._sync_buffers()\n\n                if torch.is_grad_enabled() and self.require_backward_grad_sync:\n                    self.require_forward_param_sync = True\n                    # We'll return the output object verbatim since it is a freeform\n                    # object. We need to find any tensors in this object, though,\n                    # because we need to figure out which parameters were used during\n                    # this forward pass, to ensure we short circuit reduction for any\n                    # unused parameters. Only if `find_unused_parameters` is set.\n                    if self.find_unused_parameters and not self.static_graph:\n                        # Do not need to populate this for static graph.\n                        self.reducer.prepare_for_backward(list(_find_tensors(output)))\n                    else:\n                        self.reducer.prepare_for_backward([])\n                else:\n                    self.require_forward_param_sync = False\n\n            # TODO: DDPSink is currently enabled for unused parameter detection and\n            # static graph training for first iteration.\n            if (self.find_unused_parameters and not self.static_graph) or (\n                self.static_graph and self.num_iterations == 1\n            ):\n                state_dict = {\n                    \"static_graph\": self.static_graph,\n                    \"num_iterations\": self.num_iterations,\n                }\n\n                output_tensor_list, treespec, output_is_rref = _tree_flatten_with_rref(output)\n                output_placeholders = [None for _ in range(len(output_tensor_list))]\n                # Do not touch tensors that have no grad_fn, which can cause issues\n                # such as https://github.com/pytorch/pytorch/issues/60733\n                for i, output in enumerate(output_tensor_list):\n                    if torch.is_tensor(output) and output.grad_fn is None:\n                        output_placeholders[i] = output\n\n                # When find_unused_parameters=True, makes tensors which require grad\n                # run through the DDPSink backward pass. When not all outputs are\n                # used in loss, this makes those corresponding tensors receive\n                # undefined gradient which the reducer then handles to ensure\n                # param.grad field is not touched and we don't error out.\n                passthrough_tensor_list = _DDPSink.apply(\n                    self.reducer,\n                    state_dict,\n                    *output_tensor_list,\n                )\n                for i in range(len(output_placeholders)):\n                    if output_placeholders[i] is None:\n                        output_placeholders[i] = passthrough_tensor_list[i]\n\n                # Reconstruct output data structure.\n                output = _tree_unflatten_with_rref(output_placeholders, treespec, output_is_rref)\n        return output\n"
  },
  {
    "path": "boson_multimodal/audio_processing/quantization/distrib.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"Torch distributed utilities.\"\"\"\n\nimport typing as tp\n\nimport torch\n\n\ndef rank():\n    if torch.distributed.is_initialized():\n        return torch.distributed.get_rank()\n    else:\n        return 0\n\n\ndef world_size():\n    if torch.distributed.is_initialized():\n        return torch.distributed.get_world_size()\n    else:\n        return 1\n\n\ndef is_distributed():\n    return world_size() > 1\n\n\ndef all_reduce(tensor: torch.Tensor, op=torch.distributed.ReduceOp.SUM):\n    if is_distributed():\n        return torch.distributed.all_reduce(tensor, op)\n\n\ndef _is_complex_or_float(tensor):\n    return torch.is_floating_point(tensor) or torch.is_complex(tensor)\n\n\ndef _check_number_of_params(params: tp.List[torch.Tensor]):\n    # utility function to check that the number of params in all workers is the same,\n    # and thus avoid a deadlock with distributed all reduce.\n    if not is_distributed() or not params:\n        return\n    # print('params[0].device ', params[0].device)\n    tensor = torch.tensor([len(params)], device=params[0].device, dtype=torch.long)\n    all_reduce(tensor)\n    if tensor.item() != len(params) * world_size():\n        # If not all the workers have the same number, for at least one of them,\n        # this inequality will be verified.\n        raise RuntimeError(\n            f\"Mismatch in number of params: ours is {len(params)}, at least one worker has a different one.\"\n        )\n\n\ndef broadcast_tensors(tensors: tp.Iterable[torch.Tensor], src: int = 0):\n    \"\"\"Broadcast the tensors from the given parameters to all workers.\n    This can be used to ensure that all workers have the same model to start with.\n    \"\"\"\n    if not is_distributed():\n        return\n    tensors = [tensor for tensor in tensors if _is_complex_or_float(tensor)]\n    _check_number_of_params(tensors)\n    handles = []\n    for tensor in tensors:\n        handle = torch.distributed.broadcast(tensor.data, src=src, async_op=True)\n        handles.append(handle)\n    for handle in handles:\n        handle.wait()\n\n\ndef sync_buffer(buffers, average=True):\n    \"\"\"\n    Sync grad for buffers. If average is False, broadcast instead of averaging.\n    \"\"\"\n    if not is_distributed():\n        return\n    handles = []\n    for buffer in buffers:\n        if torch.is_floating_point(buffer.data):\n            if average:\n                handle = torch.distributed.all_reduce(buffer.data, op=torch.distributed.ReduceOp.SUM, async_op=True)\n            else:\n                handle = torch.distributed.broadcast(buffer.data, src=0, async_op=True)\n            handles.append((buffer, handle))\n    for buffer, handle in handles:\n        handle.wait()\n        if average:\n            buffer.data /= world_size\n\n\ndef sync_grad(params):\n    \"\"\"\n    Simpler alternative to DistributedDataParallel, that doesn't rely\n    on any black magic. For simple models it can also be as fast.\n    Just call this on your model parameters after the call to backward!\n    \"\"\"\n    if not is_distributed():\n        return\n    handles = []\n    for p in params:\n        if p.grad is not None:\n            handle = torch.distributed.all_reduce(p.grad.data, op=torch.distributed.ReduceOp.SUM, async_op=True)\n            handles.append((p, handle))\n    for p, handle in handles:\n        handle.wait()\n        p.grad.data /= world_size()\n\n\ndef average_metrics(metrics: tp.Dict[str, float], count=1.0):\n    \"\"\"Average a dictionary of metrics across all workers, using the optional\n    `count` as unormalized weight.\n    \"\"\"\n    if not is_distributed():\n        return metrics\n    keys, values = zip(*metrics.items())\n    device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n    tensor = torch.tensor(list(values) + [1], device=device, dtype=torch.float32)\n    tensor *= count\n    all_reduce(tensor)\n    averaged = (tensor[:-1] / tensor[-1]).cpu().tolist()\n    return dict(zip(keys, averaged))\n"
  },
  {
    "path": "boson_multimodal/audio_processing/quantization/vq.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"Residual vector quantizer implementation.\"\"\"\n\nfrom dataclasses import dataclass, field\nimport math\nimport typing as tp\n\nimport torch\nfrom torch import nn\n\n# from .core_vq import ResidualVectorQuantization\nfrom .core_vq_lsx_version import ResidualVectorQuantization\n\n\n@dataclass\nclass QuantizedResult:\n    quantized: torch.Tensor\n    codes: torch.Tensor\n    bandwidth: torch.Tensor  # bandwidth in kb/s used, per batch item.\n    penalty: tp.Optional[torch.Tensor] = None\n    metrics: dict = field(default_factory=dict)\n\n\nclass ResidualVectorQuantizer(nn.Module):\n    \"\"\"Residual Vector Quantizer.\n    Args:\n        dimension (int): Dimension of the codebooks.\n        n_q (int): Number of residual vector quantizers used.\n        bins (int): Codebook size.\n        decay (float): Decay for exponential moving average over the codebooks.\n        kmeans_init (bool): Whether to use kmeans to initialize the codebooks.\n        kmeans_iters (int): Number of iterations used for kmeans initialization.\n        threshold_ema_dead_code (int): Threshold for dead code expiration. Replace any codes\n            that have an exponential moving average cluster size less than the specified threshold with\n            randomly selected vector from the current batch.\n    \"\"\"\n\n    def __init__(\n        self,\n        dimension: int = 256,\n        codebook_dim: int = None,\n        n_q: int = 8,\n        bins: int = 1024,\n        decay: float = 0.99,\n        kmeans_init: bool = True,\n        kmeans_iters: int = 50,\n        threshold_ema_dead_code: int = 2,\n    ):\n        super().__init__()\n        self.n_q = n_q\n        self.dimension = dimension\n        self.codebook_dim = codebook_dim\n        self.bins = bins\n        self.decay = decay\n        self.kmeans_init = kmeans_init\n        self.kmeans_iters = kmeans_iters\n        self.threshold_ema_dead_code = threshold_ema_dead_code\n        self.vq = ResidualVectorQuantization(\n            dim=self.dimension,\n            codebook_dim=self.codebook_dim,\n            codebook_size=self.bins,\n            num_quantizers=self.n_q,\n            decay=self.decay,\n            kmeans_init=self.kmeans_init,\n            kmeans_iters=self.kmeans_iters,\n            threshold_ema_dead_code=self.threshold_ema_dead_code,\n        )\n\n    def forward(self, x: torch.Tensor, sample_rate: int, bandwidth: tp.Optional[float] = None):  # -> QuantizedResult:\n        \"\"\"Residual vector quantization on the given input tensor.\n        Args:\n            x (torch.Tensor): Input tensor.\n            sample_rate (int): Sample rate of the input tensor.\n            bandwidth (float): Target bandwidth.\n        Returns:\n            QuantizedResult:\n                The quantized (or approximately quantized) representation with\n                the associated bandwidth and any penalty term for the loss.\n        \"\"\"\n        bw_per_q = self.get_bandwidth_per_quantizer(sample_rate)\n        n_q = self.get_num_quantizers_for_bandwidth(sample_rate, bandwidth)\n        quantized, codes, commit_loss = self.vq(x, n_q=n_q)\n        bw = torch.tensor(n_q * bw_per_q).to(x)\n        return quantized, codes, bw, torch.mean(commit_loss)\n        # return QuantizedResult(quantized, codes, bw, penalty=torch.mean(commit_loss))\n\n    def get_num_quantizers_for_bandwidth(self, sample_rate: int, bandwidth: tp.Optional[float] = None) -> int:\n        \"\"\"Return n_q based on specified target bandwidth.\"\"\"\n        bw_per_q = self.get_bandwidth_per_quantizer(sample_rate)\n        n_q = self.n_q\n        if bandwidth and bandwidth > 0.0:\n            n_q = int(max(1, math.floor(bandwidth / bw_per_q)))\n        return n_q\n\n    def get_bandwidth_per_quantizer(self, sample_rate: int):\n        \"\"\"Return bandwidth per quantizer for a given input sample rate.\"\"\"\n        return math.log2(self.bins) * sample_rate / 1000\n\n    def encode(self, x: torch.Tensor, sample_rate: int, bandwidth: tp.Optional[float] = None) -> torch.Tensor:\n        \"\"\"Encode a given input tensor with the specified sample rate at the given bandwidth.\n        The RVQ encode method sets the appropriate number of quantizer to use\n        and returns indices for each quantizer.\n        \"\"\"\n        n_q = self.get_num_quantizers_for_bandwidth(sample_rate, bandwidth)\n        codes = self.vq.encode(x, n_q=n_q)\n        return codes\n\n    def decode(self, codes: torch.Tensor) -> torch.Tensor:\n        \"\"\"Decode the given codes to the quantized representation.\"\"\"\n        quantized = self.vq.decode(codes)\n        return quantized\n"
  },
  {
    "path": "boson_multimodal/audio_processing/semantic_module.py",
    "content": "# Based on code from: https://github.com/zhenye234/xcodec\n# Licensed under MIT License\n# Modifications by BosonAI\n\nimport torch\nimport torch.nn as nn\n\n\nclass Conv1d1x1(nn.Conv1d):\n    \"\"\"1x1 Conv1d.\"\"\"\n\n    def __init__(self, in_channels, out_channels, bias=True):\n        super(Conv1d1x1, self).__init__(in_channels, out_channels, kernel_size=1, bias=bias)\n\n\nclass Conv1d(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        stride: int = 1,\n        padding: int = -1,\n        dilation: int = 1,\n        groups: int = 1,\n        bias: bool = True,\n    ):\n        super().__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.kernel_size = kernel_size\n        if padding < 0:\n            padding = (kernel_size - 1) // 2 * dilation\n        self.dilation = dilation\n        self.conv = nn.Conv1d(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=kernel_size,\n            stride=stride,\n            padding=padding,\n            dilation=dilation,\n            groups=groups,\n            bias=bias,\n        )\n\n    def forward(self, x):\n        \"\"\"\n        Args:\n            x (Tensor): Float tensor variable with the shape  (B, C, T).\n        Returns:\n            Tensor: Float tensor variable with the shape (B, C, T).\n        \"\"\"\n        x = self.conv(x)\n        return x\n\n\nclass ResidualUnit(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size=3,\n        dilation=1,\n        bias=False,\n        nonlinear_activation=\"ELU\",\n        nonlinear_activation_params={},\n    ):\n        super().__init__()\n        self.activation = getattr(nn, nonlinear_activation)(**nonlinear_activation_params)\n        self.conv1 = Conv1d(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=kernel_size,\n            stride=1,\n            dilation=dilation,\n            bias=bias,\n        )\n        self.conv2 = Conv1d1x1(out_channels, out_channels, bias)\n\n    def forward(self, x):\n        y = self.conv1(self.activation(x))\n        y = self.conv2(self.activation(y))\n        return x + y\n\n\nclass ConvTranspose1d(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        stride: int,\n        padding=-1,\n        output_padding=-1,\n        groups=1,\n        bias=True,\n    ):\n        super().__init__()\n        if padding < 0:\n            padding = (stride + 1) // 2\n        if output_padding < 0:\n            output_padding = 1 if stride % 2 else 0\n        self.deconv = nn.ConvTranspose1d(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=kernel_size,\n            stride=stride,\n            padding=padding,\n            output_padding=output_padding,\n            groups=groups,\n            bias=bias,\n        )\n\n    def forward(self, x):\n        \"\"\"\n        Args:\n            x (Tensor): Float tensor variable with the shape  (B, C, T).\n        Returns:\n            Tensor: Float tensor variable with the shape (B, C', T').\n        \"\"\"\n        x = self.deconv(x)\n        return x\n\n\nclass EncoderBlock(nn.Module):\n    def __init__(\n        self, in_channels: int, out_channels: int, stride: int, dilations=(1, 1), unit_kernel_size=3, bias=True\n    ):\n        super().__init__()\n        self.res_units = torch.nn.ModuleList()\n        for dilation in dilations:\n            self.res_units += [ResidualUnit(in_channels, in_channels, kernel_size=unit_kernel_size, dilation=dilation)]\n        self.num_res = len(self.res_units)\n\n        self.conv = Conv1d(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=3 if stride == 1 else (2 * stride),  # special case: stride=1, do not use kernel=2\n            stride=stride,\n            bias=bias,\n        )\n\n    def forward(self, x):\n        for idx in range(self.num_res):\n            x = self.res_units[idx](x)\n        x = self.conv(x)\n        return x\n\n\nclass Encoder(nn.Module):\n    def __init__(\n        self,\n        input_channels: int,\n        encode_channels: int,\n        channel_ratios=(1, 1),\n        strides=(1, 1),\n        kernel_size=3,\n        bias=True,\n        block_dilations=(1, 1),\n        unit_kernel_size=3,\n    ):\n        super().__init__()\n        assert len(channel_ratios) == len(strides)\n\n        self.conv = Conv1d(\n            in_channels=input_channels, out_channels=encode_channels, kernel_size=kernel_size, stride=1, bias=False\n        )\n        self.conv_blocks = torch.nn.ModuleList()\n        in_channels = encode_channels\n        for idx, stride in enumerate(strides):\n            out_channels = int(encode_channels * channel_ratios[idx])  # could be float\n            self.conv_blocks += [\n                EncoderBlock(\n                    in_channels,\n                    out_channels,\n                    stride,\n                    dilations=block_dilations,\n                    unit_kernel_size=unit_kernel_size,\n                    bias=bias,\n                )\n            ]\n            in_channels = out_channels\n        self.num_blocks = len(self.conv_blocks)\n        self.out_channels = out_channels\n\n    def forward(self, x):\n        x = self.conv(x)\n        for i in range(self.num_blocks):\n            x = self.conv_blocks[i](x)\n        return x\n\n\nclass DecoderBlock(nn.Module):\n    \"\"\"Decoder block (no up-sampling)\"\"\"\n\n    def __init__(\n        self, in_channels: int, out_channels: int, stride: int, dilations=(1, 1), unit_kernel_size=3, bias=True\n    ):\n        super().__init__()\n\n        if stride == 1:\n            self.conv = Conv1d(\n                in_channels=in_channels,\n                out_channels=out_channels,\n                kernel_size=3,  # fix kernel=3 when stride=1 for unchanged shape\n                stride=stride,\n                bias=bias,\n            )\n        else:\n            self.conv = ConvTranspose1d(\n                in_channels=in_channels,\n                out_channels=out_channels,\n                kernel_size=(2 * stride),\n                stride=stride,\n                bias=bias,\n            )\n\n        self.res_units = torch.nn.ModuleList()\n        for idx, dilation in enumerate(dilations):\n            self.res_units += [\n                ResidualUnit(out_channels, out_channels, kernel_size=unit_kernel_size, dilation=dilation)\n            ]\n        self.num_res = len(self.res_units)\n\n    def forward(self, x):\n        x = self.conv(x)\n        for idx in range(self.num_res):\n            x = self.res_units[idx](x)\n        return x\n\n\nclass Decoder(nn.Module):\n    def __init__(\n        self,\n        code_dim: int,\n        output_channels: int,\n        decode_channels: int,\n        channel_ratios=(1, 1),\n        strides=(1, 1),\n        kernel_size=3,\n        bias=True,\n        block_dilations=(1, 1),\n        unit_kernel_size=3,\n    ):\n        super().__init__()\n        assert len(channel_ratios) == len(strides)\n\n        self.conv1 = Conv1d(\n            in_channels=code_dim,\n            out_channels=int(decode_channels * channel_ratios[0]),\n            kernel_size=kernel_size,\n            stride=1,\n            bias=False,\n        )\n\n        self.conv_blocks = torch.nn.ModuleList()\n        for idx, stride in enumerate(strides):\n            in_channels = int(decode_channels * channel_ratios[idx])\n            if idx < (len(channel_ratios) - 1):\n                out_channels = int(decode_channels * channel_ratios[idx + 1])\n            else:\n                out_channels = decode_channels\n            self.conv_blocks += [\n                DecoderBlock(\n                    in_channels,\n                    out_channels,\n                    stride,\n                    dilations=block_dilations,\n                    unit_kernel_size=unit_kernel_size,\n                    bias=bias,\n                )\n            ]\n        self.num_blocks = len(self.conv_blocks)\n\n        self.conv2 = Conv1d(out_channels, output_channels, kernel_size, 1, bias=False)\n\n    def forward(self, z):\n        x = self.conv1(z)\n        for i in range(self.num_blocks):\n            x = self.conv_blocks[i](x)\n        x = self.conv2(x)\n        return x\n"
  },
  {
    "path": "boson_multimodal/constants.py",
    "content": "AUDIO_IN_TOKEN = \"<|AUDIO|>\"\nAUDIO_OUT_TOKEN = \"<|AUDIO_OUT|>\"\nEOS_TOKEN = \"<|end_of_text|>\"\n"
  },
  {
    "path": "boson_multimodal/data_collator/__init__.py",
    "content": ""
  },
  {
    "path": "boson_multimodal/data_collator/higgs_audio_collator.py",
    "content": "import librosa\nimport torch\nimport torch.nn.functional as F\nimport math\nfrom typing import List, Tuple\n\nfrom dataclasses import dataclass\nfrom typing import List, Optional\nfrom transformers.models.whisper.processing_whisper import WhisperProcessor\n\nfrom ..dataset.chatml_dataset import ChatMLDatasetSample\nfrom ..model.higgs_audio.utils import build_delay_pattern_mask\n\n\ndef _ceil_to_nearest(n, round_to):\n    return (n + round_to - 1) // round_to * round_to\n\n\ndef _ceil_to_next_power_of_two(self, x):\n    return 1 if x == 0 else 2 ** (x - 1).bit_length()\n\n\n@dataclass\nclass HiggsAudioBatchInput:\n    input_ids: torch.LongTensor  # shape (bsz, seq_len).\n    attention_mask: torch.Tensor  # shape (bsz, seq_len).\n    audio_features: Optional[torch.Tensor]  # shape (num_audio_in, feature_dim, max_mel_seq_len).\n    audio_feature_attention_mask: Optional[torch.Tensor]  # shape (num_audio_in, max_mel_seq_len).\n    audio_out_ids: Optional[torch.LongTensor]  # shape (num_codebooks, audio_out_total_length)\n    audio_out_ids_start: Optional[torch.LongTensor]  # shape (num_audio_out,)\n    # The audio_out_ids_start_group_loc has the same length as audio_out_ids_start. It is used to recover group location in a batch for an audio segment\n    # Currently, we concatenante audio segments along dim 0 to handle variadic audio segment length. However, in the alignment stage, we need the location information\n    # For example,\n    #  audio_out_ids_start = [0, 2, 4, 8]; and the first two audio segments come from the same sample in a batch, and other two come from different samples.\n    #  This is a batch of 3 samples, then we will have the group location as:\n    #  audio_out_ids_start_group_loc = [0, 0, 1, 2]\n    audio_out_ids_start_group_loc: Optional[\n        torch.LongTensor\n    ]  # shape (num_audio_out,), specify which a sample's group location in the batch\n    audio_in_ids: Optional[torch.LongTensor]  # shape (num_codebooks, audio_in_total_length)\n    audio_in_ids_start: Optional[torch.LongTensor]  # shape (num_audio_in,)\n    label_ids: Optional[torch.LongTensor]  # shape (bsz, seq_len)\n    label_audio_ids: Optional[torch.LongTensor]  # shape (num_codebooks, audio_out_total_length)\n    reward: Optional[float] = None\n\n\nclass HiggsAudioSampleCollator:\n    \"\"\"Sample collator for Higgs-Audio model.\n\n    Args:\n        whisper_processor (WhisperProcessor): The whisper processor.\n        audio_in_token_id (int): The token id for audio-in.\n        audio_out_token_id (int): The token id for audio-out.\n        pad_token_id (int): The token id for padding.\n        audio_stream_bos_id (int): The token id for audio-stream beginning of sentence.\n        audio_stream_eos_id (int): The token id for audio-stream end of sentence.\n        round_to (int): The round-to value.\n        pad_left (bool): Whether to pad left.\n        return_audio_in_tokens (bool): Whether to return audio-in tokens.\n        use_delay_pattern (bool): Whether to use delay pattern.\n        disable_audio_codes_transform (bool): Whether to add bos and eos tokens to audio codes.\n        chunk_size_seconds (int): The chunk size in seconds.\n        add_new_bos_eos_for_long_chunk (bool): Whether to add new bos and eos tokens for long chunks.\n        mask_audio_out_token_label (bool): Whether to always mask the label associated with <|AUDIO_OUT|> token. Since we will always have `<|AUDIO_OUT|>` after `<|audio_bos|>`, we can safely mask <|AUDIO_OUT|>.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        whisper_processor: WhisperProcessor,\n        audio_in_token_id,\n        audio_out_token_id,\n        pad_token_id,\n        audio_stream_bos_id,\n        audio_stream_eos_id,\n        round_to=8,\n        pad_left=False,\n        encode_whisper_embed=True,\n        return_audio_in_tokens=True,\n        audio_num_codebooks=None,\n        use_delay_pattern=False,\n        disable_audio_codes_transform=False,\n        chunk_size_seconds=30,  # Maximum duration for each chunk\n        add_new_bos_eos_for_long_chunk=True,\n        mask_audio_out_token_label=True,\n    ):\n        self.whisper_processor = whisper_processor\n        self.round_to = round_to\n        self.pad_left = pad_left\n        self.audio_in_token_id = audio_in_token_id\n        self.audio_out_token_id = audio_out_token_id\n        self.audio_stream_bos_id = audio_stream_bos_id\n        self.audio_stream_eos_id = audio_stream_eos_id\n        self.pad_token_id = pad_token_id\n        self.encode_whisper_embed = encode_whisper_embed\n        self.return_audio_in_tokens = return_audio_in_tokens\n        self.audio_num_codebooks = audio_num_codebooks\n        self.use_delay_pattern = use_delay_pattern\n        if encode_whisper_embed:\n            self.chunk_size_seconds = chunk_size_seconds\n            self.chunk_size_samples = int(chunk_size_seconds * whisper_processor.feature_extractor.sampling_rate)\n        else:\n            self.chunk_size_seconds = None\n            self.chunk_size_samples = None\n        self.disable_audio_codes_transform = disable_audio_codes_transform\n        self.add_new_bos_eos_for_long_chunk = add_new_bos_eos_for_long_chunk\n        self.mask_audio_out_token_label = mask_audio_out_token_label\n\n    def _process_and_duplicate_audio_tokens(\n        self, input_ids: torch.Tensor, audio_idx: int, wv: torch.Tensor, sr: int, labels: Optional[torch.Tensor] = None\n    ) -> Tuple[torch.Tensor, torch.Tensor, int]:\n        \"\"\"Process long audio and duplicate corresponding audio tokens.\n\n        Args:\n            input_ids: Input token ids\n            audio_idx: Index of the audio token in the sequence\n            wv: Audio waveform\n            sr: Sample rate\n            labels: Optional label ids to be duplicated alongside input ids\n\n        Returns:\n            Tuple of:\n                - New input ids with duplicated audio tokens\n                - New label ids (if labels were provided) or None\n                - Number of chunks created\n        \"\"\"\n        # Calculate number of chunks needed\n        total_samples = len(wv)\n        num_chunks = math.ceil(total_samples / self.chunk_size_samples)\n\n        if num_chunks <= 1:\n            return input_ids, labels, 1\n\n        # Get the three tokens: <|audio_bos|><|AUDIO|><|audio_eos|>\n        audio_token_seq = input_ids[audio_idx - 1 : audio_idx + 2]\n        # Duplicate sequence for each chunk\n        duplicated_sequence = audio_token_seq.repeat(num_chunks)\n\n        # Create new input_ids with duplicated tokens\n        new_input_ids = torch.cat([input_ids[: audio_idx - 1], duplicated_sequence, input_ids[audio_idx + 2 :]])\n\n        # If labels are provided, duplicate them as well\n        new_labels = None\n        if labels is not None:\n            label_seq = labels[audio_idx - 1 : audio_idx + 2]\n            duplicated_labels = label_seq.repeat(num_chunks)\n            new_labels = torch.cat([labels[: audio_idx - 1], duplicated_labels, labels[audio_idx + 2 :]])\n\n        return new_input_ids, new_labels, num_chunks\n\n    def __call__(self, batch: List[ChatMLDatasetSample]):\n        \"\"\"Collate the input data with support for long audio processing.\"\"\"\n\n        label_ids = None\n        label_audio_ids = None\n        if all([ele.label_ids is None for ele in batch]):\n            return_labels = False\n        else:\n            return_labels = True\n\n        if self.encode_whisper_embed:\n            # Process each sample in the batch to handle long audio\n            # TODO(?) The implementation here can be optimized.\n            processed_batch = []\n            for i in range(len(batch)):\n                sample = batch[i]\n                audio_in_mask = sample.input_ids == self.audio_in_token_id\n                audio_in_indices = torch.where(audio_in_mask)[0]\n                audio_out_mask = sample.input_ids == self.audio_out_token_id\n\n                # Process each audio token and duplicate if needed\n                modified_input_ids = sample.input_ids\n                modified_labels = sample.label_ids if return_labels else None\n                modified_waveforms_concat = []\n                modified_waveforms_start = []\n                modified_sample_rate = []\n                offset = 0  # Track position changes from duplicating tokens\n                curr_wv_offset = 0\n\n                # Process input audio tokens\n                for idx, audio_idx in enumerate(audio_in_indices):\n                    # Get the audio for this token\n                    wv, sr = sample.get_wv(idx)  # Use idx since we want the original audio index\n                    if sr != self.whisper_processor.feature_extractor.sampling_rate:\n                        resampled_wv = librosa.resample(\n                            wv.cpu().numpy(),\n                            orig_sr=sr,\n                            target_sr=self.whisper_processor.feature_extractor.sampling_rate,\n                        )\n                    else:\n                        resampled_wv = wv.cpu().numpy()\n                    wv = torch.tensor(resampled_wv, device=wv.device)\n                    sr = self.whisper_processor.feature_extractor.sampling_rate\n\n                    # Process and duplicate tokens if necessary\n                    token_pos = audio_idx + offset\n                    modified_input_ids, modified_labels, num_chunks = self._process_and_duplicate_audio_tokens(\n                        modified_input_ids, token_pos, wv, sr, modified_labels\n                    )\n\n                    # Update audio data\n                    for chunk_idx in range(num_chunks):\n                        chunk_start = chunk_idx * self.chunk_size_samples\n                        chunk_end = min((chunk_idx + 1) * self.chunk_size_samples, len(wv))\n                        chunk_wv = wv[chunk_start:chunk_end]\n                        modified_waveforms_concat.append(chunk_wv)\n                        modified_waveforms_start.append(curr_wv_offset)\n                        curr_wv_offset += len(chunk_wv)\n                        modified_sample_rate.append(sr)\n\n                    # Update offset for next iteration\n                    offset += (num_chunks - 1) * 3  # Each new chunk adds 3 more tokens\n\n                # Create new sample with modified tokens and audio data\n                processed_sample = ChatMLDatasetSample(\n                    input_ids=modified_input_ids,\n                    label_ids=modified_labels if return_labels else sample.label_ids,\n                    audio_ids_concat=sample.audio_ids_concat,\n                    audio_ids_start=sample.audio_ids_start,\n                    audio_waveforms_concat=torch.cat(modified_waveforms_concat)\n                    if modified_waveforms_concat\n                    else sample.audio_waveforms_concat,\n                    audio_waveforms_start=torch.tensor(modified_waveforms_start, dtype=torch.long)\n                    if modified_waveforms_start\n                    else sample.audio_waveforms_start,\n                    audio_sample_rate=torch.tensor(modified_sample_rate)\n                    if modified_sample_rate\n                    else sample.audio_sample_rate,\n                    audio_speaker_indices=torch.tensor([]),\n                    # FIXME(sxjscience): The logic here is not correct for audio_label_ids_concat.\n                    audio_label_ids_concat=sample.audio_label_ids_concat,\n                )\n                # audio_in_chunk_len = len(torch.where(modified_input_ids == self.audio_in_token_id)[0])\n                # assert audio_in_chunk_len == processed_sample.num_audios(), f\"Mismatch: audio_in_chunk_len={audio_in_chunk_len}, processed_sample.num_audios()={processed_sample.num_audios()}\"\n                processed_batch.append(processed_sample)\n        else:\n            processed_batch = batch\n\n        # Get the max sequence length based on processed batch\n        max_seq_length = _ceil_to_nearest(max([len(sample.input_ids) for sample in processed_batch]), self.round_to)\n\n        # Get the ids for audio-in and audio-out for each batch\n        audio_in_wv_l = []\n        audio_in_ids_l = []\n        audio_out_ids_l = []\n        audio_out_ids_group_loc_l = []\n        audio_in_label_ids_l = None\n        audio_out_label_ids_l = None\n        reward_l = []\n\n        if return_labels:\n            audio_out_no_train_flag = []  # Whether the audio-out data should be trained on or not.\n\n        # Process the audio inputs and outputs\n        for i in range(len(processed_batch)):\n            audio_in_mask = processed_batch[i].input_ids == self.audio_in_token_id\n            audio_out_mask = processed_batch[i].input_ids == self.audio_out_token_id\n            audio_ids = torch.ones_like(processed_batch[i].input_ids)\n            audio_ids[audio_in_mask ^ audio_out_mask] = torch.cumsum(audio_ids[audio_in_mask ^ audio_out_mask], 0) - 1\n            audio_in_ids = audio_ids[audio_in_mask]\n            audio_out_ids = audio_ids[audio_out_mask]\n\n            if return_labels:\n                audio_out_no_train_flag.append(processed_batch[i].label_ids[audio_out_mask] < 0)\n                if self.mask_audio_out_token_label:\n                    processed_batch[i].label_ids[audio_out_mask] = -100\n\n            # Process audio inputs\n            if self.return_audio_in_tokens:\n                audio_in_ids_l.extend(\n                    [processed_batch[i].get_audio_codes(idx)[: self.audio_num_codebooks, :] for idx in audio_in_ids]\n                )\n                if processed_batch[i].audio_label_ids_concat is not None:\n                    if audio_in_label_ids_l is None:\n                        audio_in_label_ids_l = []\n                    audio_in_label_ids_l.extend(\n                        [\n                            processed_batch[i].get_audio_codes_labels(idx)[: self.audio_num_codebooks, :]\n                            for idx in audio_in_ids\n                        ]\n                    )\n\n            audio_out_ids_l.extend(\n                [processed_batch[i].get_audio_codes(idx)[: self.audio_num_codebooks, :] for idx in audio_out_ids]\n            )\n            audio_out_ids_group_loc_l.append(i)\n            if processed_batch[i].reward is not None:\n                reward_l.append(processed_batch[i].reward)\n\n            if processed_batch[i].audio_label_ids_concat is not None:\n                if audio_out_label_ids_l is None:\n                    audio_out_label_ids_l = []\n                audio_out_label_ids_l.extend(\n                    [\n                        processed_batch[i].get_audio_codes_labels(idx)[: self.audio_num_codebooks, :]\n                        for idx in audio_out_ids\n                    ]\n                )\n\n            if self.encode_whisper_embed:\n                for idx in audio_in_ids:\n                    wv, sr = processed_batch[i].get_wv(idx)\n                    resampled_wv = wv.cpu().numpy()\n                    # Split long audio into chunks\n                    total_samples = len(resampled_wv)\n                    for chunk_start in range(0, total_samples, self.chunk_size_samples):\n                        chunk_end = min(chunk_start + self.chunk_size_samples, total_samples)\n                        chunk = resampled_wv[chunk_start:chunk_end]\n                        audio_in_wv_l.append(chunk)\n            # assert len(audio_in_wv_l) == processed_batch[i].num_audios(), \\\n            #     f\"Assertion failed: Mismatch in number of audios. \" \\\n            #     f\"Expected {processed_batch[i].num_audios()}, but got {len(audio_in_wv_l)} at index {i}.\"\n\n        if return_labels:\n            audio_out_no_train_flag = torch.cat(audio_out_no_train_flag, dim=0)\n\n        # Process all audio features\n        if len(audio_in_wv_l) > 0:\n            feature_ret = self.whisper_processor.feature_extractor(\n                audio_in_wv_l,\n                sampling_rate=self.whisper_processor.feature_extractor.sampling_rate,\n                return_attention_mask=True,\n                padding=\"max_length\",\n            )\n            audio_features = torch.from_numpy(feature_ret[\"input_features\"])\n            audio_feature_attention_mask = torch.from_numpy(feature_ret[\"attention_mask\"])\n        else:\n            if self.encode_whisper_embed:\n                audio_features = torch.zeros(\n                    (\n                        0,\n                        self.whisper_processor.feature_extractor.feature_size,\n                        self.whisper_processor.feature_extractor.nb_max_frames,\n                    ),\n                    dtype=torch.float32,\n                )\n                audio_feature_attention_mask = torch.zeros(\n                    (0, self.whisper_processor.feature_extractor.nb_max_frames), dtype=torch.int32\n                )\n            else:\n                audio_features = None\n                audio_feature_attention_mask = None\n\n        # Process audio input tokens\n        if len(audio_in_ids_l) > 0:\n            # Append audio-stream-bos and eos tokens\n            new_audio_in_ids_l = []\n            for ele in audio_in_ids_l:\n                if self.disable_audio_codes_transform:\n                    # Do not add audio-stream-bos or eos tokens.\n                    # This may indicate that the sample comes from ConstantLengthDatasetWithBuffer.\n                    audio_codes = ele\n                else:\n                    audio_codes = torch.cat(\n                        [\n                            torch.full((ele.shape[0], 1), self.audio_stream_bos_id, dtype=torch.long),\n                            ele,\n                            torch.full((ele.shape[0], 1), self.audio_stream_eos_id, dtype=torch.long),\n                        ],\n                        dim=1,\n                    )\n                    if self.use_delay_pattern:\n                        audio_codes = build_delay_pattern_mask(\n                            audio_codes.unsqueeze(0),\n                            bos_token_id=self.audio_stream_bos_id,\n                            pad_token_id=self.audio_stream_eos_id,\n                        )[0].squeeze(0)\n                new_audio_in_ids_l.append(audio_codes)\n            audio_in_ids = torch.cat(new_audio_in_ids_l, dim=1).long()\n            audio_in_ids_start = torch.cumsum(\n                torch.tensor([0] + [audio_codes.shape[1] for audio_codes in new_audio_in_ids_l[:-1]]), dim=0\n            )\n        else:\n            audio_in_ids = torch.zeros((0, 0), dtype=torch.long)\n            audio_in_ids_start = torch.zeros(0, dtype=torch.long)\n\n        # Process audio output tokens\n        audio_out_ids_start_group_loc = None\n        if len(audio_out_ids_l) > 0:\n            new_audio_out_ids_l = []\n            label_audio_ids_l = []\n            for idx, ele in enumerate(audio_out_ids_l):\n                if self.disable_audio_codes_transform:\n                    # Do not add audio-stream-bos or eos tokens.\n                    # This may indicate that the sample comes from ConstantLengthDatasetWithBuffer.\n                    audio_codes = ele\n                    if return_labels:\n                        label_audio_ids = audio_out_label_ids_l[idx]\n                else:\n                    audio_codes = torch.cat(\n                        [\n                            torch.full((ele.shape[0], 1), self.audio_stream_bos_id, dtype=torch.long),\n                            ele,\n                            torch.full((ele.shape[0], 1), self.audio_stream_eos_id, dtype=torch.long),\n                        ],\n                        dim=1,\n                    )\n                    if return_labels:\n                        label_audio_ids = torch.cat(\n                            [\n                                torch.full((ele.shape[0], 1), -100, dtype=torch.long),\n                                ele,\n                                torch.full((ele.shape[0], 1), self.audio_stream_eos_id, dtype=torch.long),\n                            ],\n                            dim=1,\n                        )\n                    if self.use_delay_pattern:\n                        audio_codes = build_delay_pattern_mask(\n                            audio_codes.unsqueeze(0),\n                            bos_token_id=self.audio_stream_bos_id,\n                            pad_token_id=self.audio_stream_eos_id,\n                        )[0].squeeze(0)\n                        if return_labels:\n                            label_audio_ids = build_delay_pattern_mask(\n                                label_audio_ids.unsqueeze(0),\n                                bos_token_id=-100,\n                                pad_token_id=-100,\n                            )[0].squeeze(0)\n                new_audio_out_ids_l.append(audio_codes)\n\n                if return_labels:\n                    if audio_out_no_train_flag[idx]:\n                        label_audio_ids[:] = -100\n                    label_audio_ids_l.append(label_audio_ids)\n\n            audio_out_ids = torch.cat(new_audio_out_ids_l, dim=1).long()\n            if return_labels:\n                label_audio_ids = torch.cat(label_audio_ids_l, dim=1).long()\n            audio_out_ids_start = torch.cumsum(\n                torch.tensor([0] + [audio_codes.shape[1] for audio_codes in new_audio_out_ids_l[:-1]]), dim=0\n            )\n            audio_out_ids_start_group_loc = torch.tensor(audio_out_ids_group_loc_l, dtype=torch.long)\n        else:\n            audio_out_ids = torch.zeros((0, 0), dtype=torch.long)\n            audio_out_ids_start = torch.zeros(0, dtype=torch.long)\n            if return_labels:\n                label_audio_ids = torch.zeros((0, 0), dtype=torch.long)\n\n        reward = torch.tensor(reward_l, dtype=torch.float32)\n\n        # Handle padding for input ids and attention mask\n        if self.pad_left:\n            input_ids = torch.stack(\n                [\n                    F.pad(ele.input_ids, (max_seq_length - len(ele.input_ids), 0), value=self.pad_token_id)\n                    for ele in processed_batch\n                ]\n            )\n            if return_labels:\n                label_ids = torch.stack(\n                    [\n                        F.pad(ele.label_ids, (max_seq_length - len(ele.label_ids), 0), value=-100)\n                        for ele in processed_batch\n                    ]\n                )\n            attention_mask = torch.stack(\n                [\n                    F.pad(torch.ones_like(ele.input_ids), (max_seq_length - len(ele.input_ids), 0), value=0)\n                    for ele in processed_batch\n                ]\n            )\n        else:\n            input_ids = torch.stack(\n                [\n                    F.pad(ele.input_ids, (0, max_seq_length - len(ele.input_ids)), value=self.pad_token_id)\n                    for ele in processed_batch\n                ]\n            )\n            if return_labels:\n                label_ids = torch.stack(\n                    [\n                        F.pad(ele.label_ids, (0, max_seq_length - len(ele.label_ids)), value=-100)\n                        for ele in processed_batch\n                    ]\n                )\n            attention_mask = torch.stack(\n                [\n                    F.pad(torch.ones_like(ele.input_ids), (0, max_seq_length - len(ele.input_ids)), value=0)\n                    for ele in processed_batch\n                ]\n            )\n\n        if not self.return_audio_in_tokens:\n            audio_in_ids = None\n            audio_in_ids_start = None\n\n        # Apply audio_num_codebooks limit if specified\n        if self.audio_num_codebooks is not None:\n            if audio_in_ids is not None:\n                audio_in_ids = audio_in_ids[: self.audio_num_codebooks]\n            if audio_out_ids is not None:\n                audio_out_ids = audio_out_ids[: self.audio_num_codebooks]\n            if label_audio_ids is not None:\n                label_audio_ids = label_audio_ids[: self.audio_num_codebooks]\n\n        return HiggsAudioBatchInput(\n            input_ids=input_ids,\n            attention_mask=attention_mask,\n            audio_features=audio_features,\n            audio_feature_attention_mask=audio_feature_attention_mask,\n            audio_out_ids=audio_out_ids,\n            audio_out_ids_start=audio_out_ids_start,\n            audio_out_ids_start_group_loc=audio_out_ids_start_group_loc,\n            audio_in_ids=audio_in_ids,\n            audio_in_ids_start=audio_in_ids_start,\n            label_ids=label_ids,\n            label_audio_ids=label_audio_ids,\n            reward=reward,\n        )\n"
  },
  {
    "path": "boson_multimodal/data_types.py",
    "content": "\"\"\"Basic data types for multimodal ChatML format.\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional, Union\n\n\n@dataclass\nclass AudioContent:\n    audio_url: str\n    # Base64 encoded audio bytes\n    raw_audio: Optional[str] = None\n    offset: Optional[float] = None\n    duration: Optional[float] = None\n    row_id: Optional[int] = None\n    type: str = \"audio\"\n\n\n@dataclass\nclass TextContent:\n    text: str\n    type: str = \"text\"\n\n\n@dataclass\nclass Message:\n    role: str\n    content: Union[str, AudioContent, TextContent, List[Union[str, AudioContent, TextContent]]]\n    recipient: Optional[str] = None\n\n\n@dataclass\nclass ChatMLSample:\n    \"\"\"Dataclass to hold multimodal ChatML data.\"\"\"\n\n    messages: List[Message]\n    start_index: Optional[int] = None  # We will mask the messages[:start_index] when finetuning the LLM.\n    misc: Optional[Dict] = None\n    speaker: Optional[str] = None\n"
  },
  {
    "path": "boson_multimodal/dataset/__init__.py",
    "content": ""
  },
  {
    "path": "boson_multimodal/dataset/chatml_dataset.py",
    "content": "import dacite\nimport pandas as pd\nimport torch\nimport json\n\nimport numpy as np\nimport multiprocessing as mp\n\nfrom dataclasses import dataclass, fields\nfrom abc import ABC, abstractmethod\nfrom typing import Union, List, Dict, Optional\n\nfrom ..data_types import ChatMLSample, TextContent, AudioContent\nfrom ..constants import AUDIO_IN_TOKEN, AUDIO_OUT_TOKEN\n\nfrom loguru import logger\n\n# Whisper processor, 30 sec -> 3000 features\n# Then we divide 4 in the audio towker, we decrease 3000 features to 750, which gives 25 Hz\nWHISPER_EMBED_NUM_HIDDEN_STATE_PER_SEC = 25\n\n\n@dataclass\nclass ChatMLDatasetSample:\n    input_ids: torch.LongTensor  # Shape (seq_len,): The input text tokens.\n    label_ids: torch.LongTensor  # Shape (seq_len,): The label ids.\n    audio_ids_concat: torch.LongTensor  # Shape (num_codebooks, audio_seq_len): The audio tokens that are concatenated.\n    # Here `audio_seq_len` is the length of the concatenated audio tokens.`\n    audio_ids_start: (\n        torch.LongTensor\n    )  # Shape (num_audios,): The start index of each audio token in the concatenated audio tokens.\n    audio_waveforms_concat: (\n        torch.Tensor\n    )  # Shape (total_wv_length,): The concatenated audio waveforms for audio-in features.\n    audio_waveforms_start: (\n        torch.LongTensor\n    )  # Shape (num_audios,): The start index of each audio waveform in the concatenated audio waveforms.\n    audio_sample_rate: torch.Tensor  # Shape (num_audios,): The sampling rate of the audio waveforms.\n    audio_speaker_indices: (\n        torch.LongTensor\n    )  # Shape (num_audios,) -1 means unknown speaker: The speaker indices for each audio.\n    audio_label_ids_concat: Optional[torch.LongTensor] = (\n        None  # Shape (num_codebooks, audio_seq_len): The audio tokens that are concatenated.\n    )\n    # Here `audio_seq_len` is the length of the concatenated audio tokens.`\n    reward: Optional[float] = None\n\n    def num_audios(self):\n        return max(len(self.audio_waveforms_start), len(self.audio_ids_start))\n\n    def get_audio_codes(self, idx):\n        code_start = self.audio_ids_start[idx]\n        if idx < len(self.audio_ids_start) - 1:\n            code_end = self.audio_ids_start[idx + 1]\n        else:\n            code_end = self.audio_ids_concat.shape[-1]\n\n        return self.audio_ids_concat[:, code_start:code_end]\n\n    def get_audio_codes_labels(self, idx):\n        if self.audio_label_ids_concat is None:\n            return None\n        code_start = self.audio_ids_start[idx]\n        if idx < len(self.audio_ids_start) - 1:\n            code_end = self.audio_ids_start[idx + 1]\n        else:\n            code_end = self.audio_ids_concat.shape[-1]\n\n        return self.audio_label_ids_concat[:, code_start:code_end]\n\n    def get_wv(self, idx):\n        wv_start = self.audio_waveforms_start[idx]\n        sr = self.audio_sample_rate[idx]\n        if idx < len(self.audio_waveforms_start) - 1:\n            wv_end = self.audio_waveforms_start[idx + 1]\n        else:\n            wv_end = self.audio_waveforms_concat.shape[-1]\n        return self.audio_waveforms_concat[wv_start:wv_end], sr\n\n    def cal_num_tokens(\n        self,\n        encode_whisper_embed: bool = True,\n        encode_audio_in_tokens: bool = False,\n        encode_audio_out_tokens: bool = True,\n        audio_in_token_id: int = 128015,\n        audio_out_token_id: int = 128016,\n    ) -> int:\n        # we firstly exclude <|AUDIO|> and <|AUDIO_OUT|> because we do late merging and replace those position with actual audio features and audio token ids\n        # It's assumed that we always have audio_ids when audio_waveforms are there (but not vice-versa)\n        num_tokens = len(self.input_ids) - len(self.audio_ids_start)\n\n        if encode_whisper_embed and len(self.audio_waveforms_concat) > 0:\n            audio_lengths = torch.diff(self.audio_waveforms_start)\n            if len(audio_lengths):\n                # Sum before calling .item()\n                num_tokens += (\n                    (\n                        np.ceil(WHISPER_EMBED_NUM_HIDDEN_STATE_PER_SEC * audio_lengths / self.audio_sample_rate[:-1])\n                    ).sum()\n                ).item()\n            # add the last audio's token estimation\n            num_tokens += (\n                np.ceil(\n                    WHISPER_EMBED_NUM_HIDDEN_STATE_PER_SEC\n                    * (self.audio_waveforms_concat.shape[0] - self.audio_waveforms_start[-1])\n                    / self.audio_sample_rate[-1]\n                )\n            ).item()\n\n        if self.audio_ids_concat.size(1) > 0:\n            audio_io_ids = self.input_ids[\n                (self.input_ids == audio_in_token_id) | (self.input_ids == audio_out_token_id)\n            ]\n            audio_io_id_lengths = torch.concat(\n                [\n                    torch.diff(self.audio_ids_start),\n                    torch.tensor([self.audio_ids_concat.shape[-1] - self.audio_ids_start[-1]]),\n                ]\n            )\n            if encode_audio_in_tokens:\n                num_tokens += torch.sum(audio_io_id_lengths[audio_io_ids == audio_in_token_id]).item()\n\n            if encode_audio_out_tokens:\n                num_tokens += torch.sum(audio_io_id_lengths[audio_io_ids == audio_out_token_id]).item()\n\n        return int(num_tokens)\n\n    @classmethod\n    def merge(\n        cls,\n        samples: List[\"ChatMLDatasetSample\"],\n        eos_token_id: int,\n        ignore_index: int,\n        padding_size: Optional[int] = None,\n    ) -> \"ChatMLDatasetSample\":\n        \"\"\"Merges a list of ChatMLDatasetSample instances, inserting eos_token_id and ignore_index between them, and adjusting offsets for audio_ids_start and audio_waveforms_start.\n\n        Args:\n            samples (List[ChatMLDatasetSample]): List of samples to merge.\n            eos_token_id (int): Tokens to be inserted into input_ids between samples.\n            ignore_index (int): Default label for padding.\n            padding_size (Optional[int]): If provided, pad the sequence to with this length.\n\n        Returns:\n            ChatMLDatasetSample: Merged and potentially padded sample.\n        \"\"\"\n        if not samples:\n            logger.fatal(\"The samples list is empty and cannot be merged.\")\n            raise ValueError(\"The samples list is empty and cannot be merged.\")\n\n        # Initialize empty lists for concatenation\n        input_ids_list = []\n        label_ids_list = []\n        audio_ids_concat_list = []\n        audio_ids_start_list = []\n        audio_waveforms_concat_list = []\n        audio_waveforms_start_list = []\n        audio_sample_rate_list = []\n        audio_speaker_indices_list = []\n\n        # Track offsets\n        audio_ids_offset = 0\n        audio_waveforms_offset = 0\n\n        for sample in samples:\n            # Add input_ids and label_ids with padding\n            if input_ids_list:\n                input_ids_list.append(torch.tensor([eos_token_id], dtype=torch.long))\n                label_ids_list.append(torch.tensor([ignore_index], dtype=torch.long))\n            input_ids_list.append(sample.input_ids)\n            label_ids_list.append(sample.label_ids)\n\n            # Add audio_ids_concat and handle empty audio ids\n            if sample.audio_ids_concat.size(1) > 0:\n                audio_ids_concat_list.append(sample.audio_ids_concat)\n\n                # Offset and add audio_ids_start\n                audio_ids_start_list.append(sample.audio_ids_start + audio_ids_offset)\n                audio_ids_offset += sample.audio_ids_concat.size(\n                    1\n                )  # (num_codebooks, seq_len): Update offset by audio_seq_len\n\n            # Add audio_waveforms_concat\n            if sample.audio_waveforms_concat.size(0) > 0:\n                # Check dimensions of the audio waveform to ensure consistency\n                if (\n                    audio_waveforms_concat_list\n                    and sample.audio_waveforms_concat.dim() != audio_waveforms_concat_list[0].dim()\n                ):\n                    logger.warning(\n                        f\"Skipping audio waveform with inconsistent dimensions: expected {audio_waveforms_concat_list[0].dim()}D, got {sample.audio_waveforms_concat.dim()}D\"\n                    )\n                    continue\n\n                audio_waveforms_concat_list.append(sample.audio_waveforms_concat)\n                audio_waveforms_start_list.append(sample.audio_waveforms_start + audio_waveforms_offset)\n                audio_waveforms_offset += sample.audio_waveforms_concat.size(0)\n\n                # Add audio_sample_rate and audio_speaker_indices\n                audio_sample_rate_list.append(sample.audio_sample_rate)\n\n            audio_speaker_indices_list.append(sample.audio_speaker_indices)\n\n        # Concatenate all tensors\n        input_ids = torch.cat(input_ids_list, dim=0)\n        label_ids = torch.cat(label_ids_list, dim=0)\n\n        # Apply padding if padding_size is specified\n        if padding_size is not None and padding_size > 0:\n            input_ids = torch.cat([input_ids, torch.full((padding_size,), eos_token_id, dtype=torch.long)], dim=0)\n            label_ids = torch.cat([label_ids, torch.full((padding_size,), ignore_index, dtype=torch.long)], dim=0)\n\n        # Safely concatenate audio tensors with proper error handling\n        try:\n            audio_ids_concat = torch.cat(audio_ids_concat_list, dim=1) if audio_ids_concat_list else torch.tensor([[]])\n            audio_ids_start = torch.cat(audio_ids_start_list, dim=0) if audio_ids_start_list else torch.tensor([])\n\n            # Check for dimensional consistency in audio waveforms\n            if audio_waveforms_concat_list:\n                dims = [t.dim() for t in audio_waveforms_concat_list]\n                if not all(d == dims[0] for d in dims):\n                    # If dimensions don't match, log warning and filter out the problematic tensors\n                    logger.warning(\n                        f\"Inconsistent dimensions in audio waveforms: {dims}. Filtering to keep only consistent ones.\"\n                    )\n                    expected_dim = max(set(dims), key=dims.count)  # Most common dimension\n                    audio_waveforms_concat_list = [t for t in audio_waveforms_concat_list if t.dim() == expected_dim]\n\n                    # Recalculate audio_waveforms_start with the filtered list\n                    if audio_waveforms_concat_list:\n                        audio_waveforms_offset = 0\n                        audio_waveforms_start_list = []\n                        for waveform in audio_waveforms_concat_list:\n                            audio_waveforms_start_list.append(torch.tensor([audio_waveforms_offset]))\n                            audio_waveforms_offset += waveform.size(0)\n\n            audio_waveforms_concat = (\n                torch.cat(audio_waveforms_concat_list, dim=0) if audio_waveforms_concat_list else torch.tensor([])\n            )\n            audio_waveforms_start = (\n                torch.cat(audio_waveforms_start_list, dim=0) if audio_waveforms_start_list else torch.tensor([])\n            )\n            audio_sample_rate = (\n                torch.cat(audio_sample_rate_list, dim=0) if audio_sample_rate_list else torch.tensor([])\n            )\n            audio_speaker_indices = (\n                torch.cat(audio_speaker_indices_list, dim=0) if audio_speaker_indices_list else torch.tensor([])\n            )\n\n        except RuntimeError as e:\n            logger.error(f\"Error during tensor concatenation: {str(e)}\")\n            logger.warning(\"Falling back to empty audio tensors\")\n            # Fall back to empty tensors\n            audio_ids_concat = torch.tensor([[]])\n            audio_ids_start = torch.tensor([])\n            audio_waveforms_concat = torch.tensor([])\n            audio_waveforms_start = torch.tensor([])\n            audio_sample_rate = torch.tensor([])\n            audio_speaker_indices = torch.tensor([])\n\n        # Create the merged sample\n        merged_sample = cls(\n            input_ids=input_ids,\n            label_ids=label_ids,\n            audio_ids_concat=audio_ids_concat,\n            audio_ids_start=audio_ids_start,\n            audio_waveforms_concat=audio_waveforms_concat,\n            audio_waveforms_start=audio_waveforms_start,\n            audio_sample_rate=audio_sample_rate,\n            audio_speaker_indices=audio_speaker_indices,\n        )\n\n        return merged_sample\n\n\n@dataclass\nclass RankedChatMLDatasetSampleTuple:\n    samples: List[ChatMLDatasetSample]\n    scores: List[float]\n\n    def max_score_sample(self) -> ChatMLDatasetSample:\n        idx = self.scores.index(max(self.scores))\n        self.samples[idx].reward = self.scores[idx]\n        return self.samples[idx]\n\n    def min_score_sample(self) -> ChatMLDatasetSample:\n        idx = self.scores.index(min(self.scores))\n        self.samples[idx].reward = self.scores[idx]\n        return self.samples[idx]\n\n\n@dataclass\nclass ChatMLDatasetStorageSample:\n    input_tokens: torch.LongTensor\n    label_tokens: torch.LongTensor\n    audio_bytes_cache_dir_index: int\n    audio_codes_cache_dir_index: int\n    audio_bytes_indices: torch.LongTensor\n    audio_codes_indices: torch.LongTensor\n    speaker_indices: torch.LongTensor\n    file_index: int\n    original_sample_index: int\n\n\n# TODO(sxjscience): We need to revist the logic about parsing speaker ids.\n# Currently, we assume that the speaker id is stored at the \"misc\" field in ChatMLSample.\ndef prepare_chatml_sample(sample: Union[ChatMLSample, Dict], tokenizer):\n    \"\"\"Preprocess the ChatML sample to get the tokens for the text part.\n\n    Args:\n        sample (ChatMLSample): The ChatML sample to preprocess.\n        tokenizer: The tokenizer to use for encoding the text.\n\n    \"\"\"\n\n    try:\n        if not isinstance(sample, ChatMLSample):\n            # Handle all fields that could be NaN\n            if \"speaker\" in sample and pd.isna(sample[\"speaker\"]):\n                sample[\"speaker\"] = None\n            if \"start_index\" in sample and pd.isna(sample[\"start_index\"]):\n                sample[\"start_index\"] = None\n            if \"content\" in sample and pd.isna(sample[\"content\"]):\n                sample[\"content\"] = \"\"\n\n            # Convert any other potential NaN values in nested structures\n            def convert_nan_to_none(obj):\n                import numpy as np\n\n                if isinstance(obj, (pd.Series, np.ndarray)):\n                    return obj.tolist()\n                elif pd.api.types.is_scalar(obj) and pd.isna(obj):\n                    return None\n                elif isinstance(obj, dict):\n                    return {k: convert_nan_to_none(v) for k, v in obj.items()}\n                elif isinstance(obj, (list, tuple)):  # Fixed: Handle both list and tuple\n                    return [convert_nan_to_none(item) for item in obj]\n                return obj\n\n            # Clean the sample data\n            clean_sample = convert_nan_to_none(sample)\n\n            val_keys = []\n            for field in fields(ChatMLSample):\n                if field.name in clean_sample:\n                    val_keys.append(field.name)\n            clean_sample = {k: clean_sample[k] for k in val_keys}\n\n            try:\n                sample = dacite.from_dict(\n                    data_class=ChatMLSample, data=clean_sample, config=dacite.Config(strict=True, check_types=True)\n                )\n            except Exception as e:\n                print(f\"Failed to convert to ChatMLSample: {e}\")\n                print(f\"Clean sample: {json.dumps(clean_sample, indent=2)}\")\n                return None, None, None, None\n\n        input_tokens = []\n        label_tokens = []\n        audio_contents = []\n        speaker_id = None\n        if sample.speaker is not None:\n            speaker_id = sample.speaker\n        elif sample.misc is not None:\n            if \"speaker\" in sample.misc:\n                speaker_id = sample.misc[\"speaker\"]\n\n        total_m = len(sample.messages)\n        for turn_id, message in enumerate(sample.messages):\n            role = message.role\n            recipient = message.recipient\n            content = message.content\n            content_l = []\n\n            if isinstance(content, str):\n                content_l.append(TextContent(text=content))\n            elif isinstance(content, TextContent):\n                content_l.append(content)\n            elif isinstance(content, AudioContent):\n                content_l.append(content)\n            elif isinstance(content, list):\n                for ele in content:\n                    if isinstance(ele, str):\n                        content_l.append(TextContent(text=ele))\n                    else:\n                        content_l.append(ele)\n            if turn_id == 0:\n                prefix = f\"<|begin_of_text|><|start_header_id|>{role}<|end_header_id|>\\n\\n\"\n            else:\n                prefix = f\"<|start_header_id|>{role}<|end_header_id|>\\n\\n\"\n            eot_postfix = \"<|eot_id|>\"\n            eom_postfix = \"<|eom_id|>\"\n\n            prefix_tokens = tokenizer.encode(prefix, add_special_tokens=False)\n            input_tokens.extend(prefix_tokens)\n            label_tokens.extend([-100 for _ in prefix_tokens])\n\n            if recipient:\n                assert role == \"assistant\", \"Recipient is only available for assistant role.\"\n                recipient_tokens = tokenizer.encode(f\"{recipient}<|recipient|>\", add_special_tokens=False)\n                input_tokens.extend(recipient_tokens)\n                label_tokens.extend(recipient_tokens)\n\n            for content in content_l:\n                if content.type == \"text\":\n                    text_tokens = tokenizer.encode(content.text, add_special_tokens=False)\n                    input_tokens.extend(text_tokens)\n                    if role == \"assistant\" and (sample.start_index is None or turn_id >= sample.start_index):\n                        label_tokens.extend(text_tokens)\n                    else:\n                        label_tokens.extend([-100 for _ in text_tokens])\n\n                elif content.type == \"audio\":\n                    # Generate the text-part of the audio tokens\n                    audio_contents.append(content)\n                    if role == \"user\" or role == \"system\":\n                        # Add the text tokens\n                        text_tokens = tokenizer.encode(\n                            f\"<|audio_bos|><|AUDIO|><|audio_eos|>\",\n                            add_special_tokens=False,\n                        )\n                        input_tokens.extend(text_tokens)\n                        label_tokens.extend([-100 for _ in text_tokens])\n                    elif role == \"assistant\":\n                        # Add the text tokens for audio-out part.\n                        text_tokens = tokenizer.encode(\n                            f\"<|audio_out_bos|><|AUDIO_OUT|><|audio_eos|>\",\n                            add_special_tokens=False,\n                        )\n                        input_tokens.extend(text_tokens)\n                        if sample.start_index is None or turn_id >= sample.start_index:\n                            label_tokens.extend(text_tokens)\n                        else:\n                            label_tokens.extend([-100 for _ in text_tokens])\n            next_id = turn_id + 1\n            if role == \"assistant\" and next_id != total_m and sample.messages[next_id].role == \"assistant\":\n                postfix_tokens = tokenizer.encode(eom_postfix, add_special_tokens=False)\n                input_tokens.extend(postfix_tokens)\n            else:\n                postfix_tokens = tokenizer.encode(eot_postfix, add_special_tokens=False)\n                input_tokens.extend(postfix_tokens)\n            if role == \"assistant\" and (sample.start_index is None or turn_id >= sample.start_index):\n                label_tokens.extend(postfix_tokens)\n            else:\n                label_tokens.extend([-100 for _ in postfix_tokens])\n\n        return input_tokens, label_tokens, audio_contents, speaker_id\n\n    except Exception as e:\n        print(f\"Error in prepare_chatml_sample: {str(e)}\")\n        print(f\"Sample data: {json.dumps(sample, indent=2)}\")\n        return None, None, None, None\n\n\ndef extract_generation_prompt_from_input_tokens(input_tokens, tokenizer):\n    \"\"\"Extract the generation prompt and reference answer from the input tokens.\n\n    For example:\n\n    Input Text = '<|begin_of_text|><|start_header_id|>user<|end_header_id|>\\n\\n\n    What words do you hear from the provided audio? Write it down for me.<|audio_bos|><|AUDIO|><|audio_eos|><|eot_id|>\n    <|start_header_id|>assistant<|end_header_id|>\\n\\nAt first they went by quick, too quick to even get.<|eot_id|>'\n\n    -->\n\n    Prompt = '<|begin_of_text|><|start_header_id|>user<|end_header_id|>\\n\\n\n    What words do you hear from the provided audio? Write it down for me.<|audio_bos|><|AUDIO|><|audio_eos|><|eot_id|>\n    <|start_header_id|>assistant<|end_header_id|>\\n\\n',\n    Reference = 'At first they went by quick, too quick to even get.'\n\n    Args:\n        input_tokens: The input tokens.\n        audio_contents: The audio contents.\n        tokenizer: The tokenizer to use for decoding the text.\n\n    Returns:\n        prompt_tokens: The tokens for the prompt.\n        reference_answer: The reference answer.\n        num_audios_in_reference: The number of audios in the reference answer.\n\n    \"\"\"\n    input_text = tokenizer.decode(input_tokens)\n    generation_prefix = \"<|start_header_id|>assistant<|end_header_id|>\\n\\n\"\n    postfix = \"<|eot_id|>\"\n    assert generation_prefix in input_text\n    generation_prompt_end_loc = input_text.rfind(generation_prefix) + len(generation_prefix)\n    generation_prompt = input_text[:generation_prompt_end_loc]\n    reference_answer = input_text[generation_prompt_end_loc : input_text.find(postfix, generation_prompt_end_loc)]\n    num_audios_in_reference = reference_answer.count(AUDIO_IN_TOKEN) + reference_answer.count(AUDIO_OUT_TOKEN)\n    return tokenizer.encode(generation_prompt, add_special_tokens=False), reference_answer, num_audios_in_reference\n\n\ndef prepare_chatml_dataframe_single_process(df, tokenizer):\n    \"\"\"Prepare the ChatML DataFrame.\"\"\"\n    ret = []\n    for _, row in df.iterrows():\n        input_tokens, label_tokens, audio_contents, speaker_id = prepare_chatml_sample(row.to_dict(), tokenizer)\n        ret.append((input_tokens, label_tokens, audio_contents, speaker_id))\n    return ret\n\n\ndef prepare_chatml_dataframe(df, tokenizer, num_process=16):\n    if num_process is None:\n        return prepare_chatml_dataframe_single_process(df, tokenizer)\n    else:\n        num_process = max(min(len(df) // 1000, num_process), 1)\n        workloads = np.array_split(df, num_process)\n        with mp.Pool(num_process) as pool:\n            ret = pool.starmap(\n                prepare_chatml_dataframe_single_process, [(workload, tokenizer) for workload in workloads]\n            )\n    return sum(ret, [])\n\n\nclass DatasetInterface(ABC):\n    @abstractmethod\n    def __getitem__(self, idx) -> Union[\"ChatMLDatasetSample\", \"RankedChatMLDatasetSampleTuple\"]:\n        \"\"\"Retrieve a dataset sample by index.\"\"\"\n        raise NotImplementedError\n\n\nclass IterableDatasetInterface(ABC):\n    @abstractmethod\n    def __iter__(self) -> Union[\"ChatMLDatasetSample\", \"RankedChatMLDatasetSampleTuple\"]:\n        \"\"\"Retrieve a sample by iterating through the dataset.\"\"\"\n        raise NotImplementedError\n\n\n@dataclass\nclass DatasetInfo:\n    dataset_type: str\n    group_type: Optional[str] = None\n    mask_text: Optional[bool] = None  # Whether to mask the text tokens for pretraining samples.\n"
  },
  {
    "path": "boson_multimodal/model/__init__.py",
    "content": ""
  },
  {
    "path": "boson_multimodal/model/higgs_audio/__init__.py",
    "content": "from transformers import AutoConfig, AutoModel\n\nfrom .configuration_higgs_audio import HiggsAudioConfig, HiggsAudioEncoderConfig\nfrom .modeling_higgs_audio import HiggsAudioModel\n\n\nAutoConfig.register(\"higgs_audio_encoder\", HiggsAudioEncoderConfig)\nAutoConfig.register(\"higgs_audio\", HiggsAudioConfig)\nAutoModel.register(HiggsAudioConfig, HiggsAudioModel)\n"
  },
  {
    "path": "boson_multimodal/model/higgs_audio/audio_head.py",
    "content": "\"\"\"Projector that maps hidden states from the LLM component to multimodal logits.\"\"\"\n\nimport torch\nfrom torch import nn\n\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple\n\nfrom .common import HiggsAudioPreTrainedModel\nfrom .configuration_higgs_audio import HiggsAudioConfig\n\n\n@dataclass\nclass HiggsAudioDecoderLayerOutput:\n    logits: torch.FloatTensor\n    audio_logits: torch.FloatTensor\n    attentions: Optional[Tuple[torch.FloatTensor, ...]] = None\n    past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None\n\n\nclass HiggsAudioDecoderProjector(HiggsAudioPreTrainedModel):\n    \"\"\"Projection layers that map hidden states from the LLM component to audio / text logits.\n\n    We support two type of audio head:\n    - Basic Audio Head:\n        Directly map the hidden states to audio logits for all the codebooks.\n    \"\"\"\n\n    def __init__(self, config: HiggsAudioConfig, layer_idx: Optional[int] = None):\n        super().__init__(config)\n        self.text_lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)\n        self.audio_lm_head = nn.Linear(\n            config.text_config.hidden_size, config.audio_num_codebooks * (config.audio_codebook_size + 2), bias=False\n        )\n\n        # Initialize weights and apply final processing\n        self.post_init()\n\n    def forward(\n        self,\n        hidden_states,\n        audio_out_mask,\n        label_audio_ids=None,\n        attention_mask=None,\n        position_ids=None,\n        past_key_values=None,\n        use_cache=None,\n        output_attentions=None,\n        output_hidden_states=None,\n        output_audio_hidden_states=False,\n        cache_position=None,\n    ):\n        \"\"\"\n        Args:\n            hidden_states (`torch.Tensor` of shape `(batch_size, seq_len, hidden_size)`):\n                Hidden states from the LLM component\n            audio_out_mask (`torch.Tensor` of shape `(batch_size, seq_len)`):\n                Mask for identifying the audio out tokens.\n            label_audio_ids (`torch.Tensor` of shape `(num_codebooks, num_audio_out_tokens)`):\n                Label tokens for the audio-out part. This is used for calculating the logits if RQ-Transformer is used.\n            attention_mask (`torch.Tensor` of shape `(batch_size, seq_len)`):\n                Mask to avoid performing attention on padding token indices\n            position_ids (`torch.Tensor` of shape `(batch_size, seq_len)`):\n                Position ids for the input tokens\n\n        Returns:\n            logits (`torch.Tensor` of shape `(batch_size, seq_len, vocab_size)`):\n                Logits for text tokens\n            audio_logits (`torch.Tensor` of shape `(num_audio_out_tokens, audio_num_codebooks * audio_codebook_size)`):\n                Logits for audio tokens. We ensure `num_text_tokens + num_audio_tokens == batch_size * seq_len`\n        \"\"\"\n        logits = self.text_lm_head(hidden_states)\n\n        all_hidden_states = () if output_hidden_states else None\n        all_self_attns = () if output_attentions else None\n        next_decoder_cache = None\n\n        if self.config.audio_decoder_proj_num_layers > 0:\n            # create position embeddings to be shared across the decoder layers\n            position_embeddings = self.rotary_emb(hidden_states, position_ids)\n            for decoder_layer in self.transformer_layers:\n                if output_hidden_states:\n                    all_hidden_states += (hidden_states,)\n\n                if self.gradient_checkpointing and self.training:\n                    layer_outputs = self._gradient_checkpointing_func(\n                        decoder_layer.__call__,\n                        hidden_states,\n                        attention_mask,\n                        position_ids,\n                        past_key_values,\n                        output_attentions,\n                        use_cache,\n                        cache_position,\n                        position_embeddings,\n                    )\n                else:\n                    layer_outputs = decoder_layer(\n                        hidden_states,\n                        attention_mask=attention_mask,\n                        position_ids=position_ids,\n                        past_key_value=past_key_values,\n                        output_attentions=output_attentions,\n                        use_cache=use_cache,\n                        cache_position=cache_position,\n                        position_embeddings=position_embeddings,\n                    )\n                hidden_states = layer_outputs[0]\n            hidden_states = self.norm(hidden_states)\n\n            if output_hidden_states:\n                all_hidden_states += (hidden_states,)\n\n            if output_attentions:\n                all_self_attns += (layer_outputs[1],)\n\n            if use_cache:\n                next_decoder_cache = layer_outputs[2 if output_attentions else 1]\n\n        next_cache = next_decoder_cache if use_cache else None\n\n        audio_logits = self.audio_lm_head(hidden_states[audio_out_mask])\n\n        if output_audio_hidden_states:\n            audio_hidden_states = hidden_states[audio_out_mask]\n        else:\n            audio_hidden_states = None\n\n        return logits, audio_logits, all_self_attns, all_hidden_states, audio_hidden_states, next_cache\n"
  },
  {
    "path": "boson_multimodal/model/higgs_audio/common.py",
    "content": "from torch import nn\n\nfrom transformers.modeling_utils import PreTrainedModel\n\nfrom .configuration_higgs_audio import HiggsAudioConfig\n\n\nclass HiggsAudioPreTrainedModel(PreTrainedModel):\n    config_class = HiggsAudioConfig\n    base_model_prefix = \"model\"\n    supports_gradient_checkpointing = True\n    _no_split_modules = []\n    _skip_keys_device_placement = \"past_key_values\"\n    _supports_flash_attn_2 = True\n    _supports_sdpa = True\n\n    def _init_weights(self, module):\n        std = self.config.init_std if hasattr(self.config, \"init_std\") else self.config.audio_encoder_config.init_std\n\n        if isinstance(module, (nn.Linear, nn.Conv1d)):\n            module.weight.data.normal_(mean=0.0, std=std)\n            if module.bias is not None:\n                module.bias.data.zero_()\n        elif isinstance(module, nn.Embedding):\n            module.weight.data.normal_(mean=0.0, std=std)\n            if module.padding_idx is not None:\n                module.weight.data[module.padding_idx].zero_()\n"
  },
  {
    "path": "boson_multimodal/model/higgs_audio/configuration_higgs_audio.py",
    "content": "from transformers.configuration_utils import PretrainedConfig\nfrom transformers.models.auto import CONFIG_MAPPING\n\n\nclass HiggsAudioEncoderConfig(PretrainedConfig):\n    \"\"\"Configuration of the Audio encoder in Higgs-Audio.\"\"\"\n\n    model_type = \"higgs_audio_encoder\"\n\n    def __init__(\n        self,\n        num_mel_bins=128,\n        encoder_layers=32,\n        encoder_attention_heads=20,\n        encoder_ffn_dim=5120,\n        encoder_layerdrop=0.0,\n        d_model=1280,\n        dropout=0.0,\n        attention_dropout=0.0,\n        activation_function=\"gelu\",\n        activation_dropout=0.0,\n        scale_embedding=False,\n        init_std=0.02,\n        max_source_positions=1500,\n        pad_token_id=128001,\n        **kwargs,\n    ):\n        super().__init__(**kwargs)\n\n        self.num_mel_bins = num_mel_bins\n        self.d_model = d_model\n        self.encoder_layers = encoder_layers\n        self.encoder_attention_heads = encoder_attention_heads\n        self.encoder_ffn_dim = encoder_ffn_dim\n        self.dropout = dropout\n        self.attention_dropout = attention_dropout\n        self.activation_function = activation_function\n        self.activation_dropout = activation_dropout\n        self.encoder_layerdrop = encoder_layerdrop\n        self.num_hidden_layers = encoder_layers\n        self.init_std = init_std\n        self.scale_embedding = scale_embedding  # scale factor will be sqrt(d_model) if True\n        self.max_source_positions = max_source_positions\n        self.pad_token_id = pad_token_id\n\n\nclass HiggsAudioConfig(PretrainedConfig):\n    r\"\"\"\n    This is the configuration class for the HiggsAudioModel.\n\n    Args:\n        text_config (`Union[AutoConfig, dict]`):\n            The config object or dictionary of the text backbone.\n        audio_encoder_config (`Union[AutoConfig, dict]`):\n            The config object or dictionary of the whisper encoder.\n            The audio encoder will be bidirectional and will be only available for audio understanding.\n        audio_tokenizer_config\n            The config object or dictionary of the audio tokenizer.\n        audio_adapter_type\n            The type of audio adapter to use. We support two types of adapter:\n            - stack:\n                We stack additional Transformer layers after the main LLM backbone for audio generation.\n            - dual_ffn:\n                For selected part of the LLM backbone, we replace the text FFN with a dual FFN architecture\n                that contains an additional audio FFN. The audio FFN will be triggered when the location is marked for audio tokens.\n            - dual_ffn_fast_forward:\n                We pick a few layers in the LLM backbone to plug-in the audio FFN. For the remaining layers,\n                the audio hidden states will be directly fast-forward to the next layer.\n                This reduces the computational cost for audio generation.\n        audio_embed_avg (`bool`, *optional*, defaults to False):\n            Whether to average the audio embeddings before sending them to the text attention layer.\n        audio_ffn_hidden_size\n            The hidden size of the audio feedforward network in dual-path FFN\n        audio_ffn_intermediate_size\n            The intermediate size of the audio feedforward network in dual-path FFN\n        audio_dual_ffn_layers\n            The layers in the LLM backbone to plug-in the dual FFN layer (mixture of audio FFN and text FFN).\n        audio_decoder_proj_num_attention (`int`, *optional*, defaults to 0):\n            The number of attention heads in the audio decoder projection layer.\n        use_delay_pattern (`bool`, *optional*, defaults to False):\n            Whether to use delay pattern in the audio decoder.\n        skip_audio_tower (`bool`, *optional*, defaults to False):\n            Whether to skip the audio tower in the audio encoder.\n        use_audio_out_embed_projector (`bool`, *optional*, defaults to False):\n            Whether to use an embedding projector to map audio out embeddings.\n        use_audio_out_self_attention (`bool`, *optional*, defaults to False):\n            Whether to use self-attention to aggregate information from audio-tokens before sending to the text attention layer.\n        audio_num_codebooks (`int`, *optional*, defaults to 12):\n            The number of codebooks in RVQGAN.\n        audio_codebook_size (`int`, *optional*, defaults to 1024):\n            The size of each codebook in RVQGAN.\n        audio_stream_bos_id\n            The id of the bos in the audio stream\n        audio_stream_eos_id\n            The id of the eos in the audio stream\n        audio_bos_token (`str`, *optional*, defaults to \"<|audio_bos|>\"):\n            The special `<|audio_bos|>` token. In Higgs-Audio, it is mapped to 128011,\n            which is the index of `<|reserved_special_token_3|>` in Llama-3.1-8B-Instruct's tokenizer.\n        audio_eos_token (`str`, *optional*, defaults to \"<|audio_eos|>\"):\n            The special `<|audio_eos|>` token. We use 128012 as the default value,\n            which is the index of `<|reserved_special_token_4|>` in Llama-3.1-8B-Instruct's tokenizer.\n        audio_out_bos_token (`str`, *optional*, defaults to \"<|audio_out_bos|>\"):\n            The special `<|audio_out_bos|>` token. We use 128013 as the default value,\n            which is the index of `<|reserved_special_token_5|>` in Llama-3.1-8B-Instruct's tokenizer.\n        audio_token (`str`, *optional*, defaults to \"<|AUDIO|>\"):\n            The special `<|AUDIO|>` token. We use 128015 as the default value,\n            which is the index of `<|reserved_special_token_7|>` in Llama-3.1-8B-Instruct's tokenizer.\n            This token indicates that the location should be filled in with whisper features.\n        audio_out_token (`str`, *optional*, defaults to \"<|AUDIO_OUT|>\"):\n            The special `<|AUDIO_OUT|>` token. We use 128016 as the default value,\n            which is the index of `<|reserved_special_token_8|>` in Llama-3.1-8B-Instruct's tokenizer.\n            This token indicates that the location should be filled in with audio tokens extracted via audio tokenizer.\n    \"\"\"\n\n    model_type = \"higgs_audio\"\n    is_composition = True\n\n    def __init__(\n        self,\n        text_config=None,\n        audio_encoder_config=None,\n        audio_tokenizer_config=None,\n        audio_adapter_type=\"stack\",\n        audio_embed_avg=False,\n        audio_ffn_hidden_size=4096,\n        audio_ffn_intermediate_size=14336,\n        audio_dual_ffn_layers=None,\n        audio_decoder_proj_num_layers=0,\n        encode_whisper_embed=True,\n        encode_audio_in_tokens=False,\n        use_delay_pattern=False,\n        skip_audio_tower=False,\n        use_audio_out_embed_projector=False,\n        use_audio_out_self_attention=False,\n        use_rq_transformer=False,\n        rq_transformer_hidden_size=None,\n        rq_transformer_intermediate_size=None,\n        rq_transformer_num_attention_heads=None,\n        rq_transformer_num_key_value_heads=None,\n        rq_transformer_num_hidden_layers=3,\n        audio_num_codebooks=12,\n        audio_codebook_size=1024,\n        audio_stream_bos_id=1024,\n        audio_stream_eos_id=1025,\n        audio_bos_token=\"<|audio_bos|>\",\n        audio_eos_token=\"<|audio_eos|>\",\n        audio_out_bos_token=\"<|audio_out_bos|>\",\n        audio_in_token=\"<|AUDIO|>\",\n        audio_out_token=\"<|AUDIO_OUT|>\",\n        audio_in_token_idx=128015,\n        audio_out_token_idx=128016,\n        pad_token_id=128001,\n        audio_out_bos_token_id=128013,\n        audio_eos_token_id=128012,\n        **kwargs,\n    ):\n        if isinstance(audio_encoder_config, dict):\n            audio_encoder_config[\"model_type\"] = (\n                audio_encoder_config[\"model_type\"] if \"model_type\" in audio_encoder_config else \"higgs_audio_encoder\"\n            )\n            audio_encoder_config = CONFIG_MAPPING[audio_encoder_config[\"model_type\"]](**audio_encoder_config)\n        elif audio_encoder_config is None:\n            audio_encoder_config = HiggsAudioEncoderConfig()\n\n        if isinstance(text_config, dict):\n            text_config[\"model_type\"] = text_config[\"model_type\"] if \"model_type\" in text_config else \"llama\"\n            text_config = CONFIG_MAPPING[text_config[\"model_type\"]](**text_config)\n        elif text_config is None:\n            text_config = CONFIG_MAPPING[\"llama\"]()\n\n        assert audio_adapter_type in [\n            \"stack\",\n            \"dual_ffn\",\n            \"dual_ffn_fast_forward\",\n        ], f\"Invalid audio adapter type: {audio_adapter_type}\"\n        if audio_adapter_type.startswith(\"dual_ffn\"):\n            assert audio_dual_ffn_layers is not None, (\n                \"audio_dual_ffn_layers must be specified when using dual_ffn adapter.\"\n            )\n        self.text_config = text_config\n        self.audio_encoder_config = audio_encoder_config\n        self.audio_tokenizer_config = audio_tokenizer_config\n        self.audio_adapter_type = audio_adapter_type\n        self.audio_embed_avg = audio_embed_avg\n        self.audio_ffn_hidden_size = audio_ffn_hidden_size\n        self.audio_ffn_intermediate_size = audio_ffn_intermediate_size\n        self.audio_dual_ffn_layers = audio_dual_ffn_layers\n        self.audio_decoder_proj_num_layers = audio_decoder_proj_num_layers\n        self.encode_whisper_embed = encode_whisper_embed\n        self.encode_audio_in_tokens = encode_audio_in_tokens\n        self.use_delay_pattern = use_delay_pattern\n        self.skip_audio_tower = skip_audio_tower\n        self.use_audio_out_embed_projector = use_audio_out_embed_projector\n        self.use_audio_out_self_attention = use_audio_out_self_attention\n\n        self.use_rq_transformer = use_rq_transformer\n\n        if self.use_rq_transformer:\n            assert not self.use_delay_pattern, \"Delay pattern is not supported if you turned on RQ-Transformer!\"\n        self.rq_transformer_hidden_size = rq_transformer_hidden_size\n        self.rq_transformer_intermediate_size = rq_transformer_intermediate_size\n        self.rq_transformer_num_attention_heads = rq_transformer_num_attention_heads\n        self.rq_transformer_num_key_value_heads = rq_transformer_num_key_value_heads\n        self.rq_transformer_num_hidden_layers = rq_transformer_num_hidden_layers\n\n        if use_rq_transformer:\n            # For RQ-Transformer, we set the hidden_size to the same as the text model's hidden size if it is not specified.\n            if self.rq_transformer_hidden_size is None:\n                self.rq_transformer_hidden_size = text_config.hidden_size\n            assert self.rq_transformer_hidden_size % 128 == 0\n            if self.rq_transformer_intermediate_size is None:\n                self.rq_transformer_intermediate_size = text_config.intermediate_size\n            if self.rq_transformer_num_attention_heads is None:\n                self.rq_transformer_num_attention_heads = self.rq_transformer_hidden_size // 128\n            if self.rq_transformer_num_key_value_heads is None:\n                self.rq_transformer_num_key_value_heads = self.rq_transformer_hidden_size // 128 // 4\n            assert self.rq_transformer_hidden_size % self.rq_transformer_num_attention_heads == 0\n            assert self.rq_transformer_hidden_size % self.rq_transformer_num_key_value_heads == 0\n\n        self.audio_num_codebooks = audio_num_codebooks\n        self.audio_codebook_size = audio_codebook_size\n        self.audio_bos_token = audio_bos_token\n        self.audio_eos_token = audio_eos_token\n        self.audio_out_bos_token = audio_out_bos_token\n        self.audio_in_token = audio_in_token\n        self.audio_out_token = audio_out_token\n        self.audio_in_token_idx = audio_in_token_idx\n        self.audio_out_token_idx = audio_out_token_idx\n        self.audio_stream_bos_id = audio_stream_bos_id\n        self.audio_stream_eos_id = audio_stream_eos_id\n        self.audio_out_bos_token_id = audio_out_bos_token_id\n        self.audio_eos_token_id = audio_eos_token_id\n\n        super().__init__(**kwargs)\n        self.pad_token_id = pad_token_id\n"
  },
  {
    "path": "boson_multimodal/model/higgs_audio/cuda_graph_runner.py",
    "content": "import torch\nimport torch.nn as nn\nfrom typing import Optional, List, Dict, Tuple, Union\nimport gc\n\nfrom transformers.cache_utils import Cache\n\n\n_NUM_WARMUP_ITERS = 2\n\n\nclass CUDAGraphRunner(nn.Module):\n    def __init__(self, model):\n        super().__init__()\n        self.model = model\n\n        self.input_buffers: Dict[str, torch.Tensor] = {}\n        self.output_buffers: Dict[str, torch.Tensor] = {}\n\n        self._graph: Optional[torch.cuda.CUDAGraph] = None\n\n    @property\n    def graph(self):\n        assert self._graph is not None\n        return self._graph\n\n    def capture(\n        self,\n        hidden_states: torch.Tensor,\n        causal_mask: torch.Tensor,\n        position_ids: torch.Tensor,\n        audio_discrete_codes_mask: torch.Tensor,\n        cache_position: torch.Tensor,\n        past_key_values: Union[Cache, List[torch.FloatTensor]],\n        use_cache: bool,\n        audio_attention_mask: torch.Tensor,\n        fast_forward_attention_mask: torch.Tensor,\n        output_attentions: bool,\n        output_hidden_states: bool,\n        is_decoding_audio_token: Optional[bool] = None,\n        is_using_cuda_graph: Optional[bool] = False,\n        stream: torch.cuda.Stream = None,\n        memory_pool: Optional[Tuple[int, int]] = None,\n    ):\n        assert self._graph is None\n        # Run warmup iterations\n        for _ in range(_NUM_WARMUP_ITERS):\n            self.model(\n                hidden_states=hidden_states,\n                causal_mask=causal_mask,\n                position_ids=position_ids,\n                audio_discrete_codes_mask=audio_discrete_codes_mask,\n                cache_position=cache_position,\n                past_key_values=past_key_values,\n                use_cache=use_cache,\n                audio_attention_mask=audio_attention_mask,\n                fast_forward_attention_mask=fast_forward_attention_mask,\n                output_attentions=output_attentions,\n                output_hidden_states=output_hidden_states,\n                is_decoding_audio_token=is_decoding_audio_token,\n                is_using_cuda_graph=is_using_cuda_graph,\n            )\n\n        torch.cuda.synchronize()\n\n        # Capture the graph\n        self._graph = torch.cuda.CUDAGraph()\n        with torch.cuda.graph(self._graph, pool=memory_pool, stream=stream):\n            out_hidden_states, all_hidden_states, all_self_attns = self.model(\n                hidden_states=hidden_states,\n                causal_mask=causal_mask,\n                position_ids=position_ids,\n                audio_discrete_codes_mask=audio_discrete_codes_mask,\n                cache_position=cache_position,\n                past_key_values=past_key_values,\n                use_cache=use_cache,\n                audio_attention_mask=audio_attention_mask,\n                fast_forward_attention_mask=fast_forward_attention_mask,\n                output_attentions=output_attentions,\n                output_hidden_states=output_hidden_states,\n                is_decoding_audio_token=is_decoding_audio_token,\n                is_using_cuda_graph=is_using_cuda_graph,\n            )\n            # hidden_states_out = torch.ops._C.weak_ref_tensor(outputs[0])\n            # del outputs\n            gc.collect()\n        torch.cuda.synchronize()\n\n        # Save input and output buffers\n        self.input_buffers = {\n            \"hidden_states\": hidden_states,\n            \"causal_mask\": causal_mask,\n            \"position_ids\": position_ids,\n            \"audio_discrete_codes_mask\": audio_discrete_codes_mask,\n            \"cache_position\": cache_position,\n            \"past_key_values\": past_key_values,\n            \"audio_attention_mask\": audio_attention_mask,\n            \"fast_forward_attention_mask\": fast_forward_attention_mask,\n        }\n        self.output_buffers = {\n            \"hidden_states\": out_hidden_states,\n            \"all_hidden_states\": all_hidden_states,\n            \"all_self_attns\": all_self_attns,\n        }\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        causal_mask: torch.Tensor,\n        position_ids: torch.Tensor,\n        audio_discrete_codes_mask: torch.Tensor,\n        cache_position: torch.Tensor,\n        audio_attention_mask: torch.Tensor,\n        fast_forward_attention_mask: torch.Tensor,\n        **kwargs,\n    ) -> torch.Tensor:\n        # Copy input tensors to buffers\n        self.input_buffers[\"hidden_states\"].copy_(hidden_states, non_blocking=True)\n        self.input_buffers[\"causal_mask\"].copy_(causal_mask, non_blocking=True)\n        self.input_buffers[\"position_ids\"].copy_(position_ids, non_blocking=True)\n        self.input_buffers[\"audio_discrete_codes_mask\"].copy_(audio_discrete_codes_mask, non_blocking=True)\n        self.input_buffers[\"cache_position\"].copy_(cache_position, non_blocking=True)\n        self.input_buffers[\"audio_attention_mask\"].copy_(audio_attention_mask, non_blocking=True)\n        self.input_buffers[\"fast_forward_attention_mask\"].copy_(fast_forward_attention_mask, non_blocking=True)\n\n        # Run the captured graph\n        self.graph.replay()\n\n        return self.output_buffers[\"hidden_states\"], None, None\n"
  },
  {
    "path": "boson_multimodal/model/higgs_audio/custom_modules.py",
    "content": "import torch\nimport torch.nn as nn\n\n\nclass PartiallyFrozenEmbedding(nn.Module):\n    \"\"\"Split an existing `nn.Embedding` module that splits the embedding into:\n\n    - A frozen embedding for indices [0..freeze_until_idx].\n    - A trainable embedding for indices [freeze_until_idx+1..vocab_size-1].\n\n    This should work with both Zero-2 and Zero-3 seamlessly\n    \"\"\"\n\n    def __init__(self, original_embedding: nn.Embedding, freeze_until_idx: int):\n        \"\"\"\n        :param original_embedding: An instance of nn.Embedding (the original embedding layer).\n        :param freeze_until_idx: The index up to which the embedding is frozen (excluding). The freeze_until_idx is not frozen.\n        \"\"\"\n        super().__init__()\n        self.freeze_until_idx = freeze_until_idx\n        self.original_vocab_size = original_embedding.num_embeddings\n        self.embedding_dim = original_embedding.embedding_dim\n\n        # Split the original embedding into frozen and trainable parts\n        self.embedding_frozen = nn.Embedding(\n            freeze_until_idx,\n            self.embedding_dim,\n            dtype=original_embedding.weight.dtype,\n            device=original_embedding.weight.device,\n        )\n        self.embedding_trainable = nn.Embedding(\n            self.original_vocab_size - freeze_until_idx,\n            self.embedding_dim,\n            dtype=original_embedding.weight.dtype,\n            device=original_embedding.weight.device,\n        )\n\n        # Copy weights from the original embedding into the frozen and trainable parts\n        with torch.no_grad():\n            self.embedding_frozen.weight.copy_(original_embedding.weight[:freeze_until_idx])\n            self.embedding_trainable.weight.copy_(original_embedding.weight[freeze_until_idx:])\n\n        # Freeze the frozen embedding\n        self.embedding_frozen.weight.requires_grad = False\n\n    def forward(self, input_ids: torch.Tensor) -> torch.Tensor:\n        \"\"\"\n        Forward pass for the split embedding wrapper.\n        :param input_ids: Tensor of shape [batch_size, seq_len] with indices in [0..original_vocab_size-1].\n        \"\"\"\n        # Masks to separate frozen and trainable indices\n        # (bsz, seq_len)\n        mask_frozen = input_ids < self.freeze_until_idx\n        mask_trainable = ~mask_frozen\n\n        # Output tensor for embedding results\n        batch_size, seq_len = input_ids.shape\n        embeddings = torch.zeros(\n            batch_size,\n            seq_len,\n            self.embedding_dim,\n            device=input_ids.device,\n            dtype=self.embedding_frozen.weight.dtype,\n        )\n\n        # Handle frozen embedding\n        if mask_frozen.any():\n            frozen_ids = input_ids[mask_frozen]\n            frozen_emb = self.embedding_frozen(frozen_ids)\n            embeddings[mask_frozen] = frozen_emb\n\n        # Handle trainable embedding\n        if mask_trainable.any():\n            # Adjust trainable IDs to the local index space of the trainable embedding\n            trainable_ids = input_ids[mask_trainable] - (self.freeze_until_idx)\n            trainable_emb = self.embedding_trainable(trainable_ids)\n            embeddings[mask_trainable] = trainable_emb\n\n        return embeddings\n\n    def to_unsplit(self) -> nn.Embedding:\n        unsplit_embedding = nn.Embedding(\n            self.original_vocab_size,\n            self.embedding_dim,\n            dtype=self.embedding_frozen.weight.dtype,\n            device=self.embedding_frozen.weight.device,\n        )\n\n        with torch.no_grad():\n            unsplit_embedding.weight[: self.freeze_until_idx].copy_(self.embedding_frozen.weight)\n            unsplit_embedding.weight[self.freeze_until_idx :].copy_(self.embedding_trainable.weight)\n\n        return unsplit_embedding\n\n\nclass PartiallyFrozenLinear(nn.Module):\n    \"\"\"A wrapper around nn.Linear to partially freeze part of the weight matrix.\"\"\"\n\n    def __init__(self, original_linear: nn.Linear, freeze_until_idx: int):\n        \"\"\"\n        :param original_linear: The original nn.Linear layer.\n        :param freeze_until_idx: The index up to which the rows of the weight matrix are frozen.\n        \"\"\"\n        super().__init__()\n        assert original_linear.bias is None, \"Currently only support linear module without bias\"\n\n        self.freeze_until_idx = freeze_until_idx\n        self.input_dim = original_linear.in_features\n        self.output_dim = original_linear.out_features\n\n        # Create frozen and trainable linear layers\n        self.linear_frozen = nn.Linear(\n            self.input_dim,\n            freeze_until_idx,\n            bias=False,\n            dtype=original_linear.weight.dtype,\n            device=original_linear.weight.device,\n        )\n        self.linear_trainable = nn.Linear(\n            self.input_dim,\n            self.output_dim - freeze_until_idx,\n            bias=False,\n            dtype=original_linear.weight.dtype,\n            device=original_linear.weight.device,\n        )\n\n        # Copy weights from the original linear layer\n        with torch.no_grad():\n            self.linear_frozen.weight.copy_(original_linear.weight[:freeze_until_idx])\n            self.linear_trainable.weight.copy_(original_linear.weight[freeze_until_idx:])\n\n        # Freeze the frozen linear layer\n        self.linear_frozen.weight.requires_grad = False\n\n    def forward(self, input_tensor):\n        # input_tensor: (bsz, seq_len, hidden_state_dim)\n        frozen_output = self.linear_frozen(input_tensor)\n        trainable_output = self.linear_trainable(input_tensor)\n        return torch.cat((frozen_output, trainable_output), dim=-1)\n\n    def to_unsplit(self) -> nn.Linear:\n        unsplit_linear = nn.Linear(\n            self.input_dim,\n            self.output_dim,\n            bias=False,\n            dtype=self.linear_frozen.weight.dtype,\n            device=self.linear_frozen.weight.device,\n        )\n\n        # Copy weights from the frozen and trainable layers into the unsplit linear layer\n        with torch.no_grad():\n            unsplit_linear.weight[: self.freeze_until_idx].copy_(self.linear_frozen.weight)\n            unsplit_linear.weight[self.freeze_until_idx :].copy_(self.linear_trainable.weight)\n\n        return unsplit_linear\n"
  },
  {
    "path": "boson_multimodal/model/higgs_audio/modeling_higgs_audio.py",
    "content": "\"\"\"Higgs-Audio is an end-to-end multimodal model with the capability to understand and generate text / audio.\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport math\nimport glob\nimport functools\nimport os\nfrom collections import defaultdict, OrderedDict\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom safetensors.torch import load_file\nfrom typing import Optional, Tuple, Union, List, Dict, Any\n\nfrom transformers import AutoTokenizer\nfrom transformers.modeling_outputs import BaseModelOutput\nfrom transformers.models.whisper.modeling_whisper import WhisperEncoderLayer\nfrom transformers.models.llama.modeling_llama import (\n    LlamaDecoderLayer,\n    LlamaRMSNorm,\n    LlamaRotaryEmbedding,\n    LLAMA_ATTENTION_CLASSES,\n    LlamaMLP,\n    LlamaRMSNorm,\n)\nfrom transformers.modeling_attn_mask_utils import AttentionMaskConverter\nfrom transformers.cache_utils import Cache, DynamicCache, StaticCache\nfrom transformers.generation import GenerationMixin, GenerationConfig, LogitsProcessorList, StoppingCriteriaList\nfrom transformers.generation.utils import GenerateNonBeamOutput\nfrom transformers.utils import logging, ModelOutput\n\nfrom .common import HiggsAudioPreTrainedModel\nfrom .utils import (\n    merge_input_ids_with_audio_features,\n    count_parameters,\n)\nfrom .configuration_higgs_audio import HiggsAudioConfig, HiggsAudioEncoderConfig\nfrom .custom_modules import PartiallyFrozenLinear, PartiallyFrozenEmbedding\nfrom .cuda_graph_runner import CUDAGraphRunner\nfrom .audio_head import HiggsAudioDecoderProjector\n\nlogger = logging.get_logger(__name__)\n\n\nclass GenerationMode(Enum):\n    \"\"\"Enum for different generation modes in HiggsAudio model.\"\"\"\n\n    TEXT = 0  # Text generation mode\n    AUDIO_INIT = 1  # Audio generation mode initialization\n    AUDIO_IN_PROGRESS = 2  # Audio generation mode in progress\n\n\ndef _whisper_encoder_zero_shape_forward(whisper_encoder, *args, **kwargs):\n    \"\"\"The whisper encoder does not support zero-shape tensor by default due to the following implementations\n\n        key_states = self._shape(self.k_proj(current_states), -1, bsz)\n\n    If `bsz` is 0, the \"-1\" dimension will be ambiguous and triggers error in the shape inference pass.\n\n    See also: https://github.com/huggingface/transformers/blob/30335093276212ce74938bdfd85bfd5df31a668a/src/transformers/models/whisper/modeling_whisper.py#L306-L307\n\n    This function monkey-patches all `_shape` functions in the whisper encoder's self-attention layers to ensure function supports zero-shape tensor.\n\n    #FIXME!!!! This is a temporary workaround and should be removed once the upstream issue is resolved.\n\n    \"\"\"\n\n    global _higgs_flash_attention_forward\n\n    def _patched_shape(tensor: torch.Tensor, seq_len: int, bsz: int, num_heads: int, head_dim: int):\n        if seq_len == -1:\n            return tensor.view(bsz, tensor.shape[1], num_heads, head_dim).transpose(1, 2).contiguous()\n        else:\n            return tensor.view(bsz, seq_len, num_heads, head_dim).transpose(1, 2).contiguous()\n\n    def _patched_scaled_dot_product_attention(\n        query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None, enable_gqa=False\n    ) -> torch.Tensor:\n        # IMPORTANT! Implementation here is wrong and is only for the purpose of obtaining the correct attn_weight shape\n        if enable_gqa:\n            key = key.repeat_interleave(query.size(-3) // key.size(-3), -3)\n            value = value.repeat_interleave(query.size(-3) // value.size(-3), -3)\n\n        attn_weight = query @ key.transpose(-2, -1)\n        return attn_weight @ value\n\n    # Apply monkey-patch\n    if whisper_encoder.config._attn_implementation != \"flash_attention_2\":\n        old_shape_functions = []\n        for layer in whisper_encoder.layers:\n            old_shape_functions.append(getattr(layer.self_attn, \"_shape\"))\n            layer.self_attn._shape = functools.partial(\n                _patched_shape, num_heads=layer.self_attn.num_heads, head_dim=layer.self_attn.head_dim\n            )\n\n    original_scaled_dot_product_attention = torch.nn.functional.scaled_dot_product_attention\n    torch.nn.functional.scaled_dot_product_attention = _patched_scaled_dot_product_attention\n\n    out = whisper_encoder(*args, **kwargs)\n    torch.nn.functional.scaled_dot_product_attention = original_scaled_dot_product_attention\n\n    # Restore the original shape functions\n    if whisper_encoder.config._attn_implementation != \"flash_attention_2\":\n        for layer, old_shape_function in zip(whisper_encoder.layers, old_shape_functions):\n            layer.self_attn._shape = old_shape_function\n\n    return out\n\n\ndef _prepare_4d_causal_attention_mask_with_cache_position(\n    attention_mask: torch.Tensor,\n    sequence_length: int,\n    target_length: int,\n    dtype: torch.dtype,\n    device: torch.device,\n    min_dtype: float,\n    cache_position: torch.Tensor,\n    batch_size: int,\n):\n    \"\"\"\n    Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape\n    `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.\n\n    Args:\n        attention_mask (`torch.Tensor`):\n            A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.\n        sequence_length (`int`):\n            The sequence length being processed.\n        target_length (`int`):\n            The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.\n        dtype (`torch.dtype`):\n            The dtype to use for the 4D attention mask.\n        device (`torch.device`):\n            The device to plcae the 4D attention mask on.\n        min_dtype (`float`):\n            The minimum value representable with the dtype `dtype`.\n        cache_position (`torch.Tensor`):\n            Indices depicting the position of the input sequence tokens in the sequence.\n        batch_size (`torch.Tensor`):\n            Batch size.\n    \"\"\"\n    if attention_mask is not None and attention_mask.dim() == 4:\n        # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.\n        causal_mask = attention_mask\n    else:\n        causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)\n        if sequence_length != 1:\n            causal_mask = torch.triu(causal_mask, diagonal=1)\n        causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)\n        causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)\n        if attention_mask is not None:\n            causal_mask = causal_mask.clone()  # copy to contiguous memory for in-place edit\n            mask_length = attention_mask.shape[-1]\n            padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]\n            padding_mask = padding_mask == 0\n            causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(\n                padding_mask, min_dtype\n            )\n\n    return causal_mask\n\n\nclass HiggsAudioFeatureProjector(nn.Module):\n    \"\"\"Projector that maps audio features extracted by Whisper to hidden state of the text model.\"\"\"\n\n    def __init__(self, config: HiggsAudioConfig):\n        super().__init__()\n        self.linear = nn.Linear(config.audio_encoder_config.d_model, config.text_config.hidden_size, bias=True)\n\n    def forward(self, audio_features):\n        hidden_states = self.linear(audio_features)\n        return hidden_states\n\n\n# Revised on top of transformers.models.qwen2_audio.modeling_qwen2_audio with Qwen2AudioEncoder --> HiggsAudioEncoder\n# The code was originally borrowed from WhisperEncoder\nclass HiggsAudioEncoder(HiggsAudioPreTrainedModel):\n    \"\"\"\n    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a\n    [`WhisperEncoderLayer`].\n\n    Args:\n        config: HiggsAudioEncoderConfig\n    \"\"\"\n\n    # Ignore copy\n    config_class = HiggsAudioEncoderConfig\n    main_input_name = \"input_features\"\n    _no_split_modules = [\"WhisperEncoderLayer\"]\n\n    def __init__(self, config: HiggsAudioEncoderConfig):\n        super().__init__(config)\n        self.dropout = config.dropout\n        self.layerdrop = config.encoder_layerdrop\n\n        embed_dim = config.d_model\n        self.num_mel_bins = config.num_mel_bins\n        self.padding_idx = config.pad_token_id\n        self.max_source_positions = config.max_source_positions\n        self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0\n\n        self.conv1 = nn.Conv1d(self.num_mel_bins, embed_dim, kernel_size=3, padding=1)\n        self.conv2 = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=2, padding=1)\n\n        self.embed_positions = nn.Embedding(self.max_source_positions, embed_dim)\n        self.embed_positions.requires_grad_(False)\n\n        # Flash Attention 2 does not support zero shape tensor, so we have to use sdpa implementation for the Whisper component.\n        self.layers = nn.ModuleList([WhisperEncoderLayer(config) for _ in range(config.encoder_layers)])\n        self.layer_norm = nn.LayerNorm(config.d_model)\n        # Ignore copy\n        self.avg_pooler = nn.AvgPool1d(2, stride=2)\n\n        self.gradient_checkpointing = False\n        # Initialize weights and apply final processing\n        self.post_init()\n\n    def _freeze_parameters(self):\n        for param in self.parameters():\n            param.requires_grad = False\n        self._requires_grad = False\n\n    def get_input_embeddings(self) -> nn.Module:\n        return self.conv1\n\n    def set_input_embeddings(self, value: nn.Module):\n        self.conv1 = value\n\n    def forward(\n        self,\n        input_features,\n        attention_mask=None,\n        head_mask=None,\n        output_attentions=None,\n        output_hidden_states=None,\n        return_dict=None,\n        check_seq_length=True,\n    ):\n        r\"\"\"\n        Args:\n            input_features (`torch.LongTensor` of shape `(batch_size, feature_size, sequence_length)`):\n                Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be\n                obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a\n                `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into\n                `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding\n                and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]\n            attention_mask (`torch.Tensor`)`, *optional*):\n                HiggsAudio does not support masking of the `input_features`, this argument is preserved for compatibility,\n                but it is not used. By default the silence in the input log mel spectrogram are ignored.\n            head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):\n                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:\n\n                - 1 indicates the head is **not masked**,\n                - 0 indicates the head is **masked**.\n            output_attentions (`bool`, *optional*):\n                Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n                returned tensors for more detail.\n            output_hidden_states (`bool`, *optional*):\n                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors\n                for more detail.\n            return_dict (`bool`, *optional*):\n                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n        \"\"\"\n\n        expected_seq_length = self.config.max_source_positions * self.conv1.stride[0] * self.conv2.stride[0]\n        if check_seq_length and (input_features.shape[-1] != expected_seq_length):\n            raise ValueError(\n                f\"HiggsAudio expects the mel input features to be of length {expected_seq_length}, but found {input_features.shape[-1]}. Make sure to pad the input mel features to {expected_seq_length}.\"\n            )\n\n        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n        output_hidden_states = (\n            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n        )\n        return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n        # Ignore copy\n        input_features = input_features.to(dtype=self.conv1.weight.dtype, device=self.conv1.weight.device)\n\n        inputs_embeds = nn.functional.gelu(self.conv1(input_features))\n        inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))\n\n        inputs_embeds = inputs_embeds.permute(0, 2, 1)\n        embed_pos = self.embed_positions.weight\n\n        hidden_states = inputs_embeds + embed_pos\n        hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n\n        encoder_states = () if output_hidden_states else None\n        all_attentions = () if output_attentions else None\n\n        # check if head_mask has a correct number of layers specified if desired\n        if head_mask is not None:\n            assert head_mask.size()[0] == (len(self.layers)), (\n                f\"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}.\"\n            )\n\n        for idx, encoder_layer in enumerate(self.layers):\n            if output_hidden_states:\n                encoder_states = encoder_states + (hidden_states,)\n            # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n            to_drop = False\n            if self.training:\n                dropout_probability = torch.rand([])\n                if dropout_probability < self.layerdrop:  # skip the layer\n                    to_drop = True\n\n            # Ignore copy\n            if to_drop:\n                layer_outputs = (None, None)\n            else:\n                if self.gradient_checkpointing and self.training:\n                    layer_outputs = self._gradient_checkpointing_func(\n                        encoder_layer.__call__,\n                        hidden_states,\n                        attention_mask,\n                        (head_mask[idx] if head_mask is not None else None),\n                        output_attentions,\n                    )\n                else:\n                    layer_outputs = encoder_layer(\n                        hidden_states,\n                        attention_mask,\n                        layer_head_mask=(head_mask[idx] if head_mask is not None else None),\n                        output_attentions=output_attentions,\n                    )\n\n                hidden_states = layer_outputs[0]\n\n            if output_attentions:\n                all_attentions = all_attentions + (layer_outputs[1],)\n\n        # Ignore copy\n        hidden_states = hidden_states.permute(0, 2, 1)\n        # If the sequence length after average pooling is not divisible by the sequence parallel size, we would duplicate it across the sequence parallel ranks.\n        # In this case, gradients need to be scaled up because the subsequent scaling up in the function _apply_audio_tower is skipped.\n        hidden_states = self.avg_pooler(hidden_states)\n\n        hidden_states = hidden_states.permute(0, 2, 1)\n\n        hidden_states = self.layer_norm(hidden_states)\n\n        if output_hidden_states:\n            encoder_states = encoder_states + (hidden_states,)\n\n        if not return_dict:\n            return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)\n        return BaseModelOutput(\n            last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions\n        )\n\n    # Ignore copy\n    def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):\n        \"\"\"\n        Computes the output length of the convolutional layers and the output length of the audio encoder\n        \"\"\"\n        input_lengths = (input_lengths - 1) // 2 + 1\n        output_lengths = (input_lengths - 2) // 2 + 1\n        return input_lengths, output_lengths\n\n\nclass HiggsAudioDualFFNDecoderLayer(nn.Module):\n    \"\"\"We implement a dual-path FFN decoder layer where the audio tokens and text tokens go through separate FFN layers.\n\n    The audio and text tokens share the text-attention layer, but will be encoded with separate feedforward layers.\n    In addition, the audio tokens can be configured to go through separate attention layer.\n\n    Following is an illustration:\n\n     t    t    t    a   a     a    t    t    t\n                        |\n                        | (shared attention layer)\n                        v\n    h_t  h_t  h_t  h_a  h_a  h_a  h_t  h_t  h_t\n                        |\n                        | (separate text/audio hidden states)\n                        v\n    [h_t  h_t  h_t  h_t  h_t  h_t], [h_a, h_a, h_a]\n             |                             |\n             | (separate FFNs)             |\n             v                             v\n    [o_t  o_t  o_t  o_t  o_t  o_t], [o_a, o_a, o_a]\n                        |\n                        | (reorder)\n                        v\n    o_t  o_t  o_t  o_a  o_a  o_a  o_t  o_t  o_t\n\n    This has a few advantages:\n    1) We are able to use a smaller FFN, or even bypass the FFN for audio tokens. This accelerates the inference speed.\n    2) The Audio-FFN introduces more trainable parameters to the model.\n       This should have the same effect as the mixture-of-expert layer and we may expect better performance due to parameter scaling.\n    3) We can replace the original FFN in LLMs with the dual-path FFN without changing the number of FLOPs.\n\n\n    \"\"\"\n\n    def __init__(\n        self, config: HiggsAudioConfig, layer_idx: int, fast_forward: bool = False, use_audio_attention: bool = False\n    ):\n        super().__init__()\n        text_config = config.text_config\n        self.hidden_size = text_config.hidden_size\n        self.layer_idx = layer_idx\n        self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=text_config, layer_idx=layer_idx)\n\n        self.mlp = LlamaMLP(text_config)\n\n        if not fast_forward:\n            if use_audio_attention:\n                self.audio_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](\n                    config=text_config, layer_idx=layer_idx + 1\n                )\n                self.audio_post_audio_attn_layer_norm = LlamaRMSNorm(\n                    text_config.hidden_size, eps=text_config.rms_norm_eps\n                )\n\n            self.audio_mlp = LlamaMLP(text_config)\n            self.audio_input_layernorm = LlamaRMSNorm(text_config.hidden_size, eps=text_config.rms_norm_eps)\n            self.audio_post_attention_layernorm = LlamaRMSNorm(text_config.hidden_size, eps=text_config.rms_norm_eps)\n\n        self.use_audio_attention = use_audio_attention\n        self.fast_forward = fast_forward\n        if self.fast_forward:\n            assert not self.use_audio_attention, (\n                \"We cannot use audio_attention if the layer is marked as fast-forward.\"\n            )\n        self.input_layernorm = LlamaRMSNorm(text_config.hidden_size, eps=text_config.rms_norm_eps)\n        self.post_attention_layernorm = LlamaRMSNorm(text_config.hidden_size, eps=text_config.rms_norm_eps)\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        attention_mask: Optional[torch.Tensor] = None,\n        audio_attention_mask: Optional[torch.Tensor] = None,\n        fast_forward_attention_mask: Optional[torch.Tensor] = None,\n        position_ids: Optional[torch.LongTensor] = None,\n        audio_out_mask: Optional[torch.BoolTensor] = None,\n        is_decoding_audio_token: Optional[bool] = None,\n        past_key_value: Optional[Cache] = None,\n        output_attentions: Optional[bool] = False,\n        use_cache: Optional[bool] = False,\n        cache_position: Optional[torch.LongTensor] = None,\n        position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,  # will become mandatory in v4.46\n        is_using_cuda_graph: Optional[bool] = False,\n        **kwargs,\n    ):\n        \"\"\"\n        Args:\n            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`\n            attention_mask (`torch.FloatTensor`, *optional*):\n                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,\n                query_sequence_length, key_sequence_length)` if default attention is used.\n            position_ids\n                IDs of positions in the input sequence\n            audio_out_mask\n                Mask for identifying the audio tokens. Size (batch_size, sequence_length)\n                1 --> location contains audio_out\n                0 --> location does not contain audio_out\n\n                When use_cache is True and not in torch compile mode, the audio_out_mask contains audio_out masks for\n                all tokens up to the current token.  That means, it has size (batch_size, sequence_length) while\n                hidden_states will have size (batch_size, 1). In the torch compile mode, the audio_out_mask will have\n                size (batch_size, 1).\n            is_decoding_audio_token\n                Used in the torch compile mode to determine if the current token is an audio token or not.\n            past_key_value (`Cache`, *optional*): cached past key and value projection states. We fetch the corresponding cached key/value via the layer_idx.\n            output_attentions (`bool`, *optional*):\n                Whether or not to return the attentions tensors of all attention layers. See `attentions` under\n                returned tensors for more detail.\n            use_cache (`bool`, *optional*):\n                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding\n                (see `past_key_values`).\n            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):\n                Indices depicting the position of the input sequence tokens in the sequence\n            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):\n                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,\n                with `head_dim` being the embedding dimension of each attention head.\n            is_using_cuda_graph (`bool`, *optional*):\n                Indicates whether the model is running by cuda graph.\n            kwargs (`dict`, *optional*):\n                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code\n                into the model\n        \"\"\"\n        residual = hidden_states\n        target_length = hidden_states.shape[1]\n        use_static_cache = isinstance(past_key_value, StaticCache)\n        decode_stage = hidden_states.shape[1] == 1\n        if is_using_cuda_graph:\n            assert decode_stage and use_static_cache, (\n                \"The CUDA graph mode should only be used in the decoding stage with static cache.\"\n            )\n\n        # If we are decoding an audio token and the layer is marked as fast-forward,\n        # we can skip it.\n        if is_decoding_audio_token and self.fast_forward:\n            return (hidden_states,)\n\n        has_audio_out = audio_out_mask is not None and audio_out_mask.shape[0] > 0\n\n        audio_out_mask_sq = audio_out_mask\n\n        if self.fast_forward and has_audio_out:\n            original_hidden_states = hidden_states.clone()\n            min_dtype = torch.finfo(hidden_states.dtype).min\n            if attention_mask is None:\n                attention_mask = ~audio_out_mask\n\n                if self.self_attn.config._attn_implementation != \"flash_attention_2\":\n                    sequence_length = audio_out_mask.shape[1]\n                    attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(\n                        attention_mask=attention_mask,\n                        sequence_length=sequence_length,\n                        target_length=sequence_length,\n                        dtype=hidden_states.dtype,\n                        min_dtype=min_dtype,\n                        device=hidden_states.device,\n                        cache_position=cache_position,\n                        batch_size=hidden_states.shape[0],\n                    )\n                    if use_cache:\n                        attention_mask = attention_mask[:, :, -target_length:, :]\n            elif len(attention_mask.shape) == 2:\n                # Attention mask has shape (batch_size, sequence_length)\n                # We should be using flash attention 2\n                attention_mask = attention_mask * ~audio_out_mask\n            elif len(attention_mask.shape) == 4:\n                # When using static cache, the attention mask was already preprocessed in the previous layer\n                if use_static_cache:\n                    attention_mask = fast_forward_attention_mask\n                else:\n                    if use_cache:\n                        # Attention mask has shape (batch_size, 1, query_length, key_length)\n                        # In addition, the attention mask should be inverted, that means \"1\" (attend_to) --> \"0\", and \"0\" --> minimal dtype value.\n                        attention_mask = attention_mask.masked_fill(\n                            audio_out_mask[:, -target_length:].reshape(audio_out_mask.shape[0], 1, target_length, 1)\n                            | audio_out_mask.reshape(audio_out_mask.shape[0], 1, 1, audio_out_mask.shape[1]),\n                            min_dtype,\n                        )\n                    else:\n                        attention_mask = attention_mask.masked_fill(\n                            audio_out_mask.reshape(audio_out_mask.shape[0], 1, audio_out_mask.shape[1], 1)\n                            | audio_out_mask.reshape(audio_out_mask.shape[0], 1, 1, audio_out_mask.shape[1]),\n                            min_dtype,\n                        )\n            else:\n                raise NotImplementedError(f\"Unsupported attention_mask format, attention_mask={attention_mask}\")\n\n            if (\n                self.self_attn.config._attn_implementation == \"sdpa\"\n                and attention_mask is not None\n                and attention_mask.device.type == \"cuda\"\n                and not output_attentions\n            ):\n                # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when\n                # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.\n                # Details: https://github.com/pytorch/pytorch/issues/110213\n                attention_mask = AttentionMaskConverter._unmask_unattended(attention_mask, min_dtype)\n\n        if has_audio_out and not self.fast_forward:\n            # Apply separate layernorm layers for audio tokens and text tokens\n            if use_cache:\n                hidden_states = torch.where(\n                    audio_out_mask_sq[:, -target_length:].unsqueeze(-1),\n                    self.audio_input_layernorm(hidden_states),\n                    self.input_layernorm(hidden_states),\n                )\n            else:\n                hidden_states = torch.where(\n                    audio_out_mask_sq.unsqueeze(-1),\n                    self.audio_input_layernorm(hidden_states),\n                    self.input_layernorm(hidden_states),\n                )\n        else:\n            hidden_states = self.input_layernorm(hidden_states)\n\n        # Audio Attention\n        if self.use_audio_attention and has_audio_out:\n            if use_static_cache:\n                assert audio_attention_mask is not None, (\n                    \"audio_attention_mask should not be None when using static cache.\"\n                )\n\n            if audio_attention_mask is None:\n                no_audio_out_mask = (~audio_out_mask)[:, -target_length:].reshape(\n                    audio_out_mask.shape[0], 1, target_length, 1\n                ) | (~audio_out_mask).reshape(audio_out_mask.shape[0], 1, 1, audio_out_mask.shape[1])\n                min_dtype = torch.finfo(hidden_states.dtype).min\n\n                if attention_mask is None:\n                    audio_attention_mask = audio_out_mask\n\n                    if self.audio_attn.config._attn_implementation != \"flash_attention_2\":\n                        sequence_length = audio_out_mask.shape[1]\n                        audio_attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(\n                            attention_mask=audio_attention_mask,\n                            sequence_length=sequence_length,\n                            target_length=sequence_length,\n                            dtype=hidden_states.dtype,\n                            min_dtype=min_dtype,\n                            device=hidden_states.device,\n                            cache_position=cache_position,\n                            batch_size=hidden_states.shape[0],\n                        )\n                        if use_cache:\n                            audio_attention_mask = audio_attention_mask[:, :, -target_length:, :]\n                        audio_attention_mask = audio_attention_mask.masked_fill(no_audio_out_mask, min_dtype)\n                elif len(attention_mask.shape) == 2:\n                    # Attention mask has shape (batch_size, sequence_length)\n                    audio_attention_mask = attention_mask * audio_out_mask\n                elif len(attention_mask.shape) == 4:\n                    # Attention mask has shape (batch_size, 1, query_length, key_length)\n                    # In addition, the attention mask should be inverted. This means \"1\" (attend_to) --> \"0\", and \"0\" --> minimal dtype value.\n                    audio_attention_mask = attention_mask.masked_fill(no_audio_out_mask, min_dtype)\n                else:\n                    raise NotImplementedError(f\"Unsupported attention_mask format, attention_mask={attention_mask}\")\n\n                if (\n                    self.audio_attn.config._attn_implementation == \"sdpa\"\n                    and audio_attention_mask is not None\n                    and audio_attention_mask.device.type == \"cuda\"\n                    and not output_attentions\n                ):\n                    # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when\n                    # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.\n                    # Details: https://github.com/pytorch/pytorch/issues/110213\n                    audio_attention_mask = AttentionMaskConverter._unmask_unattended(audio_attention_mask, min_dtype)\n\n            audio_attention_mask = audio_attention_mask.contiguous()\n\n            audio_hidden_states, audio_self_attn_weights, audio_present_key_value = self.audio_attn(\n                hidden_states=hidden_states,\n                attention_mask=audio_attention_mask,\n                position_ids=position_ids,\n                past_key_value=past_key_value,\n                output_attentions=output_attentions,\n                use_cache=use_cache,\n                cache_position=cache_position,\n                position_embeddings=position_embeddings,\n                **kwargs,\n            )\n            audio_hidden_states = residual + audio_hidden_states\n            if use_cache:\n                residual = torch.where(\n                    audio_out_mask_sq[:, -target_length:].unsqueeze(-1), audio_hidden_states, residual\n                )\n            else:\n                residual = torch.where(audio_out_mask_sq.unsqueeze(-1), audio_hidden_states, residual)\n            audio_hidden_states = self.audio_post_audio_attn_layer_norm(audio_hidden_states)\n            if use_cache:\n                hidden_states = torch.where(\n                    audio_out_mask_sq[:, -target_length:].unsqueeze(-1), audio_hidden_states, hidden_states\n                )\n            else:\n                hidden_states = torch.where(audio_out_mask_sq.unsqueeze(-1), audio_hidden_states, hidden_states)\n\n        # Text Attention\n        hidden_states, self_attn_weights, present_key_value = self.self_attn(\n            hidden_states=hidden_states,\n            attention_mask=attention_mask,\n            position_ids=position_ids,\n            past_key_value=past_key_value,\n            output_attentions=output_attentions,\n            use_cache=use_cache,\n            cache_position=cache_position,\n            position_embeddings=position_embeddings,\n            **kwargs,\n        )\n        hidden_states = residual + hidden_states\n\n        # Apply Dual-path FFN\n        residual = hidden_states\n\n        if has_audio_out and not self.fast_forward:\n            if use_cache:\n                real_audio_out_mask = audio_out_mask_sq[:, -target_length:]\n            else:\n                real_audio_out_mask = audio_out_mask_sq\n\n            # Make whole graph in decode stage\n            if decode_stage and is_using_cuda_graph:\n                assert is_decoding_audio_token is not None, (\n                    \"is_decoding_audio_token should be present in the decoding stage.\"\n                )\n                if is_decoding_audio_token:\n                    hidden_states = self.audio_post_attention_layernorm(hidden_states)\n                    hidden_states = self.audio_mlp(hidden_states)\n                else:\n                    hidden_states = self.post_attention_layernorm(hidden_states)\n                    hidden_states = self.mlp(hidden_states)\n                residual = residual + hidden_states\n            else:\n                text_hidden_states = self.post_attention_layernorm(hidden_states[~real_audio_out_mask])\n                audio_hidden_states = self.audio_post_attention_layernorm(hidden_states[real_audio_out_mask])\n\n                text_hidden_states = self.mlp(text_hidden_states)\n                residual[~real_audio_out_mask] += text_hidden_states\n\n                audio_hidden_states = self.audio_mlp(audio_hidden_states)\n                residual[real_audio_out_mask] += audio_hidden_states\n\n            hidden_states = residual\n        else:\n            hidden_states = self.post_attention_layernorm(hidden_states)\n            hidden_states = self.mlp(hidden_states)\n            hidden_states = residual + hidden_states\n\n        if self.fast_forward and has_audio_out:\n            if use_cache:\n                hidden_states = torch.where(\n                    audio_out_mask_sq[:, -target_length:].unsqueeze(-1), original_hidden_states, hidden_states\n                )\n            else:\n                hidden_states = torch.where(audio_out_mask_sq.unsqueeze(-1), original_hidden_states, hidden_states)\n\n        outputs = (hidden_states,)\n\n        if output_attentions:\n            if self.use_audio_attention:\n                # The returned attn weights have shape (batch_size, num_heads + num_audio_attn_heads, seq_length, seq_length)\n                outputs += (torch.concat([self_attn_weights, audio_self_attn_weights], dim=1),)\n            else:\n                # The returned attn weights have shape (batch_size, num_heads, seq_length, seq_length)\n                outputs += (self_attn_weights,)\n\n        if use_cache:\n            outputs += (present_key_value,)\n\n        return outputs\n\n\n@dataclass\nclass HiggsAudioModelOutputWithPast(ModelOutput):\n    loss: Optional[torch.FloatTensor] = None\n    llm_loss: Optional[torch.FloatTensor] = None\n    audio_loss: Optional[torch.FloatTensor] = None\n    codebook_losses: Optional[torch.FloatTensor] = None\n    logits: Optional[torch.FloatTensor] = None\n    expanded_input_ids: Optional[torch.LongTensor] = None\n    expanded_labels: Optional[torch.LongTensor] = None\n    audio_in_mask: Optional[torch.BoolTensor] = None\n    audio_in_discrete_codes_mask: Optional[torch.BoolTensor] = None\n    audio_out_mask: Optional[torch.BoolTensor] = None\n    attention_mask: Optional[torch.BoolTensor] = None\n    audio_logits: Optional[torch.FloatTensor] = None\n    past_key_values: Optional[Cache] = None\n    hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None\n    audio_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None\n    attentions: Optional[Tuple[torch.FloatTensor, ...]] = None\n\n\n@dataclass\nclass HiggsAudioGenerationOutput(ModelOutput):\n    \"\"\"\n    Outputs of HiggsAudio generation models, when using non-beam methods.\n\n    Args:\n        sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter\n            if all batches finished early due to the `eos_token_id`.\n        audio_sequences (`tuple(torch.LongTensor)` *optional*):\n            The generated discrete audio codes. These codes can be used to fill-in related locations of <|AUDIO_OUT|> at input sequences.\n        scores (`tuple(torch.FloatTensor)` *optional*, returned when `output_scores=True`):\n            Processed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)\n            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for\n            each generated token).\n            If the generated token is a text token, the tensor will have shape `(batch_size, config.vocab_size)`.\n            If the generated token is an audio token, the tensor will have shape `(config.audio_num_codebooks, self.audio_codebook_size)`\n        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):\n            Unprocessed prediction scores of the language modeling head or the audio head (scores for each vocabulary token before SoftMax)\n            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for\n            each generated token).\n            If the generated token is a text token, the tensor will have shape `(batch_size, config.vocab_size)`.\n            If the generated token is an audio token, the tensor will have shape `(config.audio_num_codebooks, self.audio_codebook_size)`\n        attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):\n            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of\n            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.\n        hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):\n            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of\n            `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.\n        past_key_values (`tuple(tuple(torch.FloatTensor)))`, *optional*, returned when `use_cache=True`):\n            Returns the model cache, used to speed up decoding. Different models have a different cache format, check\n            the model's documentation. Usually, a [`~cache_utils.Cache`] instance.\n    \"\"\"\n\n    sequences: torch.LongTensor = None\n    audio_sequences: Optional[List[torch.LongTensor]] = None\n    scores: Optional[Tuple[torch.FloatTensor]] = None\n    logits: Optional[Tuple[torch.FloatTensor]] = None\n    attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None\n    hidden_states: Optional[Tuple[Tuple[torch.FloatTensor]]] = None\n    past_key_values: Optional[Tuple[Tuple[Tuple[torch.FloatTensor]]]] = None\n\n\nclass HiggsAudioModel(HiggsAudioPreTrainedModel, GenerationMixin):\n    \"\"\"Higgs-Audio is an end-to-end multimodal model with the capability to understand and generate text / audio.\n\n    Consider the following example for mixed text/audio understanding / generation:\n\n    - input_tokens: <text_token1><|audio_bos|>[AUDIO]<|audio_eos|><text_token2><|audio_bos|>[AUDIO]<|audio_eos|><text_token4>\n    - input_tokens: <text_token1><|audio_bos|>[AUDIO]<|audio_eos|><text_token2><|audio_out_bos|>[AUDIO_OUT]<|audio_eos|><text_token4>\n\n    We will fill [AUDIO] with the audio features extracted by Whisper and fill [AUDIO_OUT] with the audio tokens.\n\n    Consider the following example for mixed text/audio generation:\n\n    text: <|audio_out_bos|>    MASK           MASK           MASK          MASK               MASK         <|audio_eos|> [text_token1]\n    audio:     MASK    <|audio_stream_bos|> [audio_token1] [audio_token2] [audio_token3] <|audio_stream_eos|>   MASK           MASK\n    token_type: 0               1              1              1             1                  1                 0              0\n\n    \"\"\"\n\n    _supports_cache_class = True\n    _supports_static_cache = True\n\n    def __init__(self, config: HiggsAudioConfig):\n        super().__init__(config)\n        self.padding_idx = config.pad_token_id\n        self.audio_in_token_idx = config.audio_in_token_idx\n        self.audio_out_token_idx = config.audio_out_token_idx\n        self.audio_out_bos_token_id = config.audio_out_bos_token_id if \"audio_out_bos_token_id\" in config else None\n        self.audio_eos_token_id = config.audio_eos_token_id if \"audio_eos_token_id\" in config else None\n        self.vocab_size = config.text_config.vocab_size\n        self.audio_num_codebooks = config.audio_num_codebooks\n        self.use_delay_pattern = config.use_delay_pattern\n        self.use_audio_out_embed_projector = config.use_audio_out_embed_projector\n        self.use_audio_out_self_attention = config.use_audio_out_self_attention\n\n        self.embed_tokens = nn.Embedding(self.vocab_size, config.text_config.hidden_size, self.padding_idx)\n\n        if config.audio_adapter_type == \"dual_ffn\":\n            layer_idx = 0\n            layers = []\n            for j in range(config.text_config.num_hidden_layers):\n                if j in config.audio_dual_ffn_layers:\n                    layers.append(\n                        HiggsAudioDualFFNDecoderLayer(\n                            config, layer_idx, use_audio_attention=self.use_audio_out_self_attention\n                        )\n                    )\n                    layer_idx += 2 if self.use_audio_out_self_attention else 1\n                else:\n                    layers.append(LlamaDecoderLayer(config.text_config, layer_idx))\n                    layer_idx += 1\n            self.layers = nn.ModuleList(layers)\n        elif config.audio_adapter_type == \"dual_ffn_fast_forward\":\n            layer_idx = 0\n            layers = []\n            for j in range(config.text_config.num_hidden_layers):\n                if j in config.audio_dual_ffn_layers:\n                    layers.append(\n                        HiggsAudioDualFFNDecoderLayer(\n                            config,\n                            layer_idx,\n                            fast_forward=False,\n                            use_audio_attention=self.use_audio_out_self_attention,\n                        )\n                    )\n                    layer_idx += 2 if self.use_audio_out_self_attention else 1\n                else:\n                    layers.append(\n                        HiggsAudioDualFFNDecoderLayer(config, layer_idx, fast_forward=True, use_audio_attention=False)\n                    )\n                    layer_idx += 1\n            self.layers = nn.ModuleList(layers)\n        elif config.audio_adapter_type == \"stack\":\n            self.layers = nn.ModuleList(\n                [\n                    LlamaDecoderLayer(config.text_config, layer_idx)\n                    for layer_idx in range(config.text_config.num_hidden_layers)\n                ]\n            )\n            layer_idx = config.text_config.num_hidden_layers\n        else:\n            raise NotImplementedError(f\"Audio adapter type {config.audio_adapter_type} not implemented.\")\n\n        self.num_activation_checkpointing_layers = len(self.layers)\n\n        self.decode_graph_runners = defaultdict(dict[bool, CUDAGraphRunner])\n        self.norm = LlamaRMSNorm(config.text_config.hidden_size, eps=config.text_config.rms_norm_eps)\n        self.rotary_emb = LlamaRotaryEmbedding(config=config.text_config)\n\n        if not config.skip_audio_tower:\n            self.audio_tower = HiggsAudioEncoder(config.audio_encoder_config)\n            self.audio_encoder_proj = HiggsAudioFeatureProjector(config)\n        else:\n            self.audio_tower = None\n            self.audio_encoder_proj = None\n        self.audio_decoder_proj = HiggsAudioDecoderProjector(config, layer_idx=layer_idx)\n        self.audio_codebook_size = (\n            config.audio_codebook_size + 2\n        )  # We add 1 for the audio_stream_bos token and 1 for the audio_stream_eos token\n\n        if config.use_audio_out_embed_projector:\n            self.audio_out_embed_projector = nn.Linear(\n                config.text_config.hidden_size, config.text_config.hidden_size, bias=False\n            )\n\n        self.audio_codebook_embeddings = nn.Embedding(\n            config.audio_num_codebooks * self.audio_codebook_size, config.text_config.hidden_size\n        )\n\n        self.audio_codebook_weights = (\n            torch.ones(config.audio_num_codebooks) / config.audio_num_codebooks\n        )  # default to equal weights\n        self.post_init()\n\n    def set_num_activation_checkpointing_layers(self, num_layers):\n        self.num_activation_checkpointing_layers = num_layers\n\n    def set_delay_pattern(self):\n        self.config.use_delay_pattern = True\n        self.use_delay_pattern = True\n\n    def set_audio_special_tokens(self, tokenizer: AutoTokenizer):\n        self.audio_out_bos_token_id = tokenizer.convert_tokens_to_ids(\"<|audio_out_bos|>\")\n        self.audio_eos_token_id = tokenizer.convert_tokens_to_ids(\"<|audio_eos|>\")\n\n    def _embed_audio_ids(self, audio_ids):\n        \"\"\"Embed the audio ids\n\n        Args:\n            audio_ids: torch.LongTensor of shape (num_codebooks, audio_in_total_length)\n\n        Returns:\n            audio_embed: torch.LongTensor of shape (audio_in_total_length, hidden_size)\n        \"\"\"\n        codebook_shift = (\n            torch.arange(self.config.audio_num_codebooks, device=audio_ids.device) * self.audio_codebook_size\n        )\n        audio_embed = self.audio_codebook_embeddings(audio_ids + codebook_shift.unsqueeze(-1))\n        if self.config.audio_embed_avg:\n            audio_embed = torch.mean(audio_embed, dim=0)\n        else:\n            audio_embed = torch.sum(audio_embed, dim=0)\n        if self.use_audio_out_embed_projector:\n            audio_embed = self.audio_out_embed_projector(audio_embed)\n        return audio_embed\n\n    def _apply_audio_tower(self, audio_features, audio_feature_attention_mask):\n        \"\"\"Apply the audio tower to the audio features\"\"\"\n\n        if audio_features.shape[0] == 0:\n            if torch.is_grad_enabled():\n                # FIXME!!!!!!!!\n                # This is a hack to ensure that the forward+backward pass of audio_tower and audio_encoder_proj get triggered.\n                # The monkey patch won't overwrite the backward pass of nn.Module.\n                audio_outputs = _whisper_encoder_zero_shape_forward(\n                    self.audio_tower, audio_features, attention_mask=None, check_seq_length=False\n                )\n                selected_audio_feature = audio_outputs.last_hidden_state\n                audio_features_embed = self.audio_encoder_proj(selected_audio_feature)\n                audio_feat_out_lengths = None\n                return audio_features_embed, audio_feat_out_lengths\n            else:\n                return None, None\n\n        audio_feat_lengths, audio_feat_out_lengths = self.audio_tower._get_feat_extract_output_lengths(\n            audio_feature_attention_mask.sum(-1)\n        )\n        batch_size, _, max_mel_seq_len = audio_features.shape\n        max_seq_len = (max_mel_seq_len - 1) // 2 + 1\n        # Create a sequence tensor of shape (batch_size, max_seq_len)\n        seq_range = (\n            torch.arange(0, max_seq_len, dtype=audio_feat_lengths.dtype, device=audio_feat_lengths.device)\n            .unsqueeze(0)\n            .expand(batch_size, max_seq_len)\n        )\n        lengths_expand = audio_feat_lengths.unsqueeze(1).expand(batch_size, max_seq_len)\n        # Create mask\n        padding_mask = seq_range < lengths_expand\n\n        if self.config._attn_implementation != \"flash_attention_2\":\n            audio_attention_mask = padding_mask.view(batch_size, 1, 1, max_seq_len).expand(\n                batch_size, 1, max_seq_len, max_seq_len\n            )\n        else:\n            audio_attention_mask = padding_mask\n\n        audio_outputs = self.audio_tower(audio_features, attention_mask=audio_attention_mask)\n        selected_audio_feature = audio_outputs.last_hidden_state\n        audio_features_embed = self.audio_encoder_proj(selected_audio_feature)\n\n        return audio_features_embed, audio_feat_out_lengths\n\n    def _update_causal_mask(\n        self,\n        attention_mask: torch.Tensor,\n        input_tensor: torch.Tensor,\n        cache_position: torch.Tensor,\n        past_key_values: Cache,\n        output_attentions: bool,\n    ):\n        if self.config._attn_implementation == \"flash_attention_2\":\n            if attention_mask is not None and 0.0 in attention_mask:\n                return attention_mask\n            return None\n\n        # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in\n        # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail\n        # to infer the attention mask.\n        past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0\n        using_static_cache = isinstance(past_key_values, StaticCache)\n\n        # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward\n        if self.config._attn_implementation == \"sdpa\" and not using_static_cache and not output_attentions:\n            if AttentionMaskConverter._ignore_causal_mask_sdpa(\n                attention_mask,\n                inputs_embeds=input_tensor,\n                past_key_values_length=past_seen_tokens,\n                is_training=self.training,\n            ):\n                return None\n\n        dtype, device = input_tensor.dtype, input_tensor.device\n        min_dtype = torch.finfo(dtype).min\n        sequence_length = input_tensor.shape[1]\n        if using_static_cache:\n            target_length = past_key_values.get_max_length()\n        else:\n            target_length = (\n                attention_mask.shape[-1]\n                if isinstance(attention_mask, torch.Tensor)\n                else past_seen_tokens + sequence_length + 1\n            )\n\n        # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).\n        causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(\n            attention_mask,\n            sequence_length=sequence_length,\n            target_length=target_length,\n            dtype=dtype,\n            device=device,\n            min_dtype=min_dtype,\n            cache_position=cache_position,\n            batch_size=input_tensor.shape[0],\n        )\n\n        if (\n            self.config._attn_implementation == \"sdpa\"\n            and attention_mask is not None\n            and attention_mask.device.type == \"cuda\"\n            and not output_attentions\n        ):\n            # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when\n            # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.\n            # Details: https://github.com/pytorch/pytorch/issues/110213\n            causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)\n\n        return causal_mask\n\n    def _prepare_all_static_kv_cache_masks(self, hidden_states, attention_mask, audio_out_mask, past_key_values):\n        target_length = hidden_states.shape[1]\n        cur_pos = audio_out_mask.shape[1]\n        min_dtype = torch.finfo(hidden_states.dtype).min\n        assert len(attention_mask.shape) == 4, \"Only support SDPA for now\"\n        kv_cache_len = past_key_values.get_max_cache_shape()\n        audio_out_mask_padded = torch.nn.functional.pad(audio_out_mask, (0, kv_cache_len - cur_pos), value=True)\n        fast_forward_attention_mask = attention_mask.masked_fill(\n            audio_out_mask_padded[:, audio_out_mask.shape[1] - target_length : audio_out_mask.shape[1]].reshape(\n                audio_out_mask_padded.shape[0], 1, target_length, 1\n            )\n            | audio_out_mask_padded.reshape(audio_out_mask_padded.shape[0], 1, 1, audio_out_mask_padded.shape[1]),\n            min_dtype,\n        )\n\n        no_audio_out_mask = ~audio_out_mask\n        no_audio_out_mask = torch.nn.functional.pad(\n            no_audio_out_mask, (0, kv_cache_len - audio_out_mask.shape[1]), value=False\n        )\n        no_audio_out_mask = no_audio_out_mask[\n            :, audio_out_mask.shape[1] - target_length : audio_out_mask.shape[1]\n        ].reshape(audio_out_mask.shape[0], 1, target_length, 1) | no_audio_out_mask.reshape(\n            audio_out_mask.shape[0], 1, 1, kv_cache_len\n        )\n        audio_attention_mask = attention_mask.masked_fill(no_audio_out_mask, min_dtype)\n        return fast_forward_attention_mask, audio_attention_mask\n\n    def _forward_core(\n        self,\n        hidden_states: torch.Tensor,\n        causal_mask: torch.Tensor,\n        position_ids: torch.Tensor,\n        audio_discrete_codes_mask: torch.Tensor,\n        cache_position: torch.Tensor,\n        past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]],\n        use_cache: bool,\n        audio_attention_mask: torch.Tensor,\n        fast_forward_attention_mask: torch.Tensor,\n        output_attentions: bool,\n        output_hidden_states: bool,\n        is_decoding_audio_token: Optional[bool] = None,\n        is_using_cuda_graph: Optional[bool] = False,\n    ):\n        # create position embeddings to be shared across the decoder layers\n        # When past_key_values is passed in, we need to offset the position ids when calculating the position embeddings.\n        # Therefore, cache_position is used.\n        position_id_offset = cache_position[0] if use_cache else 0\n        position_embeddings = self.rotary_emb(hidden_states, position_ids + position_id_offset)\n\n        # decoder layers\n        all_hidden_states = () if output_hidden_states else None\n        all_self_attns = () if output_attentions else None\n\n        for decoder_layer in self.layers:\n            if output_hidden_states:\n                all_hidden_states += (hidden_states,)\n            if isinstance(decoder_layer, HiggsAudioDualFFNDecoderLayer):\n                layer_outputs = decoder_layer(\n                    hidden_states,\n                    attention_mask=causal_mask,\n                    audio_attention_mask=audio_attention_mask,\n                    fast_forward_attention_mask=fast_forward_attention_mask,\n                    position_ids=position_ids,\n                    audio_out_mask=audio_discrete_codes_mask,\n                    is_decoding_audio_token=is_decoding_audio_token,\n                    past_key_value=past_key_values,\n                    output_attentions=output_attentions,\n                    use_cache=use_cache,\n                    cache_position=cache_position,\n                    position_embeddings=position_embeddings,\n                    is_using_cuda_graph=is_using_cuda_graph,\n                )\n            else:\n                layer_outputs = decoder_layer(\n                    hidden_states,\n                    attention_mask=causal_mask,\n                    position_ids=position_ids,\n                    past_key_value=past_key_values,\n                    output_attentions=output_attentions,\n                    use_cache=use_cache,\n                    cache_position=cache_position,\n                    position_embeddings=position_embeddings,\n                )\n\n            hidden_states = layer_outputs[0]\n\n            if output_attentions:\n                all_self_attns += (layer_outputs[1],)\n\n        return hidden_states, all_hidden_states, all_self_attns\n\n    def forward(\n        self,\n        input_ids: Optional[torch.LongTensor] = None,\n        inputs_embeds: Optional[torch.FloatTensor] = None,\n        attention_mask: Optional[torch.BoolTensor] = None,\n        audio_features: Optional[torch.FloatTensor] = None,\n        audio_feature_attention_mask: Optional[torch.BoolTensor] = None,\n        audio_in_ids: Optional[torch.LongTensor] = None,\n        audio_in_ids_start: Optional[torch.LongTensor] = None,\n        audio_out_ids: Optional[torch.LongTensor] = None,\n        audio_out_ids_start: Optional[torch.LongTensor] = None,\n        audio_out_ids_start_group_loc: Optional[torch.LongTensor] = None,\n        label_ids: Optional[torch.LongTensor] = None,\n        label_audio_ids: Optional[torch.LongTensor] = None,\n        past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,\n        use_cache: Optional[bool] = None,\n        output_attentions: Optional[bool] = None,\n        output_hidden_states: Optional[bool] = None,\n        output_audio_hidden_states: Optional[bool] = False,\n        return_dict: Optional[bool] = None,\n        cache_position: Optional[torch.LongTensor] = None,\n        cache_audio_discrete_codes_mask: Optional[torch.LongTensor] = None,\n        past_key_values_buckets: Optional[OrderedDict[int, Cache]] = None,\n        reward: Optional[torch.FloatTensor] = None,\n    ):\n        \"\"\"Forward pass for the Higgs-Audio model.\n\n        Args:\n            input_ids (:obj:`torch.LongTensor`):\n                The input ids of the prompt. It will have shape (bsz, seq_len).\n                When use_cache is enabled, the input_ids will have\n                shape (bsz, 1) for incremental decode or None\n            inputs_embeds:\n                Input embeddings. This flag won't be used.\n            attention_mask (:obj:`torch.LongTensor`):\n                The attention mask of the prompt. It will have shape (bsz, seq_len).\n            audio_features (:obj:`torch.FloatTensor`):\n                The audio features extracted by Whisper. It will have shape (num_audio_in, feature_dim, max_mel_seq_len).\n            audio_feature_attention_mask (:obj:`torch.LongTensor`):\n                The attention mask of the audio features. It will have shape (num_audio_in, max_mel_seq_len).\n            audio_in_ids (:obj:`torch.LongTensor`):\n                The discretized audio tokens. It will have shape (num_codebooks, audio_in_total_length).\n            audio_in_ids_start (:obj:`torch.LongTensor`):\n                The start indices for each audio in audio_in_ids. It will have shape (num_audio_in,)\n            audio_out_ids (:obj:`torch.LongTensor`):\n                The discretized audio tokens. It will have shape (num_codebooks, audio_out_total_length).\n            audio_out_ids_start (:obj:`torch.LongTensor`):\n                The start indices for each audio in audio_out_ids. It will have shape (num_audio_out,)\n            audio_out_ids_start_group_loc (:obj:`torch.LongTensor`):\n                The sample indices in a batch that map to each element in the audio_out_ids_start. It will have shape (num_audio_out,)\n            label_text_ids (:obj:`torch.LongTensor`):\n                The labels of the prompt. It will have shape (bsz, seq_len).\n            label_audio_ids (:obj:`torch.LongTensor`):\n                The labels of the audio tokens. It will have the same shape as audio_out_ids, i.e., (num_codebooks, audio_out_total_length)\n            past_key_values (:obj:`Tuple`):\n                Tuple of past key values.\n            use_cache (:obj:`bool`):\n                Whether to use cache.\n            output_attentions (:obj:`bool`):\n                Whether to output attentions.\n            output_hidden_states (:obj:`bool`):\n                Whether to output hidden states.\n            output_audio_hidden_states (:obj:`bool`):\n                Whether to output audio hidden states.\n            return_dict (:obj:`bool`):\n                Whether to return a dictionary.\n            cache_position (:obj:`torch.LongTensor`):\n                The position of the cache.\n            cache_audio_discrete_codes_mask (:obj:`torch.LongTensor`):\n                The cached audio discrete codes mask. It will only be used when use_cache is turned on.\n            past_key_values_buckets (:obj:`OrderedDict`):\n                The buckets of past key values.\n        \"\"\"\n        target_device = input_ids.device\n\n        # not used\n        del inputs_embeds\n\n        if audio_features is not None:\n            audio_features = audio_features.to(target_device)\n            audio_feature_attention_mask = audio_feature_attention_mask.to(target_device)\n\n        # 1. Extract the input embeddings\n        inputs_embeds = self.embed_tokens(input_ids)\n\n        # 2. Extract audio embeddings\n        if self.config.skip_audio_tower:\n            audio_features_embed = audio_features_length = None\n        else:\n            audio_features_embed, audio_features_length = self._apply_audio_tower(\n                audio_features, audio_feature_attention_mask\n            )\n\n        if self.config.encode_audio_in_tokens:\n            if audio_in_ids is not None and audio_in_ids.shape[-1] > 0:\n                audio_in_ids = audio_in_ids.to(target_device)\n            else:\n                audio_in_ids = torch.zeros((self.audio_num_codebooks, 0), device=target_device, dtype=torch.long)\n            audio_in_embed = self._embed_audio_ids(audio_in_ids)\n        else:\n            audio_in_embed = None\n\n        if audio_out_ids is not None and audio_out_ids.shape[-1] > 0:\n            audio_out_ids = audio_out_ids.to(target_device)\n        else:\n            audio_out_ids = torch.zeros((self.audio_num_codebooks, 0), device=target_device, dtype=torch.long)\n        audio_out_embed = self._embed_audio_ids(audio_out_ids)\n\n        # 3. Merge text, audio-in embeddings, and audio-out embeddings\n\n        # use_cache is turned on during inference time, we should set round_to to 1 to avoid extra padding in the end.\n        round_to = 1 if use_cache else 8\n        left_padding = True if use_cache or input_ids.shape[0] == 1 else False\n        (\n            inputs_embeds,\n            attention_mask,\n            labels,\n            position_ids,\n            input_ids,\n            audio_in_mask,\n            audio_in_discrete_codes_mask,\n            audio_out_mask,\n        ) = merge_input_ids_with_audio_features(\n            audio_features_embed,\n            audio_features_length,\n            audio_in_embed,\n            audio_in_ids_start,\n            audio_out_embed,\n            audio_out_ids_start,\n            self.audio_in_token_idx,\n            self.audio_out_token_idx,\n            inputs_embeds,\n            input_ids,\n            attention_mask,\n            label_ids,\n            pad_token_id=self.padding_idx,\n            round_to=round_to,\n            left_padding=left_padding,\n        )\n\n        # re-check if we use the correct kv cache bucket after\n        # the input_embeds has been merged with audio features\n        if past_key_values_buckets is not None and inputs_embeds.shape[1] > past_key_values.get_max_cache_shape():\n            past_key_values, self.current_past_key_values_bucket = self._prepare_kv_cache(\n                inputs_embeds.shape[1], None, past_key_values_buckets\n            )\n\n        if use_cache and past_key_values is None:\n            past_key_values = DynamicCache()\n\n        if cache_position is None:\n            past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0\n            cache_position = torch.arange(\n                past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device\n            )\n            if isinstance(past_key_values, StaticCache) and past_seen_tokens >= past_key_values.get_max_cache_shape():\n                raise ValueError(\n                    f\"The current sequence length ({past_seen_tokens}) exceeds \"\n                    f\"the maximum cache shape. \"\n                    f\"Please consider increasing the cache size.\"\n                )\n\n        # Use torch compile\n        use_static_cache = isinstance(past_key_values, StaticCache)\n\n        # Apply the LLM component\n        causal_mask = self._update_causal_mask(\n            attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions\n        )\n\n        hidden_states = inputs_embeds\n\n        audio_discrete_codes_mask = audio_in_discrete_codes_mask | audio_out_mask\n        if cache_audio_discrete_codes_mask is not None and use_cache:\n            audio_discrete_codes_mask = torch.concat(\n                [cache_audio_discrete_codes_mask, audio_discrete_codes_mask], dim=1\n            )\n\n        # Generate the audio attention mask outside the layer to avoid recompilation\n        if use_static_cache:\n            fast_forward_attention_mask, audio_attention_mask = self._prepare_all_static_kv_cache_masks(\n                hidden_states, causal_mask, audio_discrete_codes_mask, past_key_values\n            )\n            # Set the audio out mask to the last token\n            if hidden_states.shape[1] == 1:\n                audio_discrete_codes_mask = audio_discrete_codes_mask[:, -1:]\n                audio_discrete_codes_mask = audio_discrete_codes_mask.reshape((-1, 1)).contiguous()\n                is_decoding_audio_token = audio_discrete_codes_mask.item()\n            else:\n                is_decoding_audio_token = False\n\n        # Use the captured cuda graph runner for decoding\n        # if it exists, otherwise use the normal forward pass\n        if (\n            past_key_values is not None\n            and past_key_values.get_max_cache_shape() in self.decode_graph_runners\n            and (input_ids.shape[-1] == 1)\n        ):\n            _forward_core = self.decode_graph_runners[past_key_values.get_max_cache_shape()][is_decoding_audio_token]\n            is_using_cuda_graph = True\n        else:\n            _forward_core = self._forward_core\n            is_using_cuda_graph = False\n\n        hidden_states, all_hidden_states, all_self_attns = _forward_core(\n            hidden_states=hidden_states,\n            causal_mask=causal_mask,\n            position_ids=position_ids,\n            audio_discrete_codes_mask=audio_discrete_codes_mask,\n            is_decoding_audio_token=is_decoding_audio_token if use_static_cache else None,\n            cache_position=cache_position,\n            past_key_values=past_key_values,\n            use_cache=use_cache,\n            audio_attention_mask=audio_attention_mask if use_static_cache else None,\n            fast_forward_attention_mask=fast_forward_attention_mask if use_static_cache else None,\n            output_attentions=output_attentions,\n            output_hidden_states=output_hidden_states,\n            is_using_cuda_graph=is_using_cuda_graph,\n        )\n        hidden_states = self.norm(hidden_states)\n\n        # add hidden states from the last decoder layer\n        if output_hidden_states:\n            all_hidden_states += (hidden_states,)\n\n        # Apply the audio decoder projector\n        logits, audio_logits, decoder_all_self_attns, decoder_all_hidden_states, audio_hidden_states, _ = (\n            self.audio_decoder_proj(\n                hidden_states,\n                audio_out_mask,\n                label_audio_ids=label_audio_ids,\n                attention_mask=causal_mask,\n                position_ids=position_ids,\n                past_key_values=past_key_values,\n                use_cache=use_cache,\n                output_attentions=output_attentions,\n                output_audio_hidden_states=output_audio_hidden_states,\n                cache_position=cache_position,\n            )\n        )\n\n        if audio_logits is not None:\n            audio_logits = audio_logits.view(\n                audio_logits.shape[0], self.audio_num_codebooks, self.audio_codebook_size\n            ).float()\n\n        if output_hidden_states:\n            if decoder_all_hidden_states is not None and len(decoder_all_hidden_states) > 1:\n                all_hidden_states += decoder_all_hidden_states[1:]\n\n        if output_attentions:\n            all_self_attns += decoder_all_self_attns\n\n        next_cache = past_key_values if use_cache else None\n\n        ret = HiggsAudioModelOutputWithPast(\n            logits=logits,\n            audio_logits=audio_logits,\n            expanded_input_ids=input_ids,\n            expanded_labels=labels,\n            audio_in_mask=audio_in_mask,\n            audio_in_discrete_codes_mask=audio_in_discrete_codes_mask,\n            audio_out_mask=audio_out_mask,\n            attention_mask=attention_mask,\n            past_key_values=next_cache,\n            hidden_states=all_hidden_states,\n            audio_hidden_states=audio_hidden_states,\n            attentions=all_self_attns,\n        )\n\n        return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n        if not return_dict:\n            outputs = ret.to_tuple()\n            return outputs\n\n        return ret\n\n    # Overwrite GenerationMixin._update_model_kwargs_for_generation\n    def _update_model_kwargs_for_generation(\n        self,\n        outputs: ModelOutput,\n        model_kwargs: Dict[str, Any],\n        is_encoder_decoder: bool = False,\n        num_new_tokens: int = 1,\n        extend_attention_mask: bool = True,\n    ) -> Dict[str, Any]:\n        \"\"\"Update the model kwargs for each step.\"\"\"\n        model_kwargs[\"past_key_values\"] = outputs.past_key_values\n\n        # update attention mask\n        if \"attention_mask\" in model_kwargs:\n            attention_mask = model_kwargs[\"attention_mask\"]\n            if extend_attention_mask:\n                model_kwargs[\"attention_mask\"] = torch.cat(\n                    [attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1\n                )\n        if \"cache_audio_discrete_codes_mask\" in model_kwargs:\n            if model_kwargs[\"cache_audio_discrete_codes_mask\"] is None:\n                model_kwargs[\"cache_audio_discrete_codes_mask\"] = (\n                    outputs.audio_in_discrete_codes_mask | outputs.audio_out_mask\n                )\n            else:\n                model_kwargs[\"cache_audio_discrete_codes_mask\"] = torch.concat(\n                    [\n                        model_kwargs[\"cache_audio_discrete_codes_mask\"],\n                        outputs.audio_in_discrete_codes_mask | outputs.audio_out_mask,\n                    ],\n                    1,\n                )\n\n        return model_kwargs\n\n    def _copy_kv_cache(self, from_cache: Cache, to_cache: Cache):\n        num_layers = self.config.text_config.num_hidden_layers\n        if self.config.audio_dual_ffn_layers is not None:\n            num_layers += len(self.config.audio_dual_ffn_layers)\n        \"\"\" Copy the key-value pairs from one cache to another. \"\"\"\n        for layer_idx in range(num_layers):\n            from_cache_size = from_cache.get_max_cache_shape()\n            assert to_cache.get_max_cache_shape() >= from_cache_size, (\n                f\"The target cache size {to_cache.get_max_cache_shape()} is smaller than the source cache size {from_cache_size}.\"\n            )\n            to_cache.key_cache[layer_idx][:, :, :from_cache_size, :] = from_cache.key_cache[layer_idx]\n            to_cache.value_cache[layer_idx][:, :, :from_cache_size, :] = from_cache.value_cache[layer_idx]\n\n    def _prepare_kv_cache(\n        self,\n        current_sequence_length: int,\n        current_past_key_values_bucket: Optional[int],\n        past_key_values_buckets: OrderedDict[int, Cache],\n    ) -> Tuple[Optional[Cache], Optional[int]]:\n        \"\"\"Prepare the KV cache for the current sequence length.\"\"\"\n        for cache_length in past_key_values_buckets.keys():\n            if cache_length >= current_sequence_length:\n                # Promote to the next KV cache bucket, copy the current KV cache bucket\n                # to the new one.\n                if current_past_key_values_bucket is not None and cache_length != current_past_key_values_bucket:\n                    self._copy_kv_cache(\n                        past_key_values_buckets[current_past_key_values_bucket], past_key_values_buckets[cache_length]\n                    )\n\n                return past_key_values_buckets[cache_length], cache_length\n\n        raise ValueError(\n            f\"The current sequence length {current_sequence_length} is larger than \"\n            f\"all past key values buckets {past_key_values_buckets.keys()}.\"\n        )\n\n    def _sample_audio_tokens(\n        self,\n        hidden_states: torch.Tensor,\n        audio_logits: torch.Tensor,\n        audio_out_ids: torch.Tensor,\n        do_sample: bool,\n        logits_processor: LogitsProcessorList,\n        device: torch.device,\n        torch_generator: Optional[torch.Generator],\n        generation_config: GenerationConfig,\n        num_delay: int,\n        num_remaining_delays: Optional[int],\n    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, int, Optional[int]]:\n        \"\"\"Sample audio tokens and its corresponding text tokens from the logits\"\"\"\n\n        # parameters related to repetition aware sampling\n        ras_win_len = generation_config.generation_kwargs.get(\"ras_win_len\", None)\n        ras_win_max_num_repeat = generation_config.generation_kwargs.get(\"ras_win_max_num_repeat\", 2)\n        audio_eos_token_id = generation_config.generation_kwargs.get(\"audio_eos_token_id\", None)\n        # In the audio generation mode, we sample from audio_logits and keep updating audio_out_ids.\n        next_audio_token_logits = audio_logits.clone()[-1, :, :].float().to(device)\n        # TopP, TopK logits processor supports empty input_ids\n        next_audio_token_scores = logits_processor(None, next_audio_token_logits)\n\n        # token selection\n        if do_sample:\n            # next_audio_token_scores has been applied top_p, top_k, and temperature.\n            probs = nn.functional.softmax(next_audio_token_scores, dim=-1)\n            # TODO (joao): this OP throws \"skipping cudagraphs due to ['incompatible ops']\", find solution\n            next_audio_tokens = torch.multinomial(probs, num_samples=1, generator=torch_generator).squeeze(1)\n        else:\n            next_audio_tokens = torch.argmax(next_audio_token_scores, dim=-1)\n\n        # next_tokens: (num_codebooks, )\n        if ras_win_len is not None:\n            # check if there are repetitions over a window of tokens.\n            rep_num = (audio_out_ids[:, -ras_win_len:] == next_audio_tokens.unsqueeze(1)).sum(dim=1)\n\n            # if we saw repeated tokens in the most recent window of tokens, resample without temperature.\n            row_indices = torch.nonzero(rep_num >= ras_win_max_num_repeat).squeeze(1)\n            resampled_next_tokens = (\n                next_audio_token_logits[row_indices]\n                .softmax(dim=-1)\n                .multinomial(1, replacement=True, generator=torch_generator)\n                .squeeze(1)\n            )\n            next_audio_tokens[row_indices] = resampled_next_tokens\n\n        # Force the next text tokens to be <|AUDIO_OUT|> in audio generation mode\n        next_tokens = torch.full(\n            (audio_logits.shape[0],),\n            self.config.audio_out_token_idx,\n            dtype=torch.long,\n            device=device,\n        )\n\n        # Handle delay_pattern\n        if self.use_delay_pattern:\n            if num_delay + 1 < next_audio_tokens.shape[0]:\n                next_audio_tokens[(num_delay + 1) :] = self.config.audio_stream_bos_id\n                num_delay += 1\n            if num_remaining_delays is not None:\n                next_audio_tokens[: (self.audio_num_codebooks - num_remaining_delays)] = (\n                    self.config.audio_stream_eos_id\n                )\n                num_remaining_delays -= 1\n            else:\n                all_eos_indices = (next_audio_tokens == self.config.audio_stream_eos_id).nonzero()\n                if torch.numel(all_eos_indices) > 0:\n                    all_eos_indices = all_eos_indices[0]\n                    last_eos_idx = all_eos_indices[-1]\n                    next_audio_tokens[:last_eos_idx] = self.config.audio_stream_eos_id\n                    num_remaining_delays = self.audio_num_codebooks - last_eos_idx - 1\n            if num_remaining_delays is not None and num_remaining_delays <= 0:\n                next_tokens[...] = audio_eos_token_id\n                num_delay = 0\n                num_remaining_delays = None\n\n        return (\n            next_tokens,\n            next_audio_tokens,\n            next_audio_token_logits,\n            next_audio_token_scores,\n            num_delay,\n            num_remaining_delays,\n        )\n\n    def _sample_text_tokens(\n        self,\n        logits: torch.Tensor,\n        input_ids: torch.Tensor,\n        do_sample: bool,\n        logits_processor: LogitsProcessorList,\n        device: torch.device,\n        generation_mode: GenerationMode,\n        torch_generator: Optional[torch.Generator],\n    ) -> torch.Tensor:\n        \"\"\"Sample text tokens from the logits\"\"\"\n        # Clone is needed to avoid keeping a hanging ref to outputs.logits which may be very large for first iteration\n        # (the clone itself is always small)\n        next_token_logits = logits.clone()[:, -1, :].float()\n        next_token_logits = next_token_logits.to(input_ids.device)\n\n        # pre-process distribution\n        next_token_scores = logits_processor(input_ids, next_token_logits)\n\n        if generation_mode == GenerationMode.AUDIO_INIT:\n            # See the audio bos token, we should start generating audio tokens\n            next_tokens = torch.full(\n                (input_ids.shape[0],),\n                self.audio_out_token_idx,\n                dtype=torch.long,\n                device=device,\n            )\n            next_audio_tokens = torch.full(\n                (self.config.audio_num_codebooks,),\n                self.config.audio_stream_bos_id,\n                dtype=torch.long,\n                device=device,\n            )\n        else:\n            if do_sample:\n                probs = nn.functional.softmax(next_token_scores, dim=-1)\n                # TODO (joao): this OP throws \"skipping cudagraphs due to ['incompatible ops']\", find solution\n                next_tokens = torch.multinomial(probs, num_samples=1, generator=torch_generator).squeeze(1)\n            else:\n                next_tokens = torch.argmax(next_token_scores, dim=-1)\n\n            next_audio_tokens = None\n\n        return next_tokens, next_audio_tokens, next_token_logits, next_token_scores\n\n    # Built on top of GenerationMixin._sample.\n    # We revise the implementation to support generating both audio / text.\n    def _sample(\n        self,\n        input_ids: torch.LongTensor,\n        logits_processor: LogitsProcessorList,\n        stopping_criteria: StoppingCriteriaList,\n        generation_config: GenerationConfig,\n        synced_gpus: bool,\n        streamer: Optional[\"BaseStreamer\"],\n        past_key_values_buckets: Optional[OrderedDict[int, Cache]],\n        **model_kwargs,\n    ) -> Union[GenerateNonBeamOutput, torch.LongTensor]:\n        r\"\"\"\n        Generates sequences of token ids for joint text/audio models using **multinomial sampling**.\n\n        This function may also be revised to support generating samples from HiggsAudio-like end-to-end text/audio models built on top of LLMs.\n        If the input_ids ends with <|audio_out_bos|>, we will switch to the audio-generation mode.\n\n        ```\n        ...<|start_header_id|>assistant<|end_header_id|>\\n\\n<|audio_out_bos|>\n        ```\n\n        Otherwise, we will keep generating the text tokens.\n\n        Parameters:\n            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n                The sequence used as a prompt for the generation.\n            logits_processor (`LogitsProcessorList`):\n                An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]\n                used to modify the prediction scores of the language modeling head applied at each generation step.\n            stopping_criteria (`StoppingCriteriaList`):\n                An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]\n                used to tell if the generation loop should stop.\n            generation_config ([`~generation.GenerationConfig`]):\n                The generation configuration to be used as parametrization of the decoding method.\n            synced_gpus (`bool`):\n                Whether to continue running the while loop until max_length (needed to avoid deadlocking with\n                `FullyShardedDataParallel` and DeepSpeed ZeRO Stage 3).\n            streamer (`BaseStreamer`, *optional*):\n                Streamer object that will be used to stream the generated sequences. Generated tokens are passed\n                through `streamer.put(token_ids)` and the streamer is responsible for any further processing.\n            model_kwargs:\n                Additional model specific kwargs will be forwarded to the `forward` function of the model. If model is\n                an encoder-decoder model the kwargs should include `encoder_outputs`.\n\n        Return:\n            [`~generation.GenerateDecoderOnlyOutput`], [`~generation.GenerateEncoderDecoderOutput`] or `torch.LongTensor`:\n            A `torch.LongTensor` containing the generated tokens (default behaviour) or a\n            [`~generation.GenerateDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and\n            `return_dict_in_generate=True` or a [`~generation.GenerateEncoderDecoderOutput`] if\n            `model.config.is_encoder_decoder=True`.\n        \"\"\"\n        assert input_ids.shape[0] == 1, \"Only support batch_size=1 in _sample()\"\n        audio_out_bos_token_id = generation_config.generation_kwargs.get(\"audio_out_bos_token_id\", None)\n\n        # torch generator for sampling\n        seed = generation_config.generation_kwargs.get(\"seed\", None)\n        if seed is not None:\n            torch_generator = torch.Generator(device=input_ids.device).manual_seed(seed)\n        else:\n            torch_generator = None\n\n        # init values\n        pad_token_id = generation_config._pad_token_tensor\n        output_attentions = generation_config.output_attentions\n        output_hidden_states = generation_config.output_hidden_states\n        output_scores = generation_config.output_scores\n        output_logits = generation_config.output_logits\n        return_dict_in_generate = generation_config.return_dict_in_generate\n        max_length = generation_config.max_length\n        has_eos_stopping_criteria = any(hasattr(criteria, \"eos_token_id\") for criteria in stopping_criteria)\n        do_sample = generation_config.do_sample\n        # Used to track which past_key_va\n        self.current_past_key_values_bucket = None\n\n        # init attention / hidden states / scores tuples\n        scores = () if (return_dict_in_generate and output_scores) else None\n        raw_logits = () if (return_dict_in_generate and output_logits) else None\n\n        decoder_attentions = () if (return_dict_in_generate and output_attentions) else None\n        decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None\n\n        # keep track of which sequences are already finished\n        batch_size, cur_len = input_ids.shape\n        this_peer_finished = False\n        unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)\n        if generation_config.use_cache:\n            model_kwargs[\"cache_audio_discrete_codes_mask\"] = None\n\n        init_model_input = True\n        num_delay = 0\n        num_remaining_delays = None\n        audio_sequences = []\n        # A tensor to keep track of all the audio placeholder tokens.\n        input_ids_full = input_ids.clone()\n\n        # Initialize the audio variables based on the input prompt.\n        if input_ids[0][-1] == self.config.audio_out_token_idx:\n            audio_sequences = [model_kwargs[\"audio_out_ids\"][:, model_kwargs[\"audio_out_ids_start\"][-1] :]]\n            if self.use_delay_pattern:\n                num_delay = (\n                    self.audio_num_codebooks\n                    - (model_kwargs[\"audio_out_ids\"][:, -1] == self.config.audio_stream_bos_id).sum()\n                )\n                all_eos_indices = (model_kwargs[\"audio_out_ids\"][:, -1] == self.config.audio_stream_eos_id).nonzero()\n                if torch.numel(all_eos_indices) > 0:\n                    all_eos_indices = all_eos_indices[0]\n                    last_eos_idx = all_eos_indices[-1]\n                    num_remaining_delays = self.audio_num_codebooks - last_eos_idx - 1\n\n        while self._has_unfinished_sequences(\n            this_peer_finished, synced_gpus, device=input_ids.device, cur_len=cur_len, max_length=max_length\n        ):\n            # Check which multimodal stage we are in\n            # FIXME: Assume single input generation\n            if input_ids[0][-1] == audio_out_bos_token_id:\n                generation_mode = GenerationMode.AUDIO_INIT\n            elif input_ids[0][-1] == self.audio_out_token_idx:\n                generation_mode = GenerationMode.AUDIO_IN_PROGRESS\n            else:\n                generation_mode = GenerationMode.TEXT\n\n            is_audio_generation_mode = generation_mode == GenerationMode.AUDIO_IN_PROGRESS\n\n            if init_model_input or not generation_config.use_cache:\n                model_inputs = {\"input_ids\": input_ids, **model_kwargs}\n            else:\n                model_inputs = {\"input_ids\": input_ids[:, -1:], **model_kwargs}\n\n                if is_audio_generation_mode and generation_config.use_cache:\n                    model_inputs[\"audio_out_ids\"] = model_kwargs[\"audio_out_ids\"][:, -1:]\n                    model_inputs[\"audio_out_ids_start\"] = torch.tensor([0], dtype=torch.long, device=input_ids.device)\n                elif not is_audio_generation_mode:\n                    del model_inputs[\"audio_out_ids\"]\n                    del model_inputs[\"audio_out_ids_start\"]\n\n                if generation_config.use_cache:\n                    if \"audio_features\" in model_inputs and model_inputs[\"audio_features\"] is not None:\n                        model_inputs[\"audio_features\"] = model_inputs[\"audio_features\"][:0, ...]\n                        model_inputs[\"audio_feature_attention_mask\"] = model_inputs[\"audio_feature_attention_mask\"][\n                            :0, ...\n                        ]\n\n                    if \"audio_in_ids\" in model_inputs and model_inputs[\"audio_in_ids\"] is not None:\n                        model_inputs[\"audio_in_ids\"] = None\n                        model_inputs[\"audio_in_ids_start\"] = None\n\n            # prepare variable output controls (note: some models won't accept all output controls)\n            model_inputs.update({\"output_attentions\": output_attentions} if output_attentions else {})\n            model_inputs.update({\"output_hidden_states\": output_hidden_states} if output_hidden_states else {})\n\n            if past_key_values_buckets is not None:\n                past_key_values, self.current_past_key_values_bucket = self._prepare_kv_cache(\n                    cur_len, self.current_past_key_values_bucket, past_key_values_buckets\n                )\n                if past_key_values is not None:\n                    model_inputs.update({\"past_key_values\": past_key_values})\n                model_inputs[\"past_key_values_buckets\"] = past_key_values_buckets\n\n            # forward pass to get next token\n            outputs = self(**model_inputs, return_dict=True)\n\n            # Update the actual sequence length after the first forward pass\n            if init_model_input and past_key_values_buckets is not None:\n                cur_len = past_key_values_buckets[self.current_past_key_values_bucket].get_seq_length().item()\n\n            # synced_gpus: don't waste resources running the code we don't need; kwargs must be updated before skipping\n            model_kwargs = self._update_model_kwargs_for_generation(\n                outputs,\n                model_kwargs,\n                is_encoder_decoder=self.config.is_encoder_decoder,\n                extend_attention_mask=True,\n            )\n\n            # After the first forward pass, we can set init_model_input to False.\n            init_model_input = False\n\n            if synced_gpus and this_peer_finished:\n                continue\n\n            if is_audio_generation_mode:\n                # In audio generation mode, we sample the audio tokens from audio logits.\n                # It might also generate the audio eos token to end the audio generation.\n                (\n                    next_tokens,\n                    next_audio_tokens,\n                    next_audio_token_logits,\n                    next_audio_token_scores,\n                    num_delay,\n                    num_remaining_delays,\n                ) = self._sample_audio_tokens(\n                    hidden_states=outputs.audio_hidden_states,\n                    audio_logits=outputs.audio_logits,\n                    audio_out_ids=model_kwargs[\"audio_out_ids\"],\n                    do_sample=do_sample,\n                    logits_processor=logits_processor,\n                    device=input_ids.device,\n                    torch_generator=torch_generator,\n                    generation_config=generation_config,\n                    num_delay=num_delay,\n                    num_remaining_delays=num_remaining_delays,\n                )\n\n                # update generated ids, model inputs, and length for next step\n                model_kwargs[\"audio_out_ids\"] = torch.cat(\n                    [model_kwargs[\"audio_out_ids\"], next_audio_tokens[:, None]], dim=-1\n                )\n                audio_sequences[-1] = torch.cat([audio_sequences[-1], next_audio_tokens[:, None]], dim=-1)\n\n                if streamer is not None:\n                    streamer.put(next_audio_tokens.cpu())\n            else:\n                # In text generation mode, we sample the text tokens from text logits.\n                # It might also generate the audio placeholder token to start the audio generation.\n                next_tokens, next_audio_tokens, next_token_logits, next_token_scores = self._sample_text_tokens(\n                    input_ids=input_ids,\n                    logits=outputs.logits,\n                    do_sample=do_sample,\n                    logits_processor=logits_processor,\n                    device=input_ids.device,\n                    generation_mode=generation_mode,\n                    torch_generator=torch_generator,\n                )\n\n                if streamer is not None:\n                    streamer.put(next_tokens.cpu())\n\n                if next_audio_tokens is not None:\n                    # If the token is audio bos token, we will generate the audio placeholder token\n                    # and the corrensponding audio stream bos token to start the audio generation.\n                    audio_sequences.append(next_audio_tokens[:, None])\n                    if streamer is not None:\n                        streamer.put(next_audio_tokens.cpu())\n                    if model_kwargs[\"audio_out_ids\"] is None or model_kwargs[\"audio_out_ids\"].shape[0] == 0:\n                        # Initialize audio_out_ids\n                        model_kwargs[\"audio_out_ids\"] = next_audio_tokens[:, None]\n                        model_kwargs[\"audio_out_ids_start\"] = torch.tensor(\n                            [0], dtype=torch.long, device=input_ids.device\n                        )\n                    else:\n                        model_kwargs[\"audio_out_ids_start\"] = torch.concat(\n                            [\n                                model_kwargs[\"audio_out_ids_start\"],\n                                torch.tensor(\n                                    [model_kwargs[\"audio_out_ids\"].shape[1]], dtype=torch.long, device=input_ids.device\n                                ),\n                            ],\n                            dim=0,\n                        )\n                        model_kwargs[\"audio_out_ids\"] = torch.concat(\n                            [model_kwargs[\"audio_out_ids\"], next_audio_tokens[:, None]], dim=1\n                        )\n\n            if return_dict_in_generate:\n                if output_scores:\n                    if is_audio_generation_mode:\n                        scores += (next_audio_token_scores,)\n                    else:\n                        scores += (next_token_scores,)\n                if output_logits:\n                    if is_audio_generation_mode:\n                        raw_logits += (next_audio_token_logits,)\n                    else:\n                        raw_logits += (next_token_logits,)\n                if output_attentions:\n                    decoder_attentions += (outputs.attentions,)\n                if output_hidden_states:\n                    decoder_hidden_states += (outputs.hidden_states,)\n\n            # finished sentences should have their next token be a padding token\n            if has_eos_stopping_criteria:\n                next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)\n\n            if \"tokenizer_length\" in generation_config.generation_kwargs:\n                tokenizer_length = generation_config.generation_kwargs[\"tokenizer_length\"]\n                if torch.max(next_tokens) >= tokenizer_length:\n                    raise ValueError(\n                        f\"Next generated token has max value {torch.max(next_tokens)} which is greater than the tokenizer's vocabulary size {tokenizer_length}, this is undesired behavior.\"\n                    )\n\n            # update generated ids, model inputs, and length for next step\n            if not is_audio_generation_mode or next_tokens[0] != self.audio_out_token_idx:\n                # We only add one <|AUDIO_OUT|> token to the input_ids for simplicity.\n                input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)\n            input_ids_full = torch.cat([input_ids_full, next_tokens[:, None]], dim=-1)\n            unfinished_sequences = unfinished_sequences & ~stopping_criteria(input_ids_full, scores)\n            this_peer_finished = unfinished_sequences.max() == 0\n            cur_len += 1\n\n            # This is needed to properly delete outputs.logits which may be very large for first iteration\n            # Otherwise a reference to outputs is kept which keeps the logits alive in the next iteration\n            del outputs\n\n        if streamer is not None:\n            streamer.end()\n\n        if return_dict_in_generate:\n            return HiggsAudioGenerationOutput(\n                sequences=input_ids,\n                audio_sequences=audio_sequences,\n                scores=scores,\n                logits=raw_logits,\n                attentions=decoder_attentions,\n                hidden_states=decoder_hidden_states,\n                past_key_values=model_kwargs.get(\"past_key_values\"),\n            )\n        else:\n            return input_ids, audio_sequences\n\n    @torch.inference_mode()\n    def generate(\n        self,\n        input_ids: Optional[torch.LongTensor] = None,\n        audio_features: Optional[torch.FloatTensor] = None,\n        audio_feature_attention_mask: Optional[torch.BoolTensor] = None,\n        audio_in_ids: Optional[torch.LongTensor] = None,\n        audio_in_ids_start: Optional[torch.LongTensor] = None,\n        audio_out_ids: Optional[torch.LongTensor] = None,\n        audio_out_ids_start: Optional[torch.LongTensor] = None,\n        past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,\n        audio_out_bos_token_id: int = None,\n        audio_eos_token_id: int = None,\n        past_key_values_buckets: Optional[OrderedDict[int, Cache]] = None,\n        seed: Optional[int] = None,\n        **kwargs,\n    ):\n        \"\"\"\n        The generate function in huggingface generally follows these steps:\n\n        for sample_step in 1, 2, 3, 4, 5, ...\n            ...\n\n        \"\"\"\n        # Right now, it's a very simplified version of generate, we should revisit this after our model architecture stabilizes.\n        assert input_ids.shape[0] == 1, (\n            \"Currently HiggsAudioModel.generate() only supports batch_size=1. See the implementation of \"\n        )\n        generation_config, kwargs = self._prepare_generation_config(kwargs.pop(\"generation_config\", None), **kwargs)\n        if audio_out_bos_token_id is not None:\n            generation_config.generation_kwargs[\"audio_out_bos_token_id\"] = audio_out_bos_token_id\n        else:\n            try:\n                generation_config.generation_kwargs[\"audio_out_bos_token_id\"] = self.audio_out_bos_token_id\n            except:\n                generation_config.generation_kwargs[\"audio_out_bos_token_id\"] = None\n\n        if audio_eos_token_id is not None:\n            generation_config.generation_kwargs[\"audio_eos_token_id\"] = audio_eos_token_id\n        else:\n            try:\n                generation_config.generation_kwargs[\"audio_eos_token_id\"] = self.audio_eos_token_id\n            except:\n                generation_config.generation_kwargs[\"audio_eos_token_id\"] = None\n\n        has_default_max_length = kwargs.get(\"max_length\") is None and generation_config.max_length is not None\n        has_default_min_length = kwargs.get(\"min_length\") is None and generation_config.min_length is not None\n\n        generation_config.generation_kwargs[\"ras_win_len\"] = kwargs.pop(\"ras_win_len\", None)\n        generation_config.generation_kwargs[\"ras_win_max_num_repeat\"] = kwargs.pop(\"ras_win_max_num_repeat\", 2)\n        # Set generation seed if determinstic generation is required\n        if seed is not None:\n            generation_config.generation_kwargs[\"seed\"] = seed\n\n        # Store tokenizer in generation config if it is in kwargs without popping it\n        if \"tokenizer\" in kwargs:\n            generation_config.generation_kwargs[\"tokenizer_length\"] = len(kwargs[\"tokenizer\"])\n\n        # input_ids: [bsz, seq_len]\n        # The merging of audio features happens inside the forward path. The input_ids does not need to change.\n        # TODO: prepare the final input embeddings to improve generation performance\n        input_ids_length = input_ids.shape[-1]\n        generation_config = self._prepare_generated_length(\n            generation_config=generation_config,\n            has_default_max_length=has_default_max_length,\n            has_default_min_length=has_default_min_length,\n            model_input_name=None,\n            inputs_tensor=None,\n            input_ids_length=input_ids_length,\n        )\n        assert generation_config.num_beams == 1, \"Currently, we only support beam search with num_beams=1\"\n        return_dict_in_generate = generation_config.return_dict_in_generate\n        output_scores = generation_config.output_scores\n\n        # When attn_implement is spda or flash-attention, it will create causal mask automatically.\n        attention_mask = kwargs.pop(\"attention_mask\", None)\n        return super().generate(\n            input_ids=input_ids,\n            attention_mask=attention_mask,\n            audio_features=audio_features,\n            audio_feature_attention_mask=audio_feature_attention_mask,\n            audio_in_ids=audio_in_ids,\n            audio_in_ids_start=audio_in_ids_start,\n            audio_out_ids=audio_out_ids,\n            audio_out_ids_start=audio_out_ids_start,\n            past_key_values=past_key_values,\n            generation_config=generation_config,\n            output_scores=output_scores,\n            return_dict_in_generate=return_dict_in_generate,\n            past_key_values_buckets=past_key_values_buckets,\n            **kwargs,\n        )\n\n    def parameter_count_per_component(self):\n        \"\"\"Count the number of parameters per component in the model.\n\n        HiggsAudio has the following main components:\n            audio_tower: For mapping audio features to hidden states),\n            llm_embed: The size of embedding layer of the LLM\n            llm_non_embed: The size of non-embedding layer of the LLM\n            audio_adapter: The overall size of additional layers for audio generation\n\n        \"\"\"\n        trainable_stats = {\n            \"audio_tower\": 0,\n            \"llm_embed\": 0,\n            \"llm_non_embed\": 0,\n            \"audio_embed\": 0,\n            \"audio_adapter\": 0,\n            \"overall\": 0,\n        }\n        total_stats = {\n            \"audio_tower\": 0,\n            \"llm_embed\": 0,\n            \"llm_non_embed\": 0,\n            \"audio_embed\": 0,\n            \"audio_adapter\": 0,\n            \"overall\": 0,\n        }\n\n        total_stats[\"overall\"] = count_parameters(self, trainable_only=False)\n        trainable_stats[\"overall\"] = count_parameters(self, trainable_only=True)\n\n        for mod in [self.audio_tower]:\n            if mod is not None:\n                total_stats[\"audio_tower\"] += count_parameters(mod, trainable_only=False)\n                trainable_stats[\"audio_tower\"] += count_parameters(mod, trainable_only=True)\n\n        total_stats[\"llm_embed\"] = count_parameters(self.embed_tokens, trainable_only=False)\n        trainable_stats[\"llm_embed\"] = count_parameters(self.embed_tokens, trainable_only=True)\n\n        total_stats[\"audio_embed\"] = count_parameters(self.audio_codebook_embeddings, trainable_only=False)\n        trainable_stats[\"audio_embed\"] = count_parameters(self.audio_codebook_embeddings, trainable_only=True)\n\n        # Calculate number of parameters for LLM\n        for layer in self.layers:\n            if isinstance(layer, HiggsAudioDualFFNDecoderLayer):\n                total_param_count = count_parameters(layer, trainable_only=False)\n                total_trainable_param_count = count_parameters(layer, trainable_only=True)\n                total_stats[\"llm_non_embed\"] += total_param_count\n                trainable_stats[\"llm_non_embed\"] += total_trainable_param_count\n                if not layer.fast_forward:\n                    audio_mlp_param_count = count_parameters(layer.audio_mlp, trainable_only=False)\n                    audio_mlp_trainable_param_count = count_parameters(layer.audio_mlp, trainable_only=True)\n\n                    audio_norm_param_count = count_parameters(\n                        layer.audio_post_attention_layernorm, trainable_only=False\n                    ) + count_parameters(layer.audio_input_layernorm, trainable_only=False)\n                    audio_norm_trainable_param_count = count_parameters(\n                        layer.audio_post_attention_layernorm, trainable_only=True\n                    ) + count_parameters(layer.audio_input_layernorm, trainable_only=True)\n                    total_stats[\"llm_non_embed\"] -= audio_mlp_param_count + audio_norm_param_count\n                    trainable_stats[\"llm_non_embed\"] -= (\n                        audio_mlp_trainable_param_count + audio_norm_trainable_param_count\n                    )\n                    total_stats[\"audio_adapter\"] += audio_mlp_param_count + audio_norm_param_count\n                    trainable_stats[\"audio_adapter\"] += (\n                        audio_mlp_trainable_param_count + audio_norm_trainable_param_count\n                    )\n\n                    if layer.use_audio_attention:\n                        audio_attn_param_count = count_parameters(\n                            layer.audio_attn, trainable_only=False\n                        ) + count_parameters(layer.audio_post_audio_attn_layer_norm, trainable_only=False)\n                        audio_attn_trainable_param_count = count_parameters(\n                            layer.audio_attn, trainable_only=True\n                        ) + count_parameters(layer.audio_post_audio_attn_layer_norm, trainable_only=True)\n                        total_stats[\"llm_non_embed\"] -= audio_attn_param_count\n                        trainable_stats[\"llm_non_embed\"] -= audio_attn_trainable_param_count\n                        total_stats[\"audio_adapter\"] += audio_attn_param_count\n                        trainable_stats[\"audio_adapter\"] += audio_attn_trainable_param_count\n            else:\n                total_stats[\"llm_non_embed\"] += count_parameters(layer, trainable_only=False)\n                trainable_stats[\"llm_non_embed\"] += count_parameters(layer, trainable_only=True)\n        total_stats[\"llm_non_embed\"] += count_parameters(self.norm, trainable_only=False)\n        trainable_stats[\"llm_non_embed\"] += count_parameters(self.norm, trainable_only=True)\n\n        total_stats[\"audio_adapter\"] += count_parameters(self.audio_decoder_proj.audio_lm_head, trainable_only=False)\n        trainable_stats[\"audio_adapter\"] += count_parameters(\n            self.audio_decoder_proj.audio_lm_head, trainable_only=True\n        )\n        total_stats[\"llm_embed\"] += count_parameters(self.audio_decoder_proj.text_lm_head, trainable_only=False)\n        trainable_stats[\"llm_embed\"] += count_parameters(self.audio_decoder_proj.text_lm_head, trainable_only=True)\n\n        other_audio_modules = [self.audio_encoder_proj]\n        if self.use_audio_out_embed_projector:\n            other_audio_modules.append(self.audio_out_embed_projector)\n\n        for mod in other_audio_modules:\n            if mod is not None:\n                total_stats[\"audio_adapter\"] += count_parameters(mod, trainable_only=False)\n                trainable_stats[\"audio_adapter\"] += count_parameters(mod, trainable_only=True)\n        return {\"trainable\": trainable_stats, \"total\": total_stats}\n\n    def set_skip_audio_tower(self):\n        self.config.skip_audio_tower = True\n        self.config.encode_whisper_embed = False\n\n    def set_encode_audio_in_tokens(self):\n        self.config.encode_audio_in_tokens = True\n\n    def freeze_audio_tower(self):\n        if self.audio_tower is not None:\n            for param in self.audio_tower.parameters():\n                param.requires_grad = False\n\n    def freeze_audio_encoder_proj(self):\n        if self.audio_encoder_proj is not None:\n            for param in self.audio_encoder_proj.parameters():\n                param.requires_grad = False\n\n    def freeze_llm(self, freeze_embed=True, freeze_embed_until_idx: Optional[int] = None):\n        for layer in self.layers:\n            if isinstance(layer, HiggsAudioDualFFNDecoderLayer):\n                for param in layer.self_attn.parameters():\n                    param.requires_grad = False\n                for param in layer.mlp.parameters():\n                    param.requires_grad = False\n\n                for param in layer.post_attention_layernorm.parameters():\n                    param.requires_grad = False\n\n                for param in layer.input_layernorm.parameters():\n                    param.requires_grad = False\n            else:\n                for param in layer.parameters():\n                    param.requires_grad = False\n\n        for param in self.norm.parameters():\n            param.requires_grad = False\n\n        if freeze_embed:\n            if freeze_embed_until_idx is None:\n                for param in self.embed_tokens.parameters():\n                    param.requires_grad = False\n            else:\n                assert isinstance(self.embed_tokens, nn.Embedding)\n                self.embed_tokens = PartiallyFrozenEmbedding(\n                    original_embedding=self.embed_tokens, freeze_until_idx=freeze_embed_until_idx\n                )\n\n    def freeze_text_head(self, freeze_text_head_until_idx: Optional[int] = None):\n        \"\"\"Freeze the final text head\"\"\"\n        if freeze_text_head_until_idx is None:\n            for param in self.audio_decoder_proj.text_lm_head.parameters():\n                param.requires_grad = False\n\n        else:\n            assert isinstance(self.audio_decoder_proj.text_lm_head, nn.Linear)\n            self.audio_decoder_proj.text_lm_head = PartiallyFrozenLinear(\n                original_linear=self.audio_decoder_proj.text_lm_head, freeze_until_idx=freeze_text_head_until_idx\n            )\n\n    @classmethod\n    def merge_weights_from_checkpoint(cls, checkpoint_dir: str, merged_output_dir: str, *model_args, **kwargs):\n        # For users' convenience, we merge back embedding and text_lm_head if they are splitted\n        splitted_model = super().from_pretrained(\n            checkpoint_dir,\n            *model_args,\n            torch_dtype=torch.bfloat16,\n            device_map=\"cpu\",\n            **{**kwargs, \"state_dict\": None},  # Prevent auto-loading state_dict\n        )\n\n        # Load all safetensor shards\n        state_dict = {}\n        shard_paths = sorted(glob.glob(os.path.join(checkpoint_dir, \"*.safetensors\")))\n\n        for shard_path in shard_paths:\n            shard_dict = load_file(shard_path)  # Load each shard\n            state_dict.update(shard_dict)  # Merge into a single dict\n\n        # Merge weights\n        if (\n            \"audio_decoder_proj.text_lm_head.linear_frozen.weight\" in state_dict\n            and \"audio_decoder_proj.text_lm_head.linear_trainable.weight\" in state_dict\n        ):\n            state_dict[\"audio_decoder_proj.text_lm_head.weight\"] = torch.cat(\n                [\n                    state_dict[\"audio_decoder_proj.text_lm_head.linear_frozen.weight\"],\n                    state_dict[\"audio_decoder_proj.text_lm_head.linear_trainable.weight\"],\n                ],\n                dim=0,\n            )\n\n            del state_dict[\"audio_decoder_proj.text_lm_head.linear_frozen.weight\"]\n            del state_dict[\"audio_decoder_proj.text_lm_head.linear_trainable.weight\"]\n\n        if (\n            \"embed_tokens.embedding_frozen.weight\" in state_dict\n            and \"embed_tokens.embedding_trainable.weight\" in state_dict\n        ):\n            state_dict[\"embed_tokens.weight\"] = torch.cat(\n                [\n                    state_dict[\"embed_tokens.embedding_frozen.weight\"],\n                    state_dict[\"embed_tokens.embedding_trainable.weight\"],\n                ],\n                dim=0,\n            )\n\n            del state_dict[\"embed_tokens.embedding_frozen.weight\"]\n            del state_dict[\"embed_tokens.embedding_trainable.weight\"]\n\n        # Load the final state_dict\n        splitted_model.load_state_dict(state_dict, strict=True)\n\n        if merged_output_dir:\n            splitted_model.save_pretrained(merged_output_dir, is_main_process=True, state_dict=state_dict)\n\n    @torch.inference_mode()\n    def capture_model(self, past_key_values: list[Union[Cache, List[torch.FloatTensor]]]) -> None:\n        \"\"\"Capture CUDA graphs for the model's forward pass with different KV cache lengths.\n\n        Args:\n            past_key_values: List of KV caches to capture graphs for\n        \"\"\"\n        for past_key_value in past_key_values:\n            kv_cache_length = past_key_value.get_max_cache_shape()\n            # We capture two graphs, one for decoding audio tokens and one for decoding text tokens\n            for is_decoding_audio_token in [True, False]:\n                runner = CUDAGraphRunner(self._forward_core)\n\n                # Create dummy inputs for graph capture\n                batch_size = 1\n                hidden_dim = self.config.hidden_size\n\n                hidden_states = torch.zeros(\n                    (batch_size, 1, hidden_dim), dtype=self.config.torch_dtype, device=self.device\n                )\n                causal_mask = torch.ones(\n                    (batch_size, 1, 1, kv_cache_length), dtype=self.config.torch_dtype, device=self.device\n                )\n                position_ids = torch.zeros((batch_size, 1), dtype=torch.long, device=self.device)\n                audio_discrete_codes_mask = torch.tensor(\n                    [[is_decoding_audio_token]], dtype=torch.bool, device=self.device\n                )\n                cache_position = torch.tensor([kv_cache_length - 1], dtype=torch.long, device=self.device)\n                audio_attention_mask = torch.ones_like(causal_mask)\n                fast_forward_attention_mask = torch.ones_like(causal_mask)\n\n                runner.capture(\n                    hidden_states=hidden_states,\n                    causal_mask=causal_mask,\n                    position_ids=position_ids,\n                    audio_discrete_codes_mask=audio_discrete_codes_mask,\n                    cache_position=cache_position,\n                    past_key_values=past_key_value,\n                    use_cache=True,\n                    audio_attention_mask=audio_attention_mask,\n                    fast_forward_attention_mask=fast_forward_attention_mask,\n                    output_attentions=False,\n                    output_hidden_states=False,\n                    is_decoding_audio_token=is_decoding_audio_token,\n                    is_using_cuda_graph=True,\n                    stream=torch.cuda.Stream(device=self.device),\n                )\n\n                self.decode_graph_runners[kv_cache_length][is_decoding_audio_token] = runner\n"
  },
  {
    "path": "boson_multimodal/model/higgs_audio/utils.py",
    "content": "import contextlib\nfrom contextlib import contextmanager\nfrom functools import wraps\nimport torch\nfrom transformers.integrations import is_deepspeed_available\n\nif is_deepspeed_available():\n    from deepspeed.utils import groups as deepspeed_groups\n    from deepspeed.sequence.layer import _SeqAllToAll\nelse:\n    deepspeed_groups = None\n    _SeqAllToAll = None\n\n\ndef _ceil_to_nearest(n, round_to):\n    return (n + round_to - 1) // round_to * round_to\n\n\ndef count_parameters(model, trainable_only=True):\n    if trainable_only:\n        return sum(p.numel() for p in model.parameters() if p.requires_grad)\n    else:\n        return sum(p.numel() for p in model.parameters())\n\n\ndef build_delay_pattern_mask(\n    input_ids: torch.LongTensor,\n    bos_token_id: int,\n    pad_token_id: int,\n):\n    \"\"\"Implement the delay pattern proposed in \"Simple and Controllable Music Generation\", https://arxiv.org/pdf/2306.05284\n\n    In the delay pattern, each codebook is offset by the previous codebook by\n    one. We insert a special delay token at the start of the sequence if its delayed, and append pad token once the sequence finishes.\n\n    Take the example where there are 4 codebooks and audio sequence length=5. After shifting, the output should have length seq_len + num_codebooks - 1\n\n    - [ *,  *,  *,  *,  *,  P,  P,  P]\n    - [ B,  *,  *,  *,  *,  *,  P,  P]\n    - [ B,  B,  *,  *,  *,  *,  *,  P]\n    - [ B,  B,  B,  *,  *,  *,  *,  *]\n\n    where B indicates the delay token id, P is the special padding token id and `*` indicates that the original audio token.\n\n    Now let's consider the case where we have a sequence of audio tokens to condition on.\n    The audio tokens were originally in the following non-delayed form:\n\n    - [a, b]\n    - [c, d]\n    - [e, f]\n    - [g, h]\n\n    After conversion, we get the following delayed form:\n    - [a, b, -1, -1, -1]\n    - [B, c,  d, -1, -1]\n    - [B, B,  e,  f, -1]\n    - [B, B,  B,  g,  h]\n\n    Note that we have a special token `-1` that indicates it should be replaced by a new token we see in the generation phase.\n    In that case, we should override the `-1` tokens in auto-regressive generation.\n\n    Args:\n        input_ids (:obj:`torch.LongTensor`):\n            The input ids of the prompt. It will have shape (bsz, num_codebooks, seq_len).\n        bos_token_id (:obj:`int`):\n            The id of the special delay token\n        pad_token_id (:obj:`int`):\n            The id of the padding token. Should be the same as eos_token_id.\n\n    Returns:\n        input_ids (:obj:`torch.LongTensor`):\n            The transformed input ids with delay pattern applied. It will have shape (bsz, num_codebooks, seq_len + num_codebooks - 1).\n        input_ids_with_gen_mask (:obj:`torch.LongTensor`):\n            The transformed input ids with delay pattern applied. The -1 in the output indicates new tokens that should be generated.\n\n    \"\"\"\n    bsz, num_codebooks, seq_len = input_ids.shape\n\n    new_seq_len = seq_len + num_codebooks - 1\n    input_ids_with_gen_mask = torch.ones((bsz, num_codebooks, new_seq_len), dtype=torch.long, device=input_ids.device)\n    bos_mask = torch.tril(input_ids_with_gen_mask, -1) > 0\n    eos_mask = torch.triu(input_ids_with_gen_mask, seq_len) > 0\n    input_ids_with_gen_mask[bos_mask] = bos_token_id\n    input_ids_with_gen_mask[(~bos_mask) & (~eos_mask)] = input_ids.reshape(-1)\n    input_ids = input_ids_with_gen_mask.clone()\n    input_ids[eos_mask] = pad_token_id\n    input_ids_with_gen_mask[eos_mask] = -1\n    return input_ids, input_ids_with_gen_mask\n\n\ndef revert_delay_pattern(data):\n    \"\"\"Convert samples encoded with delay pattern back to the original form.\n\n    Args:\n        data (:obj:`torch.Tensor`):\n            The data with delay pattern applied. It will have shape (num_codebooks, seq_len + num_codebooks - 1).\n\n    Returns:\n        ret (:obj:`torch.Tensor`):\n            Recovered data with delay pattern removed. It will have shape (num_codebooks, seq_len).\n    \"\"\"\n    assert len(data.shape) == 2\n    out_l = []\n    num_codebooks = data.shape[0]\n    for i in range(num_codebooks):\n        out_l.append(data[i : (i + 1), i : (data.shape[1] - num_codebooks + 1 + i)])\n    return torch.cat(out_l, dim=0)\n\n\ndef merge_input_ids_with_audio_features(\n    audio_features_embed,\n    audio_features_length,\n    audio_in_embed,\n    audio_in_ids_start,\n    audio_out_embed,\n    audio_out_ids_start,\n    audio_in_token_idx,\n    audio_out_token_idx,\n    inputs_embeds,\n    input_ids,\n    attention_mask,\n    label_ids,\n    pad_token_id,\n    ignore_index=-100,\n    round_to=8,\n    left_padding=True,\n):\n    \"\"\"\n    Merge input_ids with audio features into final embeddings.\n\n    Args:\n        audio_features_embed (`torch.Tensor` of shape `(num_audios, max_audio_tokens, embed_dim)`):\n            Encoded vectors of all audios in the batch (obtained from the semantic encoder)\n        audio_features_length (`torch.LongTensor` of shape `(num_audios,)`):\n            The length of audio embeddings of each audio as stacked in `audio_features_embed`\n        audio_in_embed (`torch.Tensor` of shape `(total_num_audio_in_tokens, embed_dim)`):\n            The embeddings of audio-in tokens\n        audio_in_ids_start (`torch.LongTensor` of shape `(num_audios,)`):\n            The start index of the audio-in tokens for each audio\n        audio_out_embed (`torch.Tensor` of shape `(total_num_audio_out_tokens, embed_dim)`):\n            The embeddings of audio-out tokens\n        audio_out_ids_start (`torch.LongTensor` of shape `(num_audios,)`):\n            The start index of the audio-out tokens for each audio\n        audio_in_token_idx\n            The index of the audio-in token in the vocabulary\n        audio_out_token_idx\n            The index of the audio-out token in the vocabulary\n        inputs_embeds (`torch.Tensor` of shape `(batch_size, sequence_length, embed_dim)`):\n            Token embeddings before merging with audio embeddings\n        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n            Input_ids of tokens, possibly filled with audio token\n        attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n            Mask to avoid performing attention on padding token indices.\n        label_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*)\n            labels need to be recalculated to support training (if provided)\n        pad_token_id (`int`):\n            The index of the pad token in the vocabulary\n        ignore_index\n            The index to ignore in the loss calculation\n        round_to\n            The number to round to for padding\n        left_padding\n            Whether to apply left padding\n\n    Returns:\n        final_embedding\n            The final embeddings after merging audio embeddings with text embeddings.\n        final_attention_mask\n            The final attention mask after merging audio embeddings with text embeddings.\n        final_labels\n            The labels for the text stream\n        position_ids\n            Positional ids for the merged data\n        final_input_ids\n            The final input_ids after merging audio embeddings with text embeddings.\n        final_audio_in_mask\n            Mask for audio-in embeddings\n        final_audio_in_discrete_codes_mask\n            Mask for audio-in discrete tokens\n        final_audio_out_mask\n            Mask for audio-out embeddings\n\n    Explanation:\n        each audio has variable length embeddings, with length specified by\n        - audio_features_length\n        - audio_in_ids_start\n        - audio_out_ids_start\n\n        Task:\n        - fill each <|AUDIO|> with audio embeddings (it can be the combination of embeddings extracted by WhisperEncoder and embeddings from audio codebooks)\n        - fill each <|AUDIO_OUT|> with the audio-out embeddings\n\n        Example:\n            <|AUDIO_OUT|>: X (5 tokens), Y (3 tokens)\n            <|AUDIO|>: Z (8 tokens)\n\n            X, Y are in the same sequence (in-context voice-clone). Z is in a different sequence (audio understanding).\n        if right padding\n            input_ids: [\n                a b c d e f X g h i j k Y l m\n                o p q r Z s t u v _ _ _ _ _ _\n            ]\n            input_ids should be: [\n                a b c d e f X X X X X g h i j k Y Y Y l m\n                o p q r Z Z Z Z Z Z Z Z s t u v _ _ _ _ _\n            ]\n            labels should be: [\n                a b c d e f _ _ _ _ _ g h i j k _ _ _ l m\n                o p q r _ _ _ _ _ _ _ _ s t u v _ _ _ _ _\n            ]\n        elif left padding\n            input_ids: [\n                a b c d e f X g h i j k Y l m\n                _ _ _ _ _ _ o p q r Z s t u v\n            ]\n            input_ids should be: [\n                a b c d e f X X X X X g h i j k Y Y Y l m\n                _ _ _ _ _ o p q r Z Z Z Z Z Z Z Z s t u v\n            ]\n            labels should be: [\n                a b c d e f _ _ _ _ _ g h i j k _ _ _ l m\n                _ _ _ _ _ o p q r _ _ _ _ _ _ _ _ s t u v\n            ]\n\n    \"\"\"\n    if label_ids is None:\n        skip_labels = True\n    else:\n        skip_labels = False\n    if audio_features_embed is not None and audio_features_embed.shape[0] == 0:\n        audio_features_embed = None\n    if audio_in_embed is not None and audio_in_embed.shape[0] == 0:\n        audio_in_embed = None\n    if audio_out_embed is not None and audio_out_embed.shape[0] == 0:\n        audio_out_embed = None\n\n    batch_size, sequence_length, embed_dim = inputs_embeds.shape\n\n    target_device = inputs_embeds.device\n    if left_padding is None:\n        left_padding = torch.any(attention_mask[:, 0] == 0)\n\n    audio_in_token_mask = input_ids == audio_in_token_idx\n    audio_out_token_mask = input_ids == audio_out_token_idx\n    text_token_mask = (input_ids != audio_in_token_idx) & (input_ids != audio_out_token_idx)\n\n    # 1. Calculate the number of tokens for each placeholder (like [<|AUDIO|>, <|AUDIO_OUT|>]).\n    token_placeholder_num = torch.ones_like(input_ids)\n\n    if audio_features_embed is not None:\n        num_audios, max_audio_tokens, _ = audio_features_embed.shape\n        audio_in_features_mask = torch.arange(max_audio_tokens).expand(num_audios, max_audio_tokens).to(\n            audio_features_length.device\n        ) < audio_features_length.unsqueeze(1)\n        masked_audio_in_features = audio_features_embed[audio_in_features_mask].view(-1, embed_dim)\n        token_placeholder_num[audio_in_token_mask] = audio_features_length.long()\n\n    if audio_in_embed is not None:\n        audio_in_codes_length = torch.concat(\n            [\n                audio_in_ids_start[1:] - audio_in_ids_start[:-1],\n                torch.tensor(\n                    [audio_in_embed.shape[0] - audio_in_ids_start[-1]],\n                    device=audio_in_ids_start.device,\n                    dtype=torch.long,\n                ),\n            ],\n            dim=0,\n        )\n        if audio_features_embed is not None:\n            token_placeholder_num[audio_in_token_mask] += audio_in_codes_length.long()\n        else:\n            token_placeholder_num[audio_in_token_mask] = audio_in_codes_length.long()\n\n    if audio_out_embed is not None:\n        audio_out_codes_length = torch.concat(\n            [\n                audio_out_ids_start[1:] - audio_out_ids_start[:-1],\n                torch.tensor(\n                    [audio_out_embed.shape[0] - audio_out_ids_start[-1]],\n                    device=audio_out_ids_start.device,\n                    dtype=torch.long,\n                ),\n            ],\n            dim=0,\n        )\n        token_placeholder_num[audio_out_token_mask] = audio_out_codes_length.long()\n\n    new_token_positions = torch.cumsum(token_placeholder_num, -1) - 1\n    max_token_num = _ceil_to_nearest(token_placeholder_num.sum(-1).max(), round_to)\n    nb_audio_pad = max_token_num - 1 - new_token_positions[:, -1]\n\n    if left_padding:\n        new_token_positions += nb_audio_pad[:, None]  # offset for left padding\n\n    # 2. Create the full embedding, already padded to the maximum position\n    final_embedding = torch.zeros(\n        (batch_size, max_token_num, embed_dim), dtype=inputs_embeds.dtype, device=inputs_embeds.device\n    )\n    final_attention_mask = torch.zeros(\n        (batch_size, max_token_num), dtype=attention_mask.dtype, device=inputs_embeds.device\n    )\n    final_input_ids = torch.full(\n        (batch_size, max_token_num), pad_token_id, dtype=input_ids.dtype, device=inputs_embeds.device\n    )\n    if skip_labels:\n        final_labels = None\n    else:\n        final_labels = torch.full(\n            (batch_size, max_token_num), ignore_index, dtype=label_ids.dtype, device=inputs_embeds.device\n        )\n\n    final_audio_in_mask = torch.full((batch_size, max_token_num), False, dtype=torch.bool, device=inputs_embeds.device)\n    final_audio_in_discrete_codes_mask = torch.full(\n        (batch_size, max_token_num), False, dtype=torch.bool, device=inputs_embeds.device\n    )\n    final_audio_out_mask = torch.full(\n        (batch_size, max_token_num), False, dtype=torch.bool, device=inputs_embeds.device\n    )\n    # 3. Get the audio-in token positions and audio-out token positions\n    batch_id = torch.arange(batch_size, device=target_device).unsqueeze(1).expand(batch_size, sequence_length)\n    audio_in_batch_id = batch_id[audio_in_token_mask]  # Shape (num_audio_in,)\n    audio_out_batch_id = batch_id[audio_out_token_mask]  # Shape (num_audio_out,)\n    audio_features_token_ends = new_token_positions[audio_in_token_mask]  # Shape (num_audio_in,)\n    audio_out_embed_ends = new_token_positions[audio_out_token_mask]  # Shape (num_audio_out,)\n\n    if audio_in_embed is not None:\n        # Fill in the audio-in embeddings\n        seq_indices = (\n            torch.arange(max_token_num, device=target_device)\n            .unsqueeze(0)\n            .expand(audio_in_ids_start.shape[0], max_token_num)\n        )\n        audio_in_embed_token_starts = audio_features_token_ends - audio_in_codes_length + 1\n        batch_indices, col_indices = torch.where(\n            (seq_indices >= audio_in_embed_token_starts.unsqueeze(1))\n            & (seq_indices <= audio_features_token_ends.unsqueeze(1))\n        )\n        batch_indices = audio_in_batch_id[batch_indices]\n        final_embedding[batch_indices, col_indices] = audio_in_embed\n        final_input_ids[batch_indices, col_indices] = audio_in_token_idx\n        if not skip_labels:\n            final_labels[batch_indices, col_indices] = ignore_index\n        final_audio_in_mask[batch_indices, col_indices] = True\n        final_audio_in_discrete_codes_mask[batch_indices, col_indices] = True\n        audio_features_token_ends = audio_features_token_ends - audio_in_codes_length\n\n    if audio_features_embed is not None:\n        # Fill in the audio features\n        seq_indices = (\n            torch.arange(max_token_num, device=target_device)\n            .unsqueeze(0)\n            .expand(audio_features_embed.shape[0], max_token_num)\n        )\n        audio_features_token_starts = audio_features_token_ends - audio_features_length + 1\n        batch_indices, col_indices = torch.where(\n            (seq_indices >= audio_features_token_starts.unsqueeze(1))\n            & (seq_indices <= audio_features_token_ends.unsqueeze(1))\n        )\n        batch_indices = audio_in_batch_id[batch_indices]\n        final_embedding[batch_indices, col_indices] = masked_audio_in_features\n        final_input_ids[batch_indices, col_indices] = audio_in_token_idx\n        if not skip_labels:\n            final_labels[batch_indices, col_indices] = ignore_index\n        final_audio_in_mask[batch_indices, col_indices] = True\n\n    if audio_out_embed is not None:\n        # Fill in the audio-out embeddings\n        seq_indices = (\n            torch.arange(max_token_num, device=target_device)\n            .unsqueeze(0)\n            .expand(audio_out_ids_start.shape[0], max_token_num)\n        )\n        audio_out_embed_token_starts = audio_out_embed_ends - audio_out_codes_length + 1\n        batch_indices, col_indices = torch.where(\n            (seq_indices >= audio_out_embed_token_starts.unsqueeze(1))\n            & (seq_indices <= audio_out_embed_ends.unsqueeze(1))\n        )\n        batch_indices = audio_out_batch_id[batch_indices]\n        final_embedding[batch_indices, col_indices] = audio_out_embed\n        final_input_ids[batch_indices, col_indices] = audio_out_token_idx\n        if not skip_labels:\n            final_labels[batch_indices, col_indices] = ignore_index\n        final_audio_out_mask[batch_indices, col_indices] = True\n\n    # Fill in the original text embeddings and labels\n    batch_indices, non_audio_indices = torch.where(text_token_mask)\n    text_to_overwrite = new_token_positions[batch_indices, non_audio_indices]\n    final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_audio_indices]\n    if not skip_labels:\n        final_labels[batch_indices, text_to_overwrite] = label_ids[batch_indices, non_audio_indices]\n    final_input_ids[batch_indices, text_to_overwrite] = input_ids[batch_indices, non_audio_indices]\n    final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[batch_indices, non_audio_indices]\n    final_attention_mask = final_attention_mask | final_audio_in_mask | final_audio_out_mask\n\n    # Trim the tensor if there are redundant padding tokens\n    if left_padding:\n        first_non_zero_loc = final_attention_mask.sum(0).nonzero()[0]\n        first_non_zero_loc = (first_non_zero_loc // round_to) * round_to\n        if first_non_zero_loc > 0:\n            final_attention_mask = final_attention_mask[:, first_non_zero_loc:]\n            final_embedding = final_embedding[:, first_non_zero_loc:]\n            if not skip_labels:\n                final_labels = final_labels[:, first_non_zero_loc:]\n            final_input_ids = final_input_ids[:, first_non_zero_loc:]\n            final_audio_in_mask = final_audio_in_mask[:, first_non_zero_loc:]\n            final_audio_in_discrete_codes_mask = final_audio_in_discrete_codes_mask[:, first_non_zero_loc:]\n            final_audio_out_mask = final_audio_out_mask[:, first_non_zero_loc:]\n    else:\n        # We have done right padding, so we need to trim the mask\n        last_non_zero_loc = final_attention_mask.sum(0).nonzero()[-1] + 1\n        last_non_zero_loc = ((last_non_zero_loc + round_to - 1) // round_to) * round_to\n        if last_non_zero_loc < max_token_num:\n            final_attention_mask = final_attention_mask[:, :last_non_zero_loc]\n            final_embedding = final_embedding[:, :last_non_zero_loc]\n            if not skip_labels:\n                final_labels = final_labels[:, :last_non_zero_loc]\n            final_input_ids = final_input_ids[:, :last_non_zero_loc]\n            final_audio_in_mask = final_audio_in_mask[:, :last_non_zero_loc]\n            final_audio_in_discrete_codes_mask = final_audio_in_discrete_codes_mask[:, :last_non_zero_loc]\n            final_audio_out_mask = final_audio_out_mask[:, :last_non_zero_loc]\n\n    position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1)\n    return (\n        final_embedding,\n        final_attention_mask,\n        final_labels,\n        position_ids,\n        final_input_ids,\n        final_audio_in_mask,\n        final_audio_in_discrete_codes_mask,\n        final_audio_out_mask,\n    )\n\n\ndef is_deepspeed_ulysses_enabled():\n    if deepspeed_groups is None:\n        return False\n\n    \"\"\"Check if sequence parallelism is enabled.\"\"\"\n    return deepspeed_groups._get_sequence_parallel_world_size() > 1\n\n\ndef support_deepspeed_ulysses(module):\n    \"\"\"A decorator around Pytorch module. It is needed for the module that needs access to sequence parallel info.\"\"\"\n    module._sp_size = None\n    module._sp_rank = None\n    module._sp_group = None\n\n    @property\n    def sp_size(self):\n        if self._sp_size is None:\n            self._sp_size = 1\n            if is_deepspeed_ulysses_enabled():\n                self._sp_size = deepspeed_groups._get_sequence_parallel_group().size()\n        return self._sp_size\n\n    @property\n    def sp_rank(self):\n        if self._sp_rank is None:\n            self._sp_rank = 0\n            if is_deepspeed_ulysses_enabled():\n                self._sp_rank = deepspeed_groups._get_sequence_parallel_rank()\n        return self._sp_rank\n\n    @property\n    def sp_group(self):\n        if self._sp_group is None and is_deepspeed_ulysses_enabled():\n            self._sp_group = deepspeed_groups._get_sequence_parallel_group()\n        return self._sp_group\n\n    module.sp_size = sp_size\n    module.sp_rank = sp_rank\n    module.sp_group = sp_group\n\n    return module\n\n\ndef deepspeed_ulysses_attention(seq_dim=1, head_dim=2):\n    \"\"\"Perform all-to-all before and after the attention function.\"\"\"\n\n    def attention_decorator(attn_func=None):\n        def wrapped(*args, **kwargs):\n            if is_deepspeed_ulysses_enabled():\n                sp_group = deepspeed_groups._get_sequence_parallel_group()\n                scatter_idx = head_dim  # Scatter on num_heads dimension\n                gather_idx = seq_dim  # Gather on seq_len dimension\n                batch_dim_idx = 0\n                args = list(args)\n                args[0] = _SeqAllToAll.apply(sp_group, args[0], scatter_idx, gather_idx, batch_dim_idx)\n                args[1] = _SeqAllToAll.apply(sp_group, args[1], scatter_idx, gather_idx, batch_dim_idx)\n                args[2] = _SeqAllToAll.apply(sp_group, args[2], scatter_idx, gather_idx, batch_dim_idx)\n                args = tuple(args)\n\n            attn_output = attn_func(*args, **kwargs)\n\n            if is_deepspeed_ulysses_enabled():\n                scatter_idx = seq_dim  # Scatter back on seq_len dimension\n                gather_idx = head_dim  # Gather on num_heads dimension\n                batch_dim_idx = 0\n                attn_output = _SeqAllToAll.apply(sp_group, attn_output, scatter_idx, gather_idx, batch_dim_idx)\n\n            return attn_output\n\n        return wrapped\n\n    return attention_decorator\n\n\ndef deepspeed_ulysses_rope(state_seq_dim=2, trig_seq_dim=1):\n    \"\"\"Slice the corresponding cos and sin chunks for rope.\"\"\"\n\n    def rope_decorator(rope_func=None):\n        def wrapped(*args, **kwargs):\n            if is_deepspeed_ulysses_enabled():\n                sp_rank = deepspeed_groups._get_sequence_parallel_rank()\n                args = list(args)\n                seq_chunk_size = args[0].size(state_seq_dim)\n                args[2] = torch.narrow(args[2], trig_seq_dim, sp_rank * seq_chunk_size, seq_chunk_size)\n                args[3] = torch.narrow(args[3], trig_seq_dim, sp_rank * seq_chunk_size, seq_chunk_size)\n                args = tuple(args)\n\n            return rope_func(*args, **kwargs)\n\n        return wrapped\n\n    return rope_decorator\n\n\ndef _gather_tensors(input_, group=None):\n    \"\"\"Gather tensors and concatenate them along a dimension.\"\"\"\n    input_ = input_.contiguous()\n    world_size = torch.distributed.get_world_size(group)\n    if world_size == 1:\n        return input_\n    tensor_shapes = [\n        torch.empty(len(input_.size()), dtype=torch.int64, device=input_.device) for _ in range(world_size)\n    ]\n    input_size = torch.tensor(input_.size(), dtype=torch.int64, device=input_.device)\n    torch.distributed.all_gather(tensor_shapes, input_size, group=group)\n    gathered_buffers = [\n        torch.empty(tensor_shapes[i].tolist(), dtype=input_.dtype, device=input_.device) for i in range(world_size)\n    ]\n    torch.distributed.all_gather(gathered_buffers, input_, group=group)\n    return gathered_buffers\n\n\ndef _scatter_tensors(input_, group=None):\n    \"\"\"Scatter tensors.\"\"\"\n    world_size = torch.distributed.get_world_size(group)\n    if world_size == 1:\n        return input_\n    rank = torch.distributed.get_rank(group)\n    return input_[rank]\n\n\nclass _GatherTensors(torch.autograd.Function):\n    \"\"\"All gather tensors among the ranks.\"\"\"\n\n    @staticmethod\n    def symbolic(graph, input_, group):\n        return _gather_tensors(input_, group)\n\n    @staticmethod\n    def forward(ctx, input_, group):\n        ctx.group = group\n        return torch.nested.as_nested_tensor(_gather_tensors(input_, group), layout=torch.jagged)\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        return _scatter_tensors(grad_output, ctx.group), None\n\n\ndef all_gather_tensors(input_, size=None, dim=0, group=None):\n    if torch.distributed.get_world_size(group) == 1:\n        # no sequence parallelism\n        return input_\n    gathered_tensors = _GatherTensors.apply(input_, group)\n\n    if size:\n        split_gathered_tensors = []\n        for s, gathered_tensor in zip(size, gathered_tensors):\n            split_gathered_tensor = torch.split(gathered_tensor, s.tolist())\n            split_gathered_tensors.append(split_gathered_tensor)\n\n        gathered_tensors = [y for x in zip(*split_gathered_tensors) for y in x]\n\n    return torch.cat(gathered_tensors, dim).contiguous()\n\n\ndef get_sequence_data_parallel_world_size():\n    return torch.distributed.get_world_size()\n\n\ndef get_sequence_data_parallel_rank():\n    return torch.distributed.get_rank()\n\n\ndef get_sequence_data_parallel_group():\n    return torch.distributed.group.WORLD\n\n\nif is_deepspeed_available():\n    deepspeed_groups._get_sequence_data_parallel_world_size = get_sequence_data_parallel_world_size\n    deepspeed_groups._get_sequence_data_parallel_rank = get_sequence_data_parallel_rank\n    deepspeed_groups._get_sequence_data_parallel_group = get_sequence_data_parallel_group\n\n\ndef _gather_tokens(input_, dim=0, group=None):\n    \"\"\"Gather tensors and concatenate them along a dimension\"\"\"\n    input_ = input_.contiguous()\n    world_size = torch.distributed.get_world_size(group)\n    if world_size == 1:\n        return input_\n\n    gather_buffer = torch.empty(world_size * input_.numel(), dtype=input_.dtype, device=input_.device)\n    torch.distributed.all_gather_into_tensor(gather_buffer, input_, group=group)\n    if dim == 0:\n        shape = list(input_.size())\n        shape[0] = shape[0] * world_size\n        output = gather_buffer.view(shape)\n    else:\n        tensor_list = [\n            gather_buffer.narrow(0, input_.numel() * i, input_.numel()).view_as(input_) for i in range(world_size)\n        ]\n        # Note: torch.cat already creates a contiguous tensor.\n        output = torch.cat(tensor_list, dim=dim).contiguous()\n\n    return output\n\n\ndef _drop_tokens(input_, dim=0, group=None):\n    \"\"\"Divide a tensor among the sequence parallel ranks\"\"\"\n    world_size = torch.distributed.get_world_size(group)\n    if world_size == 1:\n        return input_\n    this_rank = torch.distributed.get_rank(group)\n    assert input_.shape[dim] % world_size == 0, (\n        f\"input dimension {dim} ({input_.shape[dim]}) is not divisible by sequence parallel world size ({world_size})\"\n    )\n    chunk_size = input_.shape[dim] // world_size\n\n    return torch.narrow(input_, dim, this_rank * chunk_size, chunk_size)\n\n\nclass _DropTokens(torch.autograd.Function):\n    \"Divide tokens equally among the sequence parallel ranks\"\n\n    @staticmethod\n    def symbolic(graph, input_, dim, group, grad_scale):\n        return _drop_tokens(input_, dim, group)\n\n    @staticmethod\n    def forward(ctx, input_, dim, group, grad_scale):\n        ctx.dim = dim\n        ctx.group = group\n        ctx.grad_scale = grad_scale\n        return _drop_tokens(input_, dim, group)\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        grad_input = _gather_tokens(grad_output, ctx.dim, ctx.group)\n        if ctx.grad_scale != 1:\n            grad_input /= ctx.grad_scale\n        return grad_input, None, None, None\n\n\nclass _GatherTokens(torch.autograd.Function):\n    \"Gather tokens among the sequence parallel ranks\"\n\n    @staticmethod\n    def symbolic(graph, input_, dim, group, grad_scale):\n        return _gather_tokens(input_, dim, group)\n\n    @staticmethod\n    def forward(ctx, input_, dim, group, grad_scale):\n        ctx.dim = dim\n        ctx.group = group\n        ctx.grad_scale = grad_scale\n        return _gather_tokens(input_, dim, group)\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        grad_input = _drop_tokens(grad_output, ctx.dim, ctx.group)\n        if ctx.grad_scale != 1:\n            grad_input *= ctx.grad_scale\n        return grad_input, None, None, None\n\n\ndef drop_tokens(input_, dim=0, group=None, grad_scale=1):\n    if torch.distributed.get_world_size(group) == 1:\n        # no sequence parallelism\n        return input_\n    return _DropTokens.apply(input_, dim, group, grad_scale)\n\n\ndef gather_tokens(input_, dim=0, group=None, grad_scale=1):\n    if torch.distributed.get_world_size(group) == 1:\n        # no sequence parallelism\n        return input_\n    return _GatherTokens.apply(input_, dim, group, grad_scale)\n\n\ndef sequence_chunking_per_rank(sp_size, sp_rank, *args, dim=1):\n    \"\"\"\n    Slice the inputs to create chuncks per the sequence parallel rank. This is used for the context parallel training.\n\n    Args:\n        sp_size (`int`):\n            Sequence parallel size.\n        sp_rank (`int`):\n            Sequence parallel rank for the current process.\n        dim (`int`):\n           The dimension to slice\n    \"\"\"\n    if sp_size == 1:\n        return args[0] if len(args) == 1 else args\n\n    seq_length = args[0].size(dim)\n    for arg in args[1:]:\n        assert arg.size(dim) == seq_length, (\n            f\"arg={arg} ({arg.shape[dim]}) does not have the same size as args[0] ({seq_length}) in dimension {dim}\"\n        )\n    assert seq_length % sp_size == 0, (\n        f\"dimension {dim} ({args[0].shape[dim]}) is not divisible by sequence parallel world size ({sp_size})\"\n    )\n\n    sub_seq_length = seq_length // sp_size\n    sub_seq_start = sp_rank * sub_seq_length\n\n    output = []\n    for ind in args:\n        ind = torch.narrow(ind, dim, sub_seq_start, sub_seq_length)\n        output.append(ind)\n\n    return tuple(output) if len(output) > 1 else output[0]\n\n\n@contextmanager\ndef disable_deepspeed_ulysses():\n    \"\"\"Disable deepspeed ulysses (sequence parallelism) if it is enabled\"\"\"\n    if is_deepspeed_ulysses_enabled():\n        _old_get_sequence_parallel_world_size = deepspeed_groups._get_sequence_parallel_world_size\n\n        def _get_sequence_parallel_world_size():\n            return 1\n\n        deepspeed_groups._get_sequence_parallel_world_size = _get_sequence_parallel_world_size\n        try:\n            yield\n        finally:\n            deepspeed_groups._get_sequence_parallel_world_size = _old_get_sequence_parallel_world_size\n    else:\n        context = contextlib.nullcontext\n        with context():\n            yield\n"
  },
  {
    "path": "boson_multimodal/serve/serve_engine.py",
    "content": "import asyncio\nimport base64\nimport torch\nimport numpy as np\nfrom io import BytesIO\nfrom dataclasses import dataclass\nfrom typing import List, Optional, Union\nfrom copy import deepcopy\nfrom transformers import AutoTokenizer, AutoProcessor\nfrom transformers.cache_utils import StaticCache\nfrom transformers.generation.streamers import BaseStreamer\nfrom transformers.generation.stopping_criteria import StoppingCriteria\nfrom dataclasses import asdict\nfrom loguru import logger\nimport threading\nimport librosa\n\n\nfrom ..dataset.chatml_dataset import ChatMLSample, ChatMLDatasetSample, prepare_chatml_sample\nfrom ..model.higgs_audio import HiggsAudioModel\nfrom ..model.higgs_audio.utils import revert_delay_pattern\nfrom ..data_collator.higgs_audio_collator import HiggsAudioSampleCollator\nfrom ..audio_processing.higgs_audio_tokenizer import load_higgs_audio_tokenizer\n\n\n@dataclass\nclass HiggsAudioStreamerDelta:\n    \"\"\"Represents a chunk of generated content, either text or audio tokens.\"\"\"\n\n    text: Optional[str] = None\n    text_tokens: Optional[torch.Tensor] = None\n    audio_tokens: Optional[torch.Tensor] = None\n    finish_reason: Optional[str] = None\n\n\nclass AsyncHiggsAudioStreamer(BaseStreamer):\n    \"\"\"\n    Async streamer that handles both text and audio token generation from Higgs-Audio model.\n    Stores chunks in a queue to be consumed by downstream applications.\n\n    Parameters:\n        tokenizer (`AutoTokenizer`):\n            The tokenizer used to decode text tokens.\n        skip_prompt (`bool`, *optional*, defaults to `False`):\n            Whether to skip the prompt tokens in generation.\n        timeout (`float`, *optional*):\n            The timeout for the queue. If `None`, the queue will block indefinitely.\n        decode_kwargs (`dict`, *optional*):\n            Additional keyword arguments to pass to the tokenizer's `decode` method.\n\n    Examples:\n        ```python\n        >>> from transformers import AutoTokenizer\n        >>> from threading import Thread\n        >>> import asyncio\n\n        >>> tokenizer = AutoTokenizer.from_pretrained(\"path/to/higgs/tokenizer\")\n        >>> model = HiggsAudioModel.from_pretrained(\"path/to/higgs/model\")\n        >>> inputs = tokenizer([\"Generate some text and audio:\"], return_tensors=\"pt\")\n\n        >>> async def main():\n        ...     streamer = AsyncHiggsAudioStreamer(tokenizer)\n        ...     generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)\n        ...     thread = Thread(target=model.generate, kwargs=generation_kwargs)\n        ...     thread.start()\n        ...\n        ...     async for delta in streamer:\n        ...         if delta.text is not None:\n        ...             print(\"Text:\", delta.text)\n        ...         if delta.audio_tokens is not None:\n        ...             print(\"Audio tokens shape:\", delta.audio_tokens.shape)\n        >>> asyncio.run(main())\n        ```\n    \"\"\"\n\n    def __init__(\n        self,\n        tokenizer: \"AutoTokenizer\",\n        skip_prompt: bool = False,\n        timeout: Optional[float] = None,\n        audio_num_codebooks: int = 1,\n        **decode_kwargs,\n    ):\n        self.tokenizer = tokenizer\n        self.skip_prompt = skip_prompt\n        self.timeout = timeout\n        self.decode_kwargs = decode_kwargs\n        self.audio_num_codebooks = audio_num_codebooks\n        # Queue to store generated chunks\n        self.queue = asyncio.Queue()\n        self.stop_signal = None\n\n        # Get running event loop\n        self.loop = asyncio.get_running_loop()\n        self.has_asyncio_timeout = hasattr(asyncio, \"timeout\")\n\n        # State tracking\n        self.next_tokens_are_prompt = True\n\n    def put(self, value: torch.Tensor):\n        \"\"\"\n        Receives tokens and processes them as either text or audio tokens.\n        For text tokens, decodes and caches them until complete words are formed.\n        For audio tokens, directly queues them.\n        \"\"\"\n        if value.shape[0] > 1 and not self.next_tokens_are_prompt:\n            # This is likely audio tokens (shape: [audio_num_codebooks])\n            assert value.shape[0] == self.audio_num_codebooks, \"Number of codebooks mismatch\"\n            delta = HiggsAudioStreamerDelta(audio_tokens=value)\n            if self.loop.is_running():\n                self.loop.call_soon_threadsafe(self.queue.put_nowait, delta)\n            return\n\n        # Skip prompt tokens if configured\n        if self.skip_prompt and self.next_tokens_are_prompt:\n            self.next_tokens_are_prompt = False\n            return\n\n        # Process as text tokens\n        if len(value.shape) > 1:\n            value = value[0]\n\n        text = self.tokenizer.decode(value, **self.decode_kwargs)\n        delta = HiggsAudioStreamerDelta(text=text, text_tokens=value)\n        if self.loop.is_running():\n            self.loop.call_soon_threadsafe(self.queue.put_nowait, delta)\n\n    def end(self):\n        \"\"\"Flushes any remaining text tokens and signals the end of generation.\"\"\"\n        self.next_tokens_are_prompt = True\n        if self.loop.is_running():\n            self.loop.call_soon_threadsafe(self.queue.put_nowait, self.stop_signal)\n\n    def __aiter__(self):\n        return self\n\n    async def __anext__(self):\n        try:\n            if self.has_asyncio_timeout:\n                async with asyncio.timeout(self.timeout):\n                    value = await self.queue.get()\n            else:\n                value = await asyncio.wait_for(self.queue.get(), timeout=self.timeout)\n        except asyncio.TimeoutError:\n            raise TimeoutError()\n        else:\n            if value == self.stop_signal:\n                raise StopAsyncIteration()\n            else:\n                return value\n\n\nclass AsyncStoppingCriteria(StoppingCriteria):\n    \"\"\"\n    Stopping criteria that checks for stop signal from a threading event.\n\n    Args:\n        stop_signal (threading.Event): Event that will receive stop signals\n    \"\"\"\n\n    def __init__(self, stop_signal: threading.Event):\n        self.stop_signal = stop_signal\n\n    def __call__(self, input_ids, scores, **kwargs) -> bool:\n        if self.stop_signal.is_set():\n            logger.info(f\"Stop signal received. Can be caused by client disconnection.\")\n            return True\n        return False\n\n\n@dataclass\nclass HiggsAudioResponse:\n    audio: Optional[np.ndarray] = None\n    generated_audio_tokens: Optional[np.ndarray] = None\n    sampling_rate: Optional[int] = None\n    generated_text: str = \"\"\n    generated_text_tokens: Optional[np.ndarray] = None\n    usage: Optional[dict] = None\n\n\nclass HiggsAudioServeEngine:\n    def __init__(\n        self,\n        model_name_or_path: str,\n        audio_tokenizer_name_or_path: str,\n        tokenizer_name_or_path: Optional[str] = None,\n        device: str = \"cuda\",\n        torch_dtype: Union[torch.dtype, str] = \"auto\",\n        kv_cache_lengths: List[int] = [1024, 4096, 8192],  # Multiple KV cache sizes\n    ):\n        \"\"\"\n        Initialize the HiggsAudioServeEngine, a serving wrapper for the HiggsAudioModel.\n        The model, tokenizer, and audio tokenizer will be downloaded from the Hugging Face Hub if they are not local.\n\n        Args:\n            model_name_or_path (str):\n                The name or path of the model to load.\n            audio_tokenizer_name_or_path (str):\n                The name or path of the audio tokenizer to load.\n            tokenizer_name_or_path (str):\n                The name or path of the tokenizer to load.\n            device (str):\n                The device to use for the model.\n            kv_cache_lengths (List[int]):\n                The lengths of the KV caches to use for the model. Used for cuda graph capture when device is cuda.\n            torch_dtype (Union[torch.dtype, str]):\n                The dtype to use for the model.\n        \"\"\"\n        self.device = device\n        self.model_name_or_path = model_name_or_path\n        self.torch_dtype = torch_dtype\n\n        # Initialize model and tokenizer\n        self.model = HiggsAudioModel.from_pretrained(model_name_or_path, torch_dtype=torch_dtype).to(device)\n        logger.info(f\"Loaded model from {model_name_or_path}, dtype: {self.model.dtype}\")\n\n        if tokenizer_name_or_path is None:\n            tokenizer_name_or_path = model_name_or_path\n        logger.info(f\"Loading tokenizer from {tokenizer_name_or_path}\")\n        self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path)\n\n        logger.info(f\"Initializing Higgs Audio Tokenizer\")\n        self.audio_tokenizer = load_higgs_audio_tokenizer(audio_tokenizer_name_or_path, device=device)\n\n        self.audio_num_codebooks = self.model.config.audio_num_codebooks\n        self.audio_codebook_size = self.model.config.audio_codebook_size\n        self.audio_tokenizer_tps = self.audio_tokenizer.tps\n        self.samples_per_token = int(self.audio_tokenizer.sampling_rate // self.audio_tokenizer_tps)\n        self.hamming_window_len = 2 * self.audio_num_codebooks * self.samples_per_token\n        # Set the audio special tokens\n        self.model.set_audio_special_tokens(self.tokenizer)\n\n        # Prepare KV caches for different lengths\n        cache_config = deepcopy(self.model.config.text_config)\n        cache_config.num_hidden_layers = self.model.config.text_config.num_hidden_layers\n        if self.model.config.audio_dual_ffn_layers:\n            cache_config.num_hidden_layers += len(self.model.config.audio_dual_ffn_layers)\n        # A list of KV caches for different lengths\n        self.kv_caches = {\n            length: StaticCache(\n                config=cache_config,\n                max_batch_size=1,\n                max_cache_len=length,\n                device=self.model.device,\n                dtype=self.model.dtype,\n            )\n            for length in sorted(kv_cache_lengths)\n        }\n\n        if self.model.config.encode_whisper_embed:\n            logger.info(f\"Loading whisper processor\")\n            whisper_processor = AutoProcessor.from_pretrained(\n                \"openai/whisper-large-v3-turbo\",\n                trust_remote=True,\n                device=self.device,\n            )\n        else:\n            whisper_processor = None\n\n        # Reuse collator to prepare inference samples\n        self.collator = HiggsAudioSampleCollator(\n            whisper_processor=whisper_processor,\n            encode_whisper_embed=self.model.config.encode_whisper_embed,\n            audio_in_token_id=self.model.config.audio_in_token_idx,\n            audio_out_token_id=self.model.config.audio_out_token_idx,\n            audio_stream_bos_id=self.model.config.audio_stream_bos_id,\n            audio_stream_eos_id=self.model.config.audio_stream_eos_id,\n            pad_token_id=self.model.config.pad_token_id,\n            return_audio_in_tokens=False,\n            use_delay_pattern=self.model.config.use_delay_pattern,\n            audio_num_codebooks=self.model.config.audio_num_codebooks,\n            round_to=1,\n        )\n\n        # Capture CUDA graphs for each KV cache length\n        if device == \"cuda\":\n            logger.info(f\"Capturing CUDA graphs for each KV cache length\")\n            self.model.capture_model(self.kv_caches.values())\n\n    def _prepare_inputs(self, chat_ml_sample: ChatMLSample, force_audio_gen: bool = False):\n        input_tokens, _, audio_contents, _ = prepare_chatml_sample(\n            chat_ml_sample,\n            self.tokenizer,\n        )\n\n        postfix = \"<|start_header_id|>assistant<|end_header_id|>\\n\\n\"\n        if force_audio_gen:\n            postfix += \"<|audio_out_bos|>\"\n        postfix = self.tokenizer.encode(postfix, add_special_tokens=False)\n        input_tokens.extend(postfix)\n\n        # Configure the audio inputs\n        audio_ids_l = []\n        for audio_content in audio_contents:\n            if audio_content.audio_url not in [\"placeholder\", \"\"]:\n                raw_audio, _ = librosa.load(audio_content.audio_url, sr=self.audio_tokenizer.sampling_rate)\n            elif audio_content.raw_audio is not None:\n                raw_audio, _ = librosa.load(\n                    BytesIO(base64.b64decode(audio_content.raw_audio)), sr=self.audio_tokenizer.sampling_rate\n                )\n            else:\n                raw_audio = None\n\n            if raw_audio is not None:\n                audio_ids = self.audio_tokenizer.encode(raw_audio, self.audio_tokenizer.sampling_rate)\n                audio_ids_l.append(audio_ids.squeeze(0).cpu())\n\n        if len(audio_ids_l) > 0:\n            audio_ids_start = torch.tensor(\n                np.cumsum(np.array([0] + [audio_ids.shape[1] for audio_ids in audio_ids_l])),\n                dtype=torch.long,\n                device=self.device,\n            )[0:-1]\n            audio_ids_concat = torch.cat(audio_ids_l, dim=1)\n        else:\n            audio_ids_start = None\n            audio_ids_concat = None\n\n        sample = ChatMLDatasetSample(\n            input_ids=torch.LongTensor(input_tokens),\n            label_ids=None,\n            audio_ids_concat=audio_ids_concat,\n            audio_ids_start=audio_ids_start,\n            audio_waveforms_concat=None,\n            audio_waveforms_start=None,\n            audio_sample_rate=None,\n            audio_speaker_indices=None,\n        )\n        data = self.collator([sample])\n        inputs = asdict(data)\n        for k, v in inputs.items():\n            if isinstance(v, torch.Tensor):\n                inputs[k] = v.to(self.model.device)\n\n        return inputs\n\n    def _prepare_kv_caches(self):\n        for kv_cache in self.kv_caches.values():\n            kv_cache.reset()\n\n    def generate(\n        self,\n        chat_ml_sample: ChatMLSample,\n        max_new_tokens: int,\n        temperature: float = 0.7,\n        top_k: Optional[int] = None,\n        top_p: float = 0.95,\n        stop_strings: Optional[List[str]] = None,\n        force_audio_gen: bool = False,\n        ras_win_len: Optional[int] = 7,\n        ras_win_max_num_repeat: int = 2,\n        seed: Optional[int] = None,\n    ):\n        \"\"\"\n        Generate audio from a chatml sample.\n        Args:\n            chat_ml_sample: A chatml sample.\n            max_new_tokens: The maximum number of new tokens to generate.\n            temperature: The temperature to use for the generation.\n            top_p: The top p to use for the generation.\n            stop_strings: A list of strings to stop the generation.\n            force_audio_gen: Whether to force audio generation. This ensures the model generates audio tokens rather than text tokens.\n            ras_win_len: The length of the RAS window. We use 7 by default. You can disable it by setting it to None or <=0.\n            ras_win_max_num_repeat: The maximum number of times to repeat the RAS window.\n        Returns:\n            A dictionary with the following keys:\n                audio: The generated audio.\n                sampling_rate: The sampling rate of the generated audio.\n        \"\"\"\n        # Default stop strings\n        if stop_strings is None:\n            stop_strings = [\"<|end_of_text|>\", \"<|eot_id|>\"]\n        if ras_win_len is not None and ras_win_len <= 0:\n            ras_win_len = None\n\n        with torch.no_grad():\n            inputs = self._prepare_inputs(chat_ml_sample, force_audio_gen=force_audio_gen)\n            prompt_token_ids = inputs[\"input_ids\"][0].cpu().numpy()\n\n            self._prepare_kv_caches()\n\n            outputs = self.model.generate(\n                **inputs,\n                max_new_tokens=max_new_tokens,\n                use_cache=True,\n                stop_strings=stop_strings,\n                tokenizer=self.tokenizer,\n                do_sample=False if temperature == 0.0 else True,\n                temperature=temperature,\n                top_k=top_k,\n                top_p=top_p,\n                past_key_values_buckets=self.kv_caches,\n                ras_win_len=ras_win_len,\n                ras_win_max_num_repeat=ras_win_max_num_repeat,\n                seed=seed,\n            )\n\n            if len(outputs[1]) > 0:\n                wv_list = []\n                for output_audio in outputs[1]:\n                    vq_code = revert_delay_pattern(output_audio).clip(0, self.audio_codebook_size - 1)[:, 1:-1]\n                    wv_numpy = self.audio_tokenizer.decode(vq_code.unsqueeze(0))[0, 0]\n                    wv_list.append(wv_numpy)\n                wv_numpy = np.concatenate(wv_list)\n            else:\n                wv_numpy = None\n\n            # We only support one request at a time now\n            generated_text_tokens = outputs[0][0].cpu().numpy()[len(prompt_token_ids) :]\n            generated_text = self.tokenizer.decode(generated_text_tokens)\n            generated_audio_tokens = outputs[1][0].cpu().numpy()\n            return HiggsAudioResponse(\n                audio=wv_numpy,\n                generated_audio_tokens=generated_audio_tokens,\n                sampling_rate=self.audio_tokenizer.sampling_rate,\n                generated_text=generated_text,\n                generated_text_tokens=generated_text_tokens,\n                usage={\n                    \"prompt_tokens\": prompt_token_ids.shape[0],\n                    \"completion_tokens\": generated_text_tokens.shape[0] + generated_audio_tokens.shape[1],\n                    \"total_tokens\": (\n                        prompt_token_ids.shape[0] + generated_text_tokens.shape[0] + generated_audio_tokens.shape[1]\n                    ),\n                    \"cached_tokens\": 0,\n                },\n            )\n\n    async def generate_delta_stream(\n        self,\n        chat_ml_sample: ChatMLSample,\n        max_new_tokens: int,\n        temperature: float = 0.7,\n        top_k: Optional[int] = None,\n        top_p: float = 0.95,\n        stop_strings: Optional[List[str]] = None,\n        force_audio_gen: bool = False,\n        ras_win_len: Optional[int] = 7,\n        ras_win_max_num_repeat: int = 2,\n        seed: Optional[int] = None,\n    ):\n        \"\"\"\n        Generate audio from a chatml sample.\n        Args:\n            chat_ml_sample: A chatml sample.\n            max_new_tokens: The maximum number of new tokens to generate.\n            temperature: The temperature to use for the generation.\n            top_p: The top p to use for the generation.\n            stop_strings: A list of strings to stop the generation.\n            force_audio_gen: Whether to force audio generation. This ensures the model generates audio tokens rather than text tokens.\n            ras_win_len: The length of the RAS window. We use 7 by default. You can disable it by setting it to None or <=0.\n            ras_win_max_num_repeat: The maximum number of times to repeat the RAS window.\n        Returns:\n             Delta AsyncGenerator\n        \"\"\"\n        # Default stop strings\n        if stop_strings is None:\n            stop_strings = [\"<|end_of_text|>\", \"<|eot_id|>\"]\n        if ras_win_len is not None and ras_win_len <= 0:\n            ras_win_len = None\n\n        with torch.no_grad():\n            inputs = self._prepare_inputs(chat_ml_sample, force_audio_gen=force_audio_gen)\n\n            self._prepare_kv_caches()\n\n            streamer = AsyncHiggsAudioStreamer(\n                self.tokenizer,\n                audio_num_codebooks=self.model.config.audio_num_codebooks,\n                skip_prompt=True,\n            )\n            generation_kwargs = dict(\n                **inputs,\n                max_new_tokens=max_new_tokens,\n                use_cache=True,\n                stop_strings=stop_strings,\n                tokenizer=self.tokenizer,\n                do_sample=False if temperature == 0.0 else True,\n                temperature=temperature,\n                top_k=top_k,\n                top_p=top_p,\n                past_key_values_buckets=self.kv_caches,\n                ras_win_len=ras_win_len,\n                ras_win_max_num_repeat=ras_win_max_num_repeat,\n                seed=seed,\n                streamer=streamer,\n            )\n            thread = threading.Thread(target=self.model.generate, kwargs=generation_kwargs)\n            thread.start()\n\n            async for delta in streamer:\n                yield delta\n"
  },
  {
    "path": "boson_multimodal/serve/utils.py",
    "content": "import uuid\nimport base64\nimport re\nimport regex\nfrom typing import AsyncGenerator, Union\nimport io\nfrom pydub import AudioSegment\nimport torch\nimport numpy as np\nfrom functools import lru_cache\n\nfrom ..audio_processing.higgs_audio_tokenizer import HiggsAudioTokenizer\n\n\ndef random_uuid() -> str:\n    return str(uuid.uuid4().hex)\n\n\nasync def async_generator_wrap(first_element, gen: AsyncGenerator):\n    \"\"\"Wrap an async generator with the first element.\"\"\"\n    yield first_element\n    async for item in gen:\n        yield item\n\n\n@lru_cache(maxsize=50)\ndef encode_base64_content_from_file(file_path: str) -> str:\n    \"\"\"Encode a content from a local file to base64 format.\"\"\"\n    # Read the MP3 file as binary and encode it directly to Base64\n    with open(file_path, \"rb\") as audio_file:\n        audio_base64 = base64.b64encode(audio_file.read()).decode(\"utf-8\")\n    return audio_base64\n\n\ndef pcm16_to_target_format(\n    np_audio: np.ndarray,\n    sample_rate: int,\n    bit_depth: int,\n    channels: int,\n    format: str,\n    target_rate: int,\n):\n    wav_audio = AudioSegment(\n        np_audio.tobytes(),\n        frame_rate=sample_rate,\n        sample_width=bit_depth // 8,\n        channels=channels,\n    )\n    if target_rate is not None and target_rate != sample_rate:\n        wav_audio = wav_audio.set_frame_rate(target_rate)\n\n    # Convert WAV to MP3\n    target_io = io.BytesIO()\n    wav_audio.export(target_io, format=format)\n    target_io.seek(0)\n\n    return target_io\n\n\nchinese_char_pattern = re.compile(r\"[\\u4e00-\\u9fff]+\")\n\n\ndef contains_chinese(text: str):\n    return bool(chinese_char_pattern.search(text))\n\n\n# remove blank between chinese character\ndef replace_blank(text: str):\n    out_str = []\n    for i, c in enumerate(text):\n        if c == \" \":\n            if (text[i + 1].isascii() and text[i + 1] != \" \") and (text[i - 1].isascii() and text[i - 1] != \" \"):\n                out_str.append(c)\n        else:\n            out_str.append(c)\n    return \"\".join(out_str)\n\n\ndef replace_corner_mark(text: str):\n    text = text.replace(\"²\", \"平方\")\n    text = text.replace(\"³\", \"立方\")\n    return text\n\n\n# remove meaningless symbol\ndef remove_bracket(text: str):\n    text = text.replace(\"（\", \"\").replace(\"）\", \"\")\n    text = text.replace(\"【\", \"\").replace(\"】\", \"\")\n    text = text.replace(\"`\", \"\").replace(\"`\", \"\")\n    text = text.replace(\"——\", \" \")\n    return text\n\n\n# split paragrah logic：\n# 1. per sentence max len token_max_n, min len token_min_n, merge if last sentence len less than merge_len\n# 2. cal sentence len according to lang\n# 3. split sentence according to puncatation\ndef split_paragraph(text: str, tokenize, lang=\"zh\", token_max_n=80, token_min_n=60, merge_len=20, comma_split=False):\n    def calc_utt_length(_text: str):\n        if lang == \"zh\":\n            return len(_text)\n        else:\n            return len(tokenize(_text))\n\n    def should_merge(_text: str):\n        if lang == \"zh\":\n            return len(_text) < merge_len\n        else:\n            return len(tokenize(_text)) < merge_len\n\n    if lang == \"zh\":\n        pounc = [\"。\", \"？\", \"！\", \"；\", \"：\", \"、\", \".\", \"?\", \"!\", \";\"]\n    else:\n        pounc = [\".\", \"?\", \"!\", \";\", \":\"]\n    if comma_split:\n        pounc.extend([\"，\", \",\"])\n\n    if text[-1] not in pounc:\n        if lang == \"zh\":\n            text += \"。\"\n        else:\n            text += \".\"\n\n    st = 0\n    utts = []\n    for i, c in enumerate(text):\n        if c in pounc:\n            if len(text[st:i]) > 0:\n                utts.append(text[st:i] + c)\n            if i + 1 < len(text) and text[i + 1] in ['\"', \"”\"]:\n                tmp = utts.pop(-1)\n                utts.append(tmp + text[i + 1])\n                st = i + 2\n            else:\n                st = i + 1\n\n    final_utts = []\n    cur_utt = \"\"\n    for utt in utts:\n        if calc_utt_length(cur_utt + utt) > token_max_n and calc_utt_length(cur_utt) > token_min_n:\n            final_utts.append(cur_utt)\n            cur_utt = \"\"\n        cur_utt = cur_utt + utt\n    if len(cur_utt) > 0:\n        if should_merge(cur_utt) and len(final_utts) != 0:\n            final_utts[-1] = final_utts[-1] + cur_utt\n        else:\n            final_utts.append(cur_utt)\n\n    return final_utts\n\n\ndef is_only_punctuation(text: str):\n    # Regular expression: Match strings that consist only of punctuation marks or are empty.\n    punctuation_pattern = r\"^[\\p{P}\\p{S}]*$\"\n    return bool(regex.fullmatch(punctuation_pattern, text))\n\n\n# spell Arabic numerals\ndef spell_out_number(text: str, inflect_parser):\n    new_text = []\n    st = None\n    for i, c in enumerate(text):\n        if not c.isdigit():\n            if st is not None:\n                num_str = inflect_parser.number_to_words(text[st:i])\n                new_text.append(num_str)\n                st = None\n            new_text.append(c)\n        else:\n            if st is None:\n                st = i\n    if st is not None and st < len(text):\n        num_str = inflect_parser.number_to_words(text[st:])\n        new_text.append(num_str)\n    return \"\".join(new_text)\n\n\ndef remove_emoji(text: str):\n    # Pattern to match emojis and their modifiers\n    # - Standard emoji range\n    # - Zero-width joiners (U+200D)\n    # - Variation selectors (U+FE0F, U+FE0E)\n    # - Skin tone modifiers (U+1F3FB to U+1F3FF)\n    emoji_pattern = re.compile(\n        r\"[\"\n        r\"\\U00010000-\\U0010FFFF\"  # Standard emoji range\n        r\"\\u200D\"  # Zero-width joiner\n        r\"\\uFE0F\\uFE0E\"  # Variation selectors\n        r\"\\U0001F3FB-\\U0001F3FF\"  # Skin tone modifiers\n        r\"]+\",\n        flags=re.UNICODE,\n    )\n    return emoji_pattern.sub(r\"\", text)\n\n\ndef remove_repeated_punctuations(text, punctuations):\n    if len(punctuations) == 0:\n        return text\n    pattern = f\"[{re.escape(''.join(punctuations))}]\"  # Create regex pattern for given punctuations\n    return re.sub(rf\"({pattern})\\1+\", r\"\\1\", text)\n\n\ndef full_to_half_width(text: str) -> str:\n    \"\"\"Convert full-width punctuation to half-width in a given string.\"\"\"\n    full_width = \"！＂＃＄％＆＇（）＊＋，－．／：；＜＝＞？＠［＼］＾＿｀｛｜｝～\"\n    half_width = \"!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~\"\n    trans_table = str.maketrans(full_width, half_width)\n    return text.translate(trans_table)\n\n\ndef split_interleaved_delayed_audios(\n    audio_data: Union[list[list[int]], torch.Tensor],\n    audio_tokenizer: HiggsAudioTokenizer,\n    audio_stream_eos_id: int,\n) -> list[tuple[list[list[int]], torch.Tensor]]:\n    separator = [audio_stream_eos_id] * audio_tokenizer.num_codebooks\n\n    # Convert separator to numpy array if audio_data is numpy array\n    if isinstance(audio_data, torch.Tensor):\n        audio_data = audio_data.transpose(1, 0)\n        separator = torch.tensor(separator)\n        # Find the indices where the rows equal the separator\n        split_indices = torch.where(torch.all(audio_data == separator, dim=1))[0]\n        start = 0\n        groups = []\n        for idx in split_indices:\n            groups.append(audio_data[start:idx].transpose(1, 0))\n            start = idx + 1\n        if start < len(audio_data):\n            groups.append(audio_data[start:].transpose(1, 0))\n    else:\n        groups = []\n        current = []\n        for row in audio_data:\n            current.append(row)\n\n            if row == separator:\n                groups.append(current)\n                current = []\n\n        # Don't forget the last group if there's no trailing separator\n        if current:\n            groups.append(current)\n\n    return groups\n"
  },
  {
    "path": "examples/README.md",
    "content": "# Examples\n\n> [!NOTE]  \n> If you do not like the audio you get, you can generate multiple times with different seeds. In addition, you may need to apply text normalization to get the best performance, e.g. converting 70 °F to \"seventy degrees Fahrenheit\", and converting \"1 2 3 4\" to \"one two three four\". The model also performs better in longer sentences. Right now, the model has not been post-trained, we will release the post-trained model in the future.\n\n## Single-speaker Audio Generation\n\n### Voice clone\n\n```bash\npython3 generation.py \\\n--transcript transcript/single_speaker/en_dl.txt \\\n--ref_audio broom_salesman \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\nThe model will read the transcript with the same voice as in the [reference audio](./voice_prompts/broom_salesman.wav). The technique is also called shallow voice clone.\n\nWe have some example audio prompts stored in [voice_prompts](./voice_prompts/). Feel free to pick one in the folder and try out the model. Here's another example that uses the voice of `belinda`. You can also add new own favorite voice in the folder and clone the voice.\n\n```bash\npython3 generation.py \\\n--transcript transcript/single_speaker/en_dl.txt \\\n--ref_audio belinda \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n#### (Experimental) Cross-lingual voice clone\n\nThis example demonstrates voice cloning with a Chinese prompt, where the synthesized speech is in English.\n\n```bash\npython3 generation.py \\\n--transcript transcript/single_speaker/en_dl.txt \\\n--scene_prompt empty \\\n--ref_audio zh_man_sichuan \\\n--temperature 0.3 \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n### Smart voice\n\nThe model supports reading the transcript with a random voice.\n\n```bash\npython3 generation.py \\\n--transcript transcript/single_speaker/en_dl.txt \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\nIt also works for other languages like Chinese.\n\n```bash\npython3 generation.py \\\n--transcript transcript/single_speaker/zh_ai.txt \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n### Describe speaker characteristics with text\n\nThe model allows you to describe the speaker via text. See [voice_prompts/profile.yaml](voice_prompts/profile.yaml) for examples. You can run the following two examples that try to specify male / female British accent for the speakers. Also, try to remove the `--seed 12345` flag to see how the model is generating different voices.\n\n```bash\n# Male British Accent\npython3 generation.py \\\n--transcript transcript/single_speaker/en_dl.txt \\\n--ref_audio profile:male_en_british \\\n--seed 12345 \\\n--out_path generation.wav\n\n# Female British Accent\npython3 generation.py \\\n--transcript transcript/single_speaker/en_dl.txt \\\n--ref_audio profile:female_en_british \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n### Chunking for long-form audio generation\n\nTo generate long-form audios, you can chunk the text and render each chunk one by one while putting the previous generated audio and the reference audio in the prompt. Here's an example that generates the first five paragraphs of Higgs Audio v1 release blog. See [text](./transcript/single_speaker/en_higgs_audio_blog.md).\n\n```bash\npython3 generation.py \\\n--scene_prompt scene_prompts/reading_blog.txt \\\n--transcript transcript/single_speaker/en_higgs_audio_blog.md \\\n--ref_audio en_man \\\n--chunk_method word \\\n--temperature 0.3 \\\n--generation_chunk_buffer_size 2 \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n### Experimental and Emergent Capabilities\n\nAs shown in our demo, the pretrained model is demonstrating emergent features. We prepared some samples to help you explore these experimental prompts. We will enhance the stability of these experimental prompts in the future version of HiggsAudio.\n\n#### (Experimental) Hum a tune with the cloned voice\nThe model is able to hum a tune with the cloned voice.\n\n```bash\npython3 generation.py \\\n--transcript transcript/single_speaker/experimental/en_humming.txt \\\n--ref_audio en_woman \\\n--ras_win_len 0 \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n#### (Experimental) Read the sentence while adding background music (BGM)\n\n```bash\npython3 generation.py \\\n--transcript transcript/single_speaker/experimental/en_bgm.txt \\\n--ref_audio en_woman \\\n--ras_win_len 0 \\\n--ref_audio_in_system_message \\\n--seed 123456 \\\n--out_path generation.wav\n```\n\n## Multi-speaker Audio Generation\n\n\n### Smart voice\n\nTo get started to explore HiggsAudio's capability in generating multi-speaker audios. Let's try to generate a multi-speaker dialog from transcript in the zero-shot fashion. See the transcript in [transcript/multi_speaker/en_argument.txt](transcript/multi_speaker/en_argument.txt). The speakers are annotated with `[SPEAKER0]` and `[SPEAKER1]`.\n\n```bash\npython3 generation.py \\\n--transcript transcript/multi_speaker/en_argument.txt \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\n### Multi-voice clone\nYou can also try to clone the voices from multiple people simultaneously and generate audio about the transcript. Here's an example that puts reference audios in the system message and prompt the model iteratively. You can hear \"Belinda\" arguing with \"Broom Salesman\".\n\n```bash\npython3 generation.py \\\n--transcript transcript/multi_speaker/en_argument.txt \\\n--ref_audio belinda,broom_salesman \\\n--ref_audio_in_system_message \\\n--chunk_method speaker \\\n--seed 12345 \\\n--out_path generation.wav\n```\n\nYou can also let \"Broom Salesman\" talking to \"Belinda\", who recently trained HiggsAudio.\n\n```bash\npython3 generation.py \\\n--transcript transcript/multi_speaker/en_higgs.txt \\\n--ref_audio broom_salesman,belinda \\\n--ref_audio_in_system_message \\\n--chunk_method speaker \\\n--chunk_max_num_turns 2 \\\n--seed 12345 \\\n--out_path generation.wav\n```\n"
  },
  {
    "path": "examples/generation.py",
    "content": "\"\"\"Example script for generating audio using HiggsAudio.\"\"\"\n\nimport click\nimport soundfile as sf\nimport langid\nimport jieba\nimport os\nimport re\nimport copy\nimport torchaudio\nimport tqdm\nimport yaml\n\nfrom loguru import logger\nfrom boson_multimodal.serve.serve_engine import HiggsAudioServeEngine, HiggsAudioResponse\nfrom boson_multimodal.data_types import Message, ChatMLSample, AudioContent, TextContent\n\nfrom boson_multimodal.model.higgs_audio import HiggsAudioConfig, HiggsAudioModel\nfrom boson_multimodal.data_collator.higgs_audio_collator import HiggsAudioSampleCollator\nfrom boson_multimodal.audio_processing.higgs_audio_tokenizer import load_higgs_audio_tokenizer\nfrom boson_multimodal.dataset.chatml_dataset import (\n    ChatMLDatasetSample,\n    prepare_chatml_sample,\n)\nfrom boson_multimodal.model.higgs_audio.utils import revert_delay_pattern\nfrom typing import List\nfrom transformers import AutoConfig, AutoTokenizer\nfrom transformers.cache_utils import StaticCache\nfrom typing import Optional\nfrom dataclasses import asdict\nimport torch\n\nCURR_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\nAUDIO_PLACEHOLDER_TOKEN = \"<|__AUDIO_PLACEHOLDER__|>\"\n\n\nMULTISPEAKER_DEFAULT_SYSTEM_MESSAGE = \"\"\"You are an AI assistant designed to convert text into speech.\nIf the user's message includes a [SPEAKER*] tag, do not read out the tag and generate speech for the following text, using the specified voice.\nIf no speaker tag is present, select a suitable voice on your own.\"\"\"\n\n\ndef normalize_chinese_punctuation(text):\n    \"\"\"\n    Convert Chinese (full-width) punctuation marks to English (half-width) equivalents.\n    \"\"\"\n    # Mapping of Chinese punctuation to English punctuation\n    chinese_to_english_punct = {\n        \"，\": \", \",  # comma\n        \"。\": \".\",  # period\n        \"：\": \":\",  # colon\n        \"；\": \";\",  # semicolon\n        \"？\": \"?\",  # question mark\n        \"！\": \"!\",  # exclamation mark\n        \"（\": \"(\",  # left parenthesis\n        \"）\": \")\",  # right parenthesis\n        \"【\": \"[\",  # left square bracket\n        \"】\": \"]\",  # right square bracket\n        \"《\": \"<\",  # left angle quote\n        \"》\": \">\",  # right angle quote\n        \"“\": '\"',  # left double quotation\n        \"”\": '\"',  # right double quotation\n        \"‘\": \"'\",  # left single quotation\n        \"’\": \"'\",  # right single quotation\n        \"、\": \",\",  # enumeration comma\n        \"—\": \"-\",  # em dash\n        \"…\": \"...\",  # ellipsis\n        \"·\": \".\",  # middle dot\n        \"「\": '\"',  # left corner bracket\n        \"」\": '\"',  # right corner bracket\n        \"『\": '\"',  # left double corner bracket\n        \"』\": '\"',  # right double corner bracket\n    }\n\n    # Replace each Chinese punctuation with its English counterpart\n    for zh_punct, en_punct in chinese_to_english_punct.items():\n        text = text.replace(zh_punct, en_punct)\n\n    return text\n\n\ndef prepare_chunk_text(\n    text, chunk_method: Optional[str] = None, chunk_max_word_num: int = 100, chunk_max_num_turns: int = 1\n):\n    \"\"\"Chunk the text into smaller pieces. We will later feed the chunks one by one to the model.\n\n    Parameters\n    ----------\n    text : str\n        The text to be chunked.\n    chunk_method : str, optional\n        The method to use for chunking. Options are \"speaker\", \"word\", or None. By default, we won't use any chunking and\n        will feed the whole text to the model.\n    replace_speaker_tag_with_special_tags : bool, optional\n        Whether to replace speaker tags with special tokens, by default False\n        If the flag is set to True, we will replace [SPEAKER0] with <|speaker_id_start|>SPEAKER0<|speaker_id_end|>\n    chunk_max_word_num : int, optional\n        The maximum number of words for each chunk when \"word\" chunking method is used, by default 100\n    chunk_max_num_turns : int, optional\n        The maximum number of turns for each chunk when \"speaker\" chunking method is used,\n\n    Returns\n    -------\n    List[str]\n        The list of text chunks.\n\n    \"\"\"\n    if chunk_method is None:\n        return [text]\n    elif chunk_method == \"speaker\":\n        lines = text.split(\"\\n\")\n        speaker_chunks = []\n        speaker_utterance = \"\"\n        for line in lines:\n            line = line.strip()\n            if line.startswith(\"[SPEAKER\") or line.startswith(\"<|speaker_id_start|>\"):\n                if speaker_utterance:\n                    speaker_chunks.append(speaker_utterance.strip())\n                speaker_utterance = line\n            else:\n                if speaker_utterance:\n                    speaker_utterance += \"\\n\" + line\n                else:\n                    speaker_utterance = line\n        if speaker_utterance:\n            speaker_chunks.append(speaker_utterance.strip())\n        if chunk_max_num_turns > 1:\n            merged_chunks = []\n            for i in range(0, len(speaker_chunks), chunk_max_num_turns):\n                merged_chunk = \"\\n\".join(speaker_chunks[i : i + chunk_max_num_turns])\n                merged_chunks.append(merged_chunk)\n            return merged_chunks\n        return speaker_chunks\n    elif chunk_method == \"word\":\n        # TODO: We may improve the logic in the future\n        # For long-form generation, we will first divide the text into multiple paragraphs by splitting with \"\\n\\n\"\n        # After that, we will chunk each paragraph based on word count\n        language = langid.classify(text)[0]\n        paragraphs = text.split(\"\\n\\n\")\n        chunks = []\n        for idx, paragraph in enumerate(paragraphs):\n            if language == \"zh\":\n                # For Chinese, we will chunk based on character count\n                words = list(jieba.cut(paragraph, cut_all=False))\n                for i in range(0, len(words), chunk_max_word_num):\n                    chunk = \"\".join(words[i : i + chunk_max_word_num])\n                    chunks.append(chunk)\n            else:\n                words = paragraph.split(\" \")\n                for i in range(0, len(words), chunk_max_word_num):\n                    chunk = \" \".join(words[i : i + chunk_max_word_num])\n                    chunks.append(chunk)\n            chunks[-1] += \"\\n\\n\"\n        return chunks\n    else:\n        raise ValueError(f\"Unknown chunk method: {chunk_method}\")\n\n\ndef _build_system_message_with_audio_prompt(system_message):\n    contents = []\n\n    while AUDIO_PLACEHOLDER_TOKEN in system_message:\n        loc = system_message.find(AUDIO_PLACEHOLDER_TOKEN)\n        contents.append(TextContent(system_message[:loc]))\n        contents.append(AudioContent(audio_url=\"\"))\n        system_message = system_message[loc + len(AUDIO_PLACEHOLDER_TOKEN) :]\n\n    if len(system_message) > 0:\n        contents.append(TextContent(system_message))\n    ret = Message(\n        role=\"system\",\n        content=contents,\n    )\n    return ret\n\n\nclass HiggsAudioModelClient:\n    def __init__(\n        self,\n        model_path,\n        audio_tokenizer,\n        device=None,\n        device_id=None,\n        max_new_tokens=2048,\n        kv_cache_lengths: List[int] = [1024, 4096, 8192],  # Multiple KV cache sizes,\n        use_static_kv_cache=False,\n    ):\n        # Use explicit device if provided, otherwise try CUDA/MPS/CPU\n        if device_id is not None:\n            device = f\"cuda:{device_id}\"\n            self._device = device\n        else:\n            if device is not None:\n                self._device = device\n            else:  # We get to choose the device\n                # Prefer CUDA over MPS (Apple Silicon GPU) over CPU if available\n                if torch.cuda.is_available():\n                    self._device = \"cuda:0\"\n                elif torch.backends.mps.is_available():\n                    self._device = \"mps\"\n                else:\n                    self._device = \"cpu\"\n\n        logger.info(f\"Using device: {self._device}\")\n        if isinstance(audio_tokenizer, str):\n            # For MPS, use CPU due to embedding operation limitations in quantization layers\n            audio_tokenizer_device = \"cpu\" if self._device == \"mps\" else self._device\n            self._audio_tokenizer = load_higgs_audio_tokenizer(audio_tokenizer, device=audio_tokenizer_device)\n        else:\n            self._audio_tokenizer = audio_tokenizer\n\n        self._model = HiggsAudioModel.from_pretrained(\n            model_path,\n            device_map=self._device,\n            torch_dtype=torch.bfloat16,\n        )\n        self._model.eval()\n        self._kv_cache_lengths = kv_cache_lengths\n        self._use_static_kv_cache = use_static_kv_cache\n\n        self._tokenizer = AutoTokenizer.from_pretrained(model_path)\n        self._config = AutoConfig.from_pretrained(model_path)\n        self._max_new_tokens = max_new_tokens\n        self._collator = HiggsAudioSampleCollator(\n            whisper_processor=None,\n            audio_in_token_id=self._config.audio_in_token_idx,\n            audio_out_token_id=self._config.audio_out_token_idx,\n            audio_stream_bos_id=self._config.audio_stream_bos_id,\n            audio_stream_eos_id=self._config.audio_stream_eos_id,\n            encode_whisper_embed=self._config.encode_whisper_embed,\n            pad_token_id=self._config.pad_token_id,\n            return_audio_in_tokens=self._config.encode_audio_in_tokens,\n            use_delay_pattern=self._config.use_delay_pattern,\n            round_to=1,\n            audio_num_codebooks=self._config.audio_num_codebooks,\n        )\n        self.kv_caches = None\n        if use_static_kv_cache:\n            self._init_static_kv_cache()\n\n    def _init_static_kv_cache(self):\n        cache_config = copy.deepcopy(self._model.config.text_config)\n        cache_config.num_hidden_layers = self._model.config.text_config.num_hidden_layers\n        if self._model.config.audio_dual_ffn_layers:\n            cache_config.num_hidden_layers += len(self._model.config.audio_dual_ffn_layers)\n        # A list of KV caches for different lengths\n        self.kv_caches = {\n            length: StaticCache(\n                config=cache_config,\n                max_batch_size=1,\n                max_cache_len=length,\n                device=self._model.device,\n                dtype=self._model.dtype,\n            )\n            for length in sorted(self._kv_cache_lengths)\n        }\n        # Capture CUDA graphs for each KV cache length\n        if \"cuda\" in self._device:\n            logger.info(f\"Capturing CUDA graphs for each KV cache length\")\n            self._model.capture_model(self.kv_caches.values())\n\n    def _prepare_kv_caches(self):\n        for kv_cache in self.kv_caches.values():\n            kv_cache.reset()\n\n    @torch.inference_mode()\n    def generate(\n        self,\n        messages,\n        audio_ids,\n        chunked_text,\n        generation_chunk_buffer_size,\n        temperature=1.0,\n        top_k=50,\n        top_p=0.95,\n        ras_win_len=7,\n        ras_win_max_num_repeat=2,\n        seed=123,\n        *args,\n        **kwargs,\n    ):\n        if ras_win_len is not None and ras_win_len <= 0:\n            ras_win_len = None\n        sr = 24000\n        audio_out_ids_l = []\n        generated_audio_ids = []\n        generation_messages = []\n        for idx, chunk_text in tqdm.tqdm(\n            enumerate(chunked_text), desc=\"Generating audio chunks\", total=len(chunked_text)\n        ):\n            generation_messages.append(\n                Message(\n                    role=\"user\",\n                    content=chunk_text,\n                )\n            )\n            chatml_sample = ChatMLSample(messages=messages + generation_messages)\n            input_tokens, _, _, _ = prepare_chatml_sample(chatml_sample, self._tokenizer)\n            postfix = self._tokenizer.encode(\n                \"<|start_header_id|>assistant<|end_header_id|>\\n\\n\", add_special_tokens=False\n            )\n            input_tokens.extend(postfix)\n\n            logger.info(f\"========= Chunk {idx} Input =========\")\n            logger.info(self._tokenizer.decode(input_tokens))\n            context_audio_ids = audio_ids + generated_audio_ids\n\n            curr_sample = ChatMLDatasetSample(\n                input_ids=torch.LongTensor(input_tokens),\n                label_ids=None,\n                audio_ids_concat=torch.concat([ele.cpu() for ele in context_audio_ids], dim=1)\n                if context_audio_ids\n                else None,\n                audio_ids_start=torch.cumsum(\n                    torch.tensor([0] + [ele.shape[1] for ele in context_audio_ids], dtype=torch.long), dim=0\n                )\n                if context_audio_ids\n                else None,\n                audio_waveforms_concat=None,\n                audio_waveforms_start=None,\n                audio_sample_rate=None,\n                audio_speaker_indices=None,\n            )\n\n            batch_data = self._collator([curr_sample])\n            batch = asdict(batch_data)\n            for k, v in batch.items():\n                if isinstance(v, torch.Tensor):\n                    batch[k] = v.contiguous().to(self._device)\n\n            if self._use_static_kv_cache:\n                self._prepare_kv_caches()\n\n            # Generate audio\n            outputs = self._model.generate(\n                **batch,\n                max_new_tokens=self._max_new_tokens,\n                use_cache=True,\n                do_sample=True,\n                temperature=temperature,\n                top_k=top_k,\n                top_p=top_p,\n                past_key_values_buckets=self.kv_caches,\n                ras_win_len=ras_win_len,\n                ras_win_max_num_repeat=ras_win_max_num_repeat,\n                stop_strings=[\"<|end_of_text|>\", \"<|eot_id|>\"],\n                tokenizer=self._tokenizer,\n                seed=seed,\n            )\n\n            step_audio_out_ids_l = []\n            for ele in outputs[1]:\n                audio_out_ids = ele\n                if self._config.use_delay_pattern:\n                    audio_out_ids = revert_delay_pattern(audio_out_ids)\n                step_audio_out_ids_l.append(audio_out_ids.clip(0, self._audio_tokenizer.codebook_size - 1)[:, 1:-1])\n            audio_out_ids = torch.concat(step_audio_out_ids_l, dim=1)\n            audio_out_ids_l.append(audio_out_ids)\n            generated_audio_ids.append(audio_out_ids)\n\n            generation_messages.append(\n                Message(\n                    role=\"assistant\",\n                    content=AudioContent(audio_url=\"\"),\n                )\n            )\n            if generation_chunk_buffer_size is not None and len(generated_audio_ids) > generation_chunk_buffer_size:\n                generated_audio_ids = generated_audio_ids[-generation_chunk_buffer_size:]\n                generation_messages = generation_messages[(-2 * generation_chunk_buffer_size) :]\n\n        logger.info(f\"========= Final Text output =========\")\n        logger.info(self._tokenizer.decode(outputs[0][0]))\n        concat_audio_out_ids = torch.concat(audio_out_ids_l, dim=1)\n\n        # Fix MPS compatibility: detach and move to CPU before decoding\n        if concat_audio_out_ids.device.type == \"mps\":\n            concat_audio_out_ids_cpu = concat_audio_out_ids.detach().cpu()\n        else:\n            concat_audio_out_ids_cpu = concat_audio_out_ids\n\n        concat_wv = self._audio_tokenizer.decode(concat_audio_out_ids_cpu.unsqueeze(0))[0, 0]\n        text_result = self._tokenizer.decode(outputs[0][0])\n        return concat_wv, sr, text_result\n\n\ndef prepare_generation_context(scene_prompt, ref_audio, ref_audio_in_system_message, audio_tokenizer, speaker_tags):\n    \"\"\"Prepare the context for generation.\n\n    The context contains the system message, user message, assistant message, and audio prompt if any.\n    \"\"\"\n    system_message = None\n    messages = []\n    audio_ids = []\n    if ref_audio is not None:\n        num_speakers = len(ref_audio.split(\",\"))\n        speaker_info_l = ref_audio.split(\",\")\n        voice_profile = None\n        if any([speaker_info.startswith(\"profile:\") for speaker_info in ref_audio.split(\",\")]):\n            ref_audio_in_system_message = True\n        if ref_audio_in_system_message:\n            speaker_desc = []\n            for spk_id, character_name in enumerate(speaker_info_l):\n                if character_name.startswith(\"profile:\"):\n                    if voice_profile is None:\n                        with open(f\"{CURR_DIR}/voice_prompts/profile.yaml\", \"r\", encoding=\"utf-8\") as f:\n                            voice_profile = yaml.safe_load(f)\n                    character_desc = voice_profile[\"profiles\"][character_name[len(\"profile:\") :].strip()]\n                    speaker_desc.append(f\"SPEAKER{spk_id}: {character_desc}\")\n                else:\n                    speaker_desc.append(f\"SPEAKER{spk_id}: {AUDIO_PLACEHOLDER_TOKEN}\")\n            if scene_prompt:\n                system_message = (\n                    \"Generate audio following instruction.\"\n                    \"\\n\\n\"\n                    f\"<|scene_desc_start|>\\n{scene_prompt}\\n\\n\" + \"\\n\".join(speaker_desc) + \"\\n<|scene_desc_end|>\"\n                )\n            else:\n                system_message = (\n                    \"Generate audio following instruction.\\n\\n\"\n                    + f\"<|scene_desc_start|>\\n\"\n                    + \"\\n\".join(speaker_desc)\n                    + \"\\n<|scene_desc_end|>\"\n                )\n            system_message = _build_system_message_with_audio_prompt(system_message)\n        else:\n            if scene_prompt:\n                system_message = Message(\n                    role=\"system\",\n                    content=f\"Generate audio following instruction.\\n\\n<|scene_desc_start|>\\n{scene_prompt}\\n<|scene_desc_end|>\",\n                )\n        voice_profile = None\n        for spk_id, character_name in enumerate(ref_audio.split(\",\")):\n            if not character_name.startswith(\"profile:\"):\n                prompt_audio_path = os.path.join(f\"{CURR_DIR}/voice_prompts\", f\"{character_name}.wav\")\n                prompt_text_path = os.path.join(f\"{CURR_DIR}/voice_prompts\", f\"{character_name}.txt\")\n                assert os.path.exists(prompt_audio_path), (\n                    f\"Voice prompt audio file {prompt_audio_path} does not exist.\"\n                )\n                assert os.path.exists(prompt_text_path), f\"Voice prompt text file {prompt_text_path} does not exist.\"\n                with open(prompt_text_path, \"r\", encoding=\"utf-8\") as f:\n                    prompt_text = f.read().strip()\n                audio_tokens = audio_tokenizer.encode(prompt_audio_path)\n                audio_ids.append(audio_tokens)\n\n                if not ref_audio_in_system_message:\n                    messages.append(\n                        Message(\n                            role=\"user\",\n                            content=f\"[SPEAKER{spk_id}] {prompt_text}\" if num_speakers > 1 else prompt_text,\n                        )\n                    )\n                    messages.append(\n                        Message(\n                            role=\"assistant\",\n                            content=AudioContent(\n                                audio_url=prompt_audio_path,\n                            ),\n                        )\n                    )\n    else:\n        if len(speaker_tags) > 1:\n            # By default, we just alternate between male and female voices\n            speaker_desc_l = []\n\n            for idx, tag in enumerate(speaker_tags):\n                if idx % 2 == 0:\n                    speaker_desc = f\"feminine\"\n                else:\n                    speaker_desc = f\"masculine\"\n                speaker_desc_l.append(f\"{tag}: {speaker_desc}\")\n\n            speaker_desc = \"\\n\".join(speaker_desc_l)\n            scene_desc_l = []\n            if scene_prompt:\n                scene_desc_l.append(scene_prompt)\n            scene_desc_l.append(speaker_desc)\n            scene_desc = \"\\n\\n\".join(scene_desc_l)\n\n            system_message = Message(\n                role=\"system\",\n                content=f\"{MULTISPEAKER_DEFAULT_SYSTEM_MESSAGE}\\n\\n<|scene_desc_start|>\\n{scene_desc}\\n<|scene_desc_end|>\",\n            )\n        else:\n            system_message_l = [\"Generate audio following instruction.\"]\n            if scene_prompt:\n                system_message_l.append(f\"<|scene_desc_start|>\\n{scene_prompt}\\n<|scene_desc_end|>\")\n            system_message = Message(\n                role=\"system\",\n                content=\"\\n\\n\".join(system_message_l),\n            )\n    if system_message:\n        messages.insert(0, system_message)\n    return messages, audio_ids\n\n\n@click.command()\n@click.option(\n    \"--model_path\",\n    type=str,\n    default=\"bosonai/higgs-audio-v2-generation-3B-base\",\n    help=\"Output wav file path.\",\n)\n@click.option(\n    \"--audio_tokenizer\",\n    type=str,\n    default=\"bosonai/higgs-audio-v2-tokenizer\",\n    help=\"Audio tokenizer path, if not set, use the default one.\",\n)\n@click.option(\n    \"--max_new_tokens\",\n    type=int,\n    default=2048,\n    help=\"The maximum number of new tokens to generate.\",\n)\n@click.option(\n    \"--transcript\",\n    type=str,\n    default=\"transcript/single_speaker/en_dl.txt\",\n    help=\"The prompt to use for generation. If not set, we will use a default prompt.\",\n)\n@click.option(\n    \"--scene_prompt\",\n    type=str,\n    default=f\"{CURR_DIR}/scene_prompts/quiet_indoor.txt\",\n    help=\"The scene description prompt to use for generation. If not set, or set to `empty`, we will leave it to empty.\",\n)\n@click.option(\n    \"--temperature\",\n    type=float,\n    default=1.0,\n    help=\"The value used to module the next token probabilities.\",\n)\n@click.option(\n    \"--top_k\",\n    type=int,\n    default=50,\n    help=\"The number of highest probability vocabulary tokens to keep for top-k-filtering.\",\n)\n@click.option(\n    \"--top_p\",\n    type=float,\n    default=0.95,\n    help=\"If set to float < 1, only the most probable tokens with probabilities that add up to top_p or higher are kept for generation.\",\n)\n@click.option(\n    \"--ras_win_len\",\n    type=int,\n    default=7,\n    help=\"The window length for RAS sampling. If set to 0 or a negative value, we won't use RAS sampling.\",\n)\n@click.option(\n    \"--ras_win_max_num_repeat\",\n    type=int,\n    default=2,\n    help=\"The maximum number of times to repeat the RAS window. Only used when --ras_win_len is set.\",\n)\n@click.option(\n    \"--ref_audio\",\n    type=str,\n    default=None,\n    help=\"The voice prompt to use for generation. If not set, we will let the model randomly pick a voice. \"\n    \"For multi-speaker generation, you can specify the prompts as `belinda,chadwick` and we will use the voice of belinda as SPEAKER0 and the voice of chadwick as SPEAKER1.\",\n)\n@click.option(\n    \"--ref_audio_in_system_message\",\n    is_flag=True,\n    default=False,\n    help=\"Whether to include the voice prompt description in the system message.\",\n    show_default=True,\n)\n@click.option(\n    \"--chunk_method\",\n    default=None,\n    type=click.Choice([None, \"speaker\", \"word\"]),\n    help=\"The method to use for chunking the prompt text. Options are 'speaker', 'word', or None. By default, we won't use any chunking and will feed the whole text to the model.\",\n)\n@click.option(\n    \"--chunk_max_word_num\",\n    default=200,\n    type=int,\n    help=\"The maximum number of words for each chunk when 'word' chunking method is used. Only used when --chunk_method is set to 'word'.\",\n)\n@click.option(\n    \"--chunk_max_num_turns\",\n    default=1,\n    type=int,\n    help=\"The maximum number of turns for each chunk when 'speaker' chunking method is used. Only used when --chunk_method is set to 'speaker'.\",\n)\n@click.option(\n    \"--generation_chunk_buffer_size\",\n    default=None,\n    type=int,\n    help=\"The maximal number of chunks to keep in the buffer. We will always keep the reference audios, and keep `max_chunk_buffer` chunks of generated audio.\",\n)\n@click.option(\n    \"--seed\",\n    default=None,\n    type=int,\n    help=\"Random seed for generation.\",\n)\n@click.option(\n    \"--device_id\",\n    type=int,\n    default=None,\n    help=\"The device to run the model on.\",\n)\n@click.option(\n    \"--out_path\",\n    type=str,\n    default=\"generation.wav\",\n)\n@click.option(\n    \"--use_static_kv_cache\",\n    type=int,\n    default=1,\n    help=\"Whether to use static KV cache for faster generation. Only works when using GPU.\",\n)\n@click.option(\n    \"--device\",\n    type=click.Choice([\"auto\", \"cuda\", \"mps\", \"none\"]),\n    default=\"auto\",\n    help=\"Device to use: 'auto' (pick best available), 'cuda', 'mps', or 'none' (CPU only).\",\n)\ndef main(\n    model_path,\n    audio_tokenizer,\n    max_new_tokens,\n    transcript,\n    scene_prompt,\n    temperature,\n    top_k,\n    top_p,\n    ras_win_len,\n    ras_win_max_num_repeat,\n    ref_audio,\n    ref_audio_in_system_message,\n    chunk_method,\n    chunk_max_word_num,\n    chunk_max_num_turns,\n    generation_chunk_buffer_size,\n    seed,\n    device_id,\n    out_path,\n    use_static_kv_cache,\n    device,\n):\n    # specifying a device_id implies CUDA\n    if device_id is None:\n        if device == \"auto\":\n            if torch.cuda.is_available():\n                device_id = 0\n                device = \"cuda:0\"\n            elif torch.backends.mps.is_available():\n                device_id = None  # MPS doesn't use device IDs like CUDA\n                device = \"mps\"\n            else:\n                device_id = None\n                device = \"cpu\"\n        elif device == \"cuda\":\n            device_id = 0\n            device = \"cuda:0\"\n        elif device == \"mps\":\n            device_id = None\n            device = \"mps\"\n        else:\n            device_id = None\n            device = \"cpu\"\n    else:\n        device = f\"cuda:{device_id}\"\n    # For MPS, use CPU for audio tokenizer due to embedding operation limitations\n    audio_tokenizer_device = \"cpu\" if device == \"mps\" else device\n    audio_tokenizer = load_higgs_audio_tokenizer(audio_tokenizer, device=audio_tokenizer_device)\n\n    # Disable static KV cache on MPS since it relies on CUDA graphs\n    if device == \"mps\" and use_static_kv_cache:\n        use_static_kv_cache = False\n    model_client = HiggsAudioModelClient(\n        model_path=model_path,\n        audio_tokenizer=audio_tokenizer,\n        device=device,\n        device_id=device_id,\n        max_new_tokens=max_new_tokens,\n        use_static_kv_cache=use_static_kv_cache,\n    )\n\n    pattern = re.compile(r\"\\[(SPEAKER\\d+)\\]\")\n\n    if os.path.exists(transcript):\n        logger.info(f\"Loading transcript from {transcript}\")\n        with open(transcript, \"r\", encoding=\"utf-8\") as f:\n            transcript = f.read().strip()\n\n    if scene_prompt is not None and scene_prompt != \"empty\" and os.path.exists(scene_prompt):\n        with open(scene_prompt, \"r\", encoding=\"utf-8\") as f:\n            scene_prompt = f.read().strip()\n    else:\n        scene_prompt = None\n\n    speaker_tags = sorted(set(pattern.findall(transcript)))\n    # Perform some basic normalization\n    transcript = normalize_chinese_punctuation(transcript)\n    # Other normalizations (e.g., parentheses and other symbols. Will be improved in the future)\n    transcript = transcript.replace(\"(\", \" \")\n    transcript = transcript.replace(\")\", \" \")\n    transcript = transcript.replace(\"°F\", \" degrees Fahrenheit\")\n    transcript = transcript.replace(\"°C\", \" degrees Celsius\")\n\n    for tag, replacement in [\n        (\"[laugh]\", \"<SE>[Laughter]</SE>\"),\n        (\"[humming start]\", \"<SE_s>[Humming]</SE_s>\"),\n        (\"[humming end]\", \"<SE_e>[Humming]</SE_e>\"),\n        (\"[music start]\", \"<SE_s>[Music]</SE_s>\"),\n        (\"[music end]\", \"<SE_e>[Music]</SE_e>\"),\n        (\"[music]\", \"<SE>[Music]</SE>\"),\n        (\"[sing start]\", \"<SE_s>[Singing]</SE_s>\"),\n        (\"[sing end]\", \"<SE_e>[Singing]</SE_e>\"),\n        (\"[applause]\", \"<SE>[Applause]</SE>\"),\n        (\"[cheering]\", \"<SE>[Cheering]</SE>\"),\n        (\"[cough]\", \"<SE>[Cough]</SE>\"),\n    ]:\n        transcript = transcript.replace(tag, replacement)\n    lines = transcript.split(\"\\n\")\n    transcript = \"\\n\".join([\" \".join(line.split()) for line in lines if line.strip()])\n    transcript = transcript.strip()\n\n    if not any([transcript.endswith(c) for c in [\".\", \"!\", \"?\", \",\", \";\", '\"', \"'\", \"</SE_e>\", \"</SE>\"]]):\n        transcript += \".\"\n\n    messages, audio_ids = prepare_generation_context(\n        scene_prompt=scene_prompt,\n        ref_audio=ref_audio,\n        ref_audio_in_system_message=ref_audio_in_system_message,\n        audio_tokenizer=audio_tokenizer,\n        speaker_tags=speaker_tags,\n    )\n    chunked_text = prepare_chunk_text(\n        transcript,\n        chunk_method=chunk_method,\n        chunk_max_word_num=chunk_max_word_num,\n        chunk_max_num_turns=chunk_max_num_turns,\n    )\n\n    logger.info(\"Chunks used for generation:\")\n    for idx, chunk_text in enumerate(chunked_text):\n        logger.info(f\"Chunk {idx}:\")\n        logger.info(chunk_text)\n        logger.info(\"-----\")\n\n    concat_wv, sr, text_output = model_client.generate(\n        messages=messages,\n        audio_ids=audio_ids,\n        chunked_text=chunked_text,\n        generation_chunk_buffer_size=generation_chunk_buffer_size,\n        temperature=temperature,\n        top_k=top_k,\n        top_p=top_p,\n        ras_win_len=ras_win_len,\n        ras_win_max_num_repeat=ras_win_max_num_repeat,\n        seed=seed,\n    )\n\n    sf.write(out_path, concat_wv, sr)\n    logger.info(f\"Wav file is saved to '{out_path}' with sample rate {sr}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/scene_prompts/quiet_indoor.txt",
    "content": "Audio is recorded from a quiet room.\n"
  },
  {
    "path": "examples/scene_prompts/reading_blog.txt",
    "content": "In this audio, the person is reading a blog post aloud. The content is informative and engaging, with the speaker using a clear, conversational tone to make the material feel more approachable. The pacing is moderate, allowing listeners to absorb the information, and the tone shifts slightly to emphasize key points. The speaker occasionally pauses for effect, ensuring each section flows smoothly, as they guide the listener through the post's main ideas.\n"
  },
  {
    "path": "examples/serve_engine/README.md",
    "content": "# Examples to use HiggsAudioServeEngine\n\nThe `run_hf_example.py` script provides three different examples for using the `HiggsAudioServeEngine`. \nEach example will generate an audio file (`output_{example}.wav`) in the current directory.\n\n### Zero-Shot Voice Generation\nGenerate audio with specific voice characteristics (e.g., accents).\n\n```bash\npython run_hf_example.py zero_shot\n```\n\n### Voice Cloning\nClone a voice from a reference audio sample.\n\n```bash\npython run_hf_example.py voice_clone\n```\n\n### (Experimental) Interleaved Dialogue Generation\nHiggs Audio v2 is also able to generate text. Here's an example that shows it is able to generate multi-speaker conversations with interleaved transcript and audio from scene descriptions.\n\n```bash\npython run_hf_example.py interleaved_dialogue\n```\n"
  },
  {
    "path": "examples/serve_engine/input_samples.py",
    "content": "import base64\nimport os\nfrom boson_multimodal.data_types import ChatMLSample, Message, AudioContent\n\n\ndef encode_base64_content_from_file(file_path: str) -> str:\n    \"\"\"Encode a content from a local file to base64 format.\"\"\"\n    # Read the audio file as binary and encode it directly to Base64\n    with open(file_path, \"rb\") as audio_file:\n        audio_base64 = base64.b64encode(audio_file.read()).decode(\"utf-8\")\n    return audio_base64\n\n\ndef get_interleaved_dialogue_input_sample():\n    system_prompt = (\n        \"Generate audio following instruction.\\n\\n\"\n        \"<|scene_desc_start|>\\n\"\n        \"SPEAKER0: vocal fry;moderate pitch;monotone;masculine;young adult;slightly fast\\n\"\n        \"SPEAKER1: masculine;moderate;moderate pitch;monotone;mature\\n\\n\"\n        \"In this scene, a group of adventurers is debating whether to investigate a potentially dangerous situation.\\n\"\n        \"<|scene_desc_end|>\"\n    )\n\n    messages = [\n        Message(\n            role=\"system\",\n            content=system_prompt,\n        ),\n        Message(\n            role=\"user\",\n            content=\"<|generation_instruction_start|>\\nGenerate interleaved transcript and audio that lasts for around 20 seconds.\\n<|generation_instruction_end|>\",\n        ),\n    ]\n    chat_ml_sample = ChatMLSample(messages=messages)\n    return chat_ml_sample\n\n\ndef get_zero_shot_input_sample():\n    system_prompt = (\n        \"Generate audio following instruction.\\n\\n<|scene_desc_start|>\\nSPEAKER0: british accent\\n<|scene_desc_end|>\"\n    )\n\n    messages = [\n        Message(\n            role=\"system\",\n            content=system_prompt,\n        ),\n        Message(\n            role=\"user\",\n            content=\"Hey, everyone! Welcome back to Tech Talk Tuesdays.\\n\"\n            \"It's your host, Alex, and today, we're diving into a topic that's become absolutely crucial in the tech world — deep learning.\\n\"\n            \"And let's be honest, if you've been even remotely connected to tech, AI, or machine learning lately, you know that deep learning is everywhere.\",\n        ),\n    ]\n    chat_ml_sample = ChatMLSample(messages=messages)\n    return chat_ml_sample\n\n\ndef get_voice_clone_input_sample():\n    reference_text = \"I would imagine so. A wand with a dragon heartstring core is capable of dazzling magic.\"\n    reference_audio = encode_base64_content_from_file(\n        os.path.join(os.path.dirname(__file__), \"voice_examples/old_man.wav\")\n    )\n    messages = [\n        Message(\n            role=\"user\",\n            content=reference_text,\n        ),\n        Message(\n            role=\"assistant\",\n            content=AudioContent(raw_audio=reference_audio, audio_url=\"placeholder\"),\n        ),\n        Message(\n            role=\"user\",\n            content=\"Hey, everyone! Welcome back to Tech Talk Tuesdays.\\n\"\n            \"It's your host, Alex, and today, we're diving into a topic that's become absolutely crucial in the tech world — deep learning.\\n\"\n            \"And let's be honest, if you've been even remotely connected to tech, AI, or machine learning lately, you know that deep learning is everywhere.\",\n        ),\n    ]\n    return ChatMLSample(messages=messages)\n\n\nINPUT_SAMPLES = {\n    \"interleaved_dialogue\": get_interleaved_dialogue_input_sample,\n    \"zero_shot\": get_zero_shot_input_sample,\n    \"voice_clone\": get_voice_clone_input_sample,\n}\n"
  },
  {
    "path": "examples/serve_engine/run_hf_example.py",
    "content": "\"\"\"Example for using HiggsAudio for generating both the transcript and audio in an interleaved manner.\"\"\"\n\nfrom boson_multimodal.serve.serve_engine import HiggsAudioServeEngine, HiggsAudioResponse\nimport torch\nimport torchaudio\nimport time\nfrom loguru import logger\nimport click\n\nfrom input_samples import INPUT_SAMPLES\n\nMODEL_PATH = \"bosonai/higgs-audio-v2-generation-3B-base\"\nAUDIO_TOKENIZER_PATH = \"bosonai/higgs-audio-v2-tokenizer\"\n\n\n@click.command()\n@click.argument(\"example\", type=click.Choice(list(INPUT_SAMPLES.keys())))\ndef main(example: str):\n    input_sample = INPUT_SAMPLES[example]()\n    device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n    logger.info(f\"Using device: {device}\")\n\n    serve_engine = HiggsAudioServeEngine(\n        MODEL_PATH,\n        AUDIO_TOKENIZER_PATH,\n        device=device,\n    )\n\n    logger.info(\"Starting generation...\")\n    start_time = time.time()\n    output: HiggsAudioResponse = serve_engine.generate(\n        chat_ml_sample=input_sample,\n        max_new_tokens=1024,\n        temperature=1.0,\n        top_p=0.95,\n        top_k=50,\n        stop_strings=[\"<|end_of_text|>\", \"<|eot_id|>\"],\n    )\n    elapsed_time = time.time() - start_time\n    logger.info(f\"Generation time: {elapsed_time:.2f} seconds\")\n\n    torchaudio.save(f\"output_{example}.wav\", torch.from_numpy(output.audio)[None, :], output.sampling_rate)\n    logger.info(f\"Generated text:\\n{output.generated_text}\")\n    logger.info(f\"Saved audio to output_{example}.wav\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/transcript/multi_speaker/en_argument.txt",
    "content": "[SPEAKER0] I can't believe you did that without even asking me first!\n[SPEAKER1] Oh, come on! It wasn't a big deal, and I knew you would overreact like this.\n[SPEAKER0] Overreact? You made a decision that affects both of us without even considering my opinion!\n[SPEAKER1] Because I didn't have time to sit around waiting for you to make up your mind! Someone had to act.\n"
  },
  {
    "path": "examples/transcript/multi_speaker/en_higgs.txt",
    "content": "[SPEAKER0] You're training HiggsAudio again? Aren't you tired of staring at it all day?\n[SPEAKER1] Ha! This time, I'm trying to get it to generate multi-speaker dialogues.\n[SPEAKER0] Oh, so you want it to sound like a real conversation with multiple people? That sounds… tricky.\n[SPEAKER1] It is. The biggest challenge is making sure it understands who's speaking and when. We need a solid dataset with real conversations, including interruptions and natural flow.\n[SPEAKER0] Right, because real conversations aren't just people taking turns like robots. There are overlaps, hesitations, and sudden topic changes.\n[SPEAKER1] Exactly! That's why we need speaker diarization — so the model knows when one speaker stops and another starts, even if they overlap.\n"
  },
  {
    "path": "examples/transcript/single_speaker/en_basic.txt",
    "content": "The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.\n"
  },
  {
    "path": "examples/transcript/single_speaker/en_dl.txt",
    "content": "Hey, everyone! Welcome back to Tech Talk Tuesdays.\nIt’s your host, Alex, and today, we’re diving into a topic that’s become absolutely crucial in the tech world — deep learning.\nAnd let’s be honest, if you’ve been even remotely connected to tech, AI, or machine learning lately, you know that deep learning is everywhere.\n\nSo here’s the big question: Do you want to understand how deep learning works?\nHow to use it to build powerful models that can predict, automate, and transform industries?\nWell, today, I’ve got some exciting news for you.\n\nWe’re going to talk about a course that I highly recommend: Dive into Deep Learning.\nIt’s not just another course; it’s an entire experience that will take you from a beginner to someone who is well-versed in deep learning techniques.\n"
  },
  {
    "path": "examples/transcript/single_speaker/en_higgs_audio_blog.md",
    "content": "At Boson AI, we work on making communication with AI as easy, natural and fun as talking to a human. Today, we are excited to introduce Higgs Audio Understanding and Higgs Audio Generation — two powerful tools designed to build customized AI agents tailored for diverse audio understanding and generation needs.\n\n# Higgs Audio Generation\nTo communicate with humans in a delightful and natural manner, we need to be able to generate realistic, emotionally competent and well-accentuated speech. We need a system that is capable of pronouncing words correctly, even if they derive from a foreign language, particularly for people’s names and places. We need a system that can generate conversations between multiple speakers, particularly when multiple characters in games are involved, or when reading books or screenplays.\n\nPure TTS (text to speech) systems struggle at these tasks, since they typically do not understand the meaning of what they’re generating, or any sense of urgency, hesitation, or other intonations that would be plainly obvious to a human speaker. They also struggle to adopt the natural character of a speaker, for example, whether they’re naturally enthusiastic or more deliberate and thoughtful.\n\nThe way to address this problem is to build a TTS system using a Large Language Model (LLM) as a backbone. This endows the TTS system with the understanding needed to generate competent speech. Higgs Audio Generation enhances the underlying LLM to process audio by treating raw audio as tokens. This approach enables the model to be trained end-to-end on extensive text-audio datasets.\n\nThe base model we are introducing today demonstrates impressive performance on benchmark tests. Additionally, it showcases emerging capabilities, including generating speech with emotional tone based on text semantics and producing multi-speaker dialogues from written transcripts, all due to the improved understanding. Before diving into technical details, let’s listen to two examples of audio generated by our model.\n"
  },
  {
    "path": "examples/transcript/single_speaker/experimental/en_bgm.txt",
    "content": "[music start] I will remember this, thought Ender, when I am defeated. To keep dignity, and give honor where it’s due, so that defeat is not disgrace. And I hope I don’t have to do it often. [music end]\n"
  },
  {
    "path": "examples/transcript/single_speaker/experimental/en_humming.txt",
    "content": "Are you asking if I can hum a tune? Of course I can! [humming start] la la la la la [humming end] See?\n"
  },
  {
    "path": "examples/transcript/single_speaker/zh_ai.txt",
    "content": "大家好，欢迎收听本期的跟李沐学AI。今天沐哥在忙着洗数据，所以由我，希格斯主播代替他讲这期视频。\n今天我们要聊的是一个你绝对不能忽视的话题\"多模态学习\"。\n无论你是开发者，数据科学爱好者，还是只是对人工智能感兴趣的人都一定听说过这个词。它已经成为AI时代的一个研究热点。\n那么，问题来了，你真的了解多模态吗 你知道如何自己动手构建多模态大模型吗。"
  },
  {
    "path": "examples/vllm/README.md",
    "content": "# Serve Higgs Audio with vLLM\n\nWe provided both OpenAI compatible chat completion and audio speech server backed by vLLM engine. To start the server, you can use the following command\n\n```bash\ndocker run --gpus all --ipc=host --shm-size=20gb --network=host \\\nbosonai/higgs-audio-vllm:latest \\\n--served-model-name \"higgs-audio-v2-generation-3B-base\" \\\n--model \"bosonai/higgs-audio-v2-generation-3B-base\"  \\\n--audio-tokenizer-type \"bosonai/higgs-audio-v2-tokenizer\" \\\n--limit-mm-per-prompt audio=50 \\\n--max-model-len 8192 \\\n--port 8000 \\\n--gpu-memory-utilization 0.8 \\\n--disable-mm-preprocessor-cache\n```\n\nIn audio speech API, we provided the same voices as the [voice_prompts](../voice_prompts) folder. In addition, if you want to use your custom voices, you can add the voice presets in the docker run command \n\n```bash\n--voice-presets-dir YOUR_VOICE_PRESETS_PATH\n```\n\nAnd in the voice presets directory, you need to add `config.json` file for each voice in the following format:\n```json\n{\n    \"belinda\": {\n        \"transcript\": \"Twas the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year.\",\n        \"audio_file\": \"belinda.wav\"\n    },\n    \"broom_salesman\": {\n        \"transcript\": \"I would imagine so. A wand with a dragon heartstring core is capable of dazzling magic. And the bond between you and your wand should only grow stronger. Do not be surprised at your new wand's ability to perceive your intentions - particularly in a moment of need.\",\n        \"audio_file\": \"broom_salesman.wav\"\n    }\n}\n```\n\nWe tested on A100 GPU with 40GB memory, which can achieve about 1500 tokens/s throughput for audio generation, which translate to 60 seconds audio generation per second with higgs-audio-tokenizer.\nWe also tested on RTX 4090 GPU with 24GB memory, which can achieve about 600 tokens/s throughput for audio generation, which translate to 24 seconds audio generation per second.\n\n### cURL Example\nTo quickly test the server with curl, you can use the following command to generate audio with the audio speech API.\n\n```bash\ncurl -X POST \"http://localhost:8000/v1/audio/speech\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model\": \"higgs-audio-v2-generation-3B-base\",\n    \"voice\": \"en_woman\",\n    \"input\": \"Today is a wonderful day to build something people love!\",\n    \"response_format\": \"pcm\"\n  }' \\\n  --output - | ffmpeg -f s16le -ar 24000 -ac 1 -i - speech.wav\n```\n\n\n### Python example\nYou can also use the python client code to achieve more complex use cases with the chat completion API.\n\nVoice clone\n```bash\npython run_chat_completion.py --api-base http://localhost:8000/v1 --task voice_clone\n```\n\nSmart voice\n```bash\npython run_chat_completion.py --api-base http://localhost:8000/v1 --task smart_voice\n```\n\nMultispeaker\n```bash\npython run_chat_completion.py --api-base http://localhost:8000/v1 --task multispeaker\n```\n"
  },
  {
    "path": "examples/vllm/run_chat_completion.py",
    "content": "# SPDX-License-Identifier: Apache-2.0\n\"\"\"An example showing how to use vLLM to serve multimodal models\nand run online inference with OpenAI client.\n\"\"\"\n\nimport argparse\nimport base64\nimport os\nimport time\nfrom io import BytesIO\n\nimport numpy as np\nimport requests\nimport soundfile as sf\nfrom openai import OpenAI\n\nOPENAI_AUDIO_SAMPLE_RATE = 24000\nDEFAULT_SYSTEM_PROMPT = (\n    \"Generate audio following instruction.\\n\\n\"\n    \"<|scene_desc_start|>\\n\"\n    \"Audio is recorded from a quiet room.\\n\"\n    \"<|scene_desc_end|>\"\n)\n\n\ndef encode_base64_content_from_file(file_path: str) -> str:\n    \"\"\"Encode a content from a local file to base64 format.\"\"\"\n    # Read the MP3 file as binary and encode it directly to Base64\n    with open(file_path, \"rb\") as audio_file:\n        audio_base64 = base64.b64encode(audio_file.read()).decode(\"utf-8\")\n    return audio_base64\n\n\ndef run_smart_voice() -> None:\n    chat_completion = client.chat.completions.create(\n        messages=[\n            {\"role\": \"system\", \"content\": DEFAULT_SYSTEM_PROMPT},\n            {\n                \"role\": \"user\",\n                \"content\": (\n                    \"The sun rises in the east and sets in the west. This simple fact has been observed by humans for thousands of years.\"\n                ),\n            },\n        ],\n        model=model,\n        modalities=[\"text\", \"audio\"],\n        temperature=1.0,\n        top_p=0.95,\n        extra_body={\"top_k\": 50},\n        stop=[\"<|eot_id|>\", \"<|end_of_text|>\", \"<|audio_eos|>\"],\n    )\n\n    text = chat_completion.choices[0].message.content\n    audio = chat_completion.choices[0].message.audio.data\n    # Decode base64 audio string to bytes\n    audio_bytes = base64.b64decode(audio)\n    print(\"Chat completion text output:\", text)\n    print(\"Saving the audio to file\")\n    with open(\"output_smart_voice.wav\", \"wb\") as f:\n        f.write(audio_bytes)\n\n\ndef run_voice_clone(stream: bool = False) -> None:\n    data_dir = os.path.join(os.path.dirname(__file__), \"..\", \"voice_prompts\")\n    audio_path = os.path.join(data_dir, \"belinda.wav\")\n    audio_text_path = os.path.join(data_dir, \"belinda.txt\")\n    with open(audio_text_path, \"r\") as f:\n        audio_text = f.read()\n    audio_base64 = encode_base64_content_from_file(audio_path)\n    messages = [\n        {\"role\": \"user\", \"content\": audio_text},\n        {\n            \"role\": \"assistant\",\n            \"content\": [\n                {\n                    \"type\": \"input_audio\",\n                    \"input_audio\": {\n                        \"data\": audio_base64,\n                        \"format\": \"wav\",\n                    },\n                }\n            ],\n        },\n        {\n            \"role\": \"user\",\n            \"content\": (\n                \"Hey there! I'm your friendly voice twin in the making. Pick a voice preset below or upload your own audio - let's clone some vocals and bring your voice to life!\"\n            ),\n        },\n    ]\n    start_time = time.time()\n    chat_completion = client.chat.completions.create(\n        messages=messages,\n        model=model,\n        max_completion_tokens=500,\n        stream=stream,\n        modalities=[\"text\", \"audio\"],\n        temperature=1.0,\n        top_p=0.95,\n        extra_body={\"top_k\": 50},\n        stop=[\"<|eot_id|>\", \"<|end_of_text|>\", \"<|audio_eos|>\"],\n    )\n    if stream:\n        audio_bytes_io = BytesIO()\n        i = 0\n        first_audio_latency = None\n        for chunk in chat_completion:\n            if chunk.choices and hasattr(chunk.choices[0].delta, \"audio\") and chunk.choices[0].delta.audio:\n                if first_audio_latency is None:\n                    first_audio_latency = time.time() - start_time\n                audio_bytes = base64.b64decode(chunk.choices[0].delta.audio[\"data\"])\n                audio_bytes_io.write(audio_bytes)\n                audio_data = np.frombuffer(audio_bytes, dtype=np.int16)\n                i += 1\n        audio_bytes_io.seek(0)\n        audio_data = np.frombuffer(audio_bytes_io.getvalue(), dtype=np.int16)\n        print(\"Saving the audio to file\")\n        print(f\"First audio latency: {first_audio_latency * 1000} ms\")\n        print(f\"Total audio latency: {(time.time() - start_time) * 1000} ms\")\n        sf.write(\"output_voice_clone.wav\", audio_data, OPENAI_AUDIO_SAMPLE_RATE)\n    else:\n        text = chat_completion.choices[0].message.content\n        audio = chat_completion.choices[0].message.audio.data\n        audio_bytes = base64.b64decode(audio)\n        print(\"Chat completion text output:\", text)\n        print(\"Saving the audio to file\")\n        with open(\"output_voice_clone.wav\", \"wb\") as f:\n            f.write(audio_bytes)\n\n\ndef run_generate_multispeaker(stream: bool = False) -> None:\n    MULTI_SPEAKER_SYSTEM_PROMPT = (\n        \"You are an AI assistant designed to convert text into speech.\\n\"\n        \"If the user's message includes a [SPEAKER*] tag, do not read out the tag and generate speech for the following text, using the specified voice.\\n\"\n        \"If no speaker tag is present, select a suitable voice on your own.\\n\\n\"\n        \"<|scene_desc_start|>\\n\"\n        \"SPEAKER0: feminine\\n\"\n        \"SPEAKER1: masculine\\n\"\n        \"<|scene_desc_end|>\"\n    )\n    transcript_path = os.path.join(os.path.dirname(__file__), \"..\", \"transcript\", \"multi_speaker\", \"en_argument.txt\")\n    with open(transcript_path, \"r\") as f:\n        transcript = f.read()\n\n    messages = [{\"role\": \"system\", \"content\": MULTI_SPEAKER_SYSTEM_PROMPT}, {\"role\": \"user\", \"content\": transcript}]\n    chat_completion = client.chat.completions.create(\n        messages=messages,\n        model=model,\n        stream=stream,\n        stream_options={\"include_usage\": True},\n        stop=[\"<|end_of_text|>\", \"<|eot_id|>\", \"<|audio_eos|>\"],\n        modalities=[\"text\", \"audio\"],\n        temperature=1.0,\n        top_p=0.95,\n        extra_body={\"top_k\": 50},\n    )\n\n    if stream:\n        audio_bytes_io = BytesIO()\n        i = 0\n        for chunk in chat_completion:\n            if chunk.choices and hasattr(chunk.choices[0].delta, \"audio\") and chunk.choices[0].delta.audio:\n                audio_bytes = base64.b64decode(chunk.choices[0].delta.audio[\"data\"])\n                audio_bytes_io.write(audio_bytes)\n                audio_data = np.frombuffer(audio_bytes, dtype=np.int16)\n                # sf.write(f\"output_tts_{i}.wav\", audio_data, target_rate)\n                i += 1\n            else:\n                print(chunk)\n        audio_bytes_io.seek(0)\n        audio_data = np.frombuffer(audio_bytes_io.getvalue(), dtype=np.int16)\n        print(\"Saving the audio to file\")\n        sf.write(\"output_multispeaker.wav\", audio_data, OPENAI_AUDIO_SAMPLE_RATE)\n    else:\n        text = chat_completion.choices[0].message.content\n        audio = chat_completion.choices[0].message.audio.data\n        audio_bytes = base64.b64decode(audio)\n        print(\"Chat completion text output:\", text)\n        print(\"Saving the audio to file\")\n        with open(\"output_multispeaker.wav\", \"wb\") as f:\n            f.write(audio_bytes)\n\n\ndef main(args) -> None:\n    if args.task == \"voice_clone\":\n        run_voice_clone(args.stream)\n    elif args.task == \"smart_voice\":\n        run_smart_voice()\n    elif args.task == \"multispeaker\":\n        run_generate_multispeaker(args.stream)\n    else:\n        raise ValueError(f\"Task {args.task} not supported\")\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--api-base\",\n        type=str,\n        default=\"http://localhost:8000/v1\",\n        help=\"API base URL for OpenAI client.\",\n    )\n    parser.add_argument(\"--api-key\", type=str, default=\"EMPTY\", help=\"API key for OpenAI client.\")\n    parser.add_argument(\"--stream\", action=\"store_true\", help=\"Stream the audio.\")\n    parser.add_argument(\n        \"--task\",\n        type=str,\n        default=\"voice_clone\",\n        help=\"Task to run.\",\n        choices=[\"voice_clone\", \"smart_voice\", \"multispeaker\"],\n    )\n    parser.add_argument(\"--model\", type=str, default=None, help=\"Model to use.\")\n    args = parser.parse_args()\n\n    client = OpenAI(\n        api_key=args.api_key,\n        base_url=args.api_base,\n    )\n\n    if args.model is None:\n        models = client.models.list()\n        model = models.data[0].id\n    else:\n        model = args.model\n\n    main(args)\n"
  },
  {
    "path": "examples/voice_prompts/belinda.txt",
    "content": "Twas the night before my birthday. Hooray! It's almost here! It may not be a holiday, but it's the best day of the year.\n"
  },
  {
    "path": "examples/voice_prompts/bigbang_amy.txt",
    "content": "If that was slang, I'm unfamiliar with it. <SE>[Laughter]</SE> If it was literal, I share your aversion to soiled hosiery. <SE>[Laughter]</SE> In any case, I'm here because my mother and I have agreed that I will date at least once a year.''' \n"
  },
  {
    "path": "examples/voice_prompts/bigbang_sheldon.txt",
    "content": "Hello, Amy Farrah Fowler. I'm sorry to inform you that you have been taken in by unsupportable mathematics designed to prey on the gullible and the lonely. Additionally, I'm being blackmailed with a hidden dirty sock. <SE>[Laughter]</SE>\n"
  },
  {
    "path": "examples/voice_prompts/broom_salesman.txt",
    "content": "I would imagine so. A wand with a dragon heartstring core is capable of dazzling magic. And the bond between you and your wand should only grow stronger. Do not be surprised at your new wand's ability to perceive your intentions - particularly in a moment of need.\n"
  },
  {
    "path": "examples/voice_prompts/chadwick.txt",
    "content": "Oh dear, who left all this junk lying around? Whoops, there it goes! Mind your pointed little pink head, starfish man.\n"
  },
  {
    "path": "examples/voice_prompts/en_man.txt",
    "content": "Maintaining your ability to learn translates into increased marketability, improved career options and higher salaries.\n"
  },
  {
    "path": "examples/voice_prompts/en_woman.txt",
    "content": "The device would work during the day as well, if you took steps to either block direct sunlight or point it away from the sun.\n"
  },
  {
    "path": "examples/voice_prompts/fiftyshades_anna.txt",
    "content": "I'm working at the hardware store till 7. I think I'd like that too. What?\n"
  },
  {
    "path": "examples/voice_prompts/mabaoguo.txt",
    "content": "我是浑元形意太极门掌门人马保国,刚才有个朋友问我:马老师发生什么事啦.我说怎么回事,给我发了几张截图,我一看,哦,原来是昨天,有两个年轻人,三十多岁,一个体重九十多公斤,一个体重八十多公斤.他们说,哎,有一个说是:我在健身房练功,颈椎练坏了,马老师你能不能教教我浑元功法\n"
  },
  {
    "path": "examples/voice_prompts/mabel.txt",
    "content": "You do talk an awful lot about weather, did you know that? Sometimes I wonder if you're actually content to be a wizard or if you're secretly harbouring a desire to become a seer of the clouds.\n"
  },
  {
    "path": "examples/voice_prompts/profile.yaml",
    "content": "profiles:\n  male_en: Male, American accent, modern speaking rate, moderate-pitch, friendly tone, and very clear audio.\n  female_en_story: She speaks with a calm, gentle, and informative tone at a measured pace, with excellent articulation and very clear audio. She naturally brings storytelling to life with an articulate, genuine, and personable vocal style.\n  male_en_british: He speaks with a clear British accent and a conversational, inquisitive tone. His delivery is articulate and at a moderate pace, and very clear audio.\n  female_en_british: A female voice with a clear British accent speaking at a modern rate with a moderate-pitch in an expressive and friendly tone and very clear audio.\n"
  },
  {
    "path": "examples/voice_prompts/shrek_donkey.txt",
    "content": "And I've got a great idea, I'll stick with you. You're a mean green fighting machine, together we'll scare the spit out of anybody that crosses us. \nOh, Wow, that was really scary. And if you don't mind me saying, if that don't work, your breath certainly will get the job done, 'cause you definitely need some Tic Tacs or something, 'cause your breath stinks!"
  },
  {
    "path": "examples/voice_prompts/shrek_donkey_es.txt",
    "content": "¡Uy, guau! Eso sí que asusta. Y si el rugido no funciona, tu mal aliento seguro los desmaya. Necesitas unas pastillitas de menta porque el hocico te apesta."
  },
  {
    "path": "examples/voice_prompts/shrek_fiona.txt",
    "content": "Well, when one lives alone, one has to learn these things in case there's a... There's an arrow in your butt!\nCalm down. If you want to help Shrek, run into the woods and find me a blue flower with red thorns."
  },
  {
    "path": "examples/voice_prompts/shrek_shrek.txt",
    "content": "Well, it's no wonder you don't have any friends. Listen, little donkey, take a look at me. What am I?\nNo! I'm an ogre! You know, with a torch and pitchfork. Doesn't that bother you?"
  },
  {
    "path": "examples/voice_prompts/vex.txt",
    "content": "Uhh, this is going to take forever. Why is everything so far?\n"
  },
  {
    "path": "examples/voice_prompts/zh_man_sichuan.txt",
    "content": "对，这就是我，万人敬仰的太乙真人，虽然有点婴儿肥，但也掩不住我逼人的帅气。"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[tool.ruff]\nline-length = 119\ntarget-version = \"py310\"\nindent-width = 4\nexclude = [\n    \".bzr\",\n    \".direnv\",\n    \".eggs\",\n    \".git\",\n    \".git-rewrite\",\n    \".hg\",\n    \".ipynb_checkpoints\",\n    \".mypy_cache\",\n    \".nox\",\n    \".pants.d\",\n    \".pyenv\",\n    \".pytest_cache\",\n    \".pytype\",\n    \".ruff_cache\",\n    \".svn\",\n    \".tox\",\n    \".venv\",\n    \".vscode\",\n    \"__pypackages__\",\n    \"_build\",\n    \"buck-out\",\n    \"build\",\n    \"dist\",\n    \"node_modules\",\n    \"site-packages\",\n    \"venv\",\n    \"external\",\n    \"third_party\",\n]\n\n[tool.ruff.lint]\npreview = true\nignore-init-module-imports = true\nextend-select = [\n    \"B009\", # static getattr\n    \"B010\", # static setattr\n    \"CPY\", # Copyright\n    \"E\", # PEP8 errors\n    \"F\", # PEP8 formatting\n    \"I\", # Import sorting\n    \"TID251\", # Banned API\n    \"UP\", # Pyupgrade\n    \"W\", # PEP8 warnings\n]\nignore = [\n    \"E501\", # Line length (handled by ruff-format)\n    \"E741\", # Ambiguous variable name\n    \"W605\", # Invalid escape sequence\n    \"UP007\", # X | Y type annotations\n]\n\n[tool.ruff.lint.per-file-ignores]\n\"__init__.py\" = [\n    \"F401\", # Ignore seemingly unused imports (they're meant for re-export)\n]\n\n[tool.ruff.lint.isort]\nlines-after-imports = 2\nknown-first-party = [\"character_tuning\"]\n\n[tool.ruff.format]\n# Like Black, use double quotes for strings.\nquote-style = \"double\"\n\n# Like Black, indent with spaces, rather than tabs.\nindent-style = \"space\"\n\n# Like Black, respect magic trailing commas.\nskip-magic-trailing-comma = false\n\n# Like Black, automatically detect the appropriate line ending.\nline-ending = \"auto\"\n\n# Enable auto-formatting of code examples in docstrings. Markdown,\n# reStructuredText code/literal blocks and doctests are all supported.\n#\n# This is currently disabled by default, but it is planned for this\n# to be opt-out in the future.\ndocstring-code-format = false\n\n# Set the line length limit used when formatting code snippets in\n# docstrings.\n#\n# This only has an effect when the `docstring-code-format` setting is\n# enabled.\ndocstring-code-line-length = \"dynamic\"\n\n[tool.ruff.lint.flake8-tidy-imports.banned-api]\n\"os.getenv\".msg = \"Use os.environ instead\"\n\"os.putenv\".msg = \"Use os.environ instead\"\n\"os.unsetenv\".msg = \"Use os.environ instead\"\n\n"
  },
  {
    "path": "requirements.txt",
    "content": "descript-audio-codec\ntorch\ntransformers>=4.45.1,<4.47.0\nlibrosa\ndacite\nboto3==1.35.36\ns3fs\ntorchvision\ntorchaudio\njson_repair\npandas\npydantic\nvector_quantize_pytorch\nloguru\npydub\nruff==0.12.2\nomegaconf\nclick\nlangid\njieba\naccelerate>=0.26.0\n"
  },
  {
    "path": "setup.cfg",
    "content": "[metadata]\nname = boson_multimodal\nauthor = Boson AI\nversion = 0.1.0\nurl = https://github.com/boson-ai/higgs-audio\ndescription = Higgs Audio\nlong_description = file: README.md\nlong_description_content_type = text/markdown\n\n[options]\npackages = find:\n\n[options.packages.find]\nexclude =\n    tests*\n    training*\n"
  },
  {
    "path": "setup.py",
    "content": "from setuptools import setup\n\n\nsetup()\n"
  },
  {
    "path": "tech_blogs/ARCHITECTURE_BLOG.md",
    "content": "# HiggsAudio-V2 Model Architecture\n<img src=\"../figures/higgs_audio_v2_architecture_combined.png\" width=800/>\n\n\nOur model is built on top of [Llama-3.2-3B](https://huggingface.co/meta-llama/Llama-3.2-3B). To enhance the model’s ability to process audio tokens, we incorporate the \"DualFFN\" architecture as an audio adapter. DualFFN acts as an audio-specific expert, boosting the LLM's performance with minimal computational overhead. Our implementation preserves 91% of the original LLM’s training speed with the inclusion of DualFFN.\n\nSince our audio tokenizer is based on Residual Vector-Quantization (RVQ) and contains multiple codebooks, we adopt the [delay pattern](https://proceedings.neurips.cc/paper_files/paper/2023/file/94b472a1842cd7c56dcb125fb2765fbd-Paper-Conference.pdf) to enable simultaneous code generation across codebooks while supporting streaming.\n\n<img src=\"../figures/higgs_audio_v2_open_source_delay_pattern.png\" width=800/>\n\n\n## DualFFN Performance Ablation Study\n\nTo assess the effectiveness of DualFFN, we trained two smaller models based on LLaMA-3.1-1B: one incorporating DualFFN and one without. Both models were trained for 250K steps with a learning rate of 5e-4 on a subset of the AudioVerse dataset. We evaluated their performance on SeedTTS-Eval, with the results presented in the figures below. The model equipped with DualFFN consistently outperforms its counterpart in terms of word error rate (WER) and speaker similarity.\n\n- SeedTTS-EN\n\n<img src=\"../figures/dual_ffn_comparison_seed_tts_en_wer.png\" width=400/> <img src=\"../figures/dual_ffn_comparison_seed_tts_en_sim.png\" width=400/>\n\n- SeedTTS-ZH\n\n<img src=\"../figures/dual_ffn_comparison_seed_tts_zh_wer.png\" width=400/> <img src=\"../figures/dual_ffn_comparison_seed_tts_zh_sim.png\" width=400>\n\nWe may notice that the model with DualFFN consistently outperforms the model without DualFFN in terms of word-error-rate (WER) and speaker similarity.\n"
  },
  {
    "path": "tech_blogs/TOKENIZER_BLOG.md",
    "content": "# Higgs Audio Tokenizer\n\nIn this work, we introduce a new discretized audio tokenizer that runs at just **25 frames per second** while keeping—or even improving—audio quality compared to tokenizers with twice the bitrate. Our model is the first to train on **24 kHz data** covering speech, music, and sound events in one unified system. It also uses a simple non-diffusion encoder/decoder for fast, batch inference.\n\n![XCodec Architecture](../figures/higgs_audio_tokenizer_architecture.png)\n\n## Basics of Audio Quantization\n\nAn audio signal sampled at $f_s$ Hz is first split into frames by an encoder with hop size $M$, giving a frame rate  $f_r = \\frac{f_s}{M}\\quad\\text{(frames/s)}.$\nTwo common quantizers are:\n\n- **Residual Vector Quantization (RVQ)**: $N_q$ cascaded layers with codebook size $N_{cb}$ each. When $N_{cb}=1$, it reduces to single-vector quantization.  \n- **Finite Scalar Quantization (FSQ)**: A single layer ($N_q=1$) with codebook size $N_{cb}$.  \n\nIf every combination of codewords is a token, the vocabulary size is $N_{cb}^{N_q}$, and each token needs $N_q\\log_2 N_{cb}$ bits. The overall bitrate (bits/s, BPS) is simply $f_r \\times N_q \\log_2 N_{cb}.$  \nWe aim to push this bitrate as low as possible without hurting audio fidelity.\n\n## What Makes Ours Better\n\n- **Low Frame Rate**: At 25 fps, our tokenizer halves the frame rate of many baselines when still maintaining high audio quality. \n- **Unified 24 kHz Training**: We mix speech, music, and sound-event clips in one model, capturing both semantic and acoustic details, hugely facilitating the training of audio language models.\n- **Fast Inference**: By avoiding diffusion steps, our encoder/decoder processes batches quickly, making it practical for real-time or large-scale tasks.\n\n\n## Data and Evaluation Metrics\n\nWe test on four subsets, available [here](https://huggingface.co/datasets/bosonai/AudioTokenBench):\n\n- **Speech, Music, Sound Event**: Includes 1,000 clips for each category, with each clip lasting 10 seconds.   Clips are randomly sampled from [DAPS](https://ccrma.stanford.edu/~gautham/Site/daps.html) (Speech), [MUSDB](https://sigsep.github.io/datasets/musdb.html) (Music), and [AudioSet](https://research.google.com/audioset/index.html) (Sound Event).\n\n- **Audiophile**: Contains 150 clips, each 30 seconds long, curated from eleven high-fidelity test discs. The clips feature both music and sound events, selected for audio quality evaluation.\n\nWe measure:\n\n- **Acoustic Quality**: STFT distance between the original and reconstructed audio.  \n- **Semantic Integrity**: Semantic preservation of the original audio using [SeedTTS](https://arxiv.org/abs/2406.02430)[15] dataset on English and Chinese. \n- **Aesthetics**: SOTA unified model-based quality assessment, [Meta Audiobox Aesthetics](https://github.com/facebookresearch/audiobox-aesthetics)[8], for Content Enjoyment (CE), Content Usefulness (CU) .\n\n\nWe compare our tokenizer with a wide range of baselines, from tokenizers mainly built for better acoustic reconstruction and compression rate, to those focused on semantic integrity, and to tokenizers used in existing large audio language models. We also compare with tokenizers that are pretrained specifically on speech or on music.\n\n\nThe tables below summarize the tokenizers evaluated. As shown, our tokenizer achieves a well-rounded balance of efficiency, semantic fidelity, and acoustic quality.\n\n### Accoustic Evaluation\n\nWe use the STFT metric here for simplicity. The baselines are ordered chronologically, grouped by whether semantic distillation (SD) is applied.Despite DAC’s top acoustic quality at 12× the bitrate, our tokenizer leads all other baselines.\n\n\n| Tokenizer | 💬 | 🎵 | 🥁 | SD | $f_s$ | $f_r$ | BPS* (k) ↓ | Speech ↓ | Sound Event ↓ | Music ↓ | Audiophile ↓ |\n|-----------|----|----|----|----|-------|-------|--------------------------|----------|----------------|--------|--------------|\n| [Encodec](https://huggingface.co/facebook/encodec_24khz)[3] | ✓ | ✓ | ✓ |  | 24 | 75 | 24 | 1.96 | 2.65 | 2.52 | 2.30 |\n| [DAC](https://huggingface.co/hance-ai/descript-audio-codec-24khz)[2] | ✓ | ✓ | ✓ |  | 24 | 75 | 24 | **1.13** | **1.45** | **1.34** | **1.62** |\n| [SNAC-24k](https://huggingface.co/hubertsiuzdak/snac_24khz)[6] | ✓ |  |  |  | 24 | (12, 23, 47) | 0.98 | 1.92 | 2.69 | 2.54 | 2.52 |\n| [SNAC-44.1k](https://huggingface.co/hubertsiuzdak/snac_44khz)[6] |  | ✓ | ✓ |  | 44.1 | (14, 29, 57, 115) | 2.6 | 1.83 | 2.25 | 2.05 | 2.00 |\n| [WavTokenizer](https://huggingface.co/novateur/WavTokenizer-medium-music-audio-75token/blob/main/wavtokenizer_medium_music_audio_320_24k_v2.ckpt)[7] |  | ✓ | ✓ |  | 24 | 75 | 0.9 | 1.93 | 2.44 | 2.17 | 2.15 |\n| [WavTokenizer (Speech)](https://huggingface.co/novateur/WavTokenizer-large-speech-75token/tree/main)[7] | ✓ |  |  |  | 24 | 75 | 0.9 | 1.78 | 2.47 | 2.42 | 2.47 |\n| [MuCodec](https://huggingface.co/haoheliu/audioldm_48k/tree/main)[11] |  | ✓ |  |  | 48 | 25 | 0.35 | 2.87 | 3.69 | 3.36 | 2.97 |\n| [FlowDec-75m](https://github.com/facebookresearch/FlowDec?tab=readme-ov-file)[12] | ✓ | ✓ | ✓ |  | 48 | 75 | 7.5 | 1.73 | 2.14 | 2.01 | 2.03 |\n| [FlowDec-25s](https://github.com/facebookresearch/FlowDec?tab=readme-ov-file)[12] | ✓ | ✓ | ✓ |  | 48 | 25 | 4 | 1.94 | 2.42 | 2.25 | 2.33 |\n| [SpeechTokenizer](https://huggingface.co/fnlp/SpeechTokenizer/tree/main/speechtokenizer_hubert_avg)[14] | ✓ |  |  | ✓ | 16 | 50 | 4 | 3.21 | 3.58 | 3.65 | 3.69 |\n| [SemantiCodec](https://huggingface.co/haoheliu/SemantiCodec/tree/main/semanticodec_tokenrate_100)[5] | ✓ | ✓ | ✓ | ✓ | 16 | 50 | 1.4 | 3.05 | 3.28 | 3.24 | 3.18 |\n| [Mimi](https://huggingface.co/docs/transformers/en/model_doc/mimi)[13] | ✓ |  |  | ✓ | 24 | 12.5 | 4.4 | 1.77 | 2.40 | 2.30 | 2.15 |\n| [XCodec](https://huggingface.co/ZhenYe234/xcodec/blob/main/config_hubert_general.yaml)[1] | ✓ | ✓ | ✓ | ✓ | 16 | 50 | 4 | 2.95 | 3.16 | 3.00 | 3.03 |\n| [CosyVoice 2](https://huggingface.co/FunAudioLLM/CosyVoice2-0.5B)[13] | ✓ |  |  | ✓ | 16 | 25 | -** | 2.30 | 3.30 | 3.14 | 3.25 |\n| [XCodec2](https://huggingface.co/HKUST-Audio/xcodec2/blob/main/ckpt/epoch%3D4-step%3D1400000.ckpt)[9] | ✓ |  |  | ✓ | 16 | 50 | 0.8 | 3.06 | 3.72 | 3.62 | 3.64 |\n| [XY](https://huggingface.co/fnlp/XY_Tokenizer_TTSD_V0/tree/main)[10] | ✓ |  |  | ✓ | 24 | 12.5 | 1 | 1.89 | 2.51 | 2.40 | 2.26 |\n| Ours | ✓ | ✓ | ✓ | ✓ | 24 | 25 | 2 | **1.62** | **2.03** | **1.85** | **1.80** |\n\n\n\n\\* Bits-per-second is calculated according to the checkpoint the author provided.\n\n\\*\\* CosyVoice 2 uses the continuous feature as the conditioning, we include it for completeness.\n\n\n### Semantic Evaluation\nHere we only compare with tokenizers that are trained with semantic distillation.\n[SeedTTS](https://github.com/BytedanceSpeech/seed-tts-eval) is a dataset includes prompt/target audio and texts. We reconstructed the target audio, and use the word error rate (WER) and speaker similarity (SIM) metrics to evaluate the semantic integrity. SIM is calculated by the similarity between the prompt audio and reconstructed targeted audio with [WavLM-large](https://drive.google.com/file/d/1-aE1NfzpRCLxA4GUxX9ITI3F9LlbtEGP/view) as the embedding model. \n\nThe following table shows that our tokenizer achieves comparable performance to tokenizers that 2.2x the bitrate of our model.\n\n| Model | BPS (k) | en WER ↓ | en SIM ↑ | zh WER ↓ | zh SIM ↑ |\n|------------------|---------|------------|------------|------------|------------|\n| [SpeechTokenizer](https://huggingface.co/fnlp/SpeechTokenizer/tree/main/speechtokenizer_hubert_avg) | 4 | 2.82 | 0.63 | 2.04 | 0.65 |\n| [SemantiCodec](https://huggingface.co/haoheliu/SemantiCodec/tree/main/semanticodec_tokenrate_100) | 1.4 | 3.46 | 0.56 | 2.18 | 0.60 |\n| [Mimi](https://huggingface.co/docs/transformers/en/model_doc/mimi) | 4.4 | **2.35** | **0.70** | **1.48** | **0.72** |\n| [XCodec](https://huggingface.co/ZhenYe234/xcodec/blob/main/config_hubert_general.yaml) | 4.0 | 2.68 | 0.63 | 1.66 | 0.66 |\n| [CosyVoice 2](https://huggingface.co/FunAudioLLM/CosyVoice2-0.5B) | - | 3.17 | 0.65 | 2.11 | 0.70 |\n| [XCodec2](https://huggingface.co/HKUST-Audio/xcodec2/blob/main/ckpt/epoch%3D4-step%3D1400000.ckpt) | 0.8 | 2.74 | 0.62 | 1.91 | 0.67 |\n| [XY-MOSS-TTSD](https://huggingface.co/fnlp/XY_Tokenizer_TTSD_V0/tree/main) | 1.0 | 2.72 | 0.61 | 1.58 | 0.67 |\n| Ours | 2.0 | 2.52 | 0.67 | **1.48** | 0.71 |\n\n\n\n### Audiobox Aesthetics Evaluation\n\nThis model based evaluation[8] further demonstrates the superiority of our tokenizer. CU is the Content Usefulness and CE is the Content Enjoyment. Each term is rated on a scale of 1-10. Notably, our tokenizer performs best on the Audiophile set—demonstrating a clear advantage when the original audio quality is high.\n\n\n| Model | BPS (k) | Music CE ↑ | Music CU ↑ | Sound Event CE ↑ | Sound Event CU ↑ | Speech CE ↑ | Speech CU ↑ | Audiophile CE ↑ | Audiophile CU ↑ |\n|------------------|---------|--------------|--------------|--------------------|--------------------|---------------|---------------|--------------------|--------------------|\n| Origin | - | 6.20 | 7.10 | 4.47 | 5.64 | 5.03 | 4.87 | 7.17 | 7.65 |\n| [SpeechTokenizer](https://huggingface.co/fnlp/SpeechTokenizer/tree/main/speechtokenizer_hubert_avg) | 4.0 | 3.55 | 5.22 | 3.03 | 4.50 | 4.68 | 4.58 | 3.59 | 5.07 |\n| [SemantiCodec](https://huggingface.co/haoheliu/SemantiCodec/tree/main/semanticodec_tokenrate_100) | 1.4 | 6.01 | 6.83 | 4.22 | 5.30 | 4.28 | 4.12 | 6.97 | 7.43 |\n| [Mimi](https://huggingface.co/docs/transformers/en/model_doc/mimi) | 4.4 | 6.01 | 6.83 | 4.26 | 5.35 | 4.87 | 4.72 | 6.80 | 7.29 |\n| [XCodec](https://huggingface.co/ZhenYe234/xcodec/blob/main/config_hubert_general.yaml) | 4.0 | **6.30** | **7.10** | **4.43** | 5.45 | **4.96** | **4.79** | 7.06 | 7.49 |\n| [CosyVoice 2](https://huggingface.co/FunAudioLLM/CosyVoice2-0.5B) | - | 5.21 | 6.14 | 4.08 | 4.73 | **4.91** | **4.75** | 5.97 | 6.56 |\n| [XCodec2](https://huggingface.co/HKUST-Audio/xcodec2/blob/main/ckpt/epoch%3D4-step%3D1400000.ckpt) | 0.8 | 4.38 | 5.66 | 3.43 | 4.63 | **4.93** | **4.78** | 4.56 | 5.46 |\n| [XY-MOSS-TTSD](https://huggingface.co/fnlp/XY_Tokenizer_TTSD_V0/tree/main) | 1.0 | 5.77 | 6.80 | 4.23 | 5.34 | 4.88 | 4.72 | 6.95 | 7.48 |\n| Ours | 2.0 | **6.35** | **7.15** | **4.47** | **5.51** | 4.90 | 4.70 | **7.21** | **7.66** |\n\n\n\nNote that since some tokenizers are trained on 16 kHz data, we upsample their audio outputs to 24 kHz before computing metrics. Different upsampling methods may cause slight variations (e.g., 4.36 vs. 4.43 for XCodec Sound Event CE). We report the best results we could obtain and highlight any results within 0.05 of the best one. \n\n\n\n\n\n\n\n<!-- xcodec [1]\ndac [2]\nencodec [3]\nmoshi [4]\nsemanticodec [5]\nsnac [6]\nwavtokenizer [7]\nxcodec [8]\nxcodec2 [9]\nxy-tokenizer [10]\nmucodec [11]\nflowdec [12]\ncosyvoice2 [13]\nspeechtokenizer [14] -->\n\n\n\n\n## Reference \n[1] [Ye, Zhen, et al. \"Codec does matter: Exploring the semantic shortcoming of codec for audio language model.\" Proceedings of the AAAI Conference on Artificial Intelligence. Vol. 39. No. 24. 2025.](https://arxiv.org/abs/2408.17175)\n\n[2] [Kumar, Rithesh, et al. \"High-fidelity audio compression with improved rvqgan.\" Advances in Neural Information Processing Systems 36 (2023): 27980-27993.](https://dl.acm.org/doi/10.5555/3666122.3667336)\n\n[3] [Défossez, Alexandre, et al. \"High fidelity neural audio compression.\" arXiv preprint arXiv:2210.13438 (2022).](https://arxiv.org/abs/2210.13438)\n\n[4] [Défossez, Alexandre, et al. \"Moshi: a speech-text foundation model for real-time dialogue.\" arXiv preprint arXiv:2410.00037 (2024).](https://arxiv.org/abs/2410.00037)\n\n[5] [Liu, Haohe, et al. \"Semanticodec: An ultra low bitrate semantic audio codec for general sound.\" IEEE Journal of Selected Topics in Signal Processing (2024).](https://ieeexplore.ieee.org/document/10768970)\n\n[6] [Siuzdak, Hubert, Florian Grötschla, and Luca A. Lanzendörfer. \"Snac: Multi-scale neural audio codec.\" arXiv preprint arXiv:2410.14411 (2024).](https://arxiv.org/abs/2410.14411)\n\n[7] [Ji, Shengpeng, et al. \"Wavtokenizer: an efficient acoustic discrete codec tokenizer for audio language modeling.\" arXiv preprint arXiv:2408.16532 (2024).](https://arxiv.org/abs/2408.16532)\n\n[8] [Tjandra, Andros, et al. \"Meta audiobox aesthetics: Unified automatic quality assessment for speech, music, and sound.\" arXiv preprint arXiv:2502.05139 (2025).](https://arxiv.org/abs/2502.05139)\n\n[9] [Ye, Zhen, et al. \"Llasa: Scaling Train-Time and Inference-Time Compute for Llama-based Speech Synthesis.\" arXiv preprint arXiv:2502.04128 (2025).](https://arxiv.org/abs/2502.04128)\n\n[10] [Gong, Yitian, et al. \"XY-Tokenizer: Mitigating the Semantic-Acoustic Conflict in Low-Bitrate Speech Codecs.\" arXiv preprint arXiv:2506.23325 (2025).](https://arxiv.org/abs/2506.23325)\n\n[11] [Xu, Yaoxun, et al. \"MuCodec: Ultra Low-Bitrate Music Codec.\" arXiv preprint arXiv:2409.13216 (2024).](https://arxiv.org/abs/2409.13216)\n\n[12] [Welker, Simon, et al. \"FlowDec: A flow-based full-band general audio codec with high perceptual quality.\" arXiv preprint arXiv:2503.01485 (2025).](https://arxiv.org/abs/2503.01485)\n\n[13] [Du, Zhihao, et al. \"Cosyvoice 2: Scalable streaming speech synthesis with large language models.\" arXiv preprint arXiv:2412.10117 (2024).](https://arxiv.org/abs/2412.10117)\n\n[14] [Zhang, Xin, et al. \"Speechtokenizer: Unified speech tokenizer for speech large language models.\" arXiv preprint arXiv:2308.16692 (2023).](https://arxiv.org/abs/2308.16692)\n\n[15] [Anastassiou, Philip, et al. \"Seed-tts: A family of high-quality versatile speech generation models.\" arXiv preprint arXiv:2406.02430 (2024).](https://arxiv.org/abs/2406.02430)\n"
  }
]