Skip to content

Asr - #111

Draft
aviv1ron1 wants to merge 29 commits into
mainfrom
asr
Draft

Asr#111
aviv1ron1 wants to merge 29 commits into
mainfrom
asr

Conversation

@aviv1ron1

Copy link
Copy Markdown
Collaborator

No description provided.

aviv1ron1 and others added 18 commits June 14, 2026 14:14
Signed-off-by: aviv ron <rona@il.ibm.com>
Register an ASR multimodal processor on GraniteSwitchForCausalLM: audio is
transcribed and a <|audio|> marker is replaced with the transcript tokens
(PromptReplacement), so the scheduler sizes KV for the real length. The model's
embed_multimodal supplies those positions' embeddings via the token table (the
seam a future trained audio encoder will reuse), and embed_input_ids scatters
them. Audio capability is gated per-checkpoint by config.asr_enabled.

Alpha scope: audio runs on the base model (no adapter control-token handling).

Signed-off-by: aviv ron <rona@il.ibm.com>
Signed-off-by: aviv ron <rona@il.ibm.com>
New --enable-audio / --asr-model / --asr-device flags. When audio is enabled the
composer adds the <|audio|> marker token (before the embedding resize) and writes
asr_enabled / asr_model_id / asr_device into the checkpoint config, so the vLLM
backend's gated audio processor activates for that checkpoint.

Signed-off-by: aviv ron <rona@il.ibm.com>
Signed-off-by: aviv ron <rona@il.ibm.com>
tests/unit/test_asr.py: CPU-tier unit coverage for the ASR backend (audio
coercion, mono/resample, lazy-load, transcribe with mocked pipeline); loads the
leaf module by path so it runs without the vLLM extra. docs/AUDIO.md: how to
compose --enable-audio, call it (Python + OpenAI server), the cascade design and
the future-encoder seam, and alpha limitations.

Signed-off-by: aviv ron <rona@il.ibm.com>
…ate work)

Signed-off-by: aviv ron <rona@il.ibm.com>
The Granite content-part loop only handled type=='text' and dropped audio parts,
so chat/OpenAI-server requests rendered without the <|audio|> marker and prompt
replacement failed. Add configure_audio_chat_template(): injects an elif that
appends the marker for any part whose type contains 'audio' (covers audio /
input_audio / audio_url). Called during compose when audio is enabled.

Signed-off-by: aviv ron <rona@il.ibm.com>
Set requires_raw_input_tokens=True so vLLM passes raw input_ids to forward on the
multimodal path, letting the switch detect adapter control tokens for audio
requests. embed_input_ids now applies the switch's token-exchange rewrite
(control -> substitute id) via a new SingleSwitch.apply_token_exchange helper, so
control tokens get in-distribution embeddings exactly as on the text path.

Signed-off-by: aviv ron <rona@il.ibm.com>
Signed-off-by: aviv ron <rona@il.ibm.com>
…errides in config

Signed-off-by: aviv ron <rona@il.ibm.com>
Remove the two hard caps in the audio cascade and add an encoder-agnostic
long-audio chunker:

1. Multiple clips per request. get_supported_mm_limits is now a configurable
   ceiling (asr_max_audio_clips, default 32) instead of a hardcoded 1; each
   clip's transcript is spliced at its own <|audio|> marker (the splice loop
   already supported N). For the cascade the clips cost no extra KV (transcripts
   are ordinary text tokens bounded by the context); the ceiling exists to bound
   the per-request synchronous-ASR work and the startup profiling pass.

2. Context-derived transcript budget. The fixed 2048-token cap is replaced by
   audio_token_budget() = (context - generation_reserve - prompt) / clips,
   floored at 1. get_mm_max_tokens_per_item derives from the seq_len vLLM passes;
   _call_hf_processor reads the served max_model_len and subtracts the actual
   prompt. New asr_generation_reserve_tokens (default 8192).

3. Encoder-agnostic chunker (chunking.py): split_waveform + merge_transcripts
   (word-level overlap de-dup). ASRTranscriber.transcribe gains a self_chunks
   flag: Whisper (self_chunks=True) keeps its internal timestamp stitching;
   backends with a fixed input window route through our split/transcribe/merge.
   New config: asr_self_chunks, asr_chunk_length_s, asr_chunk_overlap_s.

