From fe7b431cb7b95d66c0226aa9ea4a5f150aaeac50 Mon Sep 17 00:00:00 2001 From: aviv ron Date: Tue, 10 Nov 2026 15:42:48 +0200 Subject: [PATCH] Drop configurable ASR no-speech markers from transcripts Some ASR models emit a marker such as <|nospeech|> for silence or non-speech, and that marker was spliced into the LLM prompt as if the user had said it. Add asr_no_speech_markers to GraniteSwitchConfig, set at compose time with a repeatable --asr-no-speech-marker flag. The markers are model-specific, so there is no default and nothing is removed unless configured. Every occurrence of each marker is removed from each transcribed window before long-audio windows are merged, so a marker next to speech, repeated, or inside one chunk is caught as well. Only the configured exact strings are removed; other tags such as timings, emotions or language tags are kept. The markers are part of the transcriber cache key and are documented in docs/AUDIO.md. Signed-off-by: aviv ron --- docs/AUDIO.md | 25 +++++++ .../composer/compose_granite_switch.py | 25 ++++++- src/granite_switch/config.py | 16 +++++ src/granite_switch/vllm/audio/asr.py | 42 +++++++++-- src/granite_switch/vllm/audio/processor.py | 5 ++ .../test_asr_no_speech_marker_flag.py | 39 +++++++++++ tests/unit/test_asr.py | 70 +++++++++++++++++++ tests/unit/test_config.py | 19 +++++ tests/vllm/test_audio_processor.py | 26 ++++++- 9 files changed, 261 insertions(+), 6 deletions(-) create mode 100644 tests/composer/test_asr_no_speech_marker_flag.py diff --git a/docs/AUDIO.md b/docs/AUDIO.md index d6253d1f..20a63eda 100644 --- a/docs/AUDIO.md +++ b/docs/AUDIO.md @@ -195,6 +195,31 @@ editing that file directly — no re-compose and no patched package: "asr_generate_kwargs": {"language": "de", "task": "transcribe"} } ``` +### No-speech markers + +Some ASR models emit a marker instead of text for silence or non-speech, e.g. +`<|nospeech|>` or `<|nocaptions|>`. Left alone, that marker is spliced into the prompt as +if the user had said it. `asr_no_speech_markers` lists the exact strings to drop: +every occurrence is removed from each transcribed window (before long-audio +windows are merged), wherever it appears. A clip that was only markers becomes an +empty transcript. Any other tag (timings, emotions, language tags) is kept. + +The marker depends on the ASR model, so there is no default: nothing is removed +unless you set it. Pass it at compose time (repeat the flag for several markers; +quote the value, since `<` and `|` are shell operators): + +```bash +python -m granite_switch.composer.compose_granite_switch \ + --adapters ... --enable-audio \ + --asr-no-speech-marker "<|nospeech|>" +``` + +or set it in an existing checkpoint's `config.json`: + +```json +{ "asr_no_speech_markers": ["<|nospeech|>"] } +``` + ### Long audio & multiple clips The transcript is spliced into the prompt as ordinary text tokens — it is **not** diff --git a/src/granite_switch/composer/compose_granite_switch.py b/src/granite_switch/composer/compose_granite_switch.py index 528b31bb..14181af4 100755 --- a/src/granite_switch/composer/compose_granite_switch.py +++ b/src/granite_switch/composer/compose_granite_switch.py @@ -813,6 +813,13 @@ def _validate_save_pretrained_writes(before, after, output_path): # --------------------------------------------------------------------------- +def _non_empty_marker(value: str) -> str: + """argparse type for --asr-no-speech-marker: an empty marker would match everywhere.""" + if not value: + raise argparse.ArgumentTypeError("--asr-no-speech-marker must not be empty") + return value + + def _compose_argparser(): parser = argparse.ArgumentParser( description="Compose Granite Switch model with embedded LoRA adapters", @@ -1080,6 +1087,19 @@ def _compose_argparser(): help="Chunker window overlap in seconds (default 5.0). Only used when " "the backend does not self-chunk. Requires --enable-audio; ignored without it.", ) + parser.add_argument( + "--asr-no-speech-marker", + dest="asr_no_speech_markers", + action="append", + default=None, + metavar="MARKER", + type=_non_empty_marker, + help="Exact string the ASR model emits for silence or non-speech, e.g. " + "'<|nospeech|>'. Every occurrence is removed from the transcript before " + "it reaches the prompt; other tags are kept. Repeat the flag for several " + "markers. Model-specific: no default, so nothing is removed unless set. " + "Requires --enable-audio; ignored without it.", + ) return parser @@ -1533,6 +1553,8 @@ def build(): model.config.asr_chunk_length_s = args.asr_chunk_length_s if args.asr_chunk_overlap_s is not None: model.config.asr_chunk_overlap_s = args.asr_chunk_overlap_s + if args.asr_no_speech_markers is not None: + model.config.asr_no_speech_markers = args.asr_no_speech_markers print( f" Audio cascade enabled " f"(asr_model_id={asr_model_id}, " @@ -1544,7 +1566,8 @@ def build(): f"pipeline_kwargs={args.asr_pipeline_kwargs or {}}, " f"generate_kwargs={args.asr_generate_kwargs or {}}, " f"max_audio_clips={args.asr_max_audio_clips or 'default'}, " - f"self_chunks={args.asr_self_chunks})" + f"self_chunks={args.asr_self_chunks}, " + f"no_speech_markers={args.asr_no_speech_markers or []})" ) # Base model size (best effort) diff --git a/src/granite_switch/config.py b/src/granite_switch/config.py index 54ca9202..5aab0d88 100644 --- a/src/granite_switch/config.py +++ b/src/granite_switch/config.py @@ -130,6 +130,11 @@ class GraniteSwitchConfig(GraniteMoeHybridConfig): default CTC backend does not self-chunk, and the HF pipeline's own CTC chunking mis-trims seams for it (it needs the model to publish inputs_to_logits_ratio, which this checkpoint does not). + asr_no_speech_markers (Optional[list[str]]): Exact strings the ASR + model emits for silence or non-speech (e.g. ``"<|nospeech|>"``). + Every occurrence is removed from each transcribed window before + it reaches the prompt; any other tag is kept. Model-specific, so + set it to match ``asr_model_id``. Default: None (nothing removed). Shadow Residual (SR) parameters: dual_stream (bool): Whole-checkpoint decoder mode. ``False`` (default) = @@ -219,6 +224,7 @@ def __init__( asr_chunk_length_s: float = 120.0, asr_chunk_overlap_s: float = 5.0, asr_self_chunks: bool = False, + asr_no_speech_markers: list[str] | None = None, # Shadow Residual (SR) parameters cross_stream_rank: int | None = None, dual_stream: bool = False, @@ -370,6 +376,16 @@ def __init__( self.asr_chunk_length_s = asr_chunk_length_s self.asr_chunk_overlap_s = asr_chunk_overlap_s self.asr_self_chunks = asr_self_chunks + if asr_no_speech_markers is not None: + if isinstance(asr_no_speech_markers, str) or not all( + isinstance(m, str) and m for m in asr_no_speech_markers + ): + raise ValueError( + "asr_no_speech_markers must be a list of non-empty strings, " + f"got {asr_no_speech_markers!r}" + ) + asr_no_speech_markers = list(asr_no_speech_markers) + self.asr_no_speech_markers = asr_no_speech_markers # Shadow Residual (SR). # Pre-fusion SR checkpoints carried unfused_qkv; their weight layout is diff --git a/src/granite_switch/vllm/audio/asr.py b/src/granite_switch/vllm/audio/asr.py index e326fb49..738e5b87 100644 --- a/src/granite_switch/vllm/audio/asr.py +++ b/src/granite_switch/vllm/audio/asr.py @@ -3,7 +3,8 @@ Wraps a HuggingFace ASR pipeline. Free of any vLLM import so it unit-tests on CPU. The model loads lazily and is cached per (model_id, revision, device, -dtype, pipeline_kwargs), so a process loads each ASR model at most once. +dtype, pipeline_kwargs, no_speech_markers), so a process loads each ASR model +at most once. There is no default model here: the checkpoint config names it (the composer writes config.DEFAULT_ASR_MODEL_ID and its pinned revision), and ``model_id`` @@ -21,7 +22,7 @@ import posixpath import subprocess import threading -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from typing import Any, Union import numpy as np @@ -292,12 +293,16 @@ def __init__( pipeline_kwargs: Mapping[str, Any] | None = None, dtype: str | None = None, revision: str | None = None, + no_speech_markers: Sequence[str] | None = None, ) -> None: self.model_id = model_id self.revision = revision self.device = device self.dtype = dtype self.pipeline_kwargs: dict[str, Any] = dict(pipeline_kwargs or {}) + # Exact strings this ASR model emits for silence/non-speech. Removed per + # window (see _strip_no_speech_markers); everything else is kept. + self.no_speech_markers: tuple[str, ...] = tuple(no_speech_markers or ()) self._pipeline = None # Set by load(): whether the resolved backend decodes with CTC (no # generation, so no decode kwargs and no pipeline-level chunking). @@ -397,7 +402,24 @@ def _run_pipeline( **call_kwargs, ) text = result["text"] if isinstance(result, dict) else str(result) + # Per window, so merge_transcripts never sees a marker (nor matches its + # seam overlap on one). + return _strip_no_speech_markers(text, self.no_speech_markers) + + +def _strip_no_speech_markers(text: str, markers: Sequence[str]) -> str: + """Remove every occurrence of each no-speech marker, then normalize spacing. + + A marker can stand alone (silence), repeat, or sit next to real words, so a + whole-transcript equality check is not enough. Only the configured exact + strings are removed: other tags (timings, emotions, language) pass through. + Without markers the text is only stripped, so spacing is left untouched. + """ + if not markers: return text.strip() + for marker in markers: + text = text.replace(marker, " ") + return " ".join(text.split()) # ── Module-level cache + convenience function ──────────────────────────────── @@ -450,14 +472,23 @@ def get_transcriber( pipeline_kwargs: Mapping[str, Any] | None = None, dtype: str | None = None, revision: str | None = None, + no_speech_markers: Sequence[str] | None = None, ) -> ASRTranscriber: """Return a process-wide cached :class:`ASRTranscriber`. - Cached per ``(model_id, revision, device, dtype, pipeline_kwargs)``. + Cached per ``(model_id, revision, device, dtype, pipeline_kwargs, + no_speech_markers)``. """ if not model_id: raise ValueError("get_transcriber requires a model_id") - key = (model_id, revision, device, dtype, _freeze(pipeline_kwargs or {})) + key = ( + model_id, + revision, + device, + dtype, + _freeze(pipeline_kwargs or {}), + tuple(no_speech_markers or ()), + ) transcriber = _TRANSCRIBERS.get(key) if transcriber is None: with _CACHE_LOCK: @@ -469,6 +500,7 @@ def get_transcriber( pipeline_kwargs=pipeline_kwargs, dtype=dtype, revision=revision, + no_speech_markers=no_speech_markers, ) _TRANSCRIBERS[key] = transcriber return transcriber @@ -483,6 +515,7 @@ def transcribe( device: str = "cuda", pipeline_kwargs: Mapping[str, Any] | None = None, dtype: str | None = None, + no_speech_markers: Sequence[str] | None = None, generate_kwargs: Mapping[str, Any] | None = None, self_chunks: bool = False, chunk_length_s: float = DEFAULT_CHUNK_LENGTH_S, @@ -495,6 +528,7 @@ def transcribe( pipeline_kwargs=pipeline_kwargs, dtype=dtype, revision=revision, + no_speech_markers=no_speech_markers, ).transcribe( audio, sampling_rate, diff --git a/src/granite_switch/vllm/audio/processor.py b/src/granite_switch/vllm/audio/processor.py index 1d6736b8..cf6e30bc 100644 --- a/src/granite_switch/vllm/audio/processor.py +++ b/src/granite_switch/vllm/audio/processor.py @@ -186,6 +186,10 @@ def _asr_generate_kwargs(self) -> Mapping[str, object]: cfg = self.get_hf_config() return getattr(cfg, "asr_generate_kwargs", None) or {} + def _asr_no_speech_markers(self) -> list[str]: + cfg = self.get_hf_config() + return list(getattr(cfg, "asr_no_speech_markers", None) or []) + def _asr_max_audio_clips(self) -> int: cfg = self.get_hf_config() return int(getattr(cfg, "asr_max_audio_clips", 32) or 32) @@ -353,6 +357,7 @@ def _transcribe( device=self.info._asr_device(), pipeline_kwargs=self.info._asr_pipeline_kwargs(), dtype=self.info._asr_dtype(), + no_speech_markers=self.info._asr_no_speech_markers(), ) # The data parser already resampled to _TARGET_SR. text = transcriber.transcribe( diff --git a/tests/composer/test_asr_no_speech_marker_flag.py b/tests/composer/test_asr_no_speech_marker_flag.py new file mode 100644 index 00000000..d6c281f8 --- /dev/null +++ b/tests/composer/test_asr_no_speech_marker_flag.py @@ -0,0 +1,39 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The ``--asr-no-speech-marker`` compose option: repeatable, no default.""" + +import pytest + +from granite_switch.composer.compose_granite_switch import _compose_argparser + +pytestmark = pytest.mark.audio + + +def _parse(*extra): + return _compose_argparser().parse_args(["--adapters", "org/lib", *extra]) + + +class TestNoSpeechMarkerFlag: + def test_defaults_to_none(self): + # Model-specific, so compose sets nothing unless asked. + assert _parse().asr_no_speech_markers is None + + def test_single_marker(self): + args = _parse("--asr-no-speech-marker", "<|nospeech|>") + assert args.asr_no_speech_markers == ["<|nospeech|>"] + + def test_repeated_flag_collects_list(self): + args = _parse( + "--asr-no-speech-marker", + "<|nospeech|>", + "--asr-no-speech-marker", + "<|nocaptions|>", + ) + assert args.asr_no_speech_markers == ["<|nospeech|>", "<|nocaptions|>"] + + def test_dash_leading_marker_with_equals(self): + args = _parse("--asr-no-speech-marker=-silence-") + assert args.asr_no_speech_markers == ["-silence-"] + + def test_empty_marker_rejected(self): + with pytest.raises(SystemExit): + _parse("--asr-no-speech-marker", "") diff --git a/tests/unit/test_asr.py b/tests/unit/test_asr.py index c4bc018d..08955805 100644 --- a/tests/unit/test_asr.py +++ b/tests/unit/test_asr.py @@ -171,6 +171,68 @@ def test_short_clip_single_window(self): assert out == "seg80000" +class TestNoSpeechMarkers: + """Configured no-speech markers are removed per window, everything else kept.""" + + def _transcriber(self, texts, markers=("<|nospeech|>",)): + t = asr.ASRTranscriber(model_id="x", device="cpu", no_speech_markers=markers) + outputs = iter(texts) + t._pipeline = lambda inp, **k: {"text": next(outputs)} + return t + + def _one(self, text, markers=("<|nospeech|>",)): + t = self._transcriber([text], markers) + return t.transcribe(np.zeros(1600, dtype=np.float32), sampling_rate=16000) + + def test_marker_alone_becomes_empty(self): + assert self._one(" <|nospeech|> ") == "" + + def test_repeated_marker_becomes_empty(self): + assert self._one("<|nospeech|><|nospeech|> <|nospeech|>") == "" + + def test_marker_next_to_speech_is_removed(self): + assert self._one("hello <|nospeech|>") == "hello" + assert self._one("<|nospeech|>hello") == "hello" + + def test_marker_mid_sentence_is_removed(self): + assert self._one("hello <|nospeech|> world") == "hello world" + + def test_multiple_markers(self): + out = self._one( + "<|nocaptions|> hi <|nospeech|>", markers=("<|nospeech|>", "<|nocaptions|>") + ) + assert out == "hi" + + def test_other_tags_are_kept(self): + # Only the configured markers go: timing/emotion/language tags survive. + assert self._one("<|en|> hi <|0.50|> <|nospeech|>") == "<|en|> hi <|0.50|>" + + def test_no_markers_leaves_text_untouched(self): + assert self._one(" hi <|nospeech|> ", markers=None) == "hi <|nospeech|>" + + def test_self_chunks_path(self): + t = self._transcriber(["hi <|nospeech|>"]) + out = t.transcribe( + np.zeros(70 * 16000, dtype=np.float32), + sampling_rate=16000, + self_chunks=True, + ) + assert out == "hi" + + def test_removed_per_window_before_merge(self): + # 70s, 30s window, 5s overlap -> 3 windows. The all-silence middle window + # contributes nothing, and a marker inside a window never reaches merge. + t = self._transcriber(["hello there", "<|nospeech|>", "<|nospeech|> and then"]) + out = t.transcribe( + np.zeros(70 * 16000, dtype=np.float32), + sampling_rate=16000, + self_chunks=False, + chunk_length_s=30.0, + chunk_overlap_s=5.0, + ) + assert out == "hello there and then" + + class TestUnsupportedArchitectureError: """A transformers too old for the default model must say so actionably.""" @@ -428,6 +490,14 @@ def test_pipeline_kwargs_are_part_of_cache_key(self): assert a is not b assert a is c + def test_no_speech_markers_are_part_of_cache_key(self): + a = asr.get_transcriber("ns", "cpu", no_speech_markers=["<|nospeech|>"]) + b = asr.get_transcriber("ns", "cpu") + c = asr.get_transcriber("ns", "cpu", no_speech_markers=("<|nospeech|>",)) + assert a is not b + assert a is c + assert a.no_speech_markers == ("<|nospeech|>",) + def test_pipeline_kwargs_key_is_order_independent(self): a = asr.get_transcriber("pk2", "cpu", pipeline_kwargs={"x": 1, "y": 2}) b = asr.get_transcriber("pk2", "cpu", pipeline_kwargs={"y": 2, "x": 1}) diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index b8b54c09..eb2dce09 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -112,6 +112,25 @@ def test_asr_defaults_off(self): assert cfg.asr_dtype is None assert cfg.asr_pipeline_kwargs is None assert cfg.asr_generate_kwargs is None + # Model-specific, so no default: nothing is removed unless composed in. + assert cfg.asr_no_speech_markers is None + + def test_no_speech_markers_round_trip(self, tmp_path): + cfg = GraniteSwitchConfig( + num_adapters=0, + asr_enabled=True, + asr_no_speech_markers=["<|nospeech|>", "<|nocaptions|>"], + ) + cfg.save_pretrained(tmp_path) + loaded = GraniteSwitchConfig.from_pretrained(tmp_path) + assert loaded.asr_no_speech_markers == ["<|nospeech|>", "<|nocaptions|>"] + + @pytest.mark.parametrize("bad", ["<|nospeech|>", [""], ["ok", 3]]) + def test_invalid_no_speech_markers_raise(self, bad): + # A bare string would be iterated per character; an empty marker would + # match between every character. + with pytest.raises(ValueError, match="asr_no_speech_markers"): + GraniteSwitchConfig(num_adapters=0, asr_no_speech_markers=bad) def test_asr_dtype_round_trip(self, tmp_path): cfg = GraniteSwitchConfig( diff --git a/tests/vllm/test_audio_processor.py b/tests/vllm/test_audio_processor.py index 08c81de0..0fd8306e 100644 --- a/tests/vllm/test_audio_processor.py +++ b/tests/vllm/test_audio_processor.py @@ -180,6 +180,13 @@ def test_pipeline_and_generate_kwargs_from_config(self): assert info._asr_pipeline_kwargs() == {"chunk_length_s": 15} assert info._asr_generate_kwargs() == {"language": "de"} + def test_no_speech_markers_default_empty(self): + assert _make_info(asr_enabled=True)._asr_no_speech_markers() == [] + + def test_no_speech_markers_from_config(self): + info = _make_info(asr_enabled=True, asr_no_speech_markers=["<|nospeech|>"]) + assert info._asr_no_speech_markers() == ["<|nospeech|>"] + def test_longaudio_accessor_defaults(self): info = _make_info(asr_enabled=True) assert info._asr_max_audio_clips() == 32 @@ -242,13 +249,19 @@ def transcribe( return "hello world" def fake_get_transcriber( - model_id=None, device="cpu", pipeline_kwargs=None, dtype=None, revision=None + model_id=None, + device="cpu", + pipeline_kwargs=None, + dtype=None, + revision=None, + no_speech_markers=None, ): capture["model_id"] = model_id capture["revision"] = revision capture["device"] = device capture["pipeline_kwargs"] = pipeline_kwargs capture["dtype"] = dtype + capture["no_speech_markers"] = no_speech_markers return FakeTranscriber() monkeypatch.setattr(proc_mod, "get_transcriber", fake_get_transcriber) @@ -402,6 +415,17 @@ def test_self_chunks_and_chunk_params_forwarded(self, monkeypatch): assert capture["chunk_length_s"] == 20.0 assert capture["chunk_overlap_s"] == 3.0 + def test_no_speech_markers_forwarded_to_transcriber(self, monkeypatch): + capture = {} + info = _make_info( + asr_enabled=True, + asr_model_id="w", + asr_no_speech_markers=["<|nospeech|>", "<|nocaptions|>"], + ) + proc = _make_processor(info, monkeypatch, capture) + proc._transcribe(np.zeros(1600, dtype=np.float32), {}) + assert capture["no_speech_markers"] == ["<|nospeech|>", "<|nocaptions|>"] + def _make_processor_transcribing(info, monkeypatch, text, *, ids_for): """Processor whose transcriber returns a fixed ``text``; ``ids_for`` maps it to ids."""