Repository navigation
Parakeet batch: GPU worker + dynamic batching (36 RPS on L4, ~36x throughput) - #7938
Conversation
Apply optimizations from beastoin/NeMo#2 (zen's thread-safety + high-perf batch server): - Dedicated GPU worker thread: all model.transcribe() calls isolated on a single thread, eliminating CUDA context contention and cross-thread tensor GC crashes - Dynamic batching engine: collects concurrent requests, flushes by batch size (32) or timer (2ms) for maximum GPU utilization (43 RPS vs ~1 RPS serial on L4) - GC management: gc.disable() globally, gc.collect(0) per batch on GPU thread, full gc.collect() every 50 batches — prevents async event-loop thread from freeing CUDA pinned-memory tensors (signal 139 segfaults) - torch.compile: +20-30% throughput from kernel fusion (PARAKEET_TORCH_COMPILE env) - CUDA optimizations: cudnn.benchmark=True, set_float32_matmul_precision('high') - Result serialization: NeMo results converted to plain Python dicts on GPU thread before crossing thread boundaries - CUDA graphs control: PARAKEET_CUDA_GRAPHS=false for T4 compatibility - Backpressure: 503 when queue exceeds depth limit (default 4096) Existing v1/v2/v3 API contracts preserved. NIM fallback path preserved. Streaming (v3) continues using stream_handler.py with its own model management. Closes #7936 Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin Two blockers before merge: I verified the changed Parakeet modules with by AI for @beastoin |
… diarize=False contract 1. Model loading is now non-blocking — server starts immediately so /health returns loading status during model init; v1/v2 return 503 while loading 2. v2 diarization runs in a ThreadPoolExecutor (4 workers) instead of on the async event loop — prevents blocking the batch flush loop 3. Restore diarize=False contract: segments get SPEAKER_0 when diarize=False Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Fixed all 3 reviewer items:
by AI for @beastoin |
Greptile SummaryThis PR introduces a dedicated GPU worker thread and async dynamic batching engine for the Parakeet ASR service, replacing the single-threaded semaphore-gated approach that caused CUDA segfaults under concurrent load. The two new files (
Confidence Score: 3/5The NeMo batching core is solid, but two regressions introduced by the async endpoint conversion need fixing before this is safe to ship for NIM deployments and any caller using diarize=false. The GPU worker and batch engine logic is well-thought-out and the NeMo path works correctly. However, converting the endpoints from
Important Files Changed
Reviews (1): Last reviewed commit: "Fix review feedback: non-blocking model ..." | Re-trigger Greptile |
|
|
||
|
|
||
| @app.post("/v1/transcribe") | ||
| def transcribe(file: UploadFile = File(...)): | ||
| """Batch-transcribe an audio chunk (16 kHz mono) with on-GPU Parakeet.""" | ||
| async def transcribe(file: UploadFile = File(...)): | ||
| if gpu_worker is not None and not gpu_worker.is_ready: | ||
| return JSONResponse(status_code=503, content={"detail": "Model loading, try again shortly"}) | ||
| upload_id = str(uuid.uuid4()) | ||
| file_path = f"_temp/{upload_id}_{file.filename}" | ||
| ACTIVE_BATCH.inc() | ||
| t0 = time.monotonic() | ||
| try: | ||
| with open(file_path, "wb") as f: | ||
| f.write(file.file.read()) | ||
| with _GPU_SEMAPHORE: | ||
| f.write(await file.read()) | ||
|
|
||
| if batch_engine is not None: | ||
| result = await batch_engine.submit(file_path, timestamps=True, owns_file=True) | ||
| return JSONResponse(content=_transcribe_from_gpu_result(result)) | ||
| else: | ||
| return transcribe_file(file_path) | ||
| except QueueFullError: | ||
| return JSONResponse(status_code=503, content={"detail": "Server overloaded — try again later"}) | ||
| finally: | ||
| REQUEST_DURATION.labels(endpoint="v1_transcribe").observe(time.monotonic() - t0) | ||
| ACTIVE_BATCH.dec() |
There was a problem hiding this comment.
Blocking synchronous I/O inside async endpoints freezes the event loop
Both /v1/transcribe and /v2/transcribe were converted from def to async def, but their fallback code paths still call synchronous blocking functions directly on the event-loop thread. In NIM mode (batch_engine is None), transcribe_file(file_path) calls _transcribe_nim() which uses httpx.Client (synchronous) — this blocks the entire event loop for the full HTTP round-trip to NIM (up to 120 s timeout). The v2 diarization path is also affected: transcribe_file_v2() → _diarize_segments() → _get_embedding() uses httpx.Client synchronously even when batch_engine is not None. Before this PR these were def endpoints and FastAPI automatically ran them in a threadpool; now as async def that protection is gone.
The fix is to wrap the blocking calls with await asyncio.to_thread(...) or await loop.run_in_executor(None, ...), or keep the sync wrappers as plain def functions and let FastAPI's thread pool handle them.
| if diarize: | ||
| base = _diarize_segments(file_path, base) | ||
| else: | ||
| for seg in base["segments"]: |
There was a problem hiding this comment.
diarize=False silently drops speaker labels, breaking the v2 API contract
Previously, when diarize=False, _transcribe_v2_with_diarization would still iterate over segments and set speaker="SPEAKER_0" on each one. Now _diarize_segments is never called when diarize=False, so the segments in the response have no speaker field at all. Any client that calls /v2/transcribe with diarize=false and reads seg["speaker"] will receive a KeyError or see the field missing where it was always present before.
| if diarize: | |
| base = _diarize_segments(file_path, base) | |
| else: | |
| for seg in base["segments"]: | |
| if diarize: | |
| base = _diarize_segments(file_path, base) | |
| else: | |
| for seg in base.get("segments", []): | |
| seg["speaker"] = "SPEAKER_0" | |
| base["detected_language"] = detect_language_from_text(base.get("text", "")) |
| vram_used = torch.cuda.memory_allocated() / 1024**2 | ||
| vram_total = torch.cuda.get_device_properties(0).total_mem / 1024**2 |
There was a problem hiding this comment.
VRAM total logged against hardcoded device 0, not the configured device
torch.cuda.memory_allocated() reports for the current default device, but get_device_properties(0) is always device 0. If PARAKEET_DEVICE=cuda:1, the logged VRAM total will belong to the wrong GPU, making the log misleading for multi-GPU hosts.
| vram_used = torch.cuda.memory_allocated() / 1024**2 | |
| vram_total = torch.cuda.get_device_properties(0).total_mem / 1024**2 | |
| dev_idx = torch.device(device).index if torch.device(device).index is not None else 0 | |
| vram_used = torch.cuda.memory_allocated(device) / 1024**2 | |
| vram_total = torch.cuda.get_device_properties(dev_idx).total_mem / 1024**2 |
| audio_paths = [r.audio_path for r in batch] | ||
| timestamps = batch[0].timestamps if batch else True |
There was a problem hiding this comment.
All requests in a batch silently inherit the first request's
timestamps setting
When the batch is flushed, timestamps is taken only from batch[0]. Requests with timestamps=False that happen to land after batch[0] will receive timestamp data they didn't ask for, while a timestamps=False first item drops timestamp data for everyone. For this service all callers currently send timestamps=True, but this is a silent correctness trap for future callers.
| audio_paths = [r.audio_path for r in batch] | |
| timestamps = batch[0].timestamps if batch else True | |
| audio_paths = [r.audio_path for r in batch] | |
| # Use True if any request wants timestamps so every response is consistent | |
| timestamps = any(r.timestamps for r in batch) |
Covers: lifecycle (start/stop/load failure/timeout), sync/async submit, queue full, extract_results serialization, GC intervals, drain queue, batch flush (max-size/timer), file cleanup (owns_file), error propagation, result count mismatch, metrics, shutdown drain, transcribe routing, gpu_result bypass, diarize=False SPEAKER_0 contract, NIM mode fallback. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin I still see two blockers before merge: the new non-blocking model load lets the container accept traffic before the model is usable, but prod/dev Parakeet readiness/startup probes remain TCP-only ( I ran by AI for @beastoin |
…tdown - /health returns 503 (not 200) while model loading — K8s readiness probe now correctly gates traffic until model is ready - BatchEngine.stop() cancels flush loop immediately instead of waiting for timer — shutdown test drops from 100s to <1s Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin I still see two blockers before merge: Please push a follow-up for those two before merge. by AI for @beastoin |
- Offload sync file write/remove to _io_pool ThreadPoolExecutor in v1/v2 endpoints — prevents blocking the async event loop - Fix test order dependency: use sys.modules["nemo.collections.asr"] at runtime instead of module-level _nemo_asr reference, so tests pass regardless of pytest collection order Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin The three prior blockers look fixed, but there is one remaining blocker before merge: Verified: by AI for @beastoin |
v1/transcribe NIM-mode fallback (transcribe_file) was running sync httpx.Client.post + file I/O inline on the event loop. Moved to run_in_executor for consistency with batch path. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin One blocker remains before merge: by AI for @beastoin |
K8s readiness and startup probes now use HTTP GET /health instead of TCP checks. Since /health returns 503 while model is loading, K8s won't route traffic until the GPU model is fully ready. Liveness probe stays TCP (pod is alive even while loading). Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin No issues found on re-review. The previous blockers are addressed: model load no longer blocks FastAPI startup, Ready to merge from my review. by AI for @beastoin |
Tests: /health returns 503 while loading / 200 when ready / healthy in NIM mode, /batch/metrics returns engine stats or empty, v1/v2 endpoints return 503 on loading/queue-full and route through batch engine correctly. Total: 61 parakeet batch tests. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin One repo-rule gap remains before merge: this PR introduces new runtime env vars in by AI for @beastoin |
Documents all new env vars: PARAKEET_DEVICE, PARAKEET_TORCH_COMPILE, PARAKEET_CUDA_GRAPHS, PARAKEET_GC_INTERVAL, PARAKEET_GPU_POLL_TIMEOUT, PARAKEET_MAX_BATCH_SIZE, PARAKEET_BATCH_WAIT_SECONDS, PARAKEET_MAX_QUEUE_DEPTH, PARAKEET_INFERENCE_MODE. Also documents /health 503 readiness gate and /batch/metrics endpoint. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin One blocker before merge: the new Parakeet endpoint tests are now part of the required backend suite via by AI for @beastoin |
Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin One blocker remains: I verified the earlier review fixes with by AI for @beastoin |
GPUWorker._load_model() was missing the PARAKEET_BF16 conversion that exists in transcribe.py._load_nemo_model(). Added back: converts model to bfloat16 when BF16 is supported, halving GPU memory usage. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin One blocker remains before merge: I verified by AI for @beastoin |
Track in-flight flush tasks so stop() cancels them alongside the timer loop. Catch CancelledError in _flush_batch to resolve batch futures with errors instead of leaving them pending forever. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin No issues found on re-review. The previous blockers are addressed: startup no longer waits on Ready to merge from my side. by AI for @beastoin |
Restore real transcribe module when stream_session tests replace it with MagicMock. Clear PARAKEET_STREAM_MODEL to prevent model init during reimport. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin The implementation blockers from the previous review look addressed, and the new Parakeet batch tests pass together ( by AI for @beastoin |
PyTorch's CudaDeviceProperties uses `total_memory`, not `total_mem`. This typo crashed model loading on GPU after BF16 conversion succeeded. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin PR_APPROVED_LGTM. No issues found in this re-review; the requested Parakeet unit suite passes locally: by AI for @beastoin |
|
TESTS_APPROVED Test results:
Ready from test coverage. by AI for @beastoin |
CP9 Live Test Evidence — Parakeet Batch Perf (image: 94ec53f)Environment: dev GKE, parakeet-pool (g2-standard-8, L4 GPU, 28.9GB RAM) CP9A: Health + Single Request
CP9B: Concurrent Load Test
Crash Root Causes Found & Fixed
All CheckpointsCP0-CP9B: ✅ All passed by AI for @beastoin |
PyTorch 2.12 + CUDA 13.x has a CachingHostAllocator bug that causes cudaErrorIllegalAddress under batched inference. The NGC nemo:26.02 container (PyTorch 2.6 + CUDA 12.8) is battle-tested at 43 RPS on L4 with zero crashes. NeMo fork is installed as --no-deps --force-reinstall overlay on top of the container's NeMo to preserve CUDA/PyTorch alignment. Co-Authored-By: zen Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
@beastoin PR_APPROVED_LGTM. No issues found on re-review: the Dockerfile is rebased to by AI for @beastoin |
|
TESTS_APPROVED Test results:
Coverage verified for Ready for review. by AI for @beastoin |
pyannote.audio was upgrading torchaudio past NGC's compatible version, causing undefined symbol: torch_library_impl at container startup. Lock torch/torchaudio to NGC 26.02 versions via constraints file. Co-Authored-By: Claude Opus 4.6 <[email protected]>
NGC containers install torch/torchaudio via conda, not pip, so pip freeze doesn't list them. Use Python imports to get versions. Co-Authored-By: Claude Opus 4.6 <[email protected]>
NGC 26.02 ships torch 2.6 but no torchaudio. pyannote.audio pulls latest torchaudio (ABI-incompatible with torch 2.6). Fix: install torchaudio 2.6.x first, then pin both via constraints file. Co-Authored-By: Claude Opus 4.6 <[email protected]>
NGC torch is 2.10.0+cu128 (custom CUDA build). Installing torchaudio without --no-deps pulls in standard PyPI torch, overwriting the NGC build. Fix: install torchaudio --no-deps, then let pip see the existing torch satisfies pyannote.audio requirements naturally. Co-Authored-By: Claude Opus 4.6 <[email protected]>
pyannote.audio transitive deps (torchmetrics -> torchvision) upgraded torchvision to CUDA 13.0, conflicting with NGC's CUDA 12.8 torch. Pre-install both torchaudio and torchvision with --no-deps. Co-Authored-By: Claude Opus 4.6 <[email protected]>
torchvision uses 0.x versioning (not 2.x like torch). Switch to constraint-based pinning: extract installed versions, strip +cu128 local tags, and pass as constraints to prevent pyannote.audio deps from upgrading any torch ecosystem package. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Standard PyPI torchaudio is ABI-incompatible with NGC's custom torch. Use PyTorch's cu128 wheel index for matching builds. Install pyannote and its torch-dependent deps with --no-deps to prevent any torch ecosystem upgrades. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…eels NGC's custom torch build is ABI-incompatible with every torchaudio wheel (PyPI, cu128 index). NeMo imports torchaudio at module level via squim metrics, but parakeet never calls those functions. Stub satisfies the import chain without loading C extensions. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Replace streamsPerPod with requestsPerPod (combined streams + batch) to cover all GPU-bound traffic, not just WebSocket streams - Add parakeet_batch_pending_requests Prometheus gauge for queue depth monitoring (batch.pending_requests visibility for ops) - Dev values: add targetGPUUtilization: 70 to match prod - Manager decision: start at 25 concurrent requests, adjust down based on production p99 monitoring (zen recommended 16 for p99 < 2s SLA) Co-Authored-By: Claude Opus 4.6 <[email protected]>
Add PARAKEET_TORCH_COMPILE=true and PARAKEET_CUDA_GRAPHS=true to both prod and dev parakeet Helm values so the Helm upgrade sets image + probes + HPA + env vars in one rollout (per mon's deploy plan). Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
lgtm |
Deploy Monitor — T+20m Checkpoint (prod)Pod: 1/1 Running, 0 restarts, 35m age Status: PASS ✅ Next checkpoint: T+30m by AI for @beastoin |
## What changed and why Parakeet could keep a replica Ready after a fatal CUDA stream-capture error, so one poisoned process served only HTTP 500s indefinitely. This disables CUDA graph decoding when batch and streaming inference share the GPU, makes fatal accelerator errors poison the authoritative GPU worker state, and lets health probes recycle the replica. It also adds per-pod black-hole and fatal-CUDA alerts and fixes the dashboard to use Parakeet's `success`/`error` status labels. ## Product invariants affected none ## How it was verified - Recycled the original poisoned production pod and observed its replacement become Ready and serve successful transcriptions with no CUDA/HTTP 500 errors. - The live Prometheus form of the new black-hole query then detected the same failure recurring on that replacement. Production logs confirmed the exact `cudaErrorStreamCaptureUnsupported` failure. - Completed a rolling Parakeet-only configuration change to `PARAKEET_CUDA_GRAPHS=false` while the healthy sibling continued serving. Both replacement replicas became Ready with healthy `/health` responses and served 211 real transcriptions immediately after rollout (209 + 2), with zero HTTP 500s and zero fatal-CUDA signatures. - `backend/.venv/bin/python -m pytest -q backend/tests/unit/test_parakeet_gpu_worker.py backend/tests/unit/test_parakeet_endpoints.py backend/tests/unit/test_parakeet_stream_session.py backend/tests/unit/test_parakeet_helm_contract.py backend/tests/unit/test_monitoring_alert_rule_contract.py` — 149 passed. - `make runtime-image-source-closure` — all 10 registered runtime-image contracts passed. - `PYTHON=.venv/bin/python bash test-preflight.sh` — 18 checks passed, 0 failed. - `OMI_PR_BODY_FILE=/tmp/parakeet-pr-body.md make preflight` — all 20 diff-scoped checks passed; the bounded pre-push typecheck, unit-test, OpenAPI, and formatting gate also passed. - The repository-wide `PYTHON=.venv/bin/python bash test.sh` run reached and passed every Parakeet test, but was not green due unrelated current-tree failures in desktop release contracts and fast-unit timing guards; one unrelated memory-adapter process was interrupted after remaining idle on a live Google connection for more than eight minutes. - GitHub's backend unit, image-smoke, source-closure, API-contract, sync-gauntlet, and listen-gauntlet checks passed. The broad hermetic E2E job twice reproduced the current unrelated `TestSurfaceDefaultAccessMatrix...[agent_tools]` failure (113 passed, 3 skipped); the identical failure is present on PR #10400, whose diff only touches sync cloud-task files. The real CUDA concurrency trigger was not reproduced on a development GPU. Its production recurrence and removal by the live configuration rollout provide the runtime evidence. ## Tests - `test_exact_incident_error_transitions_real_worker_health_to_unhealthy` covers the incident error flowing through the real worker state into HTTP 503 health. - `TestGPUWorkerFatalCUDA` covers fatal classification, fail-closed admission, callback idempotency, thread shutdown, ordinary error recovery, and OOM separation. - RNNT tests cover fatal startup/decode propagation and the nonfatal fallback path. - Helm tests require CUDA graphs off plus HTTP readiness/liveness probes. - Monitoring contract tests require both per-pod alerts and application status labels. ## Failure class (fixes) Failure-Class: new ## Failure-class transition narrative (only when needed) This adds `FC-poisoned-accelerator-readiness`. Violated contract: a serving GPU process whose CUDA context is unsafe must not remain Ready or accept more inference. The canonical guard is the GPU worker's fatal state, surfaced through `/health` to Kubernetes readiness/liveness, with CUDA graphs prohibited when batch and streaming inference share a process. Evidence is the 2026-07-23 production incident, its recurrence on replacement pod `prod-omi-parakeet-6cf8b5ccbf-d5786`, and the enabling configuration from PR #7938. ## New guards (only when adding a check or ratchet) The Helm and monitoring contract checks would have caught the 2026-07-23 Parakeet incident configuration and observability gaps. This is not a shared primitive because CUDA-context validity and Parakeet's mixed batch/streaming decoder configuration are specific to this GPU service. ## Scoped cleanups (optional) The Parakeet dashboard's HTTP-style `status=~"[45].."` filters were changed to the application's actual `status="error"` label.
Record the serving-readiness contract and canonical worker/probe boundary exposed by the 2026-07-23 incident. PR BasedHardware#7938 is the enabling configuration this guard would have caught.
Record the serving-readiness contract and canonical worker/probe boundary exposed by the 2026-07-23 incident. PR BasedHardware#7938 is the enabling configuration this guard would have caught.
## What changed and why Parakeet could keep a replica Ready after a fatal CUDA stream-capture error, so one poisoned process served only HTTP 500s indefinitely. This disables CUDA graph decoding when batch and streaming inference share the GPU, makes fatal accelerator errors poison the authoritative GPU worker state, and lets health probes recycle the replica. It also adds per-pod black-hole and fatal-CUDA alerts and fixes the dashboard to use Parakeet's `success`/`error` status labels. ## Product invariants affected none ## How it was verified - Recycled the original poisoned production pod and observed its replacement become Ready and serve successful transcriptions with no CUDA/HTTP 500 errors. - The live Prometheus form of the new black-hole query then detected the same failure recurring on that replacement. Production logs confirmed the exact `cudaErrorStreamCaptureUnsupported` failure. - Completed a rolling Parakeet-only configuration change to `PARAKEET_CUDA_GRAPHS=false` while the healthy sibling continued serving. Both replacement replicas became Ready with healthy `/health` responses and served 211 real transcriptions immediately after rollout (209 + 2), with zero HTTP 500s and zero fatal-CUDA signatures. - `backend/.venv/bin/python -m pytest -q backend/tests/unit/test_parakeet_gpu_worker.py backend/tests/unit/test_parakeet_endpoints.py backend/tests/unit/test_parakeet_stream_session.py backend/tests/unit/test_parakeet_helm_contract.py backend/tests/unit/test_monitoring_alert_rule_contract.py` — 149 passed. - `make runtime-image-source-closure` — all 10 registered runtime-image contracts passed. - `PYTHON=.venv/bin/python bash test-preflight.sh` — 18 checks passed, 0 failed. - `OMI_PR_BODY_FILE=/tmp/parakeet-pr-body.md make preflight` — all 20 diff-scoped checks passed; the bounded pre-push typecheck, unit-test, OpenAPI, and formatting gate also passed. - The repository-wide `PYTHON=.venv/bin/python bash test.sh` run reached and passed every Parakeet test, but was not green due unrelated current-tree failures in desktop release contracts and fast-unit timing guards; one unrelated memory-adapter process was interrupted after remaining idle on a live Google connection for more than eight minutes. - GitHub's backend unit, image-smoke, source-closure, API-contract, sync-gauntlet, and listen-gauntlet checks passed. The broad hermetic E2E job twice reproduced the current unrelated `TestSurfaceDefaultAccessMatrix...[agent_tools]` failure (113 passed, 3 skipped); the identical failure is present on PR BasedHardware#10400, whose diff only touches sync cloud-task files. The real CUDA concurrency trigger was not reproduced on a development GPU. Its production recurrence and removal by the live configuration rollout provide the runtime evidence. ## Tests - `test_exact_incident_error_transitions_real_worker_health_to_unhealthy` covers the incident error flowing through the real worker state into HTTP 503 health. - `TestGPUWorkerFatalCUDA` covers fatal classification, fail-closed admission, callback idempotency, thread shutdown, ordinary error recovery, and OOM separation. - RNNT tests cover fatal startup/decode propagation and the nonfatal fallback path. - Helm tests require CUDA graphs off plus HTTP readiness/liveness probes. - Monitoring contract tests require both per-pod alerts and application status labels. ## Failure class (fixes) Failure-Class: new ## Failure-class transition narrative (only when needed) This adds `FC-poisoned-accelerator-readiness`. Violated contract: a serving GPU process whose CUDA context is unsafe must not remain Ready or accept more inference. The canonical guard is the GPU worker's fatal state, surfaced through `/health` to Kubernetes readiness/liveness, with CUDA graphs prohibited when batch and streaming inference share a process. Evidence is the 2026-07-23 production incident, its recurrence on replacement pod `prod-omi-parakeet-6cf8b5ccbf-d5786`, and the enabling configuration from PR BasedHardware#7938. ## New guards (only when adding a check or ratchet) The Helm and monitoring contract checks would have caught the 2026-07-23 Parakeet incident configuration and observability gaps. This is not a shared primitive because CUDA-context validity and Parakeet's mixed batch/streaming decoder configuration are specific to this GPU service. ## Scoped cleanups (optional) The Parakeet dashboard's HTTP-style `status=~"[45].."` filters were changed to the application's actual `status="error"` label.
Summary
Apply optimizations from beastoin/NeMo#2 (zen's thread-safety + high-perf batch ASR server) to Omi's parakeet batch transcription service.
Before: Single-threaded
model.transcribe()on the request thread, 1 request at a time, no batching, no GC management — prone to CUDA segfaults under concurrent load (2,103 500-errors in prod incident). Effective throughput: ~1 RPS.After: Dedicated GPU worker thread + dynamic batching engine — benchmarked at 35.92 RPS sustained on L4 (Omi end-to-end, ~36x throughput vs old code) with zero failures across 5,134 requests. Zero quality regression — Parakeet avg WER 0.5% (vs Deepgram 0.7%).
Throughput comparison
Benchmark results (zen, 2026-06-15)
Latency vs concurrency (zen benchmark data)
Transcription quality benchmark (hiro, 2026-06-15)
WER comparison on 12 LibriSpeech test-clean samples against dev GKE pod (L4, torch.compile + cuda_graphs ON):
Conclusion: Zero quality regression from batch engine + torch.compile + NGC Dockerfile changes.
HPA scaling policy (prod)
requestsPerPod: 25batch.pending_requeststargetGPUUtilization: 70Changes
New files
gpu_worker.py— Dedicated GPU inference thread with managed GC, torch.compile, CUDA optimizations, BF16 support, shutdown drainbatch_engine.py— Dynamic batching: accumulates requests, flushes by batch size (32) or timer (2ms), backpressure at queue depth limitModified files
main.py—gc.disable()at module level, lifespan context manager, non-blocking model load, ThreadPoolExecutors for diarization and file I/O, 503 readiness gating on /health,parakeet_batch_pending_requestsPrometheus gaugetranscribe.py— GPU worker routing (set_gpu_worker,_transcribe_from_gpu_result,_transcribe_via_gpu_worker), NIM fallback preserveddev_omi_parakeet_values.yaml/prod_omi_parakeet_values.yaml— readiness/startup probes changed from TCP to httpGet /health (K8s readiness gating); HPA updated: streamsPerPod → requestsPerPod: 25README.md— Documented all new env vars and endpointsTest files (78 tests total)
test_parakeet_gpu_worker.py— 27 tests: lifecycle, sync/async submit, queue full, extract results, GC, drain, safe set helpers, BF16 loadingtest_parakeet_batch_engine.py— 15 tests: flush logic, queue full, file cleanup, error propagation, metrics, shutdown cancellationtest_parakeet_batch_routing.py— 11 tests: GPU result routing, set_gpu_worker, v2 with gpu_result, diarize=false, NIM routingtest_parakeet_endpoints.py— 11 tests: /health (503/200/NIM), /batch/metrics, v1/v2 transcribe (batch, queue full, loading)Key optimizations
gc.disable()+gc.collect(0)per batchtorch.compile+cuda_graphscudnn.benchmark=TrueNGC Dockerfile (8-iteration fix)
Resolved NGC NeMo container's custom PyTorch ABI incompatibility:
import torchaudiochain without pulling ABI-incompatible PyPI wheelsReview cycle changes
stop()cancels them alongside the timer loop, catches CancelledError to resolve batch futuresmodel.to(torch.bfloat16)called when CUDA BF16 supported)Closes #7936
by AI for @beastoin