Compose CLI flags and docs/AUDIO.md updated. Tests: new test_chunking.py; budget
and chunked-path tests in test_asr.py; config round-trip/validation in
test_config.py; multi-clip, budget, and flag-forwarding in test_audio_processor.py.

Already-composed checkpoints inherit the new behavior via getattr defaults; no
re-compose required (only self_chunks=False needs a config change).

Signed-off-by: aviv ron <rona@il.ibm.com>
Add support for adapter switching and configurable encoders

Signed-off-by: Aviv Ron <rona@il.ibm.com>
# Conflicts:
#	src/granite_switch/config.py
#	src/granite_switch/vllm/granite_switch_model.py
#	src/granite_switch/vllm/switch/single.py
#	tutorials/notebooks/granite_speech_demo.ipynb

Signed-off-by: aviv ron <rona@il.ibm.com>
GraniteSwitchForCausalLM.embed_input_ids annotated is_multimodal as
Optional[torch.Tensor], but the module never imports Optional. The
NameError fires at class-definition time, so `import granite_switch.vllm`
raises and vLLM's plugin loader silently skips the entry point. The
architecture is then never registered with transformers, and any attempt
to serve a granite_switch checkpoint fails with "Transformers does not
recognize this architecture".

Use the module's prevailing PEP 604 style (torch.Tensor | None) instead of
adding a typing import.

