# Romanian text-to-speech

Source: https://docs.surogate.ai/engine/inference/tts/

You can serve the published Romanian text-to-speech model on a CPU, with three voices:
Doina, Tudor and Radu. (To run it on a GPU, see [GPU](#gpu).)

```bash
surogate serve --tts surogate/surogate-ro-tts --device cpu --threads 4 --port 8080
```

From a source checkout, build the native server first:

```bash
# Ubuntu/Debian build dependency:
sudo apt-get install libicu-dev patch
make serve-tts-build
```

The full `make serve-build` and the wheel build include `surogate-tts` as well.
The TTS-only target needs C++20, CMake, Ninja, `patch` and ICU 70 or newer, but no CUDA
toolkit or LibTorch. At runtime you need the ICU libraries the build was made against.
To use an executable you built separately, point `SUROGATE_TTS_BIN` at it.

Python finds and verifies the model files, then replaces itself with `surogate-tts`.
HTTP, Romanian text normalization and tokenization all run in C++, and the HTTP layer is
shared with native speech recognition through `csrc/src/serve/serve/audio_http.h`. A
native GGML worker (one by default; see `--max-num-seqs`) keeps the generator and codec
loaded between requests. Once the server is up, no Python, Torch, NeMo or
training-recipe process sits in the inference path.

The published binary targets Linux x86-64 and was validated on an AMD EPYC 9124. Other
CPUs need a compatible native build, validated on that CPU. With `--device cpu`, the
default, speech generation uses CPU threads and no GPU. Voices are created separately, on
offline GPUs; serving a voice never clones or trains anything.

## CPU kernels and threads

`--threads N` sets the generator's compute threads (default 4, range 1–256).
`--codec-threads N` sets the audio codec's threads separately; by default, or with `0`,
it takes the `--threads` value. The two stages can run at the same time. Both values are
thread counts per stage and don't reserve physical cores. For example:

```bash
surogate serve --tts surogate/surogate-ro-tts --threads 4 --codec-threads 4
```

`--cpu-kernels auto` selects Surogate's AVX-512 GGML backend when the CPU and the
build support it. Its FP32 projection kernels reuse vectors across outputs, and its
FP16 codec matrix kernel shares conversions across a 2×3 output tile, irregular
convolution dimensions included. Accumulation keeps the reference FP32 arithmetic and
reduction order, so model precision and sampling don't change.

`--cpu-kernels reference` selects the model package's original backend, for
comparisons. `--cpu-kernels optimized` requires the AVX-512 backend and fails without
it, where `auto` falls back to the package backend. That fallback still needs a CPU
compatible with the published native package.

The build downloads a hash-pinned GGML source archive and applies the model's ABI
additions and Surogate's kernels on top. To leave this backend out, set CMake's
`-DSUROGATE_TTS_CPU_KERNELS=OFF`. Before loading its adapter, the worker checks the
model runtime's ABI fingerprints. Newly exported voices must use the same supported
native runtime; any other runtime build needs a matching adapter.

On a multi-socket host, pin the server to one socket with a consistent CPU affinity
when you measure. More threads don't always mean lower latency. The
[CPU kernel validation report](/engine/inference/cpu-kernels/) has the measurements and checks.

## GPU

`--device N` runs the generator, the codec and sampling on CUDA device N, counted among the
devices the server can see, as for the LLM server. The default stays `--device cpu`, and
`--threads` and `--cpu-kernels` apply only on the CPU.

On a GPU you need the package's GPU variant:

- Its model, codec, tokenizer and voices are the CPU package's.
- Its `lib/` holds the same Magpie runtime built with CUDA, including `libggml-cuda`, and runs on
  compute capability 12.0 (RTX 50-series) only.
- If you give a GPU the CPU package, the server refuses it with a clear error.

The published model keeps its GPU variant in the repository's `gpu/` folder. With
`--device N`, `surogate/surogate-ro-tts` downloads and verifies that variant, pinned to a
revision like the CPU package:

```bash
surogate serve --tts surogate/surogate-ro-tts --device 0 --port 8080
```

You serve a downloaded copy or a local variant the same way:

```bash
hf download surogate/surogate-ro-tts --revision e6b1372cb1b3db6c205ebfc589fba8d630ed438b \
  --include "gpu/*" --local-dir surogate-ro-tts
surogate serve --tts surogate-ro-tts/gpu --device 0 --port 8080
```

On an RTX 5090 one request runs at about 25 times real time, with about 25 ms to the first
audio. A server holds about 2.4 GB of GPU memory per worker. Like the LLM server, the worker
needs the NVIDIA driver and the CUDA 13 runtime (`libcudart`, `libcublas`) on the host.
`/health` reports `"device": "cuda:N"`. The GPU variant can also serve `--device cpu`, with the
same results as the CPU package, but it still needs those libraries; on hosts without them,
use the CPU package.

The worker accepts only a CUDA runtime whose checksums it pins, as it does for the CPU
runtime, so the variant is published exactly as built. Its CUDA-compiled libraries aren't
bit-for-bit reproducible: a rebuild in another build directory gives the same `libggml`,
`libggml-base` and `libggml-cpu`, but a different `libnemo_speech_tts` and `libggml-cuda`.
The recipe below records how the published build was made, for provenance and for
qualifying a replacement. It uses `nemo-speech-cpp` at `07003daa` with the package's
`longform_history_fix.patch` and `longform_context_cache.h`, and the CPU package's TTS-only
options plus CUDA. The build maps source paths, links no NCCL, and loads its libraries from
their own directory:

```bash
SRC=$PWD/nemo-speech-cpp
cmake -S $SRC -B build-cuda -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON \
  -DNEMO_SPEECH_BUILD_TTS=ON -DNEMO_SPEECH_GGML_PATCHED=ON -DGGML_NATIVE=ON -DGGML_OPENMP=ON \
  -DGGML_CUDA=ON -DGGML_CUDA_NCCL=OFF -DCMAKE_CUDA_ARCHITECTURES=120 \
  -DCMAKE_C_FLAGS=-ffile-prefix-map=$SRC=nemo-speech-cpp \
  -DCMAKE_CXX_FLAGS=-ffile-prefix-map=$SRC=nemo-speech-cpp \
  -DCMAKE_CUDA_FLAGS=-Xcompiler=-ffile-prefix-map=$SRC=nemo-speech-cpp \
  -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON '-DCMAKE_INSTALL_RPATH=$ORIGIN' \
  -DNEMO_SPEECH_BUILD_ASR=OFF -DNEMO_SPEECH_BUILD_CLI=OFF -DNEMO_SPEECH_BUILD_HTTP=OFF \
  -DNEMO_SPEECH_BUILD_GRPC=OFF -DNEMO_SPEECH_BUILD_TESTS=OFF -DNEMO_SPEECH_BUILD_TOOLS=OFF
cmake --build build-cuda --target nemo_speech_tts ggml-cuda
python -m surogate.serve.tools.tts.gpu_variant CPU_PACKAGE build-cuda/bin GPU_VARIANT
```

The tool refuses a build whose checksums don't match the pinned ones. To use a different
build, qualify it first (quality and speed), then pin it in `native_worker.cpp` and in the tool.

## Model download

The first start downloads only the native CPU package, about 1.15 GiB, from HF
revision `2bf175b4edc7b3ca7261d80e4d4ad85117c4f0a4`. With `--device N` it downloads only
the GPU variant instead, about 1.35 GiB, from revision
`e6b1372cb1b3db6c205ebfc589fba8d630ed438b`. The server verifies the voice profile and
every file it lists, then runs a short warm-up before it accepts requests. Later starts
verify and reuse the cached package.

The repository is private, so authenticate with `hf auth login` or `HF_TOKEN`. The
package is cached under `~/.cache/surogate/serve`; set `SUROGATE_SERVE_CACHE` to use
another directory. `--no-cache` downloads the pinned HF package again. A cached or local
package starts without network access.

## Generate speech

```bash
curl http://localhost:8080/v1/audio/speech \
  -H 'Content-Type: application/json' \
  -d '{"model":"surogate/surogate-ro-tts","input":"Bună ziua! Cu ce vă pot ajuta?","voice":"Doina","response_format":"wav"}' \
  --output doina.wav
```

Change `voice` to `Tudor` or `Radu` to switch voices. Voice names are not
case-sensitive. To list what's available:

```bash
curl http://localhost:8080/v1/audio/voices
curl http://localhost:8080/v1/models
curl http://localhost:8080/health
```

`/health` reports ready once every worker has loaded the model. `/v1/models` reports the
model argument you started the server with. Use `--served-model-name my-tts` to set an
alias; a request that sends `model` must then use that alias.

### Request fields

| Field | Accepted values |
|---|---|
| `input` | Required Romanian text, 1–4096 characters (see `--max-input-characters`) |
| `model` | Optional served model ID |
| `voice` | A name from `/v1/audio/voices`; defaults to the first voice in the package |
| `response_format` | `wav` (default) or `pcm` |
| `speed` | `1` |
| `seed` | Integer from 0 to 2147483647; defaults to 9 |
| `stream_format` | Omitted (the complete recording), `audio` or `sse`; see [Streaming](#streaming) |

Both formats carry mono, 22,050 Hz, signed 16-bit little-endian audio; PCM has no WAV
header. `X-Audio-Sample-Rate` reports the rate. MP3, style instructions and speed changes
are not available, and unsupported fields return a JSON error. The server rejects reserved
tokenizer symbols, invalid structured dates and times, and text that grows too long once
expanded. A `Range` header gets HTTP 416.

An input of 45 words or more is synthesized sentence by sentence. `--max-input-characters N`
raises the 4096-character limit, up to 16384, so a long reply fits in one request; streamed, it
starts playing as soon as its first audio is ready. These limits scale with N:
- a sentence for every 16 characters allowed (at least 64 sentences);
- the text as spoken, with numbers, dates and abbreviations written out, may be four times the
  input, and at most 16,384 characters in any case: about 24 minutes of speech, within the 96 MiB
  of audio a request may produce;
- at most 4,096 numbers, dates and similar values per input, whatever N.

Raise `--request-timeout` along with N: on four CPU cores, synthesis takes about twice as long
as the audio lasts.

Every successful response carries `X-Usage-Characters`, the number of `input`
characters it was billed for. Characters are counted as sent, in Unicode code points,
the same way the input limit and Python's `len()` count them. A precomposed Romanian
letter with a diacritic (ă, â, î, ș, ț) is one character even though it takes two
UTF-8 bytes, so a gateway that counted request bytes would overcharge Romanian text by
about 10%. A decomposed letter (a base letter followed by a combining mark) counts as
two, and whitespace and bracketed spans that aren't spoken count too. If your account
service counts characters itself, use the same rule. Error responses (4xx and 5xx,
including queue-full, timeout and worker failures) carry no count.

### Streaming

Without `stream_format`, the response carries the complete recording once synthesis is done.
With it, audio is sent as the runtime produces it, so the first audio reaches the client after
the runtime's time to first audio plus network time. Measured over HTTP on
one machine with benchmark sentences of 3 to 5 seconds of audio: 32 ms on an RTX 5090 (median of
20 requests, p90 38 ms), and 1.3 s on four CPU cores, where the whole recording takes 9.4 s. A
3,524-character input (5 minutes of audio) started playing after 32 ms on the RTX 5090; its
synthesis took 17.5 s. On the CPU, streamed audio is the same, sample for sample, as the whole
recording.

- `stream_format: "audio"` sends the recording's bytes in a chunked body as they are produced.
  With `wav`, a header of unknown length comes first: its size fields are `0xFFFFFFFF`, which
  players read as "until the end". With `pcm`, the raw samples come alone.
- `stream_format: "sse"` sends the same bytes base64-encoded in `speech.audio.delta` events
  (`{"type": "speech.audio.delta", "audio": "…"}`). A `speech.audio.done` event with
  `usage.input_characters` and `usage.audio_seconds` ends a complete stream.

A streamed request waits in the queue like any other before its headers go out, so a full
queue, a queue timeout or an invalid request still gets its HTTP error status and no
`X-Usage-Characters`.

The client sets the pace of delivery; synthesis runs at its own speed. The worker moves on to
the next request as soon as the last audio is made, and audio the client hasn't read yet waits
in the server (at most the 96 MiB a request may produce). `--request-timeout` covers queueing and
synthesis but not delivery. A client that reads nothing for 5 seconds is disconnected. A request, streamed or whole,
keeps its place in the queue until its audio has been delivered, so `--max-pending-requests` also
bounds how many listeners can be served at once: raise it for many clients that play the audio as
it arrives. Audio not yet read takes memory, up to 96 MiB per request (about 12 GiB with 128
pending requests). An idle keep-alive connection is closed after 1 second, so a connection pool in
front of the server should reuse connections sooner or not keep them.

By the time a stream starts, `X-Usage-Characters` has already been sent. A stream that fails
partway counts as not delivered: a raw stream ends without its final chunk, which clients report
as an incomplete response, and an SSE stream ends with an `error` event instead of
`speech.audio.done`. So bill a streamed request only once it completes, because its status (200)
and `X-Usage-Characters` arrive before anyone knows whether it will.

`speech.audio.done` reports this server's usage fields, `input_characters` and
`audio_seconds`, in place of the `input_tokens`, `output_tokens` and `total_tokens` in
OpenAI's event.

The endpoint follows OpenAI's speech request shape for the fields it supports, with WAV as
its default format. From an OpenAI client, ask for `response_format="wav"` explicitly. The
service speaks Romanian only; it doesn't include the separate foreign-language routing used
for 30 rows of the research stress benchmark.

## Local and newly cloned voices

Pass the native export directory or its `voices.json`:

```bash
surogate serve --tts /models/my-voice-native --voice "My voice" --port 8080
surogate serve --tts /models/my-voice-native/voices.json --voice "My voice"
```

Use the native package that the
[published voice-creation pipeline](https://github.com/invergent-ai/training_tts/blob/main/docs/CREATE-A-VOICE.md)
produces, and keep its model, codec, runtime libraries, tokenizer and profile together.
The server verifies their hashes and takes the voice names and decoding settings from the
profile. A bare NeMo checkpoint or a Python-only voice profile has to be exported first,
with that pipeline's `ro_tts.export_native` command.

`--voice` sets the default voice; clients can still pick any voice in the loaded
package. To add a voice, make a new native export and restart the server. You don't
need a separate model process per voice.

## pocket-tts packages

A package whose `voices.json` has `"method": "pocket_tts_python"` holds a pocket-tts
model and brings its own worker program, which the server runs in place of
`surogate-tts-worker`. The worker receives the request text as UTF-8, prepares it itself
(numbers, codes, stress) and returns audio at the package's `sample_rate` (24 kHz for
pocket-tts). The server reports that rate in `X-Audio-Sample-Rate` and in every WAV
header. These packages run on CPU only.

```bash
SUROGATE_TTS_PYTHON=/path/to/venv/bin/python \
SUROGATE_TTS_VERIFY_URL=http://127.0.0.1:8001/v1/audio/transcriptions \
  surogate serve --tts /models/pocket-ro --port 8080
```

| `voices.json` field | Meaning |
|---|---|
| `sample_rate` | The worker's output rate, 8000–48000 |
| `worker` | The worker program, relative to the package |
| `model.config` | The model config, relative to the package |
| `voices.NAME.prompt` | The voice's recording, relative to the package |
| `decoding.temperature` | Sampling temperature, above 0 and at most 2 |
| `decoding.code_attempts` | Attempts per generated code, 1–8 (default 1) |
| `code_units` | Recorded character clips codes are assembled from |

The launcher checks these files, plus every hash in `MANIFEST.sha256` if the package
has one.

### Codes

The Romanian package reads IBANs, phone numbers, CNPs and other codes one character at
a time, and it never generates them. Its `units/` directory holds a recorded clip of every
character in each voice, cut from the model's own readings, checked by speech recognition
and approved by ear. The worker joins those clips with fixed pauses (`voices.json`
`code_units`), and a join can't skip, repeat or swap a character. Only the words around a
code are generated.

The worker spots most codes on its own. To make sure a code is read as one, mark it
the way SSML does:

```json
{"input": "Contul este <say-as interpret-as=\"characters\">RO49 AAAA 1B31 0075 9384 0000</say-as>."}
```

A marked code holds 1 to 64 letters, digits, spaces, `+` and `-` (spaces and hyphens
only group it visually). The tags aren't billed. Any other use of `say-as` returns 400,
so a mistyped tag is never read out loud.

If a character has no clip, the worker falls back to generating the code's sentence.
With `SUROGATE_TTS_VERIFY_URL` set to a [speech recognition](/engine/inference/speech/) server, that
sentence is transcribed with `decoding=greedy`, and if the code heard differs, synthesized
again with another seed, up to `code_attempts` times. `SUROGATE_TTS_VERIFY_API_KEY` is sent
as the bearer token.

## Queue, authentication and shutdown

`--max-num-seqs N` (default 1, at most 16) synthesizes N requests at once. Each runs in its own
worker process with its own copy of the model: about 2.4 GB of GPU memory per worker on a GPU, or
on the CPU about 1.5 GB of memory and `--threads` + `--codec-threads` threads per worker. All
workers load before the server answers, and if one fails to load, the startup error names it.

A worker that fails is replaced at once without disturbing the others, and requests go first to a
worker whose model is loaded. A worker that dies while idle is restarted in the background. One
that dies before its model loads (for example because another process took the GPU memory) is
retried every 10 seconds. Meanwhile it takes no requests as long as another worker can serve; when
none can, requests get HTTP 503 at once. `/health` stays 200 while any worker can serve, with
`"status": "degraded"` and `"workers": {"ready": R, "total": N}`, and turns 503 when none can. A
worker counts as ready once its model has loaded, or while it loads in place of one that had.

On one RTX 5090 with `--max-num-seqs 4`, streaming Doina, each request's processing time per
second of audio was (median, and the maximum in brackets; below 1 is faster than real time):

| Concurrent requests | Alone | Next to Rune serving 8 chats at once |
|---|---|---|
| 1 | 0.04 (0.04) | 0.18 (0.44) |
| 2 | 0.09 (0.13) | 0.66 (0.90) |
| 3 | 0.19 (0.28) | 0.90 (1.09) |
| 4 | 0.26 (0.55) | 0.88 (1.43) |

Rune was the Q4_K_M build with `--gpu-memory-limit-mib 20000 --max-num-seqs 8`, beside four TTS
workers (about 2.46 GB each) on the same card. First audio took 30 ms alone and 110 to 180 ms
(median) next to Rune. So next to a busy LLM server, 2 requests at a time each stay faster than
real time, and a third doesn't always. The workers share the GPU by time slicing and don't batch.

By default, eight more requests can wait, and they're served in arrival order. Set
`--max-pending-requests N` to change the queue size, or `0` to reject requests whenever every
worker is busy or a stream is still being delivered. A full queue returns HTTP 429.
`--request-timeout SECONDS` limits queueing plus synthesis time (default 300); when it runs out,
the request gets HTTP 504. When a client leaves, its request stops at the worker's next audio
chunk and the worker moves on to the next request without reloading the model. If a worker
produces no audio for 30 seconds after the client left, it is stopped instead. A worker that
failed or timed out is replaced at once, unless it died before its model loaded (then it is
retried every 10 seconds). At shutdown the workers stop at once, even mid-request.

The server binds to `127.0.0.1` by default; use `--host` to choose another interface.
`--api-key-file PATH` turns on bearer authentication for every endpoint, reading the key from a
file. Unlike `--api-key KEY`, it keeps the key off the process's command line, where every local
user can read it:

```bash
surogate serve --tts surogate/surogate-ro-tts --api-key-file /etc/surogate/tts.key
curl -H "Authorization: Bearer $(cat /etc/surogate/tts.key)" http://localhost:8080/v1/audio/voices
```

A normal shutdown stops the native workers and removes temporary audio. The server
keeps neither finished request audio nor per-request native statistics on disk.

`GET /metrics` reports the server in Prometheus text format, like the LLM server:

- `surogate_up`;
- `surogate_requests{state="running"}`: speech requests, counted from arrival, including while
  they wait in the queue, until their audio has been written or their client has gone;
- `surogate_requests_total{endpoint,outcome}`;
- `surogate_characters_total`: input characters billed;
- `surogate_audio_seconds_total`: seconds of audio synthesized.

To drain a server before you restart it, wait for `surogate_requests{state="running"}` to reach 0.

## Quality

Serving uses the published model, Romanian normalization, tokenizer and fixed
per-voice decoding settings unchanged. The 301 Romanian benchmark inputs produce the
same token sequences as the accepted native release, and HTTP control recordings match
the saved native outputs byte for byte, including voice switching and long text. That
is an integration check: it doesn't measure WER or the quality of a newly cloned voice.
Published scores and licensing are on the
[model card](https://huggingface.co/surogate/surogate-ro-tts).

## Validation

```bash
make serve-tts-build
.venv/bin/python -m pytest -q tests/serve/test_tts.py tests/serve/test_cli.py
SUROGATE_TTS_TEST_MODEL=surogate/surogate-ro-tts \
  .venv/bin/python -m pytest -q tests/serve/test_tts_http.py
```

The first command builds the server and a frontend test driver. The unit tests
exercise the native HTTP server against a protocol fixture. The opt-in test loads the
real HF model and compares the three released voices with frozen audio hashes. The
tokenizer regression fixture covers all 301 Romanian inputs.

See also: [Romanian speech recognition](/engine/inference/speech/) for the other direction, and the
[CPU kernel validation report](/engine/inference/cpu-kernels/) for how the CPU path was measured.
