Kokoro-FastAPI icon indicating copy to clipboard operation
Kokoro-FastAPI copied to clipboard

Memory leak: server heap grows ~65 MB per TTS generation on CPU (v0.9.1 and v0.9.2, kokoro lib 0.9.4)

Open glowglowflow opened this issue 4 weeks ago • 10 comments

Summary

The Kokoro-FastAPI CPU server leaks memory on every synthesis request. The heap grows monotonically, ~65 MB per short generation, with no release. The idle heap is flat. The leak reproduces identically on v0.9.1 and v0.9.2 with kokoro lib 0.9.4, and MALLOC_ARENA_MAX=1 does not prevent it.

This looks like the underlying kokoro library leak (hexgrad/kokoro#152) rather than a FastAPI-wrapper issue: the per-request voice-tensor caching fix (#453) is already in both versions tested, and the v0.9.2 voice-mix fix (#565) doesn't apply here — only single voices are used.

Environment

  • Image: ghcr.io/remsky/kokoro-fastapi-cpu, pinned v0.9.1 then v0.9.2
  • kokoro lib 0.9.4, misaki 0.9.4 (as bundled in the image)
  • CPU-only, single uvicorn worker, Docker on Ubuntu, 14 GB RAM host
  • MALLOC_ARENA_MAX=1 set on the container for both tests
  • Voice am_fenrir, model kokoro, mp3, via POST /v1/audio/speech

Reproduction

  1. Start the container fresh and let the model warm up (72 voice packs load).
  2. Record the server process heap (VmData from /proc/<pid>/status).
  3. Send 15 short distinct synthesis requests (one sentence each), ~1 s apart.
  4. Record the heap after each request.

Measured results

v0.9.1 (baseline after warm-up: VmData 1,822,880 kB, RSS 1,223,124 kB)

  • After 15 generations: VmData 2,867,652 kB (+1,044,772 kB), RSS 1,915,372 kB (+692,248 kB)
  • Per generation: ~68 MB VmData on average. First generation +145 MB (likely lazy-loads in the synthesis path); generations 2–15 average ~64 MB
  • Growth on 15/15 generations, no decreases anywhere; swap stayed at 0 throughout

v0.9.2 (baseline after warm-up: VmData 1,858,208 kB, RSS 1,249,976 kB)

  • After 15 generations: VmData 2,891,996 kB (+1,033,788 kB), RSS 1,931,448 kB (+681,472 kB)
  • Per generation: ~69 MB VmData on average. First generation +134 MB; generations 2–15 average ~64 MB
  • Identical rate to v0.9.1 — the upgrade did not change the leak

Controls

  • Idle is flat: heap was byte-identical across ~3.5 minutes idle before the test, and flat across 30 s of post-warm-up sampling.
  • Warm-up is separate from the leak: during startup the heap climbs 472 → 985 → 1,862 MB over ~15 s as the model and voices load, then goes flat. Warm-up establishes the ~1.86 GB floor; only synthesis adds on top of it.
  • Long-term accumulation matches: before these tests, the same process had grown to VmData 3,755,908 kB with 2.31 GB swapped over 10 days of occasional organic TTS use — consistent with ~65 MB per generation accumulating.
  • MALLOC_ARENA_MAX=1 was set for both tests and did not prevent the growth (as expected — it reduces fragmentation, not a genuine per-request leak).

Workaround

A conditional nightly restart when the heap passes 2.5 GB bounds the heap permanently for a rarely-used service. But every user of this image on CPU is presumably leaking the same way.

Happy to provide the per-generation logs or re-run with any suggested instrumentation.

glowglowflow avatar Nov 07 '26 15:11 glowglowflow

I can reproduce this on ghcr.io/remsky/kokoro-fastapi-cpu:v0.9.2 (x86_64, Docker, container limited to 4 CPUs, voice af_heart, mp3) and ran a few variants to narrow it down. Numbers are VmRSS of the uvicorn process in MB, measured after warm-up and after each request.

Setup: One fresh container per variant, 25 distinct sentences with 3 to 27 words (so every request in a round has a new length), 1 s pause between requests, plus a 10 s idle check at the end.

Variant RSS after warm-up after 25 requests Avg. time per request
Default 1278 1912 (+634) baseline
Same sentence 25 times 1365 1445 (+80, flat after the first request) baseline
MALLOC_ARENA_MAX=1 1267 2424 (+1157) about the same
MALLOC_MMAP_THRESHOLD_=65536 + MALLOC_TRIM_THRESHOLD_=131072 1125 1206 (+81) about 1.5x slower
ONEDNN_PRIMITIVE_CACHE_CAPACITY=0 1341 1656 (+315) about the same
jemalloc via LD_PRELOAD 1265 1276 (+11) about 1.4x slower

A longer run with 75 requests (the same 25 sentences three times):

Variant after 25 after 50 after 75 Avg. time per request
Default 1637 2314 2290 4.81 s
jemalloc 1301 1288 1300 6.48 s

What I take from this:

  • The growth depends on the input, not on the number of requests: The same sentence repeated stays flat, varied sentences keep growing. That looks like the per-shape caching found for MPS in hexgrad/kokoro#152, only on CPU.
  • Nothing is given back when idle (the 10 s idle reading matches the last request).
  • In the long run the default case flattened out in the third round at about +900 MB. So with a bounded set of lengths it seems to level off, but real traffic has far more distinct lengths than my 25.
  • MALLOC_ARENA_MAX=1 makes it worse here, not better.
  • VmData overstates the problem: With jemalloc VmData still grows by about 900 MB (reserved address space) while RSS stays flat.
  • The two settings that stop the growth (glibc thresholds, jemalloc) both cost speed in my runs, so I would not suggest either as a new default yet. ONEDNN_PRIMITIVE_CACHE_CAPACITY=0 halves the growth at no visible cost.

For anyone who needs a workaround now: Preloading jemalloc (LD_PRELOAD=/path/to/libjemalloc.so.2; the image does not ship it, I mounted the one from the Ubuntu host) keeps memory flat if the slowdown is acceptable. Next I want to try jemalloc with MALLOC_CONF tuning (background thread, decay times) to see whether the speed cost goes away. If it does, adding jemalloc to the CPU image with that config could be a small PR. Happy to share the test script.

YaannnTech avatar Nov 07 '26 17:11 YaannnTech

Thanks @glowglowflow and @YaannnTech, the details are a big help.

Looking into it as well and looks like glibc fragmentation rather than a true leak (re: the allocator change flattened it on @YaannnTech's jemalloc run). Reproduced on CPU, same early climb (~700-900 MB RSS over the first 15).

Adding a few variant test results to the ones above:

Variant RSS after 40 (MB) Long req (1.1k chars) Short req (streaming)
Default (fresh) 1714-2917 31.5 s 2.06 s
Default (after ~60 requests) ~3500 41.2 s 3.25 s
malloc_trim(0) per request 1306 42.4 s 3.48 s
malloc_trim(0) every 1 s 1340 41.8 s (didn't run)
thresholds 128K 1270 42.6 s (didn't run)
thresholds 512K 1306 36.4 s 2.59 s
thresholds 1M 1495 37.3 s 2.76 s
thresholds 4M 1776 34.5 s 2.58 s
  • Agree its likely input-driven. Every sentence with a different length has torch asks for different-size tensor: oneDNN caches and glibc holds onto them. Replaying 30 already-seen sentences stayed flat
  • The default slowed as it ran (long request 31.5 s -> ~41 s over ~60 requests). Confirming with a longer soak on v0.9.2
  • If MALLOC_CONF tuning closes the speed gap, glad to take a PR @YaannnTech . Would need to handle arm64 page sizes, since the CPU image is multi-arch.

Interim suggestions I'd add -For a restart, triggering on RSS (+ VmSwap) rather than VmData (counts reserved address space), should avoid tripping early on 2.5 GB. -Below settings also held RSS flat below with some speed cost.

# RSS flat ~1.3 GB, ~15-25% slower synthesis
environment:
  - MALLOC_MMAP_THRESHOLD_=524288
  - MALLOC_TRIM_THRESHOLD_=524288

remsky avatar Nov 07 '26 17:11 remsky

Follow-up after your replies:

  • Switched my restart guard to trigger on VmRSS + VmSwap > 2.5 GB (was VmData), per @remsky's advice. RSS alone would have missed my swapped-out state (RSS 226 MB with 2.3 GB swapped after 10 days).
  • Removed MALLOC_ARENA_MAX=1 from the container env.

Re-ran the identical 15-generation test on v0.9.2 without it (all 200s):

Before (with MALLOC_ARENA_MAX=1) After (without)
RSS +681,472 kB (~46 MB/gen) +469,468 kB (~31 MB/gen)
VmData +1,033,788 kB (~69 MB/gen) +886,308 kB (~59 MB/gen)

Growth is smaller but still there, and no longer strictly monotonic (small dips at generations 3 and 7). Matches @YaannnTech's finding that the setting made it worse here too.

glowglowflow avatar Nov 07 '26 17:11 glowglowflow

Just updating with the soak results, v0.9.2, 100 requests. Though note: this ran with MALLOC_ARENA_MAX=1 (the original setup), which would be giving a worse case as the baseline:

RSS plateau Long req, first 40 Long req, last 50
Default ~2.5 GB ~32.5 s ~39.3 s
thresholds 1M ~1.47 GB ~35.6 s ~34.4 s
  • 1M holds ~1 GB less and ends up faster than default once running awhile, ~~likely a better pick than the 512K I posted above~~*
  • Default plateau ranged 1.7-3.5 GB across runs, so a 2.5 GB guard actually may still trip on a healthy server. Would raise it ~~or pair with the 1M settings~~*

^edit: only with MALLOC_ARENA_MAX=1, see follow-comment

# with MALLOC_ARENA_MAX=1: RSS flat ~1.47 GB, ~8% slower than a fresh default, faster after ~50 requests
environment:
  - MALLOC_MMAP_THRESHOLD_=1048576
  - MALLOC_TRIM_THRESHOLD_=1048576

Without MALLOC_ARENA_MAX the default grows less, so the 1M gap is likely smaller. Letting the soak rerun without it to confirm and will post

remsky avatar Nov 07 '26 17:11 remsky

Soak rerun without MALLOC_ARENA_MAX, same setup otherwise:

RSS plateau Long req, first 40 Long req, last 50
Default ~2.05 GB ~28.5 s ~28.9 s
thresholds 1M ~1.48 -> 1.66 GB ~32.8 s ~39.7 s
  • Without it the default plateaus ~450 MB lower, is ~12% faster fresh, and held its speed the whole run
  • Walking back the 1M suggestion. Without MALLOC_ARENA_MAX it saves ~400-600 MB, but starts ~15% slower and drifted to ~37% slower after ~50 requests. Only worth it if you're stuck on MALLOC_ARENA_MAX=1

@glowglowflow your current setup (no MALLOC_ARENA_MAX, guard on RSS + VmSwap) looks like the right call. Default did hit ~3.5 GB in one earlier run for me though, might be worth giving the 2.5 GB guard some headroom

While @YaannnTech is checking jemalloc+MALLOC_CONF tuning, I'll do a run to see if ONEDNN_PRIMITIVE_CACHE_CAPACITY holds as a low cost improvement across long generations; and as a small cap vs 0 if that doesn't pan out

remsky avatar Nov 07 '26 19:11 remsky

Here is the jemalloc tuning run, with your glibc settings measured on the same box for comparison. Same setup as before (v0.9.2 CPU, fresh container per variant, 4 CPUs, no MALLOC_ARENA_MAX), now 25 varied short requests, a 10 s idle check, then 3 long requests of about 1.1k characters (each a new length). RSS in MB.

Variant RSS warm-up after 25 short after 10 s idle after 3 long Short avg Long avg
Default 1366 2210 2210 2369 4.78 s 36.2 s
glibc thresholds 512K 1142 1235 1235 1248 7.05 s 54.1 s
glibc thresholds 1M 1168 1390 1390 1429 6.98 s 53.7 s
jemalloc, dirty_decay_ms:-1,muzzy_decay_ms:-1 1594 2033 2033 2043 4.21 s 33.3 s
jemalloc, oversize_threshold:0,dirty_decay_ms:30000,muzzy_decay_ms:30000 1356 1604 1604 1583 4.23 s 33.4 s
jemalloc, same + background_thread:true 1359 1624 1416 1573 4.22 s 33.3 s

What I found:

  • The slowdown of plain jemalloc in my first comment came from purging, not from jemalloc itself: With purging off (dirty_decay_ms:-1) it was faster than the default. Background purging and a 30 s decay alone did not help, because buffers above 8 MB go to jemalloc's separate oversize arena, which gives memory back right away. oversize_threshold:0 puts them under the normal decay.
  • The last row is the best trade-off I found: About 12% faster on short and 8% faster on long requests than the default here, RSS stays about 600 to 800 MB below the default, and the background thread hands memory back when idle (1624 -> 1416 MB after 10 s).
  • The purge-off variant plateaus: In a separate 75-request run it stayed at 2033, 2054, 2055 MB after 25, 50 and 75 requests. Fast, but it keeps its peak.
  • Both glibc threshold settings were about 1.47x slower on short and long requests on this box, more than in your runs. That matches your rerun without MALLOC_ARENA_MAX, so I agree with walking them back.
  • From my first round, ONEDNN_PRIMITIVE_CACHE_CAPACITY=0 halved the growth (+315 vs +634 MB after 25 short requests) with no visible speed cost, but I only measured short requests there. Curious what your long-generation run shows.

Caveats: One run per variant, a CPU quota of 4 cores on a Ryzen 7 PRO 6860Z (Docker snap on Ubuntu 24.04), and the tuned variant only saw 28 requests, so no soak yet. jemalloc is not in the image; I preloaded the Ubuntu host's libjemalloc 5.3.0 via a bind mount.

If you are open to it, I could open a PR that installs libjemalloc2 in the CPU image and sets LD_PRELOAD plus the MALLOC_CONF above (both easy to override), after running a 100-request soak with it, same as yours. Let me know if that direction works for you or if you would rather keep the allocator out of the image.

YaannnTech avatar Nov 07 '26 19:11 YaannnTech

Nice find on the oversize arena @YaannnTech, best result in the thread so far.

My results on the long-generation run w/ ONEDNN_PRIMITIVE_CACHE_CAPACITY=0, v0.9.2 don't hold the free win once we get past short runs, and a small cap doesn't seem worth the tests. As below:

With no MALLOC_ARENA_MAX, same soak:

RSS after 20 RSS after 100 Long req, first 40 Long req, last 50
Default ~2.05 GB ~2.17 GB ~30.3 s ~29.1 s
cache 0 ~1.68 GB ~2.47 GB ~36.3 s ~37.6 s
  • Matches your halving early on (lower through ~20 requests), but it caught up by ~30 and ended ~300 MB higher
  • ~20-30% slower on long requests throughout, short ~1.75 s -> ~2.6 s. Likely rebuilding kernels for every chunk without the cache.

The jemalloc PR w/ the soak results would be great. Will give it a test through my machine as well.

  • Can we make sure to set LD_PRELOAD=libjemalloc.so.2 as a bare name so it resolves on both arches
  • (turns out Debian's arm64 libjemalloc2 is built with 64K pages, so page size I mentioned is a non-issue).

remsky avatar Nov 07 '26 20:11 remsky

Thanks! A 100-request soak is running now: The stock v0.9.2 image against one set up as it would be in the PR (Debian's libjemalloc2, LD_PRELOAD=libjemalloc.so.2 as a bare name, the MALLOC_CONF above), with a long request after every 10th. The bare name also resolves on arm64 (python:3.12-slim, libjemalloc2 5.3.0-3).

I'll post the results here in about 30 minutes, together with the exact Dockerfile change. I'm traveling after that, so if you'd rather apply it yourself, go ahead; otherwise I'm happy to open the PR tomorrow.

YaannnTech avatar Nov 07 '26 20:11 YaannnTech

Opened #595 with the change and the soak results. In short, after 100 requests with a long one after every 10th: RSS 1932 MB (v0.9.2) vs 1566 MB (jemalloc), 1874 vs 1396 MB after 15 s idle, short requests 4.90 vs 4.38 s and long ones 37.7 vs 35.3 s on average, all 200s.

Not done is a full build of Dockerfile.optimized from the branch for all CPU targets (the soak image was v0.9.2 plus the same package and ENV lines), since I'm boarding a flight now. If you'd rather take it over or adjust it, feel free.

YaannnTech avatar Nov 07 '26 20:11 YaannnTech

Thanks @YaannnTech and safe travels. I can grab it from here and run the platform builds/checks, any nits that pop up.

remsky avatar Nov 07 '26 20:11 remsky