Signed-off-by: aviv ron <rona@il.ibm.com>
…check (#45) (#109)

The audio cascade truncated the transcript to a context-derived per-clip
budget (asr_generation_reserve_tokens held back for the answer). When that
reserve met or exceeded the served max_model_len, the budget floored to 1
token: the model saw no question and refused, with no error (#45).

Rather than patch the truncation math, remove it. The transcript is now
spliced into the prompt in full, as ordinary text tokens. A request whose
prompt + transcript(s) can't leave room for the answer within max_model_len
is rejected by vLLM's standard prompt-length check (HTTP 400) — the same
loud failure text-only requests already get, instead of a silent 1-token
transcript. This also makes audio behave identically to long text.

Details:
- Remove asr_generation_reserve_tokens entirely (config field + validation,
  compose CLI flag, processor accessor). It only existed to size the old
  truncation budget.
- Drop the budget param / ids[:budget] truncation in the processor; splice
  the full transcript.
- get_mm_max_tokens_per_item now reports max(1, seq_len // count) — the
  honest worst-case transcript positions one clip can occupy. This still
  sizes vLLM's encoder cache correctly (embed_multimodal emits one row per
  transcript token); it is a profiling hint, not a request bound.
- Remove the now-dead audio_token_budget helper and its tests.

Tests updated; docs/AUDIO.md rewritten to describe reject-not-truncate.

Co-authored-by: aviv ron <rona@il.ibm.com>

Signed-off-by: Bar Haim <barha@il.ibm.com>
Signed-off-by: aviv ron <rona@il.ibm.com>
* tests: cover audio/adapter coexistence, chat-template marker, empty clips, clip ceiling

Signed-off-by: BAR HAIM <barha@il.ibm.com>

* tests: add e2e vLLM audio serving smoke (text + adapter + audio x1/x2/x3)

CI-runnable serving smoke closing the #47 e2e box. Boots a real composed,
audio-enabled GraniteSwitch checkpoint under vLLM and drives text-only,
adapter-control-token, and audio x1/x2/x3 requests through one live engine.
Markers slow+requires_model+gpu (opt-in via -m); model built through the
compose CLI with --enable-audio; synthetic audio keeps it asset-free.

Verified green on an A100 with ibm-granite/granite-4.1-3b +
granitelib-core-r1.0: 5 passed.

Signed-off-by: BAR HAIM <barha@il.ibm.com>

* tests: e2e answerability adapter over an audio-delivered document (#47)

Adds the first correctness test for the "adapters + audio together" #47
box: the RAG answerability adapter judging a query against a document
supplied as speech rather than text.

The document is delivered as audio by placing a single <|audio|> marker
as the document text (documents=[{"text": "<|audio|>"}]); the Granite
template renders each document via `doc | tojson`, so the marker lands in
the <documents> block exactly where vLLM's ASR processor splices the
transcript — the document the adapter reasons over is the transcribed
speech. The <|answerability|> control token is inserted by the same
template (aLoRA fallback path), so the switch fires the adapter at the
generation prompt.

Ground truth comes from one real clip (hf-internal-testing/
librispeech_asr_dummy row 0), driving both classes without shipping a
fixture: an answerable question whose answer is spoken, and an
unanswerable one about content the clip never mentions. Both are
distinctive enough to survive ASR word-errors, so the assertion tests
the answerability decision, not transcription accuracy (WER is a
separate box). FLAC is decoded with soundfile from the raw bytes to
avoid requiring torchcodec (datasets>=4).

Where test_audio_serving_smoke.py only proves an adapter control token
doesn't crash the audio path, this proves the switch produces the
correct verdict end-to-end through a live vLLM engine. Verified on an
A100 with granite-4.1-3b + granitelib-rag-r1.0: 2 passed.

Markers slow+requires_model+gpu; opt-in via
  pytest -m "slow and requires_model and gpu"

Signed-off-by: BAR HAIM <barha@il.ibm.com>

* tests: use committed local speech clip for answerability-over-audio

Replace the runtime hf-internal-testing/librispeech_asr_dummy download with a
committed 3s 16 kHz WAV (SpeechT5, MIT-licensed) so the test runs offline and
carries clean provenance for merge-to-main. The spoken sentence states a
location that distil-whisper transcribes cleanly, so the questions key on the
location rather than the proper noun. Verdicts verified: 2 passed on A100
(granite-4.1-3b + granitelib-rag-r1.0).

Signed-off-by: BAR HAIM <barha@il.ibm.com>

* tests: sweep all default adapters route correctly with audio enabled

Adds the 'all default adapters route correctly with audio enabled' coverage for
issue #47. Composes the full default set (RAG + Core + Guardian) with
--enable-audio and asserts the switch maps each adapter_token_ids[i] to index
i+1 (pre-control positions stay on base 0), observed via the HF backend's
_last_adapter_indices. For granite-4.1-3b, 12 adapters resolve (context_relevance
has no 4.1-3b flavor); verified 12/12 route correctly on A100.

Loads with ignore_mismatched_sizes=True: the <|audio|> token bumps vocab_size
one past the switch's control_to_substitute_lut buffer, which SingleSwitch
rebuilds from config, so the freshly-built buffer is kept.

Signed-off-by: BAR HAIM <barha@il.ibm.com>

---------

Signed-off-by: BAR HAIM <barha@il.ibm.com>
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

barvhaim and others added 9 commits July 30, 2026 15:53
Add a first-class asr_dtype config field so the precision the ASR
weights load in is tunable per checkpoint instead of hardcoded.

Previously ASRTranscriber.load() always requested float16, which
crashes any encoder with BatchNorm layers ("Expected weight to have
type Float but got Half") because BatchNorm will not promote a
float16 weight against float32 features. The only escape was to
smuggle torch_dtype through asr_pipeline_kwargs, which is opaque and
undocumented.

asr_dtype accepts auto/float16/bfloat16/float32 and is validated in
GraniteSwitchConfig.__init__ so a typo fails at compose time rather
than inside a vLLM worker. None/"auto" preserves today's behavior:
float16 on CUDA, float32 elsewhere. asr_pipeline_kwargs still merges
last and therefore still wins, so existing checkpoints that use the
torch_dtype workaround are unaffected.

Also exposed as --asr-dtype on the compose CLI (implies
--enable-audio) and documented in docs/AUDIO.md.

Separately, reduce comment and docstring volume across the audio
modules and their tests. Much of it restated the code or duplicated
docs/AUDIO.md; what remains is the comments carrying information the
code cannot, such as why kwargs.update must come last and why
requires_raw_input_tokens is set.

Note tests/vllm/test_audio_processor.py: three transcriber stubs did
not accept the new dtype kwarg and failed once processor.py started
passing it. Fixed, plus two tests asserting the dtype actually
reaches get_transcriber.

Signed-off-by: BAR HAIM <barha@il.ibm.com>
audio: make ASR dtype configurable.
Allows changing the ASR dtype from config, defaults to the device default dtype
Both are merge blockers found reviewing the ASR audio cascade. Each made
well-formed audio requests fail with the same opaque vLLM error, from
different causes:

  RuntimeError: Expected there to be 1 audio prompt placeholders
  corresponding to 1 audio items, but instead found 0 prompt placeholders!

1. _hf_processor_applies_updates was left at the base implementation, which
   returns True for raw (non-embedding) items. That tells vLLM the processor
   already expanded <|audio|> itself, so vLLM skips applying our
   PromptReplacement and merely searches the prompt for the transcript ids -
   which are not there, because _call_hf_processor deliberately leaves the
   marker in place and returns the transcript out of band. Override it to
   False.

   Only the uncached path consults the hook (the cached path hardcodes
   False), so this was silently contingent on mm_processor_cache_gb, on the
   entry point, and on the vLLM version. Configuration-dependent correctness
   is worse than a hard failure. The default path is untouched.

2. A clip with no recognizable speech transcribes to "", which produced a
   zero-length replacement. vLLM discards zero-length placeholder content and
   then reports the item as missing, so silence, music, or a 200 ms clip
   returned an opaque 500. It also left engine startup dependent on what the
   ASR model does with the silent profiling clip.

   Substitute a single space when the transcript is empty or whitespace-only,
   so every audio item occupies at least one prompt position and the model
   sees an audio turn that said nothing. Done in _transcribe rather than the
   replacement callback so audio_num_tokens stays consistent with the flat
   token buffer. Raise a clear ValueError if even the fallback tokenizes to
   nothing, rather than letting vLLM's opaque error resurface.

   This also makes startup deterministic, so the silent profiling clip is
   deliberately kept - it is now the better input, since noise or a tone
   would invite a variable-length hallucinated transcript.

Tests drive vLLM's real _apply_hf_processor_text_mm and
_maybe_apply_prompt_updates with real MultiModalDataItems rather than mocking
the machinery under test, and need no GPU or ASR model. Reverting either fix
makes the corresponding tests fail with the exact production error. Four
pre-existing tests asserted the old zero-length behavior and were updated,
since they encoded the bug.

docs/AUDIO.md documents the empty-transcript policy, as it is observable.

Signed-off-by: aviv ron <rona@il.ibm.com>
The `audio` extra (soundfile, librosa) was declared but referenced by nothing:
not `dev`, not `dev-vllm20`, not `test`, not the `tutorials` extra, and not
either CI workflow. The only mention of `uv sync --extra audio` anywhere was
inside an ImportError string in asr.py.

So no documented install path produced a working audio checkpoint. A synced pod
running the integration tests failed with:

  ModuleNotFoundError: No module named 'soundfile'

in test_audio_serving_smoke.py and test_answerability_over_audio.py. This
affected `dev` (vLLM 0.19) exactly as much as `dev-vllm20` — neither carried
the extra.

Changes:
- `dev` and `dev-vllm20` now request granite-switch[hf,compose,audio]. `test`
  picks it up transitively via include-group.
- gpu-tests.yaml states `--extra audio` explicitly. Redundant with the dev
  group today, but it documents the dependency where it is used so a later
  group refactor cannot silently drop it again.
- docs/AUDIO.md gains an Installing section. `audio` is deliberately not folded
  into the `vllm` extra, since text-only vLLM users should not carry libsndfile
  and numba; that makes `--extra vllm --extra audio` the supported serving
  command, which needs saying out loud.

ci.yaml is left alone on purpose: the CPU tier installs no vLLM, so the audio
tests skip there, and tests/unit/test_asr.py deliberately exercises the
librosa-absent path.

Verified per group with `uv export`: dev, dev-vllm20 and test all now resolve
librosa==0.11.0 and soundfile==0.14.0, and both documented serving combos
(--extra vllm/vllm20 --extra audio) resolve without tripping the declared
conflicts. The uv.lock delta is only the three requires-dev entries plus an
audioread marker that simplifies as a consequence.

Signed-off-by: aviv ron <rona@il.ibm.com>
The audio tests are spread across five directories (unit, vllm, composer,
integration), and two of the files mix audio tests in with unrelated ones, so
selecting the audio tier meant listing paths plus a `-k` filter. Register an
`audio` marker and apply it so `pytest -m audio` selects all 131 of them:

- module-level `pytestmark` on the four dedicated files (test_asr,
  test_chunking, test_audio_processor, and the three integration files)
- class-level `@pytest.mark.audio` on TestAudioConfig in test_config.py and on
  the two audio classes in test_chat_template.py, so the non-audio tests in
  those files stay unselected

test_audio_processor's existing single `pytestmark` skipif becomes a list to
hold both marks.

Documented in docs/AUDIO.md: `pytest -m audio` for everything, or
`pytest -m "audio and not gpu"` for the 118-test CPU tier that runs in seconds.

No test bodies changed; the full suite still collects 1490 tests.

Signed-off-by: aviv ron <rona@il.ibm.com>
Composing with --enable-audio produced a checkpoint whose switch lookup table
was one row shorter than the config.json shipped beside it. Loading it through
the HF backend failed with an out-of-bounds embedding gather, surfacing as the
CUDA device-side assert `indexSelectSmallIndex: srcIndex < srcSelectDimSize`.

Root cause: SingleSwitch sizes the table max(config.vocab_size, max_ctrl_id + 1)
at construction. Compose builds the model from a config whose vocab_size is
copied verbatim from the base checkpoint, then grows the vocabulary in step 3
via resize_token_embeddings, which updates config.vocab_size and both embedding
matrices but leaves the buffer untouched. Without audio the construction-time
and load-time computations agree by coincidence, because compose ends with
vocab_size == max_ctrl_id + 1. The <|audio|> marker is the first token to make
vocab_size larger than that and break the tie.

The resulting mismatch is not recoverable at load time. from_pretrained discards
the stored tensor and there is no _init_weights rule for the buffer, so it is
left as uninitialised memory. Every id then reads as a control id and the
token-exchange rewrite sends out-of-range ids into the embedding gather.

Three changes:

- Rebuild the table at the end of compose step 3, after the resize, so the saved
  buffer and the shipped config agree. The sizing rule is factored out into
  build_control_to_substitute_lut() so __init__ and the new
  SingleSwitch.rebuild_control_to_substitute_lut() cannot diverge.

- Assert the invariant in validator.validate_control_lut(), called after the
  rebuild. An internally inconsistent checkpoint now fails during compose
  instead of faulting on a GPU much later, and the error names both lengths.

- Stop add_audio_token evicting the adapter control tokens. add_special_tokens
  replaces additional_special_tokens rather than extending it, and transformers
  exposes no accessor for the current list, so the marker call now re-passes the
  control tokens explicitly via keep_special_tokens. Previously, enabling audio
  silently dropped all of them from all_special_tokens and from the saved
  tokenizer_config.json. Token ids are unchanged: the marker still takes the
  next free id.

MockTokenizer in the composer tests had append semantics for add_special_tokens
and so could never have caught that eviction; it now mirrors the replace
behaviour of the real tokenizer.

The vLLM switch keeps its own copy of the sizing expression and is deliberately
untouched: it never resizes embeddings and never writes checkpoints, and
importing from the HF backend would couple two independently installable extras.

Only newly composed checkpoints are fixed. Existing audio checkpoints still ship
a stale table and need a re-compose; they now fail clearly at from_pretrained
rather than faulting on the GPU.

Tests: 158 unit, 565 hf, 154 composer. The save/load round-trip test was
verified to fail without the rebuild, reproducing the original mismatch report.

Signed-off-by: aviv ron <rona@il.ibm.com>
…t was failing and was a problematic test. we should not test inference as it is unstable and not deterministic

Signed-off-by: aviv ron <rona@il.ibm.com>
Signed-off-by: aviv ron <rona@il.ibm.com>
…prompt-placeholder-invariants

Fixes three defects in the ASR audio cascade, plus the packaging gap that blocked testing them.
Brings in the self-hosted runner GPU test workflow (#115): comment-driven
test runs gated on admin/maintainer role, with results posted as sticky PR
comments.

Conflict in .github/workflows/gpu-tests.yaml resolved in favor of main.
The asr side's setup-uv + 'uv sync --extra audio' step is obsolete under
main's design, where the helper scripts and environment are baked into the
runner image at /opt/gsw rather than installed per run. Audio coverage is
preserved as a first-class suite scope selected by marker.

Signed-off-by: aviv ron <rona@il.ibm.com>
@aviv1ron1

Copy link
Copy Markdown
Collaborator Author

/gpu-test-dev

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants