Add ExecuTorch WebGPU program for phonon-31m-en
Browse files- .gitattributes +2 -0
- LICENSE +202 -0
- NOTICE +6 -0
- README.md +93 -0
- export/_common.py +330 -0
- export/_phonon.py +910 -0
- export/_whisper.py +662 -0
- export/phonon-31m-en.py +585 -0
- export/recipe.json +205 -0
- export/requirements.txt +15 -0
- manifest.json +46 -0
- phonon.json +482 -0
- phonon_bos_embed.f32.bin +3 -0
- phonon_flow_lm.pte +3 -0
- phonon_mimi.pte +3 -0
- phonon_text_embed.bf16.bin +3 -0
- tokenizer.json +0 -0
- voice_default.f32.bin +3 -0
- voice_en_us_easton.f32.bin +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ 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 |
+
phonon_flow_lm.pte filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
phonon_mimi.pte filter=lfs diff=lfs merge=lfs -text
|
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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PRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright [yyyy] [name of copyright owner]
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
This repository contains a modified version of gradium/phonon-31m-en.
|
| 2 |
+
|
| 3 |
+
Modifications by Meta Platforms, Inc.: conversion to the ExecuTorch program format (.pte) for the
|
| 4 |
+
ExecuTorch WebGPU backend.
|
| 5 |
+
|
| 6 |
+
The original work and these modifications are distributed under the license in LICENSE.
|
README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
base_model:
|
| 4 |
+
- gradium/phonon-31m-en
|
| 5 |
+
library_name: executorch
|
| 6 |
+
pipeline_tag: text-to-speech
|
| 7 |
+
inference: false
|
| 8 |
+
tags:
|
| 9 |
+
- executorch
|
| 10 |
+
- webgpu
|
| 11 |
+
- on-device
|
| 12 |
+
- browser
|
| 13 |
+
---
|
| 14 |
+
# Phonon 31M (English) for ExecuTorch WebGPU
|
| 15 |
+
|
| 16 |
+
This repository contains an [ExecuTorch](https://github.com/pytorch/executorch) conversion of
|
| 17 |
+
[gradium/phonon-31m-en](https://huggingface.co/gradium/phonon-31m-en) for the ExecuTorch **WebGPU** backend, so the model runs entirely in a web browser on
|
| 18 |
+
the visitor's GPU. It powers the corresponding demo in the [ExecuTorch WebGPU Playground](https://executorch.ai/playground/).
|
| 19 |
+
|
| 20 |
+
- **Base model:** [gradium/phonon-31m-en](https://huggingface.co/gradium/phonon-31m-en)
|
| 21 |
+
- **Format:** ExecuTorch `.pte` programs delegated to the WebGPU backend
|
| 22 |
+
- **Quantization:** fp32 programs; the text embedding table is stored as bf16 (its values are exactly representable in bf16)
|
| 23 |
+
- **Total size:** 150.7 MB
|
| 24 |
+
|
| 25 |
+
> **Note:** The voices are from gradium/phonon-voices (Apache-2.0); each is stored here as its 125-frame voice prompt projected into the model.
|
| 26 |
+
|
| 27 |
+
## About the original model
|
| 28 |
+
|
| 29 |
+
An English text-to-speech model that streams natural 24 kHz speech while it is still generating. A flow-matching transformer predicts an audio latent for each 80 ms frame from the text and a voice prompt, and the Mimi codec's decoder turns the latents into audio.
|
| 30 |
+
|
| 31 |
+
- **Developed by:** Gradium (builds on Pocket TTS and the Mimi codec by Kyutai)
|
| 32 |
+
- 31M parameters (excluding the audio tokenizer)
|
| 33 |
+
- English
|
| 34 |
+
- Mono 24 kHz output, one 80 ms frame per step
|
| 35 |
+
|
| 36 |
+
For training data, evaluation results and full details, see the original model card: [gradium/phonon-31m-en](https://huggingface.co/gradium/phonon-31m-en).
|
| 37 |
+
|
| 38 |
+
## Intended use and limitations
|
| 39 |
+
|
| 40 |
+
On-device speech for assistants, screen readers and other accessibility tools, games and interactive apps. Do not use it to impersonate a real person, to deceive listeners about who is speaking, or to clone a voice without the speaker's consent; tell listeners when speech is synthetic where that matters to them.
|
| 41 |
+
|
| 42 |
+
English only: text in other languages is read with the wrong pronunciation. The official runtime normalizes numbers, currency, dates, emails and so on before synthesis; that step is not part of the model and must be done by the application. Long inputs are spoken sentence by sentence, so prosody does not carry across the whole text.
|
| 43 |
+
|
| 44 |
+
## What changed in this conversion
|
| 45 |
+
|
| 46 |
+
- Exported as two ExecuTorch programs: the flow-matching transformer with its 1-step sampler and end-of-speech score, and the streaming Mimi decoder
|
| 47 |
+
- A few operations are expressed with equivalent ones the WebGPU backend supports (layer norm, mean, 1-D transposed convolution, ELU, SiLU); each was checked against the original model
|
| 48 |
+
- Weights stay fp32; the text embedding table is stored as bf16, which is exact for these weights
|
| 49 |
+
- Context capped at 512 positions (voice prompt, text and audio frames)
|
| 50 |
+
|
| 51 |
+
## Inputs and outputs
|
| 52 |
+
|
| 53 |
+
- `phonon_flow_lm.pte`: embeddings for 1 to 128 positions plus the start position and noise -> the next audio latent and the end-of-speech score; the attention cache lives inside the program
|
| 54 |
+
- `phonon_mimi.pte`: one latent plus 15 streaming state tensors -> 1,920 samples at 24 kHz and the updated state
|
| 55 |
+
- `phonon.json` documents the full contract: text embedding (`phonon_text_embed.bf16.bin`), the first-step embedding, the voices (`voice_*.f32.bin`), noise, the end-of-speech rule and the frame budget; tokenize with `tokenizer.json`
|
| 56 |
+
|
| 57 |
+
## Files
|
| 58 |
+
|
| 59 |
+
| File | Size | SHA-256 |
|
| 60 |
+
|---|---|---|
|
| 61 |
+
| `phonon.json` | 8.4 KB | `e8fa6604769aeb3b…` |
|
| 62 |
+
| `phonon_bos_embed.f32.bin` | 2.0 KB | `a4464c50596adea2…` |
|
| 63 |
+
| `phonon_flow_lm.pte` | 106.7 MB | `178698a6c4539ba4…` |
|
| 64 |
+
| `phonon_mimi.pte` | 39.4 MB | `d7acdf2d93ba4897…` |
|
| 65 |
+
| `phonon_text_embed.bf16.bin` | 3.9 MB | `7c6f3394fc86b55e…` |
|
| 66 |
+
| `tokenizer.json` | 271.5 KB | `691a00068fa7b989…` |
|
| 67 |
+
| `voice_default.f32.bin` | 250.0 KB | `d8a8ffc97e46c033…` |
|
| 68 |
+
| `voice_en_us_easton.f32.bin` | 250.0 KB | `1d6ec67cbd3a45b2…` |
|
| 69 |
+
|
| 70 |
+
Full checksums are in `manifest.json`. The playground verifies them after download.
|
| 71 |
+
|
| 72 |
+
## Running it
|
| 73 |
+
|
| 74 |
+
These programs were exported with the ExecuTorch WebGPU backend
|
| 75 |
+
([backends/webgpu](https://github.com/pytorch/executorch/tree/main/backends/webgpu)) and run in a browser (headless Chromium, WebGPU on SwiftShader) with the WebAssembly runtime build used by the [ExecuTorch WebGPU Playground](https://executorch.ai/playground/), where the full text-to-speech loop matched the CPU programs frame for frame (audio cosine 0.9999997). That runtime build is published in
|
| 76 |
+
[executorch-community/ExecuTorch-WebGPU-Runtime](https://huggingface.co/executorch-community/ExecuTorch-WebGPU-Runtime); the playground is the easiest way to run them. It downloads these files once, caches them in the browser,
|
| 77 |
+
and runs everything locally.
|
| 78 |
+
|
| 79 |
+
Requirements: a browser with WebGPU enabled.
|
| 80 |
+
|
| 81 |
+
## Provenance
|
| 82 |
+
|
| 83 |
+
- **Upstream:** `gradium/phonon-31m-en` at revision `52433c46975bfa13144c56204c9f4ee1c5b148aa` (official)
|
| 84 |
+
- **Exported with:** executorch 1.5.1+cpu, torch 2.14.1+cpu, torchao 0.18.0+cpu, transformers 5.19.0 (executorch git `3b6068392324`)
|
| 85 |
+
- **Reproduce:** `python recipes/phonon-31m-en.py --out out/phonon-31m-en` (recipe in `export/`)
|
| 86 |
+
- Re-running the recipe produces byte-identical files.
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
## License
|
| 90 |
+
|
| 91 |
+
This is a derivative of the upstream model and is distributed under the same terms
|
| 92 |
+
(`apache-2.0`); see `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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helpers for the ExecuTorch WebGPU export recipes in this directory.
|
| 2 |
+
|
| 3 |
+
Each recipe builds an eager model from a pinned upstream revision and calls
|
| 4 |
+
`export_vision` (or its own LLM path), which writes:
|
| 5 |
+
|
| 6 |
+
<out>/<name>_webgpu.pte program lowered with WebGPUPartitioner (delegate id "VulkanBackend")
|
| 7 |
+
<out>/<name>_portable.pte same exported graph without a delegate, for CPU validation only
|
| 8 |
+
<out>/recipe.json upstream id + revision, versions, shapes, dtype, command line
|
| 9 |
+
<out>/validation.json eager vs exported-program vs portable .pte (and goldens, if given)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import hashlib
|
| 13 |
+
import io
|
| 14 |
+
import json
|
| 15 |
+
import platform
|
| 16 |
+
import shlex
|
| 17 |
+
import sys
|
| 18 |
+
import urllib.request
|
| 19 |
+
import zipfile
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
PROXY_HINT = (
|
| 26 |
+
"set https_proxy if the machine needs a proxy for huggingface.co / pypi.org"
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def versions():
|
| 31 |
+
import executorch
|
| 32 |
+
import torchao
|
| 33 |
+
from executorch.version import git_version
|
| 34 |
+
|
| 35 |
+
out = {
|
| 36 |
+
"python": platform.python_version(),
|
| 37 |
+
"torch": torch.__version__,
|
| 38 |
+
"torchao": torchao.__version__,
|
| 39 |
+
"executorch": getattr(executorch, "__version__", None)
|
| 40 |
+
or __import__("executorch.version").version.__version__,
|
| 41 |
+
"executorch_git": git_version,
|
| 42 |
+
}
|
| 43 |
+
try:
|
| 44 |
+
import transformers
|
| 45 |
+
|
| 46 |
+
out["transformers"] = transformers.__version__
|
| 47 |
+
except ImportError:
|
| 48 |
+
pass
|
| 49 |
+
try:
|
| 50 |
+
import huggingface_hub
|
| 51 |
+
|
| 52 |
+
out["huggingface_hub"] = huggingface_hub.__version__
|
| 53 |
+
except ImportError:
|
| 54 |
+
pass
|
| 55 |
+
return out
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def sha256_file(path):
|
| 59 |
+
h = hashlib.sha256()
|
| 60 |
+
with open(path, "rb") as fh:
|
| 61 |
+
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
| 62 |
+
h.update(chunk)
|
| 63 |
+
return h.hexdigest()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def hf_file(repo_id, filename, revision, expected_sha256=None, cache_dir=None):
|
| 67 |
+
from huggingface_hub import hf_hub_download
|
| 68 |
+
|
| 69 |
+
path = hf_hub_download(
|
| 70 |
+
repo_id=repo_id, filename=filename, revision=revision, cache_dir=cache_dir
|
| 71 |
+
)
|
| 72 |
+
digest = sha256_file(path)
|
| 73 |
+
if expected_sha256 and digest != expected_sha256:
|
| 74 |
+
sys.exit(
|
| 75 |
+
f"{repo_id}@{revision}:{filename} sha256 {digest} != {expected_sha256}"
|
| 76 |
+
)
|
| 77 |
+
return Path(path), digest
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def pypi_wheel_member(url, expected_sha256, member):
|
| 81 |
+
"""Read one file out of a PyPI wheel, verifying the wheel's sha256."""
|
| 82 |
+
with urllib.request.urlopen(url, timeout=120) as resp:
|
| 83 |
+
blob = resp.read()
|
| 84 |
+
digest = hashlib.sha256(blob).hexdigest()
|
| 85 |
+
if digest != expected_sha256:
|
| 86 |
+
sys.exit(f"{url}: sha256 {digest} != {expected_sha256} ({PROXY_HINT})")
|
| 87 |
+
with zipfile.ZipFile(io.BytesIO(blob)) as zf:
|
| 88 |
+
return zf.read(member).decode()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def scrub(text, out_dir):
|
| 92 |
+
"""Replace machine-specific paths so recipe.json can ship with the model."""
|
| 93 |
+
text = text.replace(str(Path(out_dir).resolve()), "<out>")
|
| 94 |
+
text = text.replace(str(Path(__file__).resolve().parent), "recipes")
|
| 95 |
+
return text.replace(str(Path.home()), "~")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def command_line(out_dir):
|
| 99 |
+
argv = [f"recipes/{Path(sys.argv[0]).name}", *sys.argv[1:]]
|
| 100 |
+
args = []
|
| 101 |
+
for a in argv:
|
| 102 |
+
if a.startswith("/") or a.startswith("."):
|
| 103 |
+
a = scrub(str(Path(a).resolve()), out_dir)
|
| 104 |
+
args.append(a)
|
| 105 |
+
return scrub(" ".join(["python", *(shlex.quote(a) for a in args)]), out_dir)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def lower_webgpu(ep):
|
| 109 |
+
from executorch.backends.webgpu.partitioner import WebGPUPartitioner
|
| 110 |
+
from executorch.exir import to_edge_transform_and_lower
|
| 111 |
+
|
| 112 |
+
return to_edge_transform_and_lower(
|
| 113 |
+
ep, partitioner=[WebGPUPartitioner()]
|
| 114 |
+
).to_executorch()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def lower_portable(ep):
|
| 118 |
+
from executorch.exir import to_edge_transform_and_lower
|
| 119 |
+
|
| 120 |
+
return to_edge_transform_and_lower(ep).to_executorch()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def delegate_summary(pte_bytes):
|
| 124 |
+
"""Non-delegated kernels and per-delegate op histograms of a serialized program."""
|
| 125 |
+
import collections
|
| 126 |
+
|
| 127 |
+
from executorch.backends.vulkan.serialization.vulkan_graph_serialize import (
|
| 128 |
+
extract_vk_flatbuffer,
|
| 129 |
+
flatbuffer_to_vk_graph,
|
| 130 |
+
)
|
| 131 |
+
from executorch.exir._serialize._program import deserialize_pte_binary
|
| 132 |
+
|
| 133 |
+
pte = deserialize_pte_binary(pte_bytes)
|
| 134 |
+
prog = pte.program if hasattr(pte, "program") else pte
|
| 135 |
+
seg_base = int.from_bytes(pte_bytes[24:32], "little")
|
| 136 |
+
plan = prog.execution_plan[0]
|
| 137 |
+
ops = [f"{o.name}.{o.overload}" for o in plan.operators]
|
| 138 |
+
kernels = collections.Counter()
|
| 139 |
+
for chain in plan.chains:
|
| 140 |
+
for ins in chain.instructions:
|
| 141 |
+
if type(ins.instr_args).__name__ == "KernelCall":
|
| 142 |
+
kernels[ops[ins.instr_args.op_index]] += 1
|
| 143 |
+
delegates = []
|
| 144 |
+
for d in plan.delegates:
|
| 145 |
+
proc = d.processed
|
| 146 |
+
if proc.location.name == "INLINE":
|
| 147 |
+
blob = prog.backend_delegate_data[proc.index].data
|
| 148 |
+
else:
|
| 149 |
+
seg = prog.segments[proc.index]
|
| 150 |
+
blob = pte_bytes[seg_base + seg.offset : seg_base + seg.offset + seg.size]
|
| 151 |
+
g = flatbuffer_to_vk_graph(extract_vk_flatbuffer(blob))
|
| 152 |
+
delegates.append(
|
| 153 |
+
{
|
| 154 |
+
"id": d.id,
|
| 155 |
+
"ops": dict(collections.Counter(c.name for c in g.chain)),
|
| 156 |
+
"inputs": len(g.input_ids),
|
| 157 |
+
"outputs": len(g.output_ids),
|
| 158 |
+
}
|
| 159 |
+
)
|
| 160 |
+
return {"non_delegated_kernels": dict(kernels), "delegates": delegates}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def compare(a, b):
|
| 164 |
+
a = np.asarray(a, dtype=np.float64).ravel()
|
| 165 |
+
b = np.asarray(b, dtype=np.float64).ravel()
|
| 166 |
+
n = min(a.size, b.size)
|
| 167 |
+
a, b = a[:n], b[:n]
|
| 168 |
+
cos = float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30))
|
| 169 |
+
return {
|
| 170 |
+
"max_abs": float(np.max(np.abs(a - b))),
|
| 171 |
+
"mean_abs": float(np.mean(np.abs(a - b))),
|
| 172 |
+
"cosine": cos,
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def run_pte(pte_bytes, inputs):
|
| 177 |
+
from executorch.extension.pybindings.portable_lib import (
|
| 178 |
+
_load_for_executorch_from_buffer,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
m = _load_for_executorch_from_buffer(pte_bytes)
|
| 182 |
+
return [
|
| 183 |
+
o.detach().numpy() if isinstance(o, torch.Tensor) else o
|
| 184 |
+
for o in m.forward(inputs)
|
| 185 |
+
]
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def try_run_webgpu_pte_on_cpu(pte_bytes, inputs):
|
| 189 |
+
try:
|
| 190 |
+
return run_pte(pte_bytes, inputs), None
|
| 191 |
+
except Exception as e: # noqa: BLE001 - the error text is the result
|
| 192 |
+
return None, f"{type(e).__name__}: {str(e).splitlines()[0][:300]}"
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def export_vision(
|
| 196 |
+
*,
|
| 197 |
+
name,
|
| 198 |
+
model,
|
| 199 |
+
example_input,
|
| 200 |
+
out_dir,
|
| 201 |
+
upstream,
|
| 202 |
+
extra_recipe,
|
| 203 |
+
golden=None,
|
| 204 |
+
output_index=None,
|
| 205 |
+
):
|
| 206 |
+
"""Export, lower, write both .pte files, recipe.json, and validation.json.
|
| 207 |
+
|
| 208 |
+
`golden` is an optional (input ndarray, output ndarray) pair; when its input
|
| 209 |
+
shape matches `example_input`, all paths are also compared against it.
|
| 210 |
+
`output_index` picks one tensor when the eager model returns a tuple.
|
| 211 |
+
"""
|
| 212 |
+
out_dir = Path(out_dir)
|
| 213 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 214 |
+
torch.manual_seed(0)
|
| 215 |
+
model = model.eval()
|
| 216 |
+
|
| 217 |
+
class Wrapped(torch.nn.Module):
|
| 218 |
+
def __init__(self, m):
|
| 219 |
+
super().__init__()
|
| 220 |
+
self.m = m
|
| 221 |
+
|
| 222 |
+
def forward(self, x):
|
| 223 |
+
y = self.m(x)
|
| 224 |
+
return y[output_index] if output_index is not None else y
|
| 225 |
+
|
| 226 |
+
wrapped = Wrapped(model).eval()
|
| 227 |
+
with torch.no_grad():
|
| 228 |
+
ep = torch.export.export(wrapped, (example_input,), strict=False)
|
| 229 |
+
webgpu = lower_webgpu(ep)
|
| 230 |
+
portable = lower_portable(ep)
|
| 231 |
+
|
| 232 |
+
webgpu_path = out_dir / f"{name}_webgpu.pte"
|
| 233 |
+
portable_path = out_dir / f"{name}_portable.pte"
|
| 234 |
+
webgpu_path.write_bytes(webgpu.buffer)
|
| 235 |
+
portable_path.write_bytes(portable.buffer)
|
| 236 |
+
|
| 237 |
+
summary = delegate_summary(webgpu.buffer)
|
| 238 |
+
out_shape = list(ep.module()(example_input).shape)
|
| 239 |
+
recipe = {
|
| 240 |
+
"model": name,
|
| 241 |
+
"upstream": upstream,
|
| 242 |
+
"versions": versions(),
|
| 243 |
+
"export": {
|
| 244 |
+
"api": "torch.export.export(strict=False) -> to_edge_transform_and_lower(partitioner=[WebGPUPartitioner()]) -> to_executorch()",
|
| 245 |
+
"partitioner": "executorch.backends.webgpu.partitioner.WebGPUPartitioner() (default compile options; wraps VulkanPartitioner)",
|
| 246 |
+
"inputs": [
|
| 247 |
+
{
|
| 248 |
+
"shape": list(example_input.shape),
|
| 249 |
+
"dtype": "float32",
|
| 250 |
+
"layout": "NCHW",
|
| 251 |
+
}
|
| 252 |
+
],
|
| 253 |
+
"outputs": [{"shape": out_shape, "dtype": "float32"}],
|
| 254 |
+
"dtype": "float32",
|
| 255 |
+
"quantization": "none (fp32)",
|
| 256 |
+
**extra_recipe,
|
| 257 |
+
},
|
| 258 |
+
"files": {
|
| 259 |
+
webgpu_path.name: {
|
| 260 |
+
"bytes": webgpu_path.stat().st_size,
|
| 261 |
+
"sha256": sha256_file(webgpu_path),
|
| 262 |
+
},
|
| 263 |
+
portable_path.name: {
|
| 264 |
+
"bytes": portable_path.stat().st_size,
|
| 265 |
+
"sha256": sha256_file(portable_path),
|
| 266 |
+
"note": "CPU-only validation artifact (portable kernels, no delegate); not for release",
|
| 267 |
+
},
|
| 268 |
+
},
|
| 269 |
+
"graph": summary,
|
| 270 |
+
"command": command_line(out_dir),
|
| 271 |
+
}
|
| 272 |
+
(out_dir / "recipe.json").write_text(json.dumps(recipe, indent=2) + "\n")
|
| 273 |
+
|
| 274 |
+
# Validation on CPU.
|
| 275 |
+
gen = torch.Generator().manual_seed(1234)
|
| 276 |
+
rand_input = torch.rand(example_input.shape, generator=gen)
|
| 277 |
+
cases = {"random": rand_input}
|
| 278 |
+
if golden is not None and tuple(golden[0].shape) == tuple(example_input.shape):
|
| 279 |
+
cases["golden"] = torch.from_numpy(golden[0].copy())
|
| 280 |
+
report = {
|
| 281 |
+
"cpu_runtime": "executorch pybindings (portable_lib) from the pip wheel",
|
| 282 |
+
"cases": {},
|
| 283 |
+
}
|
| 284 |
+
webgpu_cpu_error = None
|
| 285 |
+
for label, x in cases.items():
|
| 286 |
+
with torch.no_grad():
|
| 287 |
+
eager = wrapped(x).numpy()
|
| 288 |
+
exported = ep.module()(x).numpy()
|
| 289 |
+
port = run_pte(portable.buffer, (x,))[0]
|
| 290 |
+
res = {
|
| 291 |
+
"exported_vs_eager": compare(exported, eager),
|
| 292 |
+
"portable_pte_vs_eager": compare(port, eager),
|
| 293 |
+
}
|
| 294 |
+
wg, err = try_run_webgpu_pte_on_cpu(webgpu.buffer, (x,))
|
| 295 |
+
if wg is not None:
|
| 296 |
+
res["webgpu_pte_vs_eager"] = compare(wg[0], eager)
|
| 297 |
+
else:
|
| 298 |
+
webgpu_cpu_error = err
|
| 299 |
+
if label == "golden":
|
| 300 |
+
ref = golden[1]
|
| 301 |
+
res["internal_golden_vs_eager"] = compare(eager, ref)
|
| 302 |
+
res["internal_golden_vs_portable_pte"] = compare(port, ref)
|
| 303 |
+
res["golden_note"] = (
|
| 304 |
+
"reference output from the internal goldens.manifest.json"
|
| 305 |
+
)
|
| 306 |
+
report["cases"][label] = res
|
| 307 |
+
report["webgpu_pte_on_cpu"] = (
|
| 308 |
+
"ran"
|
| 309 |
+
if webgpu_cpu_error is None
|
| 310 |
+
else f"not runnable on CPU pybindings: {webgpu_cpu_error}"
|
| 311 |
+
)
|
| 312 |
+
(out_dir / "validation.json").write_text(json.dumps(report, indent=2) + "\n")
|
| 313 |
+
print(
|
| 314 |
+
json.dumps(
|
| 315 |
+
{"recipe": recipe["files"], "graph": summary, "validation": report},
|
| 316 |
+
indent=2,
|
| 317 |
+
)
|
| 318 |
+
)
|
| 319 |
+
return ep, webgpu, portable
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def load_golden(manifest_path, key):
|
| 323 |
+
man = json.loads(Path(manifest_path).read_text())[key]["tensors"]
|
| 324 |
+
base = Path(manifest_path).parent
|
| 325 |
+
|
| 326 |
+
def ld(t):
|
| 327 |
+
return np.fromfile(base / t["file"], dtype=np.float32).reshape(t["shape"])
|
| 328 |
+
|
| 329 |
+
inp = man.get("input")
|
| 330 |
+
return ld(inp), ld(man["output"])
|
export/_phonon.py
ADDED
|
@@ -0,0 +1,910 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Phonon (gradium/phonon-31m-en) building blocks for recipes/phonon-31m-en.py: weights, eager reference, export programs.
|
| 2 |
+
|
| 3 |
+
The eager reference follows the official runtime (the `ptts` crate, src/{flow_lm,tts_model,
|
| 4 |
+
transformer,mlp,conditioners,mimi,seanet,conv}.rs) operation by operation:
|
| 5 |
+
|
| 6 |
+
voice speaker_wavs [1,512,125] -> transpose -> speaker_proj (512x512, no bias) -> [1,125,512]
|
| 7 |
+
prime transformer(voice) then transformer(text_embed(tokens)), both written to the KV cache
|
| 8 |
+
step x = input_linear(prev latent or bos_emb) + cond (cond = num_speakers("1") LUT
|
| 9 |
+
+ duration_delta(0.0) sinusoid, each through its output_proj)
|
| 10 |
+
h = out_norm(transformer(x))[:, -1]; eos_logit = out_eos(h)
|
| 11 |
+
latent = noise + flow_net(h, s=0, t=1, noise) (LSD, 1 step; noise ~ N(0, temp))
|
| 12 |
+
decode (latent * emb_std + emb_mean) -> 1x1 conv 32->512 -> depthwise convtr x16 -> 2-layer
|
| 13 |
+
transformer (window 250, layer scale) -> SEANet decoder (ratios 6,5,4) -> 1920 samples
|
| 14 |
+
|
| 15 |
+
Export programs (WebGPU):
|
| 16 |
+
FlowLMProgram forward(embeds[1,S,512] S<=128, input_pos[1] i64, noise[1,32])
|
| 17 |
+
-> latent[1,32], eos_logit[1,1], next_embeds[1,1,512] (KV cache in the program)
|
| 18 |
+
MimiStepProgram forward(latent[1,1,32], *state) -> pcm[1,1,1920], *new_state (state explicit)
|
| 19 |
+
|
| 20 |
+
Rewrites for the public WebGPU runtime (same function, checked against the eager reference):
|
| 21 |
+
* RoPE: q/k rows of in_proj permuted from interleaved pairs to halves, so the runtime's fused
|
| 22 |
+
HF RoPE (et_vk.apply_rotary_emb_hf) applies; q.k is unchanged.
|
| 23 |
+
* flow-LM LayerNorm (dynamic S): mean as a 1/512 linear + the rms_norm pattern, because
|
| 24 |
+
native_layer_norm has no resize hook and mean.dim's resize drops a keepdim'ed dim.
|
| 25 |
+
* ELU = relu(x) + exp(min(x, 0)) - 1 and SiLU = x * sigmoid(x) (no aten.elu / aten.silu).
|
| 26 |
+
* ConvTranspose1d as a 4-D (H = 1) conv_transpose2d (3-D convolution has no transposed path).
|
| 27 |
+
* Mimi streaming state as explicit tensors: mutable buffers other than the llama KV cache are
|
| 28 |
+
not kept live by the delegate.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import math
|
| 32 |
+
|
| 33 |
+
import torch
|
| 34 |
+
import torch.nn.functional as F
|
| 35 |
+
from torch import nn
|
| 36 |
+
|
| 37 |
+
D = 512
|
| 38 |
+
H = 8
|
| 39 |
+
HD = 64
|
| 40 |
+
LDIM = 32
|
| 41 |
+
FLOW_LAYERS = 6
|
| 42 |
+
MIMI_LAYERS = 2
|
| 43 |
+
MIMI_CONTEXT = 250
|
| 44 |
+
FRAME = 1920 # samples per latent frame at 24 kHz
|
| 45 |
+
UPS = 16 # mimi transformer tokens per latent frame
|
| 46 |
+
NEG = -1.0e30
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ---------------------------------------------------------------------------------------------
|
| 50 |
+
# Weights: a module whose state_dict keys are exactly the checkpoint's keys.
|
| 51 |
+
# ---------------------------------------------------------------------------------------------
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _p(*shape):
|
| 55 |
+
return nn.Parameter(torch.zeros(*shape), requires_grad=False)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class _Lin(nn.Module):
|
| 59 |
+
def __init__(self, i, o, bias):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.weight = _p(o, i)
|
| 62 |
+
if bias:
|
| 63 |
+
self.bias = _p(o)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class _LN(nn.Module):
|
| 67 |
+
def __init__(self, n):
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.weight = _p(n)
|
| 70 |
+
self.bias = _p(n)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class _Attn(nn.Module):
|
| 74 |
+
def __init__(self):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.in_proj = _Lin(D, 3 * D, False)
|
| 77 |
+
self.out_proj = _Lin(D, D, False)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class _Scale(nn.Module):
|
| 81 |
+
def __init__(self):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.scale = _p(D)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class _Layer(nn.Module):
|
| 87 |
+
def __init__(self, layer_scale):
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.self_attn = _Attn()
|
| 90 |
+
self.norm1 = _LN(D)
|
| 91 |
+
self.norm2 = _LN(D)
|
| 92 |
+
self.linear1 = _Lin(D, 2048, False)
|
| 93 |
+
self.linear2 = _Lin(2048, D, False)
|
| 94 |
+
if layer_scale:
|
| 95 |
+
self.layer_scale_1 = _Scale()
|
| 96 |
+
self.layer_scale_2 = _Scale()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class _Transformer(nn.Module):
|
| 100 |
+
def __init__(self, n, layer_scale):
|
| 101 |
+
super().__init__()
|
| 102 |
+
self.layers = nn.ModuleList(_Layer(layer_scale) for _ in range(n))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class _Seq(nn.Module):
|
| 106 |
+
"""nn.Sequential-style numbered children with only the indices that hold weights."""
|
| 107 |
+
|
| 108 |
+
def __init__(self, items):
|
| 109 |
+
super().__init__()
|
| 110 |
+
for k, m in items.items():
|
| 111 |
+
self.add_module(str(k), m)
|
| 112 |
+
|
| 113 |
+
def __getitem__(self, i):
|
| 114 |
+
return getattr(self, str(i))
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class _TimeEmbed(nn.Module):
|
| 118 |
+
def __init__(self):
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.freqs = _p(128)
|
| 121 |
+
self.mlp = _Seq({0: _Lin(256, D, True), 2: _Lin(D, D, True), 3: _Alpha()})
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class _Alpha(nn.Module):
|
| 125 |
+
def __init__(self):
|
| 126 |
+
super().__init__()
|
| 127 |
+
self.alpha = _p(D)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class _ResBlock(nn.Module):
|
| 131 |
+
def __init__(self):
|
| 132 |
+
super().__init__()
|
| 133 |
+
self.in_ln = _LN(D)
|
| 134 |
+
self.mlp = _Seq({0: _Lin(D, D, True), 2: _Lin(D, D, True)})
|
| 135 |
+
self.adaLN_modulation = _Seq({1: _Lin(D, 3 * D, True)})
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class _Final(nn.Module):
|
| 139 |
+
def __init__(self):
|
| 140 |
+
super().__init__()
|
| 141 |
+
self.linear = _Lin(D, LDIM, True)
|
| 142 |
+
self.adaLN_modulation = _Seq({1: _Lin(D, 2 * D, True)})
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class _FlowNet(nn.Module):
|
| 146 |
+
def __init__(self, depth=6):
|
| 147 |
+
super().__init__()
|
| 148 |
+
self.time_embed = nn.ModuleList([_TimeEmbed(), _TimeEmbed()])
|
| 149 |
+
self.cond_embed = _Lin(D, D, True)
|
| 150 |
+
self.input_proj = _Lin(LDIM, D, True)
|
| 151 |
+
self.res_blocks = nn.ModuleList(_ResBlock() for _ in range(depth))
|
| 152 |
+
self.final_layer = _Final()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class _Embed(nn.Module):
|
| 156 |
+
def __init__(self, n, d):
|
| 157 |
+
super().__init__()
|
| 158 |
+
self.weight = _p(n, d)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class _Cond(nn.Module):
|
| 162 |
+
def __init__(self, embed=None, proj_in=None):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.learnt_padding = _p(1, 1, D)
|
| 165 |
+
if embed is not None:
|
| 166 |
+
self.embed = _Embed(*embed)
|
| 167 |
+
if proj_in is not None:
|
| 168 |
+
self.output_proj = _Lin(proj_in, D, False)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class _Conditioners(nn.Module):
|
| 172 |
+
def __init__(self):
|
| 173 |
+
super().__init__()
|
| 174 |
+
self.duration_delta = _Cond(proj_in=128)
|
| 175 |
+
self.num_speakers = _Cond(embed=(32, 16), proj_in=16)
|
| 176 |
+
self.speaker_wavs = _Cond(proj_in=512)
|
| 177 |
+
self.transcript_in_segment = _Cond(embed=(4001, D))
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class _CondProvider(nn.Module):
|
| 181 |
+
def __init__(self):
|
| 182 |
+
super().__init__()
|
| 183 |
+
self.conditioners = _Conditioners()
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class _WST(nn.Module):
|
| 187 |
+
"""flow.w_s_t: a training-time loss-weighting net; the runtime drops it (loader.rs remap_key)."""
|
| 188 |
+
|
| 189 |
+
def __init__(self):
|
| 190 |
+
super().__init__()
|
| 191 |
+
self.w_s_t = _Seq(
|
| 192 |
+
{
|
| 193 |
+
0: _Lin(2, 32, True),
|
| 194 |
+
3: _Lin(32, 32, True),
|
| 195 |
+
6: _Lin(32, 32, True),
|
| 196 |
+
9: _Lin(32, 1, True),
|
| 197 |
+
}
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class FlowLMWeights(nn.Module):
|
| 202 |
+
def __init__(self):
|
| 203 |
+
super().__init__()
|
| 204 |
+
self.bos_emb = _p(LDIM)
|
| 205 |
+
self.emb_mean = _p(LDIM)
|
| 206 |
+
self.emb_std = _p(LDIM)
|
| 207 |
+
self.condition_provider = _CondProvider()
|
| 208 |
+
self.flow = _WST()
|
| 209 |
+
self.flow_net = _FlowNet()
|
| 210 |
+
self.input_linear = _Lin(LDIM, D, False)
|
| 211 |
+
self.out_eos = _Lin(D, 1, True)
|
| 212 |
+
self.out_norm = _LN(D)
|
| 213 |
+
self.transformer = _Transformer(FLOW_LAYERS, False)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class _Conv(nn.Module):
|
| 217 |
+
def __init__(self, i, o, k):
|
| 218 |
+
super().__init__()
|
| 219 |
+
self.conv = _ConvW(i, o, k, bias=True)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class _ConvW(nn.Module):
|
| 223 |
+
def __init__(self, i, o, k, bias):
|
| 224 |
+
super().__init__()
|
| 225 |
+
self.weight = _p(o, i, k)
|
| 226 |
+
if bias:
|
| 227 |
+
self.bias = _p(o)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class _ConvTr(nn.Module):
|
| 231 |
+
def __init__(self, i, o, k):
|
| 232 |
+
super().__init__()
|
| 233 |
+
self.convtr = _ConvTrW(i, o, k, True)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class _ConvTrW(nn.Module):
|
| 237 |
+
def __init__(self, i, o_per_group, k, bias):
|
| 238 |
+
super().__init__()
|
| 239 |
+
self.weight = _p(i, o_per_group, k)
|
| 240 |
+
if bias:
|
| 241 |
+
self.bias = _p(o_per_group)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class _Res(nn.Module):
|
| 245 |
+
def __init__(self, dim):
|
| 246 |
+
super().__init__()
|
| 247 |
+
self.block = _Seq({1: _Conv(dim, dim // 2, 3), 3: _Conv(dim // 2, dim, 1)})
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class _SEANetDecoder(nn.Module):
|
| 251 |
+
def __init__(self):
|
| 252 |
+
super().__init__()
|
| 253 |
+
self.model = _Seq(
|
| 254 |
+
{
|
| 255 |
+
0: _Conv(512, 512, 7),
|
| 256 |
+
2: _ConvTr(512, 256, 12),
|
| 257 |
+
3: _Res(256),
|
| 258 |
+
5: _ConvTr(256, 128, 10),
|
| 259 |
+
6: _Res(128),
|
| 260 |
+
8: _ConvTr(128, 64, 8),
|
| 261 |
+
9: _Res(64),
|
| 262 |
+
11: _Conv(64, 1, 3),
|
| 263 |
+
}
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class _ProjT(nn.Module):
|
| 268 |
+
def __init__(self):
|
| 269 |
+
super().__init__()
|
| 270 |
+
self.transformer = _Transformer(MIMI_LAYERS, True)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class _Quantizer(nn.Module):
|
| 274 |
+
def __init__(self):
|
| 275 |
+
super().__init__()
|
| 276 |
+
self.output_proj = _ConvW(LDIM, D, 1, bias=False)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class _Upsample(nn.Module):
|
| 280 |
+
def __init__(self):
|
| 281 |
+
super().__init__()
|
| 282 |
+
self.convtr = _Seq({})
|
| 283 |
+
self.convtr.convtr = _ConvTrW(D, 1, 2 * UPS, False)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class MimiWeights(nn.Module):
|
| 287 |
+
def __init__(self):
|
| 288 |
+
super().__init__()
|
| 289 |
+
self.decoder = _SEANetDecoder()
|
| 290 |
+
self.decoder_transformer = _ProjT()
|
| 291 |
+
self.quantizer = _Quantizer()
|
| 292 |
+
self.upsample = _Upsample()
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class PhononWeights(nn.Module):
|
| 296 |
+
def __init__(self):
|
| 297 |
+
super().__init__()
|
| 298 |
+
self.flow_lm = FlowLMWeights()
|
| 299 |
+
self.mimi = MimiWeights()
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def load_weights(safetensors_path):
|
| 303 |
+
"""Every checkpoint tensor, as float32 (bf16 -> f32 is exact), loaded with strict=True."""
|
| 304 |
+
from safetensors.torch import load_file
|
| 305 |
+
|
| 306 |
+
sd = {k: v.float() for k, v in load_file(str(safetensors_path)).items()}
|
| 307 |
+
w = PhononWeights()
|
| 308 |
+
w.load_state_dict(sd, strict=True)
|
| 309 |
+
return w.eval()
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def load_voice(path):
|
| 313 |
+
"""speaker_wavs [1, 512, T] (stored speaker-Mimi latents) from a voice .safetensors file."""
|
| 314 |
+
from safetensors.torch import load_file
|
| 315 |
+
|
| 316 |
+
t = load_file(str(path))
|
| 317 |
+
assert list(t) == ["speaker_wavs"], list(t)
|
| 318 |
+
return t["speaker_wavs"].float()
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
# ---------------------------------------------------------------------------------------------
|
| 322 |
+
# Shared math
|
| 323 |
+
# ---------------------------------------------------------------------------------------------
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def lin(m, x):
|
| 327 |
+
"""nn.Linear on a 2-D view (the public WebGPU runtime's fp32 aten.linear takes 2-D input)."""
|
| 328 |
+
shp = x.shape
|
| 329 |
+
y = F.linear(x.reshape(-1, shp[-1]), m.weight, getattr(m, "bias", None))
|
| 330 |
+
return y.reshape(*shp[:-1], y.shape[-1])
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def lin3(m, x):
|
| 334 |
+
"""nn.Linear on the tensor as it is (any rank); the Vulkan lowering adds its own 2-D views."""
|
| 335 |
+
return F.linear(x, m.weight, getattr(m, "bias", None))
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def layer_norm_dyn(m, x, eps, mean_w):
|
| 339 |
+
"""LayerNorm for the dynamic-length flow-LM program, from ops that follow a resized sequence
|
| 340 |
+
length on the public WebGPU runtime (its native_layer_norm has no resize hook, and its mean.dim
|
| 341 |
+
resize drops a keepdim'ed dim): the mean is a linear with weight 1/512 (exact: a power of two),
|
| 342 |
+
the rest matches the Vulkan rms_norm pattern (fused into et_vk.rms_norm)."""
|
| 343 |
+
xc = x - F.linear(x, mean_w)
|
| 344 |
+
return xc * torch.rsqrt((xc * xc).mean(-1, keepdim=True) + eps) * m.weight + m.bias
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def layer_norm(m, x, eps):
|
| 348 |
+
return F.layer_norm(x, (x.shape[-1],), m.weight, m.bias, eps)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def silu(x):
|
| 352 |
+
return x * torch.sigmoid(x)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def elu(x):
|
| 356 |
+
"""ELU(alpha=1) from ops the public WebGPU runtime registers (it has no aten.elu)."""
|
| 357 |
+
return torch.relu(x) + torch.exp(torch.clamp(x, max=0.0)) - 1.0
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def gelu(x):
|
| 361 |
+
return F.gelu(x) # erf
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def inv_freq():
|
| 365 |
+
"""RoPE frequencies as the runtime computes them (rope.rs): 1 / max_period^(i / half) in f32."""
|
| 366 |
+
half = HD // 2
|
| 367 |
+
i = torch.arange(half, dtype=torch.float32)
|
| 368 |
+
return 1.0 / torch.pow(torch.tensor(10000.0, dtype=torch.float32), i / half)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def rope_interleaved(x, pos):
|
| 372 |
+
"""rope_i on [B, T, H, HD] with absolute positions pos [T] (the runtime's convention:
|
| 373 |
+
pairs (2i, 2i+1) rotate by pos * inv_freq[i])."""
|
| 374 |
+
ang = pos.to(torch.float32)[:, None] * inv_freq()[None, :] # [T, half]
|
| 375 |
+
c, s = torch.cos(ang)[None, :, None, :], torch.sin(ang)[None, :, None, :]
|
| 376 |
+
xr, xi = x[..., 0::2], x[..., 1::2]
|
| 377 |
+
return torch.stack([xr * c - xi * s, xr * s + xi * c], dim=-1).flatten(-2)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def time_embed_rms(te, t):
|
| 381 |
+
"""TimestepEmbedder with TimeRmsNorm::Rms (phonon config time_rms_norm: rms)."""
|
| 382 |
+
args = t * te.freqs
|
| 383 |
+
emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 384 |
+
x = lin(te.mlp[2], silu(lin(te.mlp[0], emb)))
|
| 385 |
+
ms = (x * x).mean(-1, keepdim=True)
|
| 386 |
+
return x * torch.rsqrt(ms + 1e-5) * te.mlp[3].alpha
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def flow_net(fn, c, x, t_comb):
|
| 390 |
+
"""SimpleMLPAdaLN: c [N, 512] backbone output, x [N, 32] noise, t_comb [N or 1, 512]."""
|
| 391 |
+
x = lin(fn.input_proj, x)
|
| 392 |
+
y = t_comb + lin(fn.cond_embed, c)
|
| 393 |
+
sy = silu(y)
|
| 394 |
+
for b in fn.res_blocks:
|
| 395 |
+
ada = lin(b.adaLN_modulation[1], sy)
|
| 396 |
+
shift, scale, gate = ada[..., :D], ada[..., D : 2 * D], ada[..., 2 * D :]
|
| 397 |
+
h = layer_norm(b.in_ln, x, 1e-6) * (scale + 1.0) + shift
|
| 398 |
+
h = lin(b.mlp[2], silu(lin(b.mlp[0], h)))
|
| 399 |
+
x = x + gate * h
|
| 400 |
+
fl = fn.final_layer
|
| 401 |
+
ada = lin(fl.adaLN_modulation[1], sy)
|
| 402 |
+
shift, scale = ada[..., :D], ada[..., D:]
|
| 403 |
+
x = F.layer_norm(x, (D,), None, None, 1e-6) * (scale + 1.0) + shift
|
| 404 |
+
return lin(fl.linear, x)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def lsd_time(fn):
|
| 408 |
+
"""(time_embed[0](s=0) + time_embed[1](t=1)) / 2, the flow head's constant time condition
|
| 409 |
+
for lsd_decode_steps = 1."""
|
| 410 |
+
s = torch.zeros(1, 1)
|
| 411 |
+
t = torch.ones(1, 1)
|
| 412 |
+
return (
|
| 413 |
+
time_embed_rms(fn.time_embed[0], s) + time_embed_rms(fn.time_embed[1], t)
|
| 414 |
+
) / 2
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def sin_embedding(position, dim, max_period):
|
| 418 |
+
half = dim // 2
|
| 419 |
+
i = torch.arange(half, dtype=torch.float32)
|
| 420 |
+
ph = position / torch.pow(
|
| 421 |
+
torch.tensor(max_period, dtype=torch.float32), i / (half - 1)
|
| 422 |
+
)
|
| 423 |
+
return torch.cat([torch.cos(ph), torch.sin(ph)])
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def summed_conditions(flw, num_speakers="1", duration_delta=0.0):
|
| 427 |
+
"""conditioners.rs Conditioners::sum with the runtime's defaults, [1, 1, 512]."""
|
| 428 |
+
c = flw.condition_provider.conditioners
|
| 429 |
+
idx = ["0", "1", "2"].index(num_speakers)
|
| 430 |
+
ns = F.linear(
|
| 431 |
+
c.num_speakers.embed.weight[idx : idx + 1], c.num_speakers.output_proj.weight
|
| 432 |
+
)
|
| 433 |
+
dd = F.linear(
|
| 434 |
+
sin_embedding(1000.0 * duration_delta, 128, 10000.0)[None],
|
| 435 |
+
c.duration_delta.output_proj.weight,
|
| 436 |
+
)
|
| 437 |
+
return (ns + dd).view(1, 1, D)
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def voice_embedding(flw, speaker_wavs):
|
| 441 |
+
"""[1, 512, T] speaker latents -> [1, T, 512] voice prompt (loader.rs project_latents)."""
|
| 442 |
+
w = flw.condition_provider.conditioners.speaker_wavs.output_proj.weight
|
| 443 |
+
return F.linear(speaker_wavs.transpose(1, 2), w)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def text_embedding(flw, tokens):
|
| 447 |
+
emb = flw.condition_provider.conditioners.transcript_in_segment.embed.weight
|
| 448 |
+
return emb[torch.as_tensor(tokens, dtype=torch.long)][None]
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
# ---------------------------------------------------------------------------------------------
|
| 452 |
+
# Eager reference (Python-side state, mirrors the runtime)
|
| 453 |
+
# ---------------------------------------------------------------------------------------------
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class FlowLMRef:
|
| 457 |
+
def __init__(self, w: PhononWeights, num_speakers="1", duration_delta=0.0):
|
| 458 |
+
self.w = w.flow_lm
|
| 459 |
+
self.cond = summed_conditions(self.w, num_speakers, duration_delta)
|
| 460 |
+
self.t_comb = lsd_time(self.w.flow_net)
|
| 461 |
+
self.reset()
|
| 462 |
+
|
| 463 |
+
def reset(self):
|
| 464 |
+
self.k = [None] * FLOW_LAYERS
|
| 465 |
+
self.v = [None] * FLOW_LAYERS
|
| 466 |
+
self.pos = 0
|
| 467 |
+
|
| 468 |
+
@torch.no_grad()
|
| 469 |
+
def backbone(self, x):
|
| 470 |
+
B, T, _ = x.shape
|
| 471 |
+
pos = torch.arange(self.pos, self.pos + T)
|
| 472 |
+
for i, L in enumerate(self.w.transformer.layers):
|
| 473 |
+
h = layer_norm(L.norm1, x, 1e-5)
|
| 474 |
+
qkv = lin(L.self_attn.in_proj, h).view(B, T, 3, H, HD)
|
| 475 |
+
q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
|
| 476 |
+
q, k = rope_interleaved(q, pos), rope_interleaved(k, pos)
|
| 477 |
+
self.k[i] = k if self.k[i] is None else torch.cat([self.k[i], k], 1)
|
| 478 |
+
self.v[i] = v if self.v[i] is None else torch.cat([self.v[i], v], 1)
|
| 479 |
+
kk, vv = self.k[i].transpose(1, 2), self.v[i].transpose(1, 2)
|
| 480 |
+
qq = q.transpose(1, 2)
|
| 481 |
+
Tk = kk.shape[2]
|
| 482 |
+
qpos = torch.arange(Tk - T, Tk)[:, None]
|
| 483 |
+
mask = torch.where(torch.arange(Tk)[None, :] <= qpos, 0.0, float("-inf"))
|
| 484 |
+
att = torch.softmax(qq @ kk.transpose(-1, -2) / math.sqrt(HD) + mask, -1)
|
| 485 |
+
o = (att @ vv).transpose(1, 2).reshape(B, T, D)
|
| 486 |
+
x = x + lin(L.self_attn.out_proj, o)
|
| 487 |
+
h = layer_norm(L.norm2, x, 1e-5)
|
| 488 |
+
x = x + lin(L.linear2, gelu(lin(L.linear1, h)))
|
| 489 |
+
self.pos += T
|
| 490 |
+
return x
|
| 491 |
+
|
| 492 |
+
def prompt(self, embeds):
|
| 493 |
+
self.backbone(embeds)
|
| 494 |
+
|
| 495 |
+
@torch.no_grad()
|
| 496 |
+
def step(self, prev_latent, noise):
|
| 497 |
+
"""prev_latent None (BOS) or [1, 1, 32]; noise [1, 32]. -> latent [1,1,32], eos_logit."""
|
| 498 |
+
seq = self.w.bos_emb.view(1, 1, LDIM) if prev_latent is None else prev_latent
|
| 499 |
+
x = lin(self.w.input_linear, seq) + self.cond
|
| 500 |
+
h = layer_norm(self.w.out_norm, self.backbone(x), 1e-5)[:, -1]
|
| 501 |
+
eos = lin(self.w.out_eos, h)
|
| 502 |
+
latent = noise + flow_net(self.w.flow_net, h, noise, self.t_comb)
|
| 503 |
+
return latent.view(1, 1, LDIM), eos
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def _conv1d_stream(m, x, prev, dilation=1):
|
| 507 |
+
xx = torch.cat([prev, x], 2) if prev is not None else x
|
| 508 |
+
y = F.conv1d(xx, m.conv.weight, m.conv.bias, dilation=dilation)
|
| 509 |
+
tp = prev.shape[2] if prev is not None else 0
|
| 510 |
+
return y, (xx[:, :, xx.shape[2] - tp :] if tp else None)
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def _convtr_stream(w, bias, x, partial, stride, groups=1):
|
| 514 |
+
y = F.conv_transpose1d(x, w, bias, stride=stride, groups=groups)
|
| 515 |
+
pt = partial.shape[2]
|
| 516 |
+
y = torch.cat([y[:, :, :pt] + partial, y[:, :, pt:]], 2)
|
| 517 |
+
new_partial = y[:, :, y.shape[2] - pt :]
|
| 518 |
+
if bias is not None:
|
| 519 |
+
new_partial = new_partial - bias.view(1, -1, 1)
|
| 520 |
+
return y[:, :, : y.shape[2] - pt], new_partial
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class MimiRef:
|
| 524 |
+
"""Streaming Mimi decoder (MimiDecoder::decode_from_latent_step), one or more frames per call."""
|
| 525 |
+
|
| 526 |
+
def __init__(self, w: PhononWeights):
|
| 527 |
+
self.w = w.mimi
|
| 528 |
+
self.emb_std = w.flow_lm.emb_std
|
| 529 |
+
self.emb_mean = w.flow_lm.emb_mean
|
| 530 |
+
self.reset()
|
| 531 |
+
|
| 532 |
+
def reset(self):
|
| 533 |
+
z = lambda *s: torch.zeros(1, *s) # noqa: E731
|
| 534 |
+
self.up = z(D, UPS)
|
| 535 |
+
self.kv = [[None, None] for _ in range(MIMI_LAYERS)]
|
| 536 |
+
self.offset = 0
|
| 537 |
+
self.prev = {
|
| 538 |
+
"init": z(512, 6),
|
| 539 |
+
"r1": z(256, 2),
|
| 540 |
+
"r2": z(128, 2),
|
| 541 |
+
"r3": z(64, 2),
|
| 542 |
+
"final": z(64, 2),
|
| 543 |
+
}
|
| 544 |
+
self.partial = {"u1": z(256, 6), "u2": z(128, 5), "u3": z(64, 4)}
|
| 545 |
+
|
| 546 |
+
@torch.no_grad()
|
| 547 |
+
def transformer(self, x): # x [1, T, 512]
|
| 548 |
+
T = x.shape[1]
|
| 549 |
+
pos = torch.arange(self.offset, self.offset + T)
|
| 550 |
+
for i, L in enumerate(self.w.decoder_transformer.transformer.layers):
|
| 551 |
+
h = layer_norm(L.norm1, x, 1e-5)
|
| 552 |
+
qkv = lin(L.self_attn.in_proj, h).view(1, T, 3, H, HD)
|
| 553 |
+
q, k, v = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]
|
| 554 |
+
q, k = rope_interleaved(q, pos), rope_interleaved(k, pos)
|
| 555 |
+
q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
|
| 556 |
+
pk, pv = self.kv[i]
|
| 557 |
+
kk = k if pk is None else torch.cat([pk, k], 2)
|
| 558 |
+
vv = v if pv is None else torch.cat([pv, v], 2)
|
| 559 |
+
kvlen = kk.shape[2] - T
|
| 560 |
+
qi = torch.arange(T)[:, None] + kvlen
|
| 561 |
+
kj = torch.arange(kk.shape[2])[None, :]
|
| 562 |
+
ok = (kj <= qi) & (kj >= qi - MIMI_CONTEXT)
|
| 563 |
+
mask = torch.where(ok, 0.0, float("-inf"))
|
| 564 |
+
att = torch.softmax(q @ kk.transpose(-1, -2) / math.sqrt(HD) + mask, -1)
|
| 565 |
+
o = (att @ vv).transpose(1, 2).reshape(1, T, D)
|
| 566 |
+
self.kv[i] = [kk[:, :, -MIMI_CONTEXT:], vv[:, :, -MIMI_CONTEXT:]]
|
| 567 |
+
x = x + L.layer_scale_1.scale * lin(L.self_attn.out_proj, o)
|
| 568 |
+
h = layer_norm(L.norm2, x, 1e-5)
|
| 569 |
+
x = x + L.layer_scale_2.scale * lin(L.linear2, gelu(lin(L.linear1, h)))
|
| 570 |
+
self.offset += T
|
| 571 |
+
return x
|
| 572 |
+
|
| 573 |
+
def _res(self, blk, x, key):
|
| 574 |
+
v, self.prev[key] = _conv1d_stream(blk.block[1], elu(x), self.prev[key])
|
| 575 |
+
v, _ = _conv1d_stream(blk.block[3], elu(v), None)
|
| 576 |
+
return x + v
|
| 577 |
+
|
| 578 |
+
@torch.no_grad()
|
| 579 |
+
def decode(self, latent):
|
| 580 |
+
"""latent [1, T, 32] (flow-LM space) -> pcm [1, 1, T * 1920]."""
|
| 581 |
+
x = (latent * self.emb_std + self.emb_mean).transpose(1, 2)
|
| 582 |
+
x = F.conv1d(x, self.w.quantizer.output_proj.weight)
|
| 583 |
+
x, self.up = _convtr_stream(
|
| 584 |
+
self.w.upsample.convtr.convtr.weight, None, x, self.up, UPS, groups=D
|
| 585 |
+
)
|
| 586 |
+
x = self.transformer(x.transpose(1, 2)).transpose(1, 2)
|
| 587 |
+
m = self.w.decoder.model
|
| 588 |
+
x, self.prev["init"] = _conv1d_stream(m[0], x, self.prev["init"])
|
| 589 |
+
for up, res, s, ku, kr in [
|
| 590 |
+
(m[2], m[3], 6, "u1", "r1"),
|
| 591 |
+
(m[5], m[6], 5, "u2", "r2"),
|
| 592 |
+
(m[8], m[9], 4, "u3", "r3"),
|
| 593 |
+
]:
|
| 594 |
+
x, self.partial[ku] = _convtr_stream(
|
| 595 |
+
up.convtr.weight, up.convtr.bias, elu(x), self.partial[ku], s
|
| 596 |
+
)
|
| 597 |
+
x = self._res(res, x, kr)
|
| 598 |
+
x, self.prev["final"] = _conv1d_stream(m[11], elu(x), self.prev["final"])
|
| 599 |
+
return x
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
# ---------------------------------------------------------------------------------------------
|
| 603 |
+
# Generation policy (plan.rs, tts_model.rs)
|
| 604 |
+
# ---------------------------------------------------------------------------------------------
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def prepare_text_prompt(text):
|
| 608 |
+
text = " ".join(text.strip().replace("\n", " ").replace("\r", " ").split())
|
| 609 |
+
if not text:
|
| 610 |
+
return text, 3
|
| 611 |
+
frames_after_eos = 3 if len(text.split()) <= 4 else 1
|
| 612 |
+
text = text[0].upper() + text[1:]
|
| 613 |
+
if text[-1].isalnum():
|
| 614 |
+
text += "."
|
| 615 |
+
return text, frames_after_eos
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def frame_budget(num_tokens, frame_rate=12.5):
|
| 619 |
+
return math.ceil((num_tokens / 3.0 + 2.0) * frame_rate)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class EosPolicy:
|
| 623 |
+
def __init__(self, frames_after_eos):
|
| 624 |
+
self.n, self.countdown = frames_after_eos, None
|
| 625 |
+
|
| 626 |
+
def should_stop(self, is_eos):
|
| 627 |
+
if is_eos and self.countdown is None:
|
| 628 |
+
self.countdown = self.n
|
| 629 |
+
if self.countdown is None:
|
| 630 |
+
return False
|
| 631 |
+
if self.countdown == 0:
|
| 632 |
+
return True
|
| 633 |
+
self.countdown -= 1
|
| 634 |
+
return False
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def generate(step_fn, tokens, frames_after_eos, noise_fn, eos_threshold=4.0):
|
| 638 |
+
"""The runtime's loop (synth.rs run_inline): BOS first, the EOS frame and its tail are kept.
|
| 639 |
+
step_fn(prev_latent_or_None, noise) -> (latent [1,1,32], eos_logit). Returns latents, eos logits."""
|
| 640 |
+
eos = EosPolicy(frames_after_eos)
|
| 641 |
+
prev, lats, logits = None, [], []
|
| 642 |
+
for i in range(frame_budget(len(tokens))):
|
| 643 |
+
lat, e = step_fn(prev, noise_fn(i))
|
| 644 |
+
lats.append(lat)
|
| 645 |
+
logits.append(float(e.reshape(-1)[0]))
|
| 646 |
+
if eos.should_stop(logits[-1] > eos_threshold):
|
| 647 |
+
break
|
| 648 |
+
prev = lat
|
| 649 |
+
return lats, logits
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def tokenizer(tokenizer_json):
|
| 653 |
+
from tokenizers import Tokenizer
|
| 654 |
+
|
| 655 |
+
return Tokenizer.from_file(str(tokenizer_json))
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def tokenize(tok, text):
|
| 659 |
+
prepared, frames_after_eos = prepare_text_prompt(text)
|
| 660 |
+
return (
|
| 661 |
+
tok.encode(prepared, add_special_tokens=False).ids,
|
| 662 |
+
frames_after_eos,
|
| 663 |
+
prepared,
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
# ---------------------------------------------------------------------------------------------
|
| 668 |
+
# Export programs
|
| 669 |
+
# ---------------------------------------------------------------------------------------------
|
| 670 |
+
|
| 671 |
+
MAX_CTX = 512 # flow-LM KV cache positions: voice prompt + text tokens + generated frames
|
| 672 |
+
PREFILL_MAX = 128 # most positions one flow-LM call may write (the 125-frame voice prompt fits)
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def _half_split_perm():
|
| 676 |
+
"""Within each head, reorder q/k channels from interleaved pairs (2i, 2i+1) to halves
|
| 677 |
+
(i, i + 32): rope_i on the old layout equals rotate_half RoPE on the new one, and q.k is
|
| 678 |
+
unchanged because q and k are permuted alike."""
|
| 679 |
+
per = torch.cat([torch.arange(0, HD, 2), torch.arange(1, HD, 2)])
|
| 680 |
+
return torch.cat([h * HD + per for h in range(H)])
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def _permuted_in_proj(w):
|
| 684 |
+
"""in_proj weight [3*512, 512] with the q and k row blocks permuted, v untouched."""
|
| 685 |
+
perm = _half_split_perm()
|
| 686 |
+
return torch.cat([w[:D][perm], w[D : 2 * D][perm], w[2 * D :]], 0).contiguous()
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def rope_tables(n):
|
| 690 |
+
"""cos/sin [n, 64] in the half-split layout, angle = f32(pos) * f32(inv_freq) as rope.rs."""
|
| 691 |
+
ang = torch.arange(n, dtype=torch.float32)[:, None] * inv_freq()[None, :]
|
| 692 |
+
c, s = torch.cos(ang), torch.sin(ang)
|
| 693 |
+
return torch.cat([c, c], -1).contiguous(), torch.cat([s, s], -1).contiguous()
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def _rope_hf(q, k, cos, sin):
|
| 697 |
+
from executorch.backends.vulkan.patterns.rope_hf import HfRotaryEmbeddingPattern
|
| 698 |
+
|
| 699 |
+
return HfRotaryEmbeddingPattern()(q, k, cos, sin)
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
class _LinP(nn.Module):
|
| 703 |
+
def __init__(self, weight, bias=None):
|
| 704 |
+
super().__init__()
|
| 705 |
+
self.weight = nn.Parameter(weight.detach().clone().contiguous(), requires_grad=False)
|
| 706 |
+
if bias is not None:
|
| 707 |
+
self.bias = nn.Parameter(bias.detach().clone().contiguous(), requires_grad=False)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
class FlowLMProgram(nn.Module):
|
| 711 |
+
"""forward(embeds[1,S,512], input_pos[1] i64, noise[1,32])
|
| 712 |
+
-> latent[1,32], eos_logit[1,1], next_embeds[1,1,512].
|
| 713 |
+
|
| 714 |
+
Writes the S positions [input_pos, input_pos + S) of the in-program KV cache (llama
|
| 715 |
+
sdpa_with_kv_cache, causal), then runs the head on the last position: eos_logit = out_eos(h),
|
| 716 |
+
latent = noise + flow_net(h, s=0, t=1, noise) and next_embeds = input_linear(latent) + cond,
|
| 717 |
+
the embedding of the next step's input. Prompt calls (voice, text) ignore the outputs."""
|
| 718 |
+
|
| 719 |
+
def __init__(self, w: PhononWeights, num_speakers="1", duration_delta=0.0, attn="sdpa_kv"):
|
| 720 |
+
super().__init__()
|
| 721 |
+
from executorch.extension.llm.custom_ops import custom_ops # noqa: F401
|
| 722 |
+
|
| 723 |
+
f = w.flow_lm
|
| 724 |
+
self.attn = attn
|
| 725 |
+
self.layers = nn.ModuleList()
|
| 726 |
+
for L in f.transformer.layers:
|
| 727 |
+
m = nn.Module()
|
| 728 |
+
m.norm1, m.norm2 = L.norm1, L.norm2
|
| 729 |
+
m.in_proj = _LinP(_permuted_in_proj(L.self_attn.in_proj.weight))
|
| 730 |
+
m.out_proj, m.linear1, m.linear2 = L.self_attn.out_proj, L.linear1, L.linear2
|
| 731 |
+
self.layers.append(m)
|
| 732 |
+
self.out_norm, self.out_eos, self.input_linear = f.out_norm, f.out_eos, f.input_linear
|
| 733 |
+
self.fn = f.flow_net
|
| 734 |
+
with torch.no_grad():
|
| 735 |
+
self.register_buffer("cond", summed_conditions(f, num_speakers, duration_delta).clone(), persistent=False)
|
| 736 |
+
self.register_buffer("t_comb", lsd_time(f.flow_net).clone(), persistent=False)
|
| 737 |
+
self.register_buffer("mean_w", torch.full((1, D), 1.0 / D), persistent=False)
|
| 738 |
+
cos, sin = rope_tables(MAX_CTX)
|
| 739 |
+
self.register_buffer("rope_cos", cos, persistent=False)
|
| 740 |
+
self.register_buffer("rope_sin", sin, persistent=False)
|
| 741 |
+
for i in range(FLOW_LAYERS):
|
| 742 |
+
self.register_buffer(f"k_cache_{i}", torch.zeros(1, MAX_CTX, H, HD), persistent=False)
|
| 743 |
+
self.register_buffer(f"v_cache_{i}", torch.zeros(1, MAX_CTX, H, HD), persistent=False)
|
| 744 |
+
|
| 745 |
+
def reset(self):
|
| 746 |
+
for i in range(FLOW_LAYERS):
|
| 747 |
+
getattr(self, f"k_cache_{i}").zero_()
|
| 748 |
+
getattr(self, f"v_cache_{i}").zero_()
|
| 749 |
+
|
| 750 |
+
def forward(self, embeds, input_pos, noise):
|
| 751 |
+
S = embeds.shape[1]
|
| 752 |
+
p = input_pos[0].item()
|
| 753 |
+
torch._check_is_size(p)
|
| 754 |
+
torch._check(p + S <= MAX_CTX)
|
| 755 |
+
cos = self.rope_cos.narrow(0, p, S)
|
| 756 |
+
sin = self.rope_sin.narrow(0, p, S)
|
| 757 |
+
x = embeds
|
| 758 |
+
for i, L in enumerate(self.layers):
|
| 759 |
+
h = layer_norm_dyn(L.norm1, x, 1e-5, self.mean_w)
|
| 760 |
+
qkv = lin3(L.in_proj, h)
|
| 761 |
+
q = qkv[..., :D].reshape(1, S, H, HD)
|
| 762 |
+
k = qkv[..., D : 2 * D].reshape(1, S, H, HD)
|
| 763 |
+
v = qkv[..., 2 * D :].reshape(1, S, H, HD)
|
| 764 |
+
q, k = _rope_hf(q, k, cos, sin)
|
| 765 |
+
kc, vc = getattr(self, f"k_cache_{i}"), getattr(self, f"v_cache_{i}")
|
| 766 |
+
o = torch.ops.llama.sdpa_with_kv_cache(q, k, v, kc, vc, p, S, None, 0.0, True, None)
|
| 767 |
+
x = x + lin3(L.out_proj, o.reshape(1, S, D))
|
| 768 |
+
h = layer_norm_dyn(L.norm2, x, 1e-5, self.mean_w)
|
| 769 |
+
x = x + lin3(L.linear2, gelu(lin3(L.linear1, h)))
|
| 770 |
+
h = layer_norm(self.out_norm, x[:, -1, :], 1e-5)
|
| 771 |
+
eos = lin3(self.out_eos, h)
|
| 772 |
+
latent = noise + flow_net(self.fn, h, noise, self.t_comb)
|
| 773 |
+
nxt = lin3(self.input_linear, latent).reshape(1, 1, D) + self.cond
|
| 774 |
+
return latent, eos, nxt
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
MIMI_STATE = [
|
| 778 |
+
("upsample_partial", (1, D, UPS)),
|
| 779 |
+
("k0", (1, H, MIMI_CONTEXT, HD)),
|
| 780 |
+
("v0", (1, H, MIMI_CONTEXT, HD)),
|
| 781 |
+
("k1", (1, H, MIMI_CONTEXT, HD)),
|
| 782 |
+
("v1", (1, H, MIMI_CONTEXT, HD)),
|
| 783 |
+
("kv_seen", (1, 1, 1, MIMI_CONTEXT)),
|
| 784 |
+
("rope_offset", (1,)),
|
| 785 |
+
("init_conv_prev", (1, 512, 6)),
|
| 786 |
+
("up1_partial", (1, 256, 6)),
|
| 787 |
+
("res1_prev", (1, 256, 2)),
|
| 788 |
+
("up2_partial", (1, 128, 5)),
|
| 789 |
+
("res2_prev", (1, 128, 2)),
|
| 790 |
+
("up3_partial", (1, 64, 4)),
|
| 791 |
+
("res3_prev", (1, 64, 2)),
|
| 792 |
+
("final_conv_prev", (1, 64, 2)),
|
| 793 |
+
]
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def mimi_zero_state():
|
| 797 |
+
return [torch.zeros(s) for _, s in MIMI_STATE]
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def _convtr(x, w, b, s, groups=1):
|
| 801 |
+
"""ConvTranspose1d as a 4-D (H = 1) conv_transpose2d: the public runtime's 3-D convolution
|
| 802 |
+
has no transposed path, its 4-D one does (with groups)."""
|
| 803 |
+
y = F.conv_transpose2d(x.unsqueeze(2), w.unsqueeze(2), b, stride=(1, s), groups=groups)
|
| 804 |
+
return y.squeeze(2)
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def _convtr_step(x, w, b, partial, s, groups=1):
|
| 808 |
+
y = _convtr(x, w, b, s, groups)
|
| 809 |
+
pt = partial.shape[2]
|
| 810 |
+
n = y.shape[2]
|
| 811 |
+
head = y[:, :, :pt] + partial
|
| 812 |
+
out = torch.cat([head, y[:, :, pt : n - pt]], 2)
|
| 813 |
+
tail = y[:, :, n - pt :]
|
| 814 |
+
if b is not None:
|
| 815 |
+
tail = tail - b.view(1, -1, 1)
|
| 816 |
+
return out, tail
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def _conv_step(m, x, prev):
|
| 820 |
+
xx = torch.cat([prev, x], 2)
|
| 821 |
+
y = F.conv1d(xx, m.conv.weight, m.conv.bias)
|
| 822 |
+
return y, xx[:, :, xx.shape[2] - prev.shape[2] :]
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
class MimiStepProgram(nn.Module):
|
| 826 |
+
"""forward(latent[1,1,32], *state) -> pcm[1,1,1920], *new_state (MIMI_STATE order).
|
| 827 |
+
|
| 828 |
+
One latent frame per call, exactly the runtime's streaming decoder: every piece of streaming
|
| 829 |
+
state (conv tails, transposed-conv partial sums, the 2-layer transformer's last 250 keys and
|
| 830 |
+
values, which of them are filled, and the RoPE offset) is an explicit input and output. The
|
| 831 |
+
first call takes all-zero state."""
|
| 832 |
+
|
| 833 |
+
def __init__(self, w: PhononWeights):
|
| 834 |
+
super().__init__()
|
| 835 |
+
m = w.mimi
|
| 836 |
+
self.emb_std = nn.Parameter(w.flow_lm.emb_std.detach().clone().view(1, 1, LDIM), requires_grad=False)
|
| 837 |
+
self.emb_mean = nn.Parameter(w.flow_lm.emb_mean.detach().clone().view(1, 1, LDIM), requires_grad=False)
|
| 838 |
+
self.qproj = _LinP(m.quantizer.output_proj.weight.view(D, LDIM))
|
| 839 |
+
self.up_w = nn.Parameter(m.upsample.convtr.convtr.weight.detach().clone(), requires_grad=False)
|
| 840 |
+
self.layers = nn.ModuleList()
|
| 841 |
+
for L in m.decoder_transformer.transformer.layers:
|
| 842 |
+
q = nn.Module()
|
| 843 |
+
q.norm1, q.norm2 = L.norm1, L.norm2
|
| 844 |
+
q.in_proj = _LinP(_permuted_in_proj(L.self_attn.in_proj.weight))
|
| 845 |
+
q.out_proj, q.linear1, q.linear2 = L.self_attn.out_proj, L.linear1, L.linear2
|
| 846 |
+
q.ls1 = nn.Parameter(L.layer_scale_1.scale.detach().clone(), requires_grad=False)
|
| 847 |
+
q.ls2 = nn.Parameter(L.layer_scale_2.scale.detach().clone(), requires_grad=False)
|
| 848 |
+
self.layers.append(q)
|
| 849 |
+
self.dec = m.decoder.model
|
| 850 |
+
self.register_buffer("inv_freq", inv_freq().view(1, HD // 2), persistent=False)
|
| 851 |
+
self.register_buffer("steps", torch.arange(UPS, dtype=torch.float32).view(UPS, 1), persistent=False)
|
| 852 |
+
i = torch.arange(UPS)[:, None]
|
| 853 |
+
j = torch.arange(MIMI_CONTEXT + UPS)[None, :]
|
| 854 |
+
band = torch.where((j >= i) & (j <= i + MIMI_CONTEXT), 0.0, NEG)
|
| 855 |
+
self.register_buffer("band", band.view(1, 1, UPS, MIMI_CONTEXT + UPS), persistent=False)
|
| 856 |
+
self.register_buffer("ones_seen", torch.ones(1, 1, 1, UPS), persistent=False)
|
| 857 |
+
|
| 858 |
+
def _attn(self, L, x, kc, vc, seen, cos, sin):
|
| 859 |
+
T = UPS
|
| 860 |
+
h = layer_norm(L.norm1, x, 1e-5)
|
| 861 |
+
qkv = lin(L.in_proj, h)
|
| 862 |
+
q = qkv[..., :D].reshape(1, T, H, HD)
|
| 863 |
+
k = qkv[..., D : 2 * D].reshape(1, T, H, HD)
|
| 864 |
+
v = qkv[..., 2 * D :].reshape(1, T, H, HD)
|
| 865 |
+
rh = lambda t: torch.cat([-t[..., HD // 2 :], t[..., : HD // 2]], -1) # noqa: E731
|
| 866 |
+
q = q * cos + rh(q) * sin
|
| 867 |
+
k = k * cos + rh(k) * sin
|
| 868 |
+
q = q.permute(0, 2, 1, 3) # [1, H, T, HD]
|
| 869 |
+
k = k.permute(0, 2, 1, 3)
|
| 870 |
+
v = v.permute(0, 2, 1, 3)
|
| 871 |
+
kk = torch.cat([kc, k], 2) # [1, H, 266, HD]
|
| 872 |
+
vv = torch.cat([vc, v], 2)
|
| 873 |
+
seen_all = torch.cat([seen, self.ones_seen], 3)
|
| 874 |
+
mask = self.band + (seen_all - 1.0) * 1.0e30
|
| 875 |
+
sc = torch.bmm(q.reshape(H, T, HD), kk.reshape(H, MIMI_CONTEXT + T, HD).transpose(1, 2)) * (HD**-0.5)
|
| 876 |
+
pr = torch.softmax(sc.reshape(1, H, T, MIMI_CONTEXT + T) + mask, -1)
|
| 877 |
+
o = torch.bmm(pr.reshape(H, T, MIMI_CONTEXT + T), vv.reshape(H, MIMI_CONTEXT + T, HD))
|
| 878 |
+
o = o.reshape(1, H, T, HD).permute(0, 2, 1, 3).reshape(1, T, D)
|
| 879 |
+
x = x + L.ls1 * lin(L.out_proj, o)
|
| 880 |
+
h = layer_norm(L.norm2, x, 1e-5)
|
| 881 |
+
x = x + L.ls2 * lin(L.linear2, gelu(lin(L.linear1, h)))
|
| 882 |
+
return x, kk[:, :, UPS:], vv[:, :, UPS:], seen_all[..., UPS:]
|
| 883 |
+
|
| 884 |
+
def _res(self, blk, x, prev):
|
| 885 |
+
v, prev = _conv_step(blk.block[1], elu(x), prev)
|
| 886 |
+
v = F.conv1d(elu(v), blk.block[3].conv.weight, blk.block[3].conv.bias)
|
| 887 |
+
return x + v, prev
|
| 888 |
+
|
| 889 |
+
def forward(self, latent, up_p, k0, v0, k1, v1, seen, off, c0, u1, r1, u2, r2, u3, r3, cf):
|
| 890 |
+
x = latent * self.emb_std + self.emb_mean # [1, 1, 32]
|
| 891 |
+
x = lin(self.qproj, x).reshape(1, D, 1)
|
| 892 |
+
x, up_p = _convtr_step(x, self.up_w, None, up_p, UPS, groups=D) # [1, 512, 16]
|
| 893 |
+
pos = self.steps + off # [16, 1]
|
| 894 |
+
ang = pos * self.inv_freq # [16, 32]
|
| 895 |
+
cos = torch.cat([torch.cos(ang), torch.cos(ang)], -1).reshape(1, UPS, 1, HD)
|
| 896 |
+
sin = torch.cat([torch.sin(ang), torch.sin(ang)], -1).reshape(1, UPS, 1, HD)
|
| 897 |
+
x = x.permute(0, 2, 1) # [1, 16, 512]
|
| 898 |
+
x, k0, v0, seen0 = self._attn(self.layers[0], x, k0, v0, seen, cos, sin)
|
| 899 |
+
x, k1, v1, _ = self._attn(self.layers[1], x, k1, v1, seen, cos, sin)
|
| 900 |
+
x = x.permute(0, 2, 1) # [1, 512, 16]
|
| 901 |
+
m = self.dec
|
| 902 |
+
x, c0 = _conv_step(m[0], x, c0)
|
| 903 |
+
x, u1 = _convtr_step(elu(x), m[2].convtr.weight, m[2].convtr.bias, u1, 6)
|
| 904 |
+
x, r1 = self._res(m[3], x, r1)
|
| 905 |
+
x, u2 = _convtr_step(elu(x), m[5].convtr.weight, m[5].convtr.bias, u2, 5)
|
| 906 |
+
x, r2 = self._res(m[6], x, r2)
|
| 907 |
+
x, u3 = _convtr_step(elu(x), m[8].convtr.weight, m[8].convtr.bias, u3, 4)
|
| 908 |
+
x, r3 = self._res(m[9], x, r3)
|
| 909 |
+
pcm, cf = _conv_step(m[11], elu(x), cf)
|
| 910 |
+
return pcm, up_p, k0, v0, k1, v1, seen0, off + float(UPS), c0, u1, r1, u2, r2, u3, r3, cf
|
export/_whisper.py
ADDED
|
@@ -0,0 +1,662 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Whisper base building blocks for recipes/whisper-base.py.
|
| 2 |
+
|
| 3 |
+
Everything here is built from the pinned openai/whisper-base checkpoint loaded through transformers
|
| 4 |
+
(WhisperForConditionalGeneration); the program wrappers reuse its nn.Modules (weights are shared, not
|
| 5 |
+
copied) and only re-express the forward pass so that it lowers to one WebGPU delegate per program.
|
| 6 |
+
|
| 7 |
+
Program contract (same split and I/O as the playground's previous whisper-base export):
|
| 8 |
+
|
| 9 |
+
mel forward(frames[1,3000,400] f32) -> power_mel[1,3000,80] f32
|
| 10 |
+
frames: 30 s of 16 kHz audio, zero-padded to 480000 samples, reflect-padded by 200 on
|
| 11 |
+
both ends, 3000 windows of 400 samples at hop 160 (= whisper.js buildFrames).
|
| 12 |
+
power_mel = |rfft(hann_periodic * frame)|^2 @ mel_filters (no log; see host_log_mel).
|
| 13 |
+
encoder forward(log_mel[1,80,3000] f32) -> encoder_hidden[1,1500,512] f32 (fp32 weights)
|
| 14 |
+
cross_kv forward(encoder_hidden[1,1500,512]) -> 12 x [1,8,1500,64] f32, order k0,v0,...,k5,v5
|
| 15 |
+
(per decoder layer: encoder_attn.k_proj / v_proj, heads-first [B,H,S,D])
|
| 16 |
+
decoder_split forward(tok_embeds[1,64,512], k0, v0, ..., k5, v5) -> hidden[1,64,512]
|
| 17 |
+
tok_embeds: token embeddings WITHOUT positions for positions 0..64 (zero rows beyond
|
| 18 |
+
the live prefix); the program adds positions 0..63, runs causal self-attention over
|
| 19 |
+
the 64 rows and returns final-LayerNorm hidden states (row p predicts token p+1).
|
| 20 |
+
decode_stream forward(embed[1,1,512], input_pos[1] i64, k0, v0, ..., k5, v5) -> hidden[1,1,512]
|
| 21 |
+
embed = token embedding + positional embedding of `input_pos` (added on the host);
|
| 22 |
+
self-attention K/V cache [1,448,8,64] x 6 layers x {k,v} lives inside the program
|
| 23 |
+
(mutable buffers owned by the delegate); feed positions 0,1,2,... in order.
|
| 24 |
+
lmhead forward(hidden[1,1,512]) -> logits[1,1,51872] (tied to decoder.embed_tokens; rows
|
| 25 |
+
51865..51871 are padding with logit -1e9, see LMHeadProgram)
|
| 26 |
+
|
| 27 |
+
Precision (whisper-base.py --precision):
|
| 28 |
+
q4 (previous-export parity) cross_kv / decoder_split / decode_stream / lmhead linears are 4-bit groupwise
|
| 29 |
+
weight-only (torchao IntxWeightOnlyConfig int4, group 64, symmetric, "affine" qparams ->
|
| 30 |
+
et_vk.linear_q4gsw); int8 token-embedding table. mel and encoder are fp32.
|
| 31 |
+
fp32 every program fp32 (aten.linear on 2-D views); fp32 token-embedding table.
|
| 32 |
+
|
| 33 |
+
Host-side files (reproduced from the checkpoint by the recipe, consumed by the playground JS):
|
| 34 |
+
whisper_embed.i8.bin int8 [51865,512] round(embed_tokens / scale), scale = rowwise absmax/127 (q4)
|
| 35 |
+
whisper_embed.scale.f32.bin f32 [51865] the per-row scales (q4)
|
| 36 |
+
whisper_embed.f32.bin f32 [51865,512] embed_tokens (fp32)
|
| 37 |
+
whisper_pos_embed.f32.bin f32 [448,512] decoder.embed_positions.weight
|
| 38 |
+
vocab.json upstream tokenizer vocab (byte-level BPE, detokenization only)
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
import copy
|
| 42 |
+
import io
|
| 43 |
+
|
| 44 |
+
import numpy as np
|
| 45 |
+
import torch
|
| 46 |
+
import torch.nn.functional as F
|
| 47 |
+
|
| 48 |
+
SAMPLE_RATE = 16000
|
| 49 |
+
N_FFT = 400
|
| 50 |
+
HOP = 160
|
| 51 |
+
FRAMES = 3000
|
| 52 |
+
N_SAMPLES = FRAMES * HOP
|
| 53 |
+
PAD = N_FFT // 2
|
| 54 |
+
N_FREQ = N_FFT // 2 + 1
|
| 55 |
+
N_MELS = 80
|
| 56 |
+
ENC_LEN = 1500
|
| 57 |
+
D_MODEL = 512
|
| 58 |
+
N_HEADS = 8
|
| 59 |
+
HEAD_DIM = 64
|
| 60 |
+
N_LAYERS = 6
|
| 61 |
+
MAX_DEC = 64 # decoder_split rows; the playground's decode budget (prefix + generated)
|
| 62 |
+
KV_LEN = 448 # decode_stream self-attention cache length (= max_target_positions)
|
| 63 |
+
VOCAB = 51865
|
| 64 |
+
VOCAB_PADDED = 51872 # lmhead rows (multiple of 8, = the previous export)
|
| 65 |
+
PAD_LOGIT = -1e9
|
| 66 |
+
|
| 67 |
+
TOK = {
|
| 68 |
+
"sot": 50258,
|
| 69 |
+
"eot": 50257,
|
| 70 |
+
"en": 50259,
|
| 71 |
+
"transcribe": 50359,
|
| 72 |
+
"notimestamps": 50363,
|
| 73 |
+
}
|
| 74 |
+
PREFIX_EN = [TOK["sot"], TOK["en"], TOK["transcribe"], TOK["notimestamps"]]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# --------------------------------------------------------------------------------------------
|
| 78 |
+
# Host-side math that the playground does in JS (kept here so validation runs the same steps).
|
| 79 |
+
# --------------------------------------------------------------------------------------------
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def build_frames(pcm):
|
| 83 |
+
"""Mirror of whisper.js buildFrames(): [3000, 400] float32 windows (no window function)."""
|
| 84 |
+
pcm = np.asarray(pcm, dtype=np.float32)
|
| 85 |
+
base = np.zeros(N_SAMPLES + 2 * PAD, dtype=np.float32)
|
| 86 |
+
n = min(pcm.size, N_SAMPLES)
|
| 87 |
+
base[PAD : PAD + n] = pcm[:n]
|
| 88 |
+
for i in range(PAD):
|
| 89 |
+
base[PAD - 1 - i] = base[PAD + 1 + i]
|
| 90 |
+
base[PAD + N_SAMPLES + i] = base[PAD + N_SAMPLES - 2 - i]
|
| 91 |
+
idx = np.arange(FRAMES)[:, None] * HOP + np.arange(N_FFT)[None, :]
|
| 92 |
+
return base[idx]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def host_log_mel(power_mel):
|
| 96 |
+
"""Host step between the mel and encoder programs (WhisperFeatureExtractor normalization).
|
| 97 |
+
|
| 98 |
+
power_mel [1,3000,80] (or [3000,80]) -> log_mel [1,80,3000]:
|
| 99 |
+
x = log10(max(p, 1e-10)); x = max(x, max(x) - 8); x = (x + 4) / 4; transpose.
|
| 100 |
+
float32 throughout (the JS equivalent uses Float32Array + Math.log10).
|
| 101 |
+
"""
|
| 102 |
+
p = np.asarray(power_mel, dtype=np.float32).reshape(FRAMES, N_MELS)
|
| 103 |
+
x = np.log10(np.maximum(p, np.float32(1e-10))).astype(np.float32)
|
| 104 |
+
x = np.maximum(x, x.max() - np.float32(8.0))
|
| 105 |
+
x = ((x + np.float32(4.0)) / np.float32(4.0)).astype(np.float32)
|
| 106 |
+
return np.ascontiguousarray(x.T)[None]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class HostTables:
|
| 110 |
+
"""Token-embedding lookup as the playground JS does it, plus the files that carry the tables.
|
| 111 |
+
|
| 112 |
+
kind="int8": whisper_embed.i8.bin (int8 [51865,512], round(w / s)) + whisper_embed.scale.f32.bin
|
| 113 |
+
(s = rowwise absmax / 127): byte-identical to the previous export's files.
|
| 114 |
+
kind="fp32": whisper_embed.f32.bin (fp32 [51865,512], the checkpoint's embed_tokens).
|
| 115 |
+
Both: whisper_pos_embed.f32.bin (fp32 [448,512], decoder.embed_positions)."""
|
| 116 |
+
|
| 117 |
+
def __init__(self, model, kind):
|
| 118 |
+
e = model.model.decoder.embed_tokens.weight.detach().float()
|
| 119 |
+
self.kind = kind
|
| 120 |
+
self.pos = model.model.decoder.embed_positions.weight.detach().float().numpy()
|
| 121 |
+
if kind == "int8":
|
| 122 |
+
scale = e.abs().amax(dim=1) / 127.0
|
| 123 |
+
self.table = torch.round(e / scale[:, None]).clamp(-127, 127).to(torch.int8).numpy()
|
| 124 |
+
self.scale = scale.numpy().astype(np.float32)
|
| 125 |
+
elif kind == "fp32":
|
| 126 |
+
self.table = e.numpy().astype(np.float32)
|
| 127 |
+
self.scale = None
|
| 128 |
+
else:
|
| 129 |
+
raise ValueError(kind)
|
| 130 |
+
|
| 131 |
+
def embed(self, ids, position=None):
|
| 132 |
+
e = self.table[ids].astype(np.float32)
|
| 133 |
+
if self.scale is not None:
|
| 134 |
+
e = e * self.scale[ids][..., None]
|
| 135 |
+
if position is not None:
|
| 136 |
+
e = e + self.pos[position]
|
| 137 |
+
return e.astype(np.float32)
|
| 138 |
+
|
| 139 |
+
def files(self):
|
| 140 |
+
out = {}
|
| 141 |
+
if self.kind == "int8":
|
| 142 |
+
out["whisper_embed.i8.bin"] = self.table.tobytes()
|
| 143 |
+
out["whisper_embed.scale.f32.bin"] = self.scale.astype("<f4").tobytes()
|
| 144 |
+
else:
|
| 145 |
+
out["whisper_embed.f32.bin"] = self.table.astype("<f4").tobytes()
|
| 146 |
+
out["whisper_pos_embed.f32.bin"] = self.pos.astype("<f4").tobytes()
|
| 147 |
+
return out
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# --------------------------------------------------------------------------------------------
|
| 151 |
+
# Program wrappers.
|
| 152 |
+
# --------------------------------------------------------------------------------------------
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def dft_mel_weights(feature_extractor):
|
| 156 |
+
"""cos / -sin DFT rows with the periodic Hann window folded in, plus the HF mel filters."""
|
| 157 |
+
n = np.arange(N_FFT)
|
| 158 |
+
k = np.arange(N_FREQ)
|
| 159 |
+
window = 0.5 - 0.5 * np.cos(
|
| 160 |
+
2.0 * np.pi * n / N_FFT
|
| 161 |
+
) # periodic Hann (torch / HF default)
|
| 162 |
+
ang = 2.0 * np.pi * ((k[:, None] * n[None, :]) % N_FFT) / N_FFT
|
| 163 |
+
wc = (np.cos(ang) * window[None, :]).astype(np.float32)
|
| 164 |
+
ws = (-np.sin(ang) * window[None, :]).astype(np.float32)
|
| 165 |
+
mel = np.asarray(feature_extractor.mel_filters, dtype=np.float64).T.astype(
|
| 166 |
+
np.float32
|
| 167 |
+
)
|
| 168 |
+
assert mel.shape == (N_MELS, N_FREQ), mel.shape
|
| 169 |
+
return torch.from_numpy(wc), torch.from_numpy(ws), torch.from_numpy(mel)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class MelProgram(torch.nn.Module):
|
| 173 |
+
def __init__(self, feature_extractor):
|
| 174 |
+
super().__init__()
|
| 175 |
+
wc, ws, mel = dft_mel_weights(feature_extractor)
|
| 176 |
+
self.register_buffer("wc", wc)
|
| 177 |
+
self.register_buffer("ws", ws)
|
| 178 |
+
self.register_buffer("mel", mel)
|
| 179 |
+
|
| 180 |
+
def forward(self, frames):
|
| 181 |
+
x = frames.reshape(
|
| 182 |
+
FRAMES, N_FFT
|
| 183 |
+
) # aten.linear on the WebGPU runtime is 2-D only
|
| 184 |
+
re = F.linear(x, self.wc)
|
| 185 |
+
im = F.linear(x, self.ws)
|
| 186 |
+
return F.linear(re * re + im * im, self.mel).reshape(1, FRAMES, N_MELS)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _heads(x, s):
|
| 190 |
+
"""[s, 512] or [1, s, 512] -> [1, 8, s, 64]."""
|
| 191 |
+
return x.reshape(1, s, N_HEADS, HEAD_DIM).transpose(1, 2)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _merge(o, s):
|
| 195 |
+
"""[1, 8, s, 64] -> [1, s, 512]."""
|
| 196 |
+
return o.transpose(1, 2).reshape(1, s, D_MODEL)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def attention(q, k, v, mask, impl):
|
| 200 |
+
"""q/k/v [1,H,S,D]; scale = 1/sqrt(64) = 0.125 (a power of two, so applying it to q as HF does
|
| 201 |
+
or to q.k as the kernels do is bit-identical)."""
|
| 202 |
+
if impl == "et_vk":
|
| 203 |
+
import executorch.backends.vulkan.custom_ops_lib # noqa: F401 (torch.ops.et_vk.*)
|
| 204 |
+
|
| 205 |
+
return torch.ops.et_vk.sdpa(q, k, v, mask, None)
|
| 206 |
+
s = torch.matmul(q * 0.125, k.transpose(-2, -1))
|
| 207 |
+
if mask is not None:
|
| 208 |
+
s = s + mask
|
| 209 |
+
return torch.matmul(torch.softmax(s, dim=-1), v)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class EncoderProgram(torch.nn.Module):
|
| 213 |
+
"""HF WhisperEncoder forward re-expressed with 2-D fp32 linears.
|
| 214 |
+
|
| 215 |
+
attn="eager": matmul + softmax (lowered to aten.bmm/_softmax; activation memory is planned).
|
| 216 |
+
attn="et_vk": the fused et_vk.sdpa op (what the previous export used); on the public WebGPU
|
| 217 |
+
runtime each call allocates its own two [8,1500,1500] f32 scratch buffers (72 MB each).
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
def __init__(self, model, attn="eager"):
|
| 221 |
+
super().__init__()
|
| 222 |
+
self.enc = model.model.encoder
|
| 223 |
+
self.attn = attn
|
| 224 |
+
|
| 225 |
+
def forward(self, log_mel):
|
| 226 |
+
e = self.enc
|
| 227 |
+
x = F.gelu(e.conv1(log_mel))
|
| 228 |
+
x = F.gelu(e.conv2(x)) # [1, 512, 1500]
|
| 229 |
+
x = x.permute(0, 2, 1).reshape(ENC_LEN, D_MODEL) + e.embed_positions.weight
|
| 230 |
+
for layer in e.layers:
|
| 231 |
+
a = layer.self_attn
|
| 232 |
+
h = layer.self_attn_layer_norm(x)
|
| 233 |
+
q = _heads(a.q_proj(h), ENC_LEN)
|
| 234 |
+
k = _heads(a.k_proj(h), ENC_LEN)
|
| 235 |
+
v = _heads(a.v_proj(h), ENC_LEN)
|
| 236 |
+
o = attention(q, k, v, None, "et_vk" if self.attn == "et_vk" else "torch")
|
| 237 |
+
x = x + a.out_proj(o.transpose(1, 2).reshape(ENC_LEN, D_MODEL))
|
| 238 |
+
h = layer.final_layer_norm(x)
|
| 239 |
+
x = x + layer.fc2(F.gelu(layer.fc1(h)))
|
| 240 |
+
return e.layer_norm(x).reshape(1, ENC_LEN, D_MODEL)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _lin(m, x):
|
| 244 |
+
"""nn.Linear that lowers on the public WebGPU runtime: fp32 aten.linear only accepts 2-D
|
| 245 |
+
inputs, so fp32 weights get a [-1, K] view; int4 (q4gsw) linears accept any rank and keep it."""
|
| 246 |
+
if type(m.weight.data) is torch.Tensor and x.dim() != 2:
|
| 247 |
+
return m(x.reshape(-1, x.shape[-1])).reshape(*x.shape[:-1], m.out_features)
|
| 248 |
+
return m(x)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class CrossKVProgram(torch.nn.Module):
|
| 252 |
+
def __init__(self, decoder):
|
| 253 |
+
super().__init__()
|
| 254 |
+
self.layers = decoder.layers
|
| 255 |
+
|
| 256 |
+
def forward(self, enc):
|
| 257 |
+
out = []
|
| 258 |
+
for layer in self.layers:
|
| 259 |
+
a = layer.encoder_attn
|
| 260 |
+
out.append(_heads(_lin(a.k_proj, enc), ENC_LEN))
|
| 261 |
+
out.append(_heads(_lin(a.v_proj, enc), ENC_LEN))
|
| 262 |
+
return tuple(out)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _mlp(layer, x):
|
| 266 |
+
return x + _lin(layer.fc2, F.gelu(_lin(layer.fc1, layer.final_layer_norm(x))))
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _cross(layer, x, k, v, s, impl):
|
| 270 |
+
a = layer.encoder_attn
|
| 271 |
+
h = layer.encoder_attn_layer_norm(x)
|
| 272 |
+
o = attention(_heads(_lin(a.q_proj, h), s), k, v, None, impl)
|
| 273 |
+
return x + _lin(a.out_proj, _merge(o, s))
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class DecoderSplitProgram(torch.nn.Module):
|
| 277 |
+
"""Full-recompute decoder over MAX_DEC rows with a causal mask (no KV cache)."""
|
| 278 |
+
|
| 279 |
+
def __init__(self, decoder, attn="et_vk"):
|
| 280 |
+
super().__init__()
|
| 281 |
+
self.dec = decoder
|
| 282 |
+
self.attn = attn
|
| 283 |
+
self.register_buffer(
|
| 284 |
+
"pos", decoder.embed_positions.weight.detach()[:MAX_DEC].clone()
|
| 285 |
+
)
|
| 286 |
+
causal = torch.full((MAX_DEC, MAX_DEC), -1e30).triu(1) # same fill as the previous export
|
| 287 |
+
# et_vk.sdpa on the WebGPU runtime requires the full [B, H, S_q, S_kv] mask.
|
| 288 |
+
self.register_buffer(
|
| 289 |
+
"mask", causal.expand(1, N_HEADS, MAX_DEC, MAX_DEC).contiguous()
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
def forward(self, tok_embeds, *cross_kv):
|
| 293 |
+
x = tok_embeds + self.pos
|
| 294 |
+
for i, layer in enumerate(self.dec.layers):
|
| 295 |
+
a = layer.self_attn
|
| 296 |
+
h = layer.self_attn_layer_norm(x)
|
| 297 |
+
q = _heads(_lin(a.q_proj, h), MAX_DEC)
|
| 298 |
+
k = _heads(_lin(a.k_proj, h), MAX_DEC)
|
| 299 |
+
v = _heads(_lin(a.v_proj, h), MAX_DEC)
|
| 300 |
+
o = attention(q, k, v, self.mask, self.attn)
|
| 301 |
+
x = x + _lin(a.out_proj, _merge(o, MAX_DEC))
|
| 302 |
+
x = _cross(
|
| 303 |
+
layer, x, cross_kv[2 * i], cross_kv[2 * i + 1], MAX_DEC, self.attn
|
| 304 |
+
)
|
| 305 |
+
x = _mlp(layer, x)
|
| 306 |
+
return self.dec.layer_norm(x)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class DecodeStreamProgram(torch.nn.Module):
|
| 310 |
+
"""One token per call; self-attention K/V cache [1,448,8,64] per layer kept in the program.
|
| 311 |
+
|
| 312 |
+
Self-attention uses llama.update_cache + llama.custom_sdpa (executorch.extension.llm.custom_ops),
|
| 313 |
+
which the Vulkan partitioner fuses into sdpa_with_kv_cache with an et_vk.select_as_symint
|
| 314 |
+
position. Cross-attention uses et_vk.sdpa (attn="et_vk") or matmul/softmax (attn="torch").
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
def __init__(self, decoder, attn="et_vk"):
|
| 318 |
+
super().__init__()
|
| 319 |
+
from executorch.extension.llm.custom_ops import custom_ops # noqa: F401
|
| 320 |
+
|
| 321 |
+
self.dec = decoder
|
| 322 |
+
self.attn = attn
|
| 323 |
+
for i in range(N_LAYERS):
|
| 324 |
+
self.register_buffer(
|
| 325 |
+
f"k_cache_{i}",
|
| 326 |
+
torch.zeros(1, KV_LEN, N_HEADS, HEAD_DIM),
|
| 327 |
+
persistent=False,
|
| 328 |
+
)
|
| 329 |
+
self.register_buffer(
|
| 330 |
+
f"v_cache_{i}",
|
| 331 |
+
torch.zeros(1, KV_LEN, N_HEADS, HEAD_DIM),
|
| 332 |
+
persistent=False,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
def reset(self):
|
| 336 |
+
for i in range(N_LAYERS):
|
| 337 |
+
getattr(self, f"k_cache_{i}").zero_()
|
| 338 |
+
getattr(self, f"v_cache_{i}").zero_()
|
| 339 |
+
|
| 340 |
+
def forward(self, embed, input_pos, *cross_kv):
|
| 341 |
+
pos = input_pos[0].item()
|
| 342 |
+
torch._check_is_size(pos)
|
| 343 |
+
torch._check(pos < KV_LEN)
|
| 344 |
+
x = embed
|
| 345 |
+
for i, layer in enumerate(self.dec.layers):
|
| 346 |
+
a = layer.self_attn
|
| 347 |
+
h = layer.self_attn_layer_norm(x)
|
| 348 |
+
q = _lin(a.q_proj, h).view(1, 1, N_HEADS, HEAD_DIM)
|
| 349 |
+
k = _lin(a.k_proj, h).view(1, 1, N_HEADS, HEAD_DIM)
|
| 350 |
+
v = _lin(a.v_proj, h).view(1, 1, N_HEADS, HEAD_DIM)
|
| 351 |
+
kc = getattr(self, f"k_cache_{i}")
|
| 352 |
+
vc = getattr(self, f"v_cache_{i}")
|
| 353 |
+
torch.ops.llama.update_cache(k, kc, pos)
|
| 354 |
+
torch.ops.llama.update_cache(v, vc, pos)
|
| 355 |
+
o = torch.ops.llama.custom_sdpa(q, kc, vc, pos, None, 0.0, True, None)
|
| 356 |
+
x = x + _lin(a.out_proj, o.reshape(1, 1, D_MODEL))
|
| 357 |
+
x = _cross(layer, x, cross_kv[2 * i], cross_kv[2 * i + 1], 1, self.attn)
|
| 358 |
+
x = _mlp(layer, x)
|
| 359 |
+
return self.dec.layer_norm(x)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class LMHeadProgram(torch.nn.Module):
|
| 363 |
+
"""Tied output projection. The vocab is padded to `pad_to` rows: executorch 1.5.1's q4gsw
|
| 364 |
+
lowering pads the scales to a multiple of 4 output channels and then fails its own shape
|
| 365 |
+
check for N = 51865, so N must already be a multiple of 4 (the previous export used 51872).
|
| 366 |
+
Padded rows have zero weights and a -1e9 bias, so they can never win an argmax."""
|
| 367 |
+
|
| 368 |
+
def __init__(self, model, pad_to=0):
|
| 369 |
+
super().__init__()
|
| 370 |
+
w = model.model.decoder.embed_tokens.weight.detach().clone()
|
| 371 |
+
n = w.shape[0]
|
| 372 |
+
b = torch.zeros(max(n, pad_to))
|
| 373 |
+
if pad_to and pad_to > n:
|
| 374 |
+
w = torch.cat([w, w.new_zeros(pad_to - n, w.shape[1])])
|
| 375 |
+
b[n:] = PAD_LOGIT
|
| 376 |
+
self.proj = torch.nn.Linear(D_MODEL, w.shape[0], bias=True)
|
| 377 |
+
self.proj.weight = torch.nn.Parameter(w, requires_grad=False)
|
| 378 |
+
self.proj.bias = torch.nn.Parameter(b, requires_grad=False)
|
| 379 |
+
|
| 380 |
+
def forward(self, hidden):
|
| 381 |
+
return _lin(self.proj, hidden)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
# --------------------------------------------------------------------------------------------
|
| 385 |
+
# Quantization.
|
| 386 |
+
# --------------------------------------------------------------------------------------------
|
| 387 |
+
|
| 388 |
+
Q4_DESC = (
|
| 389 |
+
"torchao.quantization.quant_api.IntxWeightOnlyConfig(weight_dtype=torch.int4, "
|
| 390 |
+
"granularity=PerGroup(64), intx_choose_qparams_algorithm='affine') applied with quantize_ to "
|
| 391 |
+
"every nn.Linear of the program; symmetric, scale = group absmax / 7.5, q in [-8, 7]"
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def quantize_q4(module, group_size=64):
|
| 396 |
+
from torchao.quantization.granularity import PerGroup
|
| 397 |
+
from torchao.quantization.quant_api import IntxWeightOnlyConfig, quantize_
|
| 398 |
+
|
| 399 |
+
quantize_(
|
| 400 |
+
module,
|
| 401 |
+
IntxWeightOnlyConfig(
|
| 402 |
+
weight_dtype=torch.int4,
|
| 403 |
+
granularity=PerGroup(group_size),
|
| 404 |
+
intx_choose_qparams_algorithm="affine",
|
| 405 |
+
),
|
| 406 |
+
)
|
| 407 |
+
return module
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
Q8_HEAD_DESC = (
|
| 411 |
+
"PT2E with executorch.backends.vulkan.quantizer.VulkanQuantizer: weights int8 per-output-channel "
|
| 412 |
+
"symmetric (PerChannelMinMaxObserver, the quantizer's own weight spec), input activation int8 "
|
| 413 |
+
"per-tensor affine STATIC (HistogramObserver) calibrated on lmhead inputs; lowers to "
|
| 414 |
+
"quantized_decomposed.quantize_per_tensor + et_vk.linear_q8ta_q8csw"
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def q8_lmhead(lm, calib_hidden):
|
| 419 |
+
"""Static-activation int8 x per-channel int8 lmhead (the only 8-bit linear executorch 1.5.1's
|
| 420 |
+
Vulkan lowering emits that the public WebGPU runtime registers). Returns the converted GraphModule
|
| 421 |
+
and the (input scale, zero point, dequantized weight) needed for an equivalent portable module."""
|
| 422 |
+
from executorch.backends.vulkan.quantizer.vulkan_quantizer import (
|
| 423 |
+
get_symmetric_quantization_config,
|
| 424 |
+
VulkanQuantizer,
|
| 425 |
+
)
|
| 426 |
+
from torchao.quantization.pt2e import HistogramObserver
|
| 427 |
+
from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e
|
| 428 |
+
from torchao.quantization.pt2e.quantizer import QuantizationConfig, QuantizationSpec
|
| 429 |
+
|
| 430 |
+
base = get_symmetric_quantization_config(is_dynamic=False, weight_bits=8)
|
| 431 |
+
act = QuantizationSpec(
|
| 432 |
+
dtype=torch.int8,
|
| 433 |
+
quant_min=-128,
|
| 434 |
+
quant_max=127,
|
| 435 |
+
qscheme=torch.per_tensor_affine,
|
| 436 |
+
is_dynamic=False,
|
| 437 |
+
observer_or_fake_quant_ctr=HistogramObserver,
|
| 438 |
+
)
|
| 439 |
+
cfg = QuantizationConfig(
|
| 440 |
+
input_activation=act, output_activation=None, weight=base.weight, bias=None, is_qat=False
|
| 441 |
+
)
|
| 442 |
+
with torch.no_grad():
|
| 443 |
+
gm = torch.export.export(lm.eval(), (calib_hidden[:1],), strict=False).module()
|
| 444 |
+
gm = prepare_pt2e(gm, VulkanQuantizer().set_global(cfg))
|
| 445 |
+
for i in range(calib_hidden.shape[0]):
|
| 446 |
+
gm(calib_hidden[i : i + 1])
|
| 447 |
+
gm = convert_pt2e(gm)
|
| 448 |
+
qp, wdq = None, None
|
| 449 |
+
for n in gm.graph.nodes:
|
| 450 |
+
if n.op != "call_function":
|
| 451 |
+
continue
|
| 452 |
+
name = str(n.target)
|
| 453 |
+
if "quantize_per_tensor" in name and "dequantize" not in name and qp is None:
|
| 454 |
+
qp = (float(n.args[1]), int(n.args[2]))
|
| 455 |
+
if "dequantize_per_channel" in name:
|
| 456 |
+
w = getattr(gm, n.args[0].target)
|
| 457 |
+
sc = getattr(gm, n.args[1].target)
|
| 458 |
+
wdq = (w.float() * sc.float()[:, None]).contiguous()
|
| 459 |
+
if qp is None or wdq is None:
|
| 460 |
+
raise RuntimeError("q8 lmhead: could not find the quantize/dequantize nodes")
|
| 461 |
+
return gm, qp, wdq
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
class FakeQ8LMHead(torch.nn.Module):
|
| 465 |
+
"""Portable-runtime equivalent of the q8 lmhead: per-tensor int8 fake-quant of the input, then
|
| 466 |
+
an fp32 linear on the dequantized int8 weights (same bias)."""
|
| 467 |
+
|
| 468 |
+
def __init__(self, lm, qp, wdq):
|
| 469 |
+
super().__init__()
|
| 470 |
+
self.scale, self.zp = qp
|
| 471 |
+
self.register_buffer("w", wdq)
|
| 472 |
+
self.register_buffer("b", lm.proj.bias.detach().clone())
|
| 473 |
+
|
| 474 |
+
def forward(self, hidden):
|
| 475 |
+
x = hidden.reshape(-1, D_MODEL)
|
| 476 |
+
q = torch.clamp(torch.round(x / self.scale) + self.zp, -128, 127)
|
| 477 |
+
x = (q - self.zp) * self.scale
|
| 478 |
+
return F.linear(x, self.w, self.b).reshape(*hidden.shape[:-1], self.w.shape[0])
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def word_errors(tokenizer, hyp_text, ref_text):
|
| 482 |
+
"""(edits, reference words) after WhisperTokenizer.normalize (English text normalizer)."""
|
| 483 |
+
h = tokenizer.normalize(hyp_text).split()
|
| 484 |
+
r = tokenizer.normalize(ref_text).split()
|
| 485 |
+
d = list(range(len(r) + 1))
|
| 486 |
+
for i in range(1, len(h) + 1):
|
| 487 |
+
prev, d[0] = d[0], i
|
| 488 |
+
for j in range(1, len(r) + 1):
|
| 489 |
+
cur = d[j]
|
| 490 |
+
d[j] = min(d[j] + 1, d[j - 1] + 1, prev + (h[i - 1] != r[j - 1]))
|
| 491 |
+
prev = cur
|
| 492 |
+
return d[len(r)], len(r)
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def dequantized_copy(module):
|
| 496 |
+
"""Same module with every quantized linear weight replaced by its fp32 dequantization.
|
| 497 |
+
|
| 498 |
+
Used only for the CPU portable .pte (the portable runtime has no torchao kernels); its numerics
|
| 499 |
+
are the q4 numerics (dequantize-then-fp32-matmul, as the q4gsw kernels compute)."""
|
| 500 |
+
m = copy.deepcopy(module)
|
| 501 |
+
for sub in m.modules():
|
| 502 |
+
if isinstance(sub, torch.nn.Linear) and hasattr(sub.weight, "dequantize"):
|
| 503 |
+
sub.weight = torch.nn.Parameter(
|
| 504 |
+
sub.weight.dequantize().float(), requires_grad=False
|
| 505 |
+
)
|
| 506 |
+
return m
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# --------------------------------------------------------------------------------------------
|
| 510 |
+
# Speech sample.
|
| 511 |
+
# --------------------------------------------------------------------------------------------
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def load_librispeech_dummy(parquet_path, max_sec=15.0, count=8, longer=False):
|
| 515 |
+
"""First `count` clips (in file order) no longer than max_sec seconds, as 16 kHz float32.
|
| 516 |
+
longer=True selects the clips *longer* than max_sec instead (used only for calibration, so
|
| 517 |
+
calibration and evaluation clips never overlap)."""
|
| 518 |
+
import pyarrow.parquet as pq
|
| 519 |
+
import soundfile as sf
|
| 520 |
+
|
| 521 |
+
table = pq.read_table(parquet_path).to_pylist()
|
| 522 |
+
clips = []
|
| 523 |
+
for row in table:
|
| 524 |
+
audio, sr = sf.read(io.BytesIO(row["audio"]["bytes"]), dtype="float32")
|
| 525 |
+
if sr != SAMPLE_RATE:
|
| 526 |
+
raise ValueError(f"unexpected sample rate {sr}")
|
| 527 |
+
if audio.ndim != 1:
|
| 528 |
+
audio = audio.mean(axis=1)
|
| 529 |
+
if (audio.size / SAMPLE_RATE > max_sec) != longer:
|
| 530 |
+
continue
|
| 531 |
+
clips.append({"id": row["id"], "text": row["text"], "pcm": audio})
|
| 532 |
+
if len(clips) >= count:
|
| 533 |
+
break
|
| 534 |
+
return clips
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def seconds(pcm):
|
| 538 |
+
return round(len(pcm) / SAMPLE_RATE, 3)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def isclose_report(a, b):
|
| 542 |
+
a = np.asarray(a, dtype=np.float64).ravel()
|
| 543 |
+
b = np.asarray(b, dtype=np.float64).ravel()
|
| 544 |
+
d = np.abs(a - b)
|
| 545 |
+
cos = float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-30))
|
| 546 |
+
return {
|
| 547 |
+
"max_abs": float(d.max()),
|
| 548 |
+
"mean_abs": float(d.mean()),
|
| 549 |
+
"max_rel_to_absmax": float(d.max() / (np.abs(b).max() + 1e-30)),
|
| 550 |
+
"cosine": cos,
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
# --------------------------------------------------------------------------------------------
|
| 556 |
+
# Lowered-graph inspection (what the WebGPU runtime will see).
|
| 557 |
+
# --------------------------------------------------------------------------------------------
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _vk_graphs(pte_bytes):
|
| 561 |
+
from executorch.backends.vulkan.serialization.vulkan_graph_serialize import (
|
| 562 |
+
extract_vk_flatbuffer,
|
| 563 |
+
flatbuffer_to_vk_graph,
|
| 564 |
+
)
|
| 565 |
+
from executorch.exir._serialize._program import deserialize_pte_binary
|
| 566 |
+
|
| 567 |
+
pte = deserialize_pte_binary(pte_bytes)
|
| 568 |
+
prog = pte.program if hasattr(pte, "program") else pte
|
| 569 |
+
seg_base = int.from_bytes(pte_bytes[24:32], "little")
|
| 570 |
+
out = []
|
| 571 |
+
for plan in prog.execution_plan:
|
| 572 |
+
for d in plan.delegates:
|
| 573 |
+
proc = d.processed
|
| 574 |
+
if proc.location.name == "INLINE":
|
| 575 |
+
blob = prog.backend_delegate_data[proc.index].data
|
| 576 |
+
else:
|
| 577 |
+
seg = prog.segments[proc.index]
|
| 578 |
+
blob = pte_bytes[seg_base + seg.offset : seg_base + seg.offset + seg.size]
|
| 579 |
+
out.append(flatbuffer_to_vk_graph(extract_vk_flatbuffer(blob)))
|
| 580 |
+
return prog, out
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def program_io(pte_bytes):
|
| 584 |
+
"""Method names and their input/output tensor shapes + dtypes from the serialized program."""
|
| 585 |
+
from executorch.exir._serialize._program import deserialize_pte_binary
|
| 586 |
+
|
| 587 |
+
pte = deserialize_pte_binary(pte_bytes)
|
| 588 |
+
prog = pte.program if hasattr(pte, "program") else pte
|
| 589 |
+
res = {}
|
| 590 |
+
for plan in prog.execution_plan:
|
| 591 |
+
|
| 592 |
+
def desc(i):
|
| 593 |
+
v = plan.values[i].val
|
| 594 |
+
if hasattr(v, "sizes"):
|
| 595 |
+
return {"shape": list(v.sizes), "dtype": v.scalar_type.name.lower()}
|
| 596 |
+
return {"kind": type(v).__name__}
|
| 597 |
+
|
| 598 |
+
res[plan.name] = {
|
| 599 |
+
"inputs": [desc(i) for i in plan.inputs],
|
| 600 |
+
"outputs": [desc(i) for i in plan.outputs],
|
| 601 |
+
}
|
| 602 |
+
return res
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def vk_checks(pte_bytes, runtime_ops=None):
|
| 606 |
+
"""Checks against constraints of the public WebGPU runtime's op implementations
|
| 607 |
+
(backends/webgpu/runtime/ops): op registered, aten.linear 2-D, et_vk.sdpa mask shape,
|
| 608 |
+
sdpa_with_kv_cache without mask / with causal, fp32 tensors only."""
|
| 609 |
+
_, graphs = _vk_graphs(pte_bytes)
|
| 610 |
+
problems, notes = [], {}
|
| 611 |
+
for g in graphs:
|
| 612 |
+
vals = [v.value for v in g.values]
|
| 613 |
+
|
| 614 |
+
def t(i):
|
| 615 |
+
v = vals[i]
|
| 616 |
+
return v if type(v).__name__ == "VkTensor" else None
|
| 617 |
+
|
| 618 |
+
dtypes = sorted({type(v).__name__ if type(v).__name__ != "VkTensor" else v.datatype.name for v in vals})
|
| 619 |
+
notes["value_kinds"] = dtypes
|
| 620 |
+
for op in g.chain:
|
| 621 |
+
name = op.name
|
| 622 |
+
if runtime_ops is not None and name not in runtime_ops:
|
| 623 |
+
problems.append(f"{name}: not registered in the WebGPU runtime op list")
|
| 624 |
+
a = op.args
|
| 625 |
+
if name == "aten.linear.default":
|
| 626 |
+
ri, rw = len(t(a[0]).dims), len(t(a[1]).dims)
|
| 627 |
+
notes.setdefault("aten.linear input ranks", set()).add(ri)
|
| 628 |
+
if ri != 2 or rw != 2:
|
| 629 |
+
problems.append(f"aten.linear with input rank {ri}, weight rank {rw} (runtime needs 2-D)")
|
| 630 |
+
if name == "et_vk.sdpa.default":
|
| 631 |
+
q, k = t(a[0]), t(a[1])
|
| 632 |
+
m = t(a[3])
|
| 633 |
+
if m is not None:
|
| 634 |
+
need = q.dims[0] * q.dims[1] * q.dims[2] * k.dims[2]
|
| 635 |
+
got = int(np.prod(m.dims))
|
| 636 |
+
if need != got:
|
| 637 |
+
problems.append(f"et_vk.sdpa mask numel {got} != B*H*Sq*Skv {need}")
|
| 638 |
+
notes.setdefault("et_vk.sdpa q/k/mask", set()).add(
|
| 639 |
+
(tuple(q.dims), tuple(k.dims), tuple(m.dims) if m is not None else None)
|
| 640 |
+
)
|
| 641 |
+
if name == "sdpa_with_kv_cache.default":
|
| 642 |
+
mask_kind = type(vals[a[7]]).__name__
|
| 643 |
+
causal = vals[a[9]]
|
| 644 |
+
if mask_kind != "Null":
|
| 645 |
+
problems.append("sdpa_with_kv_cache with attn_mask (runtime rejects)")
|
| 646 |
+
if not (type(causal).__name__ == "Bool" and causal.bool_val):
|
| 647 |
+
problems.append(f"sdpa_with_kv_cache is_causal={causal} (runtime needs true)")
|
| 648 |
+
notes.setdefault("sdpa_with_kv_cache q/k_cache", set()).add(
|
| 649 |
+
(tuple(t(a[0]).dims), tuple(t(a[3]).dims), type(vals[a[5]]).__name__)
|
| 650 |
+
)
|
| 651 |
+
if name == "aten.convolution.default":
|
| 652 |
+
notes.setdefault("aten.convolution input/weight", set()).add(
|
| 653 |
+
(tuple(t(a[0]).dims), tuple(t(a[1]).dims))
|
| 654 |
+
)
|
| 655 |
+
for v in vals:
|
| 656 |
+
if type(v).__name__ == "VkTensor" and v.datatype.name not in ("FLOAT32", "INT32", "INT64", "UINT8", "INT8"):
|
| 657 |
+
problems.append(f"tensor dtype {v.datatype.name}")
|
| 658 |
+
break
|
| 659 |
+
for k, v in list(notes.items()):
|
| 660 |
+
if isinstance(v, set):
|
| 661 |
+
notes[k] = sorted(str(x) for x in v)
|
| 662 |
+
return {"problems": problems, "ok": not problems, "notes": notes}
|
export/phonon-31m-en.py
ADDED
|
@@ -0,0 +1,585 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Phonon 31M English (gradium/phonon-31m-en, Apache-2.0) -> two ExecuTorch WebGPU programs + host
|
| 3 |
+
tables, public ExecuTorch. Model code and per-program contract: recipes/_phonon.py.
|
| 4 |
+
|
| 5 |
+
phonon_flow_lm.pte forward(embeds f32[1,S,512] (1 <= S <= 128), input_pos i64[1], noise f32[1,32])
|
| 6 |
+
-> latent f32[1,32], eos_logit f32[1,1], next_embeds f32[1,1,512]
|
| 7 |
+
6-layer flow-LM transformer with its KV cache inside the program (512 positions),
|
| 8 |
+
the LSD flow head (1 step) and the next step's input embedding.
|
| 9 |
+
phonon_mimi.pte forward(latent f32[1,1,32], 15 state tensors) -> pcm f32[1,1,1920], 15 new states
|
| 10 |
+
one 80 ms frame of the streaming Mimi decoder; all state is explicit (zeros at start)
|
| 11 |
+
phonon_text_embed.bf16.bin the text conditioner table [4001, 512], bf16 exactly as in the checkpoint
|
| 12 |
+
phonon_bos_embed.f32.bin [512] the first step's input embedding
|
| 13 |
+
voice_<name>.f32.bin [125, 512] voice prompts (speaker latents through the speaker projection)
|
| 14 |
+
tokenizer.json, phonon.json tokenizer (upstream file) and the host contract (shapes, policy, state list)
|
| 15 |
+
|
| 16 |
+
Every program is lowered with executorch.backends.webgpu.partitioner.WebGPUPartitioner() into one
|
| 17 |
+
VulkanBackend delegate with no CPU kernels. The host does: text normalization + sentencepiece
|
| 18 |
+
tokenization, the embedding-table lookup, the noise (N(0, temperature), 32 values per frame), the EOS
|
| 19 |
+
rule (eos_logit > 4.0, then frames_after_eos more frames) and feeding next_embeds / Mimi state back.
|
| 20 |
+
|
| 21 |
+
python recipes/phonon-31m-en.py --out out/phonon-31m-en # export + CPU validation
|
| 22 |
+
python recipes/phonon-31m-en.py --out out/phonon-31m-en --no-validate # export only
|
| 23 |
+
python recipes/phonon-31m-en.py --out out/phonon-31m-en --ptts # also compare with the
|
| 24 |
+
# official runtime (pip install ptts==0.4.0)
|
| 25 |
+
|
| 26 |
+
Validation (CPU only; the WebGPU kernels cannot run here): the eager reference vs the torch.export
|
| 27 |
+
programs vs the portable .pte (ExecuTorch pybindings) over the full TTS loop with identical noise,
|
| 28 |
+
and with --ptts the official runtime's audio at temperature 0 (zero noise) for the same sentences.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import argparse
|
| 32 |
+
import json
|
| 33 |
+
import sys
|
| 34 |
+
import time
|
| 35 |
+
import wave
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
|
| 38 |
+
import numpy as np
|
| 39 |
+
import torch
|
| 40 |
+
|
| 41 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 42 |
+
import _common # noqa: E402
|
| 43 |
+
import _phonon as P # noqa: E402
|
| 44 |
+
import _whisper as W # noqa: E402 (generic lowered-graph checks: vk_checks, program_io, isclose_report)
|
| 45 |
+
|
| 46 |
+
UPSTREAM = {
|
| 47 |
+
"repo": "gradium/phonon-31m-en",
|
| 48 |
+
"revision": "52433c46975bfa13144c56204c9f4ee1c5b148aa",
|
| 49 |
+
"files": {
|
| 50 |
+
"model.safetensors": "8a04cf833cfe69b67c2ec968b2d31244655b9accc84ade9c0ebcc176f2074607",
|
| 51 |
+
"config.json": "7062ea376e6b158543c8abec8e5af67df171c49ad70eb7e2a0fb25c16f265e06",
|
| 52 |
+
"tokenizer.json": "691a00068fa7b989f2f3e5ae5daa2d1a5bb319f2d5360deafcfb19a8bb6e7936",
|
| 53 |
+
"tokenizer.model": "82e4572006d64d483317074c22c368e87779640b6f3a9dcd07b7caae32b030ce",
|
| 54 |
+
"default-voice.safetensors": "f739e8c4c76ee7f92e7c94a82002748c8cd22e99582ac49f7b9b94cd63786e18",
|
| 55 |
+
"README.md": "00f09ecdcd23ed9904f3a503baecc1f0c77515637ce6172b572ed3f50ce50c29",
|
| 56 |
+
},
|
| 57 |
+
}
|
| 58 |
+
VOICES = {
|
| 59 |
+
"repo": "gradium/phonon-voices",
|
| 60 |
+
"revision": "0ee17205f254b5abc43b266c8a0f215565c352f7",
|
| 61 |
+
"files": {
|
| 62 |
+
"voices/LMDIYE0Oa377Qh6Z.safetensors": "45c582673cb20edb04ddcca2b5a8865ddfb0a82599efadb269021e87d20fbdd4",
|
| 63 |
+
"voices.jsonl": "874f34998ce581b94f2b8912aa015639f52b5fd62eba3ba11e1b64dcaed7d802",
|
| 64 |
+
"README.md": "0186c7d586a9594db1e0283cb68e84e88bbd9bc3c29047cf0083c7483556f3ee",
|
| 65 |
+
},
|
| 66 |
+
# output name -> (repo, file); "default" is the model repo's own voice
|
| 67 |
+
"export": {
|
| 68 |
+
"default": ("model", "default-voice.safetensors"),
|
| 69 |
+
"en_us_easton": ("voices", "voices/LMDIYE0Oa377Qh6Z.safetensors"),
|
| 70 |
+
},
|
| 71 |
+
}
|
| 72 |
+
SENTENCES = [
|
| 73 |
+
"The quick brown fox jumps over the lazy dog.",
|
| 74 |
+
"This voice is generated by a small model running entirely on your device.",
|
| 75 |
+
"Please call me back when you have a moment, and we can talk about the plan.",
|
| 76 |
+
]
|
| 77 |
+
NOISE_SEED = 1000 # seeded case: noise[k] = randn(1, 32, Generator().manual_seed(NOISE_SEED + k)) * sqrt(temp)
|
| 78 |
+
NOISE_TEMP = 0.3 # the official runtime's default temperature
|
| 79 |
+
EOS_THRESHOLD = 4.0
|
| 80 |
+
SAMPLE_RATE = 24000
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def fetch():
|
| 84 |
+
paths, digests = {}, {}
|
| 85 |
+
for f, sha in UPSTREAM["files"].items():
|
| 86 |
+
paths[f], digests[f"{UPSTREAM['repo']}:{f}"] = _common.hf_file(
|
| 87 |
+
UPSTREAM["repo"], f, UPSTREAM["revision"], sha
|
| 88 |
+
)
|
| 89 |
+
vpaths = {}
|
| 90 |
+
for f, sha in VOICES["files"].items():
|
| 91 |
+
vpaths[f], digests[f"{VOICES['repo']}:{f}"] = _common.hf_file(
|
| 92 |
+
VOICES["repo"], f, VOICES["revision"], sha
|
| 93 |
+
)
|
| 94 |
+
return paths, vpaths, digests
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def flow_example():
|
| 98 |
+
return (
|
| 99 |
+
torch.randn(1, 5, P.D, generator=torch.Generator().manual_seed(0)),
|
| 100 |
+
torch.tensor([0]),
|
| 101 |
+
torch.zeros(1, P.LDIM),
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def mimi_example():
|
| 106 |
+
return (
|
| 107 |
+
torch.randn(1, 1, P.LDIM, generator=torch.Generator().manual_seed(0)),
|
| 108 |
+
*P.mimi_zero_state(),
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def export_flow(w):
|
| 113 |
+
with torch.no_grad():
|
| 114 |
+
return torch.export.export(
|
| 115 |
+
P.FlowLMProgram(w).eval(),
|
| 116 |
+
flow_example(),
|
| 117 |
+
dynamic_shapes=(
|
| 118 |
+
{1: torch.export.Dim("seq", min=1, max=P.PREFILL_MAX)},
|
| 119 |
+
None,
|
| 120 |
+
None,
|
| 121 |
+
),
|
| 122 |
+
strict=False,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def export_mimi(w):
|
| 127 |
+
with torch.no_grad():
|
| 128 |
+
return torch.export.export(
|
| 129 |
+
P.MimiStepProgram(w).eval(), mimi_example(), strict=False
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def lower_webgpu(ep, dynamic):
|
| 134 |
+
from executorch.backends.webgpu.partitioner import WebGPUPartitioner
|
| 135 |
+
from executorch.exir import to_edge_transform_and_lower
|
| 136 |
+
|
| 137 |
+
opts = {"require_dynamic_shapes": True, "force_fp16": False} if dynamic else None
|
| 138 |
+
part = WebGPUPartitioner(compile_options=opts) if opts else WebGPUPartitioner()
|
| 139 |
+
return to_edge_transform_and_lower(ep, partitioner=[part]).to_executorch()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def write_wav(path, pcm):
|
| 143 |
+
pcm16 = np.clip(
|
| 144 |
+
np.round(np.asarray(pcm, np.float64) * 32767), -32768, 32767
|
| 145 |
+
).astype("<i2")
|
| 146 |
+
with wave.open(str(path), "wb") as f:
|
| 147 |
+
f.setnchannels(1)
|
| 148 |
+
f.setsampwidth(2)
|
| 149 |
+
f.setframerate(SAMPLE_RATE)
|
| 150 |
+
f.writeframes(pcm16.tobytes())
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ---------------------------------------------------------------------------------------------
|
| 154 |
+
# Runners: flow(embeds, pos, noise) -> [latent, eos, next]; mimi(latent, *state) -> [pcm, *state]
|
| 155 |
+
# ---------------------------------------------------------------------------------------------
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class ModuleRunner:
|
| 159 |
+
def __init__(self, flow, mimi):
|
| 160 |
+
self.f, self.m = flow, mimi
|
| 161 |
+
|
| 162 |
+
def flow(self, e, p, n):
|
| 163 |
+
with torch.no_grad():
|
| 164 |
+
return [t.clone() for t in self.f(e, torch.tensor([p]), n)]
|
| 165 |
+
|
| 166 |
+
def mimi(self, *a):
|
| 167 |
+
with torch.no_grad():
|
| 168 |
+
return [t.clone() for t in self.m(*a)]
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class PteRunner:
|
| 172 |
+
def __init__(self, flow_bytes, mimi_bytes):
|
| 173 |
+
import executorch.extension.llm.custom_ops.custom_ops # noqa: F401 (portable llama::sdpa_with_kv_cache)
|
| 174 |
+
from executorch.extension.pybindings.portable_lib import (
|
| 175 |
+
_load_for_executorch_from_buffer,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
self.buffers = (flow_bytes, mimi_bytes) # the loaded programs point into these
|
| 179 |
+
self.f = _load_for_executorch_from_buffer(flow_bytes)
|
| 180 |
+
self.m = _load_for_executorch_from_buffer(mimi_bytes)
|
| 181 |
+
|
| 182 |
+
def flow(self, e, p, n):
|
| 183 |
+
return [
|
| 184 |
+
t.clone()
|
| 185 |
+
for t in self.f.forward([e.contiguous(), torch.tensor([p]), n.contiguous()])
|
| 186 |
+
]
|
| 187 |
+
|
| 188 |
+
def mimi(self, *a):
|
| 189 |
+
return [t.clone() for t in self.m.forward([t.contiguous() for t in a])]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def tts(run, voice_embeds, text_embeds, bos_embed, tokens, frames_after_eos, noise_fn):
|
| 193 |
+
"""The host loop a browser runs: voice prompt, text prompt, then step -> Mimi per frame."""
|
| 194 |
+
pos = 0
|
| 195 |
+
for e in (voice_embeds, text_embeds):
|
| 196 |
+
run.flow(e, pos, torch.zeros(1, P.LDIM))
|
| 197 |
+
pos += e.shape[1]
|
| 198 |
+
st = {"e": bos_embed, "pos": pos, "steps": []}
|
| 199 |
+
|
| 200 |
+
def step(prev, noise):
|
| 201 |
+
lat, eos, nxt = run.flow(st["e"], st["pos"], noise)
|
| 202 |
+
st["steps"].append(
|
| 203 |
+
{"in": st["e"], "noise": noise, "latent": lat, "eos": eos, "next": nxt}
|
| 204 |
+
)
|
| 205 |
+
st["pos"] += 1
|
| 206 |
+
st["e"] = nxt
|
| 207 |
+
return lat.view(1, 1, P.LDIM), eos
|
| 208 |
+
|
| 209 |
+
lats, logits = P.generate(step, tokens, frames_after_eos, noise_fn, EOS_THRESHOLD)
|
| 210 |
+
state, pcm = P.mimi_zero_state(), []
|
| 211 |
+
for lat in lats:
|
| 212 |
+
out = run.mimi(lat, *state)
|
| 213 |
+
pcm.append(out[0])
|
| 214 |
+
state = out[1:]
|
| 215 |
+
return (
|
| 216 |
+
torch.cat(lats, 1).numpy(),
|
| 217 |
+
np.array(logits),
|
| 218 |
+
torch.cat(pcm, 2).reshape(-1).numpy(),
|
| 219 |
+
st["steps"],
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def noise_fn(kind):
|
| 224 |
+
if kind == "zero":
|
| 225 |
+
return lambda k: torch.zeros(1, P.LDIM)
|
| 226 |
+
return lambda k: torch.randn(
|
| 227 |
+
1, P.LDIM, generator=torch.Generator().manual_seed(NOISE_SEED + k)
|
| 228 |
+
) * (NOISE_TEMP**0.5)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def eager_reference(w, voice_embeds, text_embeds, tokens, frames_after_eos, nfn):
|
| 232 |
+
lm = P.FlowLMRef(w)
|
| 233 |
+
lm.prompt(voice_embeds)
|
| 234 |
+
lm.prompt(text_embeds)
|
| 235 |
+
lats, logits = P.generate(lm.step, tokens, frames_after_eos, nfn, EOS_THRESHOLD)
|
| 236 |
+
mimi = P.MimiRef(w)
|
| 237 |
+
pcm = torch.cat([mimi.decode(lat) for lat in lats], 2).reshape(-1).numpy()
|
| 238 |
+
return torch.cat(lats, 1).numpy(), np.array(logits), pcm
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def write_browser_ref(
|
| 242 |
+
d,
|
| 243 |
+
sentence,
|
| 244 |
+
prepared,
|
| 245 |
+
tokens,
|
| 246 |
+
fae,
|
| 247 |
+
voice_embeds,
|
| 248 |
+
text_embeds,
|
| 249 |
+
bos_embed,
|
| 250 |
+
steps,
|
| 251 |
+
pcm,
|
| 252 |
+
noise,
|
| 253 |
+
):
|
| 254 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 255 |
+
f32 = lambda t: np.ascontiguousarray(np.asarray(t, np.float32)) # noqa: E731
|
| 256 |
+
f32(voice_embeds).tofile(d / "voice_embeds.f32")
|
| 257 |
+
f32(text_embeds).tofile(d / "text_embeds.f32")
|
| 258 |
+
f32(bos_embed).tofile(d / "bos_embed.f32")
|
| 259 |
+
np.stack([f32(s["noise"]).reshape(P.LDIM) for s in steps]).tofile(d / "noise.f32")
|
| 260 |
+
np.stack([f32(s["latent"]).reshape(P.LDIM) for s in steps]).tofile(
|
| 261 |
+
d / "ref_latents.f32"
|
| 262 |
+
)
|
| 263 |
+
np.array([float(s["eos"].reshape(-1)[0]) for s in steps], np.float32).tofile(
|
| 264 |
+
d / "ref_eos.f32"
|
| 265 |
+
)
|
| 266 |
+
np.stack([f32(s["next"]).reshape(P.D) for s in steps]).tofile(
|
| 267 |
+
d / "ref_next_embeds.f32"
|
| 268 |
+
)
|
| 269 |
+
f32(pcm).tofile(d / "ref_pcm.f32")
|
| 270 |
+
meta = {
|
| 271 |
+
"text": sentence,
|
| 272 |
+
"prepared": prepared,
|
| 273 |
+
"tokens": tokens,
|
| 274 |
+
"frames_after_eos": fae,
|
| 275 |
+
"frame_budget": P.frame_budget(len(tokens)),
|
| 276 |
+
"voice_len": int(voice_embeds.shape[1]),
|
| 277 |
+
"text_len": len(tokens),
|
| 278 |
+
"steps": len(steps),
|
| 279 |
+
"eos_threshold": EOS_THRESHOLD,
|
| 280 |
+
"noise": noise,
|
| 281 |
+
"pcm_samples": int(pcm.size),
|
| 282 |
+
"reference": "portable .pte on the ExecuTorch CPU runtime",
|
| 283 |
+
"mimi_state": [[n, list(s)] for n, s in P.MIMI_STATE],
|
| 284 |
+
}
|
| 285 |
+
(d / "meta.json").write_text(json.dumps(meta, indent=1) + "\n")
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def validate(args, out, w, tok, voices, bos_embed, eps, ptes):
|
| 289 |
+
t0 = time.time()
|
| 290 |
+
runners = {
|
| 291 |
+
"exported": ModuleRunner(eps["flow_lm"].module(), eps["mimi"].module()),
|
| 292 |
+
"portable_pte": PteRunner(ptes["flow_lm"], ptes["mimi"]),
|
| 293 |
+
}
|
| 294 |
+
report = {
|
| 295 |
+
"cpu_runtime": "executorch pybindings (portable_lib) from the pip wheel, with "
|
| 296 |
+
"executorch.extension.llm.custom_ops loaded (llama::sdpa_with_kv_cache kernel)",
|
| 297 |
+
"webgpu_pte_on_cpu": "not runnable: the pip wheel's pybindings have no WebGPU/Vulkan backend",
|
| 298 |
+
"reference": "_phonon.FlowLMRef / MimiRef: eager PyTorch that follows the official runtime "
|
| 299 |
+
"op by op (interleaved RoPE, nn.LayerNorm, 3-D conv / conv-transpose, Python-side streaming state)",
|
| 300 |
+
"cases": [],
|
| 301 |
+
}
|
| 302 |
+
oracle = None
|
| 303 |
+
if args.ptts:
|
| 304 |
+
import ptts
|
| 305 |
+
|
| 306 |
+
oracle = ptts.TTS(
|
| 307 |
+
f"hf://{UPSTREAM['repo']}@{UPSTREAM['revision']}",
|
| 308 |
+
quant="f32",
|
| 309 |
+
lang="en",
|
| 310 |
+
temperature=0.0,
|
| 311 |
+
)
|
| 312 |
+
report["ptts"] = {
|
| 313 |
+
"build_info": ptts.build_info(),
|
| 314 |
+
"quant": oracle.quant,
|
| 315 |
+
"temperature": 0.0,
|
| 316 |
+
"voice": "default",
|
| 317 |
+
}
|
| 318 |
+
venc = voices["default"]
|
| 319 |
+
cases = [(i, "zero") for i in range(len(SENTENCES))] + [(0, "seeded")]
|
| 320 |
+
for si, kind in cases:
|
| 321 |
+
ids, fae, prepared = P.tokenize(tok, SENTENCES[si])
|
| 322 |
+
temb = P.text_embedding(w.flow_lm, ids)
|
| 323 |
+
nfn = noise_fn(kind)
|
| 324 |
+
rl, re_, rpcm = eager_reference(w, venc, temb, ids, fae, nfn)
|
| 325 |
+
case = {
|
| 326 |
+
"sentence": si,
|
| 327 |
+
"text": SENTENCES[si],
|
| 328 |
+
"prepared": prepared,
|
| 329 |
+
"tokens": ids,
|
| 330 |
+
"noise": kind,
|
| 331 |
+
"reference_frames": int(rl.shape[1]),
|
| 332 |
+
}
|
| 333 |
+
if oracle is not None and kind == "zero":
|
| 334 |
+
opcm = oracle.synth(SENTENCES[si], voice="default")
|
| 335 |
+
case["ptts_frames"] = int(opcm.size // P.FRAME)
|
| 336 |
+
case["reference_vs_ptts"] = W.isclose_report(
|
| 337 |
+
rpcm[: opcm.size], opcm[: rpcm.size]
|
| 338 |
+
)
|
| 339 |
+
for rname, run in runners.items():
|
| 340 |
+
t = time.time()
|
| 341 |
+
lat, logits, pcm, steps = tts(run, venc, temb, bos_embed, ids, fae, nfn)
|
| 342 |
+
n = min(lat.shape[1], rl.shape[1])
|
| 343 |
+
r = {
|
| 344 |
+
"frames": int(lat.shape[1]),
|
| 345 |
+
"latents_vs_reference": W.isclose_report(lat[:, :n], rl[:, :n]),
|
| 346 |
+
"eos_logits_vs_reference": W.isclose_report(logits[:n], re_[:n]),
|
| 347 |
+
"pcm_vs_reference": W.isclose_report(
|
| 348 |
+
pcm[: n * P.FRAME], rpcm[: n * P.FRAME]
|
| 349 |
+
),
|
| 350 |
+
"seconds": round(time.time() - t, 1),
|
| 351 |
+
}
|
| 352 |
+
if oracle is not None and kind == "zero":
|
| 353 |
+
m = min(pcm.size, opcm.size)
|
| 354 |
+
r["pcm_vs_ptts"] = W.isclose_report(pcm[:m], opcm[:m])
|
| 355 |
+
case[rname] = r
|
| 356 |
+
if rname == "portable_pte":
|
| 357 |
+
if args.wavs:
|
| 358 |
+
(out / "samples").mkdir(exist_ok=True)
|
| 359 |
+
write_wav(out / "samples" / f"s{si}_{kind}_portable_pte.wav", pcm)
|
| 360 |
+
if args.browser_ref and (si, kind) in [(0, "seeded"), (2, "zero")]:
|
| 361 |
+
noise_desc = (
|
| 362 |
+
"zeros"
|
| 363 |
+
if kind == "zero"
|
| 364 |
+
else f"randn(1,32, Generator().manual_seed({NOISE_SEED}+k)) * sqrt({NOISE_TEMP})"
|
| 365 |
+
)
|
| 366 |
+
write_browser_ref(
|
| 367 |
+
Path(args.browser_ref) / f"s{si}_{kind}",
|
| 368 |
+
SENTENCES[si],
|
| 369 |
+
prepared,
|
| 370 |
+
ids,
|
| 371 |
+
fae,
|
| 372 |
+
venc.numpy(),
|
| 373 |
+
temb.numpy(),
|
| 374 |
+
bos_embed.numpy(),
|
| 375 |
+
steps,
|
| 376 |
+
pcm,
|
| 377 |
+
noise_desc,
|
| 378 |
+
)
|
| 379 |
+
report["cases"].append(case)
|
| 380 |
+
print(
|
| 381 |
+
f"[validate] s{si} {kind}: "
|
| 382 |
+
+ json.dumps(
|
| 383 |
+
{k: case[k] for k in case if k in ("reference_frames", "ptts_frames")}
|
| 384 |
+
| {
|
| 385 |
+
k: {
|
| 386 |
+
"frames": v["frames"],
|
| 387 |
+
"pcm_cos": v["pcm_vs_reference"]["cosine"],
|
| 388 |
+
}
|
| 389 |
+
for k, v in case.items()
|
| 390 |
+
if isinstance(v, dict) and "frames" in v
|
| 391 |
+
}
|
| 392 |
+
),
|
| 393 |
+
flush=True,
|
| 394 |
+
)
|
| 395 |
+
report["seconds"] = round(time.time() - t0, 1)
|
| 396 |
+
(out / "validation.json").write_text(json.dumps(report, indent=2) + "\n")
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def main():
|
| 400 |
+
ap = argparse.ArgumentParser(
|
| 401 |
+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
| 402 |
+
)
|
| 403 |
+
ap.add_argument("--out", required=True, help="output directory")
|
| 404 |
+
ap.add_argument(
|
| 405 |
+
"--no-validate", action="store_true", help="export only (no CPU validation)"
|
| 406 |
+
)
|
| 407 |
+
ap.add_argument(
|
| 408 |
+
"--ptts",
|
| 409 |
+
action="store_true",
|
| 410 |
+
help="also compare with the official runtime (pip install ptts==0.4.0)",
|
| 411 |
+
)
|
| 412 |
+
ap.add_argument(
|
| 413 |
+
"--wavs",
|
| 414 |
+
action="store_true",
|
| 415 |
+
help="write the portable .pte audio to <out>/samples",
|
| 416 |
+
)
|
| 417 |
+
ap.add_argument(
|
| 418 |
+
"--browser-ref", help="directory for the browser harness's reference tensors"
|
| 419 |
+
)
|
| 420 |
+
ap.add_argument(
|
| 421 |
+
"--keep-portable",
|
| 422 |
+
action="store_true",
|
| 423 |
+
help="also write the CPU-only portable .pte files",
|
| 424 |
+
)
|
| 425 |
+
ap.add_argument(
|
| 426 |
+
"--runtime-ops",
|
| 427 |
+
help="optional text file, one registered WebGPU runtime op per line",
|
| 428 |
+
)
|
| 429 |
+
args = ap.parse_args()
|
| 430 |
+
out = Path(args.out)
|
| 431 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 432 |
+
torch.manual_seed(0)
|
| 433 |
+
torch.set_grad_enabled(False)
|
| 434 |
+
|
| 435 |
+
paths, vpaths, digests = fetch()
|
| 436 |
+
w = P.load_weights(
|
| 437 |
+
paths["model.safetensors"]
|
| 438 |
+
) # strict: every checkpoint tensor has a home
|
| 439 |
+
tok = P.tokenizer(paths["tokenizer.json"])
|
| 440 |
+
runtime_ops = None
|
| 441 |
+
if args.runtime_ops:
|
| 442 |
+
runtime_ops = {
|
| 443 |
+
line.strip()
|
| 444 |
+
for line in Path(args.runtime_ops).read_text().splitlines()
|
| 445 |
+
if line.strip()
|
| 446 |
+
}
|
| 447 |
+
|
| 448 |
+
files, graphs, checks, io, eps, ptes = {}, {}, {}, {}, {}, {}
|
| 449 |
+
for name, make, dyn in [
|
| 450 |
+
("flow_lm", export_flow, True),
|
| 451 |
+
("mimi", export_mimi, False),
|
| 452 |
+
]:
|
| 453 |
+
t = time.time()
|
| 454 |
+
ep = make(w)
|
| 455 |
+
prog = lower_webgpu(ep, dyn)
|
| 456 |
+
path = out / f"phonon_{name}.pte"
|
| 457 |
+
path.unlink(missing_ok=True)
|
| 458 |
+
path.write_bytes(prog.buffer)
|
| 459 |
+
graphs[name] = _common.delegate_summary(prog.buffer)
|
| 460 |
+
checks[name] = W.vk_checks(prog.buffer, runtime_ops)
|
| 461 |
+
io[name] = W.program_io(prog.buffer)
|
| 462 |
+
files[path.name] = {
|
| 463 |
+
"bytes": path.stat().st_size,
|
| 464 |
+
"sha256": _common.sha256_file(path),
|
| 465 |
+
}
|
| 466 |
+
eps[name] = make(w) # fresh program: lowering consumes its input
|
| 467 |
+
if not args.no_validate or args.keep_portable:
|
| 468 |
+
ptes[name] = _common.lower_portable(make(w)).buffer
|
| 469 |
+
if args.keep_portable:
|
| 470 |
+
(out / "portable").mkdir(exist_ok=True)
|
| 471 |
+
(out / "portable" / f"phonon_{name}_portable.pte").write_bytes(
|
| 472 |
+
ptes[name]
|
| 473 |
+
)
|
| 474 |
+
del prog
|
| 475 |
+
print(
|
| 476 |
+
f"[export] {path.name}: {files[path.name]['bytes']} B, {time.time() - t:.1f} s, checks ok={checks[name]['ok']}, "
|
| 477 |
+
f"non-delegated={graphs[name]['non_delegated_kernels']}, delegates={len(graphs[name]['delegates'])}",
|
| 478 |
+
flush=True,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
# Host tables.
|
| 482 |
+
from safetensors.torch import load_file
|
| 483 |
+
|
| 484 |
+
emb = load_file(str(paths["model.safetensors"]))[
|
| 485 |
+
"flow_lm.condition_provider.conditioners.transcript_in_segment.embed.weight"
|
| 486 |
+
]
|
| 487 |
+
assert emb.dtype == torch.bfloat16 and tuple(emb.shape) == (4001, P.D)
|
| 488 |
+
host = {
|
| 489 |
+
"phonon_text_embed.bf16.bin": emb.contiguous()
|
| 490 |
+
.view(torch.int16)
|
| 491 |
+
.numpy()
|
| 492 |
+
.tobytes()
|
| 493 |
+
}
|
| 494 |
+
bos_embed = P.lin(
|
| 495 |
+
w.flow_lm.input_linear, w.flow_lm.bos_emb.view(1, 1, P.LDIM)
|
| 496 |
+
) + P.summed_conditions(w.flow_lm)
|
| 497 |
+
host["phonon_bos_embed.f32.bin"] = bos_embed.numpy().astype("<f4").tobytes()
|
| 498 |
+
voices = {}
|
| 499 |
+
for vname, (src, f) in VOICES["export"].items():
|
| 500 |
+
sw = P.load_voice(paths[f] if src == "model" else vpaths[f])
|
| 501 |
+
voices[vname] = P.voice_embedding(w.flow_lm, sw)
|
| 502 |
+
host[f"voice_{vname}.f32.bin"] = voices[vname].numpy().astype("<f4").tobytes()
|
| 503 |
+
host["tokenizer.json"] = paths["tokenizer.json"].read_bytes()
|
| 504 |
+
for fname, blob in host.items():
|
| 505 |
+
(out / fname).unlink(missing_ok=True)
|
| 506 |
+
(out / fname).write_bytes(blob)
|
| 507 |
+
files[fname] = {"bytes": len(blob), "sha256": _common.sha256_file(out / fname)}
|
| 508 |
+
|
| 509 |
+
contract = {
|
| 510 |
+
"sample_rate": SAMPLE_RATE,
|
| 511 |
+
"frame_samples": P.FRAME,
|
| 512 |
+
"frame_rate": 12.5,
|
| 513 |
+
"max_context": P.MAX_CTX,
|
| 514 |
+
"prefill_max": P.PREFILL_MAX,
|
| 515 |
+
"programs": io,
|
| 516 |
+
"flow_lm": "forward(embeds, input_pos, noise): writes KV positions [input_pos, input_pos + S); outputs are for "
|
| 517 |
+
"the last position. Calls: voice prompt (S = 125) at 0, text prompt (S = #tokens) at 125, then one call per "
|
| 518 |
+
"frame with S = 1: the first takes phonon_bos_embed, each later one the previous call's next_embeds",
|
| 519 |
+
"mimi": "forward(latent, *state) -> (pcm, *state): pass the previous call's states back; zeros to start",
|
| 520 |
+
"mimi_state": [[n, list(s)] for n, s in P.MIMI_STATE],
|
| 521 |
+
"text": "normalize (the official runtime's English rules; identity for plain sentences), then trim, collapse "
|
| 522 |
+
"whitespace, capitalize the first letter, append '.' if the text ends with a letter or digit; encode with "
|
| 523 |
+
"tokenizer.json without special tokens; embeds[i] = bf16 table row tokens[i] (as f32)",
|
| 524 |
+
"noise": "32 values per frame, N(0, temperature); 0.3 is the official runtime's default, 0 makes it deterministic",
|
| 525 |
+
"eos": f"stop after frames_after_eos more frames once eos_logit > {EOS_THRESHOLD} (frames_after_eos = 3 for "
|
| 526 |
+
"texts of <= 4 words, else 1); the EOS frame and its tail are decoded",
|
| 527 |
+
"frame_budget": "ceil((#tokens / 3 + 2) * 12.5) frames at most",
|
| 528 |
+
"voices": {
|
| 529 |
+
k: {"file": f"voice_{k}.f32.bin", "shape": list(v.shape[1:])}
|
| 530 |
+
for k, v in voices.items()
|
| 531 |
+
},
|
| 532 |
+
"conditions": {
|
| 533 |
+
"num_speakers": "1",
|
| 534 |
+
"duration_delta": 0.0,
|
| 535 |
+
"note": "the runtime's defaults, folded into the programs",
|
| 536 |
+
},
|
| 537 |
+
}
|
| 538 |
+
(out / "phonon.json").write_text(json.dumps(contract, indent=2) + "\n")
|
| 539 |
+
files["phonon.json"] = {
|
| 540 |
+
"bytes": (out / "phonon.json").stat().st_size,
|
| 541 |
+
"sha256": _common.sha256_file(out / "phonon.json"),
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
recipe = {
|
| 545 |
+
"model": "phonon-31m-en",
|
| 546 |
+
"upstream": {
|
| 547 |
+
"model": UPSTREAM["repo"],
|
| 548 |
+
"revision": UPSTREAM["revision"],
|
| 549 |
+
"voices": {"repo": VOICES["repo"], "revision": VOICES["revision"]},
|
| 550 |
+
"official": True,
|
| 551 |
+
"license": "apache-2.0 (model card front matter and License section; phonon-voices card front matter)",
|
| 552 |
+
"files_sha256": digests,
|
| 553 |
+
"loader": "recipes/_phonon.py load_weights: model.safetensors (bf16 flow LM, f32 Mimi decoder) -> float32, "
|
| 554 |
+
"load_state_dict(strict=True) into a module whose keys equal the checkpoint's",
|
| 555 |
+
},
|
| 556 |
+
"versions": _common.versions(),
|
| 557 |
+
"export": {
|
| 558 |
+
"api": "torch.export.export(strict=False) -> to_edge_transform_and_lower(partitioner=[WebGPUPartitioner(...)]) -> to_executorch()",
|
| 559 |
+
"partitioner": {
|
| 560 |
+
"flow_lm": "WebGPUPartitioner(compile_options={'require_dynamic_shapes': True, 'force_fp16': False}), dynamic S in [1, 128]",
|
| 561 |
+
"mimi": "WebGPUPartitioner() (default compile options, static shapes)",
|
| 562 |
+
},
|
| 563 |
+
"dtype": "float32 (bf16 checkpoint weights converted exactly)",
|
| 564 |
+
"quantization": "none",
|
| 565 |
+
"model_code": "recipes/_phonon.py FlowLMProgram, MimiStepProgram",
|
| 566 |
+
},
|
| 567 |
+
"files": files,
|
| 568 |
+
"graph": graphs,
|
| 569 |
+
"webgpu_runtime_checks": {
|
| 570 |
+
"op_list": "checked against --runtime-ops"
|
| 571 |
+
if runtime_ops
|
| 572 |
+
else "not checked (no --runtime-ops given)",
|
| 573 |
+
**checks,
|
| 574 |
+
},
|
| 575 |
+
"command": _common.command_line(out),
|
| 576 |
+
}
|
| 577 |
+
(out / "recipe.json").write_text(json.dumps(recipe, indent=2, default=str) + "\n")
|
| 578 |
+
print(json.dumps({"files": files}, indent=2), flush=True)
|
| 579 |
+
|
| 580 |
+
if not args.no_validate:
|
| 581 |
+
validate(args, out, w, tok, voices, bos_embed, eps, ptes)
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
if __name__ == "__main__":
|
| 585 |
+
main()
|
export/recipe.json
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "phonon-31m-en",
|
| 3 |
+
"upstream": {
|
| 4 |
+
"model": "gradium/phonon-31m-en",
|
| 5 |
+
"revision": "52433c46975bfa13144c56204c9f4ee1c5b148aa",
|
| 6 |
+
"voices": {
|
| 7 |
+
"repo": "gradium/phonon-voices",
|
| 8 |
+
"revision": "0ee17205f254b5abc43b266c8a0f215565c352f7"
|
| 9 |
+
},
|
| 10 |
+
"official": true,
|
| 11 |
+
"license": "apache-2.0 (model card front matter and License section; phonon-voices card front matter)",
|
| 12 |
+
"files_sha256": {
|
| 13 |
+
"gradium/phonon-31m-en:model.safetensors": "8a04cf833cfe69b67c2ec968b2d31244655b9accc84ade9c0ebcc176f2074607",
|
| 14 |
+
"gradium/phonon-31m-en:config.json": "7062ea376e6b158543c8abec8e5af67df171c49ad70eb7e2a0fb25c16f265e06",
|
| 15 |
+
"gradium/phonon-31m-en:tokenizer.json": "691a00068fa7b989f2f3e5ae5daa2d1a5bb319f2d5360deafcfb19a8bb6e7936",
|
| 16 |
+
"gradium/phonon-31m-en:tokenizer.model": "82e4572006d64d483317074c22c368e87779640b6f3a9dcd07b7caae32b030ce",
|
| 17 |
+
"gradium/phonon-31m-en:default-voice.safetensors": "f739e8c4c76ee7f92e7c94a82002748c8cd22e99582ac49f7b9b94cd63786e18",
|
| 18 |
+
"gradium/phonon-31m-en:README.md": "00f09ecdcd23ed9904f3a503baecc1f0c77515637ce6172b572ed3f50ce50c29",
|
| 19 |
+
"gradium/phonon-voices:voices/LMDIYE0Oa377Qh6Z.safetensors": "45c582673cb20edb04ddcca2b5a8865ddfb0a82599efadb269021e87d20fbdd4",
|
| 20 |
+
"gradium/phonon-voices:voices.jsonl": "874f34998ce581b94f2b8912aa015639f52b5fd62eba3ba11e1b64dcaed7d802",
|
| 21 |
+
"gradium/phonon-voices:README.md": "0186c7d586a9594db1e0283cb68e84e88bbd9bc3c29047cf0083c7483556f3ee"
|
| 22 |
+
},
|
| 23 |
+
"loader": "recipes/_phonon.py load_weights: model.safetensors (bf16 flow LM, f32 Mimi decoder) -> float32, load_state_dict(strict=True) into a module whose keys equal the checkpoint's"
|
| 24 |
+
},
|
| 25 |
+
"versions": {
|
| 26 |
+
"python": "3.12.15+meta",
|
| 27 |
+
"torch": "2.14.1+cpu",
|
| 28 |
+
"torchao": "0.18.0+cpu",
|
| 29 |
+
"executorch": "1.5.1+cpu",
|
| 30 |
+
"executorch_git": "3b60683923245cf472b7323426920e15623ba361",
|
| 31 |
+
"transformers": "5.19.0",
|
| 32 |
+
"huggingface_hub": "2.2.0"
|
| 33 |
+
},
|
| 34 |
+
"export": {
|
| 35 |
+
"api": "torch.export.export(strict=False) -> to_edge_transform_and_lower(partitioner=[WebGPUPartitioner(...)]) -> to_executorch()",
|
| 36 |
+
"partitioner": {
|
| 37 |
+
"flow_lm": "WebGPUPartitioner(compile_options={'require_dynamic_shapes': True, 'force_fp16': False}), dynamic S in [1, 128]",
|
| 38 |
+
"mimi": "WebGPUPartitioner() (default compile options, static shapes)"
|
| 39 |
+
},
|
| 40 |
+
"dtype": "float32 (bf16 checkpoint weights converted exactly)",
|
| 41 |
+
"quantization": "none",
|
| 42 |
+
"model_code": "recipes/_phonon.py FlowLMProgram, MimiStepProgram"
|
| 43 |
+
},
|
| 44 |
+
"files": {
|
| 45 |
+
"phonon_flow_lm.pte": {
|
| 46 |
+
"bytes": 111847044,
|
| 47 |
+
"sha256": "178698a6c4539ba48c93bd74c4165586c1da4fdd393bd144c27fd09d80021ad7"
|
| 48 |
+
},
|
| 49 |
+
"phonon_mimi.pte": {
|
| 50 |
+
"bytes": 41304196,
|
| 51 |
+
"sha256": "d7acdf2d93ba4897e63b58d933c7425f49cf855ecbd1a6f51e273c5dd65bb3cc"
|
| 52 |
+
},
|
| 53 |
+
"phonon_text_embed.bf16.bin": {
|
| 54 |
+
"bytes": 4097024,
|
| 55 |
+
"sha256": "7c6f3394fc86b55ed181ff0b9d2472cf0371d3feeac25a5d0f2eed0a3a2eaae1"
|
| 56 |
+
},
|
| 57 |
+
"phonon_bos_embed.f32.bin": {
|
| 58 |
+
"bytes": 2048,
|
| 59 |
+
"sha256": "a4464c50596adea27c8f0457124ead461202dc2f67daf3c6dbbc289cf289fd32"
|
| 60 |
+
},
|
| 61 |
+
"voice_default.f32.bin": {
|
| 62 |
+
"bytes": 256000,
|
| 63 |
+
"sha256": "d8a8ffc97e46c0330ef6a3842130b95cc5ee71759f66bb54bc2ec0b79fc36e57"
|
| 64 |
+
},
|
| 65 |
+
"voice_en_us_easton.f32.bin": {
|
| 66 |
+
"bytes": 256000,
|
| 67 |
+
"sha256": "1d6ec67cbd3a45b2bacf84ff7ddfb184fd9e8467c2204f2eac0f4975c354b66b"
|
| 68 |
+
},
|
| 69 |
+
"tokenizer.json": {
|
| 70 |
+
"bytes": 277967,
|
| 71 |
+
"sha256": "691a00068fa7b989f2f3e5ae5daa2d1a5bb319f2d5360deafcfb19a8bb6e7936"
|
| 72 |
+
},
|
| 73 |
+
"phonon.json": {
|
| 74 |
+
"bytes": 8599,
|
| 75 |
+
"sha256": "e8fa6604769aeb3b63e95c44c912f7ae635a324ca3793ec62fca017346521750"
|
| 76 |
+
}
|
| 77 |
+
},
|
| 78 |
+
"graph": {
|
| 79 |
+
"flow_lm": {
|
| 80 |
+
"non_delegated_kernels": {},
|
| 81 |
+
"delegates": [
|
| 82 |
+
{
|
| 83 |
+
"id": "VulkanBackend",
|
| 84 |
+
"ops": {
|
| 85 |
+
"et_vk.prepack.default": 23,
|
| 86 |
+
"sym_size.int": 1,
|
| 87 |
+
"et_vk.select_as_symint.default": 1,
|
| 88 |
+
"aten.view_copy.default": 106,
|
| 89 |
+
"aten.linear.default": 60,
|
| 90 |
+
"aten.sub.Tensor": 12,
|
| 91 |
+
"et_vk.rms_norm.default": 12,
|
| 92 |
+
"aten.add.Tensor": 47,
|
| 93 |
+
"aten.slice_copy.Tensor": 38,
|
| 94 |
+
"et_vk.apply_rotary_emb_hf.default": 6,
|
| 95 |
+
"sdpa_with_kv_cache.default": 6,
|
| 96 |
+
"aten.gelu.default": 6,
|
| 97 |
+
"aten.select_copy.int": 1,
|
| 98 |
+
"aten.native_layer_norm.default": 8,
|
| 99 |
+
"aten.sigmoid.default": 7,
|
| 100 |
+
"aten.mul.Tensor": 20,
|
| 101 |
+
"aten.unsqueeze_copy.default": 1
|
| 102 |
+
},
|
| 103 |
+
"inputs": 3,
|
| 104 |
+
"outputs": 3
|
| 105 |
+
}
|
| 106 |
+
]
|
| 107 |
+
},
|
| 108 |
+
"mimi": {
|
| 109 |
+
"non_delegated_kernels": {},
|
| 110 |
+
"delegates": [
|
| 111 |
+
{
|
| 112 |
+
"id": "VulkanBackend",
|
| 113 |
+
"ops": {
|
| 114 |
+
"et_vk.prepack.default": 34,
|
| 115 |
+
"aten.mul.Tensor": 18,
|
| 116 |
+
"aten.add.Tensor": 32,
|
| 117 |
+
"aten.view_copy.default": 30,
|
| 118 |
+
"aten.linear.default": 9,
|
| 119 |
+
"aten.clone.default": 14,
|
| 120 |
+
"aten.unsqueeze_copy.default": 9,
|
| 121 |
+
"aten.convolution.default": 12,
|
| 122 |
+
"aten.squeeze_copy.dims": 12,
|
| 123 |
+
"aten.slice_copy.Tensor": 35,
|
| 124 |
+
"aten.cat.default": 21,
|
| 125 |
+
"aten.cos.default": 2,
|
| 126 |
+
"aten.sin.default": 2,
|
| 127 |
+
"aten.permute_copy.default": 12,
|
| 128 |
+
"aten.native_layer_norm.default": 4,
|
| 129 |
+
"aten.neg.default": 4,
|
| 130 |
+
"aten.sub.Tensor": 15,
|
| 131 |
+
"aten.bmm.default": 4,
|
| 132 |
+
"aten._softmax.default": 2,
|
| 133 |
+
"aten.gelu.default": 2,
|
| 134 |
+
"aten.relu.default": 10,
|
| 135 |
+
"aten.clamp.default": 10,
|
| 136 |
+
"aten.exp.default": 10
|
| 137 |
+
},
|
| 138 |
+
"inputs": 16,
|
| 139 |
+
"outputs": 16
|
| 140 |
+
}
|
| 141 |
+
]
|
| 142 |
+
}
|
| 143 |
+
},
|
| 144 |
+
"webgpu_runtime_checks": {
|
| 145 |
+
"op_list": "checked against --runtime-ops",
|
| 146 |
+
"flow_lm": {
|
| 147 |
+
"problems": [],
|
| 148 |
+
"ok": true,
|
| 149 |
+
"notes": {
|
| 150 |
+
"value_kinds": [
|
| 151 |
+
"Bool",
|
| 152 |
+
"Double",
|
| 153 |
+
"FLOAT32",
|
| 154 |
+
"INT32",
|
| 155 |
+
"Int",
|
| 156 |
+
"IntList",
|
| 157 |
+
"Null",
|
| 158 |
+
"String",
|
| 159 |
+
"SymInt",
|
| 160 |
+
"ValueList"
|
| 161 |
+
],
|
| 162 |
+
"aten.linear input ranks": [
|
| 163 |
+
"2"
|
| 164 |
+
],
|
| 165 |
+
"sdpa_with_kv_cache q/k_cache": [
|
| 166 |
+
"((1, 128, 8, 64), (1, 512, 8, 64), 'SymInt')"
|
| 167 |
+
]
|
| 168 |
+
}
|
| 169 |
+
},
|
| 170 |
+
"mimi": {
|
| 171 |
+
"problems": [],
|
| 172 |
+
"ok": true,
|
| 173 |
+
"notes": {
|
| 174 |
+
"value_kinds": [
|
| 175 |
+
"Bool",
|
| 176 |
+
"Double",
|
| 177 |
+
"FLOAT32",
|
| 178 |
+
"Int",
|
| 179 |
+
"IntList",
|
| 180 |
+
"Null",
|
| 181 |
+
"String",
|
| 182 |
+
"ValueList"
|
| 183 |
+
],
|
| 184 |
+
"aten.linear input ranks": [
|
| 185 |
+
"2"
|
| 186 |
+
],
|
| 187 |
+
"aten.convolution input/weight": [
|
| 188 |
+
"((1, 128, 1, 480), (128, 64, 1, 8))",
|
| 189 |
+
"((1, 128, 482), (64, 128, 3))",
|
| 190 |
+
"((1, 128, 96), (256, 128, 1))",
|
| 191 |
+
"((1, 256, 1, 96), (256, 128, 1, 10))",
|
| 192 |
+
"((1, 256, 98), (128, 256, 3))",
|
| 193 |
+
"((1, 32, 1920), (64, 32, 1))",
|
| 194 |
+
"((1, 512, 1, 1), (512, 1, 1, 32))",
|
| 195 |
+
"((1, 512, 1, 16), (512, 256, 1, 12))",
|
| 196 |
+
"((1, 512, 22), (512, 512, 7))",
|
| 197 |
+
"((1, 64, 1922), (1, 64, 3))",
|
| 198 |
+
"((1, 64, 1922), (32, 64, 3))",
|
| 199 |
+
"((1, 64, 480), (128, 64, 1))"
|
| 200 |
+
]
|
| 201 |
+
}
|
| 202 |
+
}
|
| 203 |
+
},
|
| 204 |
+
"command": "python recipes/phonon-31m-en.py --out out/phonon-31m-en"
|
| 205 |
+
}
|
export/requirements.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Environment the re-exports in REEXPORT.md were produced with (Python 3.12, Linux x86_64, CPU only).
|
| 2 |
+
# python -m venv venv
|
| 3 |
+
# venv/bin/pip install -r recipes/requirements.txt --extra-index-url https://download.pytorch.org/whl/cpu
|
| 4 |
+
# executorch 1.5.1 = pytorch/executorch git 3b60683923245cf472b7323426920e15623ba361; its wheel ships
|
| 5 |
+
# backends/webgpu (WebGPUPartitioner) and examples/models/llama (export_llm).
|
| 6 |
+
executorch==1.5.1
|
| 7 |
+
torch==2.14.1+cpu
|
| 8 |
+
torchvision==0.29.1+cpu
|
| 9 |
+
torchao==0.18.0+cpu
|
| 10 |
+
transformers==5.19.0
|
| 11 |
+
huggingface_hub==2.2.0
|
| 12 |
+
safetensors==0.8.0
|
| 13 |
+
tokenizers==0.23.3
|
| 14 |
+
numpy==2.5.4
|
| 15 |
+
pillow==12.3.0
|
manifest.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "phonon-31m-en",
|
| 3 |
+
"repo": "executorch-community/Phonon-31M-EN-ExecuTorch-WebGPU",
|
| 4 |
+
"files": [
|
| 5 |
+
{
|
| 6 |
+
"path": "phonon.json",
|
| 7 |
+
"bytes": 8599,
|
| 8 |
+
"sha256": "e8fa6604769aeb3b63e95c44c912f7ae635a324ca3793ec62fca017346521750"
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"path": "phonon_bos_embed.f32.bin",
|
| 12 |
+
"bytes": 2048,
|
| 13 |
+
"sha256": "a4464c50596adea27c8f0457124ead461202dc2f67daf3c6dbbc289cf289fd32"
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"path": "phonon_flow_lm.pte",
|
| 17 |
+
"bytes": 111847044,
|
| 18 |
+
"sha256": "178698a6c4539ba48c93bd74c4165586c1da4fdd393bd144c27fd09d80021ad7"
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"path": "phonon_mimi.pte",
|
| 22 |
+
"bytes": 41304196,
|
| 23 |
+
"sha256": "d7acdf2d93ba4897e63b58d933c7425f49cf855ecbd1a6f51e273c5dd65bb3cc"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"path": "phonon_text_embed.bf16.bin",
|
| 27 |
+
"bytes": 4097024,
|
| 28 |
+
"sha256": "7c6f3394fc86b55ed181ff0b9d2472cf0371d3feeac25a5d0f2eed0a3a2eaae1"
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"path": "tokenizer.json",
|
| 32 |
+
"bytes": 277967,
|
| 33 |
+
"sha256": "691a00068fa7b989f2f3e5ae5daa2d1a5bb319f2d5360deafcfb19a8bb6e7936"
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"path": "voice_default.f32.bin",
|
| 37 |
+
"bytes": 256000,
|
| 38 |
+
"sha256": "d8a8ffc97e46c0330ef6a3842130b95cc5ee71759f66bb54bc2ec0b79fc36e57"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"path": "voice_en_us_easton.f32.bin",
|
| 42 |
+
"bytes": 256000,
|
| 43 |
+
"sha256": "1d6ec67cbd3a45b2bacf84ff7ddfb184fd9e8467c2204f2eac0f4975c354b66b"
|
| 44 |
+
}
|
| 45 |
+
]
|
| 46 |
+
}
|
phonon.json
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"sample_rate": 24000,
|
| 3 |
+
"frame_samples": 1920,
|
| 4 |
+
"frame_rate": 12.5,
|
| 5 |
+
"max_context": 512,
|
| 6 |
+
"prefill_max": 128,
|
| 7 |
+
"programs": {
|
| 8 |
+
"flow_lm": {
|
| 9 |
+
"forward": {
|
| 10 |
+
"inputs": [
|
| 11 |
+
{
|
| 12 |
+
"shape": [
|
| 13 |
+
1,
|
| 14 |
+
128,
|
| 15 |
+
512
|
| 16 |
+
],
|
| 17 |
+
"dtype": "float"
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"shape": [
|
| 21 |
+
1
|
| 22 |
+
],
|
| 23 |
+
"dtype": "long"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"shape": [
|
| 27 |
+
1,
|
| 28 |
+
32
|
| 29 |
+
],
|
| 30 |
+
"dtype": "float"
|
| 31 |
+
}
|
| 32 |
+
],
|
| 33 |
+
"outputs": [
|
| 34 |
+
{
|
| 35 |
+
"shape": [
|
| 36 |
+
1,
|
| 37 |
+
32
|
| 38 |
+
],
|
| 39 |
+
"dtype": "float"
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"shape": [
|
| 43 |
+
1,
|
| 44 |
+
1
|
| 45 |
+
],
|
| 46 |
+
"dtype": "float"
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"shape": [
|
| 50 |
+
1,
|
| 51 |
+
1,
|
| 52 |
+
512
|
| 53 |
+
],
|
| 54 |
+
"dtype": "float"
|
| 55 |
+
}
|
| 56 |
+
]
|
| 57 |
+
}
|
| 58 |
+
},
|
| 59 |
+
"mimi": {
|
| 60 |
+
"forward": {
|
| 61 |
+
"inputs": [
|
| 62 |
+
{
|
| 63 |
+
"shape": [
|
| 64 |
+
1,
|
| 65 |
+
1,
|
| 66 |
+
32
|
| 67 |
+
],
|
| 68 |
+
"dtype": "float"
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"shape": [
|
| 72 |
+
1,
|
| 73 |
+
512,
|
| 74 |
+
16
|
| 75 |
+
],
|
| 76 |
+
"dtype": "float"
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"shape": [
|
| 80 |
+
1,
|
| 81 |
+
8,
|
| 82 |
+
250,
|
| 83 |
+
64
|
| 84 |
+
],
|
| 85 |
+
"dtype": "float"
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"shape": [
|
| 89 |
+
1,
|
| 90 |
+
8,
|
| 91 |
+
250,
|
| 92 |
+
64
|
| 93 |
+
],
|
| 94 |
+
"dtype": "float"
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"shape": [
|
| 98 |
+
1,
|
| 99 |
+
8,
|
| 100 |
+
250,
|
| 101 |
+
64
|
| 102 |
+
],
|
| 103 |
+
"dtype": "float"
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"shape": [
|
| 107 |
+
1,
|
| 108 |
+
8,
|
| 109 |
+
250,
|
| 110 |
+
64
|
| 111 |
+
],
|
| 112 |
+
"dtype": "float"
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"shape": [
|
| 116 |
+
1,
|
| 117 |
+
1,
|
| 118 |
+
1,
|
| 119 |
+
250
|
| 120 |
+
],
|
| 121 |
+
"dtype": "float"
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"shape": [
|
| 125 |
+
1
|
| 126 |
+
],
|
| 127 |
+
"dtype": "float"
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"shape": [
|
| 131 |
+
1,
|
| 132 |
+
512,
|
| 133 |
+
6
|
| 134 |
+
],
|
| 135 |
+
"dtype": "float"
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"shape": [
|
| 139 |
+
1,
|
| 140 |
+
256,
|
| 141 |
+
6
|
| 142 |
+
],
|
| 143 |
+
"dtype": "float"
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"shape": [
|
| 147 |
+
1,
|
| 148 |
+
256,
|
| 149 |
+
2
|
| 150 |
+
],
|
| 151 |
+
"dtype": "float"
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"shape": [
|
| 155 |
+
1,
|
| 156 |
+
128,
|
| 157 |
+
5
|
| 158 |
+
],
|
| 159 |
+
"dtype": "float"
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"shape": [
|
| 163 |
+
1,
|
| 164 |
+
128,
|
| 165 |
+
2
|
| 166 |
+
],
|
| 167 |
+
"dtype": "float"
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"shape": [
|
| 171 |
+
1,
|
| 172 |
+
64,
|
| 173 |
+
4
|
| 174 |
+
],
|
| 175 |
+
"dtype": "float"
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"shape": [
|
| 179 |
+
1,
|
| 180 |
+
64,
|
| 181 |
+
2
|
| 182 |
+
],
|
| 183 |
+
"dtype": "float"
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"shape": [
|
| 187 |
+
1,
|
| 188 |
+
64,
|
| 189 |
+
2
|
| 190 |
+
],
|
| 191 |
+
"dtype": "float"
|
| 192 |
+
}
|
| 193 |
+
],
|
| 194 |
+
"outputs": [
|
| 195 |
+
{
|
| 196 |
+
"shape": [
|
| 197 |
+
1,
|
| 198 |
+
1,
|
| 199 |
+
1920
|
| 200 |
+
],
|
| 201 |
+
"dtype": "float"
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"shape": [
|
| 205 |
+
1,
|
| 206 |
+
512,
|
| 207 |
+
16
|
| 208 |
+
],
|
| 209 |
+
"dtype": "float"
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"shape": [
|
| 213 |
+
1,
|
| 214 |
+
8,
|
| 215 |
+
250,
|
| 216 |
+
64
|
| 217 |
+
],
|
| 218 |
+
"dtype": "float"
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"shape": [
|
| 222 |
+
1,
|
| 223 |
+
8,
|
| 224 |
+
250,
|
| 225 |
+
64
|
| 226 |
+
],
|
| 227 |
+
"dtype": "float"
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"shape": [
|
| 231 |
+
1,
|
| 232 |
+
8,
|
| 233 |
+
250,
|
| 234 |
+
64
|
| 235 |
+
],
|
| 236 |
+
"dtype": "float"
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"shape": [
|
| 240 |
+
1,
|
| 241 |
+
8,
|
| 242 |
+
250,
|
| 243 |
+
64
|
| 244 |
+
],
|
| 245 |
+
"dtype": "float"
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"shape": [
|
| 249 |
+
1,
|
| 250 |
+
1,
|
| 251 |
+
1,
|
| 252 |
+
250
|
| 253 |
+
],
|
| 254 |
+
"dtype": "float"
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"shape": [
|
| 258 |
+
1
|
| 259 |
+
],
|
| 260 |
+
"dtype": "float"
|
| 261 |
+
},
|
| 262 |
+
{
|
| 263 |
+
"shape": [
|
| 264 |
+
1,
|
| 265 |
+
512,
|
| 266 |
+
6
|
| 267 |
+
],
|
| 268 |
+
"dtype": "float"
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"shape": [
|
| 272 |
+
1,
|
| 273 |
+
256,
|
| 274 |
+
6
|
| 275 |
+
],
|
| 276 |
+
"dtype": "float"
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"shape": [
|
| 280 |
+
1,
|
| 281 |
+
256,
|
| 282 |
+
2
|
| 283 |
+
],
|
| 284 |
+
"dtype": "float"
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"shape": [
|
| 288 |
+
1,
|
| 289 |
+
128,
|
| 290 |
+
5
|
| 291 |
+
],
|
| 292 |
+
"dtype": "float"
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"shape": [
|
| 296 |
+
1,
|
| 297 |
+
128,
|
| 298 |
+
2
|
| 299 |
+
],
|
| 300 |
+
"dtype": "float"
|
| 301 |
+
},
|
| 302 |
+
{
|
| 303 |
+
"shape": [
|
| 304 |
+
1,
|
| 305 |
+
64,
|
| 306 |
+
4
|
| 307 |
+
],
|
| 308 |
+
"dtype": "float"
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"shape": [
|
| 312 |
+
1,
|
| 313 |
+
64,
|
| 314 |
+
2
|
| 315 |
+
],
|
| 316 |
+
"dtype": "float"
|
| 317 |
+
},
|
| 318 |
+
{
|
| 319 |
+
"shape": [
|
| 320 |
+
1,
|
| 321 |
+
64,
|
| 322 |
+
2
|
| 323 |
+
],
|
| 324 |
+
"dtype": "float"
|
| 325 |
+
}
|
| 326 |
+
]
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
},
|
| 330 |
+
"flow_lm": "forward(embeds, input_pos, noise): writes KV positions [input_pos, input_pos + S); outputs are for the last position. Calls: voice prompt (S = 125) at 0, text prompt (S = #tokens) at 125, then one call per frame with S = 1: the first takes phonon_bos_embed, each later one the previous call's next_embeds",
|
| 331 |
+
"mimi": "forward(latent, *state) -> (pcm, *state): pass the previous call's states back; zeros to start",
|
| 332 |
+
"mimi_state": [
|
| 333 |
+
[
|
| 334 |
+
"upsample_partial",
|
| 335 |
+
[
|
| 336 |
+
1,
|
| 337 |
+
512,
|
| 338 |
+
16
|
| 339 |
+
]
|
| 340 |
+
],
|
| 341 |
+
[
|
| 342 |
+
"k0",
|
| 343 |
+
[
|
| 344 |
+
1,
|
| 345 |
+
8,
|
| 346 |
+
250,
|
| 347 |
+
64
|
| 348 |
+
]
|
| 349 |
+
],
|
| 350 |
+
[
|
| 351 |
+
"v0",
|
| 352 |
+
[
|
| 353 |
+
1,
|
| 354 |
+
8,
|
| 355 |
+
250,
|
| 356 |
+
64
|
| 357 |
+
]
|
| 358 |
+
],
|
| 359 |
+
[
|
| 360 |
+
"k1",
|
| 361 |
+
[
|
| 362 |
+
1,
|
| 363 |
+
8,
|
| 364 |
+
250,
|
| 365 |
+
64
|
| 366 |
+
]
|
| 367 |
+
],
|
| 368 |
+
[
|
| 369 |
+
"v1",
|
| 370 |
+
[
|
| 371 |
+
1,
|
| 372 |
+
8,
|
| 373 |
+
250,
|
| 374 |
+
64
|
| 375 |
+
]
|
| 376 |
+
],
|
| 377 |
+
[
|
| 378 |
+
"kv_seen",
|
| 379 |
+
[
|
| 380 |
+
1,
|
| 381 |
+
1,
|
| 382 |
+
1,
|
| 383 |
+
250
|
| 384 |
+
]
|
| 385 |
+
],
|
| 386 |
+
[
|
| 387 |
+
"rope_offset",
|
| 388 |
+
[
|
| 389 |
+
1
|
| 390 |
+
]
|
| 391 |
+
],
|
| 392 |
+
[
|
| 393 |
+
"init_conv_prev",
|
| 394 |
+
[
|
| 395 |
+
1,
|
| 396 |
+
512,
|
| 397 |
+
6
|
| 398 |
+
]
|
| 399 |
+
],
|
| 400 |
+
[
|
| 401 |
+
"up1_partial",
|
| 402 |
+
[
|
| 403 |
+
1,
|
| 404 |
+
256,
|
| 405 |
+
6
|
| 406 |
+
]
|
| 407 |
+
],
|
| 408 |
+
[
|
| 409 |
+
"res1_prev",
|
| 410 |
+
[
|
| 411 |
+
1,
|
| 412 |
+
256,
|
| 413 |
+
2
|
| 414 |
+
]
|
| 415 |
+
],
|
| 416 |
+
[
|
| 417 |
+
"up2_partial",
|
| 418 |
+
[
|
| 419 |
+
1,
|
| 420 |
+
128,
|
| 421 |
+
5
|
| 422 |
+
]
|
| 423 |
+
],
|
| 424 |
+
[
|
| 425 |
+
"res2_prev",
|
| 426 |
+
[
|
| 427 |
+
1,
|
| 428 |
+
128,
|
| 429 |
+
2
|
| 430 |
+
]
|
| 431 |
+
],
|
| 432 |
+
[
|
| 433 |
+
"up3_partial",
|
| 434 |
+
[
|
| 435 |
+
1,
|
| 436 |
+
64,
|
| 437 |
+
4
|
| 438 |
+
]
|
| 439 |
+
],
|
| 440 |
+
[
|
| 441 |
+
"res3_prev",
|
| 442 |
+
[
|
| 443 |
+
1,
|
| 444 |
+
64,
|
| 445 |
+
2
|
| 446 |
+
]
|
| 447 |
+
],
|
| 448 |
+
[
|
| 449 |
+
"final_conv_prev",
|
| 450 |
+
[
|
| 451 |
+
1,
|
| 452 |
+
64,
|
| 453 |
+
2
|
| 454 |
+
]
|
| 455 |
+
]
|
| 456 |
+
],
|
| 457 |
+
"text": "normalize (the official runtime's English rules; identity for plain sentences), then trim, collapse whitespace, capitalize the first letter, append '.' if the text ends with a letter or digit; encode with tokenizer.json without special tokens; embeds[i] = bf16 table row tokens[i] (as f32)",
|
| 458 |
+
"noise": "32 values per frame, N(0, temperature); 0.3 is the official runtime's default, 0 makes it deterministic",
|
| 459 |
+
"eos": "stop after frames_after_eos more frames once eos_logit > 4.0 (frames_after_eos = 3 for texts of <= 4 words, else 1); the EOS frame and its tail are decoded",
|
| 460 |
+
"frame_budget": "ceil((#tokens / 3 + 2) * 12.5) frames at most",
|
| 461 |
+
"voices": {
|
| 462 |
+
"default": {
|
| 463 |
+
"file": "voice_default.f32.bin",
|
| 464 |
+
"shape": [
|
| 465 |
+
125,
|
| 466 |
+
512
|
| 467 |
+
]
|
| 468 |
+
},
|
| 469 |
+
"en_us_easton": {
|
| 470 |
+
"file": "voice_en_us_easton.f32.bin",
|
| 471 |
+
"shape": [
|
| 472 |
+
125,
|
| 473 |
+
512
|
| 474 |
+
]
|
| 475 |
+
}
|
| 476 |
+
},
|
| 477 |
+
"conditions": {
|
| 478 |
+
"num_speakers": "1",
|
| 479 |
+
"duration_delta": 0.0,
|
| 480 |
+
"note": "the runtime's defaults, folded into the programs"
|
| 481 |
+
}
|
| 482 |
+
}
|
phonon_bos_embed.f32.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a4464c50596adea27c8f0457124ead461202dc2f67daf3c6dbbc289cf289fd32
|
| 3 |
+
size 2048
|
phonon_flow_lm.pte
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:178698a6c4539ba48c93bd74c4165586c1da4fdd393bd144c27fd09d80021ad7
|
| 3 |
+
size 111847044
|
phonon_mimi.pte
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d7acdf2d93ba4897e63b58d933c7425f49cf855ecbd1a6f51e273c5dd65bb3cc
|
| 3 |
+
size 41304196
|
phonon_text_embed.bf16.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7c6f3394fc86b55ed181ff0b9d2472cf0371d3feeac25a5d0f2eed0a3a2eaae1
|
| 3 |
+
size 4097024
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
voice_default.f32.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d8a8ffc97e46c0330ef6a3842130b95cc5ee71759f66bb54bc2ec0b79fc36e57
|
| 3 |
+
size 256000
|
voice_en_us_easton.f32.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1d6ec67cbd3a45b2bacf84ff7ddfb184fd9e8467c2204f2eac0f4975c354b66b
|
| 3 |
+
size 256000
|