NVIDIA-NeMo/Speech · #16505

fix(speechlm2): find vLLM 0.33's chat parser for the prompt contract

PhilflowIO · merged Nov 19, 20262 files · 107 + / 12 −
nemo/collections/speechlm2/vllm/salm/runtime_compat.py37 + / 8 −
@@ -127,12 +127,20 @@ def _canonicalize_speechlm_parts(parts: Iterable[Any]) -> list[Any]:     return [*audio_parts, {"type": "text", "text": canonical_text}]  -def _patch_speechlm_training_prompt_contract(chat_utils: Any) -> None:-    """Install an idempotent, SpeechLM-only exact prompt adapter."""-    original = getattr(chat_utils, "_parse_chat_message_content_parts", None)+_LEGACY_PARSER_NAME = "_parse_chat_message_content_parts"+_PUBLIC_PARSER_NAME = "parse_chat_message_content_parts"+++def _patch_speechlm_training_prompt_contract(chat_utils: Any, parser_name: str = _LEGACY_PARSER_NAME) -> None:+    """Install an idempotent, SpeechLM-only exact prompt adapter.++    ``parser_name`` is the attribute of ``chat_utils`` that vLLM's chat path+    resolves the content-part parser through (see ``_locate_chat_parser``).+    """+    original = getattr(chat_utils, parser_name, None)     if not callable(original):         raise TypeError(-            "Unsupported vLLM chat API: _parse_chat_message_content_parts is missing. "+            f"Unsupported vLLM chat API: {parser_name} is missing. "             "Update the NeMo SpeechLM compatibility adapter before serving."         )     if getattr(original, "_nemo_speechlm_exact_training_prompt", False):@@ -176,14 +184,35 @@ def _parse_chat_message_content_parts(         )      _parse_chat_message_content_parts._nemo_speechlm_exact_training_prompt = True-    chat_utils._parse_chat_message_content_parts = _parse_chat_message_content_parts+    setattr(chat_utils, parser_name, _parse_chat_message_content_parts)  -def install_prompt_contract() -> None:-    """Install the SpeechLM-only vLLM chat rendering adapter."""+def _locate_chat_parser() -> tuple[Any, str]:+    """Return the module and attribute through which vLLM's chat path finds the content-part parser.++    The parser keeps its signature across releases but has moved twice:++    * vLLM 0.33 split ``vllm.renderers.chat_utils`` into a package and made the+      parser public as ``chat_message.parse_chat_message_content_parts``;+      ``parse_chat_message_content`` calls it as a global of ``chat_message``, so+      that module is the one to patch (the package re-export is a separate name).+    * vLLM 0.32 has ``vllm.renderers.chat_utils._parse_chat_message_content_parts``.+    * Earlier releases have ``vllm.entrypoints.chat_utils._parse_chat_message_content_parts``.+    """+    try:+        from vllm.renderers.chat_utils import chat_message  # vLLM >= 0.33+    except ImportError:+        chat_message = None+    if callable(getattr(chat_message, _PUBLIC_PARSER_NAME, None)):+        return chat_message, _PUBLIC_PARSER_NAME+     try:         from vllm.renderers import chat_utils  # vLLM 0.32     except ImportError:         from vllm.entrypoints import chat_utils+    return chat_utils, _LEGACY_PARSER_NAME -    _patch_speechlm_training_prompt_contract(chat_utils)++def install_prompt_contract() -> None:+    """Install the SpeechLM-only vLLM chat rendering adapter."""+    _patch_speechlm_training_prompt_contract(*_locate_chat_parser())
tests/collections/speechlm2/test_vllm_runtime_compat.py70 + / 4 −
@@ -37,7 +37,7 @@ def _part_type(part):     return part.get("type") or ("audio_url" if "audio_url" in part else None)  -def _fake_vllm_chat_utils():+def _fake_vllm_chat_utils(parser_name="_parse_chat_message_content_parts"):     """Model vLLM 0.23's non-interleaved placeholder assembly."""     calls = [] @@ -72,7 +72,7 @@ def parse(         )         return [{"role": role, "content": rendered}] -    return SimpleNamespace(_parse_chat_message_content_parts=parse), calls+    return SimpleNamespace(**{parser_name: parse}), calls   def _parse(chat_utils, parts, model_type="nemo_speechlm", **kwargs):@@ -235,21 +235,87 @@ def test_adapter_is_idempotent_and_fails_closed_on_vllm_api_change():         _patch_speechlm_training_prompt_contract(SimpleNamespace())  -def test_install_prompt_contract_patches_vllm_renderers_chat_utils(monkeypatch):+@pytest.fixture(params=[False, True], ids=["clean-cache", "0.33-parser-cached"])+def preloaded_public_parser(request, monkeypatch):+    """Optionally leave a vLLM 0.33 parser in ``sys.modules``, as plugin registration does.++    Python returns a cached child module even when the parent is mocked away, so the+    legacy-layout tests must block modern discovery themselves rather than rely on+    the parent mock. Yields the cached public module (or ``None``) so a test can+    assert it was left untouched.+    """+    if not request.param:+        yield None+        return+    public, _ = _fake_vllm_chat_utils("parse_chat_message_content_parts")+    original = public.parse_chat_message_content_parts+    monkeypatch.setitem(sys.modules, "vllm.renderers.chat_utils", SimpleNamespace(chat_message=public))+    yield public+    assert public.parse_chat_message_content_parts is original+++def _simulate_legacy_layout(monkeypatch):+    """Hide vLLM 0.33's parser package so discovery falls through to the legacy names."""+    monkeypatch.setitem(sys.modules, "vllm.renderers.chat_utils", None)+++def test_install_prompt_contract_patches_vllm_renderers_chat_utils(monkeypatch, preloaded_public_parser):     """vLLM 0.32 moved the chat parser to ``vllm.renderers.chat_utils``."""     chat_utils, _ = _fake_vllm_chat_utils()     monkeypatch.setitem(sys.modules, "vllm.renderers", SimpleNamespace(chat_utils=chat_utils))+    _simulate_legacy_layout(monkeypatch)      install_prompt_contract()      assert chat_utils._parse_chat_message_content_parts._nemo_speechlm_exact_training_prompt  -def test_install_prompt_contract_falls_back_to_vllm_entrypoints_chat_utils(monkeypatch):+def test_install_prompt_contract_falls_back_to_vllm_entrypoints_chat_utils(monkeypatch, preloaded_public_parser):     chat_utils, _ = _fake_vllm_chat_utils()     monkeypatch.setitem(sys.modules, "vllm.renderers", None)     monkeypatch.setitem(sys.modules, "vllm.entrypoints", SimpleNamespace(chat_utils=chat_utils))+    _simulate_legacy_layout(monkeypatch)      install_prompt_contract()      assert chat_utils._parse_chat_message_content_parts._nemo_speechlm_exact_training_prompt+++def test_install_prompt_contract_patches_vllm_0_33_chat_message(monkeypatch):+    """vLLM 0.33 made ``vllm.renderers.chat_utils`` a package with a public parser in ``chat_message``."""+    chat_message, calls = _fake_vllm_chat_utils("parse_chat_message_content_parts")+    # The 0.33 package re-exports the public parser but no longer has the private 0.32 name.+    package = SimpleNamespace(chat_message=chat_message, parse_chat_message_content_parts=object())+    monkeypatch.setitem(sys.modules, "vllm.renderers.chat_utils", package)+    monkeypatch.setitem(sys.modules, "vllm.renderers", SimpleNamespace(chat_utils=package))++    install_prompt_contract()++    parser = chat_message.parse_chat_message_content_parts+    assert parser._nemo_speechlm_exact_training_prompt+    assert not hasattr(package, "_parse_chat_message_content_parts")+    result = parser(+        "user",+        [_AUDIO, {"type": "text", "text": "Transcribe"}],+        _tracker("nemotron3_5_transcribe_mtp"),+        wrap_dicts=False,+        interleave_strings=False,+    )+    assert result == [{"role": "user", "content": "Transcribe <|audio|>"}]+    assert calls[0]["registered_audio_parts"] == [_AUDIO]+++def test_install_prompt_contract_is_idempotent_on_vllm_0_33(monkeypatch):+    chat_message, _ = _fake_vllm_chat_utils("parse_chat_message_content_parts")+    monkeypatch.setitem(sys.modules, "vllm.renderers.chat_utils", SimpleNamespace(chat_message=chat_message))++    install_prompt_contract()+    patched = chat_message.parse_chat_message_content_parts+    install_prompt_contract()++    assert chat_message.parse_chat_message_content_parts is patched+++def test_adapter_names_the_missing_public_parser():+    with pytest.raises(TypeError, match="parse_chat_message_content_parts is missing"):+        _patch_speechlm_training_prompt_contract(SimpleNamespace(), "parse_chat_message_content_parts")