Text-to-Audio
TensorRT
moonbox
yue2
yue
music-generation
text-to-music
song-generation
lyrics-to-song
non-commercial
Instructions to use moonbox-dev/YuE2-3B-TensorRT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- TensorRT
How to use moonbox-dev/YuE2-3B-TensorRT with TensorRT:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
fp16 build of YuE2-3B
Browse filesFiles changed (26)
- .gitattributes+14
- fp16/LICENSE.txtAdded+429
- fp16/THIRD_PARTY_NOTICES.mdAdded+15
- fp16/ar_0.engineAdded+3
- fp16/ar_1.engineAdded+3
- fp16/ar_2.engineAdded+3
- fp16/ar_3.engineAdded+3
- fp16/ar_4.engineAdded+3
- fp16/ar_5.engineAdded+3
- fp16/ar_6.engineAdded+3
- fp16/ar_7.engineAdded+3
- fp16/ar_split.jsonAdded+195
- fp16/device_chain.pyAdded+188
- fp16/licenses/SnakeBeta-NVIDIA-MIT.txtAdded+21
- fp16/licenses/stable-audio-tools-MIT.txtAdded+21
- fp16/nar_0.engineAdded+3
- fp16/nar_1.engineAdded+3
- fp16/nar_2.engineAdded+3
- fp16/nar_3.engineAdded+3
- fp16/nar_4.engineAdded+3
- fp16/nar_split.jsonAdded+112
- fp16/pipeline.pyAdded+354
- fp16/pipeline_trt.pyAdded+125
- fp16/qwen.tiktokenAdded
- fp16/trt_runner.pyAdded+98
- fp16/vae.engineAdded+3
32 unmodified lines333435363738394041424344454647484932 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textfp16/ar_0.engine filter=lfs diff=lfs merge=lfs -textfp16/ar_1.engine filter=lfs diff=lfs merge=lfs -textfp16/ar_2.engine filter=lfs diff=lfs merge=lfs -textfp16/ar_3.engine filter=lfs diff=lfs merge=lfs -textfp16/ar_4.engine filter=lfs diff=lfs merge=lfs -textfp16/ar_5.engine filter=lfs diff=lfs merge=lfs -textfp16/ar_6.engine filter=lfs diff=lfs merge=lfs -textfp16/ar_7.engine filter=lfs diff=lfs merge=lfs -textfp16/nar_0.engine filter=lfs diff=lfs merge=lfs -textfp16/nar_1.engine filter=lfs diff=lfs merge=lfs -textfp16/nar_2.engine filter=lfs diff=lfs merge=lfs -textfp16/nar_3.engine filter=lfs diff=lfs merge=lfs -textfp16/nar_4.engine filter=lfs diff=lfs merge=lfs -textfp16/vae.engine filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429YuE2 model-weight license
The YuE2-3B, YuE2-Vae and YuE2-Vae-legacy checkpoint weights arelicensed under Creative Commons Attribution-NonCommercial 4.0 International(CC BY-NC 4.0): https://creativecommons.org/licenses/by-nc/4.0/
Scope: the YuE2 checkpoint weights in model.safetensors, or the correspondingmodels/<model-name>/model.safetensors files in the inference kit.For attribution, identify YuE2, the model name and its source repository:https://huggingface.co/m-a-p/YuE2-3Bhttps://huggingface.co/m-a-p/YuE2-Vaehttps://huggingface.co/m-a-p/YuE2-Vae-legacy
This weight license does not replace separately applicable licenses for code,text tokenization files, evaluation assets or other bundled material.Third-party source notices and their original license texts are preserved inTHIRD_PARTY_NOTICES.md and licenses/.
The official license text follows without modification.Source: https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt
Attribution-NonCommercial 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm anddoes not provide legal services or legal advice. Distribution ofCreative Commons public licenses does not create a lawyer-client orother relationship. Creative Commons makes its licenses and relatedinformation available on an "as-is" basis. Creative Commons gives nowarranties regarding its licenses, any material licensed under theirterms and conditions, or any related information. Creative Commonsdisclaims all liability for damages resulting from their use to thefullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms andconditions that creators and other rights holders may use to shareoriginal works of authorship and other material subject to copyrightand certain other rights specified in the public license below. Thefollowing considerations are for informational purposes only, are notexhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial 4.0 International PublicLicense
By exercising the Licensed Rights (defined below), You accept and agreeto be bound by the terms and conditions of this Creative CommonsAttribution-NonCommercial 4.0 International Public License ("PublicLicense"). To the extent this Public License may be interpreted as acontract, You are granted the Licensed Rights in consideration of Youracceptance of these terms and conditions, and the Licensor grants Yousuch rights in consideration of benefits the Licensor receives frommaking the Licensed Material available under these terms andconditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
i. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
j. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
k. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
l. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to thefollowing conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
a. retain the following if it is supplied by the Licensor with the Licensed Material:
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights thatapply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does notreplace Your obligations under this Public License where the LicensedRights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its publiclicenses. Notwithstanding, Creative Commons may elect to apply one ofits public licenses to material it publishes and in those instanceswill be considered the “Licensor.” The text of the Creative Commonspublic licenses is dedicated to the public domain under the CC0 PublicDomain Dedication. Except for the limited purpose of indicating thatmaterial is shared under a Creative Commons public license or asotherwise permitted by the Creative Commons policies published atcreativecommons.org/policies, Creative Commons does not authorize theuse of the trademark "Creative Commons" or any other trademark or logoof Creative Commons without its prior written consent including,without limitation, in connection with any unauthorized modificationsto any of its public licenses or any other arrangements,understandings, or agreements concerning use of licensed material. Forthe avoidance of doubt, this paragraph does not form part of thepublic licenses.
Creative Commons may be contacted at creativecommons.org.
123456789101112131415# Third-party code notices
The Oobleck VAE and SnakeBeta implementation in `modeling_vae.py` is derivedfrom stable-audio-tools commit `a6ae0cdf8b2eb1567a4b42ceadddec3712d99d45`.The module hierarchy, weight normalization and activation equations preservethe checkpoint's original inference implementation.
- Oobleck / stable-audio-tools: Copyright (c) 2023 Stability AI, MIT. Full text: `licenses/stable-audio-tools-MIT.txt`.- SnakeBeta / BigVGAN: Copyright (c) 2022 NVIDIA CORPORATION, MIT. Full text: `licenses/SnakeBeta-NVIDIA-MIT.txt`.
These notices cover the identified source code and retain its original licenses.The YuE2 model checkpoint weights are separately licensed under CC BY-NC 4.0;see LICENSE for the scope and full terms. This does not relicense third-party code.123version https://git-lfs.github.com/spec/v1oid sha256:ed2fafd5c5208b09577974541a7979257d0d5fe10834a52a305eb6dbc50ede9dsize 800905604123version https://git-lfs.github.com/spec/v1oid sha256:fe5364d0b1edc4efa2ed64660f2d500cfd9795eb7de650e9ecc45f54c3f9fe66size 665015276123version https://git-lfs.github.com/spec/v1oid sha256:94d094c27ad52d8f44330c168be1c5a5e0835585288ec8e48d86eb48a0608a76size 665160716123version https://git-lfs.github.com/spec/v1oid sha256:51df9d4773b85e5c2513bca41aeff80b0bb0fb01471ad9e3afae1a05dc835291size 664869860123version https://git-lfs.github.com/spec/v1oid sha256:0a37f96055a34ce739c16d04fb227f80df094aaf9f19eaed223f2a6d7c3be0edsize 665005244123version https://git-lfs.github.com/spec/v1oid sha256:e79c11de804e1d230eafae0a2df6d4db9e031e9894aec4586e61ec452c67a4e7size 458920180123version https://git-lfs.github.com/spec/v1oid sha256:84ac4e2a156d42cf6a5c17aabdda62a8e9415050e525b5b5461a166fa1b2799asize 800861628123version https://git-lfs.github.com/spec/v1oid sha256:78744699634dd052ffa6e702a5b837f5175e0f129c91f955eaf7d2b7884ee5a7size 44298180123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195[
{
"engine": "ar_0.engine",
"inputs": [
"input_ids"
],
"outputs": [
"/embed_tokens/Gather_output_0"
]
},
{
"engine": "ar_1.engine",
"inputs": [
"input_ids",
"past_key_values.0.key",
"past_key_values.0.value",
"past_key_values.1.key",
"past_key_values.1.value",
"past_key_values.2.key",
"past_key_values.2.value",
"past_key_values.3.key",
"past_key_values.3.value",
"past_key_values.4.key",
"past_key_values.4.value",
"past_key_values.5.key",
"past_key_values.5.value",
"/embed_tokens/Gather_output_0"
],
"outputs": [
"/Cast_91_output_0",
"present.0.key",
"present.0.value",
"present.1.key",
"present.1.value",
"present.2.key",
"present.2.value",
"present.3.key",
"present.3.value",
"present.4.key",
"present.4.value",
"present.5.key",
"present.5.value"
]
},
{
"engine": "ar_2.engine",
"inputs": [
"input_ids",
"past_key_values.0.key",
"past_key_values.6.key",
"past_key_values.6.value",
"past_key_values.7.key",
"past_key_values.7.value",
"past_key_values.8.key",
"past_key_values.8.value",
"past_key_values.9.key",
"past_key_values.9.value",
"past_key_values.10.key",
"past_key_values.10.value",
"past_key_values.11.key",
"past_key_values.11.value",
"/Cast_91_output_0"
],
"outputs": [
"/Cast_175_output_0",
"present.6.key",
"present.6.value",
"present.7.key",
"present.7.value",
"present.8.key",
"present.8.value",
"present.9.key",
"present.9.value",
"present.10.key",
"present.10.value",
"present.11.key",
"present.11.value"
]
},
{
"engine": "ar_3.engine",
"inputs": [
"input_ids",
"past_key_values.0.key",
"past_key_values.12.key",
"past_key_values.12.value",
"past_key_values.13.key",
"past_key_values.13.value",
"past_key_values.14.key",
"past_key_values.14.value",
"past_key_values.15.key",
"past_key_values.15.value",
"past_key_values.16.key",
"past_key_values.16.value",
"past_key_values.17.key",
"past_key_values.17.value",
"/Cast_175_output_0"
],
"outputs": [
"/Cast_259_output_0",
"present.12.key",
"present.12.value",
"present.13.key",
"present.13.value",
"present.14.key",
"present.14.value",
"present.15.key",
"present.15.value",
"present.16.key",
"present.16.value",
"present.17.key",
"present.17.value"
]
},
{
"engine": "ar_4.engine",
"inputs": [
"input_ids",
"past_key_values.0.key",
"past_key_values.18.key",
"past_key_values.18.value",
"past_key_values.19.key",
"past_key_values.19.value",
"past_key_values.20.key",
"past_key_values.20.value",
"past_key_values.21.key",
"past_key_values.21.value",
"past_key_values.22.key",
"past_key_values.22.value",
"past_key_values.23.key",
"past_key_values.23.value",
"/Cast_259_output_0"
],
"outputs": [
"/Cast_343_output_0",
"present.18.key",
"present.18.value",
"present.19.key",
"present.19.value",
"present.20.key",
"present.20.value",
"present.21.key",
"present.21.value",
"present.22.key",
"present.22.value",
"present.23.key",
"present.23.value"
]
},
{
"engine": "ar_5.engine",
"inputs": [
"input_ids",
"past_key_values.0.key",
"past_key_values.24.key",
"past_key_values.24.value",
"past_key_values.25.key",
"past_key_values.25.value",
"past_key_values.26.key",
"past_key_values.26.value",
"past_key_values.27.key",
"past_key_values.27.value",
"/Cast_343_output_0"
],
"outputs": [
"/Cast_401_output_0",
"present.24.key",
"present.24.value",
"present.25.key",
"present.25.value",
"present.26.key",
"present.26.value",
"present.27.key",
"present.27.value"
]
},
{
"engine": "ar_6.engine",
"inputs": [
"/Cast_401_output_0"
],
"outputs": [
"/head/MatMul_output_0"
]
},
{
"engine": "ar_7.engine",
"inputs": [
"/head/MatMul_output_0"
],
"outputs": [
"logits"
]
}
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""TensorRT engines run on GPU buffers (Polygraphy's CUDA wrapper; no torch): a decoder's KV cache stays on the GPUbetween steps, and the activations between split engines (piecewise.py) never leave it.
from device_chain import Chain, Buffers step = Chain(folder, [{"engine": "gpt_step_0.engine"}, ...]) # or Chain.from_split(folder, "gpt_step") out = step({"token": np.array(...), "c_k0": cache_a["c_k0"], ...}, # numpy arrays are copied in, DeviceArrays used outputs={"n_k0": cache_b["n_k0"], ...}, # where these outputs go (else the chain's own) fetch=["logits"]) # -> {"logits": numpy array}
A tensor a call writes must not be one it reads: a cache is read from one set of buffers and written to another, andthe two sets swap after every step (Buffers.swap). Buffers are allocated at their largest shape once; a smaller shapereuses the allocation (DeviceArray.resize), so the steps allocate nothing."""from __future__ import annotations
import jsonfrom pathlib import Path
import numpy as np
def _cuda(): from polygraphy import cuda return cuda
def device_array(shape, dtype): """A DeviceArray of a numpy dtype (Polygraphy's DataType: numpy dtypes there are deprecated), which also keeps the numpy dtype (reading DeviceArray.dtype logs a deprecation warning on every call).""" from polygraphy.datatype import DataType a = _cuda().DeviceArray(shape=tuple(shape), dtype=DataType.from_dtype(np.dtype(dtype))) a.np_dtype = np.dtype(dtype) return a
def host_dtype(a) -> np.dtype: return a.np_dtype
class Engine: """One engine on device buffers. Its execution context holds device memory for the profile's largest shapes, or, with shared=True, none of its own: Chain gives all its engines one scratch buffer (they run one at a time on one stream), the size of the largest one's."""
def __init__(self, path, shared=False): import tensorrt as trt from trt_runner import lean_dlls lean_dlls() self.trt = trt runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING)) runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime engine = runtime.deserialize_cuda_engine(Path(path).read_bytes()) if engine is None: raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x " "and an RTX 30-series or newer GPU)") self.engine = engine if shared: self.context = engine.create_execution_context(trt.ExecutionContextAllocationStrategy.USER_MANAGED) self.scratch = engine.get_device_memory_size_for_profile_v2(0) else: self.context, self.scratch = engine.create_execution_context(), 0 names = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)] self.inputs = [n for n in names if engine.get_tensor_mode(n) == trt.TensorIOMode.INPUT] self.outputs = [n for n in names if engine.get_tensor_mode(n) == trt.TensorIOMode.OUTPUT] self.dtype = {n: np.dtype(trt.nptype(engine.get_tensor_dtype(n))) for n in names}
def enqueue(self, inputs: dict, outputs: dict, stream) -> None: """inputs / outputs: name -> DeviceArray. Each output is resized to its shape for these inputs.""" c = self.context for n in self.inputs: a = inputs[n] c.set_input_shape(n, tuple(a.shape)) c.set_tensor_address(n, a.ptr) for n in self.outputs: o = outputs[n] o.resize(tuple(c.get_tensor_shape(n))) c.set_tensor_address(n, o.ptr) if not c.execute_async_v3(stream.ptr): raise RuntimeError("TensorRT execution failed")
def use_memory(self, buf) -> None: self.context.set_device_memory(buf.ptr, self.scratch)
def close(self): self.context = self.engine = None
class Chain: """Engines run in order on one CUDA stream; each reads the call's inputs and earlier engines' outputs by name."""
def __init__(self, folder, plan: list[dict], shared_memory=True): self.folder, self.plan, self.engines = Path(folder), plan, [] self.pool = {} # the chain's own buffers, by tensor name self.stream = None self.shared = shared_memory # one scratch buffer for all the engines' activations
@classmethod def from_split(cls, folder, part: str): """<part>_split.json (the engines in order) if the part was split, else <part>.engine alone.""" f = Path(folder) / f"{part}_split.json" return cls(folder, json.loads(f.read_text()) if f.exists() else [{"engine": f"{part}.engine"}])
def load(self): if not self.engines: self.stream = _cuda().Stream() self.engines = [Engine(self.folder / p["engine"], self.shared) for p in self.plan] if self.shared: scratch = self.pool["scratch"] = device_array((max(1, *(e.scratch for e in self.engines)),), np.uint8) for e in self.engines: e.use_memory(scratch) return self
def buffer(self, name: str, dtype, shape=(1,)): """The chain's own buffer for a tensor (allocated on first use, at least one element).""" b = self.pool.get(name) if b is None: b = self.pool[name] = device_array(tuple(max(1, d) for d in shape) or (1,), dtype) return b
def __call__(self, feeds: dict, outputs: dict | None = None, fetch=()) -> dict: self.load() outputs = outputs or {} env, keep = {}, [] for n, v in feeds.items(): if isinstance(v, np.ndarray): # host -> a pooled device buffer of the engine's dtype want = next((e.dtype[n] for e in self.engines if n in e.dtype), v.dtype) h = np.ascontiguousarray(v, dtype=want) b = self.buffer("in:" + n, want, h.shape) b.resize(h.shape) b.copy_from(h, self.stream) keep.append(h) # alive until the stream has copied it env[n] = b else: env[n] = v for e in self.engines: outs = {n: outputs[n] if n in outputs else self.buffer(n, e.dtype[n]) for n in e.outputs} e.enqueue(env, outs, self.stream) env.update(outs) res = {} for n in fetch: a = env[n] res[n] = np.empty(tuple(a.shape), dtype=host_dtype(a)) a.copy_to(res[n], self.stream) self.stream.synchronize() return res
def close(self): for e in self.engines: e.close() for b in self.pool.values(): b.free() self.engines, self.pool = [], {}
class Buffers: """Two sets of device buffers for a decoder's caches, each allocated at the largest shape: step k reads set A and writes set B, then swap() exchanges them."""
def __init__(self, names_in: list[str], names_out: list[str], dtype, max_shape): self.names_in, self.names_out = names_in, names_out self.a = [device_array(max_shape, dtype) for _ in names_in] self.b = [device_array(max_shape, dtype) for _ in names_in]
def reads(self) -> dict: return dict(zip(self.names_in, self.a))
def writes(self) -> dict: return dict(zip(self.names_out, self.b))
def swap(self): self.a, self.b = self.b, self.a
def reset(self, shape): """Set A as an empty cache of this shape (e.g. [1, 0, 256] before a prefill): no copy, no allocation.""" for buf in self.a: buf.resize(tuple(shape))
def load(self, arrays, stream=None): """Fill set A from host arrays (the prompt's cache).""" for buf, x in zip(self.a, arrays): x = np.ascontiguousarray(x, dtype=host_dtype(buf)) buf.resize(x.shape) buf.copy_from(x, stream)
def free(self): for b in self.a + self.b: b.free() self.a = self.b = []123456789101112131415161718192021MIT License
Copyright (c) 2022 NVIDIA CORPORATION.
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021MIT License
Copyright (c) 2023 Stability AI
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123version https://git-lfs.github.com/spec/v1oid sha256:fee3de79de23d67ab63b36fbece94ca6dddef3bf39f9ec216f0d146ecd8bc509size 698557284123version https://git-lfs.github.com/spec/v1oid sha256:2dde1137935dd4545d995bcd60611db312f6877d113e0438bdea1293b1053104size 737176644123version https://git-lfs.github.com/spec/v1oid sha256:e9ad79f29145e0a8beb8af1cd376d376fe622188c8a2e426ba5b5e803f84e500size 687461820123version https://git-lfs.github.com/spec/v1oid sha256:5272a51489cf54b5a3ec40d9dc473bc0dd38056e18523ca6207997735d909cd0size 737193772123version https://git-lfs.github.com/spec/v1oid sha256:74ca548736a8fa8442d053a6afefc3ef7b650fb0e637df672ab2592f2c3b472esize 354072204123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112[
{
"engine": "nar_0.engine",
"inputs": [
"x_t",
"t",
"past.0.key",
"past.0.value",
"past.1.key",
"past.1.value",
"past.2.key",
"past.2.value",
"past.3.key",
"past.3.value",
"past.4.key",
"past.4.value",
"past.5.key",
"past.5.value"
],
"outputs": [
"/Cast_99_output_0"
]
},
{
"engine": "nar_1.engine",
"inputs": [
"x_t",
"past.0.key",
"past.6.key",
"past.6.value",
"past.7.key",
"past.7.value",
"past.8.key",
"past.8.value",
"past.9.key",
"past.9.value",
"past.10.key",
"past.10.value",
"past.11.key",
"past.11.value",
"/Cast_99_output_0"
],
"outputs": [
"/Cast_193_output_0"
]
},
{
"engine": "nar_2.engine",
"inputs": [
"x_t",
"past.0.key",
"past.12.key",
"past.12.value",
"past.13.key",
"past.13.value",
"past.14.key",
"past.14.value",
"past.15.key",
"past.15.value",
"past.16.key",
"past.16.value",
"past.17.key",
"past.17.value",
"past.18.key",
"past.18.value",
"/Cast_193_output_0"
],
"outputs": [
"/Cast_294_output_0"
]
},
{
"engine": "nar_3.engine",
"inputs": [
"x_t",
"past.0.key",
"past.19.key",
"past.19.value",
"past.20.key",
"past.20.value",
"past.21.key",
"past.21.value",
"past.22.key",
"past.22.value",
"past.23.key",
"past.23.value",
"past.24.key",
"past.24.value",
"/Cast_294_output_0"
],
"outputs": [
"/Cast_388_output_0"
]
},
{
"engine": "nar_4.engine",
"inputs": [
"x_t",
"past.0.key",
"past.25.key",
"past.25.value",
"past.26.key",
"past.26.value",
"past.27.key",
"past.27.value",
"/Cast_388_output_0"
],
"outputs": [
"velocity"
]
}
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354"""YuE2-3B with ONNX Runtime: text-to-song (style + lyrics -> 48 kHz stereo). The AR tower (score + semantic codes),the NAR flow-matching velocity and the VAE decoder as ONNX graphs; numpy around them, following the officialyue2_infer 0.1.5 pipeline:- the prompt: the native instruction for the CoT mode, [Tags] style, [Lyrics] (the checkpoint's own tiktoken BPE);- the ABC score (cot "full" / "melody") and then the semantic codes, sampled as the original samples them (allowed tokens, minimum length, windowed repetition penalty, temperature, top-k, top-p);- the acoustic latents: the codes' context chunks, the AR prefix cache, a 32-step midpoint ODE of the NAR velocity from Gaussian noise (the original's ODE state is bf16; this runtime rounds it the same way);- the VAE decoded in 512-frame tiles with a 16-frame halo (exact cores, no crossfade).
Needs numpy, onnxruntime (onnxruntime-gpu for CUDA), tiktoken; soundfile to write FLAC (else a 16-bit WAV).
python fp16/pipeline.py --style "Acoustic folk, warm male vocal" --lyrics lyrics.txt song.flac [--cuda]"""
from __future__ import annotations
import base64import mathimport unicodedataimport wavefrom pathlib import Path
import numpy as np
EOD = 151643ABC_START, ABC_END = 151847, 151848MUSIC_START, MUSIC_END = 151851, 151852CODEC_OFFSET, CODEC_SIZE = 151853, 32768VOCAB, CONTEXT = 184704, 24576SAMPLE_RATE, RATIO = 48000, 1920INSTRUCTIONS = { "off": "Generate music with codec tokens from the given conditions.", "melody": "Generate a melody-only ABC transcription without chord symbols, then generate music with codec tokens " "from the given conditions.", "full": "Generate a chord-annotated ABC transcription, then generate music with codec tokens from the given " "conditions.",}ABC_SAMPLING = dict(temperature=0.7, top_p=0.9, top_k=30, repetition_penalty=1.005, penalty_window=100, min_tokens=32, max_tokens=4096)SEMANTIC_SAMPLING = dict(temperature=1.0, top_p=0.95, top_k=100, repetition_penalty=1.2, penalty_window=50, min_tokens=200, max_tokens=9000)ODE_STEPS = 32PREFILL_CHUNK = 512VAE_CORE, VAE_HALO = 512, 16
class Tokenizer: """yue2.tokenization_yue2.YuE2TextTokenizer: the checkpoint-native qwen.tiktoken BPE (ordinary tokens only).""" PAT = (r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|" r"\s+(?!\S)|\s+")
def __init__(self, path): import tiktoken ranks = {base64.b64decode(t): int(r) for t, r in (line.split() for line in Path(path).read_bytes().splitlines() if line)} specials = ["<|endoftext|>", "<|im_start|>", "<|im_end|>", "<R>", "<S>", "<X>", "<mask>", "<sep>"] specials += [f"<extra_{i}>" for i in range(200)] specials[204:206] = ["<abc>", "</abc>"] self.enc = tiktoken.Encoding("YuE2", pat_str=self.PAT, mergeable_ranks=ranks, special_tokens={s: i + len(ranks) for i, s in enumerate(specials)})
def encode(self, text): return self.enc.encode_ordinary(unicodedata.normalize("NFC", text))
def decode(self, ids): return self.enc.decode([int(i) for i in ids if 0 <= i < self.enc.n_vocab], errors="replace")
def request_text(style, lyrics, cot): return f"{INSTRUCTIONS[cot]}\n[Tags]\n{style}\n[Lyrics]\n{lyrics}\n"
def prefixes(tok, style, lyrics, cot="full", abc_ids=None): """protocol.token_prefixes: the ABC-stage prefix (abc_ids None) or the semantic-stage prefix.""" base = [EOD] + tok.encode(request_text(style, lyrics, cot)) if cot == "off": return base + [ABC_START, ABC_END, MUSIC_START] if abc_ids is None: return base + [ABC_START] return base + [ABC_START] + list(abc_ids) + [ABC_END, MUSIC_START]
def distribution(logits, s, history, step, phase): """yue2.sampling.distribution (fp32): allowed tokens, minimum length, windowed repetition penalty, temperature, top-k, top-p. Returns the scores (-inf where removed).""" x = np.asarray(logits, np.float32).copy() end = ABC_END if phase == "abc" else MUSIC_END allowed = np.full(VOCAB, -np.inf, np.float32) if phase == "abc": allowed[:EOD] = 0 else: allowed[CODEC_OFFSET:CODEC_OFFSET + CODEC_SIZE] = 0 allowed[end] = 0 x = x + allowed if step < s["min_tokens"]: x[end] = -np.inf recent = history[-s["penalty_window"]:] if s["penalty_window"] else [] if s["repetition_penalty"] != 1.0 and len(recent): ids, counts = np.unique(np.asarray(recent, np.int64), return_counts=True) alpha = np.power(np.float32(s["repetition_penalty"]), counts.astype(np.float32)).astype(np.float32) v = x[ids] x[ids] = np.where(v < 0, v * alpha, v / alpha) if s["temperature"] == 0: return x if s["temperature"] != 1: x = x / np.float32(s["temperature"]) k = min(int(s["top_k"]), VOCAB) kth = np.partition(x, VOCAB - k)[VOCAB - k] x = np.where(x < kth, np.float32(-np.inf), x) if s["top_p"] < 1: order = np.argsort(-x, kind="stable") v = x[order] e = np.exp(v - v[0]) p = e / e.sum(dtype=np.float32) removed = np.cumsum(p, dtype=np.float32) - p > np.float32(s["top_p"]) removed[:1] = False v = np.where(removed, np.float32(-np.inf), v) x = np.empty_like(x) x[order] = v return x
def softmax(x): e = np.exp(x - x.max()) return (e / e.sum()).astype(np.float32)
def draw(probs, u): c = np.cumsum(probs.astype(np.float64)) return min(int(np.searchsorted(c, u * c[-1], side="right")), len(probs) - 1)
def bf16(x): """Round float32 to the nearest bfloat16 (ties to even), as float32.""" b = np.asarray(x, np.float32).view(np.uint32) b = (b + 0x7FFF + ((b >> 16) & 1)) & 0xFFFF0000 return b.astype(np.uint32).view(np.float32)
def shifted_t(raw): """YuE2ForCausalLM._shift_t_value with timestep_shift 1, in bf16 as the original computes it.""" t = float(bf16(np.float32(raw))) return float(bf16(np.float32(1.0 / (1.0 + math.exp(-t)))))
def chunk_ranges(frames, prefix_tokens, context=CONTEXT): size = min((context - prefix_tokens - 3) // 2, CONTEXT) return [(a, min(a + size, frames)) for a in range(0, frames, size)]
class YuE2: def __init__(self, folder, provider="cpu", emulate_bf16=True, low_memory=True): import onnxruntime as ort self.folder, self.ort = Path(folder), ort self.tok = Tokenizer(self.folder / "qwen.tiktoken") if provider != "cpu" and hasattr(ort, "preload_dlls"): try: ort.preload_dlls() except Exception: pass self.dev = "cpu" if provider == "cpu" else "cuda" self.pv = ["CPUExecutionProvider"] if provider == "cpu" else [ ("CUDAExecutionProvider", {"arena_extend_strategy": "kSameAsRequested", "use_tf32": "0"}), "CPUExecutionProvider"] self.ro = ort.RunOptions() if provider != "cpu": self.ro.add_run_config_entry("memory.enable_memory_arena_shrinkage", "gpu:0") self.s = {} self.emulate_bf16 = emulate_bf16 self.low_memory = low_memory # one large graph at a time (AR, NAR, VAE)
def session(self, name): """Sessions on first use; the AR and NAR graphs keep their residual stream in fp32, which ONNX Runtime's extended-level fusions would fold back to fp16: those two open at the basic level.""" if name not in self.s: so = self.ort.SessionOptions() so.log_severity_level = 3 if name in ("ar", "nar"): so.graph_optimization_level = self.ort.GraphOptimizationLevel.ORT_ENABLE_BASIC self.s[name] = self.ort.InferenceSession(str(self.folder / f"{name}.onnx"), so, providers=self.pv) if name == "ar": ar = self.s["ar"] self.past_names = [i.name for i in ar.get_inputs() if i.name.startswith("past_key_values.")] self.present_names = [o.name for o in ar.get_outputs() if o.name.startswith("present.")] pk = next(i for i in ar.get_inputs() if i.name == self.past_names[0]) self.kv_dt = np.float16 if pk.type == "tensor(float16)" else np.float32 return self.s[name]
def release(self, name): self.s.pop(name, None)
# AR def _ar(self, ids, cache): ar = self.session("ar") io = ar.io_binding() io.bind_cpu_input("input_ids", np.asarray([ids], np.int64)) for n, v in zip(self.past_names, cache): io.bind_ortvalue_input(n, v) io.bind_output("logits", "cpu") for n in self.present_names: io.bind_output(n, self.dev) ar.run_with_iobinding(io, self.ro) o = io.get_outputs() return o[0].numpy()[0], o[1:]
def prefill(self, ids): self.session("ar") cache = [self.ort.OrtValue.ortvalue_from_numpy(np.zeros((1, 8, 0, 128), self.kv_dt), self.dev, 0) for _ in self.past_names] logits = None for a in range(0, len(ids), PREFILL_CHUNK): logits, cache = self._ar(ids[a:a + PREFILL_CHUNK], cache) return logits, cache
def generate(self, prefix, sampling, phase, uniforms=None, forced=None, seed=None, on_logits=None): """generate_tokens: returns (tokens without the end token, truncated, drawn tokens). uniforms: draws to replay; forced: tokens to feed instead of the drawn ones (teacher forcing); on_logits(step, logits): each step's raw logits.""" rng = np.random.default_rng(seed) logits, cache = self.prefill(prefix) end = ABC_END if phase == "abc" else MUSIC_END history, drawn, eos = [], [], False for step in range(sampling["max_tokens"]): if on_logits is not None: on_logits(step, logits) sc = distribution(logits, sampling, history, step, phase) u = uniforms[step] if uniforms is not None and step < len(uniforms) else rng.random() t = int(np.argmax(sc)) if sampling["temperature"] == 0 else draw(softmax(sc), u) drawn.append(t) if forced is not None: if step >= len(forced): break t = int(forced[step]) if t == end: eos = True break history.append(t) if step + 1 < sampling["max_tokens"]: logits, cache = self._ar([t], cache) return history, not eos, drawn
# NAR def synthesize(self, prefix, codec, noise): """nar.synthesize: per context chunk, the AR cache of prefix + its codes + MUSIC_END, then the midpoint ODE (t from 1 to 0, 32 steps) of the NAR velocity. noise [frames, 64] (the original draws it with torch's CPU generator from the seed).""" out = [] for a, b in chunk_ranges(len(codec), len(prefix)): ar_tokens = list(prefix) + [int(v) + CODEC_OFFSET for v in codec[a:b]] + [MUSIC_END] _, cache = self.prefill(ar_tokens) if self.low_memory: # the AR and NAR graphs never resident together: the cache via system memory host = [c.numpy() for c in cache] cache = None self.release("ar") cache = [self.ort.OrtValue.ortvalue_from_numpy(h, self.dev, 0) for h in host] host = None out.append(self._ode(noise[a:b], cache)) if self.low_memory: cache = None self.release("nar") return np.concatenate(out)
def _velocity(self, state, t, cache): nar = self.session("nar") io = nar.io_binding() io.bind_cpu_input("x_t", np.ascontiguousarray(state, np.float32)) io.bind_cpu_input("t", np.asarray([t], np.float32)) for i, v in enumerate(cache): io.bind_ortvalue_input(f"past.{i // 2}.{'key' if i % 2 == 0 else 'value'}", v) io.bind_output("velocity", "cpu") nar.run_with_iobinding(io, self.ro) v = io.get_outputs()[0].numpy() return bf16(v) if self.emulate_bf16 else v
def _ode(self, noise, cache): r = bf16 if self.emulate_bf16 else (lambda z: np.asarray(z, np.float32)) state = r(noise) dt = 1.0 / ODE_STEPS for step in range(ODE_STEPS): t = 1.0 - step * dt raw = min(max(math.log(t / (1 - t)) if 0 < t < 1 else (20.0 if t >= 1 else -20.0), -20.0), 20.0) first = self._velocity(state, shifted_t(raw), cache) mid = r(state - r(first * np.float32(dt / 2))) tm = t - dt / 2 raw_mid = min(max(math.log(tm / (1 - tm)), -20.0), 20.0) state = r(state - r(self._velocity(mid, shifted_t(raw_mid), cache) * np.float32(dt))) return state.astype(np.float32)
# VAE def decode(self, latents): """YuE2VAE.decode_tiled (512-frame cores, 16-frame halo): [frames, 64] -> audio [samples, 2] in [-1, 1].""" vae = self.session("vae") z = np.ascontiguousarray(np.asarray(latents, np.float32).T[None]) frames = z.shape[-1] total = RATIO * frames - 64 audio = np.empty((2, total), np.float32) for start in range(0, frames, VAE_CORE): end = min(frames, start + VAE_CORE) left, right = max(0, start - VAE_HALO), min(frames, end + VAE_HALO) tile = vae.run(None, {"latents": np.ascontiguousarray(z[..., left:right])}, self.ro)[0][0] o0, o1 = start * RATIO, min(end * RATIO, total) c0 = (start - left) * RATIO audio[:, o0:o1] = tile[:, c0:c0 + o1 - o0] return np.clip(audio, -1, 1).T.copy()
def __call__(self, style, lyrics, cot="full", seed=None, abc=None, abc_sampling=None, semantic_sampling=None): rng = np.random.default_rng(seed) abc_ids = self.tok.encode(abc) if abc is not None else None if cot != "off" and abc_ids is None: abc_ids, _, _ = self.generate(prefixes(self.tok, style, lyrics, cot), {**ABC_SAMPLING, **(abc_sampling or {})}, "abc", seed=int(rng.integers(2**63))) prefix = prefixes(self.tok, style, lyrics, cot, abc_ids) codes, _, _ = self.generate(prefix, {**SEMANTIC_SAMPLING, **(semantic_sampling or {})}, "semantic", seed=int(rng.integers(2**63))) codec = [t - CODEC_OFFSET for t in codes] noise = rng.standard_normal((len(codec), 64)).astype(np.float32) latents = self.synthesize(prefix, codec, noise) self.release("ar") self.release("nar") audio = self.decode(latents) self.release("vae") return audio, {"abc": self.tok.decode(abc_ids) if abc_ids else None, "codec": codec}
def save_audio(path, audio): try: import soundfile as sf sf.write(str(path), audio, SAMPLE_RATE) except ImportError: with wave.open(str(Path(path).with_suffix(".wav")), "wb") as w: w.setnchannels(2) w.setsampwidth(2) w.setframerate(SAMPLE_RATE) w.writeframes((np.clip(audio, -1, 1) * 32767).astype("<i2").tobytes())
if __name__ == "__main__": import argparse ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--style", required=True) ap.add_argument("--lyrics", required=True, help="lyrics text or a file holding them") ap.add_argument("out") ap.add_argument("--cot", default="full", choices=list(INSTRUCTIONS)) ap.add_argument("--abc", help="an ABC score file to use instead of generating one") ap.add_argument("--seed", type=int) ap.add_argument("--dir", default=str(Path(__file__).resolve().parent)) ap.add_argument("--cuda", action="store_true") a = ap.parse_args() lyr = Path(a.lyrics).read_text(encoding="utf-8") if Path(a.lyrics).is_file() else a.lyrics abc = Path(a.abc).read_text(encoding="utf-8") if a.abc else None audio, info = YuE2(a.dir, "cuda" if a.cuda else "cpu")(a.style, lyr, a.cot, a.seed, abc) save_audio(a.out, audio) print(f"{len(audio) / SAMPLE_RATE:.1f} s written")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""YuE2-3B with TensorRT: the ONNX build's pipeline.py (the official YuE2Pipeline: score, codes, the NAR's midpointODE, the tiled VAE) with its graphs run as the engines in this folder:
ar_0..k.engine the AR tower (ar_split.json): input_ids [1, S], past_key_values.{i}.key / .value [1, 8, P, 128] (fp16) -> logits of the last position [1, 184704], present.* nar_0..k.engine the NAR velocity (nar_split.json): x_t [T, 64], t [1], past.{i}.key / .value [1, 8, L, 128] (the AR cache of the prompt and the chunk's codes) -> velocity [T, 64] vae.engine the Oobleck decoder on pipeline.py's tiles (512 latent frames + 16 on each side)
The AR's KV cache stays on the GPU (device_chain.py): two buffer sets, a call reading one and writing the longercache into the other. For a chunk's NAR, the AR engines are released and the NAR reads that cache where it is. Limitsof the engines: the AR's prompt (style, lyrics, score) plus its codes up to 6,144 positions (generation stopsthere: about 3 minutes of music after a typical prompt), and a NAR chunk up to 5,120 frames. Needs numpy, tiktoken,tensorrt-cu12 / tensorrt-lean-cu12 10.13 and polygraphy.
python pipeline_trt.py "style tags" lyrics.txt out.flac [--seed 0]"""
from __future__ import annotations
import sysfrom pathlib import Path
import numpy as np
HERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE))from device_chain import Buffers, Chain # noqa: E402from pipeline import * # noqa: E402,F401,F403 (prefixes, samplings, save_audio, ... for callers)from pipeline import PREFILL_CHUNK, CODEC_OFFSET, MUSIC_END, Tokenizer, YuE2, bf16, chunk_ranges # noqa: E402from trt_runner import OrtLike # noqa: E402
LAYERS = 28MAX_CACHE, MAX_FRAMES = 6144, 5120KV = [f"{i}.{kv}" for i in range(LAYERS) for kv in ("key", "value")]
class YuE2Trt(YuE2): def __init__(self, folder=HERE, emulate_bf16=True): self.folder = Path(folder) self.tok = Tokenizer(self.folder / "qwen.tiktoken") self.emulate_bf16 = emulate_bf16 self.low_memory = True # one tower's engines at a time self.s, self.ro = {}, None self.kv, self.kv_len = None, 0
def session(self, name): if name not in self.s: self.s[name] = (Chain.from_split(self.folder, name).load() if name in ("ar", "nar") else OrtLike(self.folder / "vae.engine", ["audio"], allocation="static")) return self.s[name]
def release(self, name): x = self.s.pop(name, None) if isinstance(x, Chain): x.close() elif x is not None: x.e.close()
# AR: the cache in self.kv on the GPU; `cache` is only a token def _ar(self, ids, cache): n = len(ids) if self.kv_len + n > MAX_CACHE: raise ValueError(f"AR: {self.kv_len} cached + {n} new positions; the engines take up to {MAX_CACHE}") out = self.session("ar")({"input_ids": np.asarray([ids], np.int64), **self.kv.reads()}, outputs=self.kv.writes(), fetch=["logits"]) self.kv.swap() self.kv_len += n return out["logits"][0], "gpu"
def prefill(self, ids): self.session("ar") if self.kv is None: self.kv = Buffers([f"past_key_values.{n}" for n in KV], [f"present.{n}" for n in KV], np.float16, (1, 8, MAX_CACHE, 128)) self.kv.reset((1, 8, 0, 128)) self.kv_len = 0 logits = None for a in range(0, len(ids), PREFILL_CHUNK): logits, _ = self._ar(ids[a:a + PREFILL_CHUNK], None) return logits, "gpu"
def generate(self, prefix, sampling, phase, **kw): room = MAX_CACHE - len(prefix) - 1 # the cache holds the prompt and the tokens fed back if room < sampling["max_tokens"]: sampling = {**sampling, "max_tokens": max(1, room)} return super().generate(prefix, sampling, phase, **kw)
# NAR: the chunk's AR cache read where it is def synthesize(self, prefix, codec, noise): out = [] for a, b in chunk_ranges(len(codec), len(prefix)): if b - a > MAX_FRAMES: raise ValueError(f"NAR: a chunk of {b - a} frames; the engines take up to {MAX_FRAMES}") self.prefill(list(prefix) + [int(v) + CODEC_OFFSET for v in codec[a:b]] + [MUSIC_END]) self.release("ar") cache = {f"past.{n}": buf for n, buf in zip(KV, self.kv.reads().values())} out.append(self._ode(noise[a:b], cache)) self.release("nar") self.kv.free() self.kv = None return np.concatenate(out)
def _velocity(self, state, t, cache): v = self.session("nar")({"x_t": np.ascontiguousarray(state, np.float32), "t": np.asarray([t], np.float32), **cache}, fetch=["velocity"])["velocity"] return bf16(v) if self.emulate_bf16 else v
def close(self): for n in list(self.s): self.release(n) if self.kv is not None: self.kv.free() self.kv = None
if __name__ == "__main__": import argparse ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("style"); ap.add_argument("lyrics"); ap.add_argument("output") ap.add_argument("--dir", default=str(HERE)); ap.add_argument("--seed", type=int, default=None) a = ap.parse_args() yue = YuE2Trt(a.dir) audio, info = yue(a.style, Path(a.lyrics).read_text(encoding="utf-8"), seed=a.seed) save_audio(a.output, audio) # noqa: F4051234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798"""A minimal TensorRT engine runner: numpy in, numpy out (tensorrt-cu12 10.x and polygraphy; no torch).
from trt_runner import Engine e = Engine("model.engine") out = e({"input": x}) # dict of output name -> numpy array"""from __future__ import annotations
from pathlib import Path
import numpy as np
def lean_dlls(): """Version-compatible engines are built against and run on TensorRT's lean runtime (pip tensorrt-lean-cu12): put its DLL folder on the search path (Windows).""" import importlib.util import os spec = importlib.util.find_spec("tensorrt_lean_libs") if spec and spec.submodule_search_locations: d = list(spec.submodule_search_locations)[0] os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "") if hasattr(os, "add_dll_directory"): os.add_dll_directory(d)
class Engine: """allocation: "static" (memory for the profiles' largest shapes, reserved once) or "runtime" (sized to each call's shapes: for pipelines of many engines with wide profiles, which would otherwise reserve every engine's maximum)."""
def __init__(self, path, allocation="static"): lean_dlls() import tensorrt as trt from polygraphy.backend.trt import TrtRunner self.trt = trt logger = trt.Logger(trt.Logger.WARNING) runtime = trt.Runtime(logger) runtime.engine_host_code_allowed = True # version-compatible engines carry their own lean runtime engine = runtime.deserialize_cuda_engine(Path(path).read_bytes()) if engine is None: raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x " "and an RTX 30-series or newer GPU)") self.engine = engine self.runner = TrtRunner(engine, allocation_strategy=allocation) self.runner.activate() self.inputs = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors) if engine.get_tensor_mode(engine.get_tensor_name(i)) == trt.TensorIOMode.INPUT]
def __call__(self, feed: dict) -> dict: feed = {k: np.ascontiguousarray(v) for k, v in feed.items() if k in self.inputs} out = self.runner.infer(feed, check_inputs=True) return {k: np.array(v) for k, v in out.items()}
def close(self): """Release the engine's device memory and weights now (deactivating the runner alone keeps the weights on the GPU until the engine object is collected).""" runner = getattr(self, "runner", None) if runner is not None and runner.is_active: runner.deactivate() self.runner = self.engine = None
def __del__(self): try: self.close() except Exception: pass
class OrtLike: """An engine behind onnxruntime's InferenceSession calls (run / get_inputs / get_outputs / get_providers), so a pipeline.py written for ONNX Runtime runs its graphs on TensorRT unchanged. Outputs come back in the order the ONNX graph listed them (pass `outputs`), else in the engine's order."""
def __init__(self, path, outputs=None, allocation="static"): self.e = Engine(path, allocation) eng = self.e.engine names = [eng.get_tensor_name(i) for i in range(eng.num_io_tensors)] self.outs = list(outputs) if outputs else [n for n in names if n not in self.e.inputs]
def get_inputs(self): """name, type ("tensor(float16)" etc., as onnxruntime spells it) and shape (-1 for dynamic dimensions).""" from types import SimpleNamespace eng, trt = self.e.engine, self.e.trt names = {trt.float16: "float16", trt.float32: "float", trt.int64: "int64", trt.int32: "int32", trt.bool: "bool", trt.int8: "int8", trt.bfloat16: "bfloat16"} return [SimpleNamespace(name=n, type=f"tensor({names.get(eng.get_tensor_dtype(n), 'float')})", shape=list(eng.get_tensor_shape(n))) for n in self.e.inputs]
def get_outputs(self): from types import SimpleNamespace return [SimpleNamespace(name=n) for n in self.outs]
def get_providers(self): return ["TensorRT"]
def run(self, names, feed, run_options=None): out = self.e(feed) return [out[n] for n in (names or self.outs)]123version https://git-lfs.github.com/spec/v1oid sha256:649aea2f85c49a5bdb86b2439e68dc57b120e8632b2b36be8dd04764a9a5c904size 334955084.gitattributes+14
fp16/LICENSE.txtAdded+429
fp16/THIRD_PARTY_NOTICES.mdAdded+15
fp16/ar_0.engineAdded+3
fp16/ar_1.engineAdded+3
fp16/ar_2.engineAdded+3
fp16/ar_3.engineAdded+3
fp16/ar_4.engineAdded+3
fp16/ar_5.engineAdded+3
fp16/ar_6.engineAdded+3
fp16/ar_7.engineAdded+3
fp16/ar_split.jsonAdded+195
fp16/device_chain.pyAdded+188
fp16/licenses/SnakeBeta-NVIDIA-MIT.txtAdded+21
fp16/licenses/stable-audio-tools-MIT.txtAdded+21
fp16/nar_0.engineAdded+3
fp16/nar_1.engineAdded+3
fp16/nar_2.engineAdded+3
fp16/nar_3.engineAdded+3
fp16/nar_4.engineAdded+3
fp16/nar_split.jsonAdded+112
fp16/pipeline.pyAdded+354
fp16/pipeline_trt.pyAdded+125
fp16/qwen.tiktokenAdded
fp16/trt_runner.pyAdded+98
fp16/vae.engineAdded+3