Skip to content

Gradium phonon improved - #1825

Open
xenova wants to merge 29 commits into
mainfrom
model/gradium-phonon-improved
Open

xenova wants to merge 29 commits into
mainfrom
model/gradium-phonon-improved

Conversation

@xenova

@xenova xenova commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

Following on from #1811, with more improvements. Associated model files can be found at https://huggingface.co/onnx-community/phonon-31m-en-ONNX/discussions/1, awaiting @nico-martin's review.

vs. #1811:

Generator precision 48 frames / 3.84 s audio 192 frames / 15.36 s audio
q4f16 2.12× faster 2.13× faster
q4 1.92× faster 2.08× faster
fp32 1.52× faster 1.58× faster

For q4f16, representative total times went from 166 → 78 ms and 640 → 305 ms.

Possibly more importantly, we also made various correctness fixes:

fp16 decoder metric Previous Current Improvement
Relative RMS error, 8 frames 2.15% 1.91% 11% lower
Relative RMS error, 192 frames 13.78% 2.09% 6.6× lower
Maximum absolute error, 192 frames 1.498 0.0515 29× lower

Model graph size improvements too:

Graph only Previous Current Reduction
Generator fp32 451 kB 225 kB 50%
Generator fp16 647 kB 228 kB 65%
Mimi fp16 70 kB 33 kB 53%

Beyond the speedup and correctness, we improved memory use, decoder correctness, export reproducibility, and the JS generation API.

On the model/export side:

  • Added real dynamic batching, including unequal text/voice lengths, per-item positions and masks, independent stopping lengths, and correctly padded audio outputs.
  • Generate eight frames per call, reducing JS→ORT calls and EOS synchronization.
  • Fused generator operations: packed QKV and AdaLN projections, GroupQueryAttention, residual layer normalization, and quantized matmul bias. Constant conditioning and timestep calculations move to export time.
  • Reduced dispatches and transfers: the final optimization pass alone removed 15.1% of generator GPU dispatches and 84% of internal upload bytes. KV and latent feedback remain on GPU.
  • Reworked Mimi attention to actually select FlashAttention, preserving its sliding window while avoiding large quadratic attention-score tensors and masks.
  • Replaced dense transposed convolutions with projection plus overlap-add, reducing layout work and avoiding the reproduced WebGPU fp16 stride-5 ConvTranspose correctness bug.
  • Packaged all ten precision variants for both models.

For the Transformers.js integration:

  • Standard model ownership: Phonon loads both generator and Mimi sessions; model.generate() returns decoded audio, and the text-to-speech pipeline returns RawAudio.
  • GPU-aware cache handling: cache registration includes KV tensors and both latent outputs, enabling GPU feedback and direct generator→decoder handoff.
  • One Mimi call per text chunk, with unused generated frames trimmed before decoding.
  • Python-aligned text preparation: PocketTTSProcessor, chat templates, voice placeholders, sentence/clause chunking, decimal handling, and a scoped Unicode byte-fallback workaround.
  • More accurate generation controls: temperature scales Gaussian noise by sqrt(temperature), deterministic generation works, and EOS tails are retained correctly across block boundaries. Generation defaults and per-call overrides are respected.
  • Better resource and input handling: intermediate state is disposed even on inference failure; caller-owned voices remain valid; malformed voices, failed downloads, and unsupported solver settings produce clear errors.
  • Added regression coverage for these behaviors and fixed the adjacent SpeechT5 processor/waveform handling.

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@xenova

xenova commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator Author

2026-10-29T00:10:43.8530374Z packages/transformers test: ModelFileNotFoundError: Could not locate file: "https://huggingface.co/onnx-community/phonon-31m-en-ONNX/resolve/main/onnx/model_q4.onnx".

CI failure just because we haven't merged modeling files in.

@nico-martin
nico-martin changed the base branch from main to v4.4-integration November 25, 2026 13:21
@nico-martin
nico-martin changed the base branch from v4.4-integration to main November 25, 2026 13:23
@nico-martin

Copy link
Copy Markdown
Collaborator

Hi @xenova, thanks for all the export work here! I pushed three commits on top, here's what changed and where it now differs from the description.

