drama3-expressive-medium: IQ4_XS GGUF, pause-fix codes, audio.cpp patch, PyTorch runtime, samples (generated voice)
Browse files- .gitattributes +12 -0
- LICENSE +114 -0
- README.md +207 -0
- SHA256SUMS +42 -0
- drama3-expressive-medium-IQ4_XS.gguf +3 -0
- drama3-expressive-medium-audiocpp-optional.patch +268 -0
- postprocess.py +55 -0
- samples/en_bored_shock.mp3 +3 -0
- samples/en_same_anger.mp3 +0 -0
- samples/en_same_joy.mp3 +3 -0
- samples/en_same_tears.mp3 +0 -0
- samples/en_same_whisper.mp3 +0 -0
- samples/en_tears_joy.mp3 +3 -0
- samples/en_whisper_shout.mp3 +3 -0
- samples/ja_bored_shock.mp3 +3 -0
- samples/ja_joy_tears.mp3 +3 -0
- samples/ja_same_anger.mp3 +3 -0
- samples/ja_same_joy.mp3 +3 -0
- samples/ja_same_tears.mp3 +3 -0
- samples/ja_same_whisper.mp3 +3 -0
- samples/ja_whisper_shout.mp3 +3 -0
- silence_codes.json +1 -0
- torch/LICENSE +114 -0
- torch/README_torch.md +202 -0
- torch/drama3_gguf.py +459 -0
- torch/fish_speech/VENDOR.md +30 -0
- torch/fish_speech/__init__.py +0 -0
- torch/fish_speech/models/__init__.py +0 -0
- torch/fish_speech/models/dac/__init__.py +0 -0
- torch/fish_speech/models/dac/modded_dac.py +473 -0
- torch/fish_speech/models/dac/rvq.py +184 -0
- torch/fish_speech/models/text2semantic/__init__.py +0 -0
- torch/fish_speech/models/text2semantic/errors.py +5 -0
- torch/fish_speech/models/text2semantic/fish_omni/__init__.py +0 -0
- torch/fish_speech/models/text2semantic/fish_omni/backbone.py +258 -0
- torch/fish_speech/models/text2semantic/fish_omni/config.py +254 -0
- torch/fish_speech/models/text2semantic/fish_omni/generate.py +686 -0
- torch/fish_speech/models/text2semantic/fish_omni/layers.py +410 -0
- torch/fish_speech/models/text2semantic/fish_omni/moe.py +155 -0
- torch/fish_speech/models/text2semantic/fish_omni/tower.py +423 -0
- torch/fish_speech/models/text2semantic/sampling.py +9 -0
- torch/gguf_kernels.py +263 -0
- torch/infer.py +290 -0
- torch/requirements.txt +9 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,15 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
drama3-expressive-medium-IQ4_XS.gguf filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
samples/en_bored_shock.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
samples/en_same_joy.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
samples/en_tears_joy.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
samples/en_whisper_shout.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
samples/ja_bored_shock.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
samples/ja_joy_tears.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
samples/ja_same_anger.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
samples/ja_same_joy.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
samples/ja_same_tears.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
samples/ja_same_whisper.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
samples/ja_whisper_shout.mp3 filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FISH AUDIO COMMUNITY LICENSE AGREEMENT
|
| 2 |
+
|
| 3 |
+
**Version 1.0 — Last Updated: October 13, 2026**
|
| 4 |
+
|
| 5 |
+
## I. INTRODUCTION
|
| 6 |
+
|
| 7 |
+
This Agreement applies to any individual person or entity ("You", "Your" or "Licensee") that uses or distributes any portion or element of the Fish Audio Materials or Derivative Works thereof for any Research, Non-Commercial, or Commercial purpose. Capitalized terms not otherwise defined herein are defined in Section V below.
|
| 8 |
+
|
| 9 |
+
This Agreement is intended to allow, free of charge, research and non-commercial uses of the Fish Audio Materials and, as set out in Section III, limited uses for a Commercial Purpose by Licensees whose Annual Revenue is less than the Revenue Threshold. Any other use of the Fish Audio Materials for a Commercial Purpose, and any Hosted Service, requires a separate written license agreement from Fish Audio.
|
| 10 |
+
|
| 11 |
+
By clicking "I Accept" or by using, distributing, or accessing any portion or element of the Fish Audio Materials or Derivative Works, You agree that You have read, understood and are bound by the terms of this Agreement. If You are acting on behalf of a company, organization or other entity, then "You" includes you and that entity, and You agree that You: (i) are an authorized representative of such entity with the authority to bind such entity to this Agreement, and (ii) You agree to the terms of this Agreement on that entity's behalf.
|
| 12 |
+
|
| 13 |
+
## II. RESEARCH & NON-COMMERCIAL USE LICENSE
|
| 14 |
+
|
| 15 |
+
Subject to the terms of this Agreement, Fish Audio grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Fish Audio's intellectual property or other rights owned by Fish Audio embodied in the Fish Audio Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Fish Audio Materials for any Research or Non-Commercial Purpose.
|
| 16 |
+
|
| 17 |
+
"Research Purpose" means academic or scientific advancement, and in each case, is not primarily intended for commercial advantage or monetary compensation to You or others.
|
| 18 |
+
|
| 19 |
+
"Non-Commercial Purpose" means any purpose other than a Research Purpose that is not primarily intended for commercial advantage or monetary compensation to You or others, such as personal use (i.e., hobbyist) or evaluation and testing.
|
| 20 |
+
|
| 21 |
+
## III. COMMERCIAL USE
|
| 22 |
+
|
| 23 |
+
**(a) Community Commercial License.** Subject to the terms of this Agreement (including Sections III(b) through III(d)), Fish Audio grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Fish Audio's intellectual property or other rights owned by Fish Audio embodied in the Fish Audio Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Fish Audio Materials for a Commercial Purpose, but only while Your Annual Revenue is less than USD 500,000 (the "Revenue Threshold").
|
| 24 |
+
|
| 25 |
+
"Annual Revenue" means, as of any date, the total gross revenue of You and Your Affiliates, in aggregate, from all sources (whether or not derived from the Fish Audio Materials or Derivative Works) for the twelve (12) months ending on that date, with amounts in other currencies converted into U.S. dollars at a published market exchange rate in effect on that date. If You deploy, install, host, or operate the Fish Audio Materials or Derivative Works for a particular third party, or deliver a copy of them to a third party, for use in that third party's products, services, or internal operations (for example, as a contractor, integrator, consultant, or on-premises vendor), the license in this Section III(a) extends to that work only if that third party's Annual Revenue, calculated as if that third party were You, is also less than the Revenue Threshold. This does not apply to (1) delivering to a third party only output (such as audio files) that You generate Yourself, for example as an agency, studio, or freelancer producing voiceovers, dubbing, or audiobooks for a client, or (2) providing Your own generally available product or service to customers or end users who do not receive a copy of the Fish Audio Materials or Derivative Works; such customers and end users do not need to meet the Revenue Threshold for that use.
|
| 26 |
+
|
| 27 |
+
**(b) Reaching the Revenue Threshold.** If, while You are using the Fish Audio Materials or Derivative Works under Section III(a), Your Annual Revenue reaches or exceeds the Revenue Threshold (the date it first does so, the "Threshold Date"), You must notify Fish Audio in writing at business@fish.audio within thirty (30) days after the Threshold Date. Notwithstanding Section III(a), the license in Section III(a) continues to apply to the uses for a Commercial Purpose that You were making on the Threshold Date for ninety (90) days after the Threshold Date (the "Transition Period"). After the Transition Period, any use for a Commercial Purpose requires a separate written license agreement from Fish Audio; however, if Your Annual Revenue later falls below the Revenue Threshold, Section III(a) applies to You again from that date. Reaching the Revenue Threshold is not a breach of this Agreement and does not affect Your license under Section II or Your ownership of outputs under Section IV(c)(iii).
|
| 28 |
+
|
| 29 |
+
**(c) Hosted Services.** Notwithstanding Sections II and III(a) and the definition of Commercial Purpose, and regardless of Your purpose or Annual Revenue, no license is granted under this Agreement to offer a Hosted Service, which requires a separate written license agreement from Fish Audio. "Hosted Service" means making the Fish Audio Materials or Derivative Works available to third parties so that they can generate speech or other audio from text, audio, or voice samples that they supply, whether through an application programming interface, software development kit, model-inference or model-hosting service, or a website, application, or feature whose primary purpose is text-to-speech, voiceover, voice generation, or voice cloning. None of the following is a Hosted Service: (1) generating speech for content that You create, select, or control, or that Your own product generates (for example, narration, dubbing, game or app characters, or an assistant's spoken replies), and delivering that speech in or with Your products or services; (2) a production service in which You operate the Fish Audio Materials or Derivative Works, direct each generation, and deliver only finished output to Your client (for example, as an agency, studio, or freelancer producing voiceovers, dubbing, or audiobooks), without giving the client self-serve or automated access; or (3) a free, non-commercial research or demonstration service (for example, a Hugging Face Space, a research demo, or a shared server for a research group) that is not monetized and is not offered or promoted as a production service or API.
|
| 30 |
+
|
| 31 |
+
**(d) Other Commercial Use.** **Any use of the Fish Audio Materials or Derivative Works for a Commercial Purpose that is not licensed under Section III(a) (including as continued under Section III(b)) requires a separate written license agreement from Fish Audio.**
|
| 32 |
+
|
| 33 |
+
"Commercial Purpose" means any purpose other than a Research Purpose or Non-Commercial Purpose that is primarily intended for or directed toward commercial advantage or monetary compensation to You or others, including but not limited to: (i) creating, modifying, or distributing Your product or service, including via a hosted service or application programming interface, (ii) Your business's or organization's internal operations, and (iii) any use in connection with a product or service for which You charge a fee or generate revenue, whether directly or indirectly.
|
| 34 |
+
|
| 35 |
+
To obtain a commercial license, please contact Fish Audio at:
|
| 36 |
+
|
| 37 |
+
- **Website:** [https://fish.audio](https://fish.audio)
|
| 38 |
+
- **Email:** business@fish.audio
|
| 39 |
+
|
| 40 |
+
## IV. GENERAL TERMS
|
| 41 |
+
|
| 42 |
+
All licenses granted under this Agreement, including Your Research, Non-Commercial, and Commercial licenses, are subject to the following terms.
|
| 43 |
+
|
| 44 |
+
### a. Distribution & Attribution
|
| 45 |
+
|
| 46 |
+
If You distribute a copy of the Fish Audio Materials or a Derivative Work to a third party, You shall (i) provide a copy of this Agreement to that third party, and (ii) retain the following attribution notice within a "Notice" text file distributed as a part of such copies: "These Fish Audio Materials are licensed under the Fish Audio Community License, Version 1.0. Copyright © 39 AI, INC. All Rights Reserved." If You distribute or make available the Fish Audio Materials or a Derivative Work, or a product or service that uses any portion of them, You shall prominently display "Built with Fish Audio" on a related website, user interface, blogpost, about page, or product documentation.
|
| 47 |
+
|
| 48 |
+
If You create a Derivative Work, You may add your own attribution notice(s) to the "Notice" text file included with that Derivative Work, provided that You clearly indicate which attributions apply to the Fish Audio Materials and state in the "Notice" text file that You changed the Fish Audio Materials and how it was modified.
|
| 49 |
+
|
| 50 |
+
### b. Use Restrictions
|
| 51 |
+
|
| 52 |
+
Your use of the Fish Audio Materials and Derivative Works, including any output or results of the Fish Audio Materials or Derivative Works, must comply with applicable laws and regulations (including Trade Control Laws and equivalent regulations).
|
| 53 |
+
|
| 54 |
+
You will not use the Fish Audio Materials or Derivative Works, or any output or results of the Fish Audio Materials or Derivative Works, to: (i) generate speech that imitates the voice of an identifiable natural person without that person's prior consent (or, for a minor, the consent of a parent or legal guardian, and for a deceased person, the consent of the holder of the relevant rights) or another legal right to do so; (ii) impersonate any person or organization in order to deceive, defraud, or harass, or to place calls in violation of applicable telemarketing or robocall laws; (iii) generate sexual content involving a minor or a voice presented as a minor's, or using the voice of any real person without that person's consent; or (iv) intentionally remove, disable, circumvent, or obscure any watermark or provenance signal applied by the Fish Audio Materials (ordinary editing, mixing, compression, or format conversion of output that is not intended to remove such a signal is not a breach of this clause (iv)). You will not distribute any tool, Derivative Work, or service designed to remove, disable, circumvent, or obscure any such watermark or provenance signal. If You make voice cloning or other speech generation using the Fish Audio Materials or Derivative Works available to third parties, You must bind them, by enforceable terms, to restrictions at least as protective as those in this Section IV(b).
|
| 55 |
+
|
| 56 |
+
Furthermore, You will not use the Fish Audio Materials or Derivative Works, or any output or results of the Fish Audio Materials or Derivative Works, to create, train, distill, or improve any foundational generative AI model or any speech, audio, or voice generation model (excluding the Models or Derivative Works). This does not restrict training models solely to detect synthetic audio, verify watermarks, or prevent spoofing.
|
| 57 |
+
|
| 58 |
+
### c. Intellectual Property
|
| 59 |
+
|
| 60 |
+
**(i) Trademark License.** No trademark licenses are granted under this Agreement. In connection with the Fish Audio Materials or Derivative Works, You may not use any name or mark owned by or associated with Fish Audio or any of its Affiliates, except (A) as required under Section IV(a), and (B) to make truthful, factual references to Fish Audio and the Models, including naming a Derivative Work model in a way that identifies its origin (for example, "Drama-3-GGUF" or "based on Fish Audio Drama 3"), provided that You do not use any Fish Audio logo, do not use a Fish Audio name or mark as the name of Your company or of any product or service other than such a Derivative Work model, and do not state or imply that Fish Audio sponsors, endorses, or officially released You, Your products, or Your Derivative Works.
|
| 61 |
+
|
| 62 |
+
**(ii) Ownership of Derivative Works.** As between You and Fish Audio, You are the owner of Derivative Works You create, subject to Fish Audio's ownership of the Fish Audio Materials and any Derivative Works made by or for Fish Audio.
|
| 63 |
+
|
| 64 |
+
**(iii) Ownership of Outputs.** As between You and Fish Audio, You own any outputs generated from the Models or Derivative Works to the extent permitted by applicable law.
|
| 65 |
+
|
| 66 |
+
**(iv) Disputes.** If You or Your Affiliate(s) institute litigation or other proceedings against Fish Audio (including a cross-claim or counterclaim in a lawsuit) alleging that the Fish Audio Materials, Derivative Works or associated outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by You, then any licenses granted to You under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Fish Audio from and against any claim by any third party arising out of or related to Your use or distribution of the Fish Audio Materials or Derivative Works in violation of this Agreement.
|
| 67 |
+
|
| 68 |
+
**(v) Feedback.** From time to time, You may provide Fish Audio with verbal and/or written suggestions, comments or other feedback related to Fish Audio's existing or prospective technology, products or services (collectively, "Feedback"). You are not obligated to provide Fish Audio with Feedback, but to the extent that You do, You hereby grant Fish Audio a perpetual, irrevocable, royalty-free, fully-paid, sub-licensable, transferable, non-exclusive, worldwide right and license to exploit the Feedback in any manner without restriction. Your Feedback is provided "AS IS" and You make no warranties whatsoever about any Feedback.
|
| 69 |
+
|
| 70 |
+
### d. Disclaimer of Warranty
|
| 71 |
+
|
| 72 |
+
UNLESS REQUIRED BY APPLICABLE LAW, THE FISH AUDIO MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OR LAWFULNESS OF USING OR REDISTRIBUTING THE FISH AUDIO MATERIALS, DERIVATIVE WORKS OR ANY OUTPUT OR RESULTS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE FISH AUDIO MATERIALS, DERIVATIVE WORKS AND ANY OUTPUT AND RESULTS.
|
| 73 |
+
|
| 74 |
+
### e. Limitation of Liability
|
| 75 |
+
|
| 76 |
+
IN NO EVENT WILL FISH AUDIO OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF FISH AUDIO OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
|
| 77 |
+
|
| 78 |
+
### f. Term and Termination
|
| 79 |
+
|
| 80 |
+
The term of this Agreement will commence upon Your acceptance of this Agreement or access to the Fish Audio Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Fish Audio may terminate this Agreement by written notice to You if You breach any term or condition of this Agreement and, if the breach is capable of cure, You do not cure it within thirty (30) days after Fish Audio's written notice describing the breach. If You breach Section IV(b), this Agreement and all licenses granted to You under it terminate automatically, without notice or cure period. Upon termination of this Agreement, You shall delete and cease use of any Fish Audio Materials or Derivative Works. Sections IV(b) (as it applies to any output or results of the Fish Audio Materials or Derivative Works that You retain), IV(c)(iii), IV(c)(iv), IV(c)(v), IV(d), IV(e), IV(g) and V shall survive the termination of this Agreement.
|
| 81 |
+
|
| 82 |
+
### g. Governing Law
|
| 83 |
+
|
| 84 |
+
This Agreement will be governed by and construed in accordance with the laws of the United States and the State of California without regard to choice of law principles, and the UN Convention on Contracts for International Sale of Goods does not apply to this Agreement.
|
| 85 |
+
|
| 86 |
+
### h. Versions
|
| 87 |
+
|
| 88 |
+
Fish Audio may publish revised versions of the Fish Audio Community License, each identified by a version number. Fish Audio Materials are licensed under the version with which Fish Audio released them, as stated in the license file accompanying them or on Fish Audio's official model page for them. A revised version applies only to Fish Audio Materials that Fish Audio releases or designates under it, and does not reduce the rights You hold under the version You received. You may elect to use Fish Audio Materials under a later version that Fish Audio designates as applicable to them.
|
| 89 |
+
|
| 90 |
+
### i. Separate Agreements
|
| 91 |
+
|
| 92 |
+
If You and Fish Audio have signed a separate written agreement covering the Fish Audio Materials, that agreement governs to the extent it conflicts with this Agreement.
|
| 93 |
+
|
| 94 |
+
## V. DEFINITIONS
|
| 95 |
+
|
| 96 |
+
**"Affiliate(s)"** means any entity that directly or indirectly controls, is controlled by, or is under common control with the subject entity; for purposes of this definition, "control" means direct or indirect ownership or control of more than 50% of the voting interests of the subject entity.
|
| 97 |
+
|
| 98 |
+
**"Agreement"** means this Fish Audio Community License Agreement, Version 1.0 (also referred to as the "Fish Audio Community License, Version 1.0" or "FACL v1.0").
|
| 99 |
+
|
| 100 |
+
**"Annual Revenue"** and **"Revenue Threshold"** have the meanings given in Section III(a), and **"Hosted Service"** has the meaning given in Section III(c).
|
| 101 |
+
|
| 102 |
+
**"Derivative Work(s)"** means (a) any derivative work of the Fish Audio Materials as recognized by U.S. copyright laws and (b) any modification of a Model, including any model initialized from all or part of a Model's weights (such as fine-tuned, quantized, merged, and low-rank adaptation ("LoRA") models), whether or not it was trained using output of a Model or Derivative Work. Derivative Works do not include the output of any Model or Derivative Work, or any other model trained or distilled using such output.
|
| 103 |
+
|
| 104 |
+
**"Documentation"** means any specifications, manuals, model cards, documentation, and other written information that Fish Audio makes available under this Agreement related to the Software or Models.
|
| 105 |
+
|
| 106 |
+
**"Fish Audio"** or **"we"** means 39 AI, INC. and its Affiliates.
|
| 107 |
+
|
| 108 |
+
**"Model(s)"** means the machine-learning models, including trained model weights and other elements of the foregoing, that Fish Audio makes available under this Agreement, including Fish Audio Drama 3 and, solely for use with Fish Audio Drama 3 and its Derivative Works, the audio codec that Fish Audio provides for use with Fish Audio Drama 3 (including the copy of that codec distributed with Fish Audio S2-Pro).
|
| 109 |
+
|
| 110 |
+
**"Software"** means Fish Audio's proprietary software made available under this Agreement now or in the future, including the Fish Speech source code (https://github.com/fishaudio/fish-speech).
|
| 111 |
+
|
| 112 |
+
**"Fish Audio Materials"** means, collectively, the Models, Software and Documentation (and any portion or combination thereof) made available under this Agreement. Model weights that Fish Audio makes available under a different license (for example, the Fish Audio S2-Pro weights under the Fish Audio Research License) are not Fish Audio Materials, even if the Software can run them, except as stated in the definition of Model(s) for the audio codec.
|
| 113 |
+
|
| 114 |
+
**"Trade Control Laws"** means any applicable U.S. and non-U.S. export control and trade sanctions laws and regulations.
|
README.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: fish-audio-community-license-v1.0
|
| 4 |
+
license_link: LICENSE
|
| 5 |
+
base_model: fishaudio/drama-3
|
| 6 |
+
base_model_relation: finetune
|
| 7 |
+
language:
|
| 8 |
+
- ja
|
| 9 |
+
- en
|
| 10 |
+
pipeline_tag: text-to-speech
|
| 11 |
+
tags:
|
| 12 |
+
- gguf
|
| 13 |
+
- text-to-speech
|
| 14 |
+
- voice-cloning
|
| 15 |
+
- emotion
|
| 16 |
+
- expressive
|
| 17 |
+
- moe
|
| 18 |
+
- quantization
|
| 19 |
+
- japanese
|
| 20 |
+
- audio.cpp
|
| 21 |
+
---
|
| 22 |
+
|
| 23 |
+
# drama3-expressive-medium: Fish Audio Drama 3 that follows acting directions mid-line, in 24 GB
|
| 24 |
+
|
| 25 |
+
**Built From Fish Audio.** This is a fine-tuned and quantized derivative of [Fish Audio Drama 3](https://huggingface.co/fishaudio/drama-3). Fish Audio does not sponsor or endorse it.
|
| 26 |
+
|
| 27 |
+
Drama 3 follows an acting direction at the start of a line, but it mostly ignores one placed in the middle: `[calm] It's fine, really. [voice breaking] I just miss her.` tends to stay calm, or to go silent at the second direction. drama3-expressive-medium was fine-tuned to change delivery where the direction says. It also speaks the whole line and ends cleanly far more often. It keeps all 256 experts and runs in 24 GB of VRAM.
|
| 28 |
+
|
| 29 |
+
| | |
|
| 30 |
+
|---|---|
|
| 31 |
+
| File | `drama3-expressive-medium-IQ4_XS.gguf`, 20.97 GiB |
|
| 32 |
+
| VRAM | Peak 21.9 GiB on an RTX 4090 (30 s uncached reference, 32 s long-form output, streaming or offline with the optional patch) |
|
| 33 |
+
| Speed | About 2.6× real time on an RTX 4090, including encoding the 29 s reference |
|
| 34 |
+
| Languages | Japanese, English (directions are written in English for both) |
|
| 35 |
+
| Features | Zero-shot cloning from about 10–30 s of reference audio, or a voice made up per seed with no reference; inline acting directions at the start of a line and mid-line |
|
| 36 |
+
| Runtime | [audio.cpp](https://github.com/0xShug0/audio.cpp) `main` at `71f42b84` or later (CUDA); the optional `drama3-expressive-medium-audiocpp-optional.patch` adds the pause fix and low-VRAM offline decoding. Or the standalone PyTorch runtime in `torch/` (GGUF only, 23.1 GiB on a 4090) |
|
| 37 |
+
|
| 38 |
+
## Samples
|
| 39 |
+
|
| 40 |
+
No reference audio: each sample's seed makes up its own voice, speaking the line's language (`--task tts` with no `voice_ref`). The first table keeps the words fixed and changes only the opening direction; the second changes the delivery mid-line.
|
| 41 |
+
|
| 42 |
+
- **Voices:** none is cloned from a recording. By speaker-verification similarity (WavLM-SV), no sample is closer to a fine-tuning speaker than 95% of the fine-tuning speakers are to their nearest other speaker.
|
| 43 |
+
- **Runtime:** audio.cpp `71f42b84` with the optional patch.
|
| 44 |
+
- **Settings:** temperature 0.7, top-p 0.7, top-k 30, pause fix on with this repo's `silence_codes.json`.
|
| 45 |
+
- **Processing:** loudness-normalized per take, so a whispered take plays at about the level of the others, with 0.1 s of silence added at each end. Nothing else.
|
| 46 |
+
|
| 47 |
+
**Same line, four directions** (a different voice in each take; seeds: English 9079, 9035, 9047, 9083; Japanese 9080, 9062, 9070, 9077)
|
| 48 |
+
|
| 49 |
+
| Direction | `You knew. You knew the whole time.` | `うそでしょ…本当にやったの?信じられない。` |
|
| 50 |
+
|---|---|---|
|
| 51 |
+
| `[overjoyed, laughing]` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/en_same_joy.mp3"></audio> | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/ja_same_joy.mp3"></audio> |
|
| 52 |
+
| `[furious, shouting]` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/en_same_anger.mp3"></audio> | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/ja_same_anger.mp3"></audio> |
|
| 53 |
+
| `[heartbroken, crying]` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/en_same_tears.mp3"></audio> | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/ja_same_tears.mp3"></audio> |
|
| 54 |
+
| `[terrified, whispering]` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/en_same_whisper.mp3"></audio> | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/ja_same_whisper.mp3"></audio> |
|
| 55 |
+
|
| 56 |
+
**Mid-line changes**
|
| 57 |
+
|
| 58 |
+
| Sample | Prompt | Audio |
|
| 59 |
+
|---|---|---|
|
| 60 |
+
| JA, whisper → shout, seed 9086 | `[whispering, scared] ねえ、静かにして。誰かいる…[shouting, furious] ちょっと!人の部屋で何してるの!` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/ja_whisper_shout.mp3"></audio> |
|
| 61 |
+
| JA, laughing → crying, seed 9153 | `[laughing, overjoyed] やった、合格したよ!ずっと頑張ってきたんだ![crying, heartbroken] …でも、一番に伝えたかったおばあちゃんは、もういないんだ。` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/ja_joy_tears.mp3"></audio> |
|
| 62 |
+
| JA, bored → excited, seed 9106 | `[bored, flat monotone] はい、次��方どうぞ。ご用件は…[shocked, screaming with excitement] えっ、うそ、本物!?サインください!` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/ja_bored_shock.mp3"></audio> |
|
| 63 |
+
| EN, whisper → shout, seed 9135 | `[whispering, scared] Shh, keep your voice down. Someone's in the house... [shouting, furious] Hey! Get out of my kitchen!` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/en_whisper_shout.mp3"></audio> |
|
| 64 |
+
| EN, crying → laughing, seed 9122 | `[sobbing, heartbroken] I studied every night, and I still failed... [laughing, overjoyed] Wait, what? I passed? I actually passed!` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/en_tears_joy.mp3"></audio> |
|
| 65 |
+
| EN, bored → excited, seed 9146 | `[bored, monotone] Next, please. Name and ticket number... [shocked, excited] Wait, is that really you? Oh my gosh, can I get a photo?` | <audio controls src="https://huggingface.co/pentacoxian-dev/drama3-expressive-medium-GGUF/resolve/main/samples/en_bored_shock.mp3"></audio> |
|
| 66 |
+
|
| 67 |
+
## Writing directions
|
| 68 |
+
|
| 69 |
+
- Put a direction in square brackets at the start of the line, and another right before the word where the delivery should change: `[cheerful] Good morning! [suddenly worried] Wait, where's my phone?`
|
| 70 |
+
- Write directions in English for Japanese lines too. 2–8 words work best. Lead with the feeling (`angry`, `heartbroken`, `amused`, `nervous`, `tender`), then add how it is voiced if useful (`whispering`, `voice breaking`, `through laughter`, `rushed`).
|
| 71 |
+
- Directions describe delivery only; the model does not speak them.
|
| 72 |
+
|
| 73 |
+
## What changed compared with Drama 3
|
| 74 |
+
|
| 75 |
+
| Part | Drama 3 | drama3-expressive-medium |
|
| 76 |
+
|---|---|---|
|
| 77 |
+
| Routed experts | 256 per layer, FP8 | All 256 kept; IQ4_XS, Q5_K in layers 0/1/2/36, with a speech imatrix (16.4 GiB). Not trained |
|
| 78 |
+
| Attention / Gated DeltaNet, shared experts | BF16 | Fine-tuned (rank-32 LoRA, merged), then Q8_0 |
|
| 79 |
+
| Embeddings, audio tower (MTP) | BF16 | Q8_0 |
|
| 80 |
+
| Output head | Full vocabulary | EOS + 4,096 semantic rows (speech only) |
|
| 81 |
+
| Codec | F16 | F16 (unchanged) |
|
| 82 |
+
|
| 83 |
+
## Training
|
| 84 |
+
|
| 85 |
+
All stages train the same LoRA adapters while the routed experts stay frozen as the shipped IQ4_XS / Q5_K banks, so what was trained is what ships.
|
| 86 |
+
|
| 87 |
+
1. **Supervised fine-tuning on emotional speech.**:
|
| 88 |
+
Every line was given inline acting directions by Qwen3.8-Omni-Flash from the audio, with a calibrated prompt; they were not reviewed by a person. Directions that only repeat the opening's emotion were removed.
|
| 89 |
+
2. **Mid-line contrast.** 2,322 spliced lines: two takes of the same speaker in different emotions, joined at a short pause and kept only where Qwen heard the change. A loss term makes the audio after the splice more likely with the right mid-line direction than with none or a wrong one.
|
| 90 |
+
3. **Recovery.** 3,000 lines with a natural pause stretched to 1–3 s, or silence appended after the last word. The added silence is not scored; resuming the next word and ending the take are.
|
| 91 |
+
4. **Preference optimization (DPO) on the model's own takes.** 4,214 pairs from 4–6 takes each of about 2,660 lines. Preferred: no long pause, no runaway, and following the mid-line directions (judged by Qwen3.8-Omni-Flash). The words must be right in both takes of a pair.
|
| 92 |
+
|
| 93 |
+
Throughout, 25% of each batch distills the original FP8 Drama 3 on plain Japanese and English speech, to keep ordinary speech close to the original.
|
| 94 |
+
|
| 95 |
+
## Evaluation
|
| 96 |
+
|
| 97 |
+
All numbers use one take per line, sampling as above, audio.cpp `71f42b84` with the optional patch and the pause fix on, and Qwen3.8-Omni-Flash as an automatic judge. **The judge under-detects audible changes:** the repo owner heard mid-line changes in takes where the judge did not.
|
| 98 |
+
|
| 99 |
+
**Mid-line directions, held-out test.** 178 two-part lines, mostly from speakers not seen in training. "Requested delivery" = after the second direction, the judge hears a delivery with the same emotion as the direction asked for. Each cell is with the mid-line direction / without it; the gain is the difference.
|
| 100 |
+
|
| 101 |
+
| Model | Requested delivery (gain) | Second half spoken | Runaway (≥ 20 s) | Pause at the change, median / 90th pct. |
|
| 102 |
+
|---|---|---|---|---|
|
| 103 |
+
| Drama 3 (Q5_K experts) | 21% / 24% (−3) | 68% / 79% | 45% / 29% | |
|
| 104 |
+
| Drama 3, this repo's quantization | 28% / 33% (−5) | 67% / 83% | 40% / 29% | 1.54 / 5.86 s |
|
| 105 |
+
| **drama3-expressive-medium** | **46% / 30% (+16)** | **98% / 100%** | **5% / 3%** | **0.38 / 1.89 s** |
|
| 106 |
+
| Original recordings | | | | 0.64 / 1.53 s |
|
| 107 |
+
|
| 108 |
+
The two Drama 3 rows were rendered with the earlier drama3-small runtime build, without the pause fix.
|
| 109 |
+
|
| 110 |
+
On a separate dev set (120 lines): requested delivery 50% / 35% (+15); runaways 2% / 2%; takes with any pause over 0.7 s 14%, against 17% for the original recordings.
|
| 111 |
+
|
| 112 |
+
**Plain speech.** drama3-small's five listening sets: 172 takes, 7 voices, Japanese and English, tags and long-form. A take fails if it runs on, drops content, or comes out in the wrong voice.
|
| 113 |
+
|
| 114 |
+
| Model | Failures |
|
| 115 |
+
|---|---|
|
| 116 |
+
| Drama 3, this repo's quantization | 27 / 172 |
|
| 117 |
+
| **drama3-expressive-medium** | **7 / 172** |
|
| 118 |
+
|
| 119 |
+
Speaker similarity on takes both models pass is unchanged (median within ±0.002).
|
| 120 |
+
|
| 121 |
+
**Listening.** On 10 random dev lines, the repo owner preferred this model over the untuned quantization on 9 and rated 1 a tie (blind).
|
| 122 |
+
|
| 123 |
+
**Distance from the original on plain speech** (teacher-forced KL over the 4,097 speech candidates, 60 held-out Japanese and English pairs): 0.048, against 0.013 for the untuned quantization.
|
| 124 |
+
|
| 125 |
+
## Usage
|
| 126 |
+
|
| 127 |
+
### audio.cpp (recommended)
|
| 128 |
+
|
| 129 |
+
Build upstream audio.cpp. The optional patch adds the pause fix and decodes offline takes in small batches, so offline mode fits a 24 GB card:
|
| 130 |
+
|
| 131 |
+
```bash
|
| 132 |
+
git clone https://github.com/0xShug0/audio.cpp && cd audio.cpp
|
| 133 |
+
git checkout 71f42b84
|
| 134 |
+
git apply /path/to/drama3-expressive-medium-audiocpp-optional.patch # optional, recommended
|
| 135 |
+
scripts/build_linux.sh --cuda on --models fish_drama3
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Clone a voice from the command line. `requests.json` holds `{"requests": [{"id", "text", "voice_ref", "options": {"reference_text": ...}, "seed", "temperature": 0.7, "top_k": 30, "top_p": 0.7, "max_tokens": 600}]}`. Give the sampling settings explicitly: upstream's defaults (temperature 1.0, top-p 0.9, top-k 4097) were not evaluated with this model.
|
| 139 |
+
|
| 140 |
+
```bash
|
| 141 |
+
AUDIOCPP_DRAMA3_MAX_PAUSE_FRAMES=10 AUDIOCPP_DRAMA3_SILENCE_CODES=silence_codes.json \
|
| 142 |
+
build/linux-cuda-release/bin/audiocpp_cli --task clon --family fish_drama3 --backend cuda --mode offline \
|
| 143 |
+
--model drama3-expressive-medium-IQ4_XS.gguf --request-sequence requests.json --out-dir out \
|
| 144 |
+
--session-option fish_drama3.codec_encoder_chunk_samples=131072 \
|
| 145 |
+
--session-option fish_drama3.cpu_expert_layers=0 --session-option fish_drama3.context_length=4096
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
- **`codec_encoder_chunk_samples=131072`** encodes the reference in chunks. Without it, a 30 s reference runs out of memory on a 24 GB card.
|
| 149 |
+
- **`cpu_expert_layers=0`** keeps all experts on the GPU. Upstream's default of 4 moves some to the CPU.
|
| 150 |
+
- **Without the optional patch:**
|
| 151 |
+
- Use `--mode streaming` on 24 GB cards; offline mode runs out of memory on takes of about 30 s.
|
| 152 |
+
- The pause fix is unavailable, so expect longer pauses than reported here.
|
| 153 |
+
- **With `audiocpp_server`:** pass `"options": {"max_pause_frames": "10", "silence_codes": "silence_codes.json"}` per request.
|
| 154 |
+
- **Long server sessions on 24 GB cards:** over 240 requests in one process the peak reached 22.0 GiB, because upstream's prefill-graph caches grow. Lowering `fish_drama3.backbone_prefill_cache_mb` and `fish_drama3.tower_prefill_cache_mb` from 256 adds headroom; this was not measured.
|
| 155 |
+
|
| 156 |
+
**Pause fix (optional patch).** After `max_pause_frames` consecutive silent frames (10 = 0.47 s), the codes in `silence_codes.json` are masked out of the next draw, so the model has to resume or end. A length guard ends takes that run far past the length expected from the text. This repo's `silence_codes.json` has 247 codes, refit on this model's renders.
|
| 157 |
+
|
| 158 |
+
**Optional clean-up.** The model is about 3.5 dB louder than Drama 3 and leaves a little more room tone between words. `postprocess.py in.wav out.wav --gate` loudness-matches a take and pulls the gaps toward silence.
|
| 159 |
+
|
| 160 |
+
### PyTorch
|
| 161 |
+
|
| 162 |
+
`torch/` runs the model from the GGUF file alone, with no audio.cpp and without the original checkpoint. It contains the vendored Fish Audio model code (Fish Audio Community License), a GGUF reader, and Triton kernels that dequantize the IQ4_XS / Q5_K experts on the fly. The generation loop follows audio.cpp's, including the pause fix and the length guard. Details: `torch/README_torch.md`.
|
| 163 |
+
|
| 164 |
+
```bash
|
| 165 |
+
cd torch && pip install -r requirements.txt # Linux x86_64, CUDA
|
| 166 |
+
python infer.py --gguf ../drama3-expressive-medium-IQ4_XS.gguf \
|
| 167 |
+
--text "[calm] It's fine, really. [voice breaking] I just miss her." \
|
| 168 |
+
--ref-audio voice.wav --ref-text "Transcript of voice.wav." --out take.wav --seed 1
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
| | RTX 4090 (24 GB) |
|
| 172 |
+
|---|---|
|
| 173 |
+
| Peak VRAM | 23.1 GiB, about 0.6 GiB free. Dense weights are kept in bf16; close other GPU programs |
|
| 174 |
+
| Speed | Decoding 62.5 frames/s (2.9× real time); 2.0–2.5× real time per take including prefill and the codec |
|
| 175 |
+
| Fidelity | Teacher-forced KL 0.004 against the training model on 4 held-out sequences. Free-running word error rate and take length match audio.cpp over 45 takes |
|
| 176 |
+
|
| 177 |
+
- **Not the same takes as audio.cpp:** the random number streams differ, so the same seed gives a different take.
|
| 178 |
+
- **Not supported:** CPU inference, streaming output and multiple GPUs. Multiple references and continuation history work from Python (`Drama3TTS`) but not from the CLI.
|
| 179 |
+
|
| 180 |
+
## Limitations
|
| 181 |
+
|
| 182 |
+
- **Runtime:** needs audio.cpp `71f42b84` or later. Not llama.cpp. The pause fix and low-VRAM offline decoding come only with the optional patch, and the numbers above assume it.
|
| 183 |
+
- **Mid-line directions are followed more often, not always.** About half the time on held-out lines, by an automatic judge.
|
| 184 |
+
- **Long pauses remain on some lines.**
|
| 185 |
+
- On held-out lines with a mid-line direction, 28% of takes contain a pause over 0.7 s, against 19% in real recordings.
|
| 186 |
+
- Sad or calm narration can come out slow, with 1–2.5 s pauses.
|
| 187 |
+
- These pauses are quiet breaths or room sound rather than the listed silence codes, so the pause fix does not shorten them.
|
| 188 |
+
- **Takes often start at full level.** In drama3-small's listening sets, 71% of takes reach within 30 dB of their speech level in the first 30 ms (92% for the untuned quantization), so the first syllable can sound clipped.
|
| 189 |
+
- **Directions were labelled automatically.** Qwen3.8-Omni-Flash wrote them; no human reviewed the training labels.
|
| 190 |
+
- **One take per line** in every evaluation above. Treat differences of a few points as noise.
|
| 191 |
+
|
| 192 |
+
## License and acceptable use
|
| 193 |
+
|
| 194 |
+
Licensed under the **Fish Audio Community License v1.0** (see `LICENSE`).
|
| 195 |
+
|
| 196 |
+
Do not use this model or its output to:
|
| 197 |
+
- imitate the voice of an identifiable person without their consent
|
| 198 |
+
- impersonate anyone to deceive, defraud or harass
|
| 199 |
+
- produce sexual content involving minors or non-consenting real people
|
| 200 |
+
- remove watermarks or provenance signals
|
| 201 |
+
|
| 202 |
+
If you offer voice cloning built on this model to others, you must bind them to restrictions at least as protective as these.
|
| 203 |
+
|
| 204 |
+
## Acknowledgements
|
| 205 |
+
|
| 206 |
+
- [Fish Audio Drama 3](https://huggingface.co/fishaudio/drama-3) and its codec.
|
| 207 |
+
- [audio.cpp](https://github.com/0xShug0/audio.cpp) for the runtime, including the i-quant and speech-only-head support contributed for drama3-small (#958, #959).
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
5980f22a07e49ce9f73b79b2d33ad8c22ebcfff49d6abd5b1f48fd1f765c56b5 ./drama3-expressive-medium-audiocpp-optional.patch
|
| 2 |
+
733a32442087acbda12ecafe8e71eb8ee5890c89b50ce7ac4ea3777faa3c823e ./LICENSE
|
| 3 |
+
e29a6e7d78ca37c0aa14b97d64026f9783398a175a9c92f641f929e5cccd0f9c ./postprocess.py
|
| 4 |
+
1148176defda2a93be56d9ceb863bd9d5ad4832d5b57b63090357bd1ee6454c8 ./README.md
|
| 5 |
+
c72ead9edced3384104d7e4cef81de7651833c0be90e03d0799628c141bcfd9f ./samples/en_bored_shock.mp3
|
| 6 |
+
a25bf60d3f0390f5da2f122e48378f6d4e67cb226e6a25251f12bcf0e2a9527a ./samples/en_same_anger.mp3
|
| 7 |
+
fb2977cec2f96059215c1f8216fdf62e4bead0cb2b3fc6ea535537d0b2c692a5 ./samples/en_same_joy.mp3
|
| 8 |
+
33d11a8a9eef50eb74901e25d53330f5efca28027c2a0f51a7bf650f2cad5c91 ./samples/en_same_tears.mp3
|
| 9 |
+
39540dbf369d2b6a30c14e0369f59f5ce91ae0ad96d9d46fa0766a516fede835 ./samples/en_same_whisper.mp3
|
| 10 |
+
d66fee92569d51ca63d60b2d83d22fc46b9c4a7057f6f2fef36464e2a452c30f ./samples/en_tears_joy.mp3
|
| 11 |
+
9f9b1f8189586999e64d0100e1c6ae5009c866c94205bb69b8407bf369c450c6 ./samples/en_whisper_shout.mp3
|
| 12 |
+
e66b921c2c2d78dfbe155ee863fea082b552b83fee4a4f5dfc82c817a71cd7f0 ./samples/ja_bored_shock.mp3
|
| 13 |
+
93ad99bfdec3b900e19a87bb488ece761768c6364e05461e820cff35c11a10eb ./samples/ja_joy_tears.mp3
|
| 14 |
+
9a9f7e4768ced75b6a7fb9baf6f109ecf3a3aa54d19c5d9bc06685d799f64f2e ./samples/ja_same_anger.mp3
|
| 15 |
+
9785bce09396eb329ebd9b862816a7bd51a9966753f04d5b6ff41bbc23955fce ./samples/ja_same_joy.mp3
|
| 16 |
+
84aa38b2d0ac872dcb51e7fefb0b74add6399aeaccef5f5538ff1d3d3d4f3f61 ./samples/ja_same_tears.mp3
|
| 17 |
+
64daf275a4706668768541c276935c32eec3f88364865e059c170c327b85c297 ./samples/ja_same_whisper.mp3
|
| 18 |
+
52fb7a8bcf9a882157782e79f22c1b9eb4b27ab5f1a7a4687eb69b0925b71abb ./samples/ja_whisper_shout.mp3
|
| 19 |
+
9ba43308fc248e66b7a68e72cc94883543dd07823b54a17e8946d9865d3069b4 ./silence_codes.json
|
| 20 |
+
340f330826314f0cddd56dc16a7ddb6e192f6cf047e119fe358258692de3a4ff ./torch/drama3_gguf.py
|
| 21 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./torch/fish_speech/__init__.py
|
| 22 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./torch/fish_speech/models/dac/__init__.py
|
| 23 |
+
3b634087274fa2c115526bc1586da95ed69964d2caf21c02b64df4bbde74f65e ./torch/fish_speech/models/dac/modded_dac.py
|
| 24 |
+
b96d24e186cf64f8fd486fb801400e62c5d95985353bffd6949897e4b8733286 ./torch/fish_speech/models/dac/rvq.py
|
| 25 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./torch/fish_speech/models/__init__.py
|
| 26 |
+
445c7029d965a48640bb583eabcae7ef100c6e7c2786dd320ade4b8fbf11f4d8 ./torch/fish_speech/models/text2semantic/errors.py
|
| 27 |
+
d958bb103c255606ec7a4fdbc06162b7ac9f18aff046d4252d6f8c78c3ca5429 ./torch/fish_speech/models/text2semantic/fish_omni/backbone.py
|
| 28 |
+
99b66eb8d29fcdf0b552f5275c2eadd7b1e4f283f466b7cca9cdbf1dd5d6a074 ./torch/fish_speech/models/text2semantic/fish_omni/config.py
|
| 29 |
+
3b71f1579bf9d16d67c8a9067394ef7ccdc2972e2056724c41ca15ce544a2a31 ./torch/fish_speech/models/text2semantic/fish_omni/generate.py
|
| 30 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./torch/fish_speech/models/text2semantic/fish_omni/__init__.py
|
| 31 |
+
1db82052534ac5b81b8e468286b741bf25edce63d1f8bcd3a7e710b609dcbb2e ./torch/fish_speech/models/text2semantic/fish_omni/layers.py
|
| 32 |
+
6dbf6d73bc134c2ed089e75ded4f67e25e398595a0ec98512b1413bd2fab7d6d ./torch/fish_speech/models/text2semantic/fish_omni/moe.py
|
| 33 |
+
3b619dfc43e9224921eaee813fd19e826b1ff5ff3ca765f390dbaa51128d1417 ./torch/fish_speech/models/text2semantic/fish_omni/tower.py
|
| 34 |
+
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ./torch/fish_speech/models/text2semantic/__init__.py
|
| 35 |
+
bfd045dc2056dd50d3272463816b7dfae8117b00b5055c1385648be83a6c315e ./torch/fish_speech/models/text2semantic/sampling.py
|
| 36 |
+
26b7f786f64b4392cd3c0d0786879f016f74d3f143854b9dd96775565c6cbd14 ./torch/fish_speech/VENDOR.md
|
| 37 |
+
e399f21ac32b930d692860853162b7a798aaa37f0365ee2bfaaf852b1878bbe1 ./torch/gguf_kernels.py
|
| 38 |
+
2b740bfb6191baca90a8c62889dbfb7be24d4202b08ce4e35c4a82da041f54ba ./torch/infer.py
|
| 39 |
+
733a32442087acbda12ecafe8e71eb8ee5890c89b50ce7ac4ea3777faa3c823e ./torch/LICENSE
|
| 40 |
+
36a12ff750833b2fd4be3114e4758d5d34e6ee87e45f4d0d30a3c374d33ee17c ./torch/README_torch.md
|
| 41 |
+
ac6cc4c7fac76f4d827e51f27f138df619b71c774a5f6e32ad974ba8b32a91f0 ./torch/requirements.txt
|
| 42 |
+
ed9913683ce930b90ff31179330468e2896ef954de3c6a3e245b22743536dbec ./drama3-expressive-medium-IQ4_XS.gguf
|
drama3-expressive-medium-IQ4_XS.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ed9913683ce930b90ff31179330468e2896ef954de3c6a3e245b22743536dbec
|
| 3 |
+
size 22512163136
|
drama3-expressive-medium-audiocpp-optional.patch
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/include/engine/community_models/fish_drama3/generator.h b/include/engine/community_models/fish_drama3/generator.h
|
| 2 |
+
index 199422ce..6e88ae72 100644
|
| 3 |
+
--- a/include/engine/community_models/fish_drama3/generator.h
|
| 4 |
+
+++ b/include/engine/community_models/fish_drama3/generator.h
|
| 5 |
+
@@ -1,5 +1,7 @@
|
| 6 |
+
#pragma once
|
| 7 |
+
|
| 8 |
+
+#include <string>
|
| 9 |
+
+
|
| 10 |
+
#include "engine/community_models/fish_drama3/prompt.h"
|
| 11 |
+
#include "engine/framework/runtime/streaming_audio.h"
|
| 12 |
+
|
| 13 |
+
@@ -14,6 +16,11 @@ struct Drama3Sampling {
|
| 14 |
+
int top_k = 4097;
|
| 15 |
+
int64_t max_frames = 1024;
|
| 16 |
+
uint32_t seed = 0;
|
| 17 |
+
+ // Pause clamp (drama3-small / drama3-expressive-medium); unset values fall back to AUDIOCPP_DRAMA3_* env vars.
|
| 18 |
+
+ int64_t max_pause_frames = -1; // -1 unset, 0 off
|
| 19 |
+
+ std::string silence_codes; // list or file path; empty = unset
|
| 20 |
+
+ double pause_end_ratio = 0; // 0 = unset (2.0)
|
| 21 |
+
+ double pause_cap_ratio = 0; // 0 = unset (3.0)
|
| 22 |
+
};
|
| 23 |
+
|
| 24 |
+
struct Drama3Generation {
|
| 25 |
+
diff --git a/model_specs/fish_drama3.json b/model_specs/fish_drama3.json
|
| 26 |
+
index c6e7a7ba..fae01094 100644
|
| 27 |
+
--- a/model_specs/fish_drama3.json
|
| 28 |
+
+++ b/model_specs/fish_drama3.json
|
| 29 |
+
@@ -122,6 +122,33 @@
|
| 30 |
+
"description": "Reproducible native sampling seed.",
|
| 31 |
+
"required": false,
|
| 32 |
+
"min": 0
|
| 33 |
+
+ },
|
| 34 |
+
+ {
|
| 35 |
+
+ "name": "max_pause_frames",
|
| 36 |
+
+ "type": "int",
|
| 37 |
+
+ "description": "Pause clamp: after this many consecutive silence-code frames the next main token must be speech or EOS (21.5 frames = 1 s). 0 disables; unset uses AUDIOCPP_DRAMA3_MAX_PAUSE_FRAMES.",
|
| 38 |
+
+ "required": false,
|
| 39 |
+
+ "min": 0
|
| 40 |
+
+ },
|
| 41 |
+
+ {
|
| 42 |
+
+ "name": "silence_codes",
|
| 43 |
+
+ "type": "string",
|
| 44 |
+
+ "description": "Semantic codes treated as silence for the pause clamp: a comma/space/JSON list or a path to a file holding one. Unset uses AUDIOCPP_DRAMA3_SILENCE_CODES.",
|
| 45 |
+
+ "required": false
|
| 46 |
+
+ },
|
| 47 |
+
+ {
|
| 48 |
+
+ "name": "pause_end_ratio",
|
| 49 |
+
+ "type": "float",
|
| 50 |
+
+ "description": "With the pause clamp: a pause after this multiple of the text's expected frames ends the take (default 2.0).",
|
| 51 |
+
+ "required": false,
|
| 52 |
+
+ "min": 0
|
| 53 |
+
+ },
|
| 54 |
+
+ {
|
| 55 |
+
+ "name": "pause_cap_ratio",
|
| 56 |
+
+ "type": "float",
|
| 57 |
+
+ "description": "With the pause clamp: stop at this multiple of the text's expected frames regardless (default 3.0).",
|
| 58 |
+
+ "required": false,
|
| 59 |
+
+ "min": 0
|
| 60 |
+
}
|
| 61 |
+
],
|
| 62 |
+
"session": [
|
| 63 |
+
diff --git a/src/community_models/fish_drama3/generator.cpp b/src/community_models/fish_drama3/generator.cpp
|
| 64 |
+
index d7ce7d00..d3c61a45 100644
|
| 65 |
+
--- a/src/community_models/fish_drama3/generator.cpp
|
| 66 |
+
+++ b/src/community_models/fish_drama3/generator.cpp
|
| 67 |
+
@@ -6,6 +6,13 @@
|
| 68 |
+
#include "engine/framework/sampling/hf_sampler.h"
|
| 69 |
+
|
| 70 |
+
#include <algorithm>
|
| 71 |
+
+#include <unordered_set>
|
| 72 |
+
+#include <unordered_map>
|
| 73 |
+
+#include <sstream>
|
| 74 |
+
+#include <limits>
|
| 75 |
+
+#include <fstream>
|
| 76 |
+
+#include <cstdlib>
|
| 77 |
+
+#include <cctype>
|
| 78 |
+
#include <array>
|
| 79 |
+
#include <cmath>
|
| 80 |
+
#include <chrono>
|
| 81 |
+
@@ -83,6 +90,96 @@ int32_t sample(const std::vector<float> & logits, float temperature, int top_k,
|
| 82 |
+
return order[choice(random)];
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
+// drama3-small pause clamp (request options max_pause_frames / silence_codes / pause_end_ratio /
|
| 86 |
+
+// pause_cap_ratio, else AUDIOCPP_DRAMA3_* env). After max_pause_frames consecutive silence-code
|
| 87 |
+
+// frames, silence codes are masked from the next main-token draw, so the model must resume speech
|
| 88 |
+
+// or emit EOS (21.5 frames = 1 s). 0 = off.
|
| 89 |
+
+struct PauseClamp {
|
| 90 |
+
+ std::unordered_set<int32_t> codes;
|
| 91 |
+
+ int64_t max_pause = 0;
|
| 92 |
+
+ // Length guard (with the clamp): a pause after end_ratio x the text's expected frames ends the
|
| 93 |
+
+ // take instead of forcing speech; cap_ratio x expected ends it regardless (babble backstop).
|
| 94 |
+
+ double end_ratio = 2.0;
|
| 95 |
+
+ double cap_ratio = 3.0;
|
| 96 |
+
+};
|
| 97 |
+
+
|
| 98 |
+
+// Expected frames for the spoken text, fitted on clean takes (21.5 frames/s):
|
| 99 |
+
+// 3.88 per CJK/kana character + 2.00 per ASCII letter or digit + 23.9 per control span ([...], <...>,
|
| 100 |
+
+// each opening bracket) + 8.5. A "Direction: ...\nLine:" prefix is not spoken.
|
| 101 |
+
+double expected_frames(const std::string & text) {
|
| 102 |
+
+ std::string spoken = text;
|
| 103 |
+
+ if (spoken.rfind("Direction:", 0) == 0) {
|
| 104 |
+
+ const auto line = spoken.find("\nLine:");
|
| 105 |
+
+ if (line != std::string::npos) spoken = spoken.substr(line + 6);
|
| 106 |
+
+ }
|
| 107 |
+
+ double cjk = 0, latin = 0, spans = 0;
|
| 108 |
+
+ int depth_square = 0, depth_angle = 0;
|
| 109 |
+
+ for (size_t i = 0; i < spoken.size();) {
|
| 110 |
+
+ const unsigned char c = static_cast<unsigned char>(spoken[i]);
|
| 111 |
+
+ uint32_t cp = c;
|
| 112 |
+
+ size_t len = 1;
|
| 113 |
+
+ if (c >= 0xF0 && i + 3 < spoken.size()) { cp = ((c & 0x07) << 18) | ((spoken[i + 1] & 0x3F) << 12) | ((spoken[i + 2] & 0x3F) << 6) | (spoken[i + 3] & 0x3F); len = 4; }
|
| 114 |
+
+ else if (c >= 0xE0 && i + 2 < spoken.size()) { cp = ((c & 0x0F) << 12) | ((spoken[i + 1] & 0x3F) << 6) | (spoken[i + 2] & 0x3F); len = 3; }
|
| 115 |
+
+ else if (c >= 0xC0 && i + 1 < spoken.size()) { cp = ((c & 0x1F) << 6) | (spoken[i + 1] & 0x3F); len = 2; }
|
| 116 |
+
+ i += len;
|
| 117 |
+
+ if (cp == '[') { ++depth_square; ++spans; continue; }
|
| 118 |
+
+ if (cp == ']') { if (depth_square > 0) --depth_square; continue; }
|
| 119 |
+
+ if (cp == '<') { ++depth_angle; ++spans; continue; }
|
| 120 |
+
+ if (cp == '>') { if (depth_angle > 0) --depth_angle; continue; }
|
| 121 |
+
+ if (depth_square > 0 || depth_angle > 0) continue;
|
| 122 |
+
+ const bool cjk_punct = cp == 0x3002 || cp == 0x3001 || cp == 0xFF01 || cp == 0xFF1F || cp == 0x300C ||
|
| 123 |
+
+ cp == 0x300D || cp == 0x2026 || cp == 0x30FB || cp == 0xFF08 || cp == 0xFF09;
|
| 124 |
+
+ if (cp >= 0x3000 && !cjk_punct) cjk += 1;
|
| 125 |
+
+ else if (cp < 0x80 && std::isalnum(static_cast<int>(cp))) latin += 1;
|
| 126 |
+
+ }
|
| 127 |
+
+ return 3.88 * cjk + 2.00 * latin + 23.9 * spans + 8.5;
|
| 128 |
+
+}
|
| 129 |
+
+
|
| 130 |
+
+std::unordered_set<int32_t> parse_silence_codes(const std::string & spec) {
|
| 131 |
+
+ static std::mutex mutex;
|
| 132 |
+
+ static std::unordered_map<std::string, std::unordered_set<int32_t>> cache;
|
| 133 |
+
+ std::lock_guard<std::mutex> lock(mutex);
|
| 134 |
+
+ if (const auto it = cache.find(spec); it != cache.end()) return it->second;
|
| 135 |
+
+ std::string text = spec;
|
| 136 |
+
+ if (std::ifstream file(spec); file) {
|
| 137 |
+
+ std::stringstream buffer;
|
| 138 |
+
+ buffer << file.rdbuf();
|
| 139 |
+
+ text = buffer.str();
|
| 140 |
+
+ }
|
| 141 |
+
+ for (char & c : text) {
|
| 142 |
+
+ if (!(c >= '0' && c <= '9')) c = ' ';
|
| 143 |
+
+ }
|
| 144 |
+
+ std::unordered_set<int32_t> codes;
|
| 145 |
+
+ std::istringstream values(text);
|
| 146 |
+
+ for (int32_t code; values >> code;) codes.insert(code);
|
| 147 |
+
+ if (codes.empty()) throw std::runtime_error("Drama 3 silence_codes is empty");
|
| 148 |
+
+ return cache.emplace(spec, std::move(codes)).first->second;
|
| 149 |
+
+}
|
| 150 |
+
+
|
| 151 |
+
+// Request options override the AUDIOCPP_DRAMA3_* environment defaults.
|
| 152 |
+
+PauseClamp resolve_pause_clamp(const Drama3Sampling & sampling) {
|
| 153 |
+
+ PauseClamp clamp;
|
| 154 |
+
+ const char * env_frames = std::getenv("AUDIOCPP_DRAMA3_MAX_PAUSE_FRAMES");
|
| 155 |
+
+ clamp.max_pause = sampling.max_pause_frames >= 0 ? sampling.max_pause_frames
|
| 156 |
+
+ : (env_frames != nullptr ? std::atoll(env_frames) : 0);
|
| 157 |
+
+ if (clamp.max_pause <= 0) {
|
| 158 |
+
+ clamp.max_pause = 0;
|
| 159 |
+
+ return clamp;
|
| 160 |
+
+ }
|
| 161 |
+
+ std::string spec = sampling.silence_codes;
|
| 162 |
+
+ if (spec.empty()) {
|
| 163 |
+
+ const char * env_codes = std::getenv("AUDIOCPP_DRAMA3_SILENCE_CODES");
|
| 164 |
+
+ if (env_codes == nullptr) throw std::runtime_error("Drama 3 pause clamp needs silence_codes or AUDIOCPP_DRAMA3_SILENCE_CODES");
|
| 165 |
+
+ spec = env_codes;
|
| 166 |
+
+ }
|
| 167 |
+
+ clamp.codes = parse_silence_codes(spec);
|
| 168 |
+
+ if (const char * v = std::getenv("AUDIOCPP_DRAMA3_END_RATIO")) clamp.end_ratio = std::atof(v);
|
| 169 |
+
+ if (const char * v = std::getenv("AUDIOCPP_DRAMA3_CAP_RATIO")) clamp.cap_ratio = std::atof(v);
|
| 170 |
+
+ if (sampling.pause_end_ratio > 0) clamp.end_ratio = sampling.pause_end_ratio;
|
| 171 |
+
+ if (sampling.pause_cap_ratio > 0) clamp.cap_ratio = sampling.pause_cap_ratio;
|
| 172 |
+
+ return clamp;
|
| 173 |
+
+}
|
| 174 |
+
+
|
| 175 |
+
std::vector<float> last_hidden(const std::vector<float> & values, int64_t width) {
|
| 176 |
+
if (values.size() < static_cast<size_t>(width)) throw std::runtime_error("Drama 3 backbone returned too few hidden values");
|
| 177 |
+
return {values.end() - width, values.end()};
|
| 178 |
+
@@ -369,6 +466,31 @@ Drama3Generation Drama3Generator::generate(const std::string & text, const std::
|
| 179 |
+
}
|
| 180 |
+
});
|
| 181 |
+
}
|
| 182 |
+
+ const PauseClamp clamp = resolve_pause_clamp(sampling);
|
| 183 |
+
+ int64_t silent_run = 0;
|
| 184 |
+
+ const double expected = expected_frames(text);
|
| 185 |
+
+ const auto end_frames = static_cast<int64_t>(clamp.end_ratio * expected);
|
| 186 |
+
+ const auto cap_frames = static_cast<int64_t>(clamp.cap_ratio * expected);
|
| 187 |
+
+ // Offline takes decode through the streaming codec graph in codec_batch_frames batches, so peak VRAM no
|
| 188 |
+
+ // longer grows with output length (a 32 s take otherwise needs 2.7-3.8 GB more on a 24 GB card).
|
| 189 |
+
+ // AUDIOCPP_DRAMA3_FULL_DECODE=1 restores the single whole-take decode graph.
|
| 190 |
+
+ const char * full_decode_env = std::getenv("AUDIOCPP_DRAMA3_FULL_DECODE");
|
| 191 |
+
+ const bool full_decode = full_decode_env != nullptr && std::string(full_decode_env) == "1";
|
| 192 |
+
+ const bool offline_stream_decode = !streaming && !full_decode;
|
| 193 |
+
+ std::vector<Drama3Frame> offline_pending;
|
| 194 |
+
+ auto flush_offline = [&] {
|
| 195 |
+
+ if (offline_pending.empty()) return;
|
| 196 |
+
+ codecs::FishDacCodes codes;
|
| 197 |
+
+ codes.codebooks = 10;
|
| 198 |
+
+ codes.frames = static_cast<int64_t>(offline_pending.size());
|
| 199 |
+
+ codes.codes.resize(offline_pending.size() * 10);
|
| 200 |
+
+ for (size_t book = 0; book < 10; ++book) {
|
| 201 |
+
+ for (size_t frame = 0; frame < offline_pending.size(); ++frame) codes.codes[book * offline_pending.size() + frame] = offline_pending[frame][book + 1];
|
| 202 |
+
+ }
|
| 203 |
+
+ runtime::append_audio_buffer(result.audio, codec_->decode_stream(codes));
|
| 204 |
+
+ offline_pending.clear();
|
| 205 |
+
+ };
|
| 206 |
+
+ if (offline_stream_decode) codec_->reset_decode_stream();
|
| 207 |
+
for (int64_t step = 0; step < sampling.max_frames; ++step) {
|
| 208 |
+
component_started = ProfileClock::now();
|
| 209 |
+
auto logits = backbone_->lm_head(hidden);
|
| 210 |
+
@@ -377,6 +499,17 @@ Drama3Generation Drama3Generator::generate(const std::string & text, const std::
|
| 211 |
+
// Both drama3 (lm_head_token_ids) and drama3-small (lm_head_rows) return
|
| 212 |
+
// compact [EOS, semantic 0..N-1] logits from the backbone.
|
| 213 |
+
auto candidates = std::move(logits);
|
| 214 |
+
+ if (clamp.max_pause > 0 && step >= cap_frames) {
|
| 215 |
+
+ std::cerr << "[fish_drama3] length guard: stopped at " << step << " frames (expected " << expected << ")\n";
|
| 216 |
+
+ break;
|
| 217 |
+
+ }
|
| 218 |
+
+ if (clamp.max_pause > 0 && silent_run >= clamp.max_pause && step >= end_frames) break; // pause after the text is done
|
| 219 |
+
+ if (clamp.max_pause > 0 && silent_run >= clamp.max_pause) {
|
| 220 |
+
+ // Long enough silence: the next frame must be speech or EOS (candidate 0).
|
| 221 |
+
+ for (const int32_t code : clamp.codes) {
|
| 222 |
+
+ if (code + 1 < static_cast<int32_t>(candidates.size())) candidates[static_cast<size_t>(code) + 1] = -std::numeric_limits<float>::infinity();
|
| 223 |
+
+ }
|
| 224 |
+
+ }
|
| 225 |
+
const int32_t first = sample(candidates, sampling.temperature, sampling.top_k, sampling.top_p, random, sampler_scratch);
|
| 226 |
+
const int32_t second = sample(candidates, 1.0F, 30, 0.95F, random, sampler_scratch);
|
| 227 |
+
const int32_t first_token = first == 0 ? assets_->eos : assets_->tower.semantic_begin + first - 1;
|
| 228 |
+
@@ -416,6 +549,11 @@ Drama3Generation Drama3Generator::generate(const std::string & text, const std::
|
| 229 |
+
}
|
| 230 |
+
component_ms[6] += debug::elapsed_ms(tower_started) - (component_ms[5] - sampling_before_tower);
|
| 231 |
+
output_frames.push_back(next);
|
| 232 |
+
+ silent_run = clamp.codes.count(next[1]) ? silent_run + 1 : 0;
|
| 233 |
+
+ if (offline_stream_decode) {
|
| 234 |
+
+ offline_pending.push_back(next);
|
| 235 |
+
+ if (static_cast<int64_t>(offline_pending.size()) >= std::max<int64_t>(1, codec_batch_frames_)) flush_offline();
|
| 236 |
+
+ }
|
| 237 |
+
if (step == 0) mark_phase("tower_first_frame_ms");
|
| 238 |
+
recent.push_back(next[0]);
|
| 239 |
+
if (recent.size() > 16) recent.pop_front();
|
| 240 |
+
@@ -470,7 +608,12 @@ Drama3Generation Drama3Generator::generate(const std::string & text, const std::
|
| 241 |
+
backbone_->release_prefill_graphs();
|
| 242 |
+
tower_->release_prefill_graphs();
|
| 243 |
+
}
|
| 244 |
+
- result.audio = codec_->decode_codes(result.codes);
|
| 245 |
+
+ if (offline_stream_decode) {
|
| 246 |
+
+ flush_offline();
|
| 247 |
+
+ codec_->reset_decode_stream();
|
| 248 |
+
+ } else {
|
| 249 |
+
+ result.audio = codec_->decode_codes(result.codes);
|
| 250 |
+
+ }
|
| 251 |
+
codec_->release_runtime_graphs();
|
| 252 |
+
component_ms[8] += debug::elapsed_ms(component_started);
|
| 253 |
+
}
|
| 254 |
+
diff --git a/src/community_models/fish_drama3/session.cpp b/src/community_models/fish_drama3/session.cpp
|
| 255 |
+
index bf3203ca..0e0b5e9e 100644
|
| 256 |
+
--- a/src/community_models/fish_drama3/session.cpp
|
| 257 |
+
+++ b/src/community_models/fish_drama3/session.cpp
|
| 258 |
+
@@ -138,6 +138,10 @@ runtime::TaskResult Drama3Session::synthesize(const runtime::TaskRequest & reque
|
| 259 |
+
sampling.top_p = runtime::parse_finite_float_option(effective.options, {"top_p"}).value_or(0.9F);
|
| 260 |
+
sampling.top_k = runtime::parse_int_option(effective.options, {"top_k"}).value_or(4097);
|
| 261 |
+
sampling.max_frames = runtime::parse_positive_i64_option(effective.options, {"max_tokens", "max_new_tokens"}, 1024);
|
| 262 |
+
+ if (const auto v = runtime::parse_int_option(effective.options, {"max_pause_frames"})) sampling.max_pause_frames = *v;
|
| 263 |
+
+ if (const auto v = runtime::find_option(effective.options, {"silence_codes"})) sampling.silence_codes = *v;
|
| 264 |
+
+ if (const auto v = runtime::parse_finite_float_option(effective.options, {"pause_end_ratio"})) sampling.pause_end_ratio = *v;
|
| 265 |
+
+ if (const auto v = runtime::parse_finite_float_option(effective.options, {"pause_cap_ratio"})) sampling.pause_cap_ratio = *v;
|
| 266 |
+
seed = runtime::parse_u32_option(effective.options, {"seed"});
|
| 267 |
+
} catch (const std::runtime_error & error) {
|
| 268 |
+
throw runtime::InvalidRequestError(error.what());
|
postprocess.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional output clean-up for drama3-expressive-medium (numpy + soundfile).
|
| 2 |
+
|
| 3 |
+
The fine-tuned model is about 3.5 dB louder than Drama 3 and leaves a little more room tone in the gaps between
|
| 4 |
+
words. This script (1) loudness-matches a take: the speech level (95th percentile of 10 ms frame levels) goes to
|
| 5 |
+
--target dBFS, peaks stay below -1 dBFS; and (2) with --gate, applies a smoothed downward expander to frames more
|
| 6 |
+
than 30 dB below the speech level (1.5 dB per dB, at most 24 dB, 50 ms hold, 5 ms attack, 80 ms release), so the
|
| 7 |
+
gaps fall toward silence while word tails are kept.
|
| 8 |
+
|
| 9 |
+
python postprocess.py in.wav out.wav [--target -20] [--gate]
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import soundfile as sf
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def frame_db(w: np.ndarray, sr: int, hop: float = 0.01) -> np.ndarray:
|
| 19 |
+
n = int(hop * sr)
|
| 20 |
+
f = w[: len(w) // n * n].reshape(-1, n)
|
| 21 |
+
return 20 * np.log10(np.sqrt((f ** 2).mean(1)) + 1e-9)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def process(w: np.ndarray, sr: int, target: float = -20.0, gate: bool = False) -> np.ndarray:
|
| 25 |
+
db = frame_db(w, sr)
|
| 26 |
+
if not len(db):
|
| 27 |
+
return w
|
| 28 |
+
level = np.percentile(db, 95)
|
| 29 |
+
out = w * 10 ** ((target - level) / 20)
|
| 30 |
+
if gate:
|
| 31 |
+
thr = level - 30.0
|
| 32 |
+
att = -np.clip((thr - db) * 1.5, 0.0, 24.0)
|
| 33 |
+
hold = 5
|
| 34 |
+
near = np.convolve((db >= thr).astype(float), np.ones(2 * hold + 1), mode="same") > 0
|
| 35 |
+
att[near] = 0.0
|
| 36 |
+
sm, g = np.zeros_like(att), 0.0
|
| 37 |
+
for i, a in enumerate(att):
|
| 38 |
+
g += (0.86 if a > g else 0.12) * (a - g)
|
| 39 |
+
sm[i] = g
|
| 40 |
+
n = int(0.01 * sr)
|
| 41 |
+
gain = np.repeat(10 ** (sm / 20), n)
|
| 42 |
+
gain = np.concatenate([gain, np.full(len(out) - len(gain), gain[-1] if len(gain) else 1.0)])
|
| 43 |
+
out = out * gain
|
| 44 |
+
return out * min(1.0, 10 ** (-1 / 20) / max(float(np.abs(out).max()), 1e-9))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
ap = argparse.ArgumentParser()
|
| 49 |
+
ap.add_argument("src")
|
| 50 |
+
ap.add_argument("dst")
|
| 51 |
+
ap.add_argument("--target", type=float, default=-20.0)
|
| 52 |
+
ap.add_argument("--gate", action="store_true")
|
| 53 |
+
a = ap.parse_args()
|
| 54 |
+
w, sr = sf.read(a.src, dtype="float32", always_2d=True)
|
| 55 |
+
sf.write(a.dst, process(w.mean(1), sr, a.target, a.gate), sr)
|
samples/en_bored_shock.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c72ead9edced3384104d7e4cef81de7651833c0be90e03d0799628c141bcfd9f
|
| 3 |
+
size 228249
|
samples/en_same_anger.mp3
ADDED
|
Binary file (70.9 kB). View file
|
|
|
samples/en_same_joy.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fb2977cec2f96059215c1f8216fdf62e4bead0cb2b3fc6ea535537d0b2c692a5
|
| 3 |
+
size 132328
|
samples/en_same_tears.mp3
ADDED
|
Binary file (87.8 kB). View file
|
|
|
samples/en_same_whisper.mp3
ADDED
|
Binary file (93.5 kB). View file
|
|
|
samples/en_tears_joy.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d66fee92569d51ca63d60b2d83d22fc46b9c4a7057f6f2fef36464e2a452c30f
|
| 3 |
+
size 218218
|
samples/en_whisper_shout.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9f9b1f8189586999e64d0100e1c6ae5009c866c94205bb69b8407bf369c450c6
|
| 3 |
+
size 205680
|
samples/ja_bored_shock.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e66b921c2c2d78dfbe155ee863fea082b552b83fee4a4f5dfc82c817a71cd7f0
|
| 3 |
+
size 205053
|
samples/ja_joy_tears.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:93ad99bfdec3b900e19a87bb488ece761768c6364e05461e820cff35c11a10eb
|
| 3 |
+
size 261477
|
samples/ja_same_anger.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9a9f7e4768ced75b6a7fb9baf6f109ecf3a3aa54d19c5d9bc06685d799f64f2e
|
| 3 |
+
size 106623
|
samples/ja_same_joy.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9785bce09396eb329ebd9b862816a7bd51a9966753f04d5b6ff41bbc23955fce
|
| 3 |
+
size 125431
|
samples/ja_same_tears.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:84aa38b2d0ac872dcb51e7fefb0b74add6399aeaccef5f5538ff1d3d3d4f3f61
|
| 3 |
+
size 137970
|
samples/ja_same_whisper.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:64daf275a4706668768541c276935c32eec3f88364865e059c170c327b85c297
|
| 3 |
+
size 125431
|
samples/ja_whisper_shout.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:52fb7a8bcf9a882157782e79f22c1b9eb4b27ab5f1a7a4687eb69b0925b71abb
|
| 3 |
+
size 237026
|
silence_codes.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
[8, 23, 40, 55, 95, 99, 106, 133, 138, 144, 156, 220, 236, 239, 245, 246, 256, 258, 262, 278, 283, 293, 294, 301, 308, 312, 322, 332, 337, 348, 365, 376, 380, 393, 434, 444, 507, 512, 513, 520, 538, 557, 583, 598, 612, 621, 656, 659, 692, 729, 730, 737, 744, 749, 766, 792, 795, 800, 843, 848, 858, 864, 878, 887, 903, 933, 963, 992, 1008, 1011, 1088, 1125, 1156, 1157, 1174, 1190, 1194, 1231, 1237, 1255, 1263, 1279, 1284, 1305, 1346, 1359, 1379, 1420, 1514, 1548, 1559, 1560, 1564, 1570, 1623, 1625, 1632, 1636, 1640, 1646, 1649, 1651, 1672, 1688, 1695, 1696, 1700, 1723, 1753, 1774, 1786, 1830, 1831, 1837, 1845, 1856, 1909, 1918, 1925, 1933, 1937, 1939, 1940, 1944, 1970, 1979, 1987, 1990, 2011, 2016, 2039, 2041, 2048, 2062, 2111, 2123, 2135, 2158, 2161, 2162, 2168, 2182, 2192, 2238, 2259, 2263, 2289, 2302, 2303, 2331, 2335, 2342, 2377, 2387, 2420, 2433, 2435, 2466, 2480, 2499, 2512, 2550, 2570, 2587, 2597, 2601, 2609, 2617, 2629, 2639, 2644, 2691, 2697, 2698, 2715, 2747, 2752, 2795, 2816, 2834, 2847, 2860, 2863, 2877, 2879, 2891, 2901, 2917, 2921, 2922, 2957, 2998, 3015, 3043, 3069, 3072, 3077, 3078, 3079, 3121, 3137, 3153, 3161, 3167, 3174, 3185, 3193, 3194, 3267, 3303, 3308, 3332, 3357, 3367, 3382, 3402, 3428, 3434, 3482, 3499, 3503, 3542, 3548, 3558, 3590, 3602, 3604, 3620, 3633, 3646, 3708, 3735, 3743, 3749, 3775, 3802, 3811, 3817, 3850, 3854, 3983, 3993, 4017, 4031, 4078, 4079, 4082]
|
torch/LICENSE
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FISH AUDIO COMMUNITY LICENSE AGREEMENT
|
| 2 |
+
|
| 3 |
+
**Version 1.0 — Last Updated: October 13, 2026**
|
| 4 |
+
|
| 5 |
+
## I. INTRODUCTION
|
| 6 |
+
|
| 7 |
+
This Agreement applies to any individual person or entity ("You", "Your" or "Licensee") that uses or distributes any portion or element of the Fish Audio Materials or Derivative Works thereof for any Research, Non-Commercial, or Commercial purpose. Capitalized terms not otherwise defined herein are defined in Section V below.
|
| 8 |
+
|
| 9 |
+
This Agreement is intended to allow, free of charge, research and non-commercial uses of the Fish Audio Materials and, as set out in Section III, limited uses for a Commercial Purpose by Licensees whose Annual Revenue is less than the Revenue Threshold. Any other use of the Fish Audio Materials for a Commercial Purpose, and any Hosted Service, requires a separate written license agreement from Fish Audio.
|
| 10 |
+
|
| 11 |
+
By clicking "I Accept" or by using, distributing, or accessing any portion or element of the Fish Audio Materials or Derivative Works, You agree that You have read, understood and are bound by the terms of this Agreement. If You are acting on behalf of a company, organization or other entity, then "You" includes you and that entity, and You agree that You: (i) are an authorized representative of such entity with the authority to bind such entity to this Agreement, and (ii) You agree to the terms of this Agreement on that entity's behalf.
|
| 12 |
+
|
| 13 |
+
## II. RESEARCH & NON-COMMERCIAL USE LICENSE
|
| 14 |
+
|
| 15 |
+
Subject to the terms of this Agreement, Fish Audio grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Fish Audio's intellectual property or other rights owned by Fish Audio embodied in the Fish Audio Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Fish Audio Materials for any Research or Non-Commercial Purpose.
|
| 16 |
+
|
| 17 |
+
"Research Purpose" means academic or scientific advancement, and in each case, is not primarily intended for commercial advantage or monetary compensation to You or others.
|
| 18 |
+
|
| 19 |
+
"Non-Commercial Purpose" means any purpose other than a Research Purpose that is not primarily intended for commercial advantage or monetary compensation to You or others, such as personal use (i.e., hobbyist) or evaluation and testing.
|
| 20 |
+
|
| 21 |
+
## III. COMMERCIAL USE
|
| 22 |
+
|
| 23 |
+
**(a) Community Commercial License.** Subject to the terms of this Agreement (including Sections III(b) through III(d)), Fish Audio grants You a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable and royalty-free limited license under Fish Audio's intellectual property or other rights owned by Fish Audio embodied in the Fish Audio Materials to use, reproduce, distribute, and create Derivative Works of, and make modifications to, the Fish Audio Materials for a Commercial Purpose, but only while Your Annual Revenue is less than USD 500,000 (the "Revenue Threshold").
|
| 24 |
+
|
| 25 |
+
"Annual Revenue" means, as of any date, the total gross revenue of You and Your Affiliates, in aggregate, from all sources (whether or not derived from the Fish Audio Materials or Derivative Works) for the twelve (12) months ending on that date, with amounts in other currencies converted into U.S. dollars at a published market exchange rate in effect on that date. If You deploy, install, host, or operate the Fish Audio Materials or Derivative Works for a particular third party, or deliver a copy of them to a third party, for use in that third party's products, services, or internal operations (for example, as a contractor, integrator, consultant, or on-premises vendor), the license in this Section III(a) extends to that work only if that third party's Annual Revenue, calculated as if that third party were You, is also less than the Revenue Threshold. This does not apply to (1) delivering to a third party only output (such as audio files) that You generate Yourself, for example as an agency, studio, or freelancer producing voiceovers, dubbing, or audiobooks for a client, or (2) providing Your own generally available product or service to customers or end users who do not receive a copy of the Fish Audio Materials or Derivative Works; such customers and end users do not need to meet the Revenue Threshold for that use.
|
| 26 |
+
|
| 27 |
+
**(b) Reaching the Revenue Threshold.** If, while You are using the Fish Audio Materials or Derivative Works under Section III(a), Your Annual Revenue reaches or exceeds the Revenue Threshold (the date it first does so, the "Threshold Date"), You must notify Fish Audio in writing at business@fish.audio within thirty (30) days after the Threshold Date. Notwithstanding Section III(a), the license in Section III(a) continues to apply to the uses for a Commercial Purpose that You were making on the Threshold Date for ninety (90) days after the Threshold Date (the "Transition Period"). After the Transition Period, any use for a Commercial Purpose requires a separate written license agreement from Fish Audio; however, if Your Annual Revenue later falls below the Revenue Threshold, Section III(a) applies to You again from that date. Reaching the Revenue Threshold is not a breach of this Agreement and does not affect Your license under Section II or Your ownership of outputs under Section IV(c)(iii).
|
| 28 |
+
|
| 29 |
+
**(c) Hosted Services.** Notwithstanding Sections II and III(a) and the definition of Commercial Purpose, and regardless of Your purpose or Annual Revenue, no license is granted under this Agreement to offer a Hosted Service, which requires a separate written license agreement from Fish Audio. "Hosted Service" means making the Fish Audio Materials or Derivative Works available to third parties so that they can generate speech or other audio from text, audio, or voice samples that they supply, whether through an application programming interface, software development kit, model-inference or model-hosting service, or a website, application, or feature whose primary purpose is text-to-speech, voiceover, voice generation, or voice cloning. None of the following is a Hosted Service: (1) generating speech for content that You create, select, or control, or that Your own product generates (for example, narration, dubbing, game or app characters, or an assistant's spoken replies), and delivering that speech in or with Your products or services; (2) a production service in which You operate the Fish Audio Materials or Derivative Works, direct each generation, and deliver only finished output to Your client (for example, as an agency, studio, or freelancer producing voiceovers, dubbing, or audiobooks), without giving the client self-serve or automated access; or (3) a free, non-commercial research or demonstration service (for example, a Hugging Face Space, a research demo, or a shared server for a research group) that is not monetized and is not offered or promoted as a production service or API.
|
| 30 |
+
|
| 31 |
+
**(d) Other Commercial Use.** **Any use of the Fish Audio Materials or Derivative Works for a Commercial Purpose that is not licensed under Section III(a) (including as continued under Section III(b)) requires a separate written license agreement from Fish Audio.**
|
| 32 |
+
|
| 33 |
+
"Commercial Purpose" means any purpose other than a Research Purpose or Non-Commercial Purpose that is primarily intended for or directed toward commercial advantage or monetary compensation to You or others, including but not limited to: (i) creating, modifying, or distributing Your product or service, including via a hosted service or application programming interface, (ii) Your business's or organization's internal operations, and (iii) any use in connection with a product or service for which You charge a fee or generate revenue, whether directly or indirectly.
|
| 34 |
+
|
| 35 |
+
To obtain a commercial license, please contact Fish Audio at:
|
| 36 |
+
|
| 37 |
+
- **Website:** [https://fish.audio](https://fish.audio)
|
| 38 |
+
- **Email:** business@fish.audio
|
| 39 |
+
|
| 40 |
+
## IV. GENERAL TERMS
|
| 41 |
+
|
| 42 |
+
All licenses granted under this Agreement, including Your Research, Non-Commercial, and Commercial licenses, are subject to the following terms.
|
| 43 |
+
|
| 44 |
+
### a. Distribution & Attribution
|
| 45 |
+
|
| 46 |
+
If You distribute a copy of the Fish Audio Materials or a Derivative Work to a third party, You shall (i) provide a copy of this Agreement to that third party, and (ii) retain the following attribution notice within a "Notice" text file distributed as a part of such copies: "These Fish Audio Materials are licensed under the Fish Audio Community License, Version 1.0. Copyright © 39 AI, INC. All Rights Reserved." If You distribute or make available the Fish Audio Materials or a Derivative Work, or a product or service that uses any portion of them, You shall prominently display "Built with Fish Audio" on a related website, user interface, blogpost, about page, or product documentation.
|
| 47 |
+
|
| 48 |
+
If You create a Derivative Work, You may add your own attribution notice(s) to the "Notice" text file included with that Derivative Work, provided that You clearly indicate which attributions apply to the Fish Audio Materials and state in the "Notice" text file that You changed the Fish Audio Materials and how it was modified.
|
| 49 |
+
|
| 50 |
+
### b. Use Restrictions
|
| 51 |
+
|
| 52 |
+
Your use of the Fish Audio Materials and Derivative Works, including any output or results of the Fish Audio Materials or Derivative Works, must comply with applicable laws and regulations (including Trade Control Laws and equivalent regulations).
|
| 53 |
+
|
| 54 |
+
You will not use the Fish Audio Materials or Derivative Works, or any output or results of the Fish Audio Materials or Derivative Works, to: (i) generate speech that imitates the voice of an identifiable natural person without that person's prior consent (or, for a minor, the consent of a parent or legal guardian, and for a deceased person, the consent of the holder of the relevant rights) or another legal right to do so; (ii) impersonate any person or organization in order to deceive, defraud, or harass, or to place calls in violation of applicable telemarketing or robocall laws; (iii) generate sexual content involving a minor or a voice presented as a minor's, or using the voice of any real person without that person's consent; or (iv) intentionally remove, disable, circumvent, or obscure any watermark or provenance signal applied by the Fish Audio Materials (ordinary editing, mixing, compression, or format conversion of output that is not intended to remove such a signal is not a breach of this clause (iv)). You will not distribute any tool, Derivative Work, or service designed to remove, disable, circumvent, or obscure any such watermark or provenance signal. If You make voice cloning or other speech generation using the Fish Audio Materials or Derivative Works available to third parties, You must bind them, by enforceable terms, to restrictions at least as protective as those in this Section IV(b).
|
| 55 |
+
|
| 56 |
+
Furthermore, You will not use the Fish Audio Materials or Derivative Works, or any output or results of the Fish Audio Materials or Derivative Works, to create, train, distill, or improve any foundational generative AI model or any speech, audio, or voice generation model (excluding the Models or Derivative Works). This does not restrict training models solely to detect synthetic audio, verify watermarks, or prevent spoofing.
|
| 57 |
+
|
| 58 |
+
### c. Intellectual Property
|
| 59 |
+
|
| 60 |
+
**(i) Trademark License.** No trademark licenses are granted under this Agreement. In connection with the Fish Audio Materials or Derivative Works, You may not use any name or mark owned by or associated with Fish Audio or any of its Affiliates, except (A) as required under Section IV(a), and (B) to make truthful, factual references to Fish Audio and the Models, including naming a Derivative Work model in a way that identifies its origin (for example, "Drama-3-GGUF" or "based on Fish Audio Drama 3"), provided that You do not use any Fish Audio logo, do not use a Fish Audio name or mark as the name of Your company or of any product or service other than such a Derivative Work model, and do not state or imply that Fish Audio sponsors, endorses, or officially released You, Your products, or Your Derivative Works.
|
| 61 |
+
|
| 62 |
+
**(ii) Ownership of Derivative Works.** As between You and Fish Audio, You are the owner of Derivative Works You create, subject to Fish Audio's ownership of the Fish Audio Materials and any Derivative Works made by or for Fish Audio.
|
| 63 |
+
|
| 64 |
+
**(iii) Ownership of Outputs.** As between You and Fish Audio, You own any outputs generated from the Models or Derivative Works to the extent permitted by applicable law.
|
| 65 |
+
|
| 66 |
+
**(iv) Disputes.** If You or Your Affiliate(s) institute litigation or other proceedings against Fish Audio (including a cross-claim or counterclaim in a lawsuit) alleging that the Fish Audio Materials, Derivative Works or associated outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by You, then any licenses granted to You under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Fish Audio from and against any claim by any third party arising out of or related to Your use or distribution of the Fish Audio Materials or Derivative Works in violation of this Agreement.
|
| 67 |
+
|
| 68 |
+
**(v) Feedback.** From time to time, You may provide Fish Audio with verbal and/or written suggestions, comments or other feedback related to Fish Audio's existing or prospective technology, products or services (collectively, "Feedback"). You are not obligated to provide Fish Audio with Feedback, but to the extent that You do, You hereby grant Fish Audio a perpetual, irrevocable, royalty-free, fully-paid, sub-licensable, transferable, non-exclusive, worldwide right and license to exploit the Feedback in any manner without restriction. Your Feedback is provided "AS IS" and You make no warranties whatsoever about any Feedback.
|
| 69 |
+
|
| 70 |
+
### d. Disclaimer of Warranty
|
| 71 |
+
|
| 72 |
+
UNLESS REQUIRED BY APPLICABLE LAW, THE FISH AUDIO MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OR LAWFULNESS OF USING OR REDISTRIBUTING THE FISH AUDIO MATERIALS, DERIVATIVE WORKS OR ANY OUTPUT OR RESULTS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE FISH AUDIO MATERIALS, DERIVATIVE WORKS AND ANY OUTPUT AND RESULTS.
|
| 73 |
+
|
| 74 |
+
### e. Limitation of Liability
|
| 75 |
+
|
| 76 |
+
IN NO EVENT WILL FISH AUDIO OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF FISH AUDIO OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
|
| 77 |
+
|
| 78 |
+
### f. Term and Termination
|
| 79 |
+
|
| 80 |
+
The term of this Agreement will commence upon Your acceptance of this Agreement or access to the Fish Audio Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Fish Audio may terminate this Agreement by written notice to You if You breach any term or condition of this Agreement and, if the breach is capable of cure, You do not cure it within thirty (30) days after Fish Audio's written notice describing the breach. If You breach Section IV(b), this Agreement and all licenses granted to You under it terminate automatically, without notice or cure period. Upon termination of this Agreement, You shall delete and cease use of any Fish Audio Materials or Derivative Works. Sections IV(b) (as it applies to any output or results of the Fish Audio Materials or Derivative Works that You retain), IV(c)(iii), IV(c)(iv), IV(c)(v), IV(d), IV(e), IV(g) and V shall survive the termination of this Agreement.
|
| 81 |
+
|
| 82 |
+
### g. Governing Law
|
| 83 |
+
|
| 84 |
+
This Agreement will be governed by and construed in accordance with the laws of the United States and the State of California without regard to choice of law principles, and the UN Convention on Contracts for International Sale of Goods does not apply to this Agreement.
|
| 85 |
+
|
| 86 |
+
### h. Versions
|
| 87 |
+
|
| 88 |
+
Fish Audio may publish revised versions of the Fish Audio Community License, each identified by a version number. Fish Audio Materials are licensed under the version with which Fish Audio released them, as stated in the license file accompanying them or on Fish Audio's official model page for them. A revised version applies only to Fish Audio Materials that Fish Audio releases or designates under it, and does not reduce the rights You hold under the version You received. You may elect to use Fish Audio Materials under a later version that Fish Audio designates as applicable to them.
|
| 89 |
+
|
| 90 |
+
### i. Separate Agreements
|
| 91 |
+
|
| 92 |
+
If You and Fish Audio have signed a separate written agreement covering the Fish Audio Materials, that agreement governs to the extent it conflicts with this Agreement.
|
| 93 |
+
|
| 94 |
+
## V. DEFINITIONS
|
| 95 |
+
|
| 96 |
+
**"Affiliate(s)"** means any entity that directly or indirectly controls, is controlled by, or is under common control with the subject entity; for purposes of this definition, "control" means direct or indirect ownership or control of more than 50% of the voting interests of the subject entity.
|
| 97 |
+
|
| 98 |
+
**"Agreement"** means this Fish Audio Community License Agreement, Version 1.0 (also referred to as the "Fish Audio Community License, Version 1.0" or "FACL v1.0").
|
| 99 |
+
|
| 100 |
+
**"Annual Revenue"** and **"Revenue Threshold"** have the meanings given in Section III(a), and **"Hosted Service"** has the meaning given in Section III(c).
|
| 101 |
+
|
| 102 |
+
**"Derivative Work(s)"** means (a) any derivative work of the Fish Audio Materials as recognized by U.S. copyright laws and (b) any modification of a Model, including any model initialized from all or part of a Model's weights (such as fine-tuned, quantized, merged, and low-rank adaptation ("LoRA") models), whether or not it was trained using output of a Model or Derivative Work. Derivative Works do not include the output of any Model or Derivative Work, or any other model trained or distilled using such output.
|
| 103 |
+
|
| 104 |
+
**"Documentation"** means any specifications, manuals, model cards, documentation, and other written information that Fish Audio makes available under this Agreement related to the Software or Models.
|
| 105 |
+
|
| 106 |
+
**"Fish Audio"** or **"we"** means 39 AI, INC. and its Affiliates.
|
| 107 |
+
|
| 108 |
+
**"Model(s)"** means the machine-learning models, including trained model weights and other elements of the foregoing, that Fish Audio makes available under this Agreement, including Fish Audio Drama 3 and, solely for use with Fish Audio Drama 3 and its Derivative Works, the audio codec that Fish Audio provides for use with Fish Audio Drama 3 (including the copy of that codec distributed with Fish Audio S2-Pro).
|
| 109 |
+
|
| 110 |
+
**"Software"** means Fish Audio's proprietary software made available under this Agreement now or in the future, including the Fish Speech source code (https://github.com/fishaudio/fish-speech).
|
| 111 |
+
|
| 112 |
+
**"Fish Audio Materials"** means, collectively, the Models, Software and Documentation (and any portion or combination thereof) made available under this Agreement. Model weights that Fish Audio makes available under a different license (for example, the Fish Audio S2-Pro weights under the Fish Audio Research License) are not Fish Audio Materials, even if the Software can run them, except as stated in the definition of Model(s) for the audio codec.
|
| 113 |
+
|
| 114 |
+
**"Trade Control Laws"** means any applicable U.S. and non-U.S. export control and trade sanctions laws and regulations.
|
torch/README_torch.md
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# drama3-expressive-medium in PyTorch (GGUF runtime)
|
| 2 |
+
|
| 3 |
+
A standalone PyTorch runtime for `drama3-expressive-medium-IQ4_XS.gguf`. It needs only the GGUF file:
|
| 4 |
+
no audio.cpp, no original 39 GB checkpoint, no fish-speech install. The model code is the vendored
|
| 5 |
+
Fish Audio implementation (`fish_speech/`, Fish Audio Community License, see `LICENSE` and
|
| 6 |
+
`fish_speech/VENDOR.md`). The generation loop follows audio.cpp's `fish_drama3` generator with this
|
| 7 |
+
repo's patch, including the pause fix and length guard.
|
| 8 |
+
|
| 9 |
+
**Built with Fish Audio.** The license, the non-commercial data terms and the acceptable-use rules in
|
| 10 |
+
the parent `README.md` apply.
|
| 11 |
+
|
| 12 |
+
## Files
|
| 13 |
+
|
| 14 |
+
| File | What it does |
|
| 15 |
+
|---|---|
|
| 16 |
+
| `infer.py` | CLI and `Drama3TTS` class: reference encoding, text chunking, generation, codec decoding, WAV output |
|
| 17 |
+
| `drama3_gguf.py` | GGUF reader, then builds the FishOmni model (backbone, codebook tower, tokenizer) and the DAC codec from it |
|
| 18 |
+
| `gguf_kernels.py` | Q8_0 / Q5_K / IQ4_XS dequantization: a torch reference (bit-exact with gguf-py) and Triton kernels for the expert banks |
|
| 19 |
+
| `fish_speech/` | Vendored Fish Audio code with minimal changes; every modified file starts with a comment listing its changes |
|
| 20 |
+
| `requirements.txt` | Tested versions |
|
| 21 |
+
|
| 22 |
+
## Usage
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
pip install -r requirements.txt # torch with CUDA; Linux x86_64
|
| 26 |
+
|
| 27 |
+
python infer.py --gguf ../drama3-expressive-medium-IQ4_XS.gguf \
|
| 28 |
+
--text "[calm] It's fine, really. [voice breaking] I just miss her." \
|
| 29 |
+
--ref-audio voice.wav --ref-text "Transcript of voice.wav." \
|
| 30 |
+
--out take.wav --seed 1
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
| Option | Default | |
|
| 34 |
+
|---|---|---|
|
| 35 |
+
| `--gguf` | `../drama3-expressive-medium-IQ4_XS.gguf` | |
|
| 36 |
+
| `--text` | | Text to speak. `[bracketed]` acting directions are passed to the model as-is |
|
| 37 |
+
| `--ref-audio`, `--ref-text` | | Voice reference (any sample rate, mixed to mono; about 10–30 s) or a `.npy` of its codes `[10, frames]`, and its transcript. Without a reference, Drama 3 picks a voice |
|
| 38 |
+
| `--save-ref-codes` | | Write the reference's codes to a `.npy` for reuse |
|
| 39 |
+
| `--out` | `out.wav` | 44.1 kHz mono 16-bit WAV |
|
| 40 |
+
| `--seed` | 0 | Text chunk *i* uses seed + *i*, as in audio.cpp |
|
| 41 |
+
| `--temperature`, `--top-p`, `--top-k` | 0.7, 0.7, 30 | Main token and the 9 residual codes |
|
| 42 |
+
| `--max-tokens` | 1024 | Frames per text chunk (21.5 frames/s) |
|
| 43 |
+
| `--max-pause-frames` | 10 | Pause fix; 0 turns off both the pause fix and the length guard |
|
| 44 |
+
| `--silence-codes` | `../silence_codes.json` | File or inline list of silent semantic codes |
|
| 45 |
+
| `--pause-end-ratio`, `--pause-cap-ratio` | 2.0, 3.0 | Length guard (see below) |
|
| 46 |
+
| `--device` | `cuda:0` | One CUDA device |
|
| 47 |
+
| `--context-length` | 4096 | Cache rows: reference + text prompt + max tokens |
|
| 48 |
+
| `--requests`, `--out-dir` | | Batch mode, using audio.cpp's request-file format: `{"requests": [{"id", "text", "voice_ref", "options": {"reference_text"}, "seed", "temperature", "top_k", "top_p", "max_tokens"}]}`. Writes `<id>.wav` and `<id>.json` |
|
| 49 |
+
| `--save-codes` | | Also writes the codes `[10, frames]` as `.npy` |
|
| 50 |
+
| `--no-cuda-graphs` | | Eager decode (slower; for debugging) |
|
| 51 |
+
|
| 52 |
+
From Python, with this folder on `sys.path`:
|
| 53 |
+
|
| 54 |
+
```python
|
| 55 |
+
from infer import Drama3TTS, Request
|
| 56 |
+
from fish_speech.models.text2semantic.fish_omni.generate import Drama3Sampling, PauseFix, load_silence_codes
|
| 57 |
+
|
| 58 |
+
tts = Drama3TTS("drama3-expressive-medium-IQ4_XS.gguf", "cuda:0", preload_refs=("voice.wav",))
|
| 59 |
+
pause = PauseFix(10, load_silence_codes("silence_codes.json"))
|
| 60 |
+
res = tts.synthesize(Request(text="...", ref_audio="voice.wav", ref_text="...", seed=1,
|
| 61 |
+
sampling=Drama3Sampling(pause=pause)))
|
| 62 |
+
# res.audio (float32, 44.1 kHz), res.codes [10, frames], res.info (timings, finish reason)
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
## How it runs
|
| 66 |
+
|
| 67 |
+
| Part | In the GGUF | On the GPU |
|
| 68 |
+
|---|---|---|
|
| 69 |
+
| Routed experts (40 × 256 × gate/up/down) | IQ4_XS, Q5_K in layers 0/1/2/36 | Kept packed (16.41 GiB). Decode: a fused Triton dequantize + GEMV over the 8 selected experts. Prefill: the experts in use are dequantized to bf16, 16 at a time, for batched matmuls |
|
| 70 |
+
| Attention, Gated DeltaNet, shared experts, tower (MTP) | Q8_0 | Dequantized to bf16 at load |
|
| 71 |
+
| Router, shared-expert gate, norms, convolutions | F16 / F32 | bf16 (exact), with the router and shared-expert gate in fp32 |
|
| 72 |
+
| Speech head `[EOS, semantic 0..4095]` | Q8_0 | fp32; logits in fp32 (the tower's codebook heads also give fp32 logits) |
|
| 73 |
+
| Token embedding (252,288 rows) | Q8_0 | Only the 4,096 semantic rows (all that decode needs). Prompt rows are dequantized on the host from the memory-mapped file |
|
| 74 |
+
| Codec (Fish DAC) | F16 | Conv / linear weights stay F16 and are cast per layer, so the codec computes in fp32. Encoder-side weights (0.39 GiB) live in host RAM except while a reference is encoded. Encode and decode run in windows with left context (exact for the causal convolutions), so memory does not grow with length |
|
| 75 |
+
|
| 76 |
+
Decoding replays one CUDA graph per step: speech head, sampling, codebook tower, then the backbone
|
| 77 |
+
on the new frame. Graphs are captured once per attended-cache bucket (1024 / 2048 / 4096 rows).
|
| 78 |
+
|
| 79 |
+
## Sampling, pause fix and length guard (as audio.cpp)
|
| 80 |
+
|
| 81 |
+
- The main token is drawn over `[EOS, semantic 0..4095]` with temperature, then top-p, then top-k.
|
| 82 |
+
The draw that crosses top-p is dropped, except the top-ranked one. If the draw repeats one of the
|
| 83 |
+
last 16 *generated* main tokens, a second draw at temperature 1.0, top-k 30, top-p 0.95 is used
|
| 84 |
+
instead. Codes 1–9 come from the tower with the same temperature / top-p / top-k.
|
| 85 |
+
- **Pause fix:** after `--max-pause-frames` consecutive frames whose semantic code is in
|
| 86 |
+
`--silence-codes`, those codes are masked out of the next draw, so the model has to resume speech or end.
|
| 87 |
+
- **Length guard:** the expected length is estimated from the text, using audio.cpp's estimate:
|
| 88 |
+
3.88 frames per CJK / kana character, 2.00 per ASCII letter or digit, 23.9 per `[...]` / `<...>` span, plus 8.5.
|
| 89 |
+
A pause after `pause_end_ratio` × expected ends the take, and generation stops at
|
| 90 |
+
`pause_cap_ratio` × expected regardless.
|
| 91 |
+
- **Long texts:** texts are split with audio.cpp's `tag_aware` chunker: whole sentences up to 200
|
| 92 |
+
codepoints, with tags kept whole. Each chunk is conditioned on the previous chunk's take, as audio.cpp does.
|
| 93 |
+
|
| 94 |
+
## Measured
|
| 95 |
+
|
| 96 |
+
All runs used a 29 s Japanese reference recording (620 frames; not included in this repo), the nine prompts of an
|
| 97 |
+
earlier sample set, and this repo's sampling settings (temperature 0.7, top-p 0.7, top-k 30, pause fix on with
|
| 98 |
+
`silence_codes.json`), with torch 2.9.1 and triton 3.5.1.
|
| 99 |
+
|
| 100 |
+
**VRAM.** The figure is the device's `memory.used`, sampled every 100 ms, minus the pre-run baseline.
|
| 101 |
+
It is measured the same way as the audio.cpp figure in the parent README.
|
| 102 |
+
|
| 103 |
+
| Run (RTX 4090, 24,564 MiB) | Peak | torch allocated / reserved |
|
| 104 |
+
|---|---|---|
|
| 105 |
+
| The 9 release prompts in one process (`--requests`) | **23.08 GiB** (23,634 MiB) | 22.35 / 22.46 GiB |
|
| 106 |
+
| Longest prompt alone (`en_lighthouse`, 270 frames, 12.6 s) | 23.08 GiB | 22.35 / 22.45 GiB |
|
| 107 |
+
| Long-form stress test: 5 text chunks, 984 frames, 45.7 s, `--max-tokens 1024` | 23.11 GiB | 22.36 / 22.48 GiB |
|
| 108 |
+
| audio.cpp, for comparison (parent README) | 21.73 GiB | |
|
| 109 |
+
|
| 110 |
+
Peak memory does not grow with the length of the take. The breakdown is 16.41 GiB packed experts,
|
| 111 |
+
2.75 GiB backbone dense weights, 2.28 GiB tower, 0.34 GiB codec decoder side (its 0.39 GiB
|
| 112 |
+
encoder side waits in host RAM), 0.27 GiB caches and CUDA graphs, about 0.3 GiB prefill / codec
|
| 113 |
+
transients, and about 0.6 GiB CUDA context. With a
|
| 114 |
+
desktop session on the card (331 MiB in these runs), about 0.6 GiB is left free.
|
| 115 |
+
|
| 116 |
+
**Speed.**
|
| 117 |
+
|
| 118 |
+
| | RTX 4090 | RTX 5090 |
|
| 119 |
+
|---|---|---|
|
| 120 |
+
| Decode | 62.5 frames/s (2.9× real time) | 71 frames/s (3.3×) |
|
| 121 |
+
| Prefill, ~780 prompt rows | 0.61 s | 0.49 s |
|
| 122 |
+
| Per take, end to end (prefill + decode + codec), 7–13 s takes | 2.0–2.5× real time | |
|
| 123 |
+
| Reference encode, 29 s | 0.43 s | |
|
| 124 |
+
| Model + codec load (GGUF in page cache) | 5.7 s, plus about 1.5 s of graph capture on the first take | 5.3 s |
|
| 125 |
+
|
| 126 |
+
audio.cpp on the 5090 decodes at about 72 frames/s on the same prompts.
|
| 127 |
+
|
| 128 |
+
**Teacher-forced parity with the training student.** The student is M2 banks plus the dpo_n1 step-50
|
| 129 |
+
LoRA, from the original checkpoint in bf16. The GGUF has that LoRA merged into the base and requantized
|
| 130 |
+
to Q8_0. Script: `drama3-expressive/tools/torch_parity.py`. Values are KL over the 4,097 speech candidates
|
| 131 |
+
at each predicted row (nats).
|
| 132 |
+
|
| 133 |
+
| Sequence | Rows predicted | KL(student ‖ torch) | p95 | Top-1 agreement | NLL of the true frame, student / torch | Tower KL (9 codebooks) | Decode path vs full forward, KL |
|
| 134 |
+
|---|---|---|---|---|---|---|---|
|
| 135 |
+
| P2 #0 (JA) | 104 | 0.0059 | 0.019 | 95.2% | 2.459 / 2.446 | 0.0035 | 0.0044 |
|
| 136 |
+
| P2 #50 (EN) | 235 | 0.0033 | 0.006 | 89.4% | 4.364 / 4.365 | 0.0020 | 0.0015 |
|
| 137 |
+
| P2 #140 (JA, `[sad]`) | 220 | 0.0036 | 0.008 | 93.6% | 3.662 / 3.656 | 0.0024 | 0.0015 |
|
| 138 |
+
| dev_midline #240 (EN, two directions) | 209 | 0.0039 | 0.009 | 92.3% | 4.123 / 4.126 | 0.0024 | 0.0022 |
|
| 139 |
+
| **Mean (row-weighted)** | 768 | **0.0039** | | | 3.652 / 3.648 | 0.0026 | 0.0024 |
|
| 140 |
+
|
| 141 |
+
The last column compares two paths in this runtime. The cached decode path is used for generation:
|
| 142 |
+
fused fp32 GEMV over packed experts and the recurrent Gated DeltaNet rule. The full-sequence forward
|
| 143 |
+
is used for prefill: bf16-dequantized experts and the chunked rule.
|
| 144 |
+
|
| 145 |
+
**Free-running against audio.cpp.** These are the earlier sample set's 9 prompts at its seeds plus 4 more seeds
|
| 146 |
+
each (seed + 1000k), so 45 takes per runtime, all with the same reference. CER is Whisper large-v3-turbo
|
| 147 |
+
with directions stripped and case, punctuation and spaces ignored. Most of the remaining CER is
|
| 148 |
+
Whisper normalization (三十 → 30, 十年 → 10年, 会った → あった). Script:
|
| 149 |
+
`drama3-expressive/tools/torch_release_eval.py`.
|
| 150 |
+
|
| 151 |
+
| | audio.cpp | torch |
|
| 152 |
+
|---|---|---|
|
| 153 |
+
| Mean CER (median) | 0.034 (0.029) | 0.030 (0.016) |
|
| 154 |
+
| Takes with CER > 0.1 | 5 (all `ja_tech_release`, "三十パーセント" → "30%") | 5 (same) |
|
| 155 |
+
| Duration, mean / median | 9.47 / 7.76 s | 9.09 / 8.36 s |
|
| 156 |
+
| Takes with a pause > 0.7 s | 34 / 45 | 36 / 45 |
|
| 157 |
+
| Takes > 15 s | 6 | 2 |
|
| 158 |
+
|
| 159 |
+
Per prompt (5 takes each; mean CER, then mean duration with min–max):
|
| 160 |
+
|
| 161 |
+
| Prompt | audio.cpp | torch |
|
| 162 |
+
|---|---|---|
|
| 163 |
+
| ja_meeting_panic | 0.041, 7.35 s (5.99–8.31) | 0.029, 8.40 s (7.43–9.85) |
|
| 164 |
+
| ja_thanks_tears | 0.000, 6.69 s (6.08–7.15) | 0.000, 6.56 s (5.67–7.20) |
|
| 165 |
+
| ja_whisper_relief | 0.033, 7.61 s (6.78–8.68) | 0.000, 8.27 s (7.11–8.92) |
|
| 166 |
+
| ja_story | 0.043, 13.81 s (11.70–17.18) | 0.043, 13.85 s (12.35–15.37) |
|
| 167 |
+
| ja_tech_release | 0.140, 8.68 s (7.62–9.98) | 0.140, 8.01 s (6.78–9.01) |
|
| 168 |
+
| en_wallet | 0.003, 7.87 s (6.27–9.80) | 0.010, 6.69 s (5.62–7.57) |
|
| 169 |
+
| en_shout_sorry | 0.000, 5.04 s (4.55–5.80) | 0.000, 5.23 s (4.23–6.46) |
|
| 170 |
+
| en_last_box | 0.000, 10.42 s (6.41–20.81) | 0.009, 11.01 s (8.92–12.96) |
|
| 171 |
+
| en_lighthouse | 0.047, 17.72 s (15.00–19.32) | 0.042, 13.82 s (12.17–17.79) |
|
| 172 |
+
|
| 173 |
+
The torch renders of that sample set's seeds are in `renders/release_samples/torch/` (RTX 4090), the other
|
| 174 |
+
seeds in `torch/seeds/`, and the scores in `torch/eval_*.json`.
|
| 175 |
+
|
| 176 |
+
## Limitations
|
| 177 |
+
|
| 178 |
+
- **CUDA only.** The expert kernels are Triton (tested on sm_89 RTX 4090 and sm_120 RTX 5090, one
|
| 179 |
+
device). The torch reference path in `gguf_kernels.py` runs anywhere, but a CPU run is far too slow to use.
|
| 180 |
+
- **The 24 GB margin is thin.** The peak is 23.1 GiB against audio.cpp's 21.7 GiB, because the dense
|
| 181 |
+
weights are bf16 (5.0 GiB) instead of Q8_0. Anything else on the card (a second process, a heavy
|
| 182 |
+
desktop) can push it into out-of-memory errors. Lower `--context-length` to save a little (caches are 0.25 GiB at 4096).
|
| 183 |
+
- **Same seed, different take than audio.cpp.** The random streams differ: torch Philox on the GPU,
|
| 184 |
+
against audio.cpp's `std::mt19937`. Takes are deterministic for a given seed, GPU model and software
|
| 185 |
+
stack, whatever their order in a batch. They differ between GPU models.
|
| 186 |
+
- **Reference codes differ from audio.cpp's.** On the 29 s reference the two encoders agree on 98.5%
|
| 187 |
+
of the semantic codes, but only on 81–90% of the residual codebooks: audio.cpp's encoder computes
|
| 188 |
+
with lower precision. On a 6 s clip on CPU, this runtime's fp32 encode matched the original fp32
|
| 189 |
+
`codec.pth` encoder on 98.5% of codes in every codebook. `--ref-audio codes.npy` accepts precomputed
|
| 190 |
+
codes, for example audio.cpp's, if exact conditioning parity matters.
|
| 191 |
+
- **Unresolved prompt-level difference.** `en_lighthouse` came out longer in audio.cpp in all 5 takes
|
| 192 |
+
(15–19 s) than in this runtime in 4 of 5 (12–14 s; one take 17.8 s). With audio.cpp's reference
|
| 193 |
+
codes the torch takes stayed short (10.5–13.7 s), so the gap is not the reference encoding. It may come
|
| 194 |
+
from the numeric paths (bf16 here, Q8_0 with quantized activations in ggml), or it may be chance with 5 takes.
|
| 195 |
+
- **Speech-only head:** only the 4,097 speech logits exist, as in audio.cpp. The model cannot emit text tokens.
|
| 196 |
+
- **Not included:** streaming output (takes are decoded when complete), batching several requests per
|
| 197 |
+
forward, multi-GPU placement. Multiple references and continuation history are available through
|
| 198 |
+
`build_drama3_prompt` / `generate_drama3` in Python, but are not exposed on the CLI.
|
| 199 |
+
- **Precision of the two paths:** prefill computes the experts in bf16 from dequantized weights, as
|
| 200 |
+
the training student does. Decode uses exact weights in fp32. The two paths differ by a teacher-forced KL of about 0.002.
|
| 201 |
+
- **Not listened to:** whether directions audibly change delivery was not checked by ear for these
|
| 202 |
+
renders; only CER, duration and pauses were measured.
|
torch/drama3_gguf.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load drama3-expressive-medium from its GGUF alone: FishOmni model (backbone + codebook tower +
|
| 2 |
+
tokenizer) and the Fish DAC codec, for PyTorch.
|
| 3 |
+
|
| 4 |
+
Storage on the device:
|
| 5 |
+
* routed experts (IQ4_XS, Q5_K in layers 0/1/2/36): packed GGUF banks, dequantized on the fly
|
| 6 |
+
(fused dequant-GEMV for decode, per-group dequantization for prefill), see gguf_kernels.py;
|
| 7 |
+
* dense weights (attention, Gated DeltaNet, shared experts, tower; Q8_0 / F16 in the GGUF):
|
| 8 |
+
dequantized to bf16 at load; the speech-only head [EOS, semantic 0..4095] in fp32;
|
| 9 |
+
* token embedding (252,288 x 2048, Q8_0): only the 4,096 semantic rows live on the device
|
| 10 |
+
(all that decode needs); prompt rows are dequantized on the host from the memory-mapped file;
|
| 11 |
+
* codec: conv / linear weights kept F16 (as stored) and cast to fp32 per layer; fp32 compute.
|
| 12 |
+
|
| 13 |
+
The GGUF was written by audio.cpp's converter: tensors whose names are longer than ggml allows are
|
| 14 |
+
stored as `_audiocpp.<i>`, with the real names (the original PyTorch checkpoint keys, prefixed
|
| 15 |
+
`model_weights/` or `codec_weights/`) in metadata `audiocpp.tensor_names` (index i = tensor i) and
|
| 16 |
+
their PyTorch shapes in `audiocpp.tensor_ranks` / `audiocpp.tensor_shapes`. The checkpoint's
|
| 17 |
+
config.json and tokenizer.json are embedded (`audiocpp.embedded_files.*`).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import functools
|
| 23 |
+
import json
|
| 24 |
+
import logging
|
| 25 |
+
import os
|
| 26 |
+
import struct
|
| 27 |
+
import sys
|
| 28 |
+
import time
|
| 29 |
+
from dataclasses import dataclass
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
import torch
|
| 33 |
+
import torch.nn as nn
|
| 34 |
+
import torch.nn.functional as F
|
| 35 |
+
|
| 36 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 37 |
+
|
| 38 |
+
import gguf_kernels as gk # noqa: E402
|
| 39 |
+
from fish_speech.models.dac.modded_dac import DAC, ModelArgs, WindowLimitedTransformer # noqa: E402
|
| 40 |
+
from fish_speech.models.dac.modded_dac import Conv1d as CodecConv1d # noqa: E402
|
| 41 |
+
from fish_speech.models.dac.modded_dac import ConvTranspose1d as CodecConvTranspose1d # noqa: E402
|
| 42 |
+
from fish_speech.models.dac.modded_dac import Linear as CodecLinear # noqa: E402
|
| 43 |
+
from fish_speech.models.dac.rvq import DownsampleResidualVectorQuantize # noqa: E402
|
| 44 |
+
from fish_speech.models.text2semantic.fish_omni.backbone import FishOmniBackbone # noqa: E402
|
| 45 |
+
from fish_speech.models.text2semantic.fish_omni.config import FishOmniConfig # noqa: E402
|
| 46 |
+
from fish_speech.models.text2semantic.fish_omni.tower import ( # noqa: E402
|
| 47 |
+
TOWER_CHECKPOINT_PREFIXES,
|
| 48 |
+
FishOmniAudioDecoder,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
logger = logging.getLogger("drama3_gguf")
|
| 52 |
+
|
| 53 |
+
MODEL_PREFIX = "model_weights/"
|
| 54 |
+
CODEC_PREFIX = "codec_weights/"
|
| 55 |
+
BACKBONE_PREFIX = "model.language_model."
|
| 56 |
+
EXPERT_PROJ = {"gate_proj": "gate", "up_proj": "up", "down_proj": "down"}
|
| 57 |
+
|
| 58 |
+
# --------------------------------------------------------------------------------------------
|
| 59 |
+
# GGUF file
|
| 60 |
+
# --------------------------------------------------------------------------------------------
|
| 61 |
+
|
| 62 |
+
_SCALARS = {0: ("<B", 1), 1: ("<b", 1), 2: ("<H", 2), 3: ("<h", 2), 4: ("<I", 4), 5: ("<i", 4), 6: ("<f", 4),
|
| 63 |
+
7: ("<?", 1), 10: ("<Q", 8), 11: ("<q", 8), 12: ("<d", 8)}
|
| 64 |
+
_NP = {0: np.uint8, 1: np.int8, 2: np.uint16, 3: np.int16, 4: np.uint32, 5: np.int32, 6: np.float32, 7: np.bool_,
|
| 65 |
+
10: np.uint64, 11: np.int64, 12: np.float64}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@dataclass
|
| 69 |
+
class TensorInfo:
|
| 70 |
+
name: str # real (checkpoint) name
|
| 71 |
+
qtype: int
|
| 72 |
+
shape: tuple[int, ...] # PyTorch order
|
| 73 |
+
offset: int # absolute file offset
|
| 74 |
+
nbytes: int
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class GGUFFile:
|
| 78 |
+
"""Minimal GGUF v3 reader (memory-mapped). gguf-py's GGUFReader parses the 27.9 MB embedded-file
|
| 79 |
+
array element by element (~2 min); this reads numeric arrays in bulk (milliseconds)."""
|
| 80 |
+
|
| 81 |
+
def __init__(self, path: str) -> None:
|
| 82 |
+
self.path = path
|
| 83 |
+
self.mm = np.memmap(path, dtype=np.uint8, mode="r")
|
| 84 |
+
mm, pos = self.mm, 0
|
| 85 |
+
|
| 86 |
+
def rd(fmt: str, size: int):
|
| 87 |
+
nonlocal pos
|
| 88 |
+
value = struct.unpack_from(fmt, mm, pos)[0]
|
| 89 |
+
pos += size
|
| 90 |
+
return value
|
| 91 |
+
|
| 92 |
+
def rstr() -> str:
|
| 93 |
+
nonlocal pos
|
| 94 |
+
n = rd("<Q", 8)
|
| 95 |
+
s = bytes(mm[pos : pos + n]).decode("utf-8")
|
| 96 |
+
pos += n
|
| 97 |
+
return s
|
| 98 |
+
|
| 99 |
+
def rval(t: int):
|
| 100 |
+
nonlocal pos
|
| 101 |
+
if t == 8:
|
| 102 |
+
return rstr()
|
| 103 |
+
if t == 9:
|
| 104 |
+
et, n = rd("<I", 4), rd("<Q", 8)
|
| 105 |
+
if et == 8:
|
| 106 |
+
return [rstr() for _ in range(n)]
|
| 107 |
+
if et == 9:
|
| 108 |
+
return [rval(9) for _ in range(n)]
|
| 109 |
+
a = np.frombuffer(mm, dtype=_NP[et], count=n, offset=pos)
|
| 110 |
+
pos += n * _SCALARS[et][1]
|
| 111 |
+
return a
|
| 112 |
+
return rd(*_SCALARS[t])
|
| 113 |
+
|
| 114 |
+
if bytes(mm[:4]) != b"GGUF":
|
| 115 |
+
raise ValueError(f"{path} is not a GGUF file")
|
| 116 |
+
pos = 4
|
| 117 |
+
self.version = rd("<I", 4)
|
| 118 |
+
n_tensors, n_kv = rd("<Q", 8), rd("<Q", 8)
|
| 119 |
+
self.metadata: dict = {}
|
| 120 |
+
for _ in range(n_kv):
|
| 121 |
+
key = rstr()
|
| 122 |
+
self.metadata[key] = rval(rd("<I", 4))
|
| 123 |
+
raw = []
|
| 124 |
+
for _ in range(n_tensors):
|
| 125 |
+
name = rstr()
|
| 126 |
+
dims = [rd("<Q", 8) for _ in range(rd("<I", 4))]
|
| 127 |
+
raw.append((name, dims, rd("<I", 4), rd("<Q", 8)))
|
| 128 |
+
align = int(self.metadata.get("general.alignment", 32))
|
| 129 |
+
data_start = (pos + align - 1) // align * align
|
| 130 |
+
names = self.metadata.get("audiocpp.tensor_names")
|
| 131 |
+
ranks = self.metadata.get("audiocpp.tensor_ranks")
|
| 132 |
+
flat_shapes = self.metadata.get("audiocpp.tensor_shapes")
|
| 133 |
+
bounds = np.concatenate([[0], np.cumsum(ranks)]) if ranks is not None else None
|
| 134 |
+
self.tensors: dict[str, TensorInfo] = {}
|
| 135 |
+
for i, (name, dims, qtype, off) in enumerate(raw):
|
| 136 |
+
real = name
|
| 137 |
+
if names is not None:
|
| 138 |
+
if name.startswith("_audiocpp."):
|
| 139 |
+
real = names[int(name.split(".", 1)[1])]
|
| 140 |
+
elif names[i] != name:
|
| 141 |
+
raise ValueError(f"tensor {i} is {name!r} but audiocpp.tensor_names has {names[i]!r}")
|
| 142 |
+
if bounds is not None:
|
| 143 |
+
shape = tuple(int(v) for v in flat_shapes[bounds[i] : bounds[i + 1]])
|
| 144 |
+
else:
|
| 145 |
+
shape = tuple(int(v) for v in reversed(dims))
|
| 146 |
+
if int(np.prod(shape)) != int(np.prod(dims)):
|
| 147 |
+
raise ValueError(f"{real}: shape {shape} does not match ggml dims {dims}")
|
| 148 |
+
if qtype not in gk.BLOCK:
|
| 149 |
+
raise NotImplementedError(f"{real}: ggml type {qtype} is not supported")
|
| 150 |
+
block, size = gk.BLOCK[qtype]
|
| 151 |
+
nbytes = int(np.prod(dims)) // block * size
|
| 152 |
+
self.tensors[real] = TensorInfo(real, qtype, shape, data_start + off, nbytes)
|
| 153 |
+
|
| 154 |
+
def embedded_file(self, name: str) -> bytes:
|
| 155 |
+
names = self.metadata["audiocpp.embedded_files.names"]
|
| 156 |
+
offsets = self.metadata["audiocpp.embedded_files.offsets"]
|
| 157 |
+
data = self.metadata["audiocpp.embedded_files.data"]
|
| 158 |
+
i = names.index(name)
|
| 159 |
+
return bytes(data[int(offsets[i]) : int(offsets[i + 1])])
|
| 160 |
+
|
| 161 |
+
def raw(self, name: str) -> np.ndarray:
|
| 162 |
+
"""uint8 [rows, row_bytes] view of a tensor (rows = prod(shape[:-1]))."""
|
| 163 |
+
info = self.tensors[name]
|
| 164 |
+
rb = gk.row_bytes(info.qtype, info.shape[-1])
|
| 165 |
+
view = np.frombuffer(self.mm, dtype=np.uint8, count=info.nbytes, offset=info.offset)
|
| 166 |
+
return view.reshape(-1, rb)
|
| 167 |
+
|
| 168 |
+
def packed(self, name: str, device) -> torch.Tensor:
|
| 169 |
+
"""Packed bytes on the device, shaped shape[:-1] + [row_bytes]."""
|
| 170 |
+
info = self.tensors[name]
|
| 171 |
+
host = torch.from_numpy(np.array(self.raw(name))) # one copy out of the page cache
|
| 172 |
+
return host.reshape(*info.shape[:-1], -1).to(device)
|
| 173 |
+
|
| 174 |
+
def tensor(self, name: str, device, dtype: torch.dtype = torch.float32) -> torch.Tensor:
|
| 175 |
+
"""Dequantized tensor in PyTorch shape (dequantization runs on `device`)."""
|
| 176 |
+
info = self.tensors[name]
|
| 177 |
+
q = self.packed(name, device)
|
| 178 |
+
return gk.dequantize_torch(q, info.qtype, info.shape[-1], dtype).reshape(info.shape)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
# --------------------------------------------------------------------------------------------
|
| 182 |
+
# Token embedding
|
| 183 |
+
# --------------------------------------------------------------------------------------------
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class GGUFEmbedding(nn.Module):
|
| 187 |
+
"""Token embedding with the full table packed on the host (memory-mapped GGUF rows) and the
|
| 188 |
+
semantic band [band_start, band_start + band_size) dequantized on the device.
|
| 189 |
+
|
| 190 |
+
CUDA ids are looked up in the band (decode: the main token is always a semantic token, or EOS,
|
| 191 |
+
which ends the take); CPU ids are dequantized row by row on the host (prompts)."""
|
| 192 |
+
|
| 193 |
+
def __init__(self, gguf: GGUFFile, name: str, band_start: int, band_size: int, device, dtype) -> None:
|
| 194 |
+
super().__init__()
|
| 195 |
+
info = gguf.tensors[name]
|
| 196 |
+
self.raw = gguf.raw(name)
|
| 197 |
+
self.qtype, self.dim = info.qtype, info.shape[-1]
|
| 198 |
+
self.num_embeddings = info.shape[0]
|
| 199 |
+
self.band_start, self.band_size = band_start, band_size
|
| 200 |
+
self.dtype = dtype
|
| 201 |
+
band = torch.from_numpy(np.array(self.raw[band_start : band_start + band_size])).to(device)
|
| 202 |
+
self.register_buffer("band", gk.dequantize_torch(band, self.qtype, self.dim, dtype), persistent=False)
|
| 203 |
+
|
| 204 |
+
def forward(self, ids: torch.Tensor) -> torch.Tensor:
|
| 205 |
+
if ids.is_cuda:
|
| 206 |
+
return F.embedding((ids - self.band_start).clamp(0, self.band_size - 1), self.band)
|
| 207 |
+
flat = ids.reshape(-1).numpy()
|
| 208 |
+
rows = torch.from_numpy(self.raw[flat])
|
| 209 |
+
out = gk.dequantize_torch(rows, self.qtype, self.dim, torch.float32).to(self.dtype)
|
| 210 |
+
return out.reshape(*ids.shape, self.dim).to(self.band.device)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# --------------------------------------------------------------------------------------------
|
| 214 |
+
# Model
|
| 215 |
+
# --------------------------------------------------------------------------------------------
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class Drama3Model(nn.Module):
|
| 219 |
+
"""Container used by fish_omni.generate: backbone + tower + tokenizer (+ decode state)."""
|
| 220 |
+
|
| 221 |
+
def __init__(self, config: FishOmniConfig, backbone: FishOmniBackbone, audio_decoder: FishOmniAudioDecoder,
|
| 222 |
+
tokenizer) -> None:
|
| 223 |
+
super().__init__()
|
| 224 |
+
self.config = config
|
| 225 |
+
self.backbone = backbone
|
| 226 |
+
self.audio_decoder = audio_decoder
|
| 227 |
+
self.tokenizer = tokenizer
|
| 228 |
+
self.cache_capacity = 0
|
| 229 |
+
self.decode_graphs = None
|
| 230 |
+
|
| 231 |
+
@property
|
| 232 |
+
def device(self) -> torch.device:
|
| 233 |
+
return self.audio_decoder.device
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _set_param(module: nn.Module, name: str, value: torch.Tensor) -> None:
|
| 237 |
+
owner, _, leaf = name.rpartition(".")
|
| 238 |
+
target = module.get_submodule(owner) if owner else module
|
| 239 |
+
old = getattr(target, leaf)
|
| 240 |
+
if tuple(old.shape) != tuple(value.shape):
|
| 241 |
+
raise ValueError(f"{name}: GGUF shape {tuple(value.shape)} != {tuple(old.shape)}")
|
| 242 |
+
if isinstance(old, nn.Parameter):
|
| 243 |
+
setattr(target, leaf, nn.Parameter(value, requires_grad=False))
|
| 244 |
+
else:
|
| 245 |
+
setattr(target, leaf, value)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def load_model(gguf: GGUFFile, device="cuda:0", dtype: torch.dtype = torch.bfloat16) -> Drama3Model:
|
| 249 |
+
from tokenizers import Tokenizer
|
| 250 |
+
|
| 251 |
+
device = torch.device(device)
|
| 252 |
+
started = time.perf_counter()
|
| 253 |
+
config = FishOmniConfig.from_dict(json.loads(gguf.embedded_file("config.json")))
|
| 254 |
+
tokenizer = Tokenizer.from_str(gguf.embedded_file("tokenizer.json").decode("utf-8"))
|
| 255 |
+
head = gguf.tensors[MODEL_PREFIX + "lm_head.weight"]
|
| 256 |
+
head_rows = head.shape[0] if head.shape[0] != config.text.vocab_size else 0
|
| 257 |
+
if head_rows and head_rows != config.audio_decoder.vocab_size + 1:
|
| 258 |
+
raise ValueError(f"lm_head has {head_rows} rows; expected the full vocabulary or EOS + semantic")
|
| 259 |
+
|
| 260 |
+
with torch.device("meta"):
|
| 261 |
+
backbone = FishOmniBackbone(config.text, dtype=dtype, head_rows=head_rows)
|
| 262 |
+
tower = FishOmniAudioDecoder(config, dtype=dtype)
|
| 263 |
+
# Parameters are created from the GGUF straight into the meta-device modules (no placeholder copies).
|
| 264 |
+
backbone.model.embed_tokens = GGUFEmbedding(
|
| 265 |
+
gguf, MODEL_PREFIX + BACKBONE_PREFIX + "embed_tokens.weight", config.semantic_start_token_id,
|
| 266 |
+
config.audio_decoder.vocab_size, device, dtype)
|
| 267 |
+
targets = dict(backbone.named_parameters())
|
| 268 |
+
tower_targets = dict(tower.named_parameters())
|
| 269 |
+
banks = {}
|
| 270 |
+
for name, info in gguf.tensors.items():
|
| 271 |
+
if not name.startswith(MODEL_PREFIX):
|
| 272 |
+
continue
|
| 273 |
+
key = name[len(MODEL_PREFIX) :]
|
| 274 |
+
if key.startswith("audio_decoder"):
|
| 275 |
+
tname = next((new + key[len(old) :] for old, new in TOWER_CHECKPOINT_PREFIXES.items()
|
| 276 |
+
if key.startswith(old)), None)
|
| 277 |
+
if tname not in tower_targets:
|
| 278 |
+
raise ValueError(f"unknown tower tensor {name}")
|
| 279 |
+
_set_param(tower, tname, gguf.tensor(name, device, torch.float32).to(tower_targets[tname].dtype))
|
| 280 |
+
continue
|
| 281 |
+
if key == "lm_head.weight":
|
| 282 |
+
_set_param(backbone, "lm_head.weight", gguf.tensor(name, device, torch.float32))
|
| 283 |
+
continue
|
| 284 |
+
if not key.startswith(BACKBONE_PREFIX):
|
| 285 |
+
raise ValueError(f"unexpected model tensor {name}")
|
| 286 |
+
pname = "model." + key[len(BACKBONE_PREFIX) :]
|
| 287 |
+
if pname == "model.embed_tokens.weight":
|
| 288 |
+
continue
|
| 289 |
+
if ".mlp.experts." in pname:
|
| 290 |
+
layer = int(pname.split(".")[2])
|
| 291 |
+
proj = EXPERT_PROJ[pname.split(".")[5]]
|
| 292 |
+
banks.setdefault(layer, {})[proj] = (gguf.packed(name, device), info.qtype)
|
| 293 |
+
continue
|
| 294 |
+
if pname not in targets:
|
| 295 |
+
raise ValueError(f"GGUF tensor {name} has no backbone parameter {pname}")
|
| 296 |
+
_set_param(backbone, pname, gguf.tensor(name, device, torch.float32).to(targets[pname].dtype))
|
| 297 |
+
del targets, tower_targets
|
| 298 |
+
for index, layer in enumerate(backbone.model.layers):
|
| 299 |
+
if set(banks.get(index, {})) != {"gate", "up", "down"}:
|
| 300 |
+
raise ValueError(f"layer {index}: expert banks incomplete")
|
| 301 |
+
layer.mlp.experts.set_banks(banks[index])
|
| 302 |
+
for module, label in ((backbone, "backbone"), (tower, "tower")):
|
| 303 |
+
left = [n for n, t in (*module.named_parameters(), *module.named_buffers()) if t.is_meta]
|
| 304 |
+
if left:
|
| 305 |
+
raise ValueError(f"{label} tensors not in the GGUF: {left[:8]}")
|
| 306 |
+
for p in [*backbone.parameters(), *tower.parameters()]:
|
| 307 |
+
p.requires_grad_(False)
|
| 308 |
+
model = Drama3Model(config, backbone, tower, tokenizer).eval()
|
| 309 |
+
if device.type == "cuda":
|
| 310 |
+
torch.cuda.synchronize(device)
|
| 311 |
+
logger.info(f"model loaded in {time.perf_counter() - started:.1f}s; "
|
| 312 |
+
f"experts {sum(b.numel() for l in banks.values() for b, _ in l.values()) / 2**30:.2f} GiB packed")
|
| 313 |
+
return model
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
# --------------------------------------------------------------------------------------------
|
| 317 |
+
# Codec
|
| 318 |
+
# --------------------------------------------------------------------------------------------
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def build_codec() -> DAC:
|
| 322 |
+
"""Fish DAC as configs/modded_dac_vq.yaml (fish-speech 1ff3c3e) builds it, without Hydra."""
|
| 323 |
+
general = functools.partial(ModelArgs, block_size=8192, n_local_heads=-1, head_dim=64, rope_base=10000,
|
| 324 |
+
norm_eps=1e-5, dropout_rate=0.1, attn_dropout_rate=0.1, channels_first=True)
|
| 325 |
+
|
| 326 |
+
def transformer() -> WindowLimitedTransformer:
|
| 327 |
+
config = ModelArgs(block_size=2048, n_layer=8, n_head=16, dim=1024, intermediate_size=3072,
|
| 328 |
+
n_local_heads=-1, head_dim=64, rope_base=10000, norm_eps=1e-5, dropout_rate=0.1,
|
| 329 |
+
attn_dropout_rate=0.1, channels_first=True)
|
| 330 |
+
return WindowLimitedTransformer(causal=True, window_size=128, input_dim=1024, config=config)
|
| 331 |
+
|
| 332 |
+
quantizer = DownsampleResidualVectorQuantize(
|
| 333 |
+
input_dim=1024, n_codebooks=9, codebook_size=1024, codebook_dim=8, quantizer_dropout=0.5,
|
| 334 |
+
downsample_factor=[2, 2], post_module=transformer(), pre_module=transformer(),
|
| 335 |
+
semantic_codebook_size=4096)
|
| 336 |
+
return DAC(sample_rate=44100, encoder_dim=64, encoder_rates=[2, 4, 8, 8], decoder_dim=1536,
|
| 337 |
+
decoder_rates=[8, 8, 4, 2], encoder_transformer_layers=[0, 0, 0, 4],
|
| 338 |
+
decoder_transformer_layers=[4, 0, 0, 0], transformer_general_config=general,
|
| 339 |
+
quantizer=quantizer)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def load_codec(gguf: GGUFFile, device="cuda:0", weight_dtype: torch.dtype = torch.float16) -> DAC:
|
| 343 |
+
"""Codec with conv / linear weights in weight_dtype (cast per layer) and the rest in fp32."""
|
| 344 |
+
device = torch.device(device)
|
| 345 |
+
with torch.device("meta"):
|
| 346 |
+
codec = build_codec()
|
| 347 |
+
big = {f"{n}.weight" for n, m in codec.named_modules()
|
| 348 |
+
if isinstance(m, (CodecConv1d, CodecConvTranspose1d, CodecLinear))}
|
| 349 |
+
params = dict(codec.named_parameters())
|
| 350 |
+
for name, info in gguf.tensors.items():
|
| 351 |
+
if not name.startswith(CODEC_PREFIX):
|
| 352 |
+
continue
|
| 353 |
+
key = name[len(CODEC_PREFIX) :]
|
| 354 |
+
if key.endswith((".causal_mask", ".freqs_cis")):
|
| 355 |
+
continue # buffers rebuilt on the fly
|
| 356 |
+
if key not in params:
|
| 357 |
+
raise ValueError(f"GGUF codec tensor {key} has no parameter")
|
| 358 |
+
dtype = weight_dtype if key in big else torch.float32
|
| 359 |
+
_set_param(codec, key, gguf.tensor(name, device, torch.float32).reshape(params[key].shape).to(dtype))
|
| 360 |
+
del params
|
| 361 |
+
left = [n for n, t in (*codec.named_parameters(), *codec.named_buffers()) if t.is_meta]
|
| 362 |
+
if left:
|
| 363 |
+
raise ValueError(f"codec parameters not in the GGUF: {left[:8]}")
|
| 364 |
+
for p in codec.parameters():
|
| 365 |
+
p.requires_grad_(False)
|
| 366 |
+
return codec.eval()
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
ENCODER_HOP = 512 # product of the encoder strides
|
| 370 |
+
ENCODE_CONTEXT = 16384 # samples of left context per window, >= the conv receptive field (~7k samples)
|
| 371 |
+
DECODE_CONTEXT = 16 # latent frames of left context per decode chunk (conv receptive field ~7 frames)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def codec_device(codec: DAC) -> torch.device:
|
| 375 |
+
return next(codec.decoder.parameters()).device
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def encoder_modules(codec: DAC) -> list[nn.Module]:
|
| 379 |
+
"""The parts only reference encoding needs (encoder, quantizer downsample + pre transformer)."""
|
| 380 |
+
return [codec.encoder, codec.quantizer.downsample, codec.quantizer.pre_module]
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def offload_encoder(codec: DAC) -> None:
|
| 384 |
+
"""Keep the encoder-side weights (~0.37 GiB) in host RAM between reference encodes."""
|
| 385 |
+
for m in encoder_modules(codec):
|
| 386 |
+
m.to("cpu")
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@torch.inference_mode()
|
| 390 |
+
def encode_audio(codec: DAC, wav: torch.Tensor, chunk: int = 131072) -> torch.Tensor:
|
| 391 |
+
"""Mono waveform [T] at 44.1 kHz -> codes [10, frames] (long, CPU).
|
| 392 |
+
|
| 393 |
+
The convolutional encoder (causal, finite receptive field) runs over windows of `chunk` samples
|
| 394 |
+
with ENCODE_CONTEXT samples of real left context, so memory does not grow with the reference;
|
| 395 |
+
the encoder transformer, final conv and quantizer then run over the whole feature sequence.
|
| 396 |
+
Same result as one full-length pass up to float rounding (audio.cpp windows its encoder the
|
| 397 |
+
same way). Offloaded encoder weights are brought to the codec's device for the call."""
|
| 398 |
+
device = codec_device(codec)
|
| 399 |
+
offloaded = next(codec.encoder.parameters()).device != device
|
| 400 |
+
if offloaded:
|
| 401 |
+
for m in encoder_modules(codec):
|
| 402 |
+
m.to(device)
|
| 403 |
+
try:
|
| 404 |
+
frame = codec.frame_length
|
| 405 |
+
length = wav.shape[-1]
|
| 406 |
+
padded = -(-length // frame) * frame
|
| 407 |
+
x = F.pad(wav.to(device, torch.float32), (0, padded - length))
|
| 408 |
+
blocks = codec.encoder.block
|
| 409 |
+
convs = nn.Sequential(*blocks[:4], *blocks[4].block[:5])
|
| 410 |
+
tail = nn.Sequential(blocks[4].block[5], *blocks[5:])
|
| 411 |
+
if chunk <= 0 or padded <= chunk + ENCODE_CONTEXT:
|
| 412 |
+
feats = convs(x[None, None])
|
| 413 |
+
else:
|
| 414 |
+
assert chunk % ENCODER_HOP == 0
|
| 415 |
+
parts = []
|
| 416 |
+
for start in range(0, padded, chunk):
|
| 417 |
+
ctx = min(start, ENCODE_CONTEXT)
|
| 418 |
+
out = convs(x[None, None, start - ctx : min(start + chunk, padded)])
|
| 419 |
+
parts.append(out[..., ctx // ENCODER_HOP :])
|
| 420 |
+
feats = torch.cat(parts, dim=-1)
|
| 421 |
+
codes = codec.quantizer.encode_codes(tail(feats))
|
| 422 |
+
return codes[0, :, : -(-length // frame)].long().cpu()
|
| 423 |
+
finally:
|
| 424 |
+
if offloaded:
|
| 425 |
+
offload_encoder(codec)
|
| 426 |
+
if device.type == "cuda":
|
| 427 |
+
torch.cuda.empty_cache()
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
@torch.inference_mode()
|
| 431 |
+
def decode_codes(codec: DAC, codes: torch.Tensor, chunk: int = 48) -> torch.Tensor:
|
| 432 |
+
"""Codes [10, frames] -> float32 waveform [frames * 2048] on the codec's device.
|
| 433 |
+
|
| 434 |
+
Codebook lookup and the quantizer's post transformer run over the whole take; the causal
|
| 435 |
+
convolutional upsampler / decoder runs in chunks of `chunk` frames with DECODE_CONTEXT frames of
|
| 436 |
+
left context, so memory does not grow with the take (same result as one full pass)."""
|
| 437 |
+
device = codec_device(codec)
|
| 438 |
+
q = codec.quantizer
|
| 439 |
+
idx = codes[None].to(device).clone()
|
| 440 |
+
idx[:, 0] = idx[:, 0].clamp(max=q.semantic_quantizer.codebook_size - 1)
|
| 441 |
+
idx[:, 1:] = idx[:, 1:].clamp(max=q.quantizer.codebook_size - 1)
|
| 442 |
+
z = q.semantic_quantizer.from_codes(idx[:, :1]) + q.quantizer.from_codes(idx[:, 1:])
|
| 443 |
+
z = q.post_module(z.float())
|
| 444 |
+
n = z.shape[-1]
|
| 445 |
+
samples = codec.frame_length
|
| 446 |
+
if chunk <= 0 or n <= chunk + DECODE_CONTEXT:
|
| 447 |
+
return codec.decoder(q.upsample(z))[0, 0]
|
| 448 |
+
out = []
|
| 449 |
+
for start in range(0, n, chunk):
|
| 450 |
+
ctx = min(start, DECODE_CONTEXT)
|
| 451 |
+
y = codec.decoder(q.upsample(z[..., start - ctx : start + chunk]))
|
| 452 |
+
out.append(y[0, 0, ctx * samples :])
|
| 453 |
+
return torch.cat(out)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def load(path: str, device="cuda:0", codec: bool = True) -> tuple[Drama3Model, DAC | None]:
|
| 457 |
+
gguf = GGUFFile(path)
|
| 458 |
+
model = load_model(gguf, device)
|
| 459 |
+
return model, (load_codec(gguf, device) if codec else None)
|
torch/fish_speech/VENDOR.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Vendored Fish Audio code
|
| 2 |
+
|
| 3 |
+
| Path | Upstream | Commit | License |
|
| 4 |
+
|---|---|---|---|
|
| 5 |
+
| `models/text2semantic/fish_omni/{config,layers,backbone,moe,tower,generate}.py` | github.com/fishaudio/fish-speech | `1ff3c3ed2f80d3106a83909dd25b83129c3d816f` (2026-10-13, "Update for Drama-3") | Fish Audio Community License v1.0 (`../LICENSE`) |
|
| 6 |
+
| `models/text2semantic/{sampling,errors}.py` | same | same | same |
|
| 7 |
+
| `models/dac/{modded_dac,rvq}.py` | same | same | same |
|
| 8 |
+
|
| 9 |
+
These Fish Audio Materials are licensed under the Fish Audio Community License, Version 1.0.
|
| 10 |
+
Copyright © 39 AI, INC. All Rights Reserved. Built with Fish Audio.
|
| 11 |
+
|
| 12 |
+
## Changes to upstream
|
| 13 |
+
|
| 14 |
+
Every modified file starts with a comment listing its changes. In short:
|
| 15 |
+
|
| 16 |
+
1. Imports made package-relative; `loguru` / `tqdm` replaced by stdlib `logging`; `fish_omni/model.py`,
|
| 17 |
+
`fp8_moe.py`, `chunking.py` and `models/dac/inference.py` are not included.
|
| 18 |
+
2. `config.py`: the GGUF keeps the FP8 checkpoint's `quantization_config`, but experts are GGUF banks
|
| 19 |
+
(`fp8_experts` is always false); reads `semantic_head_rows`.
|
| 20 |
+
3. `moe.py`: routed experts are packed GGUF banks (IQ4_XS / Q5_K) dequantized on the fly
|
| 21 |
+
(`PackedExperts`, kernels in `../gguf_kernels.py`); router and shared-expert gate in fp32.
|
| 22 |
+
4. `backbone.py`: no FP8 / checkpoint loading (moved to `../drama3_gguf.py`); optional speech-only
|
| 23 |
+
head (`head_rows`); the token embedding may be a host-side GGUF table.
|
| 24 |
+
5. `tower.py`: `decode_step` accepts speech-only head logits.
|
| 25 |
+
6. `generate.py`: prompt builder unchanged; the generation loop follows audio.cpp's fish_drama3
|
| 26 |
+
generator (drama3-medium patch: repetition-aware sampling over generated frames, pause fix, length
|
| 27 |
+
guard, tag-aware text chunking) with CUDA-graph decode adapted to the speech head.
|
| 28 |
+
7. `models/dac/*`: inference-only rewrite without `audiotools` / `descript-audio-codec`
|
| 29 |
+
(local Snake1d and VectorQuantize, folded weight norm, no 32k x 32k mask buffers, weights cast per
|
| 30 |
+
layer so F16 storage can compute in fp32).
|
torch/fish_speech/__init__.py
ADDED
|
File without changes
|
torch/fish_speech/models/__init__.py
ADDED
|
File without changes
|
torch/fish_speech/models/dac/__init__.py
ADDED
|
File without changes
|
torch/fish_speech/models/dac/modded_dac.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified for the drama3-expressive-medium PyTorch port (GGUF runtime), inference only:
|
| 2 |
+
# * no audiotools / descript-audio-codec dependency: Snake1d is defined here, and the
|
| 3 |
+
# weight-normalized convolutions are plain convolutions (the GGUF stores folded weights);
|
| 4 |
+
# * Conv / Linear layers cast their weights to the input dtype, so the large weights can stay
|
| 5 |
+
# F16 (as stored in the GGUF) while the codec computes in fp32;
|
| 6 |
+
# * no 32768 x 32768 causal-mask buffers (WindowLimitedTransformer always passes its own mask);
|
| 7 |
+
# RoPE tables are built per length with upstream's bf16 rounding;
|
| 8 |
+
# * training-only code (dropout, conformer positions, KV caches, losses, init) removed.
|
| 9 |
+
import math
|
| 10 |
+
import typing as tp
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from typing import List, Optional, Union
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from torch import Tensor, nn
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Conv1d(nn.Conv1d):
|
| 21 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 22 |
+
b = None if self.bias is None else self.bias.to(x.dtype)
|
| 23 |
+
return self._conv_forward(x, self.weight.to(x.dtype), b)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ConvTranspose1d(nn.ConvTranspose1d):
|
| 27 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 28 |
+
b = None if self.bias is None else self.bias.to(x.dtype)
|
| 29 |
+
return F.conv_transpose1d(x, self.weight.to(x.dtype), b, self.stride, self.padding,
|
| 30 |
+
self.output_padding, self.groups, self.dilation)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Linear(nn.Linear):
|
| 34 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 35 |
+
b = None if self.bias is None else self.bias.to(x.dtype)
|
| 36 |
+
return F.linear(x, self.weight.to(x.dtype), b)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Snake1d(nn.Module):
|
| 40 |
+
"""x + 1/alpha * sin(alpha * x)^2 (descript-audio-codec dac.nn.layers.Snake1d)."""
|
| 41 |
+
|
| 42 |
+
def __init__(self, channels: int):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.alpha = nn.Parameter(torch.ones(1, channels, 1))
|
| 45 |
+
|
| 46 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 47 |
+
shape = x.shape
|
| 48 |
+
x = x.reshape(shape[0], shape[1], -1)
|
| 49 |
+
alpha = self.alpha.to(x.dtype)
|
| 50 |
+
x = x + (alpha + 1e-9).reciprocal() * torch.sin(alpha * x).pow(2)
|
| 51 |
+
return x.reshape(shape)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def find_multiple(n: int, k: int) -> int:
|
| 55 |
+
if n % k == 0:
|
| 56 |
+
return n
|
| 57 |
+
return n + k - (n % k)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@dataclass
|
| 61 |
+
class ModelArgs:
|
| 62 |
+
block_size: int = 2048
|
| 63 |
+
n_layer: int = 8
|
| 64 |
+
n_head: int = 8
|
| 65 |
+
dim: int = 512
|
| 66 |
+
intermediate_size: int = 1536
|
| 67 |
+
n_local_heads: int = -1
|
| 68 |
+
head_dim: int = 64
|
| 69 |
+
rope_base: float = 10000
|
| 70 |
+
norm_eps: float = 1e-5
|
| 71 |
+
dropout_rate: float = 0.1
|
| 72 |
+
attn_dropout_rate: float = 0.1
|
| 73 |
+
channels_first: bool = True # to be compatible with conv1d input/output
|
| 74 |
+
pos_embed_type: str = "rope"
|
| 75 |
+
max_relative_position: int = 128
|
| 76 |
+
window_size: int = 512
|
| 77 |
+
|
| 78 |
+
def __post_init__(self):
|
| 79 |
+
if self.n_local_heads == -1:
|
| 80 |
+
self.n_local_heads = self.n_head
|
| 81 |
+
if self.intermediate_size is None:
|
| 82 |
+
hidden_dim = 4 * self.dim
|
| 83 |
+
n_hidden = int(2 * hidden_dim / 3)
|
| 84 |
+
self.intermediate_size = find_multiple(n_hidden, 256)
|
| 85 |
+
assert self.pos_embed_type == "rope", "only RoPE positions are supported"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class Transformer(nn.Module):
|
| 89 |
+
def __init__(self, config: ModelArgs) -> None:
|
| 90 |
+
super().__init__()
|
| 91 |
+
self.config = config
|
| 92 |
+
self.layers = nn.ModuleList(TransformerBlock(config) for _ in range(config.n_layer))
|
| 93 |
+
self.norm = RMSNorm(config.dim, eps=config.norm_eps)
|
| 94 |
+
self._freqs: Tensor | None = None
|
| 95 |
+
|
| 96 |
+
def freqs_cis(self, length: int, device) -> Tensor:
|
| 97 |
+
if self._freqs is None or self._freqs.shape[0] < length or self._freqs.device != device:
|
| 98 |
+
self._freqs = precompute_freqs_cis(max(length, 4096), self.config.head_dim,
|
| 99 |
+
self.config.rope_base).to(device)
|
| 100 |
+
return self._freqs
|
| 101 |
+
|
| 102 |
+
def forward(self, x: Tensor, input_pos: Tensor, mask: Tensor) -> Tensor:
|
| 103 |
+
freqs_cis = self.freqs_cis(int(input_pos[-1]) + 1, x.device)[input_pos]
|
| 104 |
+
for layer in self.layers:
|
| 105 |
+
x = layer(x, input_pos, freqs_cis, mask)
|
| 106 |
+
return self.norm(x)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class TransformerBlock(nn.Module):
|
| 110 |
+
def __init__(self, config: ModelArgs) -> None:
|
| 111 |
+
super().__init__()
|
| 112 |
+
self.attention = Attention(config)
|
| 113 |
+
self.feed_forward = FeedForward(config)
|
| 114 |
+
self.ffn_norm = RMSNorm(config.dim, eps=config.norm_eps)
|
| 115 |
+
self.attention_norm = RMSNorm(config.dim, eps=config.norm_eps)
|
| 116 |
+
self.attention_layer_scale = LayerScale(config.dim, inplace=True)
|
| 117 |
+
self.ffn_layer_scale = LayerScale(config.dim, inplace=True)
|
| 118 |
+
|
| 119 |
+
def forward(self, x: Tensor, input_pos: Tensor, freqs_cis: Tensor, mask: Tensor) -> Tensor:
|
| 120 |
+
h = x + self.attention_layer_scale(self.attention(self.attention_norm(x), freqs_cis, mask, input_pos))
|
| 121 |
+
return h + self.ffn_layer_scale(self.feed_forward(self.ffn_norm(h)))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class Attention(nn.Module):
|
| 125 |
+
def __init__(self, config: ModelArgs):
|
| 126 |
+
super().__init__()
|
| 127 |
+
assert config.dim % config.n_head == 0
|
| 128 |
+
total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
|
| 129 |
+
self.wqkv = Linear(config.dim, total_head_dim, bias=False)
|
| 130 |
+
self.wo = Linear(config.head_dim * config.n_head, config.dim, bias=False)
|
| 131 |
+
self.n_head = config.n_head
|
| 132 |
+
self.head_dim = config.head_dim
|
| 133 |
+
self.n_local_heads = config.n_local_heads
|
| 134 |
+
self.dim = config.dim
|
| 135 |
+
|
| 136 |
+
def forward(self, x: Tensor, freqs_cis: Tensor, mask: Tensor, input_pos: Optional[Tensor] = None) -> Tensor:
|
| 137 |
+
bsz, seqlen, _ = x.shape
|
| 138 |
+
kv_size = self.n_local_heads * self.head_dim
|
| 139 |
+
q, k, v = self.wqkv(x).split([kv_size, kv_size, kv_size], dim=-1)
|
| 140 |
+
q = q.view(bsz, seqlen, self.n_head, self.head_dim)
|
| 141 |
+
k = k.view(bsz, seqlen, self.n_local_heads, self.head_dim)
|
| 142 |
+
v = v.view(bsz, seqlen, self.n_local_heads, self.head_dim)
|
| 143 |
+
q = apply_rotary_emb(q, freqs_cis)
|
| 144 |
+
k = apply_rotary_emb(k, freqs_cis)
|
| 145 |
+
q, k, v = map(lambda t: t.transpose(1, 2), (q, k, v))
|
| 146 |
+
k = k.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
|
| 147 |
+
v = v.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
|
| 148 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
| 149 |
+
y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.head_dim * self.n_head)
|
| 150 |
+
return self.wo(y)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class FeedForward(nn.Module):
|
| 154 |
+
def __init__(self, config: ModelArgs) -> None:
|
| 155 |
+
super().__init__()
|
| 156 |
+
self.w1 = Linear(config.dim, config.intermediate_size, bias=False)
|
| 157 |
+
self.w3 = Linear(config.dim, config.intermediate_size, bias=False)
|
| 158 |
+
self.w2 = Linear(config.intermediate_size, config.dim, bias=False)
|
| 159 |
+
|
| 160 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 161 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class RMSNorm(nn.Module):
|
| 165 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 166 |
+
super().__init__()
|
| 167 |
+
self.eps = eps
|
| 168 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 169 |
+
|
| 170 |
+
def _norm(self, x):
|
| 171 |
+
return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
|
| 172 |
+
|
| 173 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 174 |
+
output = self._norm(x.float()).type_as(x)
|
| 175 |
+
return output * self.weight.to(x.dtype)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class LayerScale(nn.Module):
|
| 179 |
+
def __init__(self, dim: int, init_values: Union[float, Tensor] = 1e-2, inplace: bool = False) -> None:
|
| 180 |
+
super().__init__()
|
| 181 |
+
self.inplace = inplace
|
| 182 |
+
self.gamma = nn.Parameter(init_values * torch.ones(dim))
|
| 183 |
+
|
| 184 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 185 |
+
gamma = self.gamma.to(x.dtype)
|
| 186 |
+
return x.mul_(gamma) if self.inplace else x * gamma
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class WindowLimitedTransformer(Transformer):
|
| 190 |
+
"""Transformer with window limited attention, causal."""
|
| 191 |
+
|
| 192 |
+
def __init__(self, config: ModelArgs, input_dim: int = 512, window_size: Optional[int] = None,
|
| 193 |
+
causal: bool = True, look_ahead_conv: nn.Module = None):
|
| 194 |
+
super().__init__(config)
|
| 195 |
+
self.window_size = window_size
|
| 196 |
+
self.causal = causal
|
| 197 |
+
self.channels_first = config.channels_first
|
| 198 |
+
self.look_ahead_conv = look_ahead_conv if look_ahead_conv is not None else nn.Identity()
|
| 199 |
+
self.input_proj = Linear(input_dim, config.dim) if input_dim != config.dim else nn.Identity()
|
| 200 |
+
self.output_proj = Linear(config.dim, input_dim) if input_dim != config.dim else nn.Identity()
|
| 201 |
+
|
| 202 |
+
def make_mask(self, max_length: int, device) -> Tensor:
|
| 203 |
+
if not self.causal:
|
| 204 |
+
raise NotImplementedError
|
| 205 |
+
rows = torch.arange(max_length, device=device).view(-1, 1)
|
| 206 |
+
cols = torch.arange(max_length, device=device).view(1, -1)
|
| 207 |
+
mask = cols <= rows
|
| 208 |
+
if self.window_size is not None:
|
| 209 |
+
mask &= cols >= (rows - self.window_size + 1).clamp(min=0)
|
| 210 |
+
return mask[None, None]
|
| 211 |
+
|
| 212 |
+
def forward(self, x: Tensor, x_lens: Optional[Tensor] = None) -> Tensor:
|
| 213 |
+
if self.channels_first:
|
| 214 |
+
x = x.transpose(1, 2)
|
| 215 |
+
x = self.input_proj(x) # (B, T, D)
|
| 216 |
+
x = self.look_ahead_conv(x)
|
| 217 |
+
input_pos = torch.arange(x.shape[1], device=x.device)
|
| 218 |
+
mask = self.make_mask(x.shape[1], x.device)
|
| 219 |
+
x = super().forward(x, input_pos, mask)
|
| 220 |
+
x = self.output_proj(x)
|
| 221 |
+
if self.channels_first:
|
| 222 |
+
x = x.transpose(1, 2)
|
| 223 |
+
return x
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def precompute_freqs_cis(seq_len: int, n_elem: int, base: int = 10000, dtype: torch.dtype = torch.bfloat16) -> Tensor:
|
| 227 |
+
freqs = 1.0 / (base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem))
|
| 228 |
+
t = torch.arange(seq_len, device=freqs.device)
|
| 229 |
+
freqs = torch.outer(t, freqs)
|
| 230 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
|
| 231 |
+
cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
|
| 232 |
+
return cache.to(dtype=dtype)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def apply_rotary_emb(x: Tensor, freqs_cis: Tensor) -> Tensor:
|
| 236 |
+
xshaped = x.float().reshape(*x.shape[:-1], -1, 2)
|
| 237 |
+
freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2)
|
| 238 |
+
x_out2 = torch.stack(
|
| 239 |
+
[
|
| 240 |
+
xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1],
|
| 241 |
+
xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1],
|
| 242 |
+
],
|
| 243 |
+
-1,
|
| 244 |
+
)
|
| 245 |
+
x_out2 = x_out2.flatten(3)
|
| 246 |
+
return x_out2.type_as(x)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]):
|
| 250 |
+
"""Remove padding from x, handling properly zero padding. Only for 1d!"""
|
| 251 |
+
padding_left, padding_right = paddings
|
| 252 |
+
assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
|
| 253 |
+
assert (padding_left + padding_right) <= x.shape[-1]
|
| 254 |
+
end = x.shape[-1] - padding_right
|
| 255 |
+
return x[..., padding_left:end]
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def get_extra_padding_for_conv1d(x: torch.Tensor, kernel_size: int, stride: int, padding_total: int = 0) -> int:
|
| 259 |
+
length = x.shape[-1]
|
| 260 |
+
n_frames = (length - kernel_size + padding_total) / stride + 1
|
| 261 |
+
ideal_length = (math.ceil(n_frames) - 1) * stride + (kernel_size - padding_total)
|
| 262 |
+
return ideal_length - length
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def pad1d(x: torch.Tensor, paddings: tp.Tuple[int, int], mode: str = "zeros", value: float = 0.0):
|
| 266 |
+
length = x.shape[-1]
|
| 267 |
+
padding_left, padding_right = paddings
|
| 268 |
+
assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right)
|
| 269 |
+
if mode == "reflect":
|
| 270 |
+
max_pad = max(padding_left, padding_right)
|
| 271 |
+
extra_pad = 0
|
| 272 |
+
if length <= max_pad:
|
| 273 |
+
extra_pad = max_pad - length + 1
|
| 274 |
+
x = F.pad(x, (0, extra_pad))
|
| 275 |
+
padded = F.pad(x, paddings, mode, value)
|
| 276 |
+
end = padded.shape[-1] - extra_pad
|
| 277 |
+
return padded[..., :end]
|
| 278 |
+
return F.pad(x, paddings, mode, value)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class CausalConvNet(nn.Module):
|
| 282 |
+
def __init__(self, in_channels, out_channels, kernel_size, dilation=1, stride=1, groups=1, padding=None):
|
| 283 |
+
super().__init__()
|
| 284 |
+
self.conv = Conv1d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, groups=groups)
|
| 285 |
+
self.stride = stride
|
| 286 |
+
self.kernel_size = (kernel_size - 1) * dilation + 1
|
| 287 |
+
self.dilation = dilation
|
| 288 |
+
self.padding = self.kernel_size - self.stride
|
| 289 |
+
|
| 290 |
+
def forward(self, x):
|
| 291 |
+
pad = self.padding
|
| 292 |
+
extra_padding = get_extra_padding_for_conv1d(x, self.kernel_size, self.stride, pad)
|
| 293 |
+
x = pad1d(x, (pad, extra_padding), mode="constant", value=0)
|
| 294 |
+
return self.conv(x).contiguous()
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class CausalTransConvNet(nn.Module):
|
| 298 |
+
def __init__(self, in_channels, out_channels, kernel_size, dilation=1, stride=1, padding=None):
|
| 299 |
+
super().__init__()
|
| 300 |
+
self.conv = ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation)
|
| 301 |
+
self.stride = stride
|
| 302 |
+
self.kernel_size = kernel_size
|
| 303 |
+
|
| 304 |
+
def forward(self, x):
|
| 305 |
+
x = self.conv(x)
|
| 306 |
+
pad = self.kernel_size - self.stride
|
| 307 |
+
padding_right = math.ceil(pad)
|
| 308 |
+
padding_left = pad - padding_right
|
| 309 |
+
x = unpad1d(x, (padding_left, padding_right))
|
| 310 |
+
return x.contiguous()
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# The checkpoint's weight norms are folded into plain weights.
|
| 314 |
+
CausalWNConv1d = CausalConvNet
|
| 315 |
+
CausalWNConvTranspose1d = CausalTransConvNet
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class ResidualUnit(nn.Module):
|
| 319 |
+
def __init__(self, dim: int = 16, dilation: int = 1, causal: bool = True):
|
| 320 |
+
super().__init__()
|
| 321 |
+
assert causal, "only the causal codec is supported"
|
| 322 |
+
pad = ((7 - 1) * dilation) // 2
|
| 323 |
+
self.block = nn.Sequential(
|
| 324 |
+
Snake1d(dim),
|
| 325 |
+
CausalWNConv1d(dim, dim, kernel_size=7, dilation=dilation, padding=pad),
|
| 326 |
+
Snake1d(dim),
|
| 327 |
+
CausalWNConv1d(dim, dim, kernel_size=1),
|
| 328 |
+
)
|
| 329 |
+
self.causal = causal
|
| 330 |
+
|
| 331 |
+
def forward(self, x):
|
| 332 |
+
y = self.block(x)
|
| 333 |
+
pad = x.shape[-1] - y.shape[-1]
|
| 334 |
+
if pad > 0:
|
| 335 |
+
x = x[..., :-pad]
|
| 336 |
+
return x + y
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class EncoderBlock(nn.Module):
|
| 340 |
+
def __init__(self, dim: int = 16, stride: int = 1, causal: bool = True, n_t_layer: int = 0,
|
| 341 |
+
transformer_general_config=None):
|
| 342 |
+
super().__init__()
|
| 343 |
+
transformer_module = (
|
| 344 |
+
nn.Identity()
|
| 345 |
+
if n_t_layer == 0
|
| 346 |
+
else WindowLimitedTransformer(
|
| 347 |
+
causal=causal,
|
| 348 |
+
input_dim=dim,
|
| 349 |
+
window_size=getattr(transformer_general_config, "window_size", 512),
|
| 350 |
+
config=transformer_general_config(n_layer=n_t_layer, n_head=dim // 64, dim=dim,
|
| 351 |
+
intermediate_size=dim * 3),
|
| 352 |
+
)
|
| 353 |
+
)
|
| 354 |
+
self.block = nn.Sequential(
|
| 355 |
+
ResidualUnit(dim // 2, dilation=1, causal=causal),
|
| 356 |
+
ResidualUnit(dim // 2, dilation=3, causal=causal),
|
| 357 |
+
ResidualUnit(dim // 2, dilation=9, causal=causal),
|
| 358 |
+
Snake1d(dim // 2),
|
| 359 |
+
CausalWNConv1d(dim // 2, dim, kernel_size=2 * stride, stride=stride, padding=math.ceil(stride / 2)),
|
| 360 |
+
transformer_module,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
def forward(self, x):
|
| 364 |
+
return self.block(x)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class Encoder(nn.Module):
|
| 368 |
+
def __init__(self, d_model: int = 64, strides: list = [2, 4, 8, 8], d_latent: int = 64,
|
| 369 |
+
n_transformer_layers: list = [0, 0, 4, 4], transformer_general_config: ModelArgs = None,
|
| 370 |
+
causal: bool = True):
|
| 371 |
+
super().__init__()
|
| 372 |
+
self.block = [CausalWNConv1d(1, d_model, kernel_size=7, padding=3)]
|
| 373 |
+
for stride, n_t_layer in zip(strides, n_transformer_layers):
|
| 374 |
+
d_model *= 2
|
| 375 |
+
self.block += [EncoderBlock(d_model, stride=stride, causal=causal, n_t_layer=n_t_layer,
|
| 376 |
+
transformer_general_config=transformer_general_config)]
|
| 377 |
+
self.block += [Snake1d(d_model), CausalWNConv1d(d_model, d_latent, kernel_size=3, padding=1)]
|
| 378 |
+
self.block = nn.Sequential(*self.block)
|
| 379 |
+
self.enc_dim = d_model
|
| 380 |
+
|
| 381 |
+
def forward(self, x):
|
| 382 |
+
return self.block(x)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
class DecoderBlock(nn.Module):
|
| 386 |
+
def __init__(self, input_dim: int = 16, output_dim: int = 8, stride: int = 1, causal: bool = True,
|
| 387 |
+
n_t_layer: int = 0, transformer_general_config=None):
|
| 388 |
+
super().__init__()
|
| 389 |
+
# Upstream builds a transformer here but leaves it out of the block (unused).
|
| 390 |
+
self.block = nn.Sequential(
|
| 391 |
+
Snake1d(input_dim),
|
| 392 |
+
CausalWNConvTranspose1d(input_dim, output_dim, kernel_size=2 * stride, stride=stride,
|
| 393 |
+
padding=math.ceil(stride / 2)),
|
| 394 |
+
ResidualUnit(output_dim, dilation=1, causal=causal),
|
| 395 |
+
ResidualUnit(output_dim, dilation=3, causal=causal),
|
| 396 |
+
ResidualUnit(output_dim, dilation=9, causal=causal),
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
def forward(self, x):
|
| 400 |
+
return self.block(x)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class Decoder(nn.Module):
|
| 404 |
+
def __init__(self, input_channel, channels, rates, d_out: int = 1, causal: bool = True,
|
| 405 |
+
n_transformer_layers: list = [0, 0, 0, 0], transformer_general_config=None):
|
| 406 |
+
super().__init__()
|
| 407 |
+
layers = [CausalWNConv1d(input_channel, channels, kernel_size=7, padding=3)]
|
| 408 |
+
for i, (stride, n_t_layer) in enumerate(zip(rates, n_transformer_layers)):
|
| 409 |
+
input_dim = channels // 2**i
|
| 410 |
+
output_dim = channels // 2 ** (i + 1)
|
| 411 |
+
layers += [DecoderBlock(input_dim, output_dim, stride, causal=causal, n_t_layer=n_t_layer,
|
| 412 |
+
transformer_general_config=transformer_general_config)]
|
| 413 |
+
layers += [Snake1d(output_dim), CausalWNConv1d(output_dim, d_out, kernel_size=7, padding=3), nn.Tanh()]
|
| 414 |
+
self.model = nn.Sequential(*layers)
|
| 415 |
+
|
| 416 |
+
def forward(self, x):
|
| 417 |
+
return self.model(x)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class DAC(nn.Module):
|
| 421 |
+
def __init__(
|
| 422 |
+
self,
|
| 423 |
+
encoder_dim: int = 64,
|
| 424 |
+
encoder_rates: List[int] = [2, 4, 8, 8],
|
| 425 |
+
latent_dim: int = None,
|
| 426 |
+
decoder_dim: int = 1536,
|
| 427 |
+
decoder_rates: List[int] = [8, 8, 4, 2],
|
| 428 |
+
quantizer: torch.nn.Module = None,
|
| 429 |
+
sample_rate: int = 44100,
|
| 430 |
+
causal: bool = True,
|
| 431 |
+
encoder_transformer_layers: List[int] = [0, 0, 0, 0],
|
| 432 |
+
decoder_transformer_layers: List[int] = [0, 0, 0, 0],
|
| 433 |
+
transformer_general_config=None,
|
| 434 |
+
):
|
| 435 |
+
super().__init__()
|
| 436 |
+
self.encoder_dim = encoder_dim
|
| 437 |
+
self.encoder_rates = encoder_rates
|
| 438 |
+
self.decoder_dim = decoder_dim
|
| 439 |
+
self.decoder_rates = decoder_rates
|
| 440 |
+
self.sample_rate = sample_rate
|
| 441 |
+
if latent_dim is None:
|
| 442 |
+
latent_dim = encoder_dim * (2 ** len(encoder_rates))
|
| 443 |
+
self.latent_dim = latent_dim
|
| 444 |
+
self.hop_length = int(np.prod(encoder_rates))
|
| 445 |
+
self.encoder = Encoder(encoder_dim, encoder_rates, latent_dim, causal=causal,
|
| 446 |
+
n_transformer_layers=encoder_transformer_layers,
|
| 447 |
+
transformer_general_config=transformer_general_config)
|
| 448 |
+
self.quantizer = quantizer
|
| 449 |
+
self.decoder = Decoder(latent_dim, decoder_dim, decoder_rates, causal=causal,
|
| 450 |
+
n_transformer_layers=decoder_transformer_layers,
|
| 451 |
+
transformer_general_config=transformer_general_config)
|
| 452 |
+
self.frame_length = self.hop_length * 4
|
| 453 |
+
|
| 454 |
+
def encode(self, audio_data: torch.Tensor, audio_lengths: torch.Tensor = None, **kwargs):
|
| 455 |
+
"""audio [B, 1, T] or [B, T] at sample_rate -> (codes [B, N, frames], frame counts [B])."""
|
| 456 |
+
if audio_data.ndim == 2:
|
| 457 |
+
audio_data = audio_data.unsqueeze(1)
|
| 458 |
+
length = audio_data.shape[-1]
|
| 459 |
+
right_pad = math.ceil(length / self.frame_length) * self.frame_length - length
|
| 460 |
+
audio_data = F.pad(audio_data, (0, right_pad))
|
| 461 |
+
if audio_lengths is None:
|
| 462 |
+
audio_lengths = torch.LongTensor([length + right_pad]).to(audio_data.device)
|
| 463 |
+
z = self.encoder(audio_data)
|
| 464 |
+
indices = self.quantizer.encode_codes(z)
|
| 465 |
+
indices_lens = torch.ceil(audio_lengths / self.frame_length).long()
|
| 466 |
+
return indices, indices_lens
|
| 467 |
+
|
| 468 |
+
def from_indices(self, indices: torch.Tensor):
|
| 469 |
+
z = self.quantizer.decode(indices)
|
| 470 |
+
return self.decoder(z)
|
| 471 |
+
|
| 472 |
+
def decode(self, z: torch.Tensor):
|
| 473 |
+
return self.decoder(z)
|
torch/fish_speech/models/dac/rvq.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified for the drama3-expressive-medium PyTorch port (GGUF runtime), inference only:
|
| 2 |
+
# * ResidualVectorQuantize / VectorQuantize re-implemented here (inference parts of
|
| 3 |
+
# descript-audio-codec's dac.nn.quantize, MIT license) instead of importing `dac`;
|
| 4 |
+
# weight-normalized 1x1 convolutions are plain (folded) convolutions;
|
| 5 |
+
# * DownsampleResidualVectorQuantize.encode_codes() returns the codes without running the
|
| 6 |
+
# decoder-side post_module / upsample; training losses and dropout removed.
|
| 7 |
+
import math
|
| 8 |
+
import typing as tp
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
from .modded_dac import CausalConvNet, CausalTransConvNet, Conv1d, Linear
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class VectorQuantize(nn.Module):
|
| 18 |
+
"""Factorized (low-dimensional), l2-normalized codebook lookup."""
|
| 19 |
+
|
| 20 |
+
def __init__(self, input_dim: int, codebook_size: int, codebook_dim: int):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.codebook_size = codebook_size
|
| 23 |
+
self.codebook_dim = codebook_dim
|
| 24 |
+
self.in_proj = Conv1d(input_dim, codebook_dim, kernel_size=1)
|
| 25 |
+
self.out_proj = Conv1d(codebook_dim, input_dim, kernel_size=1)
|
| 26 |
+
self.codebook = nn.Embedding(codebook_size, codebook_dim)
|
| 27 |
+
|
| 28 |
+
def forward(self, z):
|
| 29 |
+
"""z [B, D, T] -> (z_q [B, D, T], indices [B, T])."""
|
| 30 |
+
z_e = self.in_proj(z)
|
| 31 |
+
z_q, indices = self.decode_latents(z_e)
|
| 32 |
+
return self.out_proj(z_q), indices
|
| 33 |
+
|
| 34 |
+
def embed_code(self, embed_id):
|
| 35 |
+
return F.embedding(embed_id, self.codebook.weight)
|
| 36 |
+
|
| 37 |
+
def decode_code(self, embed_id):
|
| 38 |
+
return self.embed_code(embed_id).transpose(1, 2)
|
| 39 |
+
|
| 40 |
+
def decode_latents(self, latents):
|
| 41 |
+
b, d, t = latents.shape
|
| 42 |
+
encodings = latents.transpose(1, 2).reshape(b * t, d)
|
| 43 |
+
codebook = self.codebook.weight.to(encodings.dtype)
|
| 44 |
+
encodings = F.normalize(encodings)
|
| 45 |
+
codebook = F.normalize(codebook)
|
| 46 |
+
dist = (
|
| 47 |
+
encodings.pow(2).sum(1, keepdim=True)
|
| 48 |
+
- 2 * encodings @ codebook.t()
|
| 49 |
+
+ codebook.pow(2).sum(1, keepdim=True).t()
|
| 50 |
+
)
|
| 51 |
+
indices = (-dist).max(1)[1].reshape(b, t)
|
| 52 |
+
return self.decode_code(indices), indices
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ResidualVectorQuantize(nn.Module):
|
| 56 |
+
def __init__(self, input_dim: int = 512, n_codebooks: int = 9, codebook_size: int = 1024,
|
| 57 |
+
codebook_dim: tp.Union[int, list] = 8, quantizer_dropout: float = 0.0):
|
| 58 |
+
super().__init__()
|
| 59 |
+
if isinstance(codebook_dim, int):
|
| 60 |
+
codebook_dim = [codebook_dim for _ in range(n_codebooks)]
|
| 61 |
+
self.n_codebooks = n_codebooks
|
| 62 |
+
self.codebook_dim = codebook_dim
|
| 63 |
+
self.codebook_size = codebook_size
|
| 64 |
+
self.quantizers = nn.ModuleList(
|
| 65 |
+
[VectorQuantize(input_dim, codebook_size, codebook_dim[i]) for i in range(n_codebooks)]
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
def forward(self, z):
|
| 69 |
+
"""z [B, D, T] -> (z_q, codes [B, N, T])."""
|
| 70 |
+
z_q = 0
|
| 71 |
+
residual = z
|
| 72 |
+
codes = []
|
| 73 |
+
for quantizer in self.quantizers:
|
| 74 |
+
z_q_i, indices_i = quantizer(residual)
|
| 75 |
+
z_q = z_q + z_q_i
|
| 76 |
+
residual = residual - z_q_i
|
| 77 |
+
codes.append(indices_i)
|
| 78 |
+
return z_q, torch.stack(codes, dim=1)
|
| 79 |
+
|
| 80 |
+
def from_codes(self, codes: torch.Tensor):
|
| 81 |
+
z_q = 0.0
|
| 82 |
+
for i in range(codes.shape[1]):
|
| 83 |
+
z_q = z_q + self.quantizers[i].out_proj(self.quantizers[i].decode_code(codes[:, i, :]))
|
| 84 |
+
return z_q
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ConvNeXt Block copied from https://github.com/fishaudio/fish-diffusion/blob/main/fish_diffusion/modules/convnext.py
|
| 88 |
+
class ConvNeXtBlock(nn.Module):
|
| 89 |
+
def __init__(self, dim: int, layer_scale_init_value: float = 1e-6, mlp_ratio: float = 4.0,
|
| 90 |
+
kernel_size: int = 7, dilation: int = 1):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.dwconv = CausalConvNet(dim, dim, kernel_size=kernel_size, groups=dim, dilation=dilation)
|
| 93 |
+
self.norm = nn.LayerNorm(dim, eps=1e-6)
|
| 94 |
+
self.pwconv1 = Linear(dim, int(mlp_ratio * dim))
|
| 95 |
+
self.act = nn.GELU()
|
| 96 |
+
self.pwconv2 = Linear(int(mlp_ratio * dim), dim)
|
| 97 |
+
self.gamma = (
|
| 98 |
+
nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
|
| 99 |
+
if layer_scale_init_value > 0
|
| 100 |
+
else None
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def forward(self, x, apply_residual: bool = True):
|
| 104 |
+
input = x
|
| 105 |
+
x = self.dwconv(x)
|
| 106 |
+
x = x.permute(0, 2, 1) # (N, C, L) -> (N, L, C)
|
| 107 |
+
x = F.layer_norm(x, self.norm.normalized_shape, self.norm.weight.to(x.dtype),
|
| 108 |
+
self.norm.bias.to(x.dtype), self.norm.eps)
|
| 109 |
+
x = self.pwconv1(x)
|
| 110 |
+
x = self.act(x)
|
| 111 |
+
x = self.pwconv2(x)
|
| 112 |
+
if self.gamma is not None:
|
| 113 |
+
x = self.gamma.to(x.dtype) * x
|
| 114 |
+
x = x.permute(0, 2, 1) # (N, L, C) -> (N, C, L)
|
| 115 |
+
if apply_residual:
|
| 116 |
+
x = input + x
|
| 117 |
+
return x
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class DownsampleResidualVectorQuantize(nn.Module):
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
input_dim: int = 1024,
|
| 124 |
+
n_codebooks: int = 9,
|
| 125 |
+
codebook_dim: int = 8,
|
| 126 |
+
quantizer_dropout: float = 0.5,
|
| 127 |
+
codebook_size: int = 1024,
|
| 128 |
+
semantic_codebook_size: int = 4096,
|
| 129 |
+
downsample_factor: tuple[int] = (2, 2),
|
| 130 |
+
downsample_dims: tuple[int] | None = None,
|
| 131 |
+
pre_module: nn.Module | None = None,
|
| 132 |
+
post_module: nn.Module | None = None,
|
| 133 |
+
):
|
| 134 |
+
super().__init__()
|
| 135 |
+
if downsample_dims is None:
|
| 136 |
+
downsample_dims = [input_dim for _ in range(len(downsample_factor))]
|
| 137 |
+
all_dims = (input_dim,) + tuple(downsample_dims)
|
| 138 |
+
self.semantic_quantizer = ResidualVectorQuantize(
|
| 139 |
+
input_dim=input_dim, n_codebooks=1, codebook_size=semantic_codebook_size, codebook_dim=codebook_dim
|
| 140 |
+
)
|
| 141 |
+
self.quantizer = ResidualVectorQuantize(
|
| 142 |
+
input_dim=input_dim, n_codebooks=n_codebooks, codebook_size=codebook_size, codebook_dim=codebook_dim
|
| 143 |
+
)
|
| 144 |
+
self.downsample_factor = downsample_factor
|
| 145 |
+
self.downsample_dims = downsample_dims
|
| 146 |
+
self.downsample = nn.Sequential(
|
| 147 |
+
*[
|
| 148 |
+
nn.Sequential(
|
| 149 |
+
CausalConvNet(all_dims[idx], all_dims[idx + 1], kernel_size=factor, stride=factor),
|
| 150 |
+
ConvNeXtBlock(dim=all_dims[idx + 1]),
|
| 151 |
+
)
|
| 152 |
+
for idx, factor in enumerate(downsample_factor)
|
| 153 |
+
]
|
| 154 |
+
)
|
| 155 |
+
self.upsample = nn.Sequential(
|
| 156 |
+
*[
|
| 157 |
+
nn.Sequential(
|
| 158 |
+
CausalTransConvNet(all_dims[idx + 1], all_dims[idx], kernel_size=factor, stride=factor),
|
| 159 |
+
ConvNeXtBlock(dim=all_dims[idx]),
|
| 160 |
+
)
|
| 161 |
+
for idx, factor in reversed(list(enumerate(downsample_factor)))
|
| 162 |
+
]
|
| 163 |
+
)
|
| 164 |
+
self.pre_module = pre_module if pre_module is not None else nn.Identity()
|
| 165 |
+
self.post_module = post_module if post_module is not None else nn.Identity()
|
| 166 |
+
|
| 167 |
+
def encode_codes(self, z):
|
| 168 |
+
"""Encoder latents [B, D, T] -> codes [B, 1 + n_codebooks, T / prod(downsample_factor)]."""
|
| 169 |
+
z = self.downsample(z)
|
| 170 |
+
z = self.pre_module(z)
|
| 171 |
+
semantic_z, semantic_codes = self.semantic_quantizer(z)
|
| 172 |
+
_, codes = self.quantizer(z - semantic_z)
|
| 173 |
+
return torch.cat([semantic_codes, codes], dim=1)
|
| 174 |
+
|
| 175 |
+
def decode(self, indices: torch.Tensor):
|
| 176 |
+
indices = indices.clone()
|
| 177 |
+
indices[:, 0] = torch.clamp(indices[:, 0], max=self.semantic_quantizer.codebook_size - 1)
|
| 178 |
+
indices[:, 1:] = torch.clamp(indices[:, 1:], max=self.quantizer.codebook_size - 1)
|
| 179 |
+
z_q_semantic = self.semantic_quantizer.from_codes(indices[:, :1])
|
| 180 |
+
z_q_residual = self.quantizer.from_codes(indices[:, 1:])
|
| 181 |
+
z_q = z_q_semantic + z_q_residual
|
| 182 |
+
z_q = self.post_module(z_q)
|
| 183 |
+
z_q = self.upsample(z_q)
|
| 184 |
+
return z_q
|
torch/fish_speech/models/text2semantic/__init__.py
ADDED
|
File without changes
|
torch/fish_speech/models/text2semantic/errors.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class InvalidInputError(ValueError):
|
| 2 |
+
"""The request cannot be served as given: bad text, references or length.
|
| 3 |
+
|
| 4 |
+
The API server answers these with 400; every other failure is a 500.
|
| 5 |
+
"""
|
torch/fish_speech/models/text2semantic/fish_omni/__init__.py
ADDED
|
File without changes
|
torch/fish_speech/models/text2semantic/fish_omni/backbone.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified for the drama3-expressive-medium PyTorch port (GGUF runtime): no FP8 experts; routed
|
| 2 |
+
# experts are packed GGUF banks (moe.PackedExperts); the output head may be the speech-only
|
| 3 |
+
# [EOS, semantic] head; the token embedding may be any module mapping ids to rows (the GGUF
|
| 4 |
+
# loader keeps the 252k-row table packed on the host); checkpoint loading moved to drama3_gguf.py.
|
| 5 |
+
import logging
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from collections.abc import Sequence
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from torch import Tensor
|
| 12 |
+
from torch.types import Device
|
| 13 |
+
|
| 14 |
+
from .config import FishOmniTextConfig
|
| 15 |
+
from .layers import (
|
| 16 |
+
FullAttention,
|
| 17 |
+
GatedDeltaNet,
|
| 18 |
+
LayerContext,
|
| 19 |
+
ZeroCenteredRMSNorm,
|
| 20 |
+
)
|
| 21 |
+
from .moe import SparseMoeBlock
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DecoderLayer(nn.Module):
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
config: FishOmniTextConfig,
|
| 30 |
+
layer_index: int,
|
| 31 |
+
*,
|
| 32 |
+
dtype: torch.dtype | None = None,
|
| 33 |
+
device: Device = None,
|
| 34 |
+
) -> None:
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.layer_type = config.layer_types[layer_index]
|
| 37 |
+
if self.layer_type == "full_attention":
|
| 38 |
+
self.self_attn = FullAttention(config, dtype=dtype, device=device)
|
| 39 |
+
else:
|
| 40 |
+
self.linear_attn = GatedDeltaNet(config, dtype=dtype, device=device)
|
| 41 |
+
self.mlp = SparseMoeBlock(config, dtype=dtype, device=device)
|
| 42 |
+
norm = dict(dtype=dtype, device=device)
|
| 43 |
+
self.input_layernorm = ZeroCenteredRMSNorm(
|
| 44 |
+
config.hidden_size, config.rms_norm_eps, **norm
|
| 45 |
+
)
|
| 46 |
+
self.post_attention_layernorm = ZeroCenteredRMSNorm(
|
| 47 |
+
config.hidden_size, config.rms_norm_eps, **norm
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def forward(self, x: Tensor, context: LayerContext) -> Tensor:
|
| 51 |
+
"""x is the residual stream, possibly wider than the compute dtype."""
|
| 52 |
+
compute_dtype = self.input_layernorm.weight.dtype
|
| 53 |
+
mixer = (
|
| 54 |
+
self.self_attn if self.layer_type == "full_attention" else self.linear_attn
|
| 55 |
+
)
|
| 56 |
+
x = x + mixer(self.input_layernorm(x).to(compute_dtype), context)
|
| 57 |
+
return x + self.mlp(self.post_attention_layernorm(x).to(compute_dtype))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class FishOmniTextModel(nn.Module):
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
config: FishOmniTextConfig,
|
| 64 |
+
*,
|
| 65 |
+
dtype: torch.dtype | None = None,
|
| 66 |
+
device: Device = None,
|
| 67 |
+
) -> None:
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.embed_tokens = nn.Embedding(
|
| 70 |
+
config.vocab_size, config.hidden_size, dtype=dtype, device=device
|
| 71 |
+
)
|
| 72 |
+
self.layers = nn.ModuleList(
|
| 73 |
+
DecoderLayer(config, index, dtype=dtype, device=device)
|
| 74 |
+
for index in range(config.num_hidden_layers)
|
| 75 |
+
)
|
| 76 |
+
self.norm = ZeroCenteredRMSNorm(
|
| 77 |
+
config.hidden_size, config.rms_norm_eps, dtype=dtype, device=device
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class FishOmniBackbone(nn.Module):
|
| 82 |
+
"""Qwen3.5-MoE hybrid text backbone + lm_head; layers may span several devices."""
|
| 83 |
+
|
| 84 |
+
def __init__(
|
| 85 |
+
self,
|
| 86 |
+
config: FishOmniTextConfig,
|
| 87 |
+
*,
|
| 88 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 89 |
+
device: Device = None,
|
| 90 |
+
head_rows: int = 0,
|
| 91 |
+
) -> None:
|
| 92 |
+
super().__init__()
|
| 93 |
+
self.config = config
|
| 94 |
+
self.dtype = dtype
|
| 95 |
+
# The residual stream of this model exceeds the float16 range.
|
| 96 |
+
self.residual_dtype = torch.float32 if dtype == torch.float16 else dtype
|
| 97 |
+
self.model = FishOmniTextModel(config, dtype=dtype, device=device)
|
| 98 |
+
# head_rows > 0: speech-only head whose rows are [EOS, semantic 0..N-1].
|
| 99 |
+
self.head_rows = head_rows
|
| 100 |
+
self.lm_head = nn.Linear(
|
| 101 |
+
config.hidden_size,
|
| 102 |
+
head_rows or config.vocab_size,
|
| 103 |
+
bias=False,
|
| 104 |
+
dtype=dtype,
|
| 105 |
+
device=device,
|
| 106 |
+
)
|
| 107 |
+
self.max_batch_size = 0
|
| 108 |
+
self.max_seq_len = 0
|
| 109 |
+
self.inverse_frequencies: dict[torch.device, Tensor] = {}
|
| 110 |
+
|
| 111 |
+
def materialize(
|
| 112 |
+
self, devices: Sequence[Device], device_weights: Sequence[float] | None = None
|
| 113 |
+
) -> None:
|
| 114 |
+
"""Allocate a meta-device backbone over devices in contiguous layer ranges.
|
| 115 |
+
|
| 116 |
+
Ranges are balanced by bytes, counting the embedding on the first device and
|
| 117 |
+
the final norm + lm_head on the last. device_weights (drama3-small patch)
|
| 118 |
+
gives each device's share of the bytes; the default is an even split.
|
| 119 |
+
"""
|
| 120 |
+
devices = [torch.device(d) for d in devices]
|
| 121 |
+
layer_bytes = [module_bytes(layer) for layer in self.model.layers]
|
| 122 |
+
head = module_bytes(self.model.embed_tokens)
|
| 123 |
+
tail = module_bytes(self.lm_head) + module_bytes(self.model.norm)
|
| 124 |
+
total = head + sum(layer_bytes) + tail
|
| 125 |
+
weights = list(device_weights or [1.0] * len(devices))
|
| 126 |
+
if len(weights) != len(devices):
|
| 127 |
+
raise ValueError("device_weights must have one entry per device")
|
| 128 |
+
bounds, acc = [], 0.0
|
| 129 |
+
for w in weights:
|
| 130 |
+
acc += w / sum(weights) * total
|
| 131 |
+
bounds.append(acc)
|
| 132 |
+
self.model.embed_tokens.to_empty(device=devices[0])
|
| 133 |
+
self.model.norm.to_empty(device=devices[-1])
|
| 134 |
+
self.lm_head.to_empty(device=devices[-1])
|
| 135 |
+
placement = defaultdict(list)
|
| 136 |
+
cumulative = head
|
| 137 |
+
for index, (layer, size) in enumerate(zip(self.model.layers, layer_bytes)):
|
| 138 |
+
middle = cumulative + size / 2
|
| 139 |
+
slot = next((i for i, b in enumerate(bounds) if middle < b), len(devices) - 1)
|
| 140 |
+
device = devices[slot]
|
| 141 |
+
layer.to_empty(device=device)
|
| 142 |
+
placement[str(device)].append(index)
|
| 143 |
+
cumulative += size
|
| 144 |
+
self.inverse_frequencies.clear()
|
| 145 |
+
logger.info(
|
| 146 |
+
"FishOmni backbone placement: "
|
| 147 |
+
+ ", ".join(f"{d}: layers {v[0]}-{v[-1]}" for d, v in placement.items())
|
| 148 |
+
+ f"; embed on {devices[0]}, lm_head on {devices[-1]}"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
def setup_caches(self, max_batch_size: int, max_seq_len: int) -> None:
|
| 152 |
+
assert max_seq_len <= self.config.max_position_embeddings
|
| 153 |
+
for layer in self.model.layers:
|
| 154 |
+
device = layer.input_layernorm.weight.device
|
| 155 |
+
if layer.layer_type == "full_attention":
|
| 156 |
+
layer.self_attn.allocate_cache(
|
| 157 |
+
max_batch_size, max_seq_len, self.dtype, device
|
| 158 |
+
)
|
| 159 |
+
else:
|
| 160 |
+
layer.linear_attn.allocate_cache(max_batch_size, self.dtype, device)
|
| 161 |
+
self.max_batch_size = max_batch_size
|
| 162 |
+
self.max_seq_len = max_seq_len
|
| 163 |
+
|
| 164 |
+
def embed(self, input_ids: Tensor) -> Tensor:
|
| 165 |
+
embeddings = self.model.embed_tokens
|
| 166 |
+
if isinstance(embeddings, nn.Embedding):
|
| 167 |
+
return embeddings(input_ids.to(embeddings.weight.device))
|
| 168 |
+
return embeddings(input_ids)
|
| 169 |
+
|
| 170 |
+
def forward(
|
| 171 |
+
self,
|
| 172 |
+
input_ids: Tensor | None = None,
|
| 173 |
+
*,
|
| 174 |
+
inputs_embeds: Tensor | None = None,
|
| 175 |
+
input_pos: Tensor | None = None,
|
| 176 |
+
static_kv_len: int | None = None,
|
| 177 |
+
) -> Tensor:
|
| 178 |
+
"""Final-norm hidden states [B, T, H] of B rows at the T positions input_pos.
|
| 179 |
+
|
| 180 |
+
With caches, rows at positions > 0 continue the cached sequence; without,
|
| 181 |
+
only a whole sequence from position 0 can run. static_kv_len (CUDA-graph
|
| 182 |
+
decode) attends that many cache rows without a host sync.
|
| 183 |
+
"""
|
| 184 |
+
assert (input_ids is None) != (inputs_embeds is None)
|
| 185 |
+
hidden = self.embed(input_ids) if inputs_embeds is None else inputs_embeds
|
| 186 |
+
hidden = hidden.to(self.residual_dtype)
|
| 187 |
+
batch, length = hidden.shape[:2]
|
| 188 |
+
if static_kv_len is not None:
|
| 189 |
+
assert input_pos is not None and length == 1
|
| 190 |
+
assert 0 < static_kv_len <= self.max_seq_len
|
| 191 |
+
return self.run_layers(
|
| 192 |
+
hidden,
|
| 193 |
+
input_pos,
|
| 194 |
+
kv_len=static_kv_len,
|
| 195 |
+
continue_state=True,
|
| 196 |
+
use_cache=True,
|
| 197 |
+
)
|
| 198 |
+
if input_pos is None:
|
| 199 |
+
input_pos = torch.arange(length, device=hidden.device)
|
| 200 |
+
assert input_pos.shape == (length,)
|
| 201 |
+
start, end = int(input_pos[0]), int(input_pos[-1]) + 1
|
| 202 |
+
assert start >= 0 and end - start == length, "input_pos must be contiguous"
|
| 203 |
+
use_cache = self.max_seq_len > 0
|
| 204 |
+
if use_cache:
|
| 205 |
+
assert (
|
| 206 |
+
batch <= self.max_batch_size and end <= self.max_seq_len
|
| 207 |
+
), "rows exceed the caches"
|
| 208 |
+
else:
|
| 209 |
+
assert start == 0, "continuing a sequence needs setup_caches first"
|
| 210 |
+
return self.run_layers(
|
| 211 |
+
hidden, input_pos, kv_len=end, continue_state=start > 0, use_cache=use_cache
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def run_layers(
|
| 215 |
+
self,
|
| 216 |
+
hidden: Tensor,
|
| 217 |
+
input_pos: Tensor,
|
| 218 |
+
*,
|
| 219 |
+
kv_len: int,
|
| 220 |
+
continue_state: bool,
|
| 221 |
+
use_cache: bool,
|
| 222 |
+
) -> Tensor:
|
| 223 |
+
rotary_dim = self.config.rotary_dim
|
| 224 |
+
contexts: dict[torch.device, LayerContext] = {}
|
| 225 |
+
for layer in self.model.layers:
|
| 226 |
+
device = layer.input_layernorm.weight.device
|
| 227 |
+
if device not in contexts:
|
| 228 |
+
frequencies = self.inverse_frequencies.get(device)
|
| 229 |
+
if frequencies is None:
|
| 230 |
+
exponents = torch.arange(
|
| 231 |
+
0, rotary_dim, 2, dtype=torch.float32, device=device
|
| 232 |
+
)
|
| 233 |
+
frequencies = 1.0 / (
|
| 234 |
+
self.config.rope_theta ** (exponents / rotary_dim)
|
| 235 |
+
)
|
| 236 |
+
self.inverse_frequencies[device] = frequencies
|
| 237 |
+
positions = input_pos.to(device)
|
| 238 |
+
angles = positions.float()[:, None] * frequencies[None, :]
|
| 239 |
+
angles = torch.cat((angles, angles), dim=-1)
|
| 240 |
+
contexts[device] = LayerContext(
|
| 241 |
+
input_pos=positions,
|
| 242 |
+
cos=angles.cos(),
|
| 243 |
+
sin=angles.sin(),
|
| 244 |
+
kv_len=kv_len,
|
| 245 |
+
continue_state=continue_state,
|
| 246 |
+
use_cache=use_cache,
|
| 247 |
+
)
|
| 248 |
+
hidden = layer(hidden.to(device), contexts[device])
|
| 249 |
+
norm = self.model.norm
|
| 250 |
+
return norm(hidden.to(norm.weight.device)).to(self.dtype)
|
| 251 |
+
|
| 252 |
+
def compute_logits(self, hidden: Tensor) -> Tensor:
|
| 253 |
+
return self.lm_head(hidden.to(self.lm_head.weight.device))
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def module_bytes(module: nn.Module) -> int:
|
| 257 |
+
tensors = [*module.parameters(), *module.buffers()]
|
| 258 |
+
return sum(t.numel() * t.element_size() for t in tensors)
|
torch/fish_speech/models/text2semantic/fish_omni/config.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, fields
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
# drama3-expressive-medium torch port: FP8 experts are not used (routed experts come from GGUF banks).
|
| 5 |
+
FP8_BLOCK_SIZE = 128
|
| 6 |
+
|
| 7 |
+
FISH_OMNI_MODEL_TYPE = "fish_omni"
|
| 8 |
+
TEXT_MODEL_TYPES = ("fish_omni_text", "qwen3_5_moe_text")
|
| 9 |
+
SPEECH_TEMPLATE_VERSION = "reference-bracket-v1"
|
| 10 |
+
FP8_QUANT_METHOD = "bsgemm-moe"
|
| 11 |
+
# Text config flags fixed by the architecture: (key, default when absent, required value).
|
| 12 |
+
FIXED_TEXT_FLAGS = (
|
| 13 |
+
("rotary_interleaved", False, False),
|
| 14 |
+
("use_qk_norm", True, True),
|
| 15 |
+
("attn_output_gate", True, True),
|
| 16 |
+
("layernorm_zero_centered_gamma", True, True),
|
| 17 |
+
("shared_expert_gate", True, True),
|
| 18 |
+
)
|
| 19 |
+
# attention_qk_norm is deliberately not checked; see TowerAttention.
|
| 20 |
+
FIXED_AUDIO_DECODER_FLAGS = {
|
| 21 |
+
"decoder_type": "codebook_mtp_shared",
|
| 22 |
+
"rotary_interleaved": True,
|
| 23 |
+
"attention_output_gate": True,
|
| 24 |
+
"layernorm_zero_centered_gamma": True,
|
| 25 |
+
"use_moe": False,
|
| 26 |
+
"mtp_use_swa": False,
|
| 27 |
+
"attention_qkv_bias": False,
|
| 28 |
+
"attention_o_bias": False,
|
| 29 |
+
"dropout": 0.0,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass(kw_only=True)
|
| 34 |
+
class FishOmniTextConfig:
|
| 35 |
+
vocab_size: int
|
| 36 |
+
hidden_size: int
|
| 37 |
+
num_hidden_layers: int
|
| 38 |
+
layer_types: list[str]
|
| 39 |
+
num_attention_heads: int
|
| 40 |
+
num_key_value_heads: int
|
| 41 |
+
head_dim: int
|
| 42 |
+
rope_theta: float
|
| 43 |
+
partial_rotary_factor: float
|
| 44 |
+
rms_norm_eps: float
|
| 45 |
+
max_position_embeddings: int
|
| 46 |
+
linear_conv_kernel_dim: int
|
| 47 |
+
linear_key_head_dim: int
|
| 48 |
+
linear_value_head_dim: int
|
| 49 |
+
linear_num_key_heads: int
|
| 50 |
+
linear_num_value_heads: int
|
| 51 |
+
num_experts: int
|
| 52 |
+
num_experts_per_tok: int
|
| 53 |
+
moe_intermediate_size: int
|
| 54 |
+
shared_expert_intermediate_size: int
|
| 55 |
+
norm_topk_prob: bool = True
|
| 56 |
+
|
| 57 |
+
def __post_init__(self) -> None:
|
| 58 |
+
if len(self.layer_types) != self.num_hidden_layers or not set(
|
| 59 |
+
self.layer_types
|
| 60 |
+
) <= {"linear_attention", "full_attention"}:
|
| 61 |
+
raise ValueError(
|
| 62 |
+
"layer_types must name linear_attention / full_attention for each of "
|
| 63 |
+
f"the {self.num_hidden_layers} layers; got {self.layer_types!r}"
|
| 64 |
+
)
|
| 65 |
+
if self.num_attention_heads % self.num_key_value_heads:
|
| 66 |
+
raise ValueError(
|
| 67 |
+
"num_attention_heads must be a multiple of num_key_value_heads"
|
| 68 |
+
)
|
| 69 |
+
if self.linear_num_value_heads % self.linear_num_key_heads:
|
| 70 |
+
raise ValueError(
|
| 71 |
+
"linear_num_value_heads must be a multiple of linear_num_key_heads"
|
| 72 |
+
)
|
| 73 |
+
if self.num_experts_per_tok > self.num_experts:
|
| 74 |
+
raise ValueError("num_experts_per_tok exceeds num_experts")
|
| 75 |
+
if self.rotary_dim <= 0 or self.rotary_dim % 2:
|
| 76 |
+
raise ValueError(
|
| 77 |
+
f"rotary width must be positive and even; got {self.rotary_dim}"
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def rotary_dim(self) -> int:
|
| 82 |
+
return int(self.head_dim * self.partial_rotary_factor)
|
| 83 |
+
|
| 84 |
+
@classmethod
|
| 85 |
+
def from_dict(cls, data: dict[str, Any]) -> "FishOmniTextConfig":
|
| 86 |
+
"""Parse a fish_omni_text or qwen3_5_moe_text config."""
|
| 87 |
+
if data.get("model_type") not in TEXT_MODEL_TYPES:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
f"text_config.model_type={data.get('model_type')!r}; "
|
| 90 |
+
f"expected one of {TEXT_MODEL_TYPES}"
|
| 91 |
+
)
|
| 92 |
+
if any(t != "moe" for t in data.get("mlp_layer_types") or ()):
|
| 93 |
+
raise NotImplementedError("every text_config.mlp_layer_types must be moe")
|
| 94 |
+
for key, default, required in FIXED_TEXT_FLAGS:
|
| 95 |
+
if data.get(key, default) is not required:
|
| 96 |
+
raise NotImplementedError(
|
| 97 |
+
f"text_config.{key} must be {required}; got {data.get(key)!r}"
|
| 98 |
+
)
|
| 99 |
+
if data.get("tie_word_embeddings", False):
|
| 100 |
+
raise NotImplementedError("the backbone keeps a separate lm_head")
|
| 101 |
+
rope = data.get("rope_parameters") or data
|
| 102 |
+
if rope.get("rope_type", rope.get("type", "default")) != "default":
|
| 103 |
+
raise NotImplementedError("only the default rope_type is supported")
|
| 104 |
+
|
| 105 |
+
num_layers = data["num_hidden_layers"]
|
| 106 |
+
layer_types = data.get("layer_types") or [
|
| 107 |
+
(
|
| 108 |
+
"full_attention"
|
| 109 |
+
if (i + 1) % data["full_attention_interval"] == 0
|
| 110 |
+
else "linear_attention"
|
| 111 |
+
)
|
| 112 |
+
for i in range(num_layers)
|
| 113 |
+
]
|
| 114 |
+
# Text-only positions are equal on every M-RoPE axis, so an mrope_section
|
| 115 |
+
# reduces to the plain 1-D rotation.
|
| 116 |
+
return cls(
|
| 117 |
+
vocab_size=data["vocab_size"],
|
| 118 |
+
hidden_size=data["hidden_size"],
|
| 119 |
+
num_hidden_layers=num_layers,
|
| 120 |
+
layer_types=list(layer_types),
|
| 121 |
+
num_attention_heads=data["num_attention_heads"],
|
| 122 |
+
num_key_value_heads=data["num_key_value_heads"],
|
| 123 |
+
head_dim=data["head_dim"],
|
| 124 |
+
rope_theta=rope["rope_theta"],
|
| 125 |
+
# Older configs keep the factor at the top level; 0.25 is the HF default.
|
| 126 |
+
partial_rotary_factor=rope.get(
|
| 127 |
+
"partial_rotary_factor", data.get("partial_rotary_factor", 0.25)
|
| 128 |
+
),
|
| 129 |
+
rms_norm_eps=data["rms_norm_eps"],
|
| 130 |
+
max_position_embeddings=data["max_position_embeddings"],
|
| 131 |
+
linear_conv_kernel_dim=data["linear_conv_kernel_dim"],
|
| 132 |
+
linear_key_head_dim=data["linear_key_head_dim"],
|
| 133 |
+
linear_value_head_dim=data["linear_value_head_dim"],
|
| 134 |
+
linear_num_key_heads=data["linear_num_key_heads"],
|
| 135 |
+
linear_num_value_heads=data["linear_num_value_heads"],
|
| 136 |
+
num_experts=data["num_experts"],
|
| 137 |
+
num_experts_per_tok=data["num_experts_per_tok"],
|
| 138 |
+
moe_intermediate_size=data["moe_intermediate_size"],
|
| 139 |
+
shared_expert_intermediate_size=data["shared_expert_intermediate_size"],
|
| 140 |
+
norm_topk_prob=data.get("norm_topk_prob", True),
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@dataclass(kw_only=True, frozen=True)
|
| 145 |
+
class AudioDecoderConfig:
|
| 146 |
+
dim: int
|
| 147 |
+
intermediate_size: int
|
| 148 |
+
n_head: int
|
| 149 |
+
n_local_heads: int
|
| 150 |
+
head_dim: int
|
| 151 |
+
norm_eps: float
|
| 152 |
+
rope_base: float
|
| 153 |
+
rotary_percent: float
|
| 154 |
+
vocab_size: int
|
| 155 |
+
num_codebooks: int
|
| 156 |
+
shared_enrichment_layers: int
|
| 157 |
+
vq_backbone_codebooks: int
|
| 158 |
+
|
| 159 |
+
def __post_init__(self) -> None:
|
| 160 |
+
if (
|
| 161 |
+
self.n_head % self.n_local_heads
|
| 162 |
+
or not 0 < self.rotary_dim <= self.head_dim
|
| 163 |
+
or self.rotary_dim % 2
|
| 164 |
+
):
|
| 165 |
+
raise ValueError("invalid tower attention geometry")
|
| 166 |
+
if (
|
| 167 |
+
self.num_codebooks < 2
|
| 168 |
+
or not 0 <= self.vq_backbone_codebooks < self.num_codebooks
|
| 169 |
+
):
|
| 170 |
+
raise ValueError("invalid codebook counts")
|
| 171 |
+
if self.shared_enrichment_layers < 1:
|
| 172 |
+
raise ValueError("shared_enrichment_layers must be >= 1")
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def rotary_dim(self) -> int:
|
| 176 |
+
return int(self.head_dim * self.rotary_percent)
|
| 177 |
+
|
| 178 |
+
@classmethod
|
| 179 |
+
def from_dict(cls, data: dict[str, Any]) -> "AudioDecoderConfig":
|
| 180 |
+
for key, value in FIXED_AUDIO_DECODER_FLAGS.items():
|
| 181 |
+
if data.get(key, value) != value:
|
| 182 |
+
raise ValueError(
|
| 183 |
+
f"unsupported audio_decoder_config.{key}={data[key]!r}"
|
| 184 |
+
)
|
| 185 |
+
if data.get("text_dim", data["dim"]) != data["dim"]:
|
| 186 |
+
raise ValueError("audio_decoder_config.text_dim must equal dim")
|
| 187 |
+
if data.get("n_layer") != data["shared_enrichment_layers"]:
|
| 188 |
+
raise ValueError("n_layer must equal shared_enrichment_layers")
|
| 189 |
+
placement = data.get("vq_feature_placement")
|
| 190 |
+
if placement not in ("backbone_partial", "mtp_shared_pre") or (
|
| 191 |
+
placement == "mtp_shared_pre" and data["vq_backbone_codebooks"] != 0
|
| 192 |
+
):
|
| 193 |
+
raise ValueError(f"unsupported vq_feature_placement {placement!r}")
|
| 194 |
+
return cls(**{f.name: data[f.name] for f in fields(cls)})
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@dataclass(kw_only=True)
|
| 198 |
+
class FishOmniConfig:
|
| 199 |
+
text: FishOmniTextConfig
|
| 200 |
+
audio_decoder: AudioDecoderConfig
|
| 201 |
+
semantic_start_token_id: int
|
| 202 |
+
semantic_end_token_id: int
|
| 203 |
+
eos_token_id: int
|
| 204 |
+
fp8_experts: bool = False
|
| 205 |
+
# Rows of the output head: 0 = full vocabulary; 4097 = speech-only [EOS, semantic 0..4095].
|
| 206 |
+
semantic_head_rows: int = 0
|
| 207 |
+
|
| 208 |
+
def __post_init__(self) -> None:
|
| 209 |
+
start, end = self.semantic_start_token_id, self.semantic_end_token_id
|
| 210 |
+
if not 0 <= start <= end < self.text.vocab_size:
|
| 211 |
+
raise ValueError("the semantic band must lie inside the text vocabulary")
|
| 212 |
+
if start <= self.eos_token_id <= end:
|
| 213 |
+
raise ValueError("eos_token_id lies inside the semantic band")
|
| 214 |
+
if self.audio_decoder.dim != self.text.hidden_size:
|
| 215 |
+
raise ValueError("tower and backbone hidden sizes must match")
|
| 216 |
+
if self.audio_decoder.vocab_size != end - start + 1:
|
| 217 |
+
raise ValueError("tower vocabulary must match the semantic token band")
|
| 218 |
+
|
| 219 |
+
@classmethod
|
| 220 |
+
def from_dict(cls, data: dict[str, Any]) -> "FishOmniConfig":
|
| 221 |
+
if data.get("model_type") != FISH_OMNI_MODEL_TYPE:
|
| 222 |
+
raise ValueError(
|
| 223 |
+
f"model_type={data.get('model_type')!r}; "
|
| 224 |
+
f"expected {FISH_OMNI_MODEL_TYPE!r}"
|
| 225 |
+
)
|
| 226 |
+
if data.get("audio_encoder_config") is not None:
|
| 227 |
+
raise NotImplementedError("audio_encoder_config is not supported")
|
| 228 |
+
if data.get("speech_template_version") != SPEECH_TEMPLATE_VERSION:
|
| 229 |
+
raise NotImplementedError(
|
| 230 |
+
f"speech_template_version={data.get('speech_template_version')!r}; "
|
| 231 |
+
f"only {SPEECH_TEMPLATE_VERSION} is supported"
|
| 232 |
+
)
|
| 233 |
+
# The GGUF keeps the FP8 checkpoint's quantization_config; its experts are GGUF banks instead.
|
| 234 |
+
quantization = data.get("quantization_config")
|
| 235 |
+
if quantization is not None and (
|
| 236 |
+
quantization.get("quant_method") != FP8_QUANT_METHOD
|
| 237 |
+
or quantization.get("weight_block_size") != [FP8_BLOCK_SIZE] * 2
|
| 238 |
+
):
|
| 239 |
+
raise NotImplementedError(
|
| 240 |
+
f"only {FP8_QUANT_METHOD} quantization with weight_block_size "
|
| 241 |
+
f"[{FP8_BLOCK_SIZE}, {FP8_BLOCK_SIZE}] is supported"
|
| 242 |
+
)
|
| 243 |
+
eos = data.get("eos_token_id", data["text_config"].get("eos_token_id"))
|
| 244 |
+
if eos is None:
|
| 245 |
+
raise ValueError("config has no eos_token_id")
|
| 246 |
+
return cls(
|
| 247 |
+
text=FishOmniTextConfig.from_dict(data["text_config"]),
|
| 248 |
+
audio_decoder=AudioDecoderConfig.from_dict(data["audio_decoder_config"]),
|
| 249 |
+
semantic_start_token_id=data["semantic_start_token_id"],
|
| 250 |
+
semantic_end_token_id=data["semantic_end_token_id"],
|
| 251 |
+
eos_token_id=eos,
|
| 252 |
+
fp8_experts=False,
|
| 253 |
+
semantic_head_rows=int(data.get("semantic_head_rows", 0) or 0),
|
| 254 |
+
)
|
torch/fish_speech/models/text2semantic/fish_omni/generate.py
ADDED
|
@@ -0,0 +1,686 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified for the drama3-expressive-medium PyTorch port (GGUF runtime). Prompt building
|
| 2 |
+
# (build_drama3_prompt and its checks) is upstream's, with imports adjusted. The generation loop was
|
| 3 |
+
# rewritten to follow audio.cpp's fish_drama3 generator (branch drama3-medium, commits c6dc0759 and
|
| 4 |
+
# eb29d173, src/community_models/fish_drama3/generator.cpp):
|
| 5 |
+
# * the main token is drawn over the speech head [EOS, semantic 0..4095] with temperature, top-p
|
| 6 |
+
# then top-k; a draw that repeats one of the last 16 *generated* main tokens is replaced by a
|
| 7 |
+
# second draw at temperature 1.0, top-k 30, top-p 0.95 (repetition-aware sampling);
|
| 8 |
+
# * pause fix: after max_pause_frames consecutive frames whose semantic code is in the silence
|
| 9 |
+
# list, those codes are masked from the next draw (speech or EOS must follow); length guard:
|
| 10 |
+
# a pause after end_ratio x the text's expected frames ends the take, cap_ratio x expected
|
| 11 |
+
# stops it regardless (expected frames estimated from the text as audio.cpp does);
|
| 12 |
+
# * text chunking: audio.cpp's tag_aware splitter (200 codepoints), each chunk conditioned on the
|
| 13 |
+
# previous chunk's take, seed + chunk index;
|
| 14 |
+
# * CUDA-graph decode (one graph per attended-KV bucket) adapted to the speech head and the pause
|
| 15 |
+
# state; head logits in fp32.
|
| 16 |
+
import logging
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import time
|
| 21 |
+
from collections.abc import Sequence
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
from typing import Literal
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
from tokenizers import Tokenizer
|
| 28 |
+
|
| 29 |
+
from ..errors import InvalidInputError
|
| 30 |
+
from .config import FishOmniConfig
|
| 31 |
+
from .tower import (
|
| 32 |
+
RAS_TEMPERATURE,
|
| 33 |
+
RAS_TOP_K,
|
| 34 |
+
RAS_TOP_P,
|
| 35 |
+
RAS_WINDOW_FRAMES,
|
| 36 |
+
TowerAttention,
|
| 37 |
+
sample_top_k_top_p,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
logger = logging.getLogger(__name__)
|
| 41 |
+
|
| 42 |
+
DRAMA3_TTS_INSTRUCTION = "convert the provided text to speech"
|
| 43 |
+
DRAMA3_REFERENCE_INSTRUCTION = (
|
| 44 |
+
"convert the provided text to speech reference to the following:"
|
| 45 |
+
)
|
| 46 |
+
DRAMA3_MESSAGE_END = "<|im_end|>\n"
|
| 47 |
+
DRAMA3_GENERATION_START = "<|im_start|>assistant\n<|voice|>"
|
| 48 |
+
# Only the prompt builder writes these; other special tokens in caller text are content.
|
| 49 |
+
DRAMA3_STRUCTURAL_TOKENS = (
|
| 50 |
+
"<|im_start|>",
|
| 51 |
+
"<|im_end|>",
|
| 52 |
+
"<|voice|>",
|
| 53 |
+
"<|text|>",
|
| 54 |
+
"<|interleave|>",
|
| 55 |
+
"<|semantic:",
|
| 56 |
+
)
|
| 57 |
+
SPEAKER_TAG_PATTERN = re.compile(r"<\|speaker:([0-9]+)\|>")
|
| 58 |
+
# The tokenizer has one token per speaker, <|speaker:0|> to <|speaker:15|>.
|
| 59 |
+
MAX_SPEAKER_ID = 15
|
| 60 |
+
# The Unicode White_Space property; str.strip() without arguments also strips
|
| 61 |
+
# U+001C..U+001F, which would change the empty check and the speaker-tag rule.
|
| 62 |
+
UNICODE_WHITE_SPACE = "".join(
|
| 63 |
+
map(
|
| 64 |
+
chr,
|
| 65 |
+
(*range(0x9, 0xE), 0x20, 0x85, 0xA0, 0x1680, *range(0x2000, 0x200B))
|
| 66 |
+
+ (0x2028, 0x2029, 0x202F, 0x205F, 0x3000),
|
| 67 |
+
)
|
| 68 |
+
)
|
| 69 |
+
DRAMA3_MAX_PROMPT_ROWS = 8192
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class Drama3PromptTooLongError(InvalidInputError):
|
| 73 |
+
"""The prompt has more than DRAMA3_MAX_PROMPT_ROWS rows."""
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def validate_drama3_text(text: str, location: str) -> None:
|
| 77 |
+
"""Non-empty, no structural tokens, and only canonical speaker tags 0..15."""
|
| 78 |
+
if not text.strip(UNICODE_WHITE_SPACE):
|
| 79 |
+
raise InvalidInputError(f"{location}: text must not be empty")
|
| 80 |
+
for token in DRAMA3_STRUCTURAL_TOKENS:
|
| 81 |
+
if token in text:
|
| 82 |
+
raise InvalidInputError(
|
| 83 |
+
f"{location}: {token} is written by the prompt builder"
|
| 84 |
+
)
|
| 85 |
+
for marker in re.finditer(r"<\|speaker", text):
|
| 86 |
+
tag = SPEAKER_TAG_PATTERN.match(text, marker.start())
|
| 87 |
+
digits = tag.group(1) if tag else ""
|
| 88 |
+
if not digits or str(int(digits)) != digits or int(digits) > MAX_SPEAKER_ID:
|
| 89 |
+
raise InvalidInputError(
|
| 90 |
+
f"{location}: speaker tags must be <|speaker:0|> to "
|
| 91 |
+
f"<|speaker:{MAX_SPEAKER_ID}|>; got {text!r}"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def with_speaker_tag(text: str) -> str:
|
| 96 |
+
"""Prefix <|speaker:0|> unless a tag already leads the text after white space."""
|
| 97 |
+
if SPEAKER_TAG_PATTERN.match(text.lstrip(UNICODE_WHITE_SPACE)) is None:
|
| 98 |
+
return f"<|speaker:0|> {text}"
|
| 99 |
+
return text
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def build_drama3_prompt(
|
| 103 |
+
text: str,
|
| 104 |
+
tokenizer: Tokenizer,
|
| 105 |
+
config: FishOmniConfig,
|
| 106 |
+
prompt_texts: Sequence[str] = (),
|
| 107 |
+
prompt_tokens: Sequence[torch.Tensor] = (),
|
| 108 |
+
history: Sequence[tuple[str, torch.Tensor]] = (),
|
| 109 |
+
) -> torch.Tensor:
|
| 110 |
+
"""CPU int64 rows [rows, 1 + num_codebooks] ending in the open assistant voice turn.
|
| 111 |
+
|
| 112 |
+
Text rows are [token, 0, ..., 0]; audio rows are [c0 + semantic_start, c0..cN-1].
|
| 113 |
+
Every literal is tokenized on its own: tokenizing the joined string changes ids
|
| 114 |
+
at the seams. history holds earlier (text, codes) chunks, written as completed
|
| 115 |
+
user and assistant voice turns before the current one.
|
| 116 |
+
"""
|
| 117 |
+
num_codebooks = config.audio_decoder.num_codebooks
|
| 118 |
+
codebook_size = config.audio_decoder.vocab_size
|
| 119 |
+
for token, expected in (
|
| 120 |
+
("<|semantic:0|>", config.semantic_start_token_id),
|
| 121 |
+
(f"<|semantic:{codebook_size - 1}|>", config.semantic_end_token_id),
|
| 122 |
+
("<|im_end|>", config.eos_token_id),
|
| 123 |
+
):
|
| 124 |
+
if tokenizer.token_to_id(token) != expected:
|
| 125 |
+
raise ValueError(f"tokenizer/config mismatch for {token}")
|
| 126 |
+
if len(prompt_texts) != len(prompt_tokens):
|
| 127 |
+
raise InvalidInputError("every reference needs both a transcript and codes")
|
| 128 |
+
validate_drama3_text(text, "text")
|
| 129 |
+
|
| 130 |
+
def check_codes(codes: torch.Tensor, location: str) -> None:
|
| 131 |
+
if (
|
| 132 |
+
codes.dtype.is_floating_point
|
| 133 |
+
or codes.dtype == torch.bool
|
| 134 |
+
or codes.ndim != 2
|
| 135 |
+
or codes.shape[0] != num_codebooks
|
| 136 |
+
or codes.shape[1] == 0
|
| 137 |
+
):
|
| 138 |
+
raise InvalidInputError(
|
| 139 |
+
f"{location}: codes must be integer [{num_codebooks}, frames >= 1]; "
|
| 140 |
+
f"got {codes.dtype} {tuple(codes.shape)}"
|
| 141 |
+
)
|
| 142 |
+
if codes.min() < 0 or codes.max() >= codebook_size:
|
| 143 |
+
raise InvalidInputError(
|
| 144 |
+
f"{location}: codes must be in [0, {codebook_size})"
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
segments: list[str | torch.Tensor] = [
|
| 148 |
+
"<|im_start|>system\n",
|
| 149 |
+
DRAMA3_REFERENCE_INSTRUCTION if prompt_tokens else DRAMA3_TTS_INSTRUCTION,
|
| 150 |
+
]
|
| 151 |
+
|
| 152 |
+
for index, (transcript, codes) in enumerate(zip(prompt_texts, prompt_tokens), 1):
|
| 153 |
+
location = f"reference {index}"
|
| 154 |
+
validate_drama3_text(transcript, location)
|
| 155 |
+
check_codes(codes, location)
|
| 156 |
+
# The tag must follow "Text: " directly; leading white space moves behind it.
|
| 157 |
+
tagged = with_speaker_tag(transcript)
|
| 158 |
+
body = tagged.lstrip(UNICODE_WHITE_SPACE)
|
| 159 |
+
tag = SPEAKER_TAG_PATTERN.match(body)
|
| 160 |
+
leading = tagged[: len(tagged) - len(body)]
|
| 161 |
+
transcript = tag.group(0) + leading + body[tag.end() :]
|
| 162 |
+
segments += [f"\n\n[Reference {index}]\nText: {transcript}\nSpeech: ", codes]
|
| 163 |
+
segments.append(DRAMA3_MESSAGE_END)
|
| 164 |
+
for index, (turn_text, codes) in enumerate(history, 1):
|
| 165 |
+
location = f"history {index}"
|
| 166 |
+
validate_drama3_text(turn_text, location)
|
| 167 |
+
check_codes(codes, location)
|
| 168 |
+
segments += [
|
| 169 |
+
"<|im_start|>user\n",
|
| 170 |
+
with_speaker_tag(turn_text),
|
| 171 |
+
DRAMA3_MESSAGE_END,
|
| 172 |
+
DRAMA3_GENERATION_START,
|
| 173 |
+
codes,
|
| 174 |
+
DRAMA3_MESSAGE_END,
|
| 175 |
+
]
|
| 176 |
+
segments += [
|
| 177 |
+
"<|im_start|>user\n",
|
| 178 |
+
with_speaker_tag(text),
|
| 179 |
+
DRAMA3_MESSAGE_END,
|
| 180 |
+
DRAMA3_GENERATION_START,
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
+
rows = []
|
| 184 |
+
for segment in segments:
|
| 185 |
+
if isinstance(segment, str):
|
| 186 |
+
ids = torch.tensor(tokenizer.encode(segment).ids, dtype=torch.long)
|
| 187 |
+
text_rows = torch.zeros((len(ids), 1 + num_codebooks), dtype=torch.long)
|
| 188 |
+
text_rows[:, 0] = ids
|
| 189 |
+
rows.append(text_rows)
|
| 190 |
+
else:
|
| 191 |
+
codes = segment.to(device="cpu", dtype=torch.long)
|
| 192 |
+
main = codes[:1] + config.semantic_start_token_id
|
| 193 |
+
rows.append(torch.cat((main, codes)).T)
|
| 194 |
+
rows = torch.cat(rows)
|
| 195 |
+
if len(rows) > DRAMA3_MAX_PROMPT_ROWS:
|
| 196 |
+
raise Drama3PromptTooLongError(
|
| 197 |
+
f"prompt has {len(rows)} rows; at most {DRAMA3_MAX_PROMPT_ROWS}"
|
| 198 |
+
)
|
| 199 |
+
return rows
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
DRAMA3_GRAPH_KV_BUCKETS = (1024, 2048, 4096, 8192, 16384)
|
| 203 |
+
DRAMA3_TEXT_CHUNK_CODEPOINTS = 200 # audio.cpp text_chunk_size default
|
| 204 |
+
|
| 205 |
+
FinishReason = Literal["eos", "length", "pause_end", "length_guard"]
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# --------------------------------------------------------------------------------------------
|
| 209 |
+
# Pause fix and length guard (audio.cpp PauseClamp)
|
| 210 |
+
# --------------------------------------------------------------------------------------------
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@dataclass
|
| 214 |
+
class PauseFix:
|
| 215 |
+
"""max_pause_frames 0 = off (then the length guard is off too, as in audio.cpp)."""
|
| 216 |
+
|
| 217 |
+
max_pause_frames: int = 0
|
| 218 |
+
silence_codes: tuple[int, ...] = ()
|
| 219 |
+
end_ratio: float = 2.0
|
| 220 |
+
cap_ratio: float = 3.0
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
_CJK_PUNCT = frozenset((0x3002, 0x3001, 0xFF01, 0xFF1F, 0x300C, 0x300D, 0x2026, 0x30FB, 0xFF08, 0xFF09))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def expected_frames(text: str) -> float:
|
| 227 |
+
"""Expected frames for the spoken text (21.5 frames/s), as audio.cpp estimates them:
|
| 228 |
+
3.88 per CJK/kana character + 2.00 per ASCII letter or digit + 23.9 per control span ([...],
|
| 229 |
+
<...>, counted at each opening bracket) + 8.5. A "Direction: ...\\nLine:" prefix is not spoken."""
|
| 230 |
+
spoken = text
|
| 231 |
+
if spoken.startswith("Direction:"):
|
| 232 |
+
line = spoken.find("\nLine:")
|
| 233 |
+
if line >= 0:
|
| 234 |
+
spoken = spoken[line + 6 :]
|
| 235 |
+
cjk = latin = spans = 0
|
| 236 |
+
depth_square = depth_angle = 0
|
| 237 |
+
for ch in spoken:
|
| 238 |
+
cp = ord(ch)
|
| 239 |
+
if ch == "[":
|
| 240 |
+
depth_square += 1
|
| 241 |
+
spans += 1
|
| 242 |
+
continue
|
| 243 |
+
if ch == "]":
|
| 244 |
+
depth_square = max(0, depth_square - 1)
|
| 245 |
+
continue
|
| 246 |
+
if ch == "<":
|
| 247 |
+
depth_angle += 1
|
| 248 |
+
spans += 1
|
| 249 |
+
continue
|
| 250 |
+
if ch == ">":
|
| 251 |
+
depth_angle = max(0, depth_angle - 1)
|
| 252 |
+
continue
|
| 253 |
+
if depth_square > 0 or depth_angle > 0:
|
| 254 |
+
continue
|
| 255 |
+
if cp >= 0x3000 and cp not in _CJK_PUNCT:
|
| 256 |
+
cjk += 1
|
| 257 |
+
elif cp < 0x80 and ch.isalnum():
|
| 258 |
+
latin += 1
|
| 259 |
+
return 3.88 * cjk + 2.00 * latin + 23.9 * spans + 8.5
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def load_silence_codes(spec: str) -> tuple[int, ...]:
|
| 263 |
+
"""A file path or an inline list; every run of digits is one code (audio.cpp parse_silence_codes)."""
|
| 264 |
+
text = spec
|
| 265 |
+
if os.path.isfile(spec):
|
| 266 |
+
with open(spec, encoding="utf-8") as f:
|
| 267 |
+
text = f.read()
|
| 268 |
+
codes = tuple(sorted({int(m) for m in re.findall(r"[0-9]+", text)}))
|
| 269 |
+
if not codes:
|
| 270 |
+
raise InvalidInputError("silence_codes is empty")
|
| 271 |
+
return codes
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
# --------------------------------------------------------------------------------------------
|
| 275 |
+
# Text chunking (audio.cpp framework/text/chunking.cpp, tag_aware mode)
|
| 276 |
+
# --------------------------------------------------------------------------------------------
|
| 277 |
+
|
| 278 |
+
_ASCII_SPACE = frozenset(" \t\n\v\f\r")
|
| 279 |
+
_SENTENCE_BREAKS = frozenset(".!?。!?")
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _trim_ascii(text: str) -> str:
|
| 283 |
+
return text.strip(" \t\n\v\f\r")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _tag_aware_units(text: str) -> list[tuple[int, int, bool, bool]]:
|
| 287 |
+
"""(start, end, is_tag, sentence_break) over codepoints."""
|
| 288 |
+
units, pos, n = [], 0, len(text)
|
| 289 |
+
while pos < n:
|
| 290 |
+
while pos < n and text[pos] in _ASCII_SPACE:
|
| 291 |
+
pos += 1
|
| 292 |
+
if pos >= n:
|
| 293 |
+
break
|
| 294 |
+
start, tag = pos, False
|
| 295 |
+
if text[pos] in "[<":
|
| 296 |
+
close = "]" if text[pos] == "[" else ">"
|
| 297 |
+
pos += 1
|
| 298 |
+
while pos < n and text[pos] != close:
|
| 299 |
+
pos += 1
|
| 300 |
+
if pos < n:
|
| 301 |
+
pos += 1
|
| 302 |
+
tag = True
|
| 303 |
+
else:
|
| 304 |
+
pos = start + 1
|
| 305 |
+
while pos < n and text[pos] not in _ASCII_SPACE and text[pos] not in "[<":
|
| 306 |
+
pos += 1
|
| 307 |
+
else:
|
| 308 |
+
pos += 1
|
| 309 |
+
while (pos < n and text[pos] not in _ASCII_SPACE and text[pos] not in "[<"
|
| 310 |
+
and text[pos - 1] not in _SENTENCE_BREAKS):
|
| 311 |
+
pos += 1
|
| 312 |
+
units.append((start, pos, tag, (not tag) and text[pos - 1] in _SENTENCE_BREAKS))
|
| 313 |
+
return units
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _split_tag_aware_body(text: str, budget: int) -> list[str]:
|
| 317 |
+
if len(text) <= budget:
|
| 318 |
+
return [text]
|
| 319 |
+
units = _tag_aware_units(text)
|
| 320 |
+
if not units:
|
| 321 |
+
return []
|
| 322 |
+
|
| 323 |
+
def span(a: int, b: int) -> int:
|
| 324 |
+
return units[b - 1][1] - units[a][0] if a < b else 0
|
| 325 |
+
|
| 326 |
+
def join(a: int, b: int) -> str:
|
| 327 |
+
return _trim_ascii(text[units[a][0] : units[b - 1][1]]) if a < b else ""
|
| 328 |
+
|
| 329 |
+
sentences, s0 = [], 0
|
| 330 |
+
for i, u in enumerate(units):
|
| 331 |
+
if u[3]:
|
| 332 |
+
sentences.append((s0, i + 1))
|
| 333 |
+
s0 = i + 1
|
| 334 |
+
if s0 < len(units):
|
| 335 |
+
sentences.append((s0, len(units)))
|
| 336 |
+
chunks, si = [], 0
|
| 337 |
+
while si < len(sentences):
|
| 338 |
+
a, b = sentences[si]
|
| 339 |
+
if span(a, b) > budget: # one long sentence: pack units up to the budget
|
| 340 |
+
u = a
|
| 341 |
+
while u < b:
|
| 342 |
+
hard = u
|
| 343 |
+
while hard < b and span(u, hard + 1) <= budget:
|
| 344 |
+
hard += 1
|
| 345 |
+
hard = max(hard, u + 1)
|
| 346 |
+
if piece := join(u, hard):
|
| 347 |
+
chunks.append(piece)
|
| 348 |
+
u = hard
|
| 349 |
+
si += 1
|
| 350 |
+
continue
|
| 351 |
+
end = si
|
| 352 |
+
while end < len(sentences) and span(sentences[si][0], sentences[end][1]) <= budget:
|
| 353 |
+
end += 1
|
| 354 |
+
end = max(end, si + 1)
|
| 355 |
+
if piece := join(sentences[si][0], sentences[end - 1][1]):
|
| 356 |
+
chunks.append(piece)
|
| 357 |
+
si = end
|
| 358 |
+
return chunks
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def split_text_chunks(text: str, budget: int = DRAMA3_TEXT_CHUNK_CODEPOINTS) -> list[str]:
|
| 362 |
+
"""audio.cpp's tag_aware chunking: whole sentences up to `budget` codepoints, [..] / <..> tags
|
| 363 |
+
kept whole, a leading "(...)" control repeated on every chunk. Text is ASCII-trimmed."""
|
| 364 |
+
trimmed = _trim_ascii(text)
|
| 365 |
+
if not trimmed:
|
| 366 |
+
return []
|
| 367 |
+
if trimmed.startswith("("):
|
| 368 |
+
close = trimmed.find(")")
|
| 369 |
+
if close >= 0 and close + 1 < len(trimmed):
|
| 370 |
+
prefix, body = _trim_ascii(trimmed[: close + 1]), _trim_ascii(trimmed[close + 1 :])
|
| 371 |
+
if prefix and body:
|
| 372 |
+
body_budget = max(1, budget - len(prefix) - 1)
|
| 373 |
+
return [f"{prefix} {c}" for c in _split_tag_aware_body(body, body_budget)]
|
| 374 |
+
return _split_tag_aware_body(trimmed, budget)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
# --------------------------------------------------------------------------------------------
|
| 378 |
+
# Generation
|
| 379 |
+
# --------------------------------------------------------------------------------------------
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
@dataclass
|
| 383 |
+
class Drama3Sampling:
|
| 384 |
+
temperature: float = 0.7
|
| 385 |
+
top_p: float = 0.7
|
| 386 |
+
top_k: int = 30
|
| 387 |
+
max_new_tokens: int = 1024
|
| 388 |
+
pause: PauseFix | None = None
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
@dataclass
|
| 392 |
+
class Drama3Take:
|
| 393 |
+
frames: torch.Tensor # CPU long [frames, 1 + num_codebooks] (main token, codes 0..N-1)
|
| 394 |
+
finish_reason: FinishReason
|
| 395 |
+
prefill_s: float
|
| 396 |
+
decode_s: float
|
| 397 |
+
|
| 398 |
+
@property
|
| 399 |
+
def codes(self) -> torch.Tensor:
|
| 400 |
+
"""[num_codebooks, frames] codec codes."""
|
| 401 |
+
return self.frames[:, 1:].T.contiguous()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def ensure_drama3_caches(model, capacity: int) -> None:
|
| 405 |
+
"""Grow the backbone and tower caches to capacity rows, reused across requests."""
|
| 406 |
+
if model.cache_capacity >= capacity:
|
| 407 |
+
return
|
| 408 |
+
if model.decode_graphs is not None:
|
| 409 |
+
model.decode_graphs = None # the graphs captured the old cache buffers
|
| 410 |
+
torch.cuda.empty_cache()
|
| 411 |
+
model.backbone.setup_caches(max_batch_size=1, max_seq_len=capacity)
|
| 412 |
+
model.audio_decoder.setup_caches(capacity)
|
| 413 |
+
model.cache_capacity = capacity
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def release_drama3_caches(model) -> None:
|
| 417 |
+
"""Free KV caches, recurrent states and captured graphs (e.g. before a codec decode)."""
|
| 418 |
+
model.decode_graphs = None
|
| 419 |
+
for layer in model.backbone.model.layers:
|
| 420 |
+
mixer = layer.self_attn if layer.layer_type == "full_attention" else layer.linear_attn
|
| 421 |
+
for name in ("k_cache", "v_cache", "conv_state", "recurrent_state"):
|
| 422 |
+
if hasattr(mixer, name):
|
| 423 |
+
setattr(mixer, name, None)
|
| 424 |
+
for layer in (*model.audio_decoder.shared_layers, *model.audio_decoder.residual_layers):
|
| 425 |
+
attention = layer.transformer_layer.attention
|
| 426 |
+
attention.k_cache = attention.v_cache = None
|
| 427 |
+
model.backbone.max_seq_len = 0
|
| 428 |
+
model.cache_capacity = 0
|
| 429 |
+
torch.cuda.empty_cache()
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def head_logits_fp32(weight: torch.Tensor, hidden: torch.Tensor) -> torch.Tensor:
|
| 433 |
+
"""hidden @ weight.T with fp32 output (ggml computes these heads with F32 results)."""
|
| 434 |
+
if weight.dtype == torch.float32:
|
| 435 |
+
return F.linear(hidden.float(), weight)
|
| 436 |
+
if hidden.is_cuda:
|
| 437 |
+
return torch.mm(hidden.reshape(-1, hidden.shape[-1]).to(weight.dtype), weight.T,
|
| 438 |
+
out_dtype=torch.float32).reshape(*hidden.shape[:-1], weight.shape[0])
|
| 439 |
+
return F.linear(hidden.float(), weight.float())
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class Drama3Decoder:
|
| 443 |
+
"""One decode step on device-resident state: speech head -> sample the frame (pause mask, RAS)
|
| 444 |
+
-> tower (codes 1..9) -> backbone on the new frame. Runs eagerly or replays CUDA graphs captured
|
| 445 |
+
per attended-KV bucket (Drama 3 decode is launch-bound). The host reads one small status tensor
|
| 446 |
+
per step (main token, finite flag, silent run)."""
|
| 447 |
+
|
| 448 |
+
def __init__(self, model, capacity: int, use_graphs: bool) -> None:
|
| 449 |
+
backbone, tower = model.backbone, model.audio_decoder
|
| 450 |
+
self.model = model
|
| 451 |
+
cfg = model.config
|
| 452 |
+
device = tower.device
|
| 453 |
+
width = 1 + cfg.audio_decoder.num_codebooks
|
| 454 |
+
self.codebook_size = cfg.audio_decoder.vocab_size
|
| 455 |
+
self.sem_begin = cfg.semantic_start_token_id
|
| 456 |
+
self.eos = cfg.eos_token_id
|
| 457 |
+
self.hidden = torch.zeros((1, cfg.text.hidden_size), dtype=backbone.dtype, device=device)
|
| 458 |
+
self.next_hidden = torch.zeros_like(self.hidden)
|
| 459 |
+
self.position = torch.zeros(1, dtype=torch.long, device=device)
|
| 460 |
+
self.frame = torch.zeros((1, width), dtype=torch.long, device=device)
|
| 461 |
+
self.sampled = torch.zeros_like(self.frame)
|
| 462 |
+
self.history = torch.full((RAS_WINDOW_FRAMES,), -1, dtype=torch.long, device=device)
|
| 463 |
+
self.temperature = torch.zeros((), dtype=torch.float32, device=device)
|
| 464 |
+
self.top_k = torch.zeros((), dtype=torch.long, device=device)
|
| 465 |
+
self.top_p = torch.zeros((), dtype=torch.float32, device=device)
|
| 466 |
+
self.finite = torch.ones((), dtype=torch.bool, device=device)
|
| 467 |
+
# Pause fix state: silence-code lookup over codes, blocked candidates over [EOS, codes].
|
| 468 |
+
self.sil_lookup = torch.zeros(self.codebook_size, dtype=torch.bool, device=device)
|
| 469 |
+
self.sil_mask = torch.zeros(1 + self.codebook_size, dtype=torch.bool, device=device)
|
| 470 |
+
self.max_pause = torch.zeros((), dtype=torch.long, device=device)
|
| 471 |
+
self.silent_run = torch.zeros((), dtype=torch.long, device=device)
|
| 472 |
+
self.next_silent = torch.zeros((), dtype=torch.long, device=device)
|
| 473 |
+
self.status = torch.zeros(3, dtype=torch.long, device=device)
|
| 474 |
+
self.capacity = capacity
|
| 475 |
+
self.buckets = tuple(sorted({min(b, capacity) for b in DRAMA3_GRAPH_KV_BUCKETS if b < capacity} | {capacity}))
|
| 476 |
+
self.use_graphs = use_graphs and device.type == "cuda"
|
| 477 |
+
self.graphs: dict[int, torch.cuda.CUDAGraph] = {}
|
| 478 |
+
self.pool = torch.cuda.graph_pool_handle() if self.use_graphs else None
|
| 479 |
+
|
| 480 |
+
def tower_attentions(self):
|
| 481 |
+
tower = self.model.audio_decoder
|
| 482 |
+
for layer in (*tower.shared_layers, *tower.residual_layers):
|
| 483 |
+
yield layer.transformer_layer.attention
|
| 484 |
+
|
| 485 |
+
def run(self, kv_len: int) -> None:
|
| 486 |
+
backbone, tower = self.model.backbone, self.model.audio_decoder
|
| 487 |
+
logits = head_logits_fp32(backbone.lm_head.weight, self.hidden) # [1, 1 + codebook_size]
|
| 488 |
+
self.finite.copy_(torch.isfinite(logits).all())
|
| 489 |
+
blocked = self.sil_mask & (self.max_pause > 0) & (self.silent_run >= self.max_pause)
|
| 490 |
+
logits = logits.masked_fill(blocked, -torch.inf)
|
| 491 |
+
first = sample_top_k_top_p(logits, self.temperature, self.top_k, self.top_p, check_finite=False)
|
| 492 |
+
retry = sample_top_k_top_p(logits, RAS_TEMPERATURE, RAS_TOP_K, RAS_TOP_P, check_finite=False)
|
| 493 |
+
first_token = torch.where(first == 0, self.eos, self.sem_begin + first - 1)
|
| 494 |
+
repeated = (self.history == first_token[:, None]).any(-1) & (first != 0)
|
| 495 |
+
selected = torch.where(repeated, retry, first)
|
| 496 |
+
main = torch.where(selected == 0, self.eos, self.sem_begin + selected - 1)
|
| 497 |
+
c0 = (selected - 1).clamp(0, self.codebook_size - 1)
|
| 498 |
+
semantic = selected > 0
|
| 499 |
+
h = tower.run_shared(self.hidden.to(tower.codebook_embeddings.weight.dtype), c0, semantic,
|
| 500 |
+
self.position, self.frame)
|
| 501 |
+
codes = [c0]
|
| 502 |
+
for layer, head in zip(tower.residual_layers, tower.codebook_heads):
|
| 503 |
+
h = layer(h, codes[-1], semantic, self.position)
|
| 504 |
+
codes.append(sample_top_k_top_p(head_logits_fp32(head.weight, h), self.temperature, self.top_k,
|
| 505 |
+
self.top_p, check_finite=False))
|
| 506 |
+
sampled = torch.stack((main, *codes), dim=-1)
|
| 507 |
+
self.sampled.copy_(sampled)
|
| 508 |
+
is_silent = self.sil_lookup.index_select(0, c0)[0] # no host sync (graph capture)
|
| 509 |
+
self.next_silent.copy_(torch.where(is_silent, self.silent_run + 1, 0))
|
| 510 |
+
self.status.copy_(torch.stack((main[0], self.finite.long(), self.next_silent)))
|
| 511 |
+
embeddings = tower.embed_backbone(sampled, backbone.embed(main))
|
| 512 |
+
hidden = backbone(inputs_embeds=embeddings[None], input_pos=self.position + 1, static_kv_len=kv_len)
|
| 513 |
+
self.next_hidden.copy_(hidden[0])
|
| 514 |
+
|
| 515 |
+
def capture(self, kv_len: int) -> None:
|
| 516 |
+
for attention in self.tower_attentions():
|
| 517 |
+
attention.static_kv_len = kv_len
|
| 518 |
+
try:
|
| 519 |
+
stream = torch.cuda.Stream()
|
| 520 |
+
stream.wait_stream(torch.cuda.current_stream())
|
| 521 |
+
with torch.cuda.stream(stream):
|
| 522 |
+
for _ in range(2):
|
| 523 |
+
self.run(kv_len)
|
| 524 |
+
torch.cuda.current_stream().wait_stream(stream)
|
| 525 |
+
graph = torch.cuda.CUDAGraph()
|
| 526 |
+
with torch.cuda.graph(graph, pool=self.pool):
|
| 527 |
+
self.run(kv_len)
|
| 528 |
+
self.graphs[kv_len] = graph
|
| 529 |
+
finally:
|
| 530 |
+
for attention in self.tower_attentions():
|
| 531 |
+
attention.static_kv_len = None
|
| 532 |
+
|
| 533 |
+
def capture_all(self) -> None:
|
| 534 |
+
started = time.perf_counter()
|
| 535 |
+
with torch.cuda.device(self.hidden.device):
|
| 536 |
+
for kv_len in self.buckets:
|
| 537 |
+
self.capture(kv_len)
|
| 538 |
+
logger.info(f"decode CUDA graphs: kv buckets {self.buckets} captured in "
|
| 539 |
+
f"{time.perf_counter() - started:.1f}s")
|
| 540 |
+
|
| 541 |
+
def start(self, hidden: torch.Tensor, position: int, last_frame: torch.Tensor, sampling: Drama3Sampling) -> None:
|
| 542 |
+
self.hidden.copy_(hidden)
|
| 543 |
+
self.position.fill_(position)
|
| 544 |
+
self.frame.copy_(last_frame)
|
| 545 |
+
self.history.fill_(-1) # audio.cpp: only generated main tokens are checked for repeats
|
| 546 |
+
self.temperature.fill_(sampling.temperature)
|
| 547 |
+
self.top_k.fill_(sampling.top_k)
|
| 548 |
+
self.top_p.fill_(sampling.top_p)
|
| 549 |
+
pause = sampling.pause
|
| 550 |
+
self.sil_lookup.zero_()
|
| 551 |
+
self.sil_mask.zero_()
|
| 552 |
+
self.silent_run.zero_()
|
| 553 |
+
if pause is not None and pause.max_pause_frames > 0:
|
| 554 |
+
codes = torch.tensor([c for c in pause.silence_codes if 0 <= c < self.codebook_size],
|
| 555 |
+
dtype=torch.long, device=self.sil_lookup.device)
|
| 556 |
+
self.sil_lookup[codes] = True
|
| 557 |
+
self.sil_mask[codes + 1] = True
|
| 558 |
+
self.max_pause.fill_(pause.max_pause_frames)
|
| 559 |
+
else:
|
| 560 |
+
self.max_pause.fill_(0)
|
| 561 |
+
|
| 562 |
+
def step(self, position: int) -> tuple[torch.Tensor, int, int]:
|
| 563 |
+
"""Sample the frame after `position` and run the backbone on it.
|
| 564 |
+
Returns the frame [1, 1 + N] (device), its main token and the silent run after it."""
|
| 565 |
+
kv_len = next(b for b in self.buckets if b >= position + 2)
|
| 566 |
+
if self.use_graphs:
|
| 567 |
+
self.graphs[kv_len].replay()
|
| 568 |
+
else:
|
| 569 |
+
for attention in self.tower_attentions():
|
| 570 |
+
attention.static_kv_len = kv_len
|
| 571 |
+
try:
|
| 572 |
+
self.run(kv_len)
|
| 573 |
+
finally:
|
| 574 |
+
for attention in self.tower_attentions():
|
| 575 |
+
attention.static_kv_len = None
|
| 576 |
+
sampled = self.sampled.clone()
|
| 577 |
+
status = self.status.clone()
|
| 578 |
+
# Inputs of the next step, queued before the host waits on status.
|
| 579 |
+
self.hidden.copy_(self.next_hidden)
|
| 580 |
+
self.frame.copy_(sampled)
|
| 581 |
+
self.history.copy_(torch.cat((self.history[1:], sampled[0, :1])))
|
| 582 |
+
self.silent_run.copy_(self.next_silent)
|
| 583 |
+
self.position.add_(1)
|
| 584 |
+
main, finite, silent = status.tolist()
|
| 585 |
+
if not finite:
|
| 586 |
+
raise FloatingPointError("non-finite logits; refusing to sample invalid audio")
|
| 587 |
+
return sampled, main, silent
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def get_decoder(model, capacity: int, use_graphs: bool) -> Drama3Decoder:
|
| 591 |
+
"""The model's decoder for `capacity` cache rows (graphs captured on first use)."""
|
| 592 |
+
dec = model.decode_graphs
|
| 593 |
+
if dec is not None and dec.capacity >= capacity and dec.use_graphs == use_graphs:
|
| 594 |
+
return dec
|
| 595 |
+
model.decode_graphs = None
|
| 596 |
+
torch.cuda.empty_cache()
|
| 597 |
+
ensure_drama3_caches(model, capacity)
|
| 598 |
+
dec = Drama3Decoder(model, max(capacity, model.cache_capacity), use_graphs)
|
| 599 |
+
if dec.use_graphs:
|
| 600 |
+
dec.start(torch.zeros_like(dec.hidden), 0, dec.frame, Drama3Sampling())
|
| 601 |
+
dec.capture_all()
|
| 602 |
+
model.decode_graphs = dec
|
| 603 |
+
return dec
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
@torch.inference_mode()
|
| 607 |
+
def generate_drama3(
|
| 608 |
+
model,
|
| 609 |
+
prompt: torch.Tensor,
|
| 610 |
+
*,
|
| 611 |
+
text: str,
|
| 612 |
+
sampling: Drama3Sampling,
|
| 613 |
+
capacity: int = 4096,
|
| 614 |
+
prefill_chunk_size: int = 512,
|
| 615 |
+
use_graphs: bool = True,
|
| 616 |
+
seed: int | None = None,
|
| 617 |
+
) -> Drama3Take:
|
| 618 |
+
"""Sample frames after the prompt rows (audio.cpp generator semantics).
|
| 619 |
+
|
| 620 |
+
`text` is the request text of this chunk (the length guard's estimate). `seed` seeds torch's
|
| 621 |
+
generators after graph capture, so a take does not depend on whether graphs were captured
|
| 622 |
+
first. The tower cache of prompt row p is filled with frame p + 1 as its label; the first decode
|
| 623 |
+
step writes the last slot.
|
| 624 |
+
"""
|
| 625 |
+
if sampling.top_k < 1:
|
| 626 |
+
raise InvalidInputError(f"top_k must be at least 1; got {sampling.top_k}")
|
| 627 |
+
if not (sampling.temperature >= 0 and 0 < sampling.top_p <= 1 and sampling.max_new_tokens >= 1):
|
| 628 |
+
raise InvalidInputError("invalid sampling parameters")
|
| 629 |
+
backbone, tower = model.backbone, model.audio_decoder
|
| 630 |
+
prompt_rows = len(prompt)
|
| 631 |
+
need = prompt_rows + sampling.max_new_tokens + 1
|
| 632 |
+
if need > capacity:
|
| 633 |
+
raise InvalidInputError(f"prompt ({prompt_rows} rows) + max_tokens ({sampling.max_new_tokens}) "
|
| 634 |
+
f"exceeds the context length {capacity}; increase it or shorten the reference")
|
| 635 |
+
dec = get_decoder(model, capacity, use_graphs)
|
| 636 |
+
if seed is not None:
|
| 637 |
+
torch.manual_seed(seed)
|
| 638 |
+
frames = torch.zeros((need, prompt.shape[1]), dtype=torch.long, device=tower.device)
|
| 639 |
+
frames[:prompt_rows] = prompt.to(tower.device)
|
| 640 |
+
positions = torch.arange(need, device=tower.device)
|
| 641 |
+
|
| 642 |
+
torch.cuda.synchronize() if tower.device.type == "cuda" else None
|
| 643 |
+
started = time.perf_counter()
|
| 644 |
+
prompt_cpu = prompt.cpu()
|
| 645 |
+
for start in range(0, prompt_rows, prefill_chunk_size):
|
| 646 |
+
end = min(start + prefill_chunk_size, prompt_rows)
|
| 647 |
+
chunk = frames[start:end]
|
| 648 |
+
embeddings = tower.embed_backbone(chunk, backbone.embed(prompt_cpu[start:end, 0]))
|
| 649 |
+
hidden = backbone(inputs_embeds=embeddings[None], input_pos=positions[start:end])
|
| 650 |
+
hidden = hidden[0].to(tower.device)
|
| 651 |
+
paired_end = min(end, prompt_rows - 1)
|
| 652 |
+
if paired_end > start:
|
| 653 |
+
tower.prefill(hidden[: paired_end - start], positions[start:paired_end], frames[start:paired_end],
|
| 654 |
+
frames[start + 1 : paired_end + 1])
|
| 655 |
+
if tower.device.type == "cuda":
|
| 656 |
+
torch.cuda.synchronize()
|
| 657 |
+
prefill_s = time.perf_counter() - started
|
| 658 |
+
|
| 659 |
+
pause = sampling.pause
|
| 660 |
+
clamp_on = pause is not None and pause.max_pause_frames > 0
|
| 661 |
+
expected = expected_frames(text)
|
| 662 |
+
end_frames = int(pause.end_ratio * expected) if clamp_on else 0
|
| 663 |
+
cap_frames = int(pause.cap_ratio * expected) if clamp_on else 0
|
| 664 |
+
dec.start(hidden[-1:], prompt_rows - 1, frames[prompt_rows - 1 : prompt_rows], sampling)
|
| 665 |
+
produced, silent, finish = 0, 0, "length"
|
| 666 |
+
started = time.perf_counter()
|
| 667 |
+
for step in range(sampling.max_new_tokens):
|
| 668 |
+
if clamp_on and step >= cap_frames:
|
| 669 |
+
logger.info(f"length guard: stopped at {step} frames (expected {expected:.1f})")
|
| 670 |
+
finish = "length_guard"
|
| 671 |
+
break
|
| 672 |
+
if clamp_on and silent >= pause.max_pause_frames and step >= end_frames:
|
| 673 |
+
finish = "pause_end" # a pause after the text is done
|
| 674 |
+
break
|
| 675 |
+
position = prompt_rows - 1 + step
|
| 676 |
+
sampled, main, silent = dec.step(position)
|
| 677 |
+
if main == model.config.eos_token_id:
|
| 678 |
+
finish = "eos"
|
| 679 |
+
break
|
| 680 |
+
frames[position + 1] = sampled[0]
|
| 681 |
+
produced += 1
|
| 682 |
+
decode_s = time.perf_counter() - started
|
| 683 |
+
if finish == "length":
|
| 684 |
+
logger.warning("max_tokens reached; audio may be incomplete")
|
| 685 |
+
out = frames[prompt_rows : prompt_rows + produced].cpu()
|
| 686 |
+
return Drama3Take(frames=out, finish_reason=finish, prefill_s=prefill_s, decode_s=decode_s)
|
torch/fish_speech/models/text2semantic/fish_omni/layers.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.types import Device
|
| 8 |
+
|
| 9 |
+
from .config import FishOmniTextConfig
|
| 10 |
+
|
| 11 |
+
GDN_CHUNK_SIZE = 64
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ZeroCenteredRMSNorm(nn.Module):
|
| 15 |
+
"""RMSNorm scaling by 1 + weight, computed in fp32."""
|
| 16 |
+
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
dim: int,
|
| 20 |
+
eps: float,
|
| 21 |
+
*,
|
| 22 |
+
dtype: torch.dtype | None = None,
|
| 23 |
+
device: Device = None,
|
| 24 |
+
) -> None:
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.eps = eps
|
| 27 |
+
self.weight = nn.Parameter(torch.zeros(dim, dtype=dtype, device=device))
|
| 28 |
+
|
| 29 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 30 |
+
out = x.float()
|
| 31 |
+
out = out * torch.rsqrt(out.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 32 |
+
return (out * (1.0 + self.weight.float())).type_as(x)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class GatedRMSNorm(nn.Module):
|
| 36 |
+
"""Gated DeltaNet output norm: weight * rmsnorm(x) * silu(gate)."""
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
dim: int,
|
| 41 |
+
eps: float,
|
| 42 |
+
*,
|
| 43 |
+
dtype: torch.dtype | None = None,
|
| 44 |
+
device: Device = None,
|
| 45 |
+
) -> None:
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.eps = eps
|
| 48 |
+
self.weight = nn.Parameter(torch.ones(dim, dtype=dtype, device=device))
|
| 49 |
+
|
| 50 |
+
def forward(self, x: Tensor, gate: Tensor) -> Tensor:
|
| 51 |
+
dtype = x.dtype
|
| 52 |
+
out = x.float()
|
| 53 |
+
out = out * torch.rsqrt(out.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 54 |
+
out = self.weight * out.to(dtype)
|
| 55 |
+
return (out * F.silu(gate.float())).to(dtype)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def apply_neox_rope(x: Tensor, cos: Tensor, sin: Tensor) -> Tensor:
|
| 59 |
+
"""Rotate the first rotary_dim channels of x [B, T, heads, head_dim] (half-split)."""
|
| 60 |
+
rotary_dim = cos.shape[-1]
|
| 61 |
+
rotary, passthrough = x[..., :rotary_dim].float(), x[..., rotary_dim:]
|
| 62 |
+
first, second = rotary.chunk(2, dim=-1)
|
| 63 |
+
rotated = torch.cat((-second, first), dim=-1)
|
| 64 |
+
cos, sin = cos[None, :, None, :], sin[None, :, None, :]
|
| 65 |
+
out = rotary * cos + rotated * sin
|
| 66 |
+
return torch.cat((out.to(x.dtype), passthrough), dim=-1)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def grouped_attention(
|
| 70 |
+
query: Tensor,
|
| 71 |
+
key: Tensor,
|
| 72 |
+
value: Tensor,
|
| 73 |
+
mask: Tensor | None,
|
| 74 |
+
*,
|
| 75 |
+
is_causal: bool = False,
|
| 76 |
+
scale: float | None = None,
|
| 77 |
+
) -> Tensor:
|
| 78 |
+
"""GQA SDPA: query [B, H, T, D], key / value [B, KVH, S, D], mask [T, S]."""
|
| 79 |
+
batch, heads, length, head_dim = query.shape
|
| 80 |
+
kv_heads = key.shape[1]
|
| 81 |
+
groups = heads // kv_heads
|
| 82 |
+
if groups > 1 and length == 1:
|
| 83 |
+
# Decode: fold each KV head's query heads into rows, so the cache is read
|
| 84 |
+
# once; the [1, S] mask broadcasts over them.
|
| 85 |
+
folded = query.reshape(batch, kv_heads, groups, head_dim)
|
| 86 |
+
out = F.scaled_dot_product_attention(
|
| 87 |
+
folded, key, value, attn_mask=mask, scale=scale
|
| 88 |
+
)
|
| 89 |
+
return out.reshape(batch, heads, 1, head_dim)
|
| 90 |
+
if groups > 1:
|
| 91 |
+
key = key.repeat_interleave(groups, dim=1)
|
| 92 |
+
value = value.repeat_interleave(groups, dim=1)
|
| 93 |
+
return F.scaled_dot_product_attention(
|
| 94 |
+
query, key, value, attn_mask=mask, is_causal=is_causal, scale=scale
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@dataclass(kw_only=True)
|
| 99 |
+
class LayerContext:
|
| 100 |
+
"""Per-forward inputs shared by the layers of one device."""
|
| 101 |
+
|
| 102 |
+
input_pos: Tensor # [T] contiguous positions of the rows
|
| 103 |
+
cos: Tensor
|
| 104 |
+
sin: Tensor
|
| 105 |
+
kv_len: int # attended cache prefix (last position + 1)
|
| 106 |
+
continue_state: bool # the rows continue a cached sequence
|
| 107 |
+
use_cache: bool
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class FullAttention(nn.Module):
|
| 111 |
+
"""Gated softmax attention: GQA, q/k norm, partial RoPE, sigmoid output gate."""
|
| 112 |
+
|
| 113 |
+
def __init__(
|
| 114 |
+
self,
|
| 115 |
+
config: FishOmniTextConfig,
|
| 116 |
+
*,
|
| 117 |
+
dtype: torch.dtype | None = None,
|
| 118 |
+
device: Device = None,
|
| 119 |
+
) -> None:
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.num_heads = config.num_attention_heads
|
| 122 |
+
self.num_kv_heads = config.num_key_value_heads
|
| 123 |
+
self.head_dim = config.head_dim
|
| 124 |
+
hidden = config.hidden_size
|
| 125 |
+
linear = dict(bias=False, dtype=dtype, device=device)
|
| 126 |
+
# Output rows: each head's [query, gate] pair.
|
| 127 |
+
self.q_proj = nn.Linear(hidden, self.num_heads * self.head_dim * 2, **linear)
|
| 128 |
+
self.k_proj = nn.Linear(hidden, self.num_kv_heads * self.head_dim, **linear)
|
| 129 |
+
self.v_proj = nn.Linear(hidden, self.num_kv_heads * self.head_dim, **linear)
|
| 130 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, hidden, **linear)
|
| 131 |
+
norm = dict(dtype=dtype, device=device)
|
| 132 |
+
self.q_norm = ZeroCenteredRMSNorm(self.head_dim, config.rms_norm_eps, **norm)
|
| 133 |
+
self.k_norm = ZeroCenteredRMSNorm(self.head_dim, config.rms_norm_eps, **norm)
|
| 134 |
+
self.k_cache: Tensor | None = None
|
| 135 |
+
self.v_cache: Tensor | None = None
|
| 136 |
+
|
| 137 |
+
def allocate_cache(
|
| 138 |
+
self, batch_size: int, max_seq_len: int, dtype: torch.dtype, device: Device
|
| 139 |
+
) -> None:
|
| 140 |
+
shape = (batch_size, self.num_kv_heads, max_seq_len, self.head_dim)
|
| 141 |
+
self.k_cache = torch.zeros(shape, dtype=dtype, device=device)
|
| 142 |
+
self.v_cache = torch.zeros(shape, dtype=dtype, device=device)
|
| 143 |
+
|
| 144 |
+
def forward(self, x: Tensor, context: LayerContext) -> Tensor:
|
| 145 |
+
batch, length, _ = x.shape
|
| 146 |
+
query, gate = (
|
| 147 |
+
self.q_proj(x)
|
| 148 |
+
.view(batch, length, self.num_heads, 2 * self.head_dim)
|
| 149 |
+
.chunk(2, dim=-1)
|
| 150 |
+
)
|
| 151 |
+
gate = gate.reshape(batch, length, self.num_heads * self.head_dim)
|
| 152 |
+
query = self.q_norm(query)
|
| 153 |
+
key = self.k_proj(x).view(batch, length, self.num_kv_heads, self.head_dim)
|
| 154 |
+
key = self.k_norm(key)
|
| 155 |
+
value = self.v_proj(x).view(batch, length, self.num_kv_heads, self.head_dim)
|
| 156 |
+
query = apply_neox_rope(query, context.cos, context.sin).transpose(1, 2)
|
| 157 |
+
key = apply_neox_rope(key, context.cos, context.sin).transpose(1, 2)
|
| 158 |
+
value = value.transpose(1, 2)
|
| 159 |
+
|
| 160 |
+
if context.use_cache:
|
| 161 |
+
assert self.k_cache is not None and self.v_cache is not None
|
| 162 |
+
self.k_cache[:batch].index_copy_(2, context.input_pos, key)
|
| 163 |
+
self.v_cache[:batch].index_copy_(2, context.input_pos, value)
|
| 164 |
+
key = self.k_cache[:batch, :, : context.kv_len]
|
| 165 |
+
value = self.v_cache[:batch, :, : context.kv_len]
|
| 166 |
+
key_positions = torch.arange(context.kv_len, device=x.device)
|
| 167 |
+
mask = key_positions[None, :] <= context.input_pos[:, None]
|
| 168 |
+
is_causal = False
|
| 169 |
+
else:
|
| 170 |
+
mask = None
|
| 171 |
+
is_causal = length > 1
|
| 172 |
+
|
| 173 |
+
attended = grouped_attention(
|
| 174 |
+
query, key, value, mask, is_causal=is_causal, scale=self.head_dim**-0.5
|
| 175 |
+
)
|
| 176 |
+
attended = attended.transpose(1, 2).reshape(
|
| 177 |
+
batch, length, self.num_heads * self.head_dim
|
| 178 |
+
)
|
| 179 |
+
return self.o_proj(attended * torch.sigmoid(gate))
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def l2norm(x: Tensor, eps: float = 1e-6) -> Tensor:
|
| 183 |
+
return x * torch.rsqrt((x * x).sum(dim=-1, keepdim=True) + eps)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def chunk_gated_delta_rule(
|
| 187 |
+
query: Tensor,
|
| 188 |
+
key: Tensor,
|
| 189 |
+
value: Tensor,
|
| 190 |
+
decay: Tensor,
|
| 191 |
+
beta: Tensor,
|
| 192 |
+
initial_state: Tensor | None = None,
|
| 193 |
+
chunk_size: int = GDN_CHUNK_SIZE,
|
| 194 |
+
) -> tuple[Tensor, Tensor]:
|
| 195 |
+
"""Gated delta rule over whole chunks, in fp32.
|
| 196 |
+
|
| 197 |
+
query / key [B, T, H, dk] (not yet l2-normalized), value [B, T, H, dv], decay
|
| 198 |
+
(log space, <= 0) and beta [B, T, H], initial_state [B, H, dk, dv]. Returns the
|
| 199 |
+
output [B, T, H, dv] in the query dtype and the final fp32 state.
|
| 200 |
+
"""
|
| 201 |
+
output_dtype = query.dtype
|
| 202 |
+
batch, length, heads, key_dim = key.shape
|
| 203 |
+
value_dim = value.shape[-1]
|
| 204 |
+
query, key, value, beta, decay = (
|
| 205 |
+
t.transpose(1, 2).to(torch.float32).contiguous()
|
| 206 |
+
for t in (query, key, value, beta, decay)
|
| 207 |
+
)
|
| 208 |
+
query = l2norm(query) * key_dim**-0.5
|
| 209 |
+
key = l2norm(key)
|
| 210 |
+
|
| 211 |
+
pad = (chunk_size - length % chunk_size) % chunk_size
|
| 212 |
+
query, key, value = (F.pad(t, (0, 0, 0, pad)) for t in (query, key, value))
|
| 213 |
+
beta, decay = (F.pad(t, (0, pad)) for t in (beta, decay))
|
| 214 |
+
chunk_count = (length + pad) // chunk_size
|
| 215 |
+
|
| 216 |
+
value_beta = value * beta.unsqueeze(-1)
|
| 217 |
+
key_beta = key * beta.unsqueeze(-1)
|
| 218 |
+
query, key, key_beta, value_beta = (
|
| 219 |
+
t.reshape(batch, heads, chunk_count, chunk_size, t.shape[-1])
|
| 220 |
+
for t in (query, key, key_beta, value_beta)
|
| 221 |
+
)
|
| 222 |
+
decay = decay.reshape(batch, heads, chunk_count, chunk_size)
|
| 223 |
+
upper = torch.ones(
|
| 224 |
+
chunk_size, chunk_size, dtype=torch.bool, device=query.device
|
| 225 |
+
).triu(1)
|
| 226 |
+
cumulative = decay.cumsum(dim=-1)
|
| 227 |
+
pairwise = (
|
| 228 |
+
(cumulative.unsqueeze(-1) - cumulative.unsqueeze(-2))
|
| 229 |
+
.masked_fill(upper, float("-inf"))
|
| 230 |
+
.exp()
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
system = (key_beta @ key.transpose(-1, -2)) * pairwise
|
| 234 |
+
intra = (query @ key.transpose(-1, -2)) * pairwise
|
| 235 |
+
decayed_key_beta = key_beta * cumulative.exp().unsqueeze(-1)
|
| 236 |
+
new_values = torch.linalg.solve_triangular(
|
| 237 |
+
system, value_beta, upper=False, unitriangular=True
|
| 238 |
+
)
|
| 239 |
+
key_cumulative_decay = torch.linalg.solve_triangular(
|
| 240 |
+
system, decayed_key_beta, upper=False, unitriangular=True
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
if initial_state is None:
|
| 244 |
+
state = query.new_zeros(batch, heads, key_dim, value_dim)
|
| 245 |
+
else:
|
| 246 |
+
state = initial_state.to(torch.float32)
|
| 247 |
+
output = torch.empty_like(new_values)
|
| 248 |
+
query = query * cumulative.exp().unsqueeze(-1)
|
| 249 |
+
key = key * (cumulative[..., -1:] - cumulative).exp().unsqueeze(-1)
|
| 250 |
+
chunk_decay = cumulative[..., -1].exp()[..., None, None]
|
| 251 |
+
for index in range(chunk_count):
|
| 252 |
+
corrected = new_values[:, :, index] - key_cumulative_decay[:, :, index] @ state
|
| 253 |
+
output[:, :, index] = (
|
| 254 |
+
query[:, :, index] @ state + intra[:, :, index] @ corrected
|
| 255 |
+
)
|
| 256 |
+
state = (
|
| 257 |
+
state * chunk_decay[:, :, index]
|
| 258 |
+
+ key[:, :, index].transpose(-1, -2) @ corrected
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
output = output.reshape(batch, heads, -1, value_dim)[:, :, :length]
|
| 262 |
+
return output.transpose(1, 2).contiguous().to(output_dtype), state
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def recurrent_gated_delta_rule(
|
| 266 |
+
query: Tensor,
|
| 267 |
+
key: Tensor,
|
| 268 |
+
value: Tensor,
|
| 269 |
+
decay: Tensor,
|
| 270 |
+
beta: Tensor,
|
| 271 |
+
initial_state: Tensor | None = None,
|
| 272 |
+
) -> tuple[Tensor, Tensor]:
|
| 273 |
+
"""Token-by-token gated delta rule; same contract as chunk_gated_delta_rule."""
|
| 274 |
+
output_dtype = query.dtype
|
| 275 |
+
batch, length, heads, key_dim = key.shape
|
| 276 |
+
value_dim = value.shape[-1]
|
| 277 |
+
query, key, value, beta, decay = (
|
| 278 |
+
t.transpose(1, 2).to(torch.float32).contiguous()
|
| 279 |
+
for t in (query, key, value, beta, decay)
|
| 280 |
+
)
|
| 281 |
+
query = l2norm(query) * key_dim**-0.5
|
| 282 |
+
key = l2norm(key)
|
| 283 |
+
if initial_state is None:
|
| 284 |
+
state = value.new_zeros(batch, heads, key_dim, value_dim)
|
| 285 |
+
else:
|
| 286 |
+
state = initial_state.to(torch.float32)
|
| 287 |
+
output = torch.empty_like(value)
|
| 288 |
+
for index in range(length):
|
| 289 |
+
state = state * decay[:, :, index].exp()[..., None, None]
|
| 290 |
+
k_t = key[:, :, index]
|
| 291 |
+
remembered = (state * k_t.unsqueeze(-1)).sum(dim=-2)
|
| 292 |
+
delta = (value[:, :, index] - remembered) * beta[:, :, index].unsqueeze(-1)
|
| 293 |
+
state = state + k_t.unsqueeze(-1) * delta.unsqueeze(-2)
|
| 294 |
+
output[:, :, index] = (state * query[:, :, index].unsqueeze(-1)).sum(dim=-2)
|
| 295 |
+
return output.transpose(1, 2).contiguous().to(output_dtype), state
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class GatedDeltaNet(nn.Module):
|
| 299 |
+
def __init__(
|
| 300 |
+
self,
|
| 301 |
+
config: FishOmniTextConfig,
|
| 302 |
+
*,
|
| 303 |
+
dtype: torch.dtype | None = None,
|
| 304 |
+
device: Device = None,
|
| 305 |
+
) -> None:
|
| 306 |
+
super().__init__()
|
| 307 |
+
hidden = config.hidden_size
|
| 308 |
+
self.num_k_heads = config.linear_num_key_heads
|
| 309 |
+
self.num_v_heads = config.linear_num_value_heads
|
| 310 |
+
self.head_k_dim = config.linear_key_head_dim
|
| 311 |
+
self.head_v_dim = config.linear_value_head_dim
|
| 312 |
+
self.key_dim = self.num_k_heads * self.head_k_dim
|
| 313 |
+
self.value_dim = self.num_v_heads * self.head_v_dim
|
| 314 |
+
self.conv_dim = 2 * self.key_dim + self.value_dim
|
| 315 |
+
self.conv_kernel_size = config.linear_conv_kernel_dim
|
| 316 |
+
linear = dict(bias=False, dtype=dtype, device=device)
|
| 317 |
+
# Output rows: query, key, value.
|
| 318 |
+
self.in_proj_qkv = nn.Linear(hidden, self.conv_dim, **linear)
|
| 319 |
+
self.in_proj_z = nn.Linear(hidden, self.value_dim, **linear)
|
| 320 |
+
self.in_proj_b = nn.Linear(hidden, self.num_v_heads, **linear)
|
| 321 |
+
self.in_proj_a = nn.Linear(hidden, self.num_v_heads, **linear)
|
| 322 |
+
self.conv1d = nn.Conv1d(
|
| 323 |
+
self.conv_dim,
|
| 324 |
+
self.conv_dim,
|
| 325 |
+
kernel_size=self.conv_kernel_size,
|
| 326 |
+
groups=self.conv_dim,
|
| 327 |
+
bias=False,
|
| 328 |
+
dtype=dtype,
|
| 329 |
+
device=device,
|
| 330 |
+
)
|
| 331 |
+
self.dt_bias = nn.Parameter(
|
| 332 |
+
torch.ones(self.num_v_heads, dtype=dtype, device=device)
|
| 333 |
+
)
|
| 334 |
+
self.A_log = nn.Parameter(
|
| 335 |
+
torch.zeros(self.num_v_heads, dtype=dtype, device=device)
|
| 336 |
+
)
|
| 337 |
+
self.norm = GatedRMSNorm(
|
| 338 |
+
self.head_v_dim, config.rms_norm_eps, dtype=dtype, device=device
|
| 339 |
+
)
|
| 340 |
+
self.out_proj = nn.Linear(self.value_dim, hidden, **linear)
|
| 341 |
+
self.conv_state: Tensor | None = None
|
| 342 |
+
self.recurrent_state: Tensor | None = None
|
| 343 |
+
|
| 344 |
+
def allocate_cache(
|
| 345 |
+
self, batch_size: int, dtype: torch.dtype, device: Device
|
| 346 |
+
) -> None:
|
| 347 |
+
self.conv_state = torch.zeros(
|
| 348 |
+
batch_size,
|
| 349 |
+
self.conv_dim,
|
| 350 |
+
self.conv_kernel_size - 1,
|
| 351 |
+
dtype=dtype,
|
| 352 |
+
device=device,
|
| 353 |
+
)
|
| 354 |
+
self.recurrent_state = torch.zeros(
|
| 355 |
+
batch_size,
|
| 356 |
+
self.num_v_heads,
|
| 357 |
+
self.head_k_dim,
|
| 358 |
+
self.head_v_dim,
|
| 359 |
+
dtype=torch.float32,
|
| 360 |
+
device=device,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
def forward(self, x: Tensor, context: LayerContext) -> Tensor:
|
| 364 |
+
batch, length, _ = x.shape
|
| 365 |
+
mixed = self.in_proj_qkv(x).transpose(1, 2) # [B, C, T]
|
| 366 |
+
history = self.conv_kernel_size - 1
|
| 367 |
+
if context.continue_state:
|
| 368 |
+
assert self.conv_state is not None
|
| 369 |
+
previous = self.conv_state[:batch].to(mixed.dtype)
|
| 370 |
+
else:
|
| 371 |
+
previous = mixed.new_zeros(batch, self.conv_dim, history)
|
| 372 |
+
padded = torch.cat((previous, mixed), dim=-1)
|
| 373 |
+
if context.use_cache:
|
| 374 |
+
assert self.conv_state is not None
|
| 375 |
+
self.conv_state[:batch].copy_(padded[..., -history:])
|
| 376 |
+
mixed = F.silu(F.conv1d(padded, self.conv1d.weight, groups=self.conv_dim))
|
| 377 |
+
query, key, value = mixed.transpose(1, 2).split(
|
| 378 |
+
[self.key_dim, self.key_dim, self.value_dim], dim=-1
|
| 379 |
+
)
|
| 380 |
+
query = query.reshape(batch, length, self.num_k_heads, self.head_k_dim)
|
| 381 |
+
key = key.reshape(batch, length, self.num_k_heads, self.head_k_dim)
|
| 382 |
+
value = value.reshape(batch, length, self.num_v_heads, self.head_v_dim)
|
| 383 |
+
z = self.in_proj_z(x).reshape(batch, length, self.num_v_heads, self.head_v_dim)
|
| 384 |
+
beta = torch.sigmoid(self.in_proj_b(x).float())
|
| 385 |
+
decay = -self.A_log.float().exp() * F.softplus(
|
| 386 |
+
self.in_proj_a(x).float() + self.dt_bias.float()
|
| 387 |
+
)
|
| 388 |
+
groups = self.num_v_heads // self.num_k_heads
|
| 389 |
+
if groups > 1:
|
| 390 |
+
query = query.repeat_interleave(groups, dim=2)
|
| 391 |
+
key = key.repeat_interleave(groups, dim=2)
|
| 392 |
+
|
| 393 |
+
initial_state = None
|
| 394 |
+
if context.continue_state:
|
| 395 |
+
assert self.recurrent_state is not None
|
| 396 |
+
initial_state = self.recurrent_state[:batch]
|
| 397 |
+
rule = (
|
| 398 |
+
recurrent_gated_delta_rule
|
| 399 |
+
if context.continue_state and length == 1
|
| 400 |
+
else chunk_gated_delta_rule
|
| 401 |
+
)
|
| 402 |
+
core, final_state = rule(query, key, value, decay, beta, initial_state)
|
| 403 |
+
if context.use_cache:
|
| 404 |
+
assert self.recurrent_state is not None
|
| 405 |
+
self.recurrent_state[:batch].copy_(final_state)
|
| 406 |
+
|
| 407 |
+
core = self.norm(
|
| 408 |
+
core.reshape(-1, self.head_v_dim), z.reshape(-1, self.head_v_dim)
|
| 409 |
+
).reshape(batch, length, self.value_dim)
|
| 410 |
+
return self.out_proj(core)
|
torch/fish_speech/models/text2semantic/fish_omni/moe.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified for the drama3-expressive-medium PyTorch port (GGUF runtime): the routed experts are
|
| 2 |
+
# packed GGUF banks (IQ4_XS / Q5_K) kept on the GPU and dequantized on the fly; FP8 / dense-expert
|
| 3 |
+
# code paths removed; router and shared-expert gate computed in fp32.
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch.types import Device
|
| 9 |
+
|
| 10 |
+
from .config import FishOmniTextConfig
|
| 11 |
+
|
| 12 |
+
# Up to this many (token, expert) pairs run the fused dequant-GEMV kernels (decode, CUDA-graph
|
| 13 |
+
# safe); larger batches dequantize the experts they hit, EXPERT_GROUP at a time (prefill).
|
| 14 |
+
GEMV_MAX_PAIRS = 64
|
| 15 |
+
EXPERT_GROUP = 16
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class DenseMLP(nn.Module):
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
hidden: int,
|
| 22 |
+
intermediate: int,
|
| 23 |
+
*,
|
| 24 |
+
dtype: torch.dtype | None = None,
|
| 25 |
+
device: Device = None,
|
| 26 |
+
) -> None:
|
| 27 |
+
super().__init__()
|
| 28 |
+
linear = dict(bias=False, dtype=dtype, device=device)
|
| 29 |
+
self.gate_proj = nn.Linear(hidden, intermediate, **linear)
|
| 30 |
+
self.up_proj = nn.Linear(hidden, intermediate, **linear)
|
| 31 |
+
self.down_proj = nn.Linear(intermediate, hidden, **linear)
|
| 32 |
+
|
| 33 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 34 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class PackedExperts(nn.Module):
|
| 38 |
+
"""Routed experts as GGUF banks in ggml row layout.
|
| 39 |
+
|
| 40 |
+
gate / up: uint8 [E, I, row_bytes(H)], down: uint8 [E, H, row_bytes(I)]; `qtypes` holds the
|
| 41 |
+
ggml type of each projection. Banks are buffers set by the GGUF loader (`set_banks`).
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, num_experts: int, hidden: int, intermediate: int) -> None:
|
| 45 |
+
super().__init__()
|
| 46 |
+
self.num_experts = num_experts
|
| 47 |
+
self.hidden = hidden
|
| 48 |
+
self.intermediate = intermediate
|
| 49 |
+
self.qtypes: dict[str, int] = {}
|
| 50 |
+
for proj in ("gate", "up", "down"):
|
| 51 |
+
self.register_buffer(proj, None, persistent=False)
|
| 52 |
+
|
| 53 |
+
def set_banks(self, banks: dict[str, tuple[Tensor, int]]) -> None:
|
| 54 |
+
for proj, (data, qtype) in banks.items():
|
| 55 |
+
self.register_buffer(proj, data, persistent=False)
|
| 56 |
+
self.qtypes[proj] = qtype
|
| 57 |
+
|
| 58 |
+
def forward(self, x: Tensor, topk_ids: Tensor, topk_weights: Tensor) -> Tensor:
|
| 59 |
+
"""x [N, H], topk_ids / topk_weights [N, k] -> weighted expert sum [N, H] (x.dtype)."""
|
| 60 |
+
if x.is_cuda and topk_ids.numel() <= GEMV_MAX_PAIRS:
|
| 61 |
+
return self.forward_gemv(x, topk_ids, topk_weights)
|
| 62 |
+
return self.forward_grouped(x, topk_ids, topk_weights)
|
| 63 |
+
|
| 64 |
+
def forward_gemv(self, x: Tensor, topk_ids: Tensor, topk_weights: Tensor) -> Tensor:
|
| 65 |
+
"""Fused dequantize + GEMV per (token, expert) pair; no host sync."""
|
| 66 |
+
from gguf_kernels import moe_gemv
|
| 67 |
+
|
| 68 |
+
tokens, top_k = topk_ids.shape
|
| 69 |
+
ids = topk_ids.reshape(-1).to(torch.int32)
|
| 70 |
+
qg, qu, qd = self.qtypes["gate"], self.qtypes["up"], self.qtypes["down"]
|
| 71 |
+
if qg == qu:
|
| 72 |
+
h = moe_gemv(x, ids, top_k, self.gate, self.up, qg)
|
| 73 |
+
else:
|
| 74 |
+
g = moe_gemv(x, ids, top_k, self.gate, None, qg)
|
| 75 |
+
h = F.silu(g) * moe_gemv(x, ids, top_k, self.up, None, qu)
|
| 76 |
+
y = moe_gemv(h, ids, top_k, self.down, None, qd, x_per_pair=True)
|
| 77 |
+
out = (y.view(tokens, top_k, self.hidden) * topk_weights.float()[..., None]).sum(dim=1)
|
| 78 |
+
return out.to(x.dtype)
|
| 79 |
+
|
| 80 |
+
def dense(self, ids: Tensor, dtype: torch.dtype) -> tuple[Tensor, Tensor, Tensor]:
|
| 81 |
+
from gguf_kernels import dequantize_experts
|
| 82 |
+
|
| 83 |
+
return (
|
| 84 |
+
dequantize_experts(self.gate, self.qtypes["gate"], ids, self.hidden, dtype),
|
| 85 |
+
dequantize_experts(self.up, self.qtypes["up"], ids, self.hidden, dtype),
|
| 86 |
+
dequantize_experts(self.down, self.qtypes["down"], ids, self.intermediate, dtype),
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
def forward_grouped(self, x: Tensor, topk_ids: Tensor, topk_weights: Tensor) -> Tensor:
|
| 90 |
+
"""Experts ordered by token count, EXPERT_GROUP at a time: dequantize the group, then one
|
| 91 |
+
padded batched matmul per projection (each group padded to its own busiest expert)."""
|
| 92 |
+
tokens, top_k = topk_ids.shape
|
| 93 |
+
flat_ids = topk_ids.reshape(-1)
|
| 94 |
+
order = torch.argsort(flat_ids, stable=True)
|
| 95 |
+
e_sorted = flat_ids[order]
|
| 96 |
+
counts = torch.bincount(flat_ids, minlength=self.num_experts)
|
| 97 |
+
starts = torch.cumsum(counts, 0) - counts
|
| 98 |
+
pos = torch.arange(len(order), device=x.device) - starts[e_sorted]
|
| 99 |
+
token = order // top_k
|
| 100 |
+
pair_w = topk_weights.reshape(-1)[order].float()
|
| 101 |
+
by_count = torch.argsort(counts, descending=True)
|
| 102 |
+
n_used = int((counts > 0).sum())
|
| 103 |
+
by_count = by_count[:n_used]
|
| 104 |
+
caps = counts[by_count].tolist()
|
| 105 |
+
slot = torch.full((self.num_experts,), -1, dtype=torch.long, device=x.device)
|
| 106 |
+
# Weighted output of every (token, expert) pair at its pair index; summed over the k slots in a
|
| 107 |
+
# fixed order afterwards (index_add_'s float atomics would make prefill non-deterministic).
|
| 108 |
+
out = torch.zeros(tokens * top_k, self.hidden, dtype=torch.float32, device=x.device)
|
| 109 |
+
for c in range(0, n_used, EXPERT_GROUP):
|
| 110 |
+
sel = by_count[c : c + EXPERT_GROUP]
|
| 111 |
+
g, u, d = self.dense(sel.to(torch.int32), x.dtype)
|
| 112 |
+
slot[sel] = torch.arange(len(sel), device=x.device)
|
| 113 |
+
pairs = torch.nonzero(slot[e_sorted] >= 0).squeeze(1)
|
| 114 |
+
s, p = slot[e_sorted[pairs]], pos[pairs]
|
| 115 |
+
buf = x.new_zeros(len(sel), caps[c], self.hidden).index_put((s, p), x[token[pairs]])
|
| 116 |
+
h = F.silu(torch.bmm(buf, g.transpose(1, 2))) * torch.bmm(buf, u.transpose(1, 2))
|
| 117 |
+
y = torch.bmm(h, d.transpose(1, 2))[s, p]
|
| 118 |
+
out[order[pairs]] = y.float() * pair_w[pairs, None]
|
| 119 |
+
slot[sel] = -1
|
| 120 |
+
del g, u, d, buf, h, y
|
| 121 |
+
return out.view(tokens, top_k, self.hidden).sum(dim=1).to(x.dtype)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class SparseMoeBlock(nn.Module):
|
| 125 |
+
"""Top-k routed experts plus a sigmoid-gated shared expert."""
|
| 126 |
+
|
| 127 |
+
def __init__(
|
| 128 |
+
self,
|
| 129 |
+
config: FishOmniTextConfig,
|
| 130 |
+
*,
|
| 131 |
+
dtype: torch.dtype | None = None,
|
| 132 |
+
device: Device = None,
|
| 133 |
+
) -> None:
|
| 134 |
+
super().__init__()
|
| 135 |
+
hidden = config.hidden_size
|
| 136 |
+
self.top_k = config.num_experts_per_tok
|
| 137 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 138 |
+
# Router and shared-expert gate stay fp32 (GGUF stores them as F16).
|
| 139 |
+
self.gate = nn.Linear(hidden, config.num_experts, bias=False, dtype=torch.float32, device=device)
|
| 140 |
+
self.experts = PackedExperts(config.num_experts, hidden, config.moe_intermediate_size)
|
| 141 |
+
self.shared_expert = DenseMLP(
|
| 142 |
+
hidden, config.shared_expert_intermediate_size, dtype=dtype, device=device
|
| 143 |
+
)
|
| 144 |
+
self.shared_expert_gate = nn.Linear(hidden, 1, bias=False, dtype=torch.float32, device=device)
|
| 145 |
+
|
| 146 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 147 |
+
flat = x.reshape(-1, x.shape[-1])
|
| 148 |
+
probabilities = torch.softmax(self.gate(flat.float()), dim=-1)
|
| 149 |
+
topk_weights, topk_ids = probabilities.topk(self.top_k, dim=-1)
|
| 150 |
+
if self.norm_topk_prob:
|
| 151 |
+
topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
|
| 152 |
+
out = self.experts(flat, topk_ids, topk_weights)
|
| 153 |
+
shared_gate = torch.sigmoid(self.shared_expert_gate(flat.float()))
|
| 154 |
+
shared = self.shared_expert(flat).float()
|
| 155 |
+
return (out.float() + shared_gate * shared).to(x.dtype).view_as(x)
|
torch/fish_speech/models/text2semantic/fish_omni/tower.py
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified for the drama3-expressive-medium PyTorch port (GGUF runtime): imports, stdlib logging,
|
| 2 |
+
# and decode_step accepts speech-only head logits ([EOS, semantic 0..N-1]).
|
| 3 |
+
import logging
|
| 4 |
+
import math
|
| 5 |
+
from collections.abc import Iterable
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
from torch import Tensor
|
| 11 |
+
from torch.types import Device
|
| 12 |
+
|
| 13 |
+
from .config import AudioDecoderConfig, FishOmniConfig
|
| 14 |
+
from .layers import ZeroCenteredRMSNorm, grouped_attention
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
# Repetition-aware sampling of the main token, fixed by the training recipe: when
|
| 19 |
+
# the first draw repeats one of the last RAS_WINDOW_FRAMES main tokens, a second
|
| 20 |
+
# draw with these parameters is used instead.
|
| 21 |
+
RAS_WINDOW_FRAMES = 16
|
| 22 |
+
RAS_TEMPERATURE = 1.0
|
| 23 |
+
RAS_TOP_K = 30
|
| 24 |
+
RAS_TOP_P = 0.95
|
| 25 |
+
MIN_TEMPERATURE = 1e-5
|
| 26 |
+
TOWER_CHECKPOINT_PREFIXES = {
|
| 27 |
+
"audio_decoder.codebook_embeddings.": "codebook_embeddings.",
|
| 28 |
+
"audio_decoder_mtp_shared.layers.": "shared_layers.",
|
| 29 |
+
"audio_decoder_mtp.layers.": "residual_layers.",
|
| 30 |
+
"audio_decoder_mtp.heads.": "codebook_heads.",
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def sample_top_k_top_p(
|
| 35 |
+
logits: Tensor,
|
| 36 |
+
temperature: float | Tensor,
|
| 37 |
+
top_k: int | Tensor,
|
| 38 |
+
top_p: float | Tensor,
|
| 39 |
+
*,
|
| 40 |
+
check_finite: bool = True,
|
| 41 |
+
) -> Tensor:
|
| 42 |
+
"""One id per row; drops the token crossing top_p, except the highest-ranked one.
|
| 43 |
+
|
| 44 |
+
Sampling parameters may be 0-dim device tensors (CUDA graphs); check_finite
|
| 45 |
+
syncs with the host.
|
| 46 |
+
"""
|
| 47 |
+
if isinstance(temperature, Tensor):
|
| 48 |
+
temperature = temperature.clamp(min=MIN_TEMPERATURE)
|
| 49 |
+
else:
|
| 50 |
+
temperature = max(temperature, MIN_TEMPERATURE)
|
| 51 |
+
if check_finite and not torch.isfinite(logits).all():
|
| 52 |
+
raise FloatingPointError("non-finite logits; refusing to sample invalid audio")
|
| 53 |
+
values, ids = torch.sort(logits.float() / temperature, descending=True, dim=-1)
|
| 54 |
+
ranks = torch.arange(values.shape[-1], device=values.device)
|
| 55 |
+
dropped = (values.softmax(-1).cumsum(-1) > top_p) | (ranks >= top_k)
|
| 56 |
+
dropped[..., 0] = False
|
| 57 |
+
probabilities = values.masked_fill(dropped, -torch.inf).softmax(-1)
|
| 58 |
+
noise = torch.empty_like(probabilities).exponential_()
|
| 59 |
+
choice = (probabilities / noise).argmax(-1, keepdim=True)
|
| 60 |
+
return ids.gather(-1, choice).squeeze(-1)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class TowerAttention(nn.Module):
|
| 64 |
+
"""Gated attention over time; checkpoint wqkv rows are [Q | Gate | K | V]."""
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
config: AudioDecoderConfig,
|
| 69 |
+
*,
|
| 70 |
+
dtype: torch.dtype | None = None,
|
| 71 |
+
device: Device = None,
|
| 72 |
+
) -> None:
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.config = config
|
| 75 |
+
q_width = config.n_head * config.head_dim
|
| 76 |
+
kv_width = config.n_local_heads * config.head_dim
|
| 77 |
+
linear = dict(bias=False, dtype=dtype, device=device)
|
| 78 |
+
norm = dict(dtype=dtype, device=device)
|
| 79 |
+
self.wqkv = nn.Linear(config.dim, 2 * q_width + 2 * kv_width, **linear)
|
| 80 |
+
self.wo = nn.Linear(q_width, config.dim, **linear)
|
| 81 |
+
# Always on, whatever audio_decoder_config.attention_qk_norm says: training runs
|
| 82 |
+
# q/k norm in the audio decoder, but the exporter never writes that field, so
|
| 83 |
+
# released Drama 3 configs carry its default false. Keep the (1 + weight) scale too:
|
| 84 |
+
# exported weights are zero-centered, not pre-shifted by one.
|
| 85 |
+
self.q_norm = ZeroCenteredRMSNorm(config.head_dim, config.norm_eps, **norm)
|
| 86 |
+
self.k_norm = ZeroCenteredRMSNorm(config.head_dim, config.norm_eps, **norm)
|
| 87 |
+
self.k_cache: Tensor | None = None
|
| 88 |
+
self.v_cache: Tensor | None = None
|
| 89 |
+
# CUDA-graph decode attends this many cache rows; the mask hides the rest.
|
| 90 |
+
self.static_kv_len: int | None = None
|
| 91 |
+
|
| 92 |
+
def setup_cache(self, max_seq_len: int) -> None:
|
| 93 |
+
shape = (1, self.config.n_local_heads, max_seq_len, self.config.head_dim)
|
| 94 |
+
self.k_cache = self.wqkv.weight.new_zeros(shape)
|
| 95 |
+
self.v_cache = self.wqkv.weight.new_zeros(shape)
|
| 96 |
+
|
| 97 |
+
def rotate(self, x: Tensor, positions: Tensor) -> Tensor:
|
| 98 |
+
"""Interleaved (non-neox) partial RoPE, computed in fp32."""
|
| 99 |
+
width = self.config.rotary_dim
|
| 100 |
+
exponents = torch.arange(0, width, 2, device=x.device, dtype=torch.float32)
|
| 101 |
+
angles = positions.float()[:, None] * self.config.rope_base ** (
|
| 102 |
+
-exponents / width
|
| 103 |
+
)
|
| 104 |
+
cos, sin = angles.cos()[:, None], angles.sin()[:, None]
|
| 105 |
+
even, odd = x[..., :width:2].float(), x[..., 1:width:2].float()
|
| 106 |
+
rotated = torch.stack((even * cos - odd * sin, odd * cos + even * sin), -1)
|
| 107 |
+
return torch.cat((rotated.flatten(-2).to(x.dtype), x[..., width:]), dim=-1)
|
| 108 |
+
|
| 109 |
+
def forward(self, x: Tensor, positions: Tensor) -> Tensor:
|
| 110 |
+
cfg = self.config
|
| 111 |
+
length = len(positions)
|
| 112 |
+
q_width, kv_width = cfg.n_head * cfg.head_dim, cfg.n_local_heads * cfg.head_dim
|
| 113 |
+
q, gate, k, v = self.wqkv(x).split((q_width, q_width, kv_width, kv_width), -1)
|
| 114 |
+
q = self.q_norm(q.reshape(length, cfg.n_head, cfg.head_dim))
|
| 115 |
+
k = self.k_norm(k.reshape(length, cfg.n_local_heads, cfg.head_dim))
|
| 116 |
+
q = self.rotate(q, positions).transpose(0, 1).unsqueeze(0)
|
| 117 |
+
k = self.rotate(k, positions).transpose(0, 1).unsqueeze(0)
|
| 118 |
+
v = v.reshape(length, cfg.n_local_heads, cfg.head_dim)
|
| 119 |
+
v = v.transpose(0, 1).unsqueeze(0)
|
| 120 |
+
if self.k_cache is not None:
|
| 121 |
+
if self.static_kv_len is not None:
|
| 122 |
+
end = self.static_kv_len
|
| 123 |
+
else:
|
| 124 |
+
end = int(positions[-1]) + 1
|
| 125 |
+
assert end <= self.k_cache.shape[2], "tower cache capacity exceeded"
|
| 126 |
+
self.k_cache.index_copy_(2, positions, k)
|
| 127 |
+
self.v_cache.index_copy_(2, positions, v)
|
| 128 |
+
k, v = self.k_cache[:, :, :end], self.v_cache[:, :, :end]
|
| 129 |
+
key_positions = torch.arange(end, device=x.device)
|
| 130 |
+
else:
|
| 131 |
+
key_positions = positions
|
| 132 |
+
mask = key_positions[None, :] <= positions[:, None]
|
| 133 |
+
out = grouped_attention(q, k, v, mask)
|
| 134 |
+
out = out.squeeze(0).transpose(0, 1).reshape(length, q_width)
|
| 135 |
+
return self.wo(out * gate.sigmoid())
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class FP32OutputLinear(nn.Linear):
|
| 139 |
+
"""FP16 GEMM with FP32 output, keeping values beyond the FP16 range."""
|
| 140 |
+
|
| 141 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 142 |
+
if x.dtype != torch.float16:
|
| 143 |
+
return super().forward(x)
|
| 144 |
+
if x.is_cuda:
|
| 145 |
+
out = torch.mm(
|
| 146 |
+
x.reshape(-1, self.in_features), self.weight.T, out_dtype=torch.float32
|
| 147 |
+
)
|
| 148 |
+
out = out.reshape(*x.shape[:-1], self.out_features)
|
| 149 |
+
else:
|
| 150 |
+
out = F.linear(x.float(), self.weight.float())
|
| 151 |
+
return out if self.bias is None else out + self.bias.float()
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class TowerMLP(nn.Module):
|
| 155 |
+
def __init__(
|
| 156 |
+
self,
|
| 157 |
+
config: AudioDecoderConfig,
|
| 158 |
+
*,
|
| 159 |
+
dtype: torch.dtype | None = None,
|
| 160 |
+
device: Device = None,
|
| 161 |
+
) -> None:
|
| 162 |
+
super().__init__()
|
| 163 |
+
linear = dict(bias=False, dtype=dtype, device=device)
|
| 164 |
+
self.w1 = nn.Linear(config.dim, config.intermediate_size, **linear)
|
| 165 |
+
self.w3 = nn.Linear(config.dim, config.intermediate_size, **linear)
|
| 166 |
+
# The checkpoint's down projections exceed 65504 under FP16.
|
| 167 |
+
self.w2 = FP32OutputLinear(config.intermediate_size, config.dim, **linear)
|
| 168 |
+
|
| 169 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 170 |
+
return self.w2(F.silu(self.w1(x)) * self.w3(x))
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class TowerTransformerLayer(nn.Module):
|
| 174 |
+
def __init__(
|
| 175 |
+
self,
|
| 176 |
+
config: AudioDecoderConfig,
|
| 177 |
+
*,
|
| 178 |
+
dtype: torch.dtype | None = None,
|
| 179 |
+
device: Device = None,
|
| 180 |
+
) -> None:
|
| 181 |
+
super().__init__()
|
| 182 |
+
args = dict(dtype=dtype, device=device)
|
| 183 |
+
self.attention = TowerAttention(config, **args)
|
| 184 |
+
self.attention_norm = ZeroCenteredRMSNorm(config.dim, config.norm_eps, **args)
|
| 185 |
+
self.ffn_norm = ZeroCenteredRMSNorm(config.dim, config.norm_eps, **args)
|
| 186 |
+
self.feed_forward = TowerMLP(config, **args)
|
| 187 |
+
|
| 188 |
+
def forward(self, x: Tensor, positions: Tensor) -> Tensor:
|
| 189 |
+
dtype = self.attention.wqkv.weight.dtype
|
| 190 |
+
residual = x.float() if dtype == torch.float16 else x
|
| 191 |
+
residual = residual + self.attention(
|
| 192 |
+
self.attention_norm(residual).to(dtype), positions
|
| 193 |
+
)
|
| 194 |
+
return residual + self.feed_forward(self.ffn_norm(residual).to(dtype))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class TowerLayer(nn.Module):
|
| 198 |
+
"""Mix a code embedding into the hidden state, then one pre-norm block."""
|
| 199 |
+
|
| 200 |
+
def __init__(
|
| 201 |
+
self,
|
| 202 |
+
config: AudioDecoderConfig,
|
| 203 |
+
*,
|
| 204 |
+
shared: bool,
|
| 205 |
+
dtype: torch.dtype | None = None,
|
| 206 |
+
device: Device = None,
|
| 207 |
+
) -> None:
|
| 208 |
+
super().__init__()
|
| 209 |
+
self.shared = shared
|
| 210 |
+
args = dict(dtype=dtype, device=device)
|
| 211 |
+
# Checkpoint name of the embedding differs between shared / residual layers.
|
| 212 |
+
name = "semantic_embedding" if shared else "codebook_embedding"
|
| 213 |
+
self.add_module(name, nn.Embedding(config.vocab_size, config.dim, **args))
|
| 214 |
+
self.enorm = ZeroCenteredRMSNorm(config.dim, config.norm_eps, **args)
|
| 215 |
+
self.hnorm = ZeroCenteredRMSNorm(config.dim, config.norm_eps, **args)
|
| 216 |
+
self.eh_proj = nn.Linear(2 * config.dim, config.dim, bias=False, **args)
|
| 217 |
+
self.transformer_layer = TowerTransformerLayer(config, **args)
|
| 218 |
+
self.final_layernorm = ZeroCenteredRMSNorm(config.dim, config.norm_eps, **args)
|
| 219 |
+
|
| 220 |
+
def forward(
|
| 221 |
+
self,
|
| 222 |
+
hidden: Tensor,
|
| 223 |
+
codes: Tensor,
|
| 224 |
+
semantic: Tensor,
|
| 225 |
+
positions: Tensor,
|
| 226 |
+
shared_input: Tensor | None = None,
|
| 227 |
+
) -> Tensor:
|
| 228 |
+
embedding = self.semantic_embedding if self.shared else self.codebook_embedding
|
| 229 |
+
codes = codes.clamp(0, embedding.num_embeddings - 1)
|
| 230 |
+
e = torch.where(semantic[:, None], embedding(codes), 0.0)
|
| 231 |
+
if shared_input is not None:
|
| 232 |
+
e = e + shared_input
|
| 233 |
+
mixed = self.eh_proj(torch.cat((self.enorm(e), self.hnorm(hidden)), dim=-1))
|
| 234 |
+
out = self.final_layernorm(self.transformer_layer(mixed, positions))
|
| 235 |
+
return out.to(mixed.dtype)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class FishOmniAudioDecoder(nn.Module):
|
| 239 |
+
"""Codebook tower: predicts codes 1..N-1 of each frame, attending over time.
|
| 240 |
+
|
| 241 |
+
A frame row is [main token id, code 0, ..., code N-1]; code 0 is the main
|
| 242 |
+
token's offset in the semantic band.
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
def __init__(
|
| 246 |
+
self,
|
| 247 |
+
config: FishOmniConfig,
|
| 248 |
+
*,
|
| 249 |
+
dtype: torch.dtype = torch.float16,
|
| 250 |
+
device: Device = None,
|
| 251 |
+
) -> None:
|
| 252 |
+
super().__init__()
|
| 253 |
+
cfg = self.config = config.audio_decoder
|
| 254 |
+
self.semantic_begin = config.semantic_start_token_id
|
| 255 |
+
self.semantic_end = config.semantic_end_token_id
|
| 256 |
+
self.eos_id = config.eos_token_id
|
| 257 |
+
args = dict(dtype=dtype, device=device)
|
| 258 |
+
self.codebook_embeddings = nn.Embedding(
|
| 259 |
+
cfg.vocab_size * cfg.num_codebooks, cfg.dim, **args
|
| 260 |
+
)
|
| 261 |
+
self.shared_layers = nn.ModuleList(
|
| 262 |
+
TowerLayer(cfg, shared=True, **args)
|
| 263 |
+
for _ in range(cfg.shared_enrichment_layers)
|
| 264 |
+
)
|
| 265 |
+
self.residual_layers = nn.ModuleList(
|
| 266 |
+
TowerLayer(cfg, shared=False, **args) for _ in range(cfg.num_codebooks - 1)
|
| 267 |
+
)
|
| 268 |
+
self.codebook_heads = nn.ModuleList(
|
| 269 |
+
nn.Linear(cfg.dim, cfg.vocab_size, bias=False, **args)
|
| 270 |
+
for _ in range(cfg.num_codebooks - 1)
|
| 271 |
+
)
|
| 272 |
+
# Ids the main token is drawn from (eos + the semantic band), built lazily
|
| 273 |
+
# on the tower's device: creating it inside CUDA-graph capture is illegal.
|
| 274 |
+
self.main_candidates: Tensor | None = None
|
| 275 |
+
|
| 276 |
+
@property
|
| 277 |
+
def device(self) -> torch.device:
|
| 278 |
+
return self.codebook_embeddings.weight.device
|
| 279 |
+
|
| 280 |
+
def setup_caches(self, max_seq_len: int) -> None:
|
| 281 |
+
for layer in (*self.shared_layers, *self.residual_layers):
|
| 282 |
+
layer.transformer_layer.attention.setup_cache(max_seq_len)
|
| 283 |
+
|
| 284 |
+
def is_semantic(self, tokens: Tensor) -> Tensor:
|
| 285 |
+
return (tokens >= self.semantic_begin) & (tokens <= self.semantic_end)
|
| 286 |
+
|
| 287 |
+
def embedding_sum(self, frames: Tensor, first: int, end: int) -> Tensor:
|
| 288 |
+
"""Summed embeddings of codes first..end-1 per frame."""
|
| 289 |
+
if first == end:
|
| 290 |
+
return self.codebook_embeddings.weight.new_zeros(
|
| 291 |
+
(len(frames), self.config.dim)
|
| 292 |
+
)
|
| 293 |
+
offsets = torch.arange(first, end, device=self.device) * self.config.vocab_size
|
| 294 |
+
rows = frames[:, 1 + first : 1 + end] + offsets
|
| 295 |
+
return F.embedding_bag(rows, self.codebook_embeddings.weight, mode="sum")
|
| 296 |
+
|
| 297 |
+
def embed_backbone(self, frames: Tensor, text_embeddings: Tensor) -> Tensor:
|
| 298 |
+
"""Backbone input: semantic frames add codes 1..K to the token embedding."""
|
| 299 |
+
frames = frames.to(self.device)
|
| 300 |
+
count = self.config.vq_backbone_codebooks
|
| 301 |
+
extra = self.embedding_sum(frames, 1, 1 + count).to(text_embeddings.device)
|
| 302 |
+
mixed = (text_embeddings + extra) / math.sqrt(1 + count)
|
| 303 |
+
semantic = self.is_semantic(frames[:, 0]).to(text_embeddings.device)
|
| 304 |
+
return torch.where(semantic[:, None], mixed, text_embeddings)
|
| 305 |
+
|
| 306 |
+
def run_shared(
|
| 307 |
+
self,
|
| 308 |
+
hidden: Tensor,
|
| 309 |
+
c0: Tensor,
|
| 310 |
+
semantic: Tensor,
|
| 311 |
+
positions: Tensor,
|
| 312 |
+
frames: Tensor,
|
| 313 |
+
) -> Tensor:
|
| 314 |
+
# The first shared layer also sees the codes the backbone did not.
|
| 315 |
+
unseen = self.embedding_sum(
|
| 316 |
+
frames, 1 + self.config.vq_backbone_codebooks, self.config.num_codebooks
|
| 317 |
+
)
|
| 318 |
+
unseen = torch.where(self.is_semantic(frames[:, 0])[:, None], unseen, 0.0)
|
| 319 |
+
for index, layer in enumerate(self.shared_layers):
|
| 320 |
+
hidden = layer(
|
| 321 |
+
hidden, c0, semantic, positions, unseen if index == 0 else None
|
| 322 |
+
)
|
| 323 |
+
return hidden
|
| 324 |
+
|
| 325 |
+
def prefill(
|
| 326 |
+
self, hidden: Tensor, positions: Tensor, frames: Tensor, next_frames: Tensor
|
| 327 |
+
) -> None:
|
| 328 |
+
"""Teacher-force the tower cache; row p is labelled with frame p + 1."""
|
| 329 |
+
semantic = self.is_semantic(next_frames[:, 0])
|
| 330 |
+
hidden = self.run_shared(hidden, next_frames[:, 1], semantic, positions, frames)
|
| 331 |
+
for index, layer in enumerate(self.residual_layers):
|
| 332 |
+
hidden = layer(hidden, next_frames[:, index + 1], semantic, positions)
|
| 333 |
+
|
| 334 |
+
def decode_step(
|
| 335 |
+
self,
|
| 336 |
+
logits: Tensor,
|
| 337 |
+
hidden: Tensor,
|
| 338 |
+
positions: Tensor,
|
| 339 |
+
frames: Tensor,
|
| 340 |
+
history: Tensor,
|
| 341 |
+
*,
|
| 342 |
+
temperature: float | Tensor,
|
| 343 |
+
top_k: int | Tensor,
|
| 344 |
+
top_p: float | Tensor,
|
| 345 |
+
check_finite: bool = True,
|
| 346 |
+
) -> Tensor:
|
| 347 |
+
"""Sample the frame after each row; the main token is drawn over eos + semantics."""
|
| 348 |
+
if self.main_candidates is None or self.main_candidates.device != self.device:
|
| 349 |
+
eos = torch.tensor([self.eos_id], device=self.device)
|
| 350 |
+
band = torch.arange(
|
| 351 |
+
self.semantic_begin, self.semantic_end + 1, device=self.device
|
| 352 |
+
)
|
| 353 |
+
self.main_candidates = torch.cat((eos, band)).sort().values
|
| 354 |
+
candidates = self.main_candidates
|
| 355 |
+
# Speech-only head: the logits already are the candidates, in this order.
|
| 356 |
+
if logits.shape[-1] == len(candidates):
|
| 357 |
+
candidate_logits = logits
|
| 358 |
+
else:
|
| 359 |
+
candidate_logits = logits[:, candidates]
|
| 360 |
+
first = candidates[
|
| 361 |
+
sample_top_k_top_p(
|
| 362 |
+
candidate_logits, temperature, top_k, top_p, check_finite=check_finite
|
| 363 |
+
)
|
| 364 |
+
]
|
| 365 |
+
retry = candidates[
|
| 366 |
+
sample_top_k_top_p(
|
| 367 |
+
candidate_logits,
|
| 368 |
+
RAS_TEMPERATURE,
|
| 369 |
+
RAS_TOP_K,
|
| 370 |
+
RAS_TOP_P,
|
| 371 |
+
check_finite=False,
|
| 372 |
+
)
|
| 373 |
+
]
|
| 374 |
+
# Only audio tokens are resampled, as in S2: the window starts with prompt rows,
|
| 375 |
+
# which hold the user turn's eos, and a stop must not be redrawn.
|
| 376 |
+
repeated = (history[-RAS_WINDOW_FRAMES:] == first[:, None]).any(-1)
|
| 377 |
+
repeated &= self.is_semantic(first)
|
| 378 |
+
main = torch.where(repeated, retry, first)
|
| 379 |
+
c0 = (main - self.semantic_begin).clamp(0, self.config.vocab_size - 1)
|
| 380 |
+
semantic = self.is_semantic(main)
|
| 381 |
+
hidden = self.run_shared(hidden, c0, semantic, positions, frames)
|
| 382 |
+
codes = [c0]
|
| 383 |
+
for layer, head in zip(self.residual_layers, self.codebook_heads):
|
| 384 |
+
hidden = layer(hidden, codes[-1], semantic, positions)
|
| 385 |
+
codes.append(
|
| 386 |
+
sample_top_k_top_p(
|
| 387 |
+
head(hidden), temperature, top_k, top_p, check_finite=check_finite
|
| 388 |
+
)
|
| 389 |
+
)
|
| 390 |
+
return torch.stack((main, *codes), dim=-1)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
@torch.no_grad()
|
| 394 |
+
def load_audio_decoder_weights(
|
| 395 |
+
model: FishOmniAudioDecoder, weights: Iterable[tuple[str, Tensor]]
|
| 396 |
+
) -> None:
|
| 397 |
+
"""Copy audio_decoder* checkpoint tensors into model, each parameter exactly once."""
|
| 398 |
+
targets = dict(model.named_parameters())
|
| 399 |
+
loaded = set()
|
| 400 |
+
for key, tensor in weights:
|
| 401 |
+
name = next(
|
| 402 |
+
(
|
| 403 |
+
new + key[len(old) :]
|
| 404 |
+
for old, new in TOWER_CHECKPOINT_PREFIXES.items()
|
| 405 |
+
if key.startswith(old)
|
| 406 |
+
),
|
| 407 |
+
None,
|
| 408 |
+
)
|
| 409 |
+
if name not in targets:
|
| 410 |
+
raise ValueError(f"unknown tower weight {key}")
|
| 411 |
+
if name in loaded:
|
| 412 |
+
raise ValueError(f"tower weight filled twice: {key}")
|
| 413 |
+
target = targets[name]
|
| 414 |
+
if target.shape != tensor.shape:
|
| 415 |
+
raise ValueError(f"{key}: shape {tensor.shape} != {target.shape}")
|
| 416 |
+
value = tensor.to(device=target.device, dtype=target.dtype)
|
| 417 |
+
if not torch.isfinite(value).all():
|
| 418 |
+
raise FloatingPointError(f"{key} cannot be represented in {target.dtype}")
|
| 419 |
+
target.copy_(value)
|
| 420 |
+
loaded.add(name)
|
| 421 |
+
if missing := targets.keys() - loaded:
|
| 422 |
+
raise ValueError(f"tower weights not loaded: {sorted(missing)[:8]}")
|
| 423 |
+
logger.info(f"FishOmni tower: loaded {len(loaded)} tensors on {model.device}")
|
torch/fish_speech/models/text2semantic/sampling.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sampling defaults for S2-Pro and Drama 3: those of the official Fish Audio SDK
|
| 2 |
+
(fish-audio-sdk TTSConfig). The SDK has no top_k; both models use 30."""
|
| 3 |
+
|
| 4 |
+
DEFAULT_MAX_NEW_TOKENS = 1024 # per text chunk
|
| 5 |
+
DEFAULT_TEMPERATURE = 0.7
|
| 6 |
+
DEFAULT_TOP_P = 0.7
|
| 7 |
+
DEFAULT_TOP_K = 30
|
| 8 |
+
DEFAULT_REPETITION_PENALTY = 1.2
|
| 9 |
+
DEFAULT_CHUNK_LENGTH = 200
|
torch/gguf_kernels.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GGUF block formats used by drama3-expressive-medium, for PyTorch.
|
| 2 |
+
|
| 3 |
+
* Torch reference dequantization of Q8_0, Q5_K and IQ4_XS (CPU or GPU), a port of gguf-py's
|
| 4 |
+
quants.py; values are bit-exact against gguf-py / ggml's dequantize_row_*.
|
| 5 |
+
* Triton kernels (CUDA) for the routed-expert banks, which stay packed on the GPU:
|
| 6 |
+
- dequantize_experts(): selected experts of a bank -> bf16 [n, rows, K] (prefill path);
|
| 7 |
+
- moe_gemv(): fused dequantize + matrix-vector product over (token, expert) pairs (decode path),
|
| 8 |
+
gate/up with SiLU-gating, then down.
|
| 9 |
+
The Triton tile code computes each weight with the same float operations as the reference, so the
|
| 10 |
+
dequantized values are identical.
|
| 11 |
+
|
| 12 |
+
Block layouts (ggml):
|
| 13 |
+
Q8_0 34 B / 32 w : d f16 | qs int8[32] w = d * q
|
| 14 |
+
Q5_K 176 B / 256 w: d f16 | dmin f16 | scales u8[12] | qh u8[32] | qs u8[128]
|
| 15 |
+
w = (d * sc_j) * (nibble | qh_bit << 4) - dmin * m_j (j = sub-block of 32)
|
| 16 |
+
IQ4_XS 136 B / 256 w: d f16 | scales_h u16 | scales_l u8[4] | qs u8[128]
|
| 17 |
+
w = (d * (ls_j - 32)) * kvalues_iq4nl[nibble]
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from torch import Tensor
|
| 24 |
+
|
| 25 |
+
try: # Triton is only needed for the CUDA expert kernels.
|
| 26 |
+
import triton
|
| 27 |
+
import triton.language as tl
|
| 28 |
+
except ImportError: # pragma: no cover
|
| 29 |
+
triton = None
|
| 30 |
+
tl = None
|
| 31 |
+
|
| 32 |
+
# ggml type ids (gguf GGMLQuantizationType)
|
| 33 |
+
F32, F16, Q8_0, Q5_K, IQ4_XS = 0, 1, 8, 13, 23
|
| 34 |
+
TYPE_NAMES = {F32: "F32", F16: "F16", Q8_0: "Q8_0", Q5_K: "Q5_K", IQ4_XS: "IQ4_XS"}
|
| 35 |
+
# (weights per block, bytes per block)
|
| 36 |
+
BLOCK = {F32: (1, 4), F16: (1, 2), Q8_0: (32, 34), Q5_K: (256, 176), IQ4_XS: (256, 136)}
|
| 37 |
+
QK_K = 256
|
| 38 |
+
IQ4NL_VALUES = (-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def row_bytes(qtype: int, n_per_row: int) -> int:
|
| 42 |
+
block, size = BLOCK[qtype]
|
| 43 |
+
assert n_per_row % block == 0
|
| 44 |
+
return n_per_row // block * size
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# --------------------------------------------------------------------------------------------
|
| 48 |
+
# Torch reference (any device)
|
| 49 |
+
# --------------------------------------------------------------------------------------------
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _f16(x: Tensor) -> Tensor:
|
| 53 |
+
return x.contiguous().view(torch.float16).float()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _shifts(values, device, shape) -> Tensor:
|
| 57 |
+
return torch.tensor(values, dtype=torch.uint8, device=device).reshape(shape)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _q8_0(b: Tensor) -> Tensor:
|
| 61 |
+
return b[:, 2:].contiguous().view(torch.int8).float() * _f16(b[:, :2])
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _scale_min_k4(scales: Tensor) -> tuple[Tensor, Tensor]:
|
| 65 |
+
n = scales.shape[0]
|
| 66 |
+
s = scales.reshape(n, 3, 4)
|
| 67 |
+
d, m, m_d = s[:, 0:1], s[:, 1:2], s[:, 2:3]
|
| 68 |
+
sc = torch.cat([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], dim=-1)
|
| 69 |
+
mn = torch.cat([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], dim=-1)
|
| 70 |
+
return sc.reshape(n, 8), mn.reshape(n, 8)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _q5_k(b: Tensor) -> Tensor:
|
| 74 |
+
n = b.shape[0]
|
| 75 |
+
d, dmin, scales = _f16(b[:, :2]), _f16(b[:, 2:4]), b[:, 4:16]
|
| 76 |
+
qh, qs = b[:, 16:48], b[:, 48:]
|
| 77 |
+
sc, m = _scale_min_k4(scales)
|
| 78 |
+
d = (d * sc.float()).reshape(n, -1, 1)
|
| 79 |
+
dm = (dmin * m.float()).reshape(n, -1, 1)
|
| 80 |
+
ql = qs.reshape(n, -1, 1, 32) >> _shifts([0, 4], b.device, (1, 1, 2, 1))
|
| 81 |
+
qh = qh.reshape(n, -1, 1, 32) >> _shifts(list(range(8)), b.device, (1, 1, 8, 1))
|
| 82 |
+
ql = (ql & 0x0F).reshape(n, -1, 32)
|
| 83 |
+
qh = (qh & 0x01).reshape(n, -1, 32)
|
| 84 |
+
q = (ql | (qh << 4)).float()
|
| 85 |
+
return (d * q - dm).reshape(n, QK_K)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _iq4_xs(b: Tensor) -> Tensor:
|
| 89 |
+
n = b.shape[0]
|
| 90 |
+
d = _f16(b[:, :2])
|
| 91 |
+
scales_h = b[:, 2:4].contiguous().view(torch.int16).to(torch.int64) & 0xFFFF
|
| 92 |
+
scales_l = b[:, 4:8]
|
| 93 |
+
qs = b[:, 8:]
|
| 94 |
+
lo = (scales_l.reshape(n, 4, 1) >> _shifts([0, 4], b.device, (1, 1, 2))).reshape(n, 8) & 0x0F
|
| 95 |
+
hi = (scales_h >> torch.arange(0, 16, 2, dtype=torch.int64, device=b.device)) & 3
|
| 96 |
+
dl = (d * ((lo.to(torch.int64) | (hi << 4)) - 32).float()).reshape(n, 8, 1)
|
| 97 |
+
q = qs.reshape(n, 8, 1, 16) >> _shifts([0, 4], b.device, (1, 1, 2, 1))
|
| 98 |
+
values = torch.tensor(IQ4NL_VALUES, dtype=torch.float32, device=b.device)
|
| 99 |
+
q = values[(q & 0x0F).long()].reshape(n, 8, 32)
|
| 100 |
+
return (dl * q).reshape(n, QK_K)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
_TORCH_KERNELS = {Q8_0: _q8_0, Q5_K: _q5_k, IQ4_XS: _iq4_xs}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def dequantize_torch(q: Tensor, qtype: int, n_per_row: int, dtype: torch.dtype = torch.float32,
|
| 107 |
+
chunk_blocks: int = 1 << 16) -> Tensor:
|
| 108 |
+
"""q uint8 [..., row_bytes] -> dtype [..., n_per_row] (reference path, any device)."""
|
| 109 |
+
if qtype == F32:
|
| 110 |
+
return q.contiguous().view(torch.float32).reshape(*q.shape[:-1], n_per_row).to(dtype)
|
| 111 |
+
if qtype == F16:
|
| 112 |
+
return q.contiguous().view(torch.float16).reshape(*q.shape[:-1], n_per_row).to(dtype)
|
| 113 |
+
block, size = BLOCK[qtype]
|
| 114 |
+
lead = q.shape[:-1]
|
| 115 |
+
blocks = q.reshape(-1, size)
|
| 116 |
+
kernel = _TORCH_KERNELS[qtype]
|
| 117 |
+
out = torch.empty(blocks.shape[0], block, dtype=dtype, device=q.device)
|
| 118 |
+
for s in range(0, blocks.shape[0], chunk_blocks):
|
| 119 |
+
out[s : s + chunk_blocks] = kernel(blocks[s : s + chunk_blocks]).to(dtype)
|
| 120 |
+
return out.reshape(*lead, n_per_row)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# --------------------------------------------------------------------------------------------
|
| 124 |
+
# Triton kernels (CUDA)
|
| 125 |
+
# --------------------------------------------------------------------------------------------
|
| 126 |
+
|
| 127 |
+
if triton is not None:
|
| 128 |
+
|
| 129 |
+
@triton.jit
|
| 130 |
+
def _u8(ptr, off):
|
| 131 |
+
return tl.load(ptr + off).to(tl.int32)
|
| 132 |
+
|
| 133 |
+
@triton.jit
|
| 134 |
+
def _f16_at(ptr, off):
|
| 135 |
+
lo = tl.load(ptr + off).to(tl.uint16)
|
| 136 |
+
hi = tl.load(ptr + off + 1).to(tl.uint16)
|
| 137 |
+
return (lo | (hi << 8)).to(tl.float16, bitcast=True).to(tl.float32)
|
| 138 |
+
|
| 139 |
+
@triton.jit
|
| 140 |
+
def _tile_iq4_xs(ptr, base, w, kv_ptr):
|
| 141 |
+
"""base: int64 byte offset of each row's 256-weight block [R, 1]; w: weight index [1, 256]."""
|
| 142 |
+
d = _f16_at(ptr, base)
|
| 143 |
+
sh = _u8(ptr, base + 2) | (_u8(ptr, base + 3) << 8)
|
| 144 |
+
ib = w // 32
|
| 145 |
+
sl = (_u8(ptr, base + 4 + ib // 2) >> (4 * (ib % 2))) & 0xF
|
| 146 |
+
ls = sl | (((sh >> (2 * ib)) & 3) << 4)
|
| 147 |
+
dl = d * (ls - 32).to(tl.float32)
|
| 148 |
+
qb = _u8(ptr, base + 8 + 16 * ib + (w % 16))
|
| 149 |
+
nib = (qb >> (4 * ((w % 32) // 16))) & 0xF
|
| 150 |
+
return dl * tl.load(kv_ptr + nib)
|
| 151 |
+
|
| 152 |
+
@triton.jit
|
| 153 |
+
def _tile_q5_k(ptr, base, w):
|
| 154 |
+
d = _f16_at(ptr, base)
|
| 155 |
+
dmin = _f16_at(ptr, base + 2)
|
| 156 |
+
j = w // 32
|
| 157 |
+
a = _u8(ptr, base + 4 + j)
|
| 158 |
+
b = _u8(ptr, base + 8 + j)
|
| 159 |
+
c = _u8(ptr, base + 4 + (j % 4)) # q[j - 4] for j >= 4
|
| 160 |
+
sc = tl.where(j < 4, a & 63, (b & 0xF) | ((c >> 6) << 4))
|
| 161 |
+
m = tl.where(j < 4, b & 63, (b >> 4) | ((a >> 6) << 4))
|
| 162 |
+
l = w % 32
|
| 163 |
+
ql = _u8(ptr, base + 48 + 32 * (w // 64) + l)
|
| 164 |
+
nib = (ql >> (4 * (j % 2))) & 0xF
|
| 165 |
+
hb = (_u8(ptr, base + 16 + l) >> j) & 1
|
| 166 |
+
q = (nib | (hb << 4)).to(tl.float32)
|
| 167 |
+
return (d * sc.to(tl.float32)) * q - dmin * m.to(tl.float32)
|
| 168 |
+
|
| 169 |
+
@triton.jit
|
| 170 |
+
def _tile(ptr, base, w, kv_ptr, QTYPE: tl.constexpr):
|
| 171 |
+
if QTYPE == 23:
|
| 172 |
+
return _tile_iq4_xs(ptr, base, w, kv_ptr)
|
| 173 |
+
else:
|
| 174 |
+
return _tile_q5_k(ptr, base, w)
|
| 175 |
+
|
| 176 |
+
@triton.jit
|
| 177 |
+
def _dequant_experts_kernel(q_ptr, ids_ptr, out_ptr, kv_ptr, ROWS: tl.constexpr, K: tl.constexpr,
|
| 178 |
+
ROW_BYTES: tl.constexpr, BB: tl.constexpr, QTYPE: tl.constexpr,
|
| 179 |
+
BLOCK_R: tl.constexpr):
|
| 180 |
+
n = tl.program_id(0) # selected expert slot
|
| 181 |
+
rb = tl.program_id(1) # row block
|
| 182 |
+
kb = tl.program_id(2) # 256-weight block along K
|
| 183 |
+
e = tl.load(ids_ptr + n).to(tl.int64)
|
| 184 |
+
rows = rb * BLOCK_R + tl.arange(0, BLOCK_R)[:, None]
|
| 185 |
+
w = tl.arange(0, 256)[None, :]
|
| 186 |
+
base = (e * ROWS + rows) * ROW_BYTES + kb * BB
|
| 187 |
+
y = _tile(q_ptr, base, w, kv_ptr, QTYPE)
|
| 188 |
+
dst = (n.to(tl.int64) * ROWS + rows) * K + kb * 256 + w
|
| 189 |
+
tl.store(out_ptr + dst, y.to(out_ptr.dtype.element_ty))
|
| 190 |
+
|
| 191 |
+
@triton.jit
|
| 192 |
+
def _gemv_kernel(x_ptr, ids_ptr, w1_ptr, w3_ptr, out_ptr, kv_ptr, TOPK: tl.constexpr, ROWS: tl.constexpr,
|
| 193 |
+
K: tl.constexpr, ROW_BYTES: tl.constexpr, BB: tl.constexpr, QTYPE: tl.constexpr,
|
| 194 |
+
GATED: tl.constexpr, X_PER_PAIR: tl.constexpr, BLOCK_R: tl.constexpr):
|
| 195 |
+
"""out[p, r] = W1[e_p, r] . x (or silu(W1 x) * (W3 x) with GATED), fp32 accumulation.
|
| 196 |
+
|
| 197 |
+
x row: token p // TOPK, or pair p itself when X_PER_PAIR (the down projection's input)."""
|
| 198 |
+
p = tl.program_id(0)
|
| 199 |
+
rb = tl.program_id(1)
|
| 200 |
+
e = tl.load(ids_ptr + p).to(tl.int64)
|
| 201 |
+
if X_PER_PAIR:
|
| 202 |
+
xrow = p
|
| 203 |
+
else:
|
| 204 |
+
xrow = p // TOPK
|
| 205 |
+
rows = rb * BLOCK_R + tl.arange(0, BLOCK_R)[:, None]
|
| 206 |
+
w = tl.arange(0, 256)[None, :]
|
| 207 |
+
acc1 = tl.zeros([BLOCK_R], dtype=tl.float32)
|
| 208 |
+
acc3 = tl.zeros([BLOCK_R], dtype=tl.float32)
|
| 209 |
+
for kb in tl.static_range(K // 256):
|
| 210 |
+
x = tl.load(x_ptr + xrow.to(tl.int64) * K + kb * 256 + w).to(tl.float32)
|
| 211 |
+
base = (e * ROWS + rows) * ROW_BYTES + kb * BB
|
| 212 |
+
acc1 += tl.sum(_tile(w1_ptr, base, w, kv_ptr, QTYPE) * x, axis=1)
|
| 213 |
+
if GATED:
|
| 214 |
+
acc3 += tl.sum(_tile(w3_ptr, base, w, kv_ptr, QTYPE) * x, axis=1)
|
| 215 |
+
if GATED:
|
| 216 |
+
acc1 = acc1 * tl.sigmoid(acc1) * acc3
|
| 217 |
+
r1 = rb * BLOCK_R + tl.arange(0, BLOCK_R)
|
| 218 |
+
tl.store(out_ptr + p.to(tl.int64) * ROWS + r1, acc1)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
_KV_TABLES: dict[torch.device, Tensor] = {}
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _kv_table(device) -> Tensor:
|
| 225 |
+
device = torch.device(device)
|
| 226 |
+
if device not in _KV_TABLES:
|
| 227 |
+
_KV_TABLES[device] = torch.tensor(IQ4NL_VALUES, dtype=torch.float32, device=device)
|
| 228 |
+
return _KV_TABLES[device]
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def dequantize_experts(bank: Tensor, qtype: int, ids: Tensor, k: int, dtype=torch.bfloat16,
|
| 232 |
+
block_r: int = 16) -> Tensor:
|
| 233 |
+
"""bank uint8 [E, rows, row_bytes] (CUDA), ids int [n] -> dtype [n, rows, k]."""
|
| 234 |
+
_, rows, rb = bank.shape
|
| 235 |
+
n = ids.numel()
|
| 236 |
+
out = torch.empty((n, rows, k), dtype=dtype, device=bank.device)
|
| 237 |
+
if n == 0:
|
| 238 |
+
return out
|
| 239 |
+
if triton is None or not bank.is_cuda:
|
| 240 |
+
return dequantize_torch(bank[ids.long()], qtype, k, dtype)
|
| 241 |
+
grid = (n, rows // block_r, k // QK_K)
|
| 242 |
+
_dequant_experts_kernel[grid](bank, ids, out, _kv_table(bank.device), ROWS=rows, K=k, ROW_BYTES=rb,
|
| 243 |
+
BB=BLOCK[qtype][1], QTYPE=qtype, BLOCK_R=block_r, num_warps=4)
|
| 244 |
+
return out
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def moe_gemv(x: Tensor, ids: Tensor, top_k: int, w1: Tensor, w3: Tensor | None, qtype: int,
|
| 248 |
+
x_per_pair: bool = False, block_r: int = 16) -> Tensor:
|
| 249 |
+
"""Fused dequant-GEMV over (token, expert) pairs.
|
| 250 |
+
|
| 251 |
+
x [N, K] (or [P, K] with x_per_pair), ids [P] expert of each pair (pairs of token t are
|
| 252 |
+
t * top_k ... t * top_k + top_k - 1). Banks w1 / w3 uint8 [E, rows, row_bytes].
|
| 253 |
+
Returns fp32 [P, rows]: W1 x, or silu(W1 x) * (W3 x) when w3 is given.
|
| 254 |
+
"""
|
| 255 |
+
_, rows, rb = w1.shape
|
| 256 |
+
k = x.shape[-1]
|
| 257 |
+
p = ids.numel()
|
| 258 |
+
out = torch.empty((p, rows), dtype=torch.float32, device=x.device)
|
| 259 |
+
grid = (p, rows // block_r)
|
| 260 |
+
_gemv_kernel[grid](x.contiguous(), ids, w1, w3 if w3 is not None else w1, out, _kv_table(x.device),
|
| 261 |
+
TOPK=top_k, ROWS=rows, K=k, ROW_BYTES=rb, BB=BLOCK[qtype][1], QTYPE=qtype,
|
| 262 |
+
GATED=w3 is not None, X_PER_PAIR=x_per_pair, BLOCK_R=block_r, num_warps=4)
|
| 263 |
+
return out
|
torch/infer.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""drama3-expressive-medium text-to-speech in PyTorch, from the GGUF alone.
|
| 3 |
+
|
| 4 |
+
python infer.py --gguf drama3-expressive-medium-IQ4_XS.gguf \\
|
| 5 |
+
--text "[calm] It's fine. [voice breaking] I just miss her." \\
|
| 6 |
+
--ref-audio voice.wav --ref-text "transcript of voice.wav" --out take.wav --seed 1
|
| 7 |
+
|
| 8 |
+
Batch mode renders an audio.cpp-style request file with one model load:
|
| 9 |
+
|
| 10 |
+
python infer.py --gguf ... --requests requests.json --out-dir renders/
|
| 11 |
+
|
| 12 |
+
requests.json: {"requests": [{"id", "text", "voice_ref", "options": {"reference_text"}, "seed",
|
| 13 |
+
"temperature", "top_k", "top_p", "max_tokens"}]} (missing fields fall back to the CLI values).
|
| 14 |
+
|
| 15 |
+
Sampling follows audio.cpp's fish_drama3 generator (drama3-medium patch): temperature / top-p /
|
| 16 |
+
top-k for the main token and the 9 residual codes, repetition-aware redraw, the pause fix
|
| 17 |
+
(--max-pause-frames, --silence-codes) and the length guard; texts longer than 200 codepoints are
|
| 18 |
+
split into sentence chunks, each conditioned on the previous chunk's take.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import logging
|
| 26 |
+
import math
|
| 27 |
+
import os
|
| 28 |
+
import sys
|
| 29 |
+
import time
|
| 30 |
+
|
| 31 |
+
# Less fragmentation between prefill, decode and codec buffers (matters on 24 GB cards).
|
| 32 |
+
os.environ.setdefault("PYTORCH_ALLOC_CONF", os.environ.get("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True"))
|
| 33 |
+
|
| 34 |
+
from dataclasses import dataclass, field
|
| 35 |
+
|
| 36 |
+
import numpy as np
|
| 37 |
+
import torch
|
| 38 |
+
import torch.nn.functional as F
|
| 39 |
+
|
| 40 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 41 |
+
sys.path.insert(0, HERE)
|
| 42 |
+
|
| 43 |
+
import drama3_gguf # noqa: E402
|
| 44 |
+
from fish_speech.models.text2semantic.errors import InvalidInputError # noqa: E402
|
| 45 |
+
from fish_speech.models.text2semantic.fish_omni.generate import ( # noqa: E402
|
| 46 |
+
Drama3Sampling,
|
| 47 |
+
PauseFix,
|
| 48 |
+
build_drama3_prompt,
|
| 49 |
+
generate_drama3,
|
| 50 |
+
load_silence_codes,
|
| 51 |
+
split_text_chunks,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
logger = logging.getLogger("drama3")
|
| 55 |
+
SAMPLE_RATE = 44100
|
| 56 |
+
DEFAULT_SILENCE_CODES = os.path.join(os.path.dirname(HERE), "silence_codes.json")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# --------------------------------------------------------------------------------------------
|
| 60 |
+
# Audio I/O and codec helpers
|
| 61 |
+
# --------------------------------------------------------------------------------------------
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def resample(wav: torch.Tensor, orig: int, new: int, lowpass_filter_width: int = 6, rolloff: float = 0.99) -> torch.Tensor:
|
| 65 |
+
"""torchaudio.functional.resample (sinc_interp_hann), as audio.cpp uses for references."""
|
| 66 |
+
if orig == new:
|
| 67 |
+
return wav
|
| 68 |
+
gcd = math.gcd(orig, new)
|
| 69 |
+
o, n = orig // gcd, new // gcd
|
| 70 |
+
base = min(o, n) * rolloff
|
| 71 |
+
width = math.ceil(lowpass_filter_width * o / base)
|
| 72 |
+
dtype, device = wav.dtype, wav.device
|
| 73 |
+
idx = torch.arange(-width, width + o, dtype=dtype, device=device)[None, None] / o
|
| 74 |
+
t = torch.arange(0, -n, -1, dtype=dtype, device=device)[:, None, None] / n + idx
|
| 75 |
+
t *= base
|
| 76 |
+
t = t.clamp_(-lowpass_filter_width, lowpass_filter_width)
|
| 77 |
+
window = torch.cos(t * math.pi / lowpass_filter_width / 2) ** 2
|
| 78 |
+
t *= math.pi
|
| 79 |
+
kernel = torch.where(t == 0, torch.tensor(1.0).to(t), t.sin() / t) * (window * (base / o))
|
| 80 |
+
length = wav.shape[-1]
|
| 81 |
+
x = F.pad(wav.reshape(1, -1), (width, width + o))
|
| 82 |
+
out = F.conv1d(x[:, None], kernel, stride=o).transpose(1, 2).reshape(1, -1)
|
| 83 |
+
return out[0, : int(math.ceil(n * length / o))]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def load_audio(path: str, sample_rate: int = SAMPLE_RATE) -> torch.Tensor:
|
| 87 |
+
"""Mono float32 waveform at sample_rate (channels averaged, as audio.cpp does)."""
|
| 88 |
+
import soundfile as sf
|
| 89 |
+
|
| 90 |
+
data, sr = sf.read(path, dtype="float32", always_2d=True)
|
| 91 |
+
wav = torch.from_numpy(data.mean(axis=1).astype(np.float32))
|
| 92 |
+
return resample(wav, sr, sample_rate)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def encode_reference(codec, wav: torch.Tensor) -> torch.Tensor:
|
| 96 |
+
"""Waveform [T] at 44.1 kHz -> codes [10, frames] (long, CPU)."""
|
| 97 |
+
return drama3_gguf.encode_audio(codec, wav)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def decode_codes(codec, codes: torch.Tensor) -> np.ndarray:
|
| 101 |
+
"""Codes [10, frames] -> float32 waveform (2048 samples per frame)."""
|
| 102 |
+
return drama3_gguf.decode_codes(codec, codes).float().cpu().numpy()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# --------------------------------------------------------------------------------------------
|
| 106 |
+
# Synthesis
|
| 107 |
+
# --------------------------------------------------------------------------------------------
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@dataclass
|
| 111 |
+
class Request:
|
| 112 |
+
text: str
|
| 113 |
+
ref_audio: str | None = None
|
| 114 |
+
ref_text: str | None = None
|
| 115 |
+
seed: int = 0
|
| 116 |
+
sampling: Drama3Sampling = field(default_factory=Drama3Sampling)
|
| 117 |
+
save_ref_codes: str | None = None # write the reference codes [10, frames] here (.npy)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@dataclass
|
| 121 |
+
class Result:
|
| 122 |
+
audio: np.ndarray
|
| 123 |
+
codes: torch.Tensor # [10, frames]
|
| 124 |
+
info: dict
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class Drama3TTS:
|
| 128 |
+
"""Model + codec on one device. References listed in `preload_refs` are encoded before the
|
| 129 |
+
language model is loaded; afterwards the codec's encoder side lives in host RAM and visits the
|
| 130 |
+
GPU only to encode a new reference (keeps the 24 GB peak down)."""
|
| 131 |
+
|
| 132 |
+
def __init__(self, gguf_path: str, device: str = "cuda:0", context_length: int = 4096,
|
| 133 |
+
cuda_graphs: bool = True, preload_refs: tuple[str, ...] = ()) -> None:
|
| 134 |
+
started = time.perf_counter()
|
| 135 |
+
self.device = torch.device(device)
|
| 136 |
+
self.gguf = drama3_gguf.GGUFFile(gguf_path)
|
| 137 |
+
self.codec = drama3_gguf.load_codec(self.gguf, self.device)
|
| 138 |
+
self._ref_cache: dict[str, torch.Tensor] = {}
|
| 139 |
+
t = time.perf_counter()
|
| 140 |
+
for path in dict.fromkeys(preload_refs):
|
| 141 |
+
self.reference_codes(path)
|
| 142 |
+
self.ref_encode_s = time.perf_counter() - t
|
| 143 |
+
drama3_gguf.offload_encoder(self.codec)
|
| 144 |
+
if self.device.type == "cuda":
|
| 145 |
+
torch.cuda.empty_cache()
|
| 146 |
+
self.model = drama3_gguf.load_model(self.gguf, self.device)
|
| 147 |
+
self.context_length = context_length
|
| 148 |
+
self.cuda_graphs = cuda_graphs and self.device.type == "cuda"
|
| 149 |
+
self.load_s = time.perf_counter() - started
|
| 150 |
+
|
| 151 |
+
def reference_codes(self, path: str) -> torch.Tensor:
|
| 152 |
+
"""Codes [10, frames] of a reference: an audio file, or a .npy of codes (e.g. from --save-codes)."""
|
| 153 |
+
if path not in self._ref_cache:
|
| 154 |
+
if path.endswith(".npy"):
|
| 155 |
+
codes = torch.from_numpy(np.load(path).astype(np.int64))
|
| 156 |
+
if codes.ndim != 2 or codes.shape[0] != 10:
|
| 157 |
+
raise InvalidInputError(f"{path}: reference codes must be [10, frames]")
|
| 158 |
+
self._ref_cache[path] = codes
|
| 159 |
+
return codes
|
| 160 |
+
self._ref_cache[path] = encode_reference(self.codec, load_audio(path))
|
| 161 |
+
if self.device.type == "cuda":
|
| 162 |
+
torch.cuda.empty_cache()
|
| 163 |
+
return self._ref_cache[path]
|
| 164 |
+
|
| 165 |
+
def synthesize(self, req: Request) -> Result:
|
| 166 |
+
model = self.model
|
| 167 |
+
started = time.perf_counter()
|
| 168 |
+
refs_text, refs_codes = [], []
|
| 169 |
+
if req.ref_audio:
|
| 170 |
+
if not req.ref_text:
|
| 171 |
+
raise InvalidInputError("--ref-audio needs --ref-text (its transcript)")
|
| 172 |
+
refs_text, refs_codes = [req.ref_text], [self.reference_codes(req.ref_audio)]
|
| 173 |
+
if req.save_ref_codes:
|
| 174 |
+
np.save(req.save_ref_codes, refs_codes[0].numpy().astype(np.int16))
|
| 175 |
+
encode_s = time.perf_counter() - started
|
| 176 |
+
chunks = split_text_chunks(req.text)
|
| 177 |
+
if not chunks:
|
| 178 |
+
raise InvalidInputError("text is empty")
|
| 179 |
+
takes, history = [], []
|
| 180 |
+
for index, chunk in enumerate(chunks):
|
| 181 |
+
prompt = build_drama3_prompt(chunk, model.tokenizer, model.config, refs_text, refs_codes, history)
|
| 182 |
+
take = generate_drama3(model, prompt, text=chunk, sampling=req.sampling, capacity=self.context_length,
|
| 183 |
+
use_graphs=self.cuda_graphs, seed=req.seed + index)
|
| 184 |
+
if len(take.frames) == 0:
|
| 185 |
+
raise RuntimeError("Drama 3 ended before producing an audio frame")
|
| 186 |
+
takes.append((chunk, take, len(prompt)))
|
| 187 |
+
history = [(chunk, take.codes)]
|
| 188 |
+
codes = torch.cat([t.codes for _, t, _ in takes], dim=1)
|
| 189 |
+
started_decode = time.perf_counter()
|
| 190 |
+
audio = decode_codes(self.codec, codes)
|
| 191 |
+
if self.device.type == "cuda":
|
| 192 |
+
torch.cuda.synchronize(self.device)
|
| 193 |
+
decode_audio_s = time.perf_counter() - started_decode
|
| 194 |
+
frames = codes.shape[1]
|
| 195 |
+
gen_s = sum(t.prefill_s + t.decode_s for _, t, _ in takes)
|
| 196 |
+
info = {
|
| 197 |
+
"frames": frames,
|
| 198 |
+
"duration_s": len(audio) / SAMPLE_RATE,
|
| 199 |
+
"chunks": [{"text": c, "frames": len(t.frames), "finish": t.finish_reason, "prompt_rows": rows,
|
| 200 |
+
"prefill_s": round(t.prefill_s, 3), "decode_s": round(t.decode_s, 3)} for c, t, rows in takes],
|
| 201 |
+
"reference_encode_s": round(encode_s, 3),
|
| 202 |
+
"generate_s": round(gen_s, 3),
|
| 203 |
+
"codec_decode_s": round(decode_audio_s, 3),
|
| 204 |
+
"frames_per_s": round(sum(len(t.frames) for _, t, _ in takes) / max(1e-9, sum(t.decode_s for _, t, _ in takes)), 2),
|
| 205 |
+
"wall_s": round(time.perf_counter() - started, 3),
|
| 206 |
+
}
|
| 207 |
+
info["x_real_time"] = round(info["duration_s"] / max(1e-9, info["wall_s"]), 2)
|
| 208 |
+
return Result(audio=audio, codes=codes, info=info)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def write_wav(path: str, audio: np.ndarray) -> None:
|
| 212 |
+
import soundfile as sf
|
| 213 |
+
|
| 214 |
+
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
| 215 |
+
sf.write(path, np.clip(audio, -1.0, 1.0), SAMPLE_RATE, subtype="PCM_16")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def main() -> None:
|
| 219 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 220 |
+
ap.add_argument("--gguf", default=os.path.join(os.path.dirname(HERE), "drama3-expressive-medium-IQ4_XS.gguf"))
|
| 221 |
+
ap.add_argument("--text", help="text to speak; [bracketed] acting directions are passed as-is")
|
| 222 |
+
ap.add_argument("--ref-audio", help="voice reference (any sample rate; mixed to mono), or a .npy of its codes [10, frames]")
|
| 223 |
+
ap.add_argument("--ref-text", help="transcript of --ref-audio")
|
| 224 |
+
ap.add_argument("--out", default="out.wav", help="output wav (44.1 kHz mono, 16-bit)")
|
| 225 |
+
ap.add_argument("--requests", help="audio.cpp-style request JSON (batch mode, see the module doc)")
|
| 226 |
+
ap.add_argument("--out-dir", default="out", help="batch mode: <id>.wav and <id>.json here")
|
| 227 |
+
ap.add_argument("--seed", type=int, default=0)
|
| 228 |
+
ap.add_argument("--temperature", type=float, default=0.7)
|
| 229 |
+
ap.add_argument("--top-p", type=float, default=0.7)
|
| 230 |
+
ap.add_argument("--top-k", type=int, default=30)
|
| 231 |
+
ap.add_argument("--max-tokens", type=int, default=1024, help="max frames per text chunk (21.5 frames/s)")
|
| 232 |
+
ap.add_argument("--max-pause-frames", type=int, default=10, help="pause fix; 0 turns it and the length guard off")
|
| 233 |
+
ap.add_argument("--silence-codes", default=DEFAULT_SILENCE_CODES, help="file or list of silent semantic codes")
|
| 234 |
+
ap.add_argument("--pause-end-ratio", type=float, default=2.0)
|
| 235 |
+
ap.add_argument("--pause-cap-ratio", type=float, default=3.0)
|
| 236 |
+
ap.add_argument("--device", default="cuda:0")
|
| 237 |
+
ap.add_argument("--context-length", type=int, default=4096, help="cache rows: prompt (reference + text) + max tokens")
|
| 238 |
+
ap.add_argument("--no-cuda-graphs", action="store_true")
|
| 239 |
+
ap.add_argument("--save-codes", action="store_true", help="also write the codes [10, frames] as .npy")
|
| 240 |
+
ap.add_argument("--save-ref-codes", help="write the reference's codes [10, frames] to this .npy (reuse with --ref-audio x.npy)")
|
| 241 |
+
ap.add_argument("--verbose", action="store_true")
|
| 242 |
+
args = ap.parse_args()
|
| 243 |
+
logging.basicConfig(level=logging.INFO if args.verbose else logging.WARNING,
|
| 244 |
+
format="%(asctime)s %(name)s: %(message)s")
|
| 245 |
+
if not args.text and not args.requests:
|
| 246 |
+
ap.error("give --text or --requests")
|
| 247 |
+
|
| 248 |
+
pause = None
|
| 249 |
+
if args.max_pause_frames > 0:
|
| 250 |
+
pause = PauseFix(max_pause_frames=args.max_pause_frames, silence_codes=load_silence_codes(args.silence_codes),
|
| 251 |
+
end_ratio=args.pause_end_ratio, cap_ratio=args.pause_cap_ratio)
|
| 252 |
+
|
| 253 |
+
def sampling(item: dict | None = None) -> Drama3Sampling:
|
| 254 |
+
item = item or {}
|
| 255 |
+
return Drama3Sampling(temperature=float(item.get("temperature", args.temperature)),
|
| 256 |
+
top_p=float(item.get("top_p", args.top_p)), top_k=int(item.get("top_k", args.top_k)),
|
| 257 |
+
max_new_tokens=int(item.get("max_tokens", args.max_tokens)), pause=pause)
|
| 258 |
+
|
| 259 |
+
if args.requests:
|
| 260 |
+
with open(args.requests, encoding="utf-8") as f:
|
| 261 |
+
items = json.load(f)["requests"]
|
| 262 |
+
jobs = [(it.get("id", f"req{i}"), Request(text=it["text"], ref_audio=it.get("voice_ref"),
|
| 263 |
+
ref_text=(it.get("options") or {}).get("reference_text"),
|
| 264 |
+
seed=int(it.get("seed", args.seed)), sampling=sampling(it)))
|
| 265 |
+
for i, it in enumerate(items)]
|
| 266 |
+
else:
|
| 267 |
+
jobs = [(None, Request(text=args.text, ref_audio=args.ref_audio, ref_text=args.ref_text, seed=args.seed,
|
| 268 |
+
sampling=sampling(), save_ref_codes=args.save_ref_codes))]
|
| 269 |
+
|
| 270 |
+
tts = Drama3TTS(args.gguf, args.device, args.context_length, cuda_graphs=not args.no_cuda_graphs,
|
| 271 |
+
preload_refs=tuple(r.ref_audio for _, r in jobs if r.ref_audio and not r.ref_audio.endswith(".npy")))
|
| 272 |
+
print(f"loaded in {tts.load_s:.1f}s (reference encoding {tts.ref_encode_s:.2f}s)", file=sys.stderr)
|
| 273 |
+
for job_id, req in jobs:
|
| 274 |
+
result = tts.synthesize(req)
|
| 275 |
+
out = os.path.join(args.out_dir, f"{job_id}.wav") if job_id is not None else args.out
|
| 276 |
+
write_wav(out, result.audio)
|
| 277 |
+
if args.save_codes:
|
| 278 |
+
np.save(os.path.splitext(out)[0] + ".codes.npy", result.codes.numpy().astype(np.int16))
|
| 279 |
+
info = {"id": job_id, "out": out, "text": req.text, "seed": req.seed, **result.info}
|
| 280 |
+
if job_id is not None:
|
| 281 |
+
with open(os.path.splitext(out)[0] + ".json", "w", encoding="utf-8") as f:
|
| 282 |
+
json.dump(info, f, ensure_ascii=False, indent=1)
|
| 283 |
+
if torch.cuda.is_available() and tts.device.type == "cuda":
|
| 284 |
+
info["peak_allocated_gib"] = round(torch.cuda.max_memory_allocated(tts.device) / 2**30, 3)
|
| 285 |
+
info["peak_reserved_gib"] = round(torch.cuda.max_memory_reserved(tts.device) / 2**30, 3)
|
| 286 |
+
print(json.dumps(info, ensure_ascii=False), flush=True)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
main()
|
torch/requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tested on Linux x86_64, Python 3.12, CUDA 12.8 driver stack, RTX 5090 / RTX 4090.
|
| 2 |
+
torch==2.9.1 # CUDA build (cu128); provides triton 3.5.1 on Linux
|
| 3 |
+
triton==3.5.1 # fused GGUF expert kernels (installed with torch on Linux)
|
| 4 |
+
numpy==2.5.4
|
| 5 |
+
tokenizers==0.23.2
|
| 6 |
+
soundfile==0.14.0
|
| 7 |
+
# Optional, only for the verification scripts (not imported by infer.py / drama3_gguf.py):
|
| 8 |
+
# gguf==0.19.0 # cross-check the dequantization against gguf-py
|
| 9 |
+
# transformers==5.19.0 # Whisper large-v3-turbo CER
|