Repository navigation
feat(parakeet): Prometheus metrics + autoscaling Helm chart - #7685
Conversation
Add prometheus_client with gauges and histograms for autoscaling: - parakeet_active_streams: active /v3/stream WebSocket connections - parakeet_active_batch_requests: active /v1 and /v2 batch requests - parakeet_request_duration_seconds: request latency histogram - parakeet_stream_duration_seconds: WebSocket session duration Metrics exposed at /metrics endpoint via make_asgi_app(). Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
…raping Exposes metrics port (default 9091) as a separate service so Prometheus can discover and scrape parakeet_* metrics independently from the main HTTP service. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Prometheus Operator discovers and scrapes parakeet metrics at /metrics on the metrics port with configurable interval (default 15s). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…rics Defines adapter rules that translate Prometheus metrics into K8s custom metrics API for HPA consumption: - parakeet_active_streams (avg per pod) - parakeet_active_batch_requests (avg per pod) - parakeet_active_requests_total (combined streams + batch) - parakeet_request_latency_p99 (histogram quantile) - parakeet_gpu_utilization (DCGM avg over 1min) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…util Replace basic CPU/latency HPA with custom metrics from Prometheus: - streamsPerPod: scale when avg active streams per pod exceeds threshold - requestsPerPod: scale on total active requests (streams + batch) - targetGPUUtilization: scale on DCGM GPU utilization percentage - requestLatencyP99: retain latency-based scaling as option Add metrics port to deployment spec. Add metrics config section to values.yaml with ServiceMonitor and adapter toggles. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Dev: metrics enabled, streamsPerPod=30, maxReplicas=1 (dev constraint), ingress paths for /v2/transcribe and /v3/stream added. Prod: metrics enabled, streamsPerPod=60, targetGPUUtilization=70, maxReplicas=10, aggressive scale-up (2 pods/60s), ingress paths for /v2/transcribe and /v3/stream added. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR adds Prometheus metrics instrumentation to the Parakeet ASR service and wires up a full Helm autoscaling stack (ServiceMonitor, prometheus-adapter ConfigMap, upgraded HPA) modeled after the Deepgram self-hosted chart.
Confidence Score: 3/5The autoscaling pipeline as deployed will be silently inert: Prometheus cannot scrape the metrics, so the HPA custom metrics will never trigger. Two bugs need to be fixed before this provides any production value. The entire observability and autoscaling pipeline depends on Prometheus successfully scraping the metrics endpoint. Because make_asgi_app() is served on the main app port but the Service targets port 9091, every scrape fails silently — no metrics reach Prometheus, no custom metrics reach the HPA, and the scaling logic never fires. The second bug (wrong seriesQuery for the combined metric) would further cause under-scaling once the port issue is fixed. The Python instrumentation itself and the HPA/values structure are correct; these are targeted fixes rather than a broad rewrite. backend/charts/parakeet/templates/service-metrics.yaml (targetPort must match the port FastAPI actually listens on) and backend/charts/parakeet/templates/prometheus-adapter-config.yaml (seriesQuery for parakeet_active_requests_total should cover batch requests, not only streams). Important Files Changed
Sequence DiagramsequenceDiagram
participant Client
participant Parakeet as Parakeet Pod (main port)
participant MetricsSvc as service-metrics (port 9091)
participant Prometheus
participant Adapter as prometheus-adapter
participant HPA
Client->>Parakeet: POST /v1/transcribe or /v2/transcribe
Parakeet->>Parakeet: ACTIVE_BATCH.inc() / REQUEST_DURATION.observe()
Client->>Parakeet: WS /v3/stream
Parakeet->>Parakeet: ACTIVE_STREAMS.inc() / STREAM_DURATION.observe()
Note over MetricsSvc,Parakeet: Port mismatch: metrics served on main port, not 9091
Prometheus->>MetricsSvc: Scrape :9091/metrics (via ServiceMonitor)
MetricsSvc-->>Prometheus: connection refused (wrong port)
Note over Adapter,Prometheus: If scraping fixed:
Prometheus->>Adapter: Custom metrics API query
Adapter->>HPA: parakeet_active_streams, parakeet_gpu_utilization, etc.
HPA->>HPA: Compute desiredReplicas
HPA-->>Parakeet: Scale deployment
Reviews (1): Last reviewed commit: "feat(parakeet/chart): enable metrics and..." | Re-trigger Greptile |
| ) | ||
|
|
||
| app = FastAPI() | ||
| app.mount("/metrics", make_asgi_app()) |
There was a problem hiding this comment.
Metrics endpoint served on wrong port
make_asgi_app() is mounted on the FastAPI app, which means /metrics is served on the same port as the main application (the container's primary HTTP port, e.g. 80). However, service-metrics.yaml creates a Service with targetPort: 9091, and deployment.yaml declares containerPort: 9091. No process actually binds to port 9091, so every Prometheus scrape from the ServiceMonitor will fail with "connection refused."
The fix is one of: (a) start a separate HTTP server on 9091 via prometheus_client.start_http_server(9091) inside startup_warmup, or (b) update service-metrics.yaml to use targetPort: {{ .Values.service.port }} (the main app port) so the existing /metrics mount is reachable.
| - seriesQuery: 'parakeet_active_streams{namespace!="",pod!=""}' | ||
| resources: | ||
| overrides: | ||
| namespace: {resource: "namespace"} | ||
| pod: {resource: "pod"} | ||
| name: | ||
| as: "parakeet_active_requests_total" | ||
| metricsQuery: 'avg(parakeet_active_streams{<<.LabelMatchers>>}) + avg(parakeet_active_batch_requests{<<.LabelMatchers>>})' |
There was a problem hiding this comment.
Wrong
seriesQuery for parakeet_active_requests_total
The rule for parakeet_active_requests_total (the streams + batch combined metric) uses seriesQuery: 'parakeet_active_streams{...}'. The prometheus-adapter uses seriesQuery to discover which pods to expose the metric for. When a pod has zero active streams but nonzero batch requests (a pure-batch workload), it won't appear in the streams series, so the adapter skips it entirely and returns 0 for that pod. The HPA would then under-count active load and fail to scale out. The seriesQuery should reference parakeet_active_batch_requests (or a union of both series).
| ) | ||
|
|
||
| app = FastAPI() | ||
| app.mount("/metrics", make_asgi_app()) |
There was a problem hiding this comment.
/metrics exposed unauthenticated on the main app port
make_asgi_app() is mounted directly on the FastAPI application, placing /metrics on the same port as the API. Although none of the named ingress path entries include /metrics, a misconfigured or catch-all ingress rule would expose Prometheus metric data (active connection counts, latency histograms) publicly without authentication. Consider gating the endpoint to cluster-internal traffic only or at minimum checking that the ingress rules are strict enough in both environment overlays.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| - port: {{ .Values.metrics.port }} | ||
| targetPort: {{ .Values.metrics.port }} | ||
| protocol: TCP | ||
| name: metrics |
There was a problem hiding this comment.
The
targetPort is hardcoded to metrics.port (9091), but FastAPI is served on service.port (default 80). Unless a separate process is bound to 9091, Prometheus scrapes will be refused. Align the target port with the actual port serving /metrics on the container.
| - port: {{ .Values.metrics.port }} | |
| targetPort: {{ .Values.metrics.port }} | |
| protocol: TCP | |
| name: metrics | |
| - port: {{ .Values.metrics.port }} | |
| targetPort: {{ .Values.service.port }} | |
| protocol: TCP | |
| name: metrics |
GPU work during WebSocket teardown (final transcription) was not counted in the active streams gauge because dec() happened before flush(). Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ules for global metrics CODEx review findings: - HPA: switch streamsPerPod/requestsPerPod from External to Pods type (per-pod metrics must use Pods, not External) - Adapter: use 'sum(...) by (<<.GroupBy>>)' to return one value per pod (adapter contract: one series per requested object) - Adapter: move latency/GPU to externalRules section (global metrics) - HPA: store requestLatencyP99 as K8s Quantity string directly Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ate port Prometheus metrics are mounted on the main FastAPI app at /metrics (port 8080), not on a separate server. Fix the metrics service targetPort to match the main service port. Remove the separate metrics containerPort from the deployment spec. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Review Response (Round 1)Finding 1: Metrics port mismatch — FIXEDMetrics are mounted on the main FastAPI app at Finding 2: ConfigMap not auto-mounted — ACKNOWLEDGEDThe adapter ConfigMap is a reference config that ops merges into the cluster's prometheus-adapter. This is the same pattern used for DG self-hosted (adapter rules are in the chart values, not auto-mounted). Documented in the ConfigMap comment. Finding 3: GPU metric too broad — ACKNOWLEDGEDDCGM labels vary by cluster config. Adding a container-specific filter requires knowing the exact DCGM exporter label scheme. For now, Commit
by AI for @beastoin |
…us discovery Prometheus Operator's serviceMonitorSelector requires a matching release label. Without it, the ServiceMonitor is ignored and metrics are never scraped. Found during CP9B dev cluster testing. Co-Authored-By: Claude Opus 4.6 <[email protected]>
CP9 Changed-Path Coverage Checklist
L1 SynthesisP1-P5 proven on dev GKE GPU pod (L4). All 4 Prometheus metric families present at L2 SynthesisP1-P7 proven end-to-end. ServiceMonitor→Prometheus pipeline working: Prometheus target UP, metrics queryable via PromQL ( by AI for @beastoin |
All Checkpoints Passed — Ready for Merge
PR is ready for human merge approval. by AI for @beastoin |
|
lgtm |
…ployment, benchmarks (#7653) * Add ParakeetPrerecordedProvider for batch STT path Implements the PrerecordedSTTProvider ABC for Parakeet/Nemotron ASR, enabling STT_PRERECORDED_MODEL=parakeet for all 9 batch callsites. Includes transcribe_url (download-then-transcribe), transcribe_bytes (PCM-to-WAV wrapping), embedding-based diarization, and factory routing. Closes #7651 Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add parakeet to streaming STT factory routing Enables STT_SERVICE_MODELS=parakeet as a first-class routing option in get_stt_service_for_language() instead of opt-in only. Requires HOSTED_PARAKEET_API_URL to be set. Closes #7651 Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add unit tests for ParakeetPrerecordedProvider 25 tests covering: factory routing, transcribe_bytes/url, output format, diarization clustering, retry/error handling, return_language fallback, and postprocess_words() compatibility. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add parakeet prerecorded tests to test.sh Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix reviewer feedback: diarization state, WAV slicing, download streaming 1. Make diarization centroids/counts per-call instead of process-global to prevent concurrent request contamination 2. Always use WAV parsing for segment slicing since audio_bytes is always WAV format at the diarization point 3. Stream URL downloads with early Content-Length rejection to prevent buffering oversized responses in memory Co-Authored-By: Claude Opus 4.6 <[email protected]> * Update tests for streaming download and per-call diarization state Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add streaming overflow and factory routing tests per tester feedback Adds 3 tests: streamed download overflow without Content-Length header, streaming factory routing with parakeet in STT_SERVICE_MODELS, and fallback when HOSTED_PARAKEET_API_URL is unset. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add NIM inference mode to Parakeet transcribe service Supports PARAKEET_INFERENCE_MODE=nim for TensorRT-optimized NIM sidecar inference alongside the existing raw NeMo mode. NIM mode proxies to a NIM_INFERENCE_URL endpoint without loading NeMo/torch into the gateway. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add NIM-based Dockerfile for TensorRT-optimized Parakeet deployment Lightweight FastAPI auth gateway that proxies to a NIM sidecar container. No NeMo/torch/CUDA dependencies — just httpx for NIM communication. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add PARAKEET_MODEL and PARAKEET_INFERENCE_MODE to dev Helm values Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add PARAKEET_MODEL and PARAKEET_INFERENCE_MODE to prod Helm values Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add Parakeet vs Deepgram pre-recorded WER benchmark LibriSpeech test-clean methodology matching kelvin's PR #7142 framework. Measures WER, latency, punctuation quality for both providers. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add Parakeet vs Deepgram streaming WER benchmark Real-time pace (3200 bytes/100ms) matching Omi wearable output. Measures WER, first-segment latency, connect time, segment count. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix NIM API endpoint to /v1/audio/transcriptions with language field Per NVIDIA ASR NIM docs, the correct endpoint is /v1/audio/transcriptions (not /v1/transcribe) and requires a language multipart field. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Clarify NIM Dockerfile as auth gateway with sidecar deployment docs Documents the 2-container sidecar pattern, Helm changes needed for NIM mode, NGC registry setup, and local dev docker-compose workflow. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix streaming benchmark WAV parsing to use wave.open instead of byte offset ffmpeg-generated WAVs can contain extra chunks beyond the 44-byte header, so use wave.open().readframes() for reliable PCM extraction. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add unit tests for Parakeet NIM inference mode 3 tests: correct API endpoint + language field, text-only fallback segment generation, and error propagation from NIM service. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add parakeet NIM tests to test.sh Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add /v2/transcribe endpoint with diarization support V2 returns segments with speaker labels. Accepts diarize form param. Falls back to SPEAKER_0 when diarization model is not loaded. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add v2 transcription with NeMo and NIM diarization support NeMo v2: uses NeuralDiarizer to assign speaker labels per segment. NIM v2: passes diarize=true to NIM API, reads speaker from response. Model loaded lazily via PARAKEET_DIARIZATION_MODEL env var. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Use Parakeet v2 endpoint for diarization with v1 fallback Tries /v2/transcribe with server-side diarization when diarize=True. Falls back to /v1/transcribe + client-side embedding clustering on 404. Controlled by PARAKEET_USE_V2 env var (default: enabled). Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add multi-language + code-switching benchmark for Parakeet 8 single-language (es/fr/de/pt/ja/zh/hi/ko) + 3 code-switching samples. Compares WER per language against Deepgram nova-3. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add DER (Diarization Error Rate) benchmark for Parakeet Frame-level DER with 0.25s collar, greedy speaker mapping. Uses L2 multi-speaker interleaved LibriSpeech audio (2-3 speakers). Reports miss/FA/confusion breakdown per sample. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add Parakeet to kelvin's pyannote DER benchmark script Third provider in the DER comparison loop. Uses build_hypothesis_from_words (same word-level format as Deepgram). Auto-enabled when HOSTED_PARAKEET_API_URL set. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Move embedding diarization to parakeet server v2 endpoint Server-side speaker clustering using HOSTED_SPEAKER_EMBEDDING_API_URL (same technique that achieved 9.2% DER in benchmarks). Replaces the NeMo NeuralDiarizer approach that failed to load. Each segment's audio is extracted, embedded via the diarizer service, and clustered with cosine distance. Works with both NeMo and NIM inference modes. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add httpx and scipy to parakeet requirements for v2 diarization Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add numpy and scipy to NIM Dockerfile for v2 diarization Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add langdetect language detection to parakeet v2 endpoint V2 response now includes detected_language field using the same langdetect library the backend uses for translation. Resolves the "no native language detection" limitation. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Use detected_language from parakeet v2 response for return_language Instead of falling back to explicit language or 'en', reads the detected_language field from the v2 transcription response. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add langdetect to parakeet requirements and NIM Dockerfile Co-Authored-By: Claude Opus 4.6 <[email protected]> * Try multiple NeMo model classes for Nemotron compatibility ASRModel.from_pretrained fails on Nemotron 3.5 with abstract method error. Now tries EncDecRNNTBPEModel, EncDecCTCModelBPE, and EncDecMultiTaskModel before falling back to ASRModel. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add language-based fallback for Parakeet streaming routing Parakeet only supports 25 EU languages. Unsupported languages (CJK, Hindi, Korean, etc.) now fall through to the next provider in STT_SERVICE_MODELS (typically Deepgram). Prevents romanization of non-Latin scripts. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add language-based fallback for Parakeet batch routing Unsupported languages fall back to Deepgram instead of sending CJK/Hindi/Korean to Parakeet where they get romanized. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Update tests for language-based provider fallback Tests verify CJK/Hindi/Korean fall back to Deepgram when STT_PRERECORDED_MODEL=parakeet or STT_SERVICE_MODELS=parakeet. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix parakeet_languages to match official model card Per NVIDIA parakeet-tdt-0.6b-v3 HuggingFace model card: removed unsupported ca/no/sr, added supported el/lv/mt/ru. 26 languages total (25 EU + multi). Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add HOSTED_PARAKEET_API_URL to dev backend-listen Helm values Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add HOSTED_PARAKEET_API_URL to prod backend-listen Helm values Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add HOSTED_SPEAKER_EMBEDDING_API_URL to dev parakeet Helm values Required for v2 server-side diarization. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add HOSTED_SPEAKER_EMBEDDING_API_URL to prod parakeet Helm values Required for v2 server-side diarization. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add StreamSession for /v3/stream with VAD + ASR + diarization WebSocket streaming handler: Silero VAD filters silence, NeMo ASR transcribes speech windows, embedding clustering assigns speakers. Session-persistent centroids for stable SPEAKER_N labels across the entire connection lifetime. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add /v3/stream WebSocket endpoint to Parakeet service Accepts PCM16 chunks, runs server-side VAD + diarization, returns segments with {text, start, end, speaker, detected_language} in real-time. Auth via query param to match WebSocket limitations. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add ParakeetWebSocketSocket for true streaming via /v3/stream Replaces HTTP-per-window approach with WebSocket relay. Sends raw PCM chunks to Parakeet service, receives speaker-labeled segments. Controlled by PARAKEET_USE_STREAM_WS env var (default: enabled). Falls back to ParakeetStreamingSocket (HTTP) when disabled. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix reviewer feedback on /v3/stream WebSocket endpoint 1. Bounded ASR executor (max_workers=1) instead of default pool 2. VAD model loading with lock, torch imported at module level 3. All imports at top level (no in-function imports) 4. Receive timeout (30s) on WebSocket to prevent idle resource hold 5. EOS "finalize" signal before close to flush tail segments 6. Auth via headers instead of query string (no secret in logs) 7. Cleanup in finally protected against flush exceptions 8. Embedding calls offloaded to executor (non-blocking) Co-Authored-By: Claude Opus 4.6 <[email protected]> * Remove query-param auth fallback from /v3/stream Header-only auth — prevents secret leaking in access logs. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Remove HTTP fallback — streaming always uses /v3/stream WebSocket No env var toggle. process_audio_parakeet always connects to the /v3/stream WebSocket endpoint with server-side VAD + diarization. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Change max speech window from 15s to 5s for faster segment delivery Closer to Deepgram's response cadence. Configurable via PARAKEET_MAX_WINDOW_S env var. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix /v3/stream auth — accept WebSocket before checking credentials FastAPI rejects with 403 if close() is called before accept(). Accept first, then check auth and close with 1008 if unauthorized. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix import rule violations — all imports at module top level Moved nemo_asr, httpx, io, wave, numpy, scipy, langdetect to top-level imports in transcribe.py and stream_handler.py. Conditional imports use try/except at module level. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Remove remaining in-function import aliases streaming.py: removed redundant websockets/json aliases (already imported at top level). x_benchmark_parakeet_der.py: moved BytesIO to top level. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Use in-memory numpy arrays for streaming ASR instead of temp files Passes PCM bytes directly as float32 numpy array to NeMo transcribe(), skipping the temp file write/read/delete cycle. Falls back to file-based for NIM mode. Batch path (transcribe.py) unchanged — still file-based since it receives uploaded files. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix stale _json reference to json.JSONDecodeError Left over from removed alias. Would crash on malformed WS messages. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add built-in speaker embedding to Parakeet streaming service Loads pyannote/wespeaker-voxceleb-resnet34-LM directly on GPU — eliminates HTTP round-trip to diarizer service per segment (~200ms saved). Falls back to HTTP if pyannote not available. All imports at module top level. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix websockets kwarg: extra_headers for websockets==12.0 compat websockets 12.0 uses extra_headers, not additional_headers. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Handle websockets 12.x and 16.x header kwarg difference 12.x uses extra_headers, 14+ uses additional_headers. Detect by major version to support both pinned and upgraded versions. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Implement chunked streaming with left context for lower WER Replaces fixed 5s window approach with RNNT-style chunked streaming: - 2s chunks with 10s left context (transcribes left+current, emits delta) - VAD used for endpointing only (when to finalize utterance), not as the ASR window boundary - Text deduplication via prefix/overlap matching between chunks - Full utterance re-transcription on silence endpointing for final quality - Configurable via PARAKEET_CHUNK_S and PARAKEET_LEFT_CONTEXT_S Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix chunk boundary trigger — only transcribe at chunk intervals Track _last_chunk_offset to prevent ASR call on every VAD frame after buffer exceeds chunk size. Resets on speech start/end. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Lower VAD threshold from 0.5 to 0.3 to prevent speech truncation Root cause of 10% streaming WER: VAD at 0.5 classified quieter speech passages as silence, dropping 36-51% of audio before ASR. Batch (no VAD) gets 0% WER on the same audio. Configurable via PARAKEET_VAD_THRESHOLD env var. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix VAD gating: all audio goes to ASR, VAD only for endpointing Previously VAD gated which audio reached ASR — quieter speech was dropped (36-51% audio loss). Now all PCM is buffered and transcribed in chunks. VAD only controls when to finalize an utterance (silence endpointing). This ensures 100% audio coverage while still detecting speech boundaries for segment emission. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Simplify streaming: accumulate until VAD endpointing, transcribe full utterance Remove mid-speech chunking with text deduplication — it produced 18% WER due to imperfect overlap matching. Now: accumulate all audio during speech, transcribe the complete utterance on silence endpointing. This matches batch quality (0.1% WER) since NeMo sees the full context in one shot. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add per-session VAD tuning via WebSocket query params vad_threshold and hangover_s can be passed as query params to /v3/stream for runtime tuning without pod restarts. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Separate batch and streaming ASR models PARAKEET_MODEL for batch (/v1, /v2 — TDT, best accuracy offline) PARAKEET_STREAM_MODEL for streaming (/v3 — RNNT, supports true streaming) Defaults to same model. When PARAKEET_STREAM_MODEL differs, loads both models on GPU. Streaming handler uses _stream_model. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Use _stream_model for streaming ASR instead of _batch_model Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add PARAKEET_STREAM_MODEL to dev and prod Helm values Co-Authored-By: Claude Opus 4.6 <[email protected]> * Require explicit PARAKEET_STREAM_MODEL — no silent fallback to batch Streaming model must be set via env var. Logs warning if unset and uses batch model as temporary fallback until configured. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fail hard if PARAKEET_STREAM_MODEL not set — no fallback Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add StreamSession unit tests for /v3/stream handler 11 tests: feed silence/speech, flush pending/empty/short, cleanup, speaker assignment fallback, VAD param overrides. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add test_parakeet_stream_session to test.sh Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix streaming WER: use file-based transcription instead of numpy NeMo produces worse transcriptions when given raw numpy arrays vs WAV files (30% WER vs 0% on same audio). Root cause: NeMo's file reader applies normalization/preprocessing that the numpy path skips. Always use temp file path for consistent quality. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Implement NeMo RNNT chunked streaming decoder with preserved state Replaces batch-style model.transcribe() per utterance with NeMo's RNNT streaming API: StreamingBatchedAudioBuffer + decoding_computer with prev_batched_state carried across chunks. This gives the RNNT model full context continuity instead of losing it at VAD boundaries. Falls back to file-based batch transcription if NeMo streaming utilities are unavailable. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add RNNT streaming decoder unit tests Tests: drain_streaming_asr, delta text emission, batch fallback skip. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Check for RNNT decoding_computer before enabling streaming decoder TDT models don't have decoding.decoding.decoding_computer — the RNNT streaming path hung when tried on TDT. Now checks model has the required attribute before enabling, falls back to batch cleanly. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Load models via CPU→BF16→CUDA to avoid OOM on RNNT 1.1b Loads on CPU first (avoids 2x GPU peak from state_dict + weights), converts to BF16 (halves weight memory 4.4GB → 2.2GB), then moves to GPU. Fits RNNT 1.1b on L4 (24GB VRAM). Controlled by PARAKEET_BF16 env var (default: enabled). Per geni's root cause analysis. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Separate torch and torchaudio imports — torchaudio may not be installed torchaudio import failure was dragging torch down, disabling VAD and RNNT streaming decoder even when torch is available. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix RNNT streaming decoder: unpack and CUDA graph issues 1. decoding_computer returns variable-length tuple — unpack safely 2. Disable use_cuda_graph_decoder (incompatible with BF16 tensors, causes CUDA illegal memory access crash) Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix parakeet websocket startup drain * Add parakeet websocket startup regression test * Fix L2 relay: finish() queues finalize instead of hard-closing finish() was setting _closed=True immediately, killing the send loop before queued audio reached the server. Now queues finalize signal instead. Send loop sends "finalize" to server, waits 5s for final segments, then exits. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add RNNT decoder warmup at service startup + fix L2 relay 1. warmup_rnnt_decoder() runs a dummy 3s chunk through the RNNT decoder at startup to pre-compile CUDA kernels (eliminates 15-20s cold-start latency on first connection) 2. finish() queues finalize instead of hard-closing (allows queued audio to be sent before teardown) 3. Debug logging for WS connection success/failure Co-Authored-By: Claude Opus 4.6 <[email protected]> * Two-phase shutdown: drain STT before closing WS on supervisor exit When supervisor exits (e.g., lifecycle_done), drain the STT socket first to capture final segments, then set websocket_active=False. Previously the WS was closed immediately, dropping segments in flight. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Set PARAKEET_STREAM_MODEL to RNNT 1.1b in Helm values Dual model: TDT 0.6b (batch) + RNNT 1.1b (streaming). Requires g2-standard-8 with 20Gi+ memory limit and BF16 loading. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix 12 production quality issues from CODEx final review 1. Helm memory: 4-6Gi → 8-20Gi for dual-model RNNT+TDT 2. Batch language fallback: get_prerecorded_provider now checks _parakeet_languages before routing to Parakeet 3. RNNT buffer leak: clear _asr_audio_buf when streaming fails 4. Idle WS timeout: close /v3/stream after 10 idle timeouts 5. GatedSTTSocket unwrap: two-phase shutdown now always unwraps 6. Queue full logging: warn instead of silent drop 7. Send-after-finalize blocked: _finalized flag prevents data loss 8. PCM retry: pass encoding=None on retry to prevent double-wrap 9. VAD error logging: debug log instead of silent swallow 10. Streaming WS send error: log QueueFull instead of silent pass Co-Authored-By: Claude Opus 4.6 <[email protected]> * Add GitHub Actions workflow for Parakeet GKE deployment Same pattern as gcp_diarizer.yml. Builds Docker image, deploys via Helm to dev or prod GKE. Memory (20Gi) and startup probe (failureThreshold=60) baked into Helm values. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Increase startup probe failureThreshold to 60 in Helm values Dual model load + RNNT warmup takes ~5 min. Default 30 was too low. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(parakeet): Prometheus metrics + autoscaling Helm chart (#7685) * feat(parakeet): add Prometheus metrics instrumentation Add prometheus_client with gauges and histograms for autoscaling: - parakeet_active_streams: active /v3/stream WebSocket connections - parakeet_active_batch_requests: active /v1 and /v2 batch requests - parakeet_request_duration_seconds: request latency histogram - parakeet_stream_duration_seconds: WebSocket session duration Metrics exposed at /metrics endpoint via make_asgi_app(). Co-Authored-By: Claude Opus 4.6 <[email protected]> * chore(parakeet): add prometheus-client dependency Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(parakeet/chart): add metrics ClusterIP service for Prometheus scraping Exposes metrics port (default 9091) as a separate service so Prometheus can discover and scrape parakeet_* metrics independently from the main HTTP service. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(parakeet/chart): add ServiceMonitor for Prometheus auto-discovery Prometheus Operator discovers and scrapes parakeet metrics at /metrics on the metrics port with configurable interval (default 15s). Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(parakeet/chart): add prometheus-adapter rules for custom HPA metrics Defines adapter rules that translate Prometheus metrics into K8s custom metrics API for HPA consumption: - parakeet_active_streams (avg per pod) - parakeet_active_batch_requests (avg per pod) - parakeet_active_requests_total (combined streams + batch) - parakeet_request_latency_p99 (histogram quantile) - parakeet_gpu_utilization (DCGM avg over 1min) Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(parakeet/chart): upgrade HPA to scale on active streams and GPU util Replace basic CPU/latency HPA with custom metrics from Prometheus: - streamsPerPod: scale when avg active streams per pod exceeds threshold - requestsPerPod: scale on total active requests (streams + batch) - targetGPUUtilization: scale on DCGM GPU utilization percentage - requestLatencyP99: retain latency-based scaling as option Add metrics port to deployment spec. Add metrics config section to values.yaml with ServiceMonitor and adapter toggles. Co-Authored-By: Claude Opus 4.6 <[email protected]> * feat(parakeet/chart): enable metrics and autoscaling in dev/prod values Dev: metrics enabled, streamsPerPod=30, maxReplicas=1 (dev constraint), ingress paths for /v2/transcribe and /v3/stream added. Prod: metrics enabled, streamsPerPod=60, targetGPUUtilization=70, maxReplicas=10, aggressive scale-up (2 pods/60s), ingress paths for /v2/transcribe and /v3/stream added. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(parakeet): move ACTIVE_STREAMS.dec() after session.flush() GPU work during WebSocket teardown (final transcription) was not counted in the active streams gauge because dec() happened before flush(). Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(parakeet/chart): use Pods metric type for per-pod HPA + externalRules for global metrics CODEx review findings: - HPA: switch streamsPerPod/requestsPerPod from External to Pods type (per-pod metrics must use Pods, not External) - Adapter: use 'sum(...) by (<<.GroupBy>>)' to return one value per pod (adapter contract: one series per requested object) - Adapter: move latency/GPU to externalRules section (global metrics) - HPA: store requestLatencyP99 as K8s Quantity string directly Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(parakeet/chart): metrics service targets main app port, not separate port Prometheus metrics are mounted on the main FastAPI app at /metrics (port 8080), not on a separate server. Fix the metrics service targetPort to match the main service port. Remove the separate metrics containerPort from the deployment spec. Co-Authored-By: Claude Opus 4.6 <[email protected]> * fix(parakeet/chart): add release label to ServiceMonitor for Prometheus discovery Prometheus Operator's serviceMonitorSelector requires a matching release label. Without it, the ServiceMonitor is ignored and metrics are never scraped. Found during CP9B dev cluster testing. Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]> * Add AGC normalization, max speech duration (5s), and Helm config - AGC normalizes quiet Omi BLE mic audio to 80% peak before VAD - MAX_SPEECH_DURATION_S forces segment emission on continuous speech - PARAKEET_MAX_SPEECH_S=5 in dev and prod Helm values for real-time feel - RNNT decoder state stays continuous across forced emissions Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix word truncation on forced 5s emission boundary When MAX_SPEECH_DURATION_S forces a segment emission, the RNNT decoder may be mid-word. Hold back the trailing word and include it in the next emission to prevent truncated output like "diar" instead of "diarization". Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix word truncation: pad partial RNNT chunks before forced emission The RNNT decoder processes audio in 2s chunks. At the 5s forced emission boundary, up to 2s of audio remains unprocessed, causing mid-word text truncation ("speaker"→"spe"). Fix: pad partial chunks with silence to a complete chunk size and drain through the decoder before emitting. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Fix word truncation on ALL emission paths, not just forced 5s Silence-based and post-drain emissions were calling _transcribe_utterance() without trim_trailing_word=True or pad_partial drain. The RNNT decoder has ~2s right-context latency, so the last word is often incomplete at any emission boundary. Now all three paths drain partial chunks and trim. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Cache RNNT model initialization — only run change_decoding_strategy once The RNNT decoder's _ensure_initialized() called model.change_decoding_strategy() on every new WebSocket session (~12s each time). This blocked feed() long enough to cause 0 transcripts on most connections. Now the expensive model config (freeze, eval, decoding strategy, preprocessor) runs once at startup warmup and is cached via _rnnt_model_initialized flag. Per-session init only creates the StreamingBatchedAudioBuffer and context sizes (~instant). Co-Authored-By: Claude Opus 4.6 <[email protected]> * Remove parakeet auth + fix CODEx issues (ingress, README, Dockerfile.nim) 1. Remove ENCRYPTION_SECRET auth from parakeet service — runs behind internal LB only, auth adds complexity without security value. Removed from main.py endpoints, backend WS relay, and pre_recorded provider. Updated test to verify no auth header sent. 2. Update README.md — was stale (only documented /v1, said no diarization). Now covers all 3 endpoints, env vars, and deployment. 3. Fix Dockerfile.nim — missing stream_handler.py COPY (would fail at startup since main.py imports it). 4. Ingress paths already had /v2 and /v3 from earlier commit — verified. 52/52 tests pass. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Remove redundant two-phase STT drain on supervisor exit The receive_data() finally block (line 2646-2675) already handles EOS drain: flushes remaining audio, unwraps GatedSTTSocket, calls drain_and_close(), and only then sets websocket_active=False. The duplicate drain at the supervisor exit level was redundant. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Remove debug PCM capture code from transcribe.py PARAKEET_DEBUG_CAPTURE wav writer was a dev-time debugging tool for capturing decoded PCM to /tmp. Not needed in production. Co-Authored-By: Claude Opus 4.6 <[email protected]> * Support comma-separated STT_PRERECORDED_MODEL with language fallback STT_PRERECORDED_MODEL now works like STT_SERVICE_MODELS — iterates comma-separated models and picks the first that supports the language. e.g. "parakeet,dg-nova-3" uses Parakeet for EU languages and falls back to Deepgram nova-3 for CJK/Hindi/Korean. Both get_prerecorded_service() and get_prerecorded_provider() updated. Co-Authored-By: Claude Opus 4.6 <[email protected]> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
Summary
Adds production-grade autoscaling infrastructure to the Parakeet ASR service, modeled after the Deepgram self-hosted chart pattern. Built on top of #7653 (hiro's Parakeet implementation).
Relates to #7651
Changes
Prometheus Metrics Instrumentation (
backend/parakeet/main.py)parakeet_active_streams(Gauge) — active /v3/stream WebSocket connections (dec after flush so GPU teardown work is counted)parakeet_active_batch_requests(Gauge) — active /v1 and /v2 batch requestsparakeet_request_duration_seconds(Histogram) — request latency by endpointparakeet_stream_duration_seconds(Histogram) — WebSocket session duration/metricsviaprometheus_client.make_asgi_app()Helm Chart Templates (new)
service-metrics.yaml— ClusterIP service on port 9091 for Prometheus scrapingservicemonitor.yaml— ServiceMonitor for Prometheus Operator auto-discoveryprometheus-adapter-config.yaml— adapter rules for custom + external metrics:rulessection: per-pod metrics (parakeet_active_streams,parakeet_active_batch_requests,parakeet_active_requests_total) usingsum(...) by (<<.GroupBy>>)— returns one value per podexternalRulessection: global metrics (parakeet_request_latency_p99,parakeet_gpu_utilization) — not pod-associatedHelm Chart Updates (existing)
deployment.yaml— added metrics port to container spechpa.yaml— uses correct K8s metric types:Podstype forstreamsPerPodandrequestsPerPod(per-pod metrics)Externaltype fortargetGPUUtilizationandrequestLatencyP99(global metrics)values.yaml— addedmetricsconfig section (port, ServiceMonitor, adapter toggles)Environment Values
streamsPerPod=30, maxReplicas=1streamsPerPod=60,targetGPUUtilization=70, maxReplicas=10, aggressive scale-up (2 pods/60s)Autoscaling Pipeline
Review Cycle Changes
by (<<.GroupBy>>)for per-pod grouping. MovedACTIVE_STREAMS.dec()aftersession.flush(). Separated adapter rules intorules(custom) andexternalRules(external).Risks / Edge Cases
Prerequisites
by AI for @beastoin