Speech & audio · Kubernetes

Running Nemotron diarization on a GPU that scales to zero

A how-to: package NVIDIA’s Nemotron 3 Diarization as a service on a Kubernetes GPU node that costs nothing when idle, and join its speakers to your transcript.

Diarization answers “who spoke when?”. We run NVIDIA’s Nemotron 3 Diarization as a small HTTP service on a single T4 GPU that scales to zero when nobody is using it, next to a separate speech recognition (ASR) service. This is how to build the same thing: the image, the service, the Kubernetes deployment, the scale-to-zero wiring, and the client that wakes it up and joins speakers to words.

Why Nemotron: on a thirty-second, two-person recording it put every word with the right speaker. Sortformer managed 93%; NeMo’s clustering diarizer managed 20% with no hint, because it found twelve speakers, and 92% when told there were at most four. That is one clip, not an evaluation, but it shows how much the defaults around a model matter.

One clip · 30 seconds · two speakers

A useful clue, a very small sample

Nemotron100%
Sortformer93%
Clustering · max 492%
Clustering · unhinted20%
Reported word-to-speaker correctness in the reference caller’s comment. These are recorded results, not a new benchmark or a measure of transcription accuracy.

What you need

  • A Kubernetes cluster with a GPU node group that can scale to zero. We use EKS with cluster-autoscaler and an on-demand g4dn.xlarge (one T4, 16 GB) node group.
  • The NVIDIA device plugin, so pods can request nvidia.com/gpu.
  • KEDA for scaling the Deployment to and from zero.
  • A Redis-compatible store for the wake signal. We use Dragonfly, which we already run as a queue.
  • A container registry, and a Hugging Face account if you want an authenticated download.

Nothing here is EKS-specific apart from the node-group tags in step 4.

1. Build an image that starts without the internet

Bake the weights into the image, check them, and run the model once on CPU before the build is allowed to finish. A trimmed Dockerfile:

FROM pytorch/pytorch:2.12.0-cuda12.6-cudnn9-runtime
WORKDIR /app
COPY requirements.txt constraints.txt ./
RUN pip install --no-cache-dir -c constraints.txt -r requirements.txt

# Weights in their own layer, so editing the app does not re-download ~575 MB.
COPY models.py prefetch.py ./
RUN --mount=type=secret,id=hf,required=false 
    HF_TOKEN=$(cat /run/secrets/hf 2>/dev/null || true) python -m prefetch

COPY . .
RUN python -m smoke          # load every model and run it on CPU
ENV HF_HUB_OFFLINE=1
CMD ["uvicorn", "app:app", "--host=0.0.0.0", "--port=8000", "--workers=1"]

prefetch.py downloads config.json, processor_config.json and model.safetensors from a pinned revision with hf_hub_download(…, revision=…, local_dir=…), then checks the checkpoint’s SHA-256 and exits if it differs. Pin the libraries too: we use torch==2.12.0, transformers==5.18.0 and, for the clustering fallback, nemo_toolkit[asr]==3.0.0. It is also worth a build step that writes and decodes a short MP3 and FLAC with soundfile, so a missing codec fails the build, not the first customer request.

HF_HUB_OFFLINE=1 goes after the prefetch and smoke test, so at runtime nothing can reach for the network. That trades a download at startup for a bigger image pull, which matters for cold starts (step 5).

2. Serve the model

Nemotron 3 loads through Transformers, not NeMo. Our NeMo version could not load it, and the Transformers classes work as documented on the model card. The T4 has no bfloat16, so it runs in float32:

from transformers import AutoModelForAudioFrameClassification, AutoProcessor

processor = AutoProcessor.from_pretrained(
    path, streaming_modes={"offline_style": (340, 40)}, streaming_mode="offline_style")
model = AutoModelForAudioFrameClassification.from_pretrained(
    path, torch_dtype=torch.float32).to("cuda")

The model takes 16 kHz mono audio, turns it into mel-spectrogram features every 10 ms and outputs, for each frame, the probability that each of eight speaker channels is active, shaped [T, 8] (architecture). Long audio goes through in chunks, with a speaker cache carrying identities from one chunk to the next. This is the loop from the Transformers docs, with the two fixes we needed:

duration = len(audio) / rate
# The first chunk must be full length, so pad short clips with silence…
if (short := processor.num_samples_first_audio_chunk - len(audio)) > 0:
    audio = np.pad(audio, (0, short))

cache, logits = None, []
with torch.inference_mode():
    for inputs in chunks(processor, audio, rate):   # first, middle and last chunks
        out = model(**inputs.to(model.device, dtype=model.dtype), speaker_cache=cache)
        logits.append(out.logits)
        cache = out.speaker_cache

segments = processor.extract_speaker_dict(torch.cat(logits, dim=1))[0]
turns = [
    {"start": float(s["Start"]), "end": min(float(s["End"]), duration),   # …and clip back
     "speaker": f"speaker_{int(s['Speaker'])}"}
    for s in segments
]

The service is a FastAPI app with POST /diarize and an unauthenticated GET /health. The request takes a URL to the audio rather than an upload, plus optional counts:

class DiarizeRequest(BaseModel):
    audio_url: str
    num_speakers: int | None = None
    min_speakers: int | None = None
    max_speakers: int | None = None
    pipeline: Literal["clustering", "sortformer", "nemotron3"] = "clustering"

and returns turns:

{"turns": [{"start": 0.0, "end": 3.2, "speaker": "speaker_0"}], "num_speakers": 2, "pipeline": "nemotron3"}

Three details are worth copying:

  • One worker and a lock. Run a single Uvicorn worker and put inference behind a threading.Lock, so two processes never each load the models onto one GPU. NeMo’s clustering diarizer also keeps per-run state on the instance.
  • Load at startup. Load models in FastAPI’s lifespan handler, before the app serves anything, so /health only answers once the model is on the GPU.
  • Validate counts loudly. Nemotron has eight output channels and ignores count hints. We reject num_speakers or min_speakers above eight with a 400 that says to use clustering, and for max_speakers above eight, or any count at all, return a warning in an X-NeMo-Warning header instead of silently ignoring it.

Notice the default pipeline is clustering. Every client should send the pipeline it wants.

3. Deploy it

The Deployment asks for one GPU, runs on the GPU nodes only, and starts at zero replicas:

spec:
  replicas: 0
  strategy: { type: Recreate }       # never two pods wanting the one GPU
  template:
    spec:
      nodeSelector: { workload: gpu-inference }
      tolerations: [{ key: nvidia.com/gpu, operator: Exists, effect: NoSchedule }]
      containers:
        - name: diarizer
          resources:
            requests: { cpu: "2", memory: 8Gi, ephemeral-storage: 10Gi, nvidia.com/gpu: "1" }
            limits:   { memory: 12Gi, ephemeral-storage: 20Gi, nvidia.com/gpu: "1" }
          startupProbe:   { httpGet: { path: /health, port: 8000 }, initialDelaySeconds: 20, periodSeconds: 5, failureThreshold: 60 }
          readinessProbe: { httpGet: { path: /health, port: 8000 }, periodSeconds: 10, failureThreshold: 3 }
          livenessProbe:  { httpGet: { path: /health, port: 8000 }, periodSeconds: 30, failureThreshold: 4 }

Host memory and disk are sized for long audio, not the model. The service decodes and resamples in 60-second blocks but keeps the whole waveform: three hours of 16 kHz mono is about 0.7 GB as float32, before the model’s working memory and the downloaded file. Downloads and decoding happen before the inference lock, so concurrent requests stack up there; one GPU per pod is a scheduling choice, not admission control. The startup probe allows about five minutes for imports and model loading, which covers the container but not provisioning a node or pulling the image.

4. Scale the pods and the nodes to zero

Two separate things have to reach zero. KEDA scales the Deployment, watching the length of a list in Redis:

apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: diarizer }
spec:
  scaleTargetRef: { name: diarizer }
  minReplicaCount: 0
  maxReplicaCount: 1
  pollingInterval: 15
  cooldownPeriod: 600
  triggers:
    - type: redis
      metadata: { address: redis.example.svc:6379, listName: diarizer-wake, listLength: "2" }
      authenticationRef: { name: redis-auth }   # a TriggerAuthentication with the password

Our store accepts unauthenticated connections from inside the VPC, so ours has no authenticationRef; yours should, unless you have the same network boundary.

Then the node has to go too, or you pay for an idle T4. With cluster-autoscaler and an EKS managed node group, set minSize: 0, give the group the GPU taint and labels, and tag the Auto Scaling group so the autoscaler knows a node from this group would satisfy a pending pod even when none exist:

k8s.io/cluster-autoscaler/node-template/label/workload: gpu-inference
k8s.io/cluster-autoscaler/node-template/taint/nvidia.com/gpu: "true:NoSchedule"
k8s.io/cluster-autoscaler/node-template/resources/nvidia.com/gpu: "1"

Without those tags a pod can sit Pending forever on a group with zero nodes. If the group is shared with another GPU service, as ours is, zero replicas here does not mean zero instances. We moved to on-demand after spot g4dn capacity was repeatedly unavailable.

5. Wake it from the client

At zero replicas nothing is listening, so the client signals demand first. The service never reads the list; it only exists for KEDA to count. The contract we use:

redis-cli LREM diarizer-wake 0 "$JOB_ID"   # no duplicates from retries
redis-cli LPUSH diarizer-wake "$JOB_ID"
redis-cli EXPIRE diarizer-wake 600         # a crashed client cannot keep the GPU on

Then poll GET /health until it answers, with a deadline: a cold start (node boot, image pull, model load) takes about three to five minutes for us. Send the request, and remove the entry with LREM when the job is done. For jobs longer than the expiry, refresh it while the job runs. A stale entry keeps the pod warm for nothing; one that expires mid-request lets it scale down too early. After the list empties, the 600-second cooldown keeps the pod warm for the next burst.

The caller’s lifecycle contract

A sleeping service needs more than a POST

  1. 01 / SIGNALPush a sentinel

    The caller writes to the Redis-compatible Dragonfly list.

  2. 02 / WAKEKEDA requests a pod

    15-second polling; zero to one replica. Node capacity must also be available.

  3. 03 / WAITModels become ready

    Image pull, imports and model loading come before /health succeeds.

  4. 04 / WORKCall the HTTP API

    ASR and diarization run independently; the caller merges their results.

  5. 05 / IDLEKeep warm, then stop

    After the trigger becomes inactive, a 600-second cooldown precedes scale-down.

The Redis item signals demand; audio travels through HTTP. This diagram describes the intended orchestration, not functionality built into the reference CLI.

6. Join speakers to words

Send the same audio to ASR and the diarizer in parallel and join the results on time. ASR returns words with start and end times; the diarizer returns turns. Each word goes to the turn it overlaps most, or the nearest turn if none overlaps:

starts = np.array([t["start"] for t in turns]); ends = np.array([t["end"] for t in turns])
for w in words:
    overlap = np.minimum(ends, w["end"]) - np.maximum(starts, w["start"])
    i = int(np.argmax(overlap))
    if overlap[i] <= 0:
        i = int(np.argmin(np.maximum(starts - w["end"], w["start"] - ends)))
    w["speaker"] = turns[i]["speaker"]

Then relabel speakers A, B, C in order of first appearance and group consecutive words from the same speaker into utterances.

Illustrative timing · not the evaluation recording

The word belongs to the turn it overlaps most

Assigning a word across a speaker boundarySpeaker A ends at 1.5 seconds and speaker B begins there. A word from 1.4 to 1.8 seconds overlaps A by 0.1 seconds and B by 0.3 seconds, so it is assigned to B.Speaker ASpeaker BASR word1.0 s1.5 s2.0 s2.5 s3.0 s0.1 s with A / 0.3 s with B → B
Both outputs share the audio’s clock. If a word overlaps no turn, the reference caller uses the nearest turn. This rule still produces just one speaker label per word.

Keeping the two services apart means you can change the ASR model while holding speakers fixed, or the reverse. The join is a heuristic: a word that crosses a turn boundary gets one label, two people talking over one word cannot both have it, and timestamp errors become attribution errors without either service failing.

Choosing speaker counts

Eight is the size of Nemotron’s output, not a target: a ninth voice has no channel, and chunking lengthens a session without adding channels (output specification). Treat eight as the limit for one recording and use clustering above it, with a hint. For clustering, num_speakers is an exact count and max_speakers an upper bound; “two speakers” is much stronger information than “no more than four”, and no hint at all is what produced twelve speakers in the example above.

Before you rely on it

  • Time each stage of a cold start separately: node, image pull, model load.
  • Measure warm inference time and peak host memory on your longest recordings.
  • Test a job that outlasts the wake entry’s expiry, a failed request, and two callers at once.
  • Compare speaker accuracy on longer recordings, more speakers and unknown counts, with the ASR output held fixed and the count assumptions written down for each run.