What I did

  • The JS didn't match the graphs that got merged on the Hub. generate() now feeds position_ids, a full-length attention_mask, and num_frames as [1]. It no longer feeds audio_prompt_latents_mask, and it strips the voice placeholders and audio BOS from input_ids since the graph prepends the voice and adds its own BOS.
  • generate() rejects malformed prompts and voices with clear errors, and the pipeline rejects voice tensors that aren't flat or [1, 512, frames].
  • split_text strips audio marker strings from the text, like Python.
  • The mocked sessions now mirror the real graph, and the real-model test checks for a natural end of speech and audible output.

Different from the description

  • The Hub files are merged, so that note is outdated.
  • The export is batch-dynamic, but the JS takes one prompt per call with an unpadded voice.
  • PocketTTSProcessor uses the base loader again (uses_processor_config), so it reads processor_config.json.
  • On the SpeechT5 fix: on main the pipeline throws "Missing the following inputs: speaker_embeddings, encoder_hidden_states, output_sequence". With this PR it speaks again.

@xenova xenova left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

latest review

Comment on lines +49 to +55
// Match the Phonon checkpoint's generation_config.json, not Python's generic Pocket TTS defaults.
do_sample: true,
temperature: 0.3,
num_flow_steps: 1,
eos_threshold: config.eos_threshold,
min_frames_before_eos: 0,
...this.generation_config,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we match the generation_config.json, and we always load the generation config and set it, then I'd say these extra parameters aren't needed.

Comment on lines +61 to +91
if (options.num_flow_steps !== 1) {
throw new Error('This ONNX export supports num_flow_steps=1; other values require re-export.');
}
if (input_ids.dims.length !== 2 || input_ids.dims[0] !== 1) {
throw new Error('Phonon generate() accepts one prompt per call.');
}
if (
attention_mask.dims.length !== 2 ||
attention_mask.dims[0] !== 1 ||
attention_mask.dims[1] !== input_ids.dims[1]
) {
throw new Error('attention_mask must match the shape of input_ids.');
}
if (
!(audio_prompt_latents instanceof Tensor) ||
audio_prompt_latents.type !== 'float32' ||
audio_prompt_latents.dims.length !== 3 ||
audio_prompt_latents.dims[0] !== 1 ||
audio_prompt_latents.dims[2] !== config.audio_prompt_dim
) {
throw new Error('audio_prompt_latents must be a float32 tensor of shape [1, frames, audio_prompt_dim].');
}
const voice_length = audio_prompt_latents.dims[1];
if (
audio_prompt_latents_mask !== undefined &&
(audio_prompt_latents_mask.dims.length !== 2 ||
audio_prompt_latents_mask.dims[0] !== 1 ||
audio_prompt_latents_mask.dims[1] !== voice_length ||
audio_prompt_latents_mask.data.some((value) => Number(value) !== 1))
) {
throw new Error('Phonon requires an unpadded voice prompt with a matching audio_prompt_latents_mask.');

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

imo this is overly defensive. we don't really do this for other models. We get a clear enough error back from ONNX Runtime.

...Object.fromEntries(Object.entries(kwargs).filter(([, value]) => value != null)),
};
const { model, mimi_decoder } = this.sessions;
const block_size = model.inputMetadata.find(({ name }) => name === 'noise').shape[1];

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i assume this should be a config value we can extract?

while (num_frames < Math.min(stop_frame ?? max_frames, max_frames)) {
const prefill = num_frames === 0;
// The KV cache includes voice and text positions, unlike the audio latent cache.
const past_length = cache['past_key_values.0.key'].dims.at(-2);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if this is of type DynamicCache, then I think there is a class method which does the same thing as this


// Until tokenizers.js implements Unigram byte fallback, expand unknown pieces
// before they are converted to IDs. Limit the workaround to this processor.
// TODO: remove this adapter once https://github.com/huggingface/tokenizers.js/issues/26 is fixed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with all the recent tokenizers.js PRs users have submitted, maybe this is a good one to tackle to include in our next release.

Comment on lines +54 to +61
const boundary_ids = (pieces) =>
new Set(
/** @type {number[]} */ (this.tokenizer.convert_tokens_to_ids(pieces)).filter(
(id) => Number.isInteger(id) && id !== this.tokenizer.unk_token_id,
),
);
const sentence_ends = boundary_ids(['.', '!', '...', '?']);
const clause_ends = boundary_ids([',', ';', ':']);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

worth moving to constructor or not?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file is so complex -- we can probably simplify a lot

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not ideal to recreate tokenizer logic here. better to use official tokenizer imo

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants