davanstrien HF Staff commited on
Commit
01eff4c
·
verified ·
1 Parent(s): a53c76f

Sync from GitHub via hub-sync

Browse files
Files changed (3) hide show
  1. README.md +18 -0
  2. nemotron-transcribe-image.sh +60 -0
  3. nemotron-transcribe.py +682 -0
README.md CHANGED
@@ -60,6 +60,7 @@ Audio already on your machine? Mount the folder directly — `-v ./audio:/input`
60
  | `easytranscriber-transcribe.py` | Cohere Transcribe 2B (default) or Whisper variants | [easytranscriber](https://github.com/kb-labb/easytranscriber) | JSON word timestamps (+ optional `.txt` / `.srt`) | 42.9x RT (L4) |
61
  | `moss-transcribe-diarize.py` | [MOSS-Transcribe-Diarize](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) (0.9B) | transformers (remote code) | JSON speaker segments `{start, end, speaker, text}` (+ optional `.txt` / `.srt`) | 3.2x RT (A10G, 74-min file) |
62
  | `moss-transcribe-diarize-server.py` | [MOSS-Transcribe-Diarize](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) (0.9B) | in-job sgl-omni server | JSON speaker segments (+ optional `.txt`) | 47.4x RT aggregate (A100, 6 streams) |
 
63
 
64
  **`cohere-transcribe.py`** (recommended for plain text) — uses `model.transcribe()` with automatic long-form chunking, overlap, and reassembly. Stable dependencies.
65
 
@@ -75,6 +76,23 @@ Audio already on your machine? Mount the folder directly — `-v ./audio:/input`
75
 
76
  **`moss-transcribe-diarize-server.py`** — same model at **~12x the throughput** for many files: serves it behind sglang-omni inside the job and posts files concurrently (continuous batching). Splits long tapes into ≤55-min clips to fit the context window (speaker labels reset between clips, recorded as `part` on each segment) and automatically continues from the last timestamp when the model stops early, reporting `coverage_s` per file. Needs `a100-large` — 24 GB cards OOM on long-tape KV. The `hf jobs run` command lives in the script docstring (server + driver in one job).
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  #### Options — `cohere-transcribe.py` / `cohere-transcribe-vllm.py`
79
 
80
  | Flag | Default | Description |
 
60
  | `easytranscriber-transcribe.py` | Cohere Transcribe 2B (default) or Whisper variants | [easytranscriber](https://github.com/kb-labb/easytranscriber) | JSON word timestamps (+ optional `.txt` / `.srt`) | 42.9x RT (L4) |
61
  | `moss-transcribe-diarize.py` | [MOSS-Transcribe-Diarize](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) (0.9B) | transformers (remote code) | JSON speaker segments `{start, end, speaker, text}` (+ optional `.txt` / `.srt`) | 3.2x RT (A10G, 74-min file) |
62
  | `moss-transcribe-diarize-server.py` | [MOSS-Transcribe-Diarize](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) (0.9B) | in-job sgl-omni server | JSON speaker segments (+ optional `.txt`) | 47.4x RT aggregate (A100, 6 streams) |
63
+ | `nemotron-transcribe.py` | [Nemotron 3.5 Transcribe](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B) (30B MoE, ~4B active, 40 languages) | in-job vLLM 0.32 + NeMo Speech server | `.txt` (+ JSON word timestamps, speakers and diarization with `--timestamps`) | 116x RT aggregate (RTX PRO 6000, 10 files) + ~8 min fixed setup |
64
 
65
  **`cohere-transcribe.py`** (recommended for plain text) — uses `model.transcribe()` with automatic long-form chunking, overlap, and reassembly. Stable dependencies.
66
 
 
76
 
77
  **`moss-transcribe-diarize-server.py`** — same model at **~12x the throughput** for many files: serves it behind sglang-omni inside the job and posts files concurrently (continuous batching). Splits long tapes into ≤55-min clips to fit the context window (speaker labels reset between clips, recorded as `part` on each segment) and automatically continues from the last timestamp when the model stops early, reporting `coverage_s` per file. Needs `a100-large` — 24 GB cards OOM on long-tape KV. The `hf jobs run` command lives in the script docstring (server + driver in one job).
78
 
79
+ **`nemotron-transcribe.py`** — when you want **punctuated text, speaker tags and word timestamps from one model, in 40 languages** (speaker tags in 13, up to 8 speakers), and have enough audio to amortise a fixed ~8 min setup. The model only serves on vLLM 0.32.0 with the NeMo Speech plugin, so the script starts that server inside the job and posts files concurrently: 10 half-hour 1940s radio episodes (4.9 h) took 2.5 min once the server was up, a $0.48 job on `rtx-pro-6000`. The `[tool.hf-jobs]` header sets the flavor and a prebuilt image (`cr.hf.co/davanstrien/nemotron-transcribe`, built in a Job by `nemotron-transcribe-image.sh`) that pins NeMo Speech to one commit and carries FlashInfer kernels already compiled for that GPU. `--image vllm/vllm-openai:v0.32.0` makes the script install the stack at runtime instead (~2 min slower; it downloads FlashInfer's precompiled kernels). Prompts are the model card's presets (`--style verbatim|clean|speakers`, or `--prompt` with `Context terms: <names>` for jargon), and the card's generation-loop guardrail is applied to every transcript. `--timestamps` adds a JSON per file with word start/end times, speaker tags and diarization segments, from the CTC head bundled in the checkpoint. Files over 55 min are split into equal parts, and speaker tags reset between parts. On the same 10 episodes, after Whisper-style text normalisation, its words differ from Cohere's by 7.0% (Granite vs Cohere: 7.7%; Nemotron vs Granite: 8.4%); there is no ground truth for these episodes, so this measures agreement, not accuracy. Once loaded it matches Cohere's speed (116x vs 120x RT on the same audio), but the fixed setup makes a 5-hour batch cost $0.48 against Cohere's $0.16 and Granite's $0.20, so reach for it when you need the speaker tags, timestamps or languages. The vLLM integration is NVIDIA's development path; the card says it is about 2x slower than their NIM.
80
+
81
+ #### Options — `nemotron-transcribe.py`
82
+
83
+ | Flag | Default | Description |
84
+ |------|---------|-------------|
85
+ | `--style` | `verbatim` | Model-card prompt preset: `verbatim` (fillers kept), `clean` (fillers dropped) or `speakers` (`<spk:N>` tags) |
86
+ | `--prompt` | none | Custom user prompt (overrides `--style`), e.g. `Transcribe with punctuation and capitalization. Context terms: <names>.` |
87
+ | `--timestamps` | off | Also write JSON with word timestamps, speaker tags and diarization segments (uses the `speakers` prompt) |
88
+ | `--concurrency` | 16 | Files in flight against the server |
89
+ | `--part-minutes` | 55 | Split longer audio into equal parts of at most this length, up to 60 (the model is trained on recordings up to 1 h); speaker tags reset between parts |
90
+ | `--server` | `http://127.0.0.1:8000` | Use a server already running there instead of starting one |
91
+ | `--nemo-ref` | the image's commit (`7b05f096`) | NeMo Speech ref to install when the image has no prebuilt stack; `main` follows the model card |
92
+ | `--workdir` | `/opt/nemotron-transcribe` (prebuilt image), else `/tmp/nemotron-transcribe` | Where the serving stack and checkpoint live (the prebuilt image's stack is used when present) |
93
+ | `--request-timeout` | 3600 | Per-request timeout in seconds |
94
+ | `--max-files` | all | Limit files to process (for testing) |
95
+
96
  #### Options — `cohere-transcribe.py` / `cohere-transcribe-vllm.py`
97
 
98
  | Flag | Default | Description |
nemotron-transcribe-image.sh ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Build and push the prebuilt image for nemotron-transcribe.py, inside an HF Job.
3
+ #
4
+ # The recipe installs vLLM 0.32.0 + NeMo Speech main at runtime and FlashInfer
5
+ # JIT-builds kernels on first start. This script does all of that once, on the
6
+ # target GPU, and pushes the result as one layer on top of the vLLM image:
7
+ #
8
+ # - /opt/nemotron-transcribe/nemo-speech (source + locked venv + kernels)
9
+ # - FlashInfer JIT cache and vLLM torch.compile cache (warm for the flavor
10
+ # the build ran on; other GPUs rebuild their kernels on first start)
11
+ #
12
+ # The model checkpoint is NOT baked in (it downloads in ~35 s on Jobs).
13
+ # No Docker daemon is needed: `crane append` adds the layer and pushes.
14
+ #
15
+ # Run (the container repo must exist; HF_TOKEN needs write on its org):
16
+ #
17
+ # hf jobs run --flavor rtx-pro-6000 -s HF_TOKEN --timeout 1h \
18
+ # -v hf://datasets/uv-scripts/transcription:/recipe:ro \
19
+ # vllm/vllm-openai:v0.32.0 -- \
20
+ # bash /recipe/nemotron-transcribe-image.sh cr.hf.co/uv-scripts/nemotron-transcribe
21
+ #
22
+ # Optional env: NEMO_REF (NeMo Speech branch/tag/commit, default main:
23
+ # a new image pins a new commit; update DEFAULT_NEMO_REF in the recipe to match) and
24
+ # TAG_SUFFIX (appended to the tag, to keep an earlier build of the same commit).
25
+ set -euo pipefail
26
+
27
+ REPO="${1:?usage: nemotron-transcribe-image.sh <cr.hf.co/namespace/name>}"
28
+ RECIPE_DIR="$(cd "$(dirname "$0")" && pwd)"
29
+ BASE="vllm/vllm-openai:v0.32.0"
30
+ WORKDIR=/opt/nemotron-transcribe
31
+
32
+ pip install -q uv
33
+
34
+ # 1. Install + warm up: run the recipe on a short silent clip.
35
+ mkdir -p /tmp/warmup-in /tmp/warmup-out
36
+ python3 -c "import wave; w = wave.open('/tmp/warmup-in/silence.wav', 'wb'); w.setnchannels(1); w.setsampwidth(2); w.setframerate(16000); w.writeframes(b'\0' * 64000); w.close()"
37
+ uv run "$RECIPE_DIR/nemotron-transcribe.py" /tmp/warmup-in /tmp/warmup-out \
38
+ --workdir "$WORKDIR" --nemo-ref "${NEMO_REF:-main}"
39
+
40
+ NEMO_SHA="$(cat "$WORKDIR/nemo-speech/.nemo-ref")"
41
+ TAG="v0.32.0-nemo-${NEMO_SHA:0:12}${TAG_SUFFIX:-}"
42
+
43
+ # 2. One layer: the serving stack and the warm caches, not the checkpoint.
44
+ # A cache directory may not exist (e.g. every kernel came precompiled).
45
+ paths=("${WORKDIR#/}")
46
+ for cache in root/.cache/flashinfer root/.cache/vllm; do
47
+ if [ -d "/$cache" ]; then paths+=("$cache"); fi
48
+ done
49
+ tar -C / -cf /tmp/layer.tar \
50
+ --exclude="${WORKDIR#/}/model" --exclude="${WORKDIR#/}/nemo-speech.tar.gz" \
51
+ "${paths[@]}"
52
+ ls -lh /tmp/layer.tar
53
+
54
+ # 3. Append it to the base image and push (also tag :latest).
55
+ curl -sL https://github.com/google/go-containerregistry/releases/download/v0.22.1/go-containerregistry_Linux_x86_64.tar.gz \
56
+ | tar -xz -C /usr/local/bin crane
57
+ crane auth login cr.hf.co -u "$(python3 -c "from huggingface_hub import whoami; print(whoami()['name'])" 2>/dev/null || echo user)" -p "$HF_TOKEN"
58
+ crane append --platform linux/amd64 -b "$BASE" -f /tmp/layer.tar -t "$REPO:$TAG"
59
+ crane tag "$REPO:$TAG" latest
60
+ echo "PUSHED $REPO:$TAG"
nemotron-transcribe.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = [
4
+ # "huggingface-hub",
5
+ # "requests",
6
+ # "librosa",
7
+ # "soundfile",
8
+ # ]
9
+ #
10
+ # [tool.hf-jobs]
11
+ # image = "cr.hf.co/davanstrien/nemotron-transcribe:v0.32.0-nemo-7b05f096d54d"
12
+ # flavor = "rtx-pro-6000"
13
+ # secrets = ["HF_TOKEN"]
14
+ # ///
15
+
16
+ """
17
+ Transcribe audio with NVIDIA Nemotron 3.5 Transcribe via an in-job vLLM server.
18
+
19
+ Serves nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B behind vLLM + the NeMo
20
+ Speech plugin inside the job and posts files concurrently, so continuous
21
+ batching decodes many recordings at once.
22
+
23
+ The model only runs on vLLM 0.32.0 + NeMo Speech main (no stable wheel ships
24
+ the plugin). The header's image has that serving stack prebuilt (NeMo Speech
25
+ pinned to commit 7b05f096d54d, FlashInfer kernels warm for rtx-pro-6000; built
26
+ by nemotron-transcribe-image.sh). On any other image the script builds the
27
+ stack itself first: it downloads the NeMo Speech source, installs it with the
28
+ model card's locked `uv sync` plus FlashInfer's precompiled kernels. Either way
29
+ it downloads the checkpoint, starts `vllm serve` with the card's single-GPU
30
+ flags as a subprocess, splits audio longer than the model's one-hour limit,
31
+ posts files concurrently, and writes .txt (+ JSON with word timestamps and
32
+ speakers when --timestamps is set). If a server already answers on --server,
33
+ the setup is skipped.
34
+
35
+ Run on HF Jobs (image, flavor and HF_TOKEN secret come from the
36
+ [tool.hf-jobs] header above; needs `hf` CLI 1.32+):
37
+
38
+ hf jobs uv run --detach --timeout 4h \\
39
+ -v hf://buckets/user/audio-files:/input:ro \\
40
+ -v hf://buckets/user/transcripts:/output \\
41
+ https://huggingface.co/datasets/uv-scripts/transcription/raw/main/nemotron-transcribe.py \\
42
+ /input /output
43
+
44
+ Setup is a fixed ~8 min per job on the prebuilt image (2 min image pull,
45
+ 35 s checkpoint download, ~4 min engine warmup); ~10 min with
46
+ `--image vllm/vllm-openai:v0.32.0`, which installs the stack at runtime. Batch
47
+ many files into one job: 10 half-hour episodes (4.9 h) transcribed in 2.5 min
48
+ (116x realtime) once the server was up, for a $0.48 job.
49
+
50
+ The server flags are the model card's single-GPU settings (written for an
51
+ H100 80 GB; Jobs has no H100, so rtx-pro-6000 96 GB is the default here).
52
+ The timestamp middleware finds the checkpoint's bundled CTC head only in a
53
+ local model directory, which is why the checkpoint is downloaded first and
54
+ served by path.
55
+
56
+ Input: Output:
57
+ /input/tape1.mp3 -> /output/tape1.txt
58
+ /input/sub/tape2.mp3 -> /output/sub/tape2.txt
59
+ (+ tape2.json with --timestamps)
60
+
61
+ Model: nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B (30B MoE, ~4B active,
62
+ OpenMDW-1.1)
63
+ - 40 transcription languages, speaker tags in 13, up to 8 speakers.
64
+ - Trained on recordings up to 1 hour; longer files are split into parts.
65
+ Speaker tags are consistent WITHIN a part and reset BETWEEN parts
66
+ (the part index is recorded on every word as "part").
67
+ - The card's generation-loop guardrail is applied to every transcript.
68
+ """
69
+
70
+ import argparse
71
+ import base64
72
+ import concurrent.futures
73
+ import io
74
+ import json
75
+ import logging
76
+ import math
77
+ import os
78
+ import re
79
+ import shutil
80
+ import signal
81
+ import subprocess
82
+ import sys
83
+ import tarfile
84
+ import time
85
+ import urllib.request
86
+ from pathlib import Path
87
+
88
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
89
+ logger = logging.getLogger(__name__)
90
+
91
+ MODEL = "nvidia/NVIDIA-Nemotron-3.5-Transcribe-30B-A4B"
92
+
93
+ # Where the prebuilt image (nemotron-transcribe-image.sh) installs the serving
94
+ # stack and its warm kernel caches.
95
+ PREBUILT_WORKDIR = Path("/opt/nemotron-transcribe")
96
+ # The NeMo Speech main commit the prebuilt image carries. The card asks for the
97
+ # latest main, which changes daily; pass --nemo-ref main to follow it.
98
+ DEFAULT_NEMO_REF = "7b05f096d54db47078fd1569a54d1f3ba4a4c51f"
99
+
100
+ # Written last by install_serving_stack, so a half-finished install is redone.
101
+ INSTALL_MARKER = ".install-complete"
102
+
103
+ AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".opus"}
104
+
105
+ SAMPLE_RATE = 16000
106
+
107
+ # The model is trained on recordings up to one hour. Stay a little under it.
108
+ DEFAULT_PART_SECONDS = 3300 # 55 min
109
+ MAX_PART_SECONDS = 3600 # the server's audio decode limit
110
+
111
+ # A dense one-hour conversation can need about 20,000 output tokens (card).
112
+ MAX_TOKENS = 24576
113
+
114
+ # User prompts from the model card's prompt guide. Transcription keeps the
115
+ # system prompt empty.
116
+ PROMPTS = {
117
+ "verbatim": (
118
+ "Audio transcription. Language: as spoken. Wording: verbatim, including "
119
+ "fillers and repetitions. Formatting: punctuation and capitalization. "
120
+ "Output: transcript only."
121
+ ),
122
+ "clean": (
123
+ "Audio transcription. Language: as spoken. Wording: omit fillers and "
124
+ "accidental repetitions; keep the remaining spoken wording unchanged. "
125
+ "Formatting: punctuation and capitalization. Output: transcript only."
126
+ ),
127
+ "speakers": (
128
+ "Transcribe this audio with punctuation and capitalization. Include all "
129
+ "spoken words and verbal fillers. Write numbers in their standard written "
130
+ "form. Put speaker tags <spk:0> <spk:1> <spk:2> <spk:3> on the transcription."
131
+ ),
132
+ }
133
+
134
+ # Generation-loop guardrail from the model card (adapted there from the
135
+ # Qwen3-ASR repetition fix, Apache 2.0).
136
+ CHAR_RUN = re.compile(r"(.)\1{20,}", re.DOTALL)
137
+ BLOCK_RUN = re.compile(r"(.{1,4096}?)\1{19,}", re.DOTALL)
138
+
139
+
140
+ def cleanup_generation_loops(text: str) -> str:
141
+ text = CHAR_RUN.sub(lambda m: m.group(1), text)
142
+ return BLOCK_RUN.sub(lambda m: m.group(1), text)
143
+
144
+
145
+ def write_atomic(path: Path, text: str):
146
+ """Write via a temp file, so an interrupted write never looks finished."""
147
+ tmp = path.with_name(path.name + ".tmp")
148
+ tmp.write_text(text, encoding="utf-8")
149
+ os.replace(tmp, path)
150
+
151
+
152
+ def discover_audio_files(input_dir: Path) -> list[Path]:
153
+ return [
154
+ p
155
+ for p in sorted(input_dir.rglob("*"))
156
+ if p.is_file() and p.suffix.lower() in AUDIO_EXTENSIONS
157
+ ]
158
+
159
+
160
+ def encode_flac(audio) -> str:
161
+ """Encode a 16 kHz mono waveform as base64 FLAC (lossless, ~half of WAV)."""
162
+ import soundfile
163
+
164
+ buf = io.BytesIO()
165
+ soundfile.write(buf, audio, SAMPLE_RATE, format="FLAC")
166
+ return base64.b64encode(buf.getvalue()).decode()
167
+
168
+
169
+ def transcribe_part(
170
+ server: str, audio_b64: str, prompt: str, timestamps: bool, timeout_s: int
171
+ ) -> dict:
172
+ import requests
173
+
174
+ extra = {
175
+ "chat_template_kwargs": {"enable_thinking": False},
176
+ "skip_special_tokens": False, # keep speaker and event tags
177
+ "spaces_between_special_tokens": False,
178
+ "seed": 0,
179
+ }
180
+ if timestamps:
181
+ extra["mm_processor_kwargs"] = {"capture_ctc_timestamps": True}
182
+ body = {
183
+ "model": MODEL,
184
+ "messages": [
185
+ {
186
+ "role": "user",
187
+ "content": [
188
+ {"type": "text", "text": prompt},
189
+ {
190
+ "type": "audio_url",
191
+ "audio_url": {"url": f"data:audio/flac;base64,{audio_b64}"},
192
+ },
193
+ ],
194
+ }
195
+ ],
196
+ "temperature": 0,
197
+ "top_p": 1.0,
198
+ "max_tokens": MAX_TOKENS,
199
+ **extra,
200
+ }
201
+ resp = requests.post(f"{server}/v1/chat/completions", json=body, timeout=timeout_s)
202
+ resp.raise_for_status()
203
+ return resp.json()
204
+
205
+
206
+ def shift_alignment(alignment: dict, offset_s: float, part_index: int) -> dict:
207
+ """Move a part's word and diarization times onto the whole-file timeline."""
208
+ words = [
209
+ {
210
+ **w,
211
+ "start": round(w["start"] + offset_s, 3),
212
+ "end": round(w["end"] + offset_s, 3),
213
+ "part": part_index,
214
+ }
215
+ for w in alignment.get("words") or []
216
+ ]
217
+ diarization = [
218
+ {
219
+ **seg,
220
+ "start": round(seg["start"] + offset_s, 3),
221
+ "end": round(seg["end"] + offset_s, 3),
222
+ "part": part_index,
223
+ }
224
+ for seg in alignment.get("diarization") or []
225
+ ]
226
+ return {
227
+ "words": words,
228
+ "diarization": diarization,
229
+ "speaker_tag_to_diarization_speaker": alignment.get(
230
+ "speaker_tag_to_diarization_speaker"
231
+ ),
232
+ "error": alignment.get("error"),
233
+ }
234
+
235
+
236
+ def server_is_up(server: str) -> bool:
237
+ import requests
238
+
239
+ try:
240
+ return requests.get(f"{server}/health", timeout=5).status_code == 200
241
+ except requests.RequestException:
242
+ return False
243
+
244
+
245
+ def install_serving_stack(workdir: Path, nemo_ref: str) -> Path:
246
+ """Install vLLM 0.32.0 + NeMo Speech as the model card does; return the venv."""
247
+ src = workdir / "nemo-speech"
248
+ venv = src / ".venv"
249
+ marker = src / INSTALL_MARKER
250
+ # The first prebuilt image predates the marker; the builder only publishes
251
+ # complete installs, so a vllm binary in the prebuilt workdir counts too.
252
+ prebuilt = workdir == PREBUILT_WORKDIR and (venv / "bin" / "vllm").exists()
253
+ if marker.exists() or prebuilt:
254
+ logger.info(f"Using the installed serving stack in {src}")
255
+ return venv
256
+ if src.exists():
257
+ logger.info(f"Removing an incomplete install in {src}")
258
+ shutil.rmtree(src)
259
+
260
+ # Resolve the ref to a commit so the run records exactly what it served.
261
+ with urllib.request.urlopen(
262
+ f"https://api.github.com/repos/NVIDIA-NeMo/Speech/commits/{nemo_ref}"
263
+ ) as resp:
264
+ sha = json.load(resp)["sha"]
265
+ # The source tarball, not `git clone`: the vLLM image ships without git.
266
+ url = f"https://github.com/NVIDIA-NeMo/Speech/archive/{sha}.tar.gz"
267
+ logger.info(f"Downloading NeMo Speech source ({nemo_ref} = {sha})...")
268
+ archive = workdir / "nemo-speech.tar.gz"
269
+ urllib.request.urlretrieve(url, archive)
270
+ with tarfile.open(archive) as tar:
271
+ top = tar.getnames()[0].split("/")[0]
272
+ tar.extractall(workdir, filter="data")
273
+ (workdir / top).rename(src)
274
+ (src / ".nemo-ref").write_text(sha)
275
+
276
+ uv = shutil.which("uv")
277
+ if uv is None:
278
+ sys.exit("uv is not on PATH: it is needed to install the serving stack")
279
+ python = str(venv / "bin" / "python")
280
+ env = {**os.environ, "UV_PROJECT_ENVIRONMENT": str(venv)}
281
+ steps = [
282
+ # The image's own Python: a uv-downloaded one would live outside the
283
+ # workdir, so a prebuilt image made from this workdir would lose it.
284
+ [uv, "venv", "-q", "-p", "3.12", str(venv)],
285
+ [uv, "sync", "-q", "--extra", "asr", "--extra", "vllm", "--locked", "--no-install-project"],
286
+ [uv, "pip", "install", "-q", "--python", python, "--no-deps", "-e", "."],
287
+ # PyAV decodes compressed audio; vLLM needs OpenCV, which NeMo excludes.
288
+ [uv, "pip", "install", "-q", "--python", python, "--no-deps",
289
+ "av==19.0.2", "opencv-python-headless==5.0.0.93"],
290
+ ] # fmt: skip
291
+ logger.info("Installing vLLM 0.32.0 + NeMo Speech (locked uv sync)...")
292
+ for step in steps:
293
+ subprocess.run(step, cwd=src, env=env, check=True)
294
+
295
+ # The locked env has flashinfer-python but not its precompiled kernels, so
296
+ # FlashInfer JIT-builds them at startup (~10 min on rtx-pro-6000). vLLM's
297
+ # `download-kernels` installs them; FlashInfer's installer needs pip.
298
+ logger.info("Installing FlashInfer precompiled kernels...")
299
+ subprocess.run([uv, "pip", "install", "-q", "--python", python, "pip"], check=True)
300
+ result = subprocess.run([str(venv / "bin" / "vllm"), "download-kernels"])
301
+ if result.returncode != 0:
302
+ logger.warning("Kernel download failed; FlashInfer will JIT-build at startup")
303
+ marker.write_text(sha)
304
+ return venv
305
+
306
+
307
+ def start_server(venv: Path, model_dir: Path, port: int) -> subprocess.Popen:
308
+ """Start `vllm serve` with the model card's single-GPU flags."""
309
+ env = {
310
+ **os.environ,
311
+ "VLLM_PLUGINS": "nemo_speechlm",
312
+ # Allow recordings up to one hour (the default is 600 seconds).
313
+ "VLLM_MAX_AUDIO_DECODE_DURATION_S": str(MAX_PART_SECONDS),
314
+ "VLLM_MAX_AUDIO_CLIP_FILESIZE_MB": "180",
315
+ # Word timestamps require the V1 model runner.
316
+ "VLLM_USE_V2_MODEL_RUNNER": "0",
317
+ }
318
+ cmd = [
319
+ str(venv / "bin" / "vllm"), "serve", str(model_dir),
320
+ "--served-model-name", MODEL,
321
+ "--port", str(port),
322
+ "--trust-remote-code", "--dtype", "bfloat16",
323
+ "--gpu-memory-utilization", "0.94",
324
+ "--max-model-len", "65536",
325
+ "--max-num-batched-tokens", "4096",
326
+ "--max-num-seqs", "192",
327
+ "--enable-chunked-prefill", "--no-enable-prefix-caching",
328
+ "--use-replayssm", "--mamba-backend", "flashinfer", "--mamba-cache-mode", "none",
329
+ "--mm-processor-cache-gb", "0", "--no-async-scheduling",
330
+ "--limit-mm-per-prompt", '{"audio":{"count":6,"length":120000000}}',
331
+ "--speculative-config", '{"method":"mtp","num_speculative_tokens":8}',
332
+ "--reasoning-parser", "nemotron_v3",
333
+ "--trust-request-mm-kwargs",
334
+ "--middleware",
335
+ "nemo.collections.speechlm2.vllm.salm.ctc_serving.ctc_timestamp_middleware",
336
+ ] # fmt: skip
337
+ logger.info("Starting vllm serve...")
338
+ # Own process group, so stop_server also reaches vLLM's engine workers.
339
+ return subprocess.Popen(cmd, env=env, start_new_session=True)
340
+
341
+
342
+ def stop_server(process: subprocess.Popen):
343
+ if process.poll() is not None:
344
+ return
345
+ logger.info("Stopping vllm serve...")
346
+ os.killpg(process.pid, signal.SIGTERM)
347
+ try:
348
+ process.wait(timeout=60)
349
+ except subprocess.TimeoutExpired:
350
+ os.killpg(process.pid, signal.SIGKILL)
351
+ process.wait()
352
+
353
+
354
+ def wait_for_server(
355
+ server: str, process: subprocess.Popen | None = None, timeout_s: int = 3600
356
+ ):
357
+ logger.info(f"Waiting for server at {server} (model load + warmup)...")
358
+ deadline = time.time() + timeout_s
359
+ while time.time() < deadline:
360
+ if server_is_up(server):
361
+ logger.info("Server is ready")
362
+ return
363
+ if process is not None and process.poll() is not None:
364
+ logger.error(f"vllm serve exited with code {process.returncode}")
365
+ sys.exit(1)
366
+ time.sleep(15)
367
+ logger.error(f"Server did not become ready within {timeout_s}s")
368
+ sys.exit(1)
369
+
370
+
371
+ def process_file(
372
+ file_path: Path,
373
+ input_dir: Path,
374
+ output_dir: Path,
375
+ server: str,
376
+ prompt: str,
377
+ timestamps: bool,
378
+ part_seconds: int,
379
+ request_timeout: int,
380
+ ) -> dict:
381
+ import librosa
382
+
383
+ rel = file_path.relative_to(input_dir)
384
+ start_time = time.time()
385
+
386
+ audio, _ = librosa.load(str(file_path), sr=SAMPLE_RATE, mono=True)
387
+ duration = len(audio) / SAMPLE_RATE
388
+ if len(audio) == 0:
389
+ raise ValueError("decoded to no audio")
390
+
391
+ # Equal parts of at most part_seconds, so there is no short tail part
392
+ # with its own speaker-tag namespace.
393
+ n_parts = math.ceil(duration / part_seconds)
394
+ part_length = duration / n_parts
395
+
396
+ texts = []
397
+ parts = []
398
+ for part_index in range(n_parts):
399
+ offset = part_index * part_length
400
+ lo = int(offset * SAMPLE_RATE)
401
+ hi = (
402
+ len(audio)
403
+ if part_index == n_parts - 1
404
+ else int((offset + part_length) * SAMPLE_RATE)
405
+ )
406
+ payload = transcribe_part(
407
+ server, encode_flac(audio[lo:hi]), prompt, timestamps, request_timeout
408
+ )
409
+ choice = payload["choices"][0]
410
+ text = cleanup_generation_loops(choice["message"]["content"] or "").strip()
411
+ texts.append(text)
412
+ part = {
413
+ "part": part_index,
414
+ "offset_s": round(offset, 1),
415
+ "duration_s": round((hi - lo) / SAMPLE_RATE, 1),
416
+ "finish_reason": choice.get("finish_reason"),
417
+ "completion_tokens": payload.get("usage", {}).get("completion_tokens"),
418
+ "text": text,
419
+ }
420
+ if timestamps:
421
+ part["alignment"] = shift_alignment(
422
+ payload.get("ctc_timestamps") or {"error": "no ctc_timestamps"},
423
+ offset,
424
+ part_index,
425
+ )
426
+ if part["finish_reason"] == "length":
427
+ logger.warning(f" {rel}: part {part_index} hit max_tokens — truncated")
428
+ parts.append(part)
429
+
430
+ txt_path = output_dir / rel.with_suffix(".txt")
431
+ txt_path.parent.mkdir(parents=True, exist_ok=True)
432
+ write_atomic(txt_path, "\n\n".join(texts) + "\n")
433
+
434
+ alignment_errors = [
435
+ p["alignment"]["error"]
436
+ for p in parts
437
+ if timestamps and p["alignment"]["error"] is not None
438
+ ]
439
+ if alignment_errors:
440
+ # No JSON, so a rerun retries this file instead of skipping it.
441
+ raise RuntimeError(f"alignment failed: {alignment_errors}")
442
+ if timestamps:
443
+ record = {
444
+ "file": str(rel),
445
+ "model": MODEL,
446
+ "prompt": prompt,
447
+ "duration_s": round(duration, 1),
448
+ "parts": parts,
449
+ }
450
+ write_atomic(
451
+ txt_path.with_suffix(".json"),
452
+ json.dumps(record, ensure_ascii=False, indent=2),
453
+ )
454
+
455
+ elapsed = time.time() - start_time
456
+ logger.info(
457
+ f" {rel}: {duration / 60:.1f} min, {len(parts)} part(s), "
458
+ f"{sum(len(t.split()) for t in texts)} words in {elapsed:.0f}s"
459
+ + (f", alignment errors: {alignment_errors}" if alignment_errors else "")
460
+ )
461
+ return {
462
+ "file": str(rel),
463
+ "duration_s": round(duration, 1),
464
+ "num_parts": len(parts),
465
+ "truncated_parts": sum(p["finish_reason"] == "length" for p in parts),
466
+ "alignment_errors": alignment_errors,
467
+ "elapsed_s": round(elapsed, 1),
468
+ }
469
+
470
+
471
+ def main():
472
+ parser = argparse.ArgumentParser(
473
+ description="Concurrent transcription via an in-job Nemotron Transcribe vLLM server.",
474
+ formatter_class=argparse.RawDescriptionHelpFormatter,
475
+ epilog="See module docstring for the full `hf jobs run` command.",
476
+ )
477
+ parser.add_argument("input_dir", help="Directory containing audio files")
478
+ parser.add_argument("output_dir", help="Directory to write transcripts")
479
+ parser.add_argument(
480
+ "--server",
481
+ default="http://127.0.0.1:8000",
482
+ help="vLLM server base URL (default: in-job localhost:8000). If no "
483
+ "server answers there, the script installs and starts one.",
484
+ )
485
+ parser.add_argument(
486
+ "--nemo-ref",
487
+ default=DEFAULT_NEMO_REF,
488
+ help="NeMo Speech branch, tag or commit to install when the image has "
489
+ "no prebuilt stack (default: the image's commit; `main` follows the card)",
490
+ )
491
+ parser.add_argument(
492
+ "--workdir",
493
+ default=PREBUILT_WORKDIR
494
+ if PREBUILT_WORKDIR.exists()
495
+ else "/tmp/nemotron-transcribe",
496
+ help="Where the serving stack and checkpoint are installed (default: "
497
+ f"{PREBUILT_WORKDIR} in the prebuilt image, else /tmp/nemotron-transcribe)",
498
+ )
499
+ parser.add_argument(
500
+ "--style",
501
+ choices=sorted(PROMPTS),
502
+ default="verbatim",
503
+ help="Prompt preset from the model card (default: verbatim). "
504
+ "'speakers' adds <spk:N> tags; --timestamps implies it.",
505
+ )
506
+ parser.add_argument(
507
+ "--prompt",
508
+ default=None,
509
+ help="Custom user prompt, e.g. with 'Context terms: <names>' "
510
+ "(overrides --style)",
511
+ )
512
+ parser.add_argument(
513
+ "--timestamps",
514
+ action="store_true",
515
+ help="Also write JSON with word timestamps, speakers and diarization "
516
+ "segments (needs the server's --middleware flag)",
517
+ )
518
+ parser.add_argument(
519
+ "--concurrency",
520
+ type=int,
521
+ default=16,
522
+ help="Concurrent files in flight (default: 16)",
523
+ )
524
+ parser.add_argument(
525
+ "--part-minutes",
526
+ type=float,
527
+ default=DEFAULT_PART_SECONDS / 60,
528
+ help="Split audio into equal parts of at most this length, up to 60 "
529
+ "(default: 55 min — the "
530
+ "model is trained on recordings up to one hour). Speaker tags reset "
531
+ "between parts.",
532
+ )
533
+ parser.add_argument(
534
+ "--request-timeout",
535
+ type=int,
536
+ default=3600,
537
+ help="Per-request timeout in seconds (default: 3600)",
538
+ )
539
+ parser.add_argument(
540
+ "--max-files", type=int, default=None, help="Limit files (for testing)"
541
+ )
542
+
543
+ args = parser.parse_args()
544
+
545
+ input_dir = Path(args.input_dir)
546
+ output_dir = Path(args.output_dir)
547
+ if not input_dir.is_dir():
548
+ logger.error(f"Input directory does not exist: {input_dir}")
549
+ sys.exit(1)
550
+ output_dir.mkdir(parents=True, exist_ok=True)
551
+
552
+ part_seconds = int(args.part_minutes * 60)
553
+ if part_seconds < 1 or part_seconds > MAX_PART_SECONDS:
554
+ logger.error("--part-minutes must be between 1/60 (one second) and 60")
555
+ sys.exit(1)
556
+
557
+ if args.prompt:
558
+ prompt = args.prompt
559
+ elif args.timestamps:
560
+ prompt = PROMPTS["speakers"]
561
+ else:
562
+ prompt = PROMPTS[args.style]
563
+
564
+ files = discover_audio_files(input_dir)
565
+ if not files:
566
+ logger.error(f"No audio files found in {input_dir}")
567
+ sys.exit(1)
568
+
569
+ # Resume: outputs are written per file, so a rerun after a timeout or
570
+ # crash only processes what's missing.
571
+ done_suffix = ".json" if args.timestamps else ".txt"
572
+ done = {
573
+ f
574
+ for f in files
575
+ if (output_dir / f.relative_to(input_dir).with_suffix(done_suffix)).exists()
576
+ }
577
+ if done:
578
+ logger.info(f"Skipping {len(done)} file(s) with existing output")
579
+ files = [f for f in files if f not in done]
580
+ if not files:
581
+ logger.info("Nothing to do — all outputs exist")
582
+ return
583
+ if args.max_files:
584
+ files = files[: args.max_files]
585
+ logger.info(f"Found {len(files)} audio file(s) to process")
586
+
587
+ server_process = None
588
+ if server_is_up(args.server):
589
+ logger.info(f"Using the running server at {args.server}")
590
+ else:
591
+ from urllib.parse import urlparse
592
+
593
+ from huggingface_hub import snapshot_download
594
+
595
+ # Only start a server where the requests will go: this machine, on
596
+ # the port named in --server.
597
+ url = urlparse(args.server)
598
+ if url.hostname not in {"127.0.0.1", "localhost"} or url.port is None:
599
+ logger.error(
600
+ f"No server answers at {args.server}. To start one here, pass "
601
+ "--server http://127.0.0.1:<port> (the default is port 8000)."
602
+ )
603
+ sys.exit(1)
604
+ if shutil.which("nvidia-smi") is None:
605
+ logger.error("No GPU found: run on a GPU flavor (see the header)")
606
+ sys.exit(1)
607
+ workdir = Path(args.workdir)
608
+ workdir.mkdir(parents=True, exist_ok=True)
609
+ venv = install_serving_stack(workdir, args.nemo_ref)
610
+ logger.info(f"Downloading {MODEL}...")
611
+ model_dir = Path(snapshot_download(MODEL, local_dir=workdir / "model"))
612
+ server_process = start_server(venv, model_dir, url.port)
613
+
614
+ # Results are appended as files finish, so a crash keeps what completed
615
+ # and a resumed run adds to the earlier records instead of replacing them.
616
+ summary_path = output_dir / "summary.jsonl"
617
+ results = []
618
+ try:
619
+ wait_for_server(args.server, server_process)
620
+ start_time = time.time()
621
+ with (
622
+ concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool,
623
+ open(summary_path, "a", encoding="utf-8") as summary,
624
+ ):
625
+ futures = {
626
+ pool.submit(
627
+ process_file,
628
+ f,
629
+ input_dir,
630
+ output_dir,
631
+ args.server,
632
+ prompt,
633
+ args.timestamps,
634
+ part_seconds,
635
+ args.request_timeout,
636
+ ): f
637
+ for f in files
638
+ }
639
+ for fut in concurrent.futures.as_completed(futures):
640
+ f = futures[fut]
641
+ try:
642
+ result = fut.result()
643
+ except Exception as exc:
644
+ logger.error(f" {f.name} FAILED: {exc}")
645
+ result = {"file": str(f.relative_to(input_dir)), "error": str(exc)}
646
+ results.append(result)
647
+ summary.write(json.dumps(result, ensure_ascii=False) + "\n")
648
+ summary.flush()
649
+ elapsed = time.time() - start_time
650
+ finally:
651
+ if server_process is not None:
652
+ stop_server(server_process)
653
+
654
+ ok = [r for r in results if "error" not in r]
655
+ total_audio = sum(r["duration_s"] for r in ok)
656
+ elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
657
+ logger.info("=" * 50)
658
+ logger.info(f"Done! {len(ok)}/{len(files)} file(s) in {elapsed_str}")
659
+ if total_audio:
660
+ logger.info(f" Audio: {total_audio / 3600:.1f} h total")
661
+ logger.info(f" RTFx: {total_audio / elapsed:.1f}x realtime (aggregate)")
662
+ logger.info(f" Summary: {summary_path}")
663
+ if len(ok) < len(files):
664
+ # Non-zero, so the job (and the image builder's warm-up) shows as failed.
665
+ logger.error(f" Failed: {len(files) - len(ok)} file(s) — see {summary_path}")
666
+ sys.exit(1)
667
+
668
+
669
+ if __name__ == "__main__":
670
+ if len(sys.argv) == 1:
671
+ print("=" * 60)
672
+ print("Nemotron 3.5 Transcribe (in-job vLLM server)")
673
+ print("=" * 60)
674
+ print("\nStarts an in-job vLLM server (vLLM 0.32.0 + NeMo Speech), splits")
675
+ print("audio over one hour, posts files concurrently, writes .txt")
676
+ print("transcripts (+ JSON word timestamps and speakers with --timestamps).")
677
+ print("\nSee module docstring for the `hf jobs uv run` command")
678
+ print("(image + flavor come from the [tool.hf-jobs] header).")
679
+ print("\nFor full help: uv run nemotron-transcribe.py --help")
680
+ sys.exit(0)
681
+
682
+ main()