Repository navigation
Conversation
This was referenced Oct 14, 2026
…sidecars (0xShug0#900) The Rockchip NPU compute paths are model-local modules, not a ggml backend: RKNN has no runtime graph builder, so each graph-isolated stage is compiled offline for one fixed shape and voiced through librknnrt. Every one of them currently carries its own copy of the driver plumbing — read the engine image, rknn_init, pick the NPU cores, query the tensor attributes, inputs_set/run/outputs_get, destroy the context, and format the status codes. Adds the shared part in one place: - `include/engine/framework/rknn/engine.h` / `src/framework/rknn/engine.cpp`: `engine::rknn::read_engine`, `engine::rknn::status` (both build with or without `ENGINE_HAVE_RKNN`) and, with it, `engine::rknn::Engine` — a `rknn_context` plus its cached input/output attributes and one fused `run(inputs, outputs)` step. The core-mask choice, including the `AUDIOCPP_RKNN_CORE_MASK` override and the AUTO fallback, moves here too. - `tests/unittests/test_rknn_engine.cpp` covers the part that is testable without a board: the engine-image reader (round trip, missing file, empty file) and the status format. Nothing is registered, selected, or called by any model in this commit; the sidecar PRs are rebased onto it and keep only their tensor geometry, window walk and seam stitching. Co-authored-by: wOvAN <[email protected]>
* Add CTC word timestamps to Granite Speech 5.0 TurboCTC. Word spans and greedy-class confidence now follow the encoder clock, while the transcript text stays the same. Co-authored-by: Cursor <[email protected]> * Clamp Granite word spans to the chunk end and validate chunked and streaming runs Word ends are limited to the clip they came from, so fixed and VAD chunks cannot produce words that run into the next chunk. The golden test now also checks a fixed-chunk run and a streaming run, and takes --backend and --chunk-seconds. Co-authored-by: Cursor <[email protected]> * Report Granite word timestamps in input-rate samples The frontend resamples to 16 kHz, so CTC frame positions are converted to the input buffer's sample rate before chunk offsets and the chunk-end clamp are applied. The golden test now checks 48 kHz and 8 kHz input against the 16 kHz word times. Co-authored-by: Cursor <[email protected]> --------- Co-authored-by: Cursor <[email protected]>
…s) (0xShug0#906) apply_repetition_penalty walked the whole history and rescaled a logit again for every occurrence, so a speech token (or EOS) that had already appeared n times was penalized penalty^n. transformers' RepetitionPenaltyLogitsProcessor, and this repo's own HfLogitsProcessor::apply_repetition_penalty, rescale each distinct token in the history exactly once. Remember which speech tokens (and EOS) were already rescaled in this step and skip the repeats. Co-authored-by: Zlatko Zlatkov <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
* Separate model library page and clarify package installation status * Add missing models and controls to the WebUI
* Add an opt-in RKNN speech decoder for Qwen3 TTS on Rockchip NPUs
Route the qwen3_tts speech tokenizer decoder (codes to PCM) to a pre-compiled
stateful RKNN step graph through librknnrt, behind ENGINE_ENABLE_RKNN (OFF by
default) and the session options qwen3_tts.rknn_decoder and
qwen3_tts.rknn_decoder_first. Model stages already compute through their own
graph and ExecutionContext, so this is a model-local module rather than a ggml
backend. With the options unset nothing links or loads librknnrt; with the flag
off the options fail loudly instead of falling back to CPU silently.
The graph is stateful: the causal-conv tails and the sliding-window KV history
travel through the graph I/O, so a step decodes from continuous state. In
streaming the ggml decoder re-voices the left-context tokens of every window,
this voices each token once. The optional first-group model runs the first token
group at a smaller compiled batch, and the cache layout is batch-independent, so
its cache feeds the main model directly.
tools/prepare_qwen3_tts_rknn_vocoder.py is the producer of the .rknn: re-trace
the decoder from the checkpoint, self-check the stepwise decode against a full
decode, convert per target SoC.
Validated on an Orange Pi 5 Plus (RK3588), native aarch64 build, 300 Russian
characters, greedy (do_sample=false seed=42), conv_weight_type=f16:
- offline RTF 3.01 -> 2.17, peak RSS 4200 -> 2560 MB, decoder 130.1 -> 64.1 ms/token
- streaming wall 151.2 -> 57.7 s, first audio 3.4 s -> 0.88 s
- output SNR against the ggml decoder 27.0 dB, with the per-second dips
confined to near-silence (the fp16 noise floor) and no discontinuity at the
compiled group boundaries
- the two compiled batch sizes agree to 56.8 dB
- producer: export self-check 111.4 dB (B=64) and 103.7 dB (B=16); converting a
reference ONNX reproduces the reference .rknn byte for byte
Not validated: other families, other SoCs, and CI (no NPU hardware; the path is
off by default there).
* Measure the board's DRAM ceiling and stop attributing the sidecars to it
(cherry picked from commit bb2d9c1)
* Measure the talker's weight traffic and what re-quantizing it buys
(cherry picked from commit 9316507)
* Localize and remove the wide-window saturation; record the talker listening verdict
(cherry picked from commit 6111d67)
* Name the real cost of the in-graph wide-window escape
(cherry picked from commit 7c039c4)
* Measure the cheap wide window: W=136 is not a win, and normalized stats have no width to help
(cherry picked from commit a6af3e7)
* Record the Kokoro utterance provenance and the build-dependence of absolute figures
(cherry picked from commit 08a92bf)
* Correct the folded-sine board verdict: it costs 36% generator time, not 8% less
* fix(qwen3_tts): drop the speech-tokenizer weight blob the NPU path never reads
With `qwen3_tts.rknn_decoder` set the NPU sidecar voices the speech decoder, so
the ggml decoder's weights are never loaded and only the decoder config is read
from the asset source. The speech-tokenizer tensor source is one resident blob
opened for the whole model, and a source frees only the ranges it has handed out,
so the decoder's half of it stayed mapped for the session's lifetime. Every
consumer of that source uploads its weights in its own constructor, so by the end
of the session constructor the blob is dead.
Measured on an Orange Pi 5 Plus (RK3588), 0.6B q8_0 Base, 300 Russian characters,
greedy, conv_weight_type=f16, same engine, same command: peak RSS 2879 -> 2868 MB
and peak footprint (vsize) 6274 -> 4671 MB. The RSS delta is small because the
blob is file-backed and the decoder's pages were never touched; what the release
removes is the 1.6 GB mapping itself. Output is byte-identical (md5
b942ae13ea623721f0b6dadce63d04e0).
* Move the chunked-voicing restructure out of this PR
Chunking is a shared-path behaviour change (offline text chunks are voiced in one
decoder pass over the concatenated codes), so it does not belong in an opt-in
sidecar PR. It goes up as its own change; this branch keeps only the RKNN seam:
the two session options, the decoder constructor argument, the streaming
reset/flush hooks, and releasing the speech-tokenizer weight blob the NPU path
never reads.
* refactor(qwen3_tts): use the shared RKNN engine plumbing in the speech decoder sidecar
Moved to framework/rknn: the engine-image reader, rknn_init plus the
RKNN_NPU_CORE_0_1_2-then-AUTO core-mask block with the
AUDIOCPP_RKNN_CORE_MASK override, the IN_OUT_NUM and per-index
INPUT_ATTR queries, the inputs_set/run/outputs_get/outputs_release
step sequence, rknn_destroy and the status-string formatter — all now
supplied by engine::rknn::read_engine, Engine::load, the cached
input_attr/output_attr accessors, Engine::run and engine::rknn::status.
The two core-mask return-code timing keys went with the block.
Stayed model-local: the tensor geometry and name checks (audio_codes
group/codebook dims, freqs_in RoPE width, cache_in/cache_valid sizes),
the stateful step logic (conv tails and sliding-window KV history
through graph I/O, cache_valid as the filled-slot count), the
first-group (B=16) engine handling, group padding, reset/flush
semantics, and every model-specific error message. With
pass_through = 0 the codes input now passes n_elems * sizeof(i64)
instead of attr.size, per the shared header's fp16-width caveat;
one rknn_context per sidecar is unchanged.
Co-Authored-By: Claude <[email protected]>
* docs(rknn): bring the board build guide onto the shipped kokoro path
The guide still documented the kokoro producer's --dump-dir and the --global-stats engine as a
shipped opt-in. Both were removed: the producer's gates compute the full-length decode in-process, and
the runtime rejects a 7-input engine at load. The statistics findings stay, reframed as the reason the
path is not in the build.
Adds the near-Nyquist clicks measurement and the gain-path cap, the two kokoro window-walk knobs in
the Run section, and drops the stale "against a dumped decode" from the Verified list.
---------
Co-authored-by: wOvAN <[email protected]>
Co-authored-by: Claude <[email protected]>
* Add an opt-in RKNN VITS decoder for Piper TTS on Rockchip NPUs The piper_tts decoder is 75% of the runtime on an RK3588, and the stages are already graph-isolated, so the same per-stage seam used for qwen3_tts applies: with ENGINE_ENABLE_RKNN and the session option piper_tts.rknn_decoder, the decoder stage is voiced by a pre-compiled .rknn through librknnrt instead of ggml, and the ggml decoder graph is never built. tools/prepare_piper_tts_rknn_vocoder.py slices a Piper voice ONNX at the seam the runtime has on hand - the inverse-flow input z [1,192,N] and its frame mask y_mask [1,1,N], plus g for a multi-speaker voice - verifies the fixed-window decode against a full-length decode on latents from the voice's own encoder, and compiles the slice. The window contract (93 slices: 45 emitted plus 24+24 real context, short windows zero-padded and mask-zeroed, the tail window extending its left context) is implemented identically in src/community_models/piper_tts/rknn_decoder.cpp; the padding is measured, not inherited from paroli's 45+5+5, which leaves interior windows 8-60 dB off a full-length decode. Runtime validation, Orange Pi 5 Plus (RK3588), librknnrt 2.3.2, native gcc build with -DENGINE_ENABLE_RKNN=ON -DENGINE_RKNN_INCLUDE_DIR=/usr/local/include -DENGINE_RKNN_LIBRARY=/usr/lib/librknnrt.so, model models/Piper-TTS-GGUF/piper-en-us-lessac-medium-orig.gguf, 443 characters at --text-chunk-size 60 (10 chunks, 25.18 s of audio), seed 1234: path RTF peak RSS decoder ms ggml decoder 0.198 299 MB 2070 RKNN decoder (w93) 0.0696 175 MB 1030 Quality, same run, ggml-vs-RKNN output: SNR 24.1 dB global, 40 dB median per 256-sample slice, best alignment lag 0 samples in every window, max sample-to-sample step 13384 vs 13412 (no seam clicks). The dips are near-silence and one loud plosive onset, i.e. the fp16 engine's noise floor. The producer's self-check gates interior windows at 40 dB against a full-length decode (measured 98+ dB at this padding) and the stitched output at 20 dB. The last slices of a latent are the one thing a fixed-shape window cannot reproduce: a full-length decode has the end of the tensor there, where a window has padding, and a conv layer two levels deep reads the pad's own conv output (nonzero, from the biases) where the full decode reads the implicit zeros past the tensor end. No mask value in the padding reproduces that; the last ~7 slices of a short latent land 20-40 dB off. With the sidecar selected, load_weights no longer materializes the dec.* tensors, for a graph that is never built: same engine, same command, piper_tts.weights.buffer_mb 59.70 -> 53.36, peak RSS 169 -> 162 MB, peak footprint (vsize) 400 -> 392 MB, RTF 0.0826 -> 0.0770, output byte-identical (md5 2e4ece97e6ae9e4c8bb715cfccba9409). piper_tts asks for RKNN_NPU_CORE_0_1_2 and falls back to AUTO. AUTO lets the driver pick, and for graphs this small it picks one core (rknpu/load stays at Core0: 100% for the whole run). * refactor(piper_tts): use the shared RKNN engine plumbing in the decoder sidecar Move the driver plumbing onto engine::rknn::Engine: the engine-image reader (read_engine), the rknn_init + rknn_set_core_mask block (the RKNN_NPU_CORE_0_1_2-then-AUTO fallback and the AUDIOCPP_RKNN_CORE_MASK env override now live in Engine::load), the IN_OUT_NUM query and the per-index INPUT_ATTR/OUTPUT_ATTR loops (now input_count/output_count/input_attr/output_attr, cached at load), the inputs_set -> run -> outputs_get -> outputs_release sequence (one Engine::run), and rknn_destroy plus the status-string formatter (Engine's destructor and engine::rknn::status). Stays model-local: the fixed-window contract (93 = 45 emitted + 24+24 context, zero-padding and mask-zeroing of short windows, the tail window's extended left context), the z/y_mask/g tensor geometry and name checks, the seam stitching, the timing-log keys, and every model-specific error message. Inputs keep pass_through = 0 with size = n_elems * sizeof(float), not attr.size, and the sidecar keeps its single rknn_context (no dup_context). Co-Authored-By: Claude Opus 4.5 <[email protected]> --------- Co-authored-by: wOvAN <[email protected]> Co-authored-by: Claude Opus 4.5 <[email protected]>
…#904) * Add an opt-in RKNN iSTFTNet generator for Kokoro TTS on Rockchip NPUs The kokoro_tts generator is 83% of the runtime on an RK3588 (RTF 1.41 for a 14.85 s utterance), and the stages are already graph-isolated, so the same per-stage seam used for qwen3_tts and piper_tts applies: with ENGINE_ENABLE_RKNN and the session option kokoro_tts.rknn_generator the generator stage is voiced by a pre-compiled .rknn through librknnrt instead of ggml, and the ggml generator graph is never prepared. The seam is the generator alone - x [1,512,W], the harmonic conditioning har [1,22,60W+1], the style vector and the frame mask at the two rates the graph normalizes at, in and out as spec_phase [1,22,60W+1]. Source-signal synthesis, the forward STFT and the iSTFT head stay on CPU, and the windows are stitched in the spectrogram domain (one global iSTFT over the stitched spectrogram), so there is no waveform crossfade and no depop search. tools/prepare_kokoro_tts_rknn_generator.py re-traces the generator the GGUF weights describe (decoder.module.generator.* in kokoro-v1_0.pth) at one fixed window, checks it against the runtime, and compiles it. Three graph rewrites are compiled in, all of them the reference Kokoro RKNN port's, and each is there for a measured reason: - Weight-norm folded at load. Left in the graph, vector_norm traces to 51 ReduceL2 nodes and rknn.build aborts. - Masked instance norm through GlobalAveragePool. A ReduceSum over the time axis lowers to a register field capped at 8191. The mask has to zero the padding at every stage boundary (after the upsampling reflect-pad, on the resblock sum, on the noise branch), not only inside AdaIN's statistics: a conv after a masked AdaIN writes real-frame sums into the pad, and the next conv_transpose reads them where a full decode reads implicit zeros. - Snake's sin to a clipped minimax odd polynomial (degree 5), and its 1/alpha folded into the following convolution. librknnrt has no NPU Sin: the 48 sine nodes of a 128-frame window ran on CPU and were 41% of the window's time (350 ms of 846 ms, RKNN_LOG_LEVEL=5 operator ranking). Degree 5, 7 and 9 measure the same 30.4 dB against the exact sine, so the clip saturation past pi dominates and the cheap fit wins. The alpha-fold is exact algebra and removes one multiply and one divide per Snake; elementwise ops are 84% of this graph's NPU time and the convolutions 15%. The window width is capped by the NPU, not by the model: the longest axis in the graph, the fine rate 60W+1, has to stay under the 13-bit register field. At W=512 the compiler emits ~800k "REGTASK: The bit width of field value exceeds the limit, ... limit: 0x1fff, value: 0x7800" lines and the engine voices clipped noise (rms 32764 of 32767, SNR -27 dB against the CPU decode). 128 is the widest power of two inside the limit, and it emits 128-2*28 = 72 latent frames per step, where 28 is the measured receptive field. Runtime validation, Orange Pi 5 Plus (RK3588), librknnrt 2.3.2, native gcc build with -DENGINE_ENABLE_RKNN=ON -DENGINE_RKNN_INCLUDE_DIR=/usr/local/include -DENGINE_RKNN_LIBRARY=/usr/lib/librknnrt.so, model models/Kokoro-82M-GGUF/kokoro-82m-q8_0.gguf, 185 Russian characters, seed 1234, --threads 4 (14.85 s of audio, 1188 latent frames, 17 windows): path RTF peak RSS generator ms ggml generator 1.415 2777 MB 17748 RKNN generator (w128) 0.867 2334 MB 9609 1.63x wall, 1.85x on the generator (14.9 -> 8.1 ms per latent frame processed), -16% RSS, NPU load Core0 95% / Core1 18% / Core2 19%. The generator-side gain is smaller than the 5.1x measured in the reference engine because this window carries 28+28 frames of context for 72 emitted frames (1.78x of the compute is context, and 28 is the exact receptive field, so it cannot shrink) and because the register limit forces 17 windows. Producer gates, on a decode dumped out of this runtime (AUDIOCPP_KOKORO_DECODER_DUMP): the re-traced module reproduces the runtime's own generator at 60.5 dB interior SNR (the floor is the q8_0 style affine), a padded 128-frame window reproduces the same frames decoded unpadded at 135.1 dB, and the exported ONNX reproduces the torch graph it was traced from at 124.6 dB - measured with the torch reference evaluated in the same sine form, so the gate measures the export and not the approximation. Quality, ggml-vs-RKNN output SNR 0.49 dB, and that number has to be read against what it compares. The generator normalizes per window (AdaIN), so a multi-window decode is a different valid synthesis and not an approximation of the full-length one: dropping 2 of 486 latent frames from the statistics moves the generator output by 25% RMS. The shipping reference Kokoro engine, with the same per-window normalization at T_fix=50, measures 17.11 dB against its own CPU decode on a 7.1 s utterance (2 windows); the gap between its 17 dB and our 0.5 dB is window count, not stitching. Utterances of 72 latent frames or fewer (about 0.9 s) fit one window and are exact. Also in this commit: - kokoro_tts asks for RKNN_NPU_CORE_0_1_2 and falls back to AUTO, as piper_tts does. One context per sidecar: running the windows concurrently on three rknn_dup_context contexts, which is what the reference engine does, measured 1.15x on the window loop (9650 -> 8375 ms) with corrupted output (-7 dB SNR, rms 2x the reference) - duplicated contexts share the runtime's tensor staging, and this engine streams ~75 MB of weights per window, so windows are DRAM-bound, not scheduler-bound. - kokoro_tts accepts the rknn_generator session option by name as well as through the spec, because a published GGUF package embeds an older spec (piper_tts does the same). - The generator I/O dump harness, which is what the producer's parity gate reads. Two knobs on the window walk, both off by default (with them unset the render is byte-identical to the shipping stitch, md5 1f4926e4...), measured on the same utterance against the artifact the ear hears - per-window loudness pumping (0.9 s window rms against the CPU render, spread 7.23 dB, seams clean): walk windows SNR max|d| spread RTF RSS stitch (shipping) 17 0.46 20777 7.23 1.16 2340 overlap 36 32 0.84 20715 7.14 1.79 2340 gain 17 -0.08 25988 3.27 2.24 2884 overlap 36 + gain 32 0.38 25942 3.05 3.03 2884 kokoro_tts.rknn_generator_overlap advances the walk by emitted-overlap and blends the shared spectrogram columns with a raised-cosine ramp; kokoro_tts.rknn_generator_gain keeps the ggml generator graph prepared, renders one full-length CPU decode per utterance, and gives each window's log-magnitude rows the log-loudness ratio against it. The pumping is a loudness effect, not a seam effect: overlap alone does not move the metric, the loudness correction halves it for 1.9x wall. * Add an in-graph windowed decode so a wide Kokoro window stops saturating (cherry picked from commit 9cb1c82) * Correct the folded-sine board verdict: it costs 36% generator time, not 8% less * Fold the Snake sine by pi, not 2*pi: exact for sin^2, 43 dB tighter at the same cost The shipped range reduction folds the Snake argument by 2*pi and fits sin on [-pi,pi]. Snake consumes sin(alpha*x)^2, which is pi-periodic, so the fold period can be pi: k = Floor(x/pi + 0.5); xr = x - k*pi, with the minimax fit of sin on [-pi/2, pi/2]. Same 10 elementwise ops per sine, same 74.7 MB engine, and the fit gets half the interval: the exported graph measures 93.2 dB against the exact sine (the 2*pi fold: 50.0 dB at the generator output, the clipped form 30.4), and the export-vs-torch gate moves 124.6 -> 124.3 dB, i.e. the reference and the rewrite are still the same function. The torch reference form has to fit on the same domain as the ONNX rewrite, so the export gate's coefficient call now derives the clip from the reduction mode. Measured on RK3588 (integration build, 6.37 s RU, --threads 4, engines from one producer revision interleaved 3x): RTF median 0.867 clipped, 1.079 2*pi-fold, 1.046 pi-fold - the fold's cost is the Floor chain, not its algebra. The build log names the mechanism: the 2.3.2 compiler lowers every rounding op off the NPU (`Floor FLOAT16 CPU` at all 48 sine sites of a folded engine, `Clip FLOAT16 NPU` at all 48 of the clipped one, 58 CPU-lowered ops against 10), so each fold site is a full-tensor NPU->CPU->NPU round trip. Renders are audibly distinct: clipped-vs-2*pi 17.28 dB, clipped-vs-pi 16.95, 2*pi-vs-pi 28.48 dB (max|d| 8020/6922/1936 of 32767). RK3566 re-export: 61,281,856 bytes, 352 REGTASK lines, same gates. * docs(kokoro_tts): attribute the RKNN generator clicks to the engine, not the window walk A listening pass found 3 clicks on the 33.58 s render and 2 on the 14.88 s English one. They are content-locked, not grid-locked (moving the window walk with rknn_generator_overlap=36 reproduces them at the identical samples; all three sine forms put them at the same samples), and engine-only (the CPU render of the same text and seed has no jump there, and a 30 ms window at those positions carries 2.5-5x the CPU render's 9-12 kHz energy). Not the fp16 range and not the iSTFT head: the dumped generator output of the NPU render has log-magnitude rows in [-58.8, +3.35] (CPU [-115, +3.03]), and clamping the exponent at 4.0 in the head leaves every render byte-identical. The engine raises its own upper mel bins at those columns (row 6 +3.31 against +1.74, the Nyquist bin +0.50 against -0.93) at the window-relative fine columns where the graph's largest activations peak, and the same graph is clean there in fp32 onnxruntime and in the PC simulator of the same compiled engine, so the excess is the RK3588 DPU's own fp16 accumulation at the activation peaks. * refactor(kokoro_tts): drop the parity-dump and global-stats experiment paths Both paths existed to measure the sidecar, not to serve a request, and both changed behaviour outside the sidecar: the dump path wrote files under an environment variable from inside the shared decoder, and the statistics path added graph inputs and outputs to the generator graph, extra forward-expanded nodes, and a runtime hook in the shared runtime. Removed: AUDIOCPP_KOKORO_DECODER_DUMP and its writer in src/models/kokoro_tts/ decoder.cpp; the stats-capture parameter, the per-site (mean, biased variance) graph outputs and their readout in the generator graph session; the sidecar's stats_in/use_global/stats_out contract, which is now the 5-input/1-output shipping contract (a 7-input engine is rejected by the name and count check); --global-stats and --dump-dir in tools/prepare_kokoro_tts_rknn_generator.py, keeping the torch-module gate and the padded-window exactness gate. Restored: upload_time_masks guards mask.norm for null again, as upstream does, now that no graph in the tree registers those inputs. The findings stay in the docs: the statistics path is fp32-exact (9.7 -> 135.4 dB) and unusable on a board (every window after the first renders as a constant-energy tone, 1.8x wall, +1.5 GB RSS), which is why it is not shipped. Verified on an Orange Pi 5 Plus (RK3588), gcc 15.2, librknnrt 2.3.2, engine gen_w128.rknn, af_heart, seed 1234, --text-chunk-size 120: the stripped build renders byte-identical to the pre-strip build (md5 3515c8a25eba36ea525f091fdb054b90), and both the RKNN-on and RKNN-off targets build clean. * refactor(kokoro_tts): use the shared RKNN engine plumbing in the generator sidecar Moved to framework/rknn: the engine-image reader (read_engine), the rknn_init plus RKNN_NPU_CORE_0_1_2-then-AUTO core-mask block with the AUDIOCPP_RKNN_CORE_MASK override (Engine::load; the two core-mask return-code timing keys went with the block, the measured core-split numbers stayed as a comment), the IN_OUT_NUM query and the per-index INPUT_ATTR/OUTPUT_ATTR loops (cached input_count/output_count/input_attr/output_attr), the inputs_set/run/outputs_get/outputs_release step sequence (one Engine::run), and rknn_destroy plus the status-string formatter (Engine's destructor and engine::rknn::status). Stayed model-local: the 5-input/1-output contract and its name check (x/har/style/mask_mid/mask_out; a 7-input engine is rejected by the count check naming tools/prepare_kokoro_tts_rknn_generator.py), the W=128 latent-frame window walk (emitted = W - 2*padding, the 60W+1 fine-rate iSTFT geometry), the overlap and gain knobs, the seam stitching, the timing-log keys, and every model-specific error message. Inputs keep pass_through = 0 with size = n_elems * sizeof(float), not attr.size, and the sidecar keeps its single rknn_context (no dup_context). Co-Authored-By: Claude <[email protected]> * fix(kokoro_tts): cap the NPU's near-Nyquist spikes at the reference on the gain path The RKNN render carries 2-3 content-locked near-Nyquist clicks per 26 s render: at the columns where the graph's activations peak, the top iSTFT bins run 10-24x the full-length CPU decode's 9-12 kHz energy there. They are fp16 rounding in the convolutional accumulation. Measured invariant to every export-time lever that exists: the clip sine, the range-reduced sine (--sin-reduce), the exact Sin node, the unfolded Snake (--no-snake-fold, which bounds the convolution input), and the w128/w136 grids all leave the same columns at the same magnitude. RKNN 2.3.2 has no per-layer dtype knob, and moving the peak convolutions to the CPU gives up the sidecar (the convolutions are 15% of the window's time, the elementwise chain 84%). What does remove them is to cap the top five log-magnitude rows at the reference level at every column, which needs the full-length CPU decode the gain knob already runs. Orange Pi 5 Plus (RK3588), gen_reduce5_w128.rknn, af_heart, seed 1234, 25.9 s render, per-column 9-12 kHz energy ratio against the CPU render (top 8 columns) and full-render SNR against it: | path | top-8 ratios | SNR | wall | peak RSS | |---|---|---|---|---| | shipping (no gain) | 23.3 .. 10.6x | 0.62 dB | 29.7 s | 2792 MB | | gain, no cap | 14.7 .. 6.5x | 0.08 dB | - | - | | gain + cap | 2.8 .. 1.4x | 0.13 dB | 56.6 s | 3393 MB | The residual 1.4-2.8x is the iSTFT Hann-overlap smear: PCM at 9-12 kHz draws on spectrogram bins beyond the five the cap touches. SNR is dominated by the per-window-vs-full-length normalization gap (~0 dB for every w128 engine), not by the clicks, so it does not move. Without kokoro_tts.rknn_generator_gain there is no reference and the block is a no-op: the shipping render is byte-identical (md5 3515c8a2...). --------- Co-authored-by: wOvAN <[email protected]> Co-authored-by: Claude <[email protected]>
The four graph arenas in `vits_runtime.cpp` are sized for the CPU backend's typical request, and the unrolled VITS decoder graph is the worst case. With a long text and no `--text-chunk-size` the latent is long, the decoder graph is unrolled over the whole of it, and the arena overflows: the run dies in ggml_new_object: not enough space in the context's memory pool (needed 17773472, available 16777216) Measured on an Orange Pi 5 Plus (RK3588), gcc 15.2, lessac-medium, 443 characters, seed 1234, no chunking: before, the run aborts with that message (exit 139, no audio); after, it renders (RTF 0.286, peak RSS 878 MB). `--text-chunk-size` is the only current workaround, and it is a user-visible workaround for a constant in the runtime. Duration arena 16 -> 32 MiB, decoder arena 16 -> 64 MiB. A device backend is the same story with a steeper slope: it allocates tensor payloads in the arena, where the CPU backend keeps them outside the ggml context. The chunked CPU path is unaffected: same engine, same command (443 characters at --text-chunk-size 60, seed 1234), output byte-identical (md5 a5347b3e on both builds), peak RSS 342 -> 337 MB (run-to-run noise; the arena is a context pool allocated up front and touched lazily).
wOvAN
force-pushed
the
piper-graph-arenas
branch
from
October 14, 2026 21:18
97a5a25 to
830b175
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Size the Piper TTS graph arenas for long unchunked latents
Branch:
piper-graph-arenas, basemain. Split out of 0xShug0/audio.cpp#897 at review: it is a change to existingruntime behaviour, so it gets its own review and its own backend testing.
Why
The four graph arenas in
src/community_models/piper_tts/vits_runtime.cppare compile-timeconstants sized for the CPU backend's typical request. The VITS decoder graph is unrolled over the
whole latent, so it is the worst case, and with a long text and no
--text-chunk-sizethe latent islong:
That is the run dying before it produces any audio. The only current workaround is
--text-chunk-size, i.e. a user-visible workaround for a constant in the runtime.A device backend has the same shape with a steeper slope: it allocates tensor payloads inside the
arena, where the CPU backend keeps them outside the ggml context, so the same graph needs
substantially more of it.
Change
Duration graph arena 16 → 32 MiB, decoder graph arena 16 → 64 MiB. The duration-flow and I/O arenas
are untouched.
Measured on the board
Orange Pi 5 Plus (RK3588), gcc 15.2, native build,
piper-en-us-lessac-medium-orig.gguf, seed 1234.Long text, no chunking (443 characters, one latent):
not enough space in the context's memory pool (needed 17773472, available 16777216)Chunked CPU path (443 characters at
--text-chunk-size 60, the path the RKNN sidecar PR measures):output byte-identical on both builds (md5
a5347b3e), RTF 0.2048 → 0.2082, peak RSS 342 → 337 MB.The arena is a ggml context pool allocated up front and touched lazily, so the larger pool costs
address space, not resident memory.
Vulkan, same board (
ENGINE_ENABLE_VULKAN=ON, Mali render nodes present):piper_ttsdoes notreach the arena limit at all — it aborts earlier, on the duration graph, at
GGML_ASSERT(ctx->descriptor_set_idx < ctx->descriptor_sets.size())inggml-vulkan.cpp, on bothbuilds. That is a separate structural defect and is not what this PR fixes; it is reported here so
the reviewer knows the device-backend motivation is measured on the arena request size, not
demonstrated end-to-end on Vulkan.
python3 tools/check_loader_catalog_sync.py --self-test && python3 tools/check_loader_catalog_sync.pypasses (nothing in the catalog changes).
Known limitations
not here.
for a longer latent; the ceiling for an arbitrarily long unchunked latent is unbounded, so very
long single-shot texts can still overflow. Chunking remains the supported path for long-form.