Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/AUDIO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
25 changes: 24 additions & 1 deletion src/granite_switch/composer/compose_granite_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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}, "
Expand All @@ -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)
Expand Down
16 changes: 16 additions & 0 deletions src/granite_switch/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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) =
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
42 changes: 38 additions & 4 deletions src/granite_switch/vllm/audio/asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``
Expand All @@ -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
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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 ────────────────────────────────
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -495,6 +528,7 @@ def transcribe(
pipeline_kwargs=pipeline_kwargs,
dtype=dtype,
revision=revision,
no_speech_markers=no_speech_markers,
).transcribe(
audio,
sampling_rate,
Expand Down
5 changes: 5 additions & 0 deletions src/granite_switch/vllm/audio/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
39 changes: 39 additions & 0 deletions tests/composer/test_asr_no_speech_marker_flag.py
Original file line number Diff line number Diff line change
@@ -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", "")
70 changes: 70 additions & 0 deletions tests/unit/test_asr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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})
Expand Down
Loading
Loading