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.
A useful clue, a very small sample
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
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
/healthonly answers once the model is on the GPU. - Validate counts loudly. Nemotron has eight output channels and ignores count hints. We
reject
num_speakersormin_speakersabove eight with a 400 that says to use clustering, and formax_speakersabove eight, or any count at all, return a warning in anX-NeMo-Warningheader 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.