A 3D tensor is laid out as [batch, time, feature] in models such as torchaudio’s Conformer and RNN-T. Its rank is the easy part. Portability breaks on two other things: which axis is time, and how that axis is declared dynamic. ONNX can carry a time dimension as a named symbol, while Core ML wants a bounded range or a fixed set of shapes. If one distilled checkpoint has to export cleanly to both, the time axis has to be declared once, with a real upper bound, and checked at export rather than discovered on a phone. This page stays at the level of the tensor. The wider latency and real-time picture is covered in our piece on cross-platform TTS inference with ONNX and CoreML. Our broader work on speech synthesis and other model families is described on our generative AI research and development page.
Is a 3D Tensor in a TTS Model Just a 3D Matrix?
Mathematically, yes. A 3D tensor is an array indexed by three integers, so “a stack of matrices” is a fair first picture. That picture stops helping at the point that matters for deployment, though. The three axes of a TTS tensor are not interchangeable: each one means something, and the export toolchain needs to know which of them may change length at runtime.
Torchaudio documents its Conformer encoder as taking and returning tensors of shape (B, T, input_dim), which is batch by time by feature. Tacotron2’s predicted mel spectrogram has the shape (n_batch, n_mels, max of mel_specgram_lengths), so time comes last. Both tensors are rank 3, but they put time in different positions. That is why tensor layout is best treated as an interface contract between the model and every runtime it ships to, not as an internal PyTorch detail.
Which Axis Is Time? Batch, Time and Feature in Real Speech Models
The batch axis counts the sentences processed together. On a phone it is generally 1, and ONNX Runtime’s mobile docs suggest fixing it to 1 for NNAPI. The feature axis is the encoding width D or the number of mel bins. The architecture sets it, and it should stay static. The time axis is the one whose length varies at runtime. On the input side it counts tokens or phonemes, and on the output side it counts frames. Its length depends on the text being spoken.
TTS adds two complications. First, Tacotron2’s batched tokens are sized to the longest item, and a separate lengths tensor carries each item’s real length. Tacotron2 takes tokens of shape (n_batch, max of lengths) together with a lengths input, and it returns mel spectrograms together with their lengths. Second, a single tensor can carry two time axes at once. Tacotron2’s attention weights have shape (n_batch, max of mel_specgram_lengths, max of lengths), so they are indexed by output frames and input tokens.
Layout Reference for Common Speech Tensors
| Tensor (documented shape) | Time axis index | Note |
|---|---|---|
| Conformer input/output: (B, T, input_dim) | 1 | Feature-last layout |
| RNN-T source frames: (B, T, D) | 1 | Right-padded with right context |
| Emformer input: (B, T + right_context_length, D) | 1 | Time length includes look-ahead context |
| Tacotron2 tokens: (n_batch, max of lengths) | 1 | Rank 2, padded to the longest item |
| Tacotron2 mel output: (n_batch, n_mels, max of mel_specgram_lengths) | 2 | Channel-first, time last |
| Tacotron2 attention: (n_batch, max of mel_specgram_lengths, max of lengths) | 1 and 2 | Two independent time axes |
| ConvTasNet waveform: [batch, channel, frames] | 2 | Audio-domain 3D tensor |
| Kokoro Core ML vocoder body output: [1, 128, T] | 2 | Output that moved 168 of 617 ops to CPU |
The index column matters because every dynamic-axis declaration is written against it. A wrong index makes the wrong dimension flexible.
Why ONNX Runtime and Core ML Treat a Dynamic Time Axis Differently
ONNX represents each dimension in one of three ways: a known integer (dim_value), a symbolic name (dim_param), or neither, which is an anonymous unknown. When an axis is declared dynamic at export, the dimension is not hardcoded, so ONNX Runtime can accept inputs and produce outputs whose length varies along that axis. ONNX shape inference has limits, though. A Reshape to a shape supplied at runtime blocks it, and it does no arithmetic on symbols. Concatenating (5, 2) with (N, 2) yields (M, 2), not (N+5, 2). In a TTS graph, the frame axis produced after durations are expanded can therefore carry a new unknown symbol rather than a length computed from the token axis.
Core ML asks for more commitment up front. When converting to an ML program, a RangeDim must have a positive upper bound, or Core ML Tools raises an exception. Only the older neural network format accepts -1 for “unbounded”, and even then device memory sets the real limit. Apple’s guide says bounded ranges give the runtime compiler more room to optimise. It recommends EnumeratedShapes for best performance, with up to 128 shapes compiled for on the device. Multi-input TTS models hit a further constraint: before iOS 18 only one input could use EnumeratedShapes, and from iOS 18 multiple enumerated inputs must have the same number of shapes and match by index. The conversion mechanics themselves are covered in our introduction to coremltools.
ONNX Runtime’s own documentation notes that CoreML may perform better with fixed input shapes. Its model usability checker reports nodes that are unsupported because an input has a dynamic shape, and it estimates whether fixing those shapes would help. Shape choices at a graph boundary can also change where Core ML schedules work. In the open-source Kokoro Core ML port, splitting the vocoder so that the truncated body emitted a [1, 128, T] output sent 168 of 617 operations to the CPU, and the stage took 353 ms instead of 44 ms. Whether fixing shapes is worth it for a particular model is a question for the checker and a profiler, not a rule of thumb.
Numerical agreement differs between ONNX and Core ML too. An empirical study of deep learning model conversion found prediction differences that were negligible for ONNX models, while the largest offsets came from Core ML conversions. The study covered CNNs such as VGG-16 and ResNet-18 as well as RNN models, and its authors name input sizes and shapes as future work. It is a reason to validate each target separately, not a measurement of TTS.
How to Declare a Dynamic Sequence Dimension so One Checkpoint Exports to Both Runtimes
Declare the time dimension once, in PyTorch, with a real upper bound, and let both converters inherit it. torch.export supports this with explicit dynamic dimensions. Dynamic dimensions are declared with the Dim() API and attached to example inputs through dynamic_shapes. The resulting graph records the shape constraints that keep it valid for future inputs. Core ML Tools converts an exported program’s torch.export.Dim to a RangeDim automatically. EnumeratedShapes still have to be listed in the inputs argument. PyTorch’s ONNX exporter based on torch.export uses the same engine and records the same shape constraints before it translates the graph to ONNX.
The torch.export Route with Named Dims
Dim can be used as a hint (Dim.AUTO, Dim.DYNAMIC, Dim.STATIC) or as a named dimension with bounds, such as Dim("name", min=1, max=2). A tensor’s dynamic shape is given as a dict from axis index to Dim, or as a tuple with None for static axes. For a phoneme-input acoustic model, the shape looks like this:
from torch.export import Dim, export
# MAX_TOKENS is the model's real input cap, not a guess
tokens = Dim("tokens", min=2, max=MAX_TOKENS)
# phoneme_ids: [1, T] int64, phoneme_lengths: [1]
ep = export(
model,
(phoneme_ids, phoneme_lengths),
dynamic_shapes=({1: tokens}, None),
)
# Core ML: ct.convert(ep, ...) turns `tokens` into a bounded RangeDim
# ONNX: pass the same dynamic_shapes to the torch.export-based exporter
The bounded max is what Core ML’s ML program format requires, and the ONNX exporter keeps it as a range constraint. One declaration serves both targets. The range constraints in the PyTorch tutorial’s exported program start at 2 (VR[2, int_oo]). Dim.DYNAMIC raises an error if the code specialises the dimension to a constant, which surfaces the problem at export time. Conflicting markers on equivalent dimensions (one dynamic, one static) are a common source of specialisation. So a token tensor and a mask of the same length should share one Dim. When the export rejects a spec, a helper in torch.export can turn the ConstraintViolation message into a corrected dynamic_shapes.
The Legacy dynamic_axes Route
With the tracing exporter, the shapes of the example arguments become the shapes in the ONNX graph unless dynamic_axes overrides them. dynamic_axes is a dict keyed by the names in input_names and output_names, mapping axis indices to descriptive names. Piper’s VITS export declares input as {0: "batch_size", 1: "phonemes"}, input_lengths as {0: "batch_size"} and output as {0: "batch_size", 1: "time"}. The output time axis has its own name, which matches the model: output frames and input tokens have separate lengths. Reusing the input’s name would claim an equality the model does not have. Indices have to follow the layout table above. On a (n_batch, n_mels, T) mel output, marking axis 1 makes the mel-bin axis flexible and leaves time fixed at whatever the example produced.
When the Sequence Axis Is Dynamic but the Runtime Still Fails
A user on the PyTorch forums declared only seq_len as dynamic on a character embedder. When fed a different length, ONNX Runtime failed in an Expand node with “Attempting to broadcast an axis by a dimension other than 1. 500 by 1951”. The fix was to make the batch dimension dynamic as well and to pass the initial hidden state into the forward pass during tracing. Our reading is that the traced initial hidden state kept a fixed size that collided with the dynamic axis. Recurrent TTS decoders that initialise their own state deserve the same check.
Truncated Audio, Dropout or a Bad Model? Reading the Symptoms
Start by running the same input through the PyTorch reference. A fault that reproduces there is not an export problem. A fault that appears on only one runtime points to the export, and the time axis is the first place to look.
| Symptom on the target runtime | Likely shape cause | First check |
|---|---|---|
| Output length barely changes with input length, or audio stops at a fixed point | Time axis not declared dynamic, so the example’s length was baked into the graph | Look for dim_value where you expected dim_param on input and output time axes |
| Runtime exception only for lengths other than the example’s | Broadcast against a size the trace froze | Make the related axes dynamic, and pass internally created state as an input |
| Correct audio, but slower than expected on device | Dynamic shapes leaving nodes unsupported by the CoreML EP | Model usability checker, then a profile of where operations land |
| Small numeric drift at every length | Not a shape problem: ONNX Runtime’s CoreML EP defaults to the NeuralNetwork format, which casts to FP16 | Set ModelFormat to MLProgram |
The FP16 row is in the table because its drift is not a shape fault. The fix is a provider option; see also our article on compiler flags for ONNX and CoreML.
Validating 3D Tensor Shapes at Export Time, Before a Device Sees the Model
These checks run in order, cheapest first. Each one catches a class of fault the next would only find more slowly.
- Read the exported program’s shape contract. The
ExportedProgramsignature shows symbolic sizes, andrange_constraintsgives each symbol’s valid range. The ONNX exporter keeps these range constraints, andrename_axeslets you give symbols likebatchandseq_lenreadable names. When a guard surprises you,TORCH_LOGS="+dynamic"shows where it was emitted. - Check the ONNX graph’s dimensions. Running
onnx.checkerand ONNX shape inference on the exported file confirms the graph is well formed and shows whether time stays symbolic through to the output. Expect a fresh symbol after Concat or a data-dependent Reshape, since shape inference stops there. - Ask how the CoreML EP will partition the graph. ONNX Runtime’s model usability checker checks operator support for the CoreML EP. For dynamic inputs it estimates whether fixed shapes would help.
- Fix shapes per bucket if static wins.
python -m onnxruntime.tools.make_dynamic_shape_fixed --dim_param batch --dim_value 1 model.onnx model.fixed.onnxsets a named symbol to a fixed value.--input_namewith--input_shapehandles unnamed dimensions. - Sweep lengths against the reference. Run the shortest input, the export example, each bucket edge and the declared maximum through PyTorch, ONNX Runtime and Core ML. Compare output lengths against the lengths tensor as well as the values, because a truncated output can match closely over the frames it does contain.
- Catch mismatches before export. PyTea, a static analyser from Seoul National University, detects tensor-shape errors in PyTorch code without running it. It caught every shape-mismatch case in the six forum questions its authors collected. It was built for training code, so for inference graphs it supplements the steps above rather than replacing them.
These checks belong in the job that builds the artefacts, so a shape regression fails the build instead of a device test. That is ordinary MLOps engineering discipline applied to an export pipeline.
The Maximum Length Is a Product Decision
Everything above depends on a number that nobody can export their way out of: the longest utterance the product will synthesise in one call. Core ML forces that number into the ML program, and EnumeratedShapes reward a small set of known lengths. ONNX lets you skip it, but skipping it leaves the limit implicit rather than removing it. We would decide the cap and the buckets from the product’s real text lengths first. Then we would ask whether chunked synthesis over a fixed window removes the need for an open-ended time axis altogether. Restructuring what is computed often beats tuning how a converter handles a shape it was never meant to see. For each model, then, the open question is where the frame axis loses its link to the token axis. Find that point in your graph, and you know where the export needs its strongest test.