{"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: LMCache/LMCache\nPull request: [Bugfix] Skip PD transfer for local requests in PDBackendAsync\nLabels: full\nFiles changed (2): lmcache/v1/storage_backend/pd_backend_async.py, tests/v1/storage_backend/test_pd_backend_async.py\n\n## Description (results removed)\n\nSkip the transfer when `transfer_spec` is `None`, as `PDBackend.batched_submit_put_task` already does. The storage manager still drops its references after the call, so the buffers are freed.\n\nFixes #5777\n\n**If applicable**:\n\n## Diff\n\n```diff\ndiff --git a/lmcache/v1/storage_backend/pd_backend_async.py b/lmcache/v1/storage_backend/pd_backend_async.py\nindex 31272f68dd6..4cff62eec95 100644\n--- a/lmcache/v1/storage_backend/pd_backend_async.py\n+++ b/lmcache/v1/storage_backend/pd_backend_async.py\n@@ -1059,8 +1059,14 @@ def batched_submit_put_task(\n :param keys: Cache keys for this batch.\n :param memory_objs: Memory objects to transfer.\n :param transfer_spec: Transfer specification (carries req_id, etc.).\n+ ``None`` for local requests, which are not transferred.\n :param on_complete_callback: Optional per-key completion callback.\n \"\"\"\n+ # Skip PD transfer for local requests (no transfer_spec), as PDBackend\n+ # does. Requests without kv_transfer_params have no disagg_spec.\n+ if transfer_spec is None:\n+ return\n+\n for mem_obj in memory_objs:\n mem_obj.ref_count_up()\n \ndiff --git a/tests/v1/storage_backend/test_pd_backend_async.py b/tests/v1/storage_backend/test_pd_backend_async.py\nindex c2d5a29d186..919947fe815 100644\n--- a/tests/v1/storage_backend/test_pd_backend_async.py\n+++ b/tests/v1/storage_backend/test_pd_backend_async.py\n@@ -285,6 +285,14 @@ def cb(key):\n assert ev.wait(timeout=timeout), f\"req-{i} did not complete\"\n \n \n+def test_sender_skips_request_without_transfer_spec(async_sender):\n+ \"\"\"A request without transfer_spec is local and is not transferred.\"\"\"\n+ mem_obj = _make_mem_obj()\n+ async_sender.batched_submit_put_task([_make_key(0)], [mem_obj], transfer_spec=None)\n+ mem_obj.ref_count_up.assert_not_called()\n+ assert mem_obj.get_ref_count() == 1\n+\n+\n def test_sender_flow_control_backpressure(async_sender):\n \"\"\"allocate() blocks when staging buffer is physically full, unblocks on notify.\"\"\"\n sentinel = _make_mem_obj(idx=77)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: LMCache/LMCache\nPull request: [good-second-issue] cli: fix trace replay percentile off-by-one (#4416)\nLabels: full, good second issue, skip expensive ci\nFiles changed (2): lmcache/cli/commands/trace/_stats.py, tests/cli/commands/trace/test_stats.py\n\n## Description (results removed)\n\nFix the nearest-rank percentile off-by-one in `_percentile()`.\n\nThe function treated the 1-based rank `ceil(p * N / 100)` as a 0-based index, so whenever `p * N / 100` landed on a whole number it returned one sample too high (p90/p99 reported the max). It also divided before multiplying, which made `(7 / 100.0) * 100` land on `7.000000000000001` and bump the rank by one.\n\nChanges:\n- Compute the 0-based index as `ceil(p * N / 100) - 1`, multiplying before dividing to keep integer percentiles exact.\n- Fix the existing test that encoded the off-by-one.\n\nVerification:\n- Confirmed the fixed helper returns p50=50, p99=99, p7=7, p90-of-10=9 via direct module import.\n\nCloses #4416\nRefs #5751\n\n## Diff\n\n```diff\ndiff --git a/lmcache/cli/commands/trace/_stats.py b/lmcache/cli/commands/trace/_stats.py\nindex e6151da7343..0b3bcd8741c 100644\n--- a/lmcache/cli/commands/trace/_stats.py\n+++ b/lmcache/cli/commands/trace/_stats.py\n@@ -22,6 +22,7 @@\n from dataclasses import dataclass, field\n import csv\n import json\n+import math\n import statistics\n import threading\n \n@@ -88,10 +89,11 @@ def _percentile(sorted_values: list[float], pct: float) -> float:\n return sorted_values[0]\n if pct >= 100:\n return sorted_values[-1]\n- # bisect_left gives the insertion index; the nearest-rank formula\n- # maps p to ceil(p/100 * N) which equals floor((p/100 * N - eps) + 1).\n+ # Nearest-rank: p maps to the 1-based rank ceil(p * N / 100), so the\n+ # 0-based index is ceil(p * N / 100) - 1. Multiply before dividing\n+ # so integer percentiles land exactly on a whole rank.\n n = len(sorted_values)\n- idx = max(0, min(n - 1, int((pct / 100.0) * n)))\n+ idx = max(0, min(n - 1, math.ceil((pct * n) / 100.0) - 1))\n return sorted_values[idx]\n \n \ndiff --git a/tests/cli/commands/trace/test_stats.py b/tests/cli/commands/trace/test_stats.py\nindex f7ccc8007ef..6004b0204cb 100644\n--- a/tests/cli/commands/trace/test_stats.py\n+++ b/tests/cli/commands/trace/test_stats.py\n@@ -29,8 +29,21 @@ def test_p100_returns_max(self):\n \n def test_p50_on_100_values(self):\n vals = [float(i) for i in range(1, 101)]\n- # nearest-rank with floor((50/100)*100)=50 → index 50 → value 51\n- assert _percentile(vals, 50) == 51.0\n+ # nearest-rank: ceil(50/100 * 100) = 50 → index 49 → value 50\n+ assert _percentile(vals, 50) == 50.0\n+\n+ def test_whole_rank_percentiles_are_not_off_by_one(self):\n+ vals = [float(i) for i in range(1, 101)]\n+ # ceil(99/100 * 100) = 99 → index 98 → value 99 (not the max)\n+ assert _percentile(vals, 99) == 99.0\n+ # p90 of ten samples is the ninth value\n+ assert _percentile([float(i) for i in range(1, 11)], 90) == 9.0\n+\n+ def test_inexact_division_rounds_to_correct_rank(self):\n+ vals = [float(i) for i in range(1, 101)]\n+ # (7 / 100.0) * 100 == 7.000000000000001, which must still map to\n+ # rank 7 (index 6 → value 7), not rank 8.\n+ assert _percentile(vals, 7) == 7.0\n \n \n class TestReplayStatsCollector:\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: LMCache/LMCache\nPull request: [Bugfix] S3 L2 adapter: bounds-check GET bodies and treat a wrong-sized object as a miss\nLabels: full\nFiles changed (3): docs/source/mp/l2_storage/s3.rst, lmcache/v1/distributed/l2_adapters/s3_l2_adapter.py, tests/v1/distributed/test_s3_l2_adapter.py\n\n## Description (results removed)\n\nThe fix stays in the load path, where the destination size is known:\n\n1. Before the GET: a cached object size (from this adapter's own store, or from HEAD at lookup) that differs from `obj.get_size()` makes the key a miss; nothing is transferred.\n3. After the GET: the load bit is set only when the bytes copied equal `obj.get_size()`.\n\nNone of this is in `on_done`: the CRT completes `finished_future`, which `_execute_load` awaits, before calling `on_done`, so an error raised there cannot change the result (#3832's guard has this problem, as @JiataiWang noted there).\n\nFixes #3831. Supersedes #3832; happy to close this one if @HaozheZhang6 prefers to update that PR.\n\n- Policy is exact size or miss, as in valkey and bigtable (fs rejects short reads only). The rule is stated in the class docstring and on the adapter's documentation page (`docs/source/mp/l2_storage/s3.rst`). The serdes on the wrapper path (FP8, AES-GCM, TurboQuant) produce exact sizes, so nothing in tree changes. A custom serializer whose `estimate_serialized_size` is a strict upper bound would now miss on S3, as it already does on valkey. The adapter cannot tell a required length from an allocation; letting adapters report the delivered length for the format to validate is an interface change I would propose separately, or here if you prefer.\n\n**If applicable**:\n\n## Diff\n\n```diff\ndiff --git a/lmcache/v1/distributed/l2_adapters/s3_l2_adapter.py b/lmcache/v1/distributed/l2_adapters/s3_l2_adapter.py\nindex 4ce2cd7bd11..0d6aa8cd7aa 100644\n--- a/lmcache/v1/distributed/l2_adapters/s3_l2_adapter.py\n+++ b/lmcache/v1/distributed/l2_adapters/s3_l2_adapter.py\n@@ -445,6 +445,12 @@ class S3L2Adapter(L2AdapterInterface):\n connection-class errors, ``connection_disabled`` is set; all\n subsequent submits short-circuit and record failure without\n touching S3.\n+\n+ Load sizes: a key counts as loaded only when the object delivered\n+ exactly ``obj.get_size()`` bytes. A GET body that would run past the\n+ destination is refused before the copy, and a shorter object is a\n+ miss, as in the valkey and fs adapters. The object on S3 is left\n+ alone; the adapter only forgets its cached size for that key.\n \"\"\"\n \n max_connection_failures = 3\n@@ -881,10 +887,30 @@ def on_headers(status_code, headers, **kwargs):\n def _get_request(self, key_str: str, mem_obj: MemoryObj):\n req = self._make_request(\"GET\", key_str)\n data_ptr = mem_obj.data_ptr\n+ capacity = mem_obj.get_size()\n+ # Bytes copied into ``mem_obj`` so far. ``_execute_load`` compares\n+ # the total with the destination size once the transfer is over.\n+ # The comparison cannot live in ``on_done``: the CRT completes\n+ # ``finished_future`` (which ``_execute_load`` awaits) before it\n+ # invokes ``on_done``, so an error raised there arrives too late\n+ # to change the load result.\n+ progress = {\"received\": 0}\n \n def on_body(chunk, offset, **kwargs):\n+ n = len(chunk)\n+ if offset < 0 or offset + n > capacity:\n+ # Never write outside the caller's buffer. Raising here\n+ # makes the CRT abort the transfer and surface the error\n+ # through ``finished_future``, so the key is reported as\n+ # a miss and nothing past ``capacity`` is touched.\n+ raise RuntimeError(\n+ f\"S3 GET for {key_str} returned bytes outside the \"\n+ f\"destination buffer: offset={offset} len={n} \"\n+ f\"capacity={capacity}\"\n+ )\n # Write chunk into the caller-provided MemoryObj buffer.\n- ctypes.memmove(data_ptr + offset, chunk, len(chunk))\n+ ctypes.memmove(data_ptr + offset, chunk, n)\n+ progress[\"received\"] += n\n \n def on_done(error=None, status_code=None, **kwargs):\n ok = (status_code in (200, 206)) or (status_code is None and error is None)\n@@ -902,7 +928,7 @@ def on_done(error=None, status_code=None, **kwargs):\n credential_provider=self._credentials_provider,\n region=self._region,\n )\n- return s3_req\n+ return s3_req, progress\n \n def _put_request(self, key_str: str, mem_obj: MemoryObj):\n stream = MemoryViewStream(mem_obj.byte_array)\n@@ -1207,14 +1233,34 @@ async def _execute_load(\n ) -> None:\n bitmap = Bitmap(len(keys))\n futures = []\n- launched_indices = []\n+ # (index, key string, expected byte count, GET progress) per GET.\n+ launched: list[tuple[int, str, int, dict]] = []\n \n for i, (key, obj) in enumerate(zip(keys, objects, strict=True)):\n try:\n key_str = _object_key_to_string(key)\n- s3_req = self._get_request(key_str, obj)\n+ expected = obj.get_size()\n+ with self._lock:\n+ cached_size = self._object_size_cache.get(key_str)\n+ if cached_size is not None and cached_size != expected:\n+ # The object on S3 is not the size this load expects:\n+ # written under another layout or serde, or truncated.\n+ # Reading it would fill the destination with the wrong\n+ # bytes, so report a miss and forget the cached size so\n+ # that a later lookup asks S3 again.\n+ logger.warning(\n+ \"S3L2Adapter: object %s is %d bytes on S3 but the \"\n+ \"load expects %d; treating it as a miss\",\n+ key_str,\n+ cached_size,\n+ expected,\n+ )\n+ with self._lock:\n+ self._object_size_cache.pop(key_str, None)\n+ continue\n+ s3_req, progress = self._get_request(key_str, obj)\n futures.append(asyncio.wrap_future(s3_req.finished_future))\n- launched_indices.append(i)\n+ launched.append((i, key_str, expected, progress))\n except Exception:\n logger.exception(\"S3L2Adapter failed to launch GET\")\n \n@@ -1222,9 +1268,32 @@ async def _execute_load(\n last_error: Optional[str] = None\n any_success = False\n \n- for idx, result in zip(launched_indices, results, strict=True):\n+ for (idx, key_str, expected, progress), result in zip(\n+ launched, results, strict=True\n+ ):\n if isinstance(result, Exception):\n last_error = str(result)\n+ # Whatever failed, the cached size is no longer trustworthy\n+ # (the object may have grown or vanished): forget it so the\n+ # next lookup asks S3 instead of launching the same GET.\n+ with self._lock:\n+ self._object_size_cache.pop(key_str, None)\n+ continue\n+ received = progress[\"received\"]\n+ if received != expected:\n+ # The transfer completed but delivered fewer bytes than the\n+ # destination holds (more is rejected in ``on_body``). The\n+ # buffer is only partly written, so this is a miss, as in\n+ # the valkey adapter, not a hit with a stale tail.\n+ logger.warning(\n+ \"S3L2Adapter: GET for %s delivered %d bytes, expected %d; \"\n+ \"treating it as a miss\",\n+ key_str,\n+ received,\n+ expected,\n+ )\n+ with self._lock:\n+ self._object_size_cache.pop(key_str, None)\n continue\n bitmap.set(idx)\n any_success = True\ndiff --git a/tests/v1/distributed/test_s3_l2_adapter.py b/tests/v1/distributed/test_s3_l2_adapter.py\nindex b58a363a1c0..34ce3768740 100644\n--- a/tests/v1/distributed/test_s3_l2_adapter.py\n+++ b/tests/v1/distributed/test_s3_l2_adapter.py\n@@ -48,6 +48,9 @@ def __init__(self):\n # When non-None, every request raises with this message\n # (used to simulate network failures for the circuit-breaker test).\n self._inject_error: str | None = None\n+ # When set, GET bodies are delivered in pieces of this many bytes\n+ # at increasing offsets, as a ranged GET would.\n+ self._get_chunk_size: int | None = None\n self._put_count = 0\n self._get_count = 0\n self._delete_count = 0\n@@ -57,6 +60,7 @@ def reset(self):\n with self._lock:\n self._data.clear()\n self._inject_error = None\n+ self._get_chunk_size = None\n self._put_count = self._get_count = 0\n self._delete_count = self._head_count = 0\n \n@@ -80,6 +84,14 @@ def set_error(self, msg: str | None):\n with self._lock:\n self._inject_error = msg\n \n+ def set_get_chunk_size(self, n: int | None):\n+ with self._lock:\n+ self._get_chunk_size = n\n+\n+ def get_chunk_size(self) -> int | None:\n+ with self._lock:\n+ return self._get_chunk_size\n+\n def counts(self) -> dict[str, int]:\n with self._lock:\n return {\n@@ -155,12 +167,25 @@ def _parse_list_query(path: str) -> tuple[str | None, int, str | None]:\n return prefix, max_keys, cont\n \n \n+def _call_on_done(on_done, **kwargs) -> None:\n+ \"\"\"Invoke ``on_done`` the way the CRT does: after ``finished_future``\n+ is settled, with any exception it raises dropped, never propagated.\n+ A check that lives in ``on_done`` therefore cannot fail a request.\"\"\"\n+ if on_done is None:\n+ return\n+ try:\n+ on_done(**kwargs)\n+ except Exception:\n+ pass\n+\n+\n class _FakeS3Request:\n \"\"\"In-process substitute for awscrt.s3.S3Request.\n \n Dispatches by HTTP method + operation_name against ``_BACKEND`` and\n- fires the on_headers / on_body / on_done callbacks that the real CRT\n- would invoke, then completes the finished_future.\n+ fires the on_headers / on_body callbacks that the real CRT would\n+ invoke, then settles ``finished_future`` and only then calls\n+ ``on_done``, in the CRT's order.\n \"\"\"\n \n def __init__(\n@@ -199,9 +224,8 @@ def __init__(\n on_headers(200, [(\"content-type\", \"application/xml\")])\n if on_body is not None:\n on_body(xml, 0)\n- if on_done is not None:\n- on_done(error=None, status_code=200)\n self.finished_future.set_result(None)\n+ _call_on_done(on_done, error=None, status_code=200)\n except Exception as e:\n if not self.finished_future.done():\n self.finished_future.set_exception(e)\n@@ -225,29 +249,28 @@ def __init__(\n _BACKEND._put_count += 1\n if on_headers is not None:\n on_headers(200, [])\n- if on_done is not None:\n- on_done(error=None, status_code=200)\n self.finished_future.set_result(None)\n+ _call_on_done(on_done, error=None, status_code=200)\n \n elif method == \"GET\":\n with _BACKEND._lock:\n _BACKEND._get_count += 1\n data = _BACKEND.get(key_str)\n if data is None:\n- if on_done is not None:\n- try:\n- on_done(error=None, status_code=404)\n- except Exception:\n- pass\n self.finished_future.set_exception(\n RuntimeError(f\"S3 GET 404 for {key_str}\")\n )\n+ _call_on_done(on_done, error=None, status_code=404)\n return\n if on_body is not None:\n- on_body(data, 0)\n- if on_done is not None:\n- on_done(error=None, status_code=200)\n+ step = _BACKEND.get_chunk_size() or max(len(data), 1)\n+ for off in range(0, len(data), step):\n+ on_body(data[off : off + step], off)\n+ # The CRT completes ``finished_future`` before it invokes\n+ # ``on_done``: an exception raised in ``on_done`` cannot\n+ # fail a request that has already been reported done.\n self.finished_future.set_result(None)\n+ _call_on_done(on_done, error=None, status_code=200)\n \n elif method == \"HEAD\":\n with _BACKEND._lock:\n@@ -270,9 +293,8 @@ def __init__(\n _BACKEND.delete(key_str)\n if on_headers is not None:\n on_headers(204, [])\n- if on_done is not None:\n- on_done(error=None, status_code=204)\n self.finished_future.set_result(None)\n+ _call_on_done(on_done, error=None, status_code=204)\n \n else:\n self.finished_future.set_exception(\n@@ -280,13 +302,9 @@ def __init__(\n )\n \n except Exception as e:\n- try:\n- if on_done is not None:\n- on_done(error=str(e), status_code=None)\n- except Exception:\n- pass\n if not self.finished_future.done():\n self.finished_future.set_exception(e)\n+ _call_on_done(on_done, error=str(e), status_code=None)\n \n \n class _FakeHttpRequest:\n@@ -350,6 +368,26 @@ def create_memory_obj(size: int = 16, fill_value: float = 1.0) -> TensorMemoryOb\n return TensorMemoryObj(raw_data, metadata, parent_allocator=None)\n \n \n+def create_guarded_memory_obj(\n+ size: int = 16, guard_value: float = -1.0\n+) -> tuple[TensorMemoryObj, torch.Tensor]:\n+ \"\"\"A MemoryObj over the first ``size`` float32 elements of a tensor\n+ twice that long. The second half is a sentinel: a copy that runs past\n+ the logical buffer lands there, where the test can see it, instead of\n+ in unrelated memory. Returns the object and the sentinel view.\"\"\"\n+ backing = torch.full((size * 2,), guard_value, dtype=torch.float32)\n+ metadata = MemoryObjMetadata(\n+ shape=torch.Size([size]),\n+ dtype=torch.float32,\n+ address=0,\n+ phy_size=size * 4,\n+ fmt=MemoryFormat.KV_2LTD,\n+ ref_count=1,\n+ )\n+ obj = TensorMemoryObj(backing[:size], metadata, parent_allocator=None)\n+ return obj, backing[size:]\n+\n+\n def wait_for_event_fd(event_fd: int, timeout: float = 5.0) -> bool:\n poll = select.poll()\n poll.register(event_fd, select.POLLIN)\n@@ -520,6 +558,128 @@ def test_query_lookup_returns_none_after_pop(self, adapter):\n assert adapter.query_lookup_and_lock_result(tid) is None\n \n \n+# =============================================================================\n+# Size validation on load\n+# =============================================================================\n+\n+\n+class TestLoadSizeValidation:\n+ \"\"\"The store is not trusted to hold objects of the expected size.\n+\n+ A GET must never write outside the destination buffer, and a load\n+ is a hit only when exactly the destination's byte count arrived.\n+ \"\"\"\n+\n+ @staticmethod\n+ def _store(adapter, key, obj) -> None:\n+ tid = adapter.submit_store_task([key], [obj])\n+ assert wait_for_event_fd(adapter.get_store_event_fd())\n+ assert adapter.pop_completed_store_tasks()[tid].is_successful()\n+\n+ @staticmethod\n+ def _load(adapter, keys, dsts):\n+ tid = adapter.submit_load_task(keys, dsts)\n+ assert wait_for_event_fd(adapter.get_load_event_fd())\n+ bm = adapter.query_load_result(tid)\n+ assert bm is not None\n+ return bm\n+\n+ @staticmethod\n+ def _replace_object(key, data: bytes) -> str:\n+ key_str = s3mod._object_key_to_string(key)\n+ _BACKEND.put(key_str, data)\n+ return key_str\n+\n+ def test_short_object_is_a_miss(self, adapter):\n+ # Stored at the right size, then replaced on the store by a\n+ # shorter object under the same key. The cached size still says\n+ # the object is complete, so the GET is issued and delivers half.\n+ key = create_object_key(1)\n+ self._store(adapter, key, create_memory_obj(fill_value=3.14))\n+ data = _BACKEND.get(s3mod._object_key_to_string(key))\n+ assert data is not None\n+ key_str = self._replace_object(key, data[: len(data) // 2])\n+\n+ bm = self._load(adapter, [key], [create_memory_obj(fill_value=0.0)])\n+ assert bm.test(0) is False\n+ # The size cache no longer vouches for the key, so the next\n+ # lookup asks S3 again instead of repeating the failed load.\n+ assert key_str not in adapter._object_size_cache\n+\n+ def test_mismatching_cached_size_skips_the_get(self, adapter):\n+ # A fresh adapter learns the size from HEAD during lookup; the\n+ # load then sees it disagrees with the destination and does not\n+ # transfer anything.\n+ key = create_object_key(2)\n+ dst = create_memory_obj(fill_value=0.0)\n+ self._replace_object(key, b\"\\x55\" * (dst.get_size() // 2))\n+\n+ tid = adapter.submit_lookup_and_lock_task([key], {0: _EMPTY_LAYOUT})\n+ assert wait_for_event_fd(adapter.get_lookup_and_lock_event_fd())\n+ lookup_bm = adapter.query_lookup_and_lock_result(tid)\n+ assert lookup_bm is not None and lookup_bm.test(0) is True\n+\n+ gets_before = _BACKEND.counts()[\"get\"]\n+ bm = self._load(adapter, [key], [dst])\n+ assert bm.test(0) is False\n+ assert _BACKEND.counts()[\"get\"] == gets_before\n+ assert torch.all(dst.tensor == 0.0)\n+\n+ def test_oversized_object_is_rejected_before_any_copy(self, adapter):\n+ # No cached size, so the GET is issued; the body is twice the\n+ # destination and arrives in one callback. It must be refused\n+ # before the first memmove: neither the buffer nor the guard\n+ # region after it may change.\n+ key = create_object_key(3)\n+ dst, guard = create_guarded_memory_obj()\n+ self._replace_object(key, b\"\\x7f\" * (dst.get_size() * 2))\n+\n+ bm = self._load(adapter, [key], [dst])\n+ assert bm.test(0) is False\n+ assert torch.all(dst.tensor == -1.0)\n+ assert torch.all(guard == -1.0)\n+\n+ def test_oversized_object_in_a_later_callback(self, adapter):\n+ # The object grew after this adapter cached its size, so the\n+ # size check before the GET passes and the body arrives in three\n+ # pieces; the third would cross the end of the destination.\n+ key = create_object_key(4)\n+ dst, guard = create_guarded_memory_obj()\n+ capacity = dst.get_size()\n+ self._store(adapter, key, create_memory_obj(fill_value=2.0))\n+ key_str = self._replace_object(key, b\"\\x7f\" * (capacity * 3 // 2))\n+ _BACKEND.set_get_chunk_size(capacity // 2)\n+\n+ bm = self._load(adapter, [key], [dst])\n+ assert bm.test(0) is False\n+ assert torch.all(guard == -1.0)\n+ assert key_str not in adapter._object_size_cache\n+\n+ def test_fragmented_delivery_of_a_complete_object_is_a_hit(self, adapter):\n+ key = create_object_key(5)\n+ self._store(adapter, key, create_memory_obj(fill_value=1.5))\n+ dst = create_memory_obj(fill_value=0.0)\n+ _BACKEND.set_get_chunk_size(24) # 64 bytes -> offsets 0, 24, 48\n+\n+ bm = self._load(adapter, [key], [dst])\n+ assert bm.test(0) is True\n+ assert torch.all(dst.tensor == 1.5)\n+\n+ def test_only_the_wrong_sized_key_misses(self, adapter):\n+ keys = [create_object_key(i) for i in (10, 11, 12)]\n+ for key in keys:\n+ self._store(adapter, key, create_memory_obj(fill_value=1.0))\n+ data = _BACKEND.get(s3mod._object_key_to_string(keys[1]))\n+ assert data is not None\n+ self._replace_object(keys[1], data[:8])\n+\n+ dsts = [create_memory_obj(fill_value=0.0) for _ in keys]\n+ bm = self._load(adapter, keys, dsts)\n+ assert (bm.test(0), bm.test(1), bm.test(2)) == (True, False, True)\n+ assert torch.all(dsts[0].tensor == 1.0)\n+ assert torch.all(dsts[2].tensor == 1.0)\n+\n+\n # =============================================================================\n # Eviction (delete + locking)\n # =============================================================================\n\n[1 documentation file diff(s) omitted]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: LMCache/LMCache\nPull request: [Bugfix][MP] Carry the model revision as an lmcache.tag identity tag\nLabels: full\nFiles changed (3): docs/source/mp/configuration.rst, lmcache/integration/vllm/lmcache_mp_connector.py, tests/v1/test_mp_cache_model_identity.py\n\n## Description (results removed)\n\nFixes #6253\n\n`--revision` changes the KV bytes for the same token prefix, but it was not part of the cache\nidentity: chunk hashes cover token ids only and the object key carried the model name, so two\nengines serving one model ID at different revisions shared objects and the second one read KV\ncomputed by the first one's weights (#6253).\n\nThe connector now adds the resolved revision to the request configuration as\n`lmcache.tag.revision=`. Everything else comes from #6199: `get_request_tags` turns\n`lmcache.tag.*` entries into `ObjectKeyIdentity.tags` for both the flat and the grouped key\nexpanders, so the revision separates objects in L1 and in the L2 key format. `model_name` keeps\nmeaning the served model, and no wire field is added.\n\nEngines that do not pin `--revision` add no tag — vLLM resolves the default branch to a commit for\nevery Hub model, and tracking that would rename every existing cache namespace on upgrade — so their\ncaches keep hitting.\n\n- Engine revision wins over a request-supplied `lmcache.tag.revision`: a stale value would write\n objects under a revision that is not serving them. The conflict is logged.\n- Revision resolution uses `ResolvedRevision.resolved` (the commit) when available and falls back to\n the requested ref when vLLM could not resolve it (local path, ModelScope, offline Hub lookup).\n `ResolvedRevision.initial is None` means \"no pin\" and stays untagged.\n- Layout registry: `(model_name, world_size)` is still shared across revisions. That is correct for\n weights-only revisions; it is documented in `docs/source/mp/configuration.rst` rather than keyed\n by revision. Happy to change it if you prefer.\n- Tests are CPU-only and the vLLM-dependent cases skip when vLLM is absent, so the k3 unit job still\n collects the file: 9 tests in `tests/v1/test_mp_cache_model_identity.py`.\n- The revision lookups tolerate partially built objects, because the MP tests stub the connector and\n the vLLM config: the tag helper reads `_revision_tag` through `getattr`, and the resolver accepts a\n- End-to-end on one RTX 5090 laptop under WSL2 (vLLM 0.29, `lmcache server` in `engine_driven` mode,\n same prompt, one engine restart per row):\n\n | engine | server log |\n |---|---|\n | `--revision revA`, cold | `Stored 432 tokens` |\n | `--revision revA`, restarted | `Prefetch 27/27 retained` → `Retrieved 432 tokens` |\n | `--revision revB` | `Stored 432 tokens` — no cross-revision hit |\n | no `--revision` | `Stored 432 tokens` — its own namespace |\n\n- `@amit70` independently reproduced the collision and the fix on vLLM 0.32 with two real Hub\n revisions, including the unpinned engine; the commits keep a `Co-authored-by` trailer for that\n contribution. The `lmcache.tag.*` form follows `@maobaolong`'s review on this PR.\n- AI assistance was used to implement the change, tests and docs. I reviewed every changed line and\n ran the checks recorded above.\n\n[lmcache-pr-6253-explainer-93f4226e.html](https://github.com/user-attachments/files/34382293/lmcache-pr-6253-explainer-93f4226e.html)\n\n**If applicable**:\n\n
\n\n agent-assisted changes.\n- [x] The HTML explainer is detailed enough for a reviewer without prior context, and its\n\n
\n\n## Diff\n\n```diff\ndiff --git a/lmcache/integration/vllm/lmcache_mp_connector.py b/lmcache/integration/vllm/lmcache_mp_connector.py\nindex 4329bb2354b..a5707ca5fb0 100644\n--- a/lmcache/integration/vllm/lmcache_mp_connector.py\n+++ b/lmcache/integration/vllm/lmcache_mp_connector.py\n@@ -133,6 +133,9 @@ class SupportsHMA: # type: ignore[no-redef]\n logger = lmcache_init_logger(__name__)\n \n _DCP_LAYOUT_NAMESPACE = \"##lmcache-dcp-layout-v1-\"\n+# Request-config key whose value becomes ``ObjectKeyIdentity.tags[\"revision\"]``.\n+# See ``get_request_tags`` in ``lmcache.v1.distributed.api``.\n+_REVISION_TAG_KEY = \"lmcache.tag.revision\"\n _MAX_LCM_EXPANSION_FACTOR = 4\n \n \n@@ -361,6 +364,41 @@ def get_dcp_decorated_model_name(\n return f\"{model_name}{_DCP_LAYOUT_NAMESPACE}d{dcp_size}-interleave{interleave}\"\n \n \n+def _revision_cache_token(vllm_config: VllmConfig) -> str | None:\n+ \"\"\"Return the model revision that must be part of the cache identity.\n+\n+ vLLM resolves ``--revision`` to a commit hash for Hub models and exposes\n+ the hash as ``ResolvedRevision.resolved``. Two engines that pin different\n+ commits of one model ID produce different KV bytes for the same tokens, so\n+ the hash is what the identity has to track: the requested ref alone would\n+ not change when the branch moves. A revision vLLM could not resolve (local\n+ path, ModelScope, offline lookup) is used verbatim.\n+\n+ An engine that passes no ``--revision`` still gets the default branch\n+ resolved, to ``ResolvedRevision(initial=None, ...)``. Tracking that hash\n+ would rename every existing cache namespace on upgrade without any\n+ guarantee about the served weights, so only an explicitly pinned revision\n+ takes part in the identity.\n+\n+ Args:\n+ vllm_config: The active vLLM configuration.\n+\n+ Returns:\n+ The commit hash, the requested revision, or ``None`` when the engine\n+ does not pin a revision.\n+ \"\"\"\n+ model_config = getattr(vllm_config, \"model_config\", None)\n+ revision = (\n+ getattr(model_config, \"revision\", None) if model_config is not None else None\n+ )\n+ if not revision:\n+ return None\n+ requested = getattr(revision, \"initial\", revision)\n+ if requested is None:\n+ return None\n+ return str(getattr(revision, \"resolved\", None) or requested)\n+\n+\n def get_resolved_attention_block_sizes(\n vllm_config: VllmConfig,\n kv_cache_config: \"KVCacheConfig | None\",\n@@ -625,6 +663,9 @@ def __init__(\n vllm_config, kv_cache_config\n )\n cache_model_name = get_dcp_decorated_model_name(vllm_config, kv_cache_config)\n+ # Identity tag sent with every request; empty when the engine pinned no\n+ # revision, so unpinned engines keep their existing cache namespace.\n+ self._revision_tag = _revision_cache_token(vllm_config) or \"\"\n \n assert vllm_config.kv_transfer_config is not None\n self._can_store = vllm_config.kv_transfer_config.is_kv_producer\n@@ -688,10 +729,11 @@ def __init__(\n \n logger.info(\n \"Resolved LMCache MP geometry: group_tokens_per_block=%s, \"\n- \"scheduler_block_size=%d, cache_model_name=%s\",\n+ \"scheduler_block_size=%d, cache_model_name=%s, revision=%s\",\n group_tokens_per_block,\n scheduler_block_size,\n cache_model_name,\n+ self._revision_tag or \"-\",\n )\n \n assert vllm_config.parallel_config.world_size % n_servers == 0, (\n@@ -1998,9 +2040,37 @@ def _get_or_create_request_tracker(\n for session_id in actions.sessions_to_end:\n self.scheduler_adapter.end_session(session_id)\n new_tracker = LMCacheMPRequestTracker(request)\n+ self._apply_revision_tag(new_tracker)\n self.request_trackers[request_id] = new_tracker\n return self.request_trackers[request_id]\n \n+ def _apply_revision_tag(self, tracker: LMCacheMPRequestTracker) -> None:\n+ \"\"\"Carry the engine revision as an ``lmcache.tag.revision`` tag.\n+\n+ The tag travels in the request configuration, so the server derives it\n+ with ``get_request_tags`` next to every other identity tag and no extra\n+ wire field is needed. Engines without a pinned revision add nothing.\n+\n+ A request that already sets the key to another value would silently\n+ write objects under a revision that is not the one serving it, so the\n+ engine revision wins and the conflict is logged.\n+ \"\"\"\n+ revision_tag = getattr(self, \"_revision_tag\", \"\")\n+ if not revision_tag:\n+ return\n+ configs = dict(getattr(tracker, \"request_configs\", None) or {})\n+ configured = configs.get(_REVISION_TAG_KEY)\n+ if configured is not None and configured != revision_tag:\n+ logger.warning(\n+ \"Request %s sets %s=%r, overriding it with the engine revision %r\",\n+ tracker.request_id,\n+ _REVISION_TAG_KEY,\n+ configured,\n+ revision_tag,\n+ )\n+ configs[_REVISION_TAG_KEY] = revision_tag\n+ tracker.request_configs = configs\n+\n def _cleanup_request_tracker(self, request_id: str) -> None:\n \"\"\"\n Clean up request tracker and associated lookup future for a request.\ndiff --git a/tests/v1/test_mp_cache_model_identity.py b/tests/v1/test_mp_cache_model_identity.py\nnew file mode 100644\nindex 00000000000..42064fa9c07\n--- /dev/null\n+++ b/tests/v1/test_mp_cache_model_identity.py\n@@ -0,0 +1,133 @@\n+# SPDX-License-Identifier: Apache-2.0\n+\"\"\"Cache identity of the vLLM MP connector: the model revision tag.\n+\n+The connector keeps the served model name and adds the resolved revision as an\n+``lmcache.tag.revision`` request-configuration entry, which the server turns\n+into an identity tag. These tests pin the three decisions: which revision\n+becomes a tag, that the tag reaches the request configuration, and that engines\n+without a pinned revision stay untagged. No GPU needed.\n+\n+The modules that import vLLM are imported lazily so the k3 unit environment,\n+which has no vLLM, still collects this file.\n+\"\"\"\n+\n+# Standard\n+from types import SimpleNamespace\n+import importlib.util\n+\n+# Third Party\n+import pytest\n+\n+# First Party\n+from lmcache.v1.distributed.api import get_request_tags\n+\n+requires_vllm = pytest.mark.skipif(\n+ importlib.util.find_spec(\"vllm\") is None, reason=\"requires vLLM\"\n+)\n+\n+_COMMIT = \"a\" * 40\n+_TAG_KEY = \"lmcache.tag.revision\"\n+\n+\n+class ResolvedRevision(str):\n+ \"\"\"Duck-typed stand-in for ``huggingface_hub.ResolvedRevision``.\n+\n+ vLLM stores the commit hash of a Hub revision on the string it returns,\n+ keeping the requested ref as the string value.\n+ \"\"\"\n+\n+ def __new__(cls, resolved: str, initial: str | None = None) -> \"ResolvedRevision\":\n+ revision = super().__new__(cls, initial if initial is not None else \"main\")\n+ revision.initial = initial # type: ignore[attr-defined]\n+ revision.resolved = resolved # type: ignore[attr-defined]\n+ return revision\n+\n+\n+def _config(*, revision: object = None) -> SimpleNamespace:\n+ \"\"\"Build the vLLM config subset the revision helper reads.\"\"\"\n+ return SimpleNamespace(\n+ model_config=SimpleNamespace(model=\"org/model\", revision=revision)\n+ )\n+\n+\n+def _revision_token(config: SimpleNamespace) -> str | None:\n+ \"\"\"Resolve the revision token for ``config`` through the real helper.\"\"\"\n+ # First Party\n+ from lmcache.integration.vllm.lmcache_mp_connector import (\n+ _revision_cache_token,\n+ )\n+\n+ return _revision_cache_token(config)\n+\n+\n+def _apply(tag: str, configs: dict[str, object] | None) -> dict[str, object] | None:\n+ \"\"\"Run the connector's tag injection on a minimal tracker stub.\"\"\"\n+ # First Party\n+ from lmcache.integration.vllm.lmcache_mp_connector import LMCacheMPConnector\n+\n+ connector = SimpleNamespace(_revision_tag=tag)\n+ tracker = SimpleNamespace(request_id=\"req\", request_configs=configs)\n+ LMCacheMPConnector._apply_revision_tag(connector, tracker) # type: ignore[arg-type]\n+ return tracker.request_configs\n+\n+\n+@requires_vllm\n+def test_unpinned_revision_has_no_token():\n+ \"\"\"Engines without ``--revision`` must not change cache identity.\"\"\"\n+ assert _revision_token(_config()) is None\n+ assert _revision_token(_config(revision=\"\")) is None\n+\n+\n+@requires_vllm\n+def test_resolved_default_branch_is_not_a_pin():\n+ \"\"\"vLLM resolves the default branch for every Hub model; that is not a pin.\"\"\"\n+ assert _revision_token(_config(revision=ResolvedRevision(\"c\" * 40))) is None\n+\n+\n+@requires_vllm\n+def test_pinned_revision_uses_the_commit_hash():\n+ \"\"\"A pinned branch tracks the commit, so moving it changes the identity.\"\"\"\n+ assert (\n+ _revision_token(_config(revision=ResolvedRevision(_COMMIT, \"main\"))) == _COMMIT\n+ )\n+\n+\n+@requires_vllm\n+def test_unresolved_revision_is_used_verbatim():\n+ \"\"\"A revision vLLM could not resolve still separates the identities.\"\"\"\n+ assert _revision_token(_config(revision=\"refs/pr/4\")) == \"refs/pr/4\"\n+\n+\n+@requires_vllm\n+def test_revision_tag_reaches_the_request_configuration():\n+ \"\"\"The tag must be visible to the server through the request configs.\"\"\"\n+ configs = _apply(_COMMIT, None)\n+\n+ assert configs == {_TAG_KEY: _COMMIT}\n+\n+\n+@requires_vllm\n+def test_no_revision_leaves_request_configuration_alone():\n+ \"\"\"Untagged requests are what engines without a pin keep sending.\"\"\"\n+ assert _apply(\"\", None) is None\n+ assert _apply(\"\", {\"lmcache.tag.salt\": \"x\"}) == {\"lmcache.tag.salt\": \"x\"}\n+\n+\n+@requires_vllm\n+def test_engine_revision_wins_over_a_request_supplied_tag():\n+ \"\"\"A stale request tag must not redirect objects to another revision.\"\"\"\n+ configs = _apply(_COMMIT, {_TAG_KEY: \"b\" * 40, \"lmcache.tag.salt\": \"x\"})\n+\n+ assert configs == {_TAG_KEY: _COMMIT, \"lmcache.tag.salt\": \"x\"}\n+\n+\n+def test_server_derives_the_revision_tag_from_the_configuration():\n+ \"\"\"The server-side contract: ``lmcache.tag.*`` becomes identity tags.\"\"\"\n+ tags = get_request_tags({_TAG_KEY: _COMMIT, \"lmcache.mp.save_decode_cache\": True})\n+\n+ assert dict(tags) == {\"revision\": _COMMIT}\n+\n+\n+def test_unrelated_request_configuration_is_not_an_identity_tag():\n+ \"\"\"Only the ``lmcache.tag.*`` namespace may partition the cache.\"\"\"\n+ assert dict(get_request_tags({\"lmcache.mp.save_decode_cache\": True})) == {}\n\n[1 documentation file diff(s) omitted]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: NVIDIA/TensorRT-LLM\nPull request: [None][fix] Fix NCCL scope overhead, benchmark graph defaults and KV bounce streams\nLabels: ci: full pre-merge approved\nFiles changed (5): tensorrt_llm/_torch/nccl_window_tensor_scope.py, tensorrt_llm/_torch/pyexecutor/engine/model_call.py, tensorrt_llm/_torch/pyexecutor/model_engine.py, tensorrt_llm/bench/dataclasses/configuration.py, tests/unittest/_torch/test_nccl_window_graph.py\n\n## Description (results removed)\n\n## Description\n\nPeerless model forwards enter unnecessary NCCL lease scopes, eager layer hooks and recursive metadata discovery add overhead, benchmark CUDA graph defaults can disagree with the merged runtime batch capacity, and Python KV bounce copies can serialize behind unrelated legacy-default-stream work.\n\nGate NCCL scopes on peer communication; skip exact built-in scalars, cache dataclass field names, and collect direct tensor inputs/outputs without recursion. Eager marked layers use removable `forward` wrappers to preserve the hook-free `nn.Module` path, while the generic module installer retains its hooks. Tensor discovery preserves alias/cycle traversal order, output escape, and exception cleanup. Benchmark graph defaults use the final merged configuration without mutating reusable options, and Python bounce streams are non-blocking.\n\nThe broader module tests and their CI-list changes are reviewed separately:\n\n[table with results removed]\n\nThe NCCL, benchmark and bounce test PRs depend on this fix and remain drafts pending its merge. All test branches target `main` and exclude production changes.\n\n## Test Coverage\n[results removed]\n## PR Checklist\n\n- [x] Reviewed the applicable repository PR checklist items; commits include DCO sign-off.\n\n## Dev Engineer Review\n\n- `ModelEngine` enables NCCL scopes only when distributed state exists and the world size exceeds one or DWDP is enabled. `ModelCaller` exposes `nccl_window_scopes_enabled`. Verify single-rank and DWDP behavior.\n- Tensor discovery adds direct-tensor and container paths, caches dataclass field names, and excludes dataclass traversal for module-call inputs. Eager marked layers use removable `forward` wrappers; the generic installer retains hooks. Verify traversal order, alias and cycle handling, output escape, exception cleanup, and wrapper removal.\n- Python KV bounce streams now use the non-blocking CUDA stream flag.\n\n## QA Engineer Review\n\n- Modified `tests/unittest/_torch/test_nccl_window_graph.py`. It is listed in `tests/integration/test_lists/test-db/l0_cpu.yml`. No manual-QA listing was found.\n- The tests compare output and module-call tensor discovery with generic traversal for nested, cyclic, aliased, and quantized-tensor inputs. They also cover disabled dataclass traversal and removable eager wrappers for inherited and instance-assigned `forward` methods.\n- **Coverage verdict: needs follow-up.** The reported CPU results used an overlaid wheel, not the current source checkout. Current-source runtime validation and matching-build CI results are not established.\n\n- `tensorrt_llm/_torch/disaggregation/native/bounce/impl.py`: Verify bounce-copy ordering and completion with the new non-blocking CUDA stream.\n- `tensorrt_llm/_torch/nccl_window_tensor_scope.py`: Verify tensor discovery, output escape, exception cleanup, and eager wrapper binding and removal.\n- `tensorrt_llm/_torch/pyexecutor/engine/model_call.py`: Verify calls with NCCL scopes enabled and disabled, including output handling when enabled.\n- `tensorrt_llm/_torch/pyexecutor/model_engine.py`: Verify scope installation and enablement for single-rank, multi-rank, and DWDP configurations.\n- `tensorrt_llm/bench/dataclasses/configuration.py`: Verify graph defaults after configuration merging, including empty and `None` configurations.\n- `tests/unittest/_torch/test_nccl_window_graph.py`: Covers tensor discovery and eager-forward wrappers. Listed in CI at `tests/integration/test_lists/test-db/l0_cpu.yml`; no manual-QA listing was found.\n\n## Diff\n\n```diff\ndiff --git a/tensorrt_llm/_torch/nccl_window_tensor_scope.py b/tensorrt_llm/_torch/nccl_window_tensor_scope.py\nindex 9af4d69f0444..35fa6e590477 100644\n--- a/tensorrt_llm/_torch/nccl_window_tensor_scope.py\n+++ b/tensorrt_llm/_torch/nccl_window_tensor_scope.py\n@@ -17,6 +17,7 @@\n from contextlib import contextmanager\n from contextvars import ContextVar\n from dataclasses import fields, is_dataclass\n+from functools import lru_cache, wraps\n from types import TracebackType\n from typing import Any, Iterable, Iterator, TypeVar\n \n@@ -42,15 +43,28 @@ def is_nccl_window_tensor_scoped_module(module_type: type[torch.nn.Module]) -> b\n return getattr(module_type, _SCOPED_MODULE_MARKER, False)\n \n \n+# Exact built-in scalar types cannot contain tensors. Subclasses still take the\n+# generic path, including dataclass subclasses.\n+_SCALAR_TYPES = frozenset((type(None), bool, int, float, complex, str, bytes))\n+\n+\n+@lru_cache(maxsize=256)\n+def _dataclass_field_names(cls: type) -> tuple[str, ...]:\n+ return tuple(field.name for field in fields(cls))\n+\n+\n def _cuda_tensors(\n value: Any,\n tensors: list[torch.Tensor],\n visited: set[int] | None = None,\n+ include_dataclasses: bool = True,\n ) -> None:\n if isinstance(value, torch.Tensor):\n if value.is_cuda:\n tensors.append(value)\n return\n+ if type(value) in _SCALAR_TYPES:\n+ return\n \n if visited is None:\n visited = set()\n@@ -60,25 +74,74 @@ def _cuda_tensors(\n visited.add(identity)\n \n if isinstance(value, Fp4QuantizedTensor):\n- _cuda_tensors(value.fp4_tensor, tensors, visited)\n- _cuda_tensors(value.scaling_factor, tensors, visited)\n- _cuda_tensors(value.unquantized_hidden_states, tensors, visited)\n+ _cuda_tensors(value.fp4_tensor, tensors, visited, include_dataclasses)\n+ _cuda_tensors(value.scaling_factor, tensors, visited, include_dataclasses)\n+ _cuda_tensors(value.unquantized_hidden_states, tensors, visited, include_dataclasses)\n elif isinstance(value, MxFp8QuantizedTensor):\n- _cuda_tensors(value.fp8_tensor, tensors, visited)\n- _cuda_tensors(value.scaling_factor, tensors, visited)\n+ _cuda_tensors(value.fp8_tensor, tensors, visited, include_dataclasses)\n+ _cuda_tensors(value.scaling_factor, tensors, visited, include_dataclasses)\n elif is_dataclass(value) and not isinstance(value, type):\n- for field in fields(value):\n+ if not include_dataclasses:\n+ return\n+ value_type = type(value)\n+ for name in _dataclass_field_names(value_type):\n # Computed metadata properties can require initialization or read CUDA values.\n- if isinstance(getattr(type(value), field.name, None), property):\n+ if isinstance(getattr(value_type, name, None), property):\n continue\n # ``init=False`` fields need not exist until the dataclass initializes them.\n- _cuda_tensors(getattr(value, field.name, None), tensors, visited)\n+ _cuda_tensors(getattr(value, name, None), tensors, visited, include_dataclasses)\n elif isinstance(value, dict):\n for item in value.values():\n- _cuda_tensors(item, tensors, visited)\n+ if type(item) not in _SCALAR_TYPES:\n+ _cuda_tensors(item, tensors, visited, include_dataclasses)\n elif isinstance(value, (list, tuple)):\n for item in value:\n- _cuda_tensors(item, tensors, visited)\n+ if type(item) not in _SCALAR_TYPES:\n+ _cuda_tensors(item, tensors, visited, include_dataclasses)\n+\n+\n+def _module_call_cuda_tensors(args: tuple, kwargs: dict[str, Any]) -> list[torch.Tensor]:\n+ \"\"\"Collect a module call's CUDA tensor inputs, excluding shared metadata.\n+\n+ Equivalent to ``_cuda_tensors((args, kwargs), tensors, include_dataclasses=False)``\n+ with direct tensor arguments handled without recursion. Shared per-forward\n+ metadata belongs to the enclosing scope, including when nested inside\n+ activation containers.\n+ \"\"\"\n+ tensors: list[torch.Tensor] = []\n+ visited: set[int] | None = None\n+ for container in (args, kwargs):\n+ if visited is not None:\n+ identity = id(container)\n+ if identity in visited:\n+ continue\n+ visited.add(identity)\n+ values = args if container is args else kwargs.values()\n+ for value in values:\n+ if type(value) is torch.Tensor:\n+ if value.is_cuda:\n+ tensors.append(value)\n+ elif type(value) not in _SCALAR_TYPES:\n+ if visited is None:\n+ visited = {id(args), id(container)}\n+ _cuda_tensors(value, tensors, visited, include_dataclasses=False)\n+ return tensors\n+\n+\n+def _output_cuda_tensors(value: Any, tensors: list[torch.Tensor]) -> None:\n+ \"\"\"Equivalent to ``_cuda_tensors(value, tensors)``; flat tensor tuples skip recursion.\"\"\"\n+ if type(value) is tuple or type(value) is list:\n+ visited: set[int] | None = None\n+ for item in value:\n+ if type(item) is torch.Tensor:\n+ if item.is_cuda:\n+ tensors.append(item)\n+ elif type(item) not in _SCALAR_TYPES:\n+ if visited is None:\n+ visited = {id(value)}\n+ _cuda_tensors(item, tensors, visited)\n+ return\n+ _cuda_tensors(value, tensors)\n \n \n class _NCCLWindowTensorScope:\n@@ -93,12 +156,21 @@ class _NCCLWindowTensorScope:\n scope's entry depth, quarantining their unescaped leases.\n \"\"\"\n \n- def __init__(self, inputs: Any):\n+ def __init__(self, inputs: Any, *, include_dataclasses: bool = True) -> None:\n self._inputs: list[torch.Tensor] = []\n- _cuda_tensors(inputs, self._inputs)\n+ _cuda_tensors(inputs, self._inputs, include_dataclasses=include_dataclasses)\n self._outputs: list[torch.Tensor] = []\n self._entry_depth = 0\n \n+ @classmethod\n+ def _for_module_call(cls, args: tuple, kwargs: dict[str, Any]) -> \"_NCCLWindowTensorScope\":\n+ \"\"\"Scope one eager module call; its shared metadata stays with the enclosing scope.\"\"\"\n+ scope = cls.__new__(cls)\n+ scope._inputs = _module_call_cuda_tensors(args, kwargs)\n+ scope._outputs = []\n+ scope._entry_depth = 0\n+ return scope\n+\n def __enter__(self) -> \"_NCCLWindowTensorScope\":\n if self._inputs:\n self._entry_depth = torch.ops.trtllm.begin_nccl_window_tensor_scope.tracked(\n@@ -107,7 +179,7 @@ def __enter__(self) -> \"_NCCLWindowTensorScope\":\n return self\n \n def escape(self, outputs: Any) -> Any:\n- _cuda_tensors(outputs, self._outputs)\n+ _output_cuda_tensors(outputs, self._outputs)\n return outputs\n \n def __exit__(\n@@ -148,7 +220,9 @@ def install_module_nccl_window_tensor_scopes(\n )\n \n def begin_scope(_module, args, kwargs, *, active_scopes=active_scopes):\n- scope = nccl_window_tensor_scope((args, kwargs))\n+ # Shared metadata belongs to the enclosing forward, including when\n+ # nested inside activation containers. Outputs still escape recursively.\n+ scope = _NCCLWindowTensorScope._for_module_call(args, kwargs)\n scope.__enter__()\n active_scopes.set((*active_scopes.get(), scope))\n \n@@ -179,11 +253,46 @@ def end_scope(\n return handles\n \n \n+class _ForwardScopeHandle:\n+ \"\"\"Restore a forward replaced by :func:`install_eager_nccl_window_tensor_scopes`.\"\"\"\n+\n+ def __init__(self, module: torch.nn.Module, previous: Any, wrapper: Any) -> None:\n+ self._module = module\n+ self._previous = previous\n+ self._wrapper = wrapper\n+\n+ def remove(self) -> None:\n+ module, self._module = self._module, None\n+ if module is None or module.__dict__.get(\"forward\") is not self._wrapper:\n+ return\n+ if self._previous is None:\n+ del module.forward\n+ else:\n+ module.forward = self._previous\n+\n+\n+def _install_forward_scope(module: torch.nn.Module) -> _ForwardScopeHandle:\n+ # A per-instance forward keeps nn.Module calls on their hook-free fast path; eager\n+ # decoder layers run once per layer per iteration.\n+ previous = module.__dict__.get(\"forward\")\n+ forward = module.forward\n+\n+ @wraps(forward)\n+ def forward_in_scope(*args: Any, **kwargs: Any) -> Any:\n+ scope = _NCCLWindowTensorScope._for_module_call(args, kwargs)\n+ with scope:\n+ return scope.escape(forward(*args, **kwargs))\n+\n+ module.forward = forward_in_scope\n+ return _ForwardScopeHandle(module, previous, forward_in_scope)\n+\n+\n def install_eager_nccl_window_tensor_scopes(\n model: torch.nn.Module,\n-) -> list[torch.utils.hooks.RemovableHandle]:\n+) -> list[_ForwardScopeHandle]:\n \"\"\"Install eager model scopes without exposing Python hooks to Dynamo.\"\"\"\n- modules = (\n- module for module in model.modules() if is_nccl_window_tensor_scoped_module(type(module))\n- )\n- return install_module_nccl_window_tensor_scopes(modules)\n+ return [\n+ _install_forward_scope(module)\n+ for module in model.modules()\n+ if is_nccl_window_tensor_scoped_module(type(module))\n+ ]\ndiff --git a/tensorrt_llm/_torch/pyexecutor/engine/model_call.py b/tensorrt_llm/_torch/pyexecutor/engine/model_call.py\nindex 82bc340400ad..06884aa47c6c 100644\n--- a/tensorrt_llm/_torch/pyexecutor/engine/model_call.py\n+++ b/tensorrt_llm/_torch/pyexecutor/engine/model_call.py\n@@ -33,6 +33,8 @@ class ModelCaller:\n aux_streams: The backend's mutable stream container, retained by reference.\n prefill_compile_only: Whether torch.compile covers only eligible prefill\n batches, so each call must scope ``is_torch_compiling()`` to that decision.\n+ nccl_window_scopes_enabled: Whether this forward can allocate NCCL window\n+ leases through communication with peers.\n \n Encoder stacks and multimodal encoders with different invocation contracts\n call their models directly.\n@@ -45,6 +47,7 @@ def __init__(\n compile_backend: Backend | None = None,\n aux_streams: Backend.Streams | None = None,\n prefill_compile_only: bool = False,\n+ nccl_window_scopes_enabled: bool = True,\n ) -> None:\n if compile_backend is not None and aux_streams is None:\n raise ValueError(\"A compile backend requires its auxiliary stream container.\")\n@@ -52,6 +55,7 @@ def __init__(\n self._compile_backend = compile_backend\n self._aux_streams = aux_streams\n self._prefill_compile_only = prefill_compile_only\n+ self._nccl_window_scopes_enabled = nccl_window_scopes_enabled\n \n def __call__(self, **kwargs: Any) -> Any:\n attrs = get_model_extra_attrs()\n@@ -75,12 +79,14 @@ def __call__(self, **kwargs: Any) -> Any:\n if self._prefill_compile_only\n else contextlib.nullcontext()\n )\n- with compile_scope:\n- # This boundary stays outside torch.compile, so one lease scope covers\n- # eager, compiled, and CUDA-graph model execution.\n- with nccl_window_tensor_scope(kwargs) as scope:\n- if is_trace_enabled(\"TLLM_TRACE_MODEL_FORWARD\"):\n- outputs = trace_func(self._model.forward)(**kwargs)\n- else:\n- outputs = self._model.forward(**kwargs)\n- return scope.escape(outputs)\n+ # This boundary stays outside torch.compile, so one lease scope covers\n+ # eager, compiled, and CUDA-graph model execution.\n+ window_scope = (\n+ nccl_window_tensor_scope(kwargs) if self._nccl_window_scopes_enabled else None\n+ )\n+ with compile_scope, window_scope if window_scope is not None else contextlib.nullcontext():\n+ if is_trace_enabled(\"TLLM_TRACE_MODEL_FORWARD\"):\n+ outputs = trace_func(self._model.forward)(**kwargs)\n+ else:\n+ outputs = self._model.forward(**kwargs)\n+ return window_scope.escape(outputs) if window_scope is not None else outputs\ndiff --git a/tensorrt_llm/_torch/pyexecutor/model_engine.py b/tensorrt_llm/_torch/pyexecutor/model_engine.py\nindex 6c7650d678bf..232c3ba733b2 100644\n--- a/tensorrt_llm/_torch/pyexecutor/model_engine.py\n+++ b/tensorrt_llm/_torch/pyexecutor/model_engine.py\n@@ -489,6 +489,12 @@ def _compile_model(self, configured_encoder_max_num_tokens: int | None) -> None:\n )\n \n self._torch_compile_prefill_only = False\n+ self._nccl_window_tensor_scope_hooks = []\n+ # A forward without peers cannot allocate NCCL window leases. DWDP\n+ # peers are separate from the model-parallel communicator's world size.\n+ window_scopes_enabled = self.dist is not None and (\n+ self.dist.world_size > 1 or self.mapping.dwdp_enabled\n+ )\n \n backend_num_streams = None\n try:\n@@ -550,7 +556,10 @@ def _compile_model(self, configured_encoder_max_num_tokens: int | None) -> None:\n torch._dynamo.config.cache_size_limit = 16\n else:\n set_torch_compiling(False)\n- install_eager_nccl_window_tensor_scopes(self.model)\n+ if window_scopes_enabled:\n+ self._nccl_window_tensor_scope_hooks = install_eager_nccl_window_tensor_scopes(\n+ self.model\n+ )\n \n # Capture local encoders after their metadata is sized and before\n # KV-cache estimation, so graph memory is included in the profile.\n@@ -570,6 +579,7 @@ def _compile_model(self, configured_encoder_max_num_tokens: int | None) -> None:\n compile_backend=self._torch_compile_backend,\n aux_streams=backend_num_streams,\n prefill_compile_only=self._torch_compile_prefill_only,\n+ nccl_window_scopes_enabled=window_scopes_enabled,\n )\n \n def _init_execution_services(self) -> None:\ndiff --git a/tensorrt_llm/bench/dataclasses/configuration.py b/tensorrt_llm/bench/dataclasses/configuration.py\nindex 263d41494f4d..93a95655d1c1 100755\n--- a/tensorrt_llm/bench/dataclasses/configuration.py\n+++ b/tensorrt_llm/bench/dataclasses/configuration.py\n@@ -1,3 +1,6 @@\n+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+# SPDX-License-Identifier: Apache-2.0\n+\n from __future__ import annotations\n \n from dataclasses import dataclass\n@@ -73,18 +76,17 @@ def get_llm_args(self) -> Dict:\n explicit_cli_keys=self.explicit_cli_keys)\n \n if self.backend == \"pytorch\":\n- cuda_graph_config = updated_llm_args.pop(\n- \"cuda_graph_config\", llm_args[\"cuda_graph_config\"])\n- if cuda_graph_config:\n- # Use runtime max_batch_size as cuda_graph_config.max_batch_size\n- # if both max_batch_size and batch_sizes are not set.\n- batch_sizes_set = cuda_graph_config.get(\"batch_sizes\",\n- None) is not None\n+ cuda_graph_config = updated_llm_args.get(\"cuda_graph_config\", {})\n+ if cuda_graph_config is not None:\n+ cuda_graph_config = dict(cuda_graph_config)\n+ # Derive defaults from the final YAML/CLI capacity without\n+ # mutating the reusable performance options.\n+ batch_sizes_set = bool(cuda_graph_config.get(\"batch_sizes\"))\n max_batch_size_set = cuda_graph_config.get(\n \"max_batch_size\", None) is not None\n if not batch_sizes_set and not max_batch_size_set:\n- cuda_graph_config[\n- \"max_batch_size\"] = self.settings_config.max_batch_size\n+ cuda_graph_config[\"max_batch_size\"] = updated_llm_args[\n+ \"max_batch_size\"]\n updated_llm_args[\"cuda_graph_config\"] = cuda_graph_config\n \n return updated_llm_args\ndiff --git a/tests/unittest/_torch/test_nccl_window_graph.py b/tests/unittest/_torch/test_nccl_window_graph.py\nindex 6ea6ad2e4085..dda74c92c4ae 100644\n--- a/tests/unittest/_torch/test_nccl_window_graph.py\n+++ b/tests/unittest/_torch/test_nccl_window_graph.py\n@@ -387,15 +387,24 @@ def test_nested_graph_capture_restores_previous_owner(monkeypatch):\n def tensor_scope_events(monkeypatch):\n events = []\n \n- def collect_tensors(value, tensors):\n+ def collect_tensors(value, tensors, visited=None, include_dataclasses=True):\n if value is not None:\n tensors.extend(value)\n \n+ def collect_module_call_tensors(args, kwargs):\n+ tensors = []\n+ collect_tensors((args, kwargs), tensors)\n+ return tensors\n+\n monkeypatch.setattr(\n nccl_window_tensor_scope,\n \"_cuda_tensors\",\n collect_tensors,\n )\n+ monkeypatch.setattr(nccl_window_tensor_scope, \"_output_cuda_tensors\", collect_tensors)\n+ monkeypatch.setattr(\n+ nccl_window_tensor_scope, \"_module_call_cuda_tensors\", collect_module_call_tensors\n+ )\n \n def begin(tensors):\n events.append((\"begin\", tensors))\n@@ -964,3 +973,94 @@ def forward(*args: object, **kwargs: object) -> torch.Tensor:\n ScheduledRequests(), None, enable_spec_decode=False, runtime_draft_len=0\n )\n assert events == [\"begin\", \"forward\", \"end\"]\n+\n+\n+def test_fast_tensor_collectors_match_generic_traversal() -> None:\n+ from tensorrt_llm._torch.utils import Fp4QuantizedTensor, MxFp8QuantizedTensor\n+\n+ class Ids(list):\n+ pass\n+\n+ @dataclass\n+ class Metadata:\n+ seq_lens: torch.Tensor\n+ request_ids: Ids\n+\n+ with FakeTensorMode():\n+ hidden, residual, packed, scale, fp8, fp8_scale, seq_lens = (\n+ torch.empty(2, device=\"cuda\") for _ in range(7)\n+ )\n+ cpu = torch.ones(2)\n+ fp4 = Fp4QuantizedTensor(packed, scale)\n+ mxfp8 = MxFp8QuantizedTensor(fp8, fp8_scale)\n+ metadata = Metadata(seq_lens, Ids(range(5)))\n+ nested = [hidden, (fp4, None, 3), {\"m\": metadata, \"t\": residual}]\n+ nested.append(nested)\n+ values = [\n+ hidden,\n+ cpu,\n+ None,\n+ 7,\n+ \"name\",\n+ fp4,\n+ mxfp8,\n+ metadata,\n+ nested,\n+ (hidden, residual),\n+ (hidden, metadata, [residual, hidden]),\n+ {\"a\": fp4, \"b\": (mxfp8, seq_lens)},\n+ ]\n+\n+ def generic(value, include_dataclasses=True):\n+ tensors = []\n+ nccl_window_tensor_scope._cuda_tensors(\n+ value, tensors, include_dataclasses=include_dataclasses\n+ )\n+ return list(map(id, tensors))\n+\n+ for value in values:\n+ tensors = []\n+ nccl_window_tensor_scope._output_cuda_tensors(value, tensors)\n+ assert list(map(id, tensors)) == generic(value)\n+\n+ args = (hidden, nested, metadata, None, fp4)\n+ kwargs = {\"residual\": residual, \"metadata\": metadata, \"pair\": (mxfp8, nested), \"n\": 2}\n+ kwargs[\"args_alias\"] = args\n+ kwargs[\"kwargs_cycle\"] = kwargs\n+ tensors = nccl_window_tensor_scope._module_call_cuda_tensors(args, kwargs)\n+ assert list(map(id, tensors)) == generic((args, kwargs), include_dataclasses=False)\n+\n+ args = (hidden, kwargs)\n+ kwargs[\"args_alias\"] = args\n+ tensors = nccl_window_tensor_scope._module_call_cuda_tensors(args, kwargs)\n+ assert list(map(id, tensors)) == generic((args, kwargs), include_dataclasses=False)\n+\n+\n+@pytest.mark.parametrize(\"instance_forward\", [False, True])\n+def test_eager_decoder_layer_scope_keeps_module_call_fast_path(\n+ instance_forward: bool,\n+) -> None:\n+ from tensorrt_llm._torch.modules.decoder_layer import DecoderLayer\n+\n+ class TestLayer(DecoderLayer):\n+ def forward(self, hidden_states, **kwargs):\n+ return hidden_states\n+\n+ layer = TestLayer()\n+ if instance_forward:\n+ layer.forward = lambda hidden_states: hidden_states\n+ original_forward = layer.forward\n+ original_signature = inspect.signature(layer.forward)\n+ handles = nccl_window_tensor_scope.install_eager_nccl_window_tensor_scopes(layer)\n+ output = torch.ones(1)\n+ try:\n+ assert not layer._forward_pre_hooks and not layer._forward_hooks\n+ assert inspect.signature(layer.forward) == original_signature\n+ assert layer(output) is output and layer(output) is output\n+ finally:\n+ for handle in handles:\n+ handle.remove()\n+ handle.remove()\n+ assert (\"forward\" in layer.__dict__) is instance_forward\n+ assert layer.forward == original_forward\n+ assert layer(output) is output\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: NVIDIA/TensorRT-LLM\nPull request: [TRTLLM-17359][fix] Preserve per-rank attention-DP KV metrics\nLabels: ci: full pre-merge approved\nFiles changed (8): docs/source/commands/trtllm-serve/trtllm-serve.rst, tensorrt_llm/_torch/pyexecutor/adp_iter_stats.py, tensorrt_llm/_torch/pyexecutor/scheduler/rank_state.py, tensorrt_llm/metrics/collector.py, tests/unittest/_torch/executor/test_adp_router.py, tests/unittest/_torch/executor/test_iter_stats_populate.py, tests/unittest/grpc/openengine/test_metrics.py, tests/unittest/metrics/test_collector.py\n\n## Description (results removed)\n\n## Summary\n\n**Prometheus label-schema change:** 28 existing KV-cache and rank-local scheduling metric families gain `dp_rank`, including `dp_rank=\"0\"` in single-rank serving. This fixes attention-DP rows copying rank 0's KV measurements, separates cumulative reuse/miss histories, and counts shared speculative-token increments once.\n\nFixes #21124. Tracking: [TRTLLM-17359](https://nvidia.atlassian.net/browse/TRTLLM-17359).\n\n## Scope\n\n- [Capture immutable primary/cross KV snapshots](https://github.com/chienchunhung/TensorRT-LLM/blob/bc01999755c604727016f1d1ac561519e933a261/tensorrt_llm/_torch/pyexecutor/adp_iter_stats.py#L129) with each iteration and restore fresh native objects; missing historical measurements remain absent, so gauges retain their last value and can become stale.\n- [Transport snapshots through the existing object allgather](https://github.com/chienchunhung/TensorRT-LLM/blob/bc01999755c604727016f1d1ac561519e933a261/tensorrt_llm/_torch/pyexecutor/scheduler/rank_state.py#L87), preserving hit-rate precision, optional load telemetry, compact frames, and routing tails; snapshot width derives from `RankKvCacheStats`, with framing constants on `RankIterStatsPayload`.\n- [Keep rank-local measurements and cumulative baselines separate](https://github.com/chienchunhung/TensorRT-LLM/blob/bc01999755c604727016f1d1ac561519e933a261/tensorrt_llm/metrics/collector.py#L943); a decrease warns, contributes no increment, and rebaselines only that rank, while ordered per-rank delivery remains required.\n- Retain rank-0 ownership for shared measurements, fixing duplicated speculative drafted/accepted-token increments; completed-request counts were already zeroed on peer rows by the previous fanout.\n- Rebase onto upstream `main` at `eebd9d0fcf`, preserving the new collector factory, custom registries, multiprocess gauges, and KV-balanced admission; extend the existing [OpenEngine multiprocess scrape test](https://github.com/chienchunhung/TensorRT-LLM/blob/bc01999755c604727016f1d1ac561519e933a261/tests/unittest/grpc/openengine/test_metrics.py#L282) to verify distinct rank gauges and reuse totals.\n\n**Dashboard migration:** retain `dp_rank` to inspect individual ranks or aggregate it explicitly. Sum additive counts where appropriate; use maximum utilization for the fullest rank, and do not sum utilization or hit-rate ratios. [Documentation](https://github.com/chienchunhung/TensorRT-LLM/blob/bc01999755c604727016f1d1ac561519e933a261/docs/source/commands/trtllm-serve/trtllm-serve.rst#L414) explains ownership, freshness, and delivery assumptions.\n\n## Verification\n[results removed]\n## Notes\n\nRelease-owner note: include the `dp_rank` label-schema change and dashboard migration in the release notes. Compact and versioned frames are internal same-build formats; this change makes no cross-version or rolling-upgrade compatibility guarantee.\n\n## Diff\n\n```diff\ndiff --git a/tensorrt_llm/_torch/pyexecutor/adp_iter_stats.py b/tensorrt_llm/_torch/pyexecutor/adp_iter_stats.py\nindex dff8d078eedb..45862bcc78df 100644\n--- a/tensorrt_llm/_torch/pyexecutor/adp_iter_stats.py\n+++ b/tensorrt_llm/_torch/pyexecutor/adp_iter_stats.py\n@@ -7,10 +7,16 @@\n from dataclasses import dataclass\n from typing import Dict, List, Optional, Set\n \n-from tensorrt_llm.bindings.executor import InflightBatchingStats, IterationStats, RequestStats\n+from tensorrt_llm.bindings.executor import (\n+ InflightBatchingStats,\n+ IterationStats,\n+ KvCacheStats,\n+ RequestStats,\n+)\n from tensorrt_llm.logger import logger\n \n from .scheduler.adp_router import RankIterStatsPayload, RankState\n+from .scheduler.rank_state import RankKvCacheStats\n \n _ITERATION_STATS_SCALAR_FIELDS = (\n \"timestamp\",\n@@ -28,13 +34,50 @@\n )\n \n _ITERATION_STATS_OPTIONAL_FIELDS = (\n- \"kv_cache_stats\",\n- \"cross_kv_cache_stats\",\n \"static_batching_stats\",\n \"specdec_stats\",\n )\n \n \n+def _snapshot_kv_cache_stats(stats: KvCacheStats | None) -> RankKvCacheStats | None:\n+ \"\"\"Capture a rank's KV counters independently of the mutable native object.\n+\n+ Args:\n+ stats: Local KV snapshot, or None when this iteration has no measurement.\n+\n+ Returns:\n+ Immutable scalar snapshot, or None when unavailable.\n+ \"\"\"\n+ if stats is None:\n+ return None\n+ return RankKvCacheStats(\n+ max_num_blocks=stats.max_num_blocks,\n+ free_num_blocks=stats.free_num_blocks,\n+ used_num_blocks=stats.used_num_blocks,\n+ tokens_per_block=stats.tokens_per_block,\n+ alloc_total_blocks=stats.alloc_total_blocks,\n+ alloc_new_blocks=stats.alloc_new_blocks,\n+ reused_blocks=stats.reused_blocks,\n+ missed_blocks=stats.missed_blocks,\n+ cache_hit_rate=stats.cache_hit_rate,\n+ )\n+\n+\n+def _restore_kv_cache_stats(snapshot: RankKvCacheStats) -> KvCacheStats:\n+ \"\"\"Create a native KV stats object from one rank's captured values.\n+\n+ Args:\n+ snapshot: Immutable counters captured with the rank's iteration payload.\n+\n+ Returns:\n+ A fresh native stats object.\n+ \"\"\"\n+ stats = KvCacheStats()\n+ for name, value in zip(snapshot._fields, snapshot):\n+ setattr(stats, name, value)\n+ return stats\n+\n+\n @dataclass\n class ADPIterStatsRecord:\n \"\"\"Append-ready stats row produced by Attention-DP fanout.\"\"\"\n@@ -96,6 +139,8 @@ def make_payload(stats: IterationStats) -> RankIterStatsPayload:\n num_gen_kv_tokens=ifb.num_gen_kv_tokens,\n num_paused_requests=ifb.num_paused_requests,\n num_paused_kv_tokens=ifb.num_paused_kv_tokens,\n+ kv_cache_stats=_snapshot_kv_cache_stats(stats.kv_cache_stats),\n+ cross_kv_cache_stats=_snapshot_kv_cache_stats(stats.cross_kv_cache_stats),\n )\n \n def queue(\n@@ -144,9 +189,12 @@ def _recompute_oldest_iter(self) -> None:\n self._oldest_iter = min(self._payloads) if self._payloads else None\n \n def _ensure_zero_payload(self, iter_id: int) -> None:\n- \"\"\"Add a zero payload when this rank had no work for an iteration.\"\"\"\n+ \"\"\"Add a zero-work payload for a missing iteration.\"\"\"\n if iter_id in self._payloads:\n return\n+ [comment with results removed]\n+ # Reading the live cache manager here could put newer KV values before\n+ # that queued snapshot. Leave KV statistics absent for this iteration.\n self._payloads[iter_id] = RankIterStatsPayload(\n has_iter_stats=1,\n iter_stats_iter=iter_id,\n@@ -206,9 +254,13 @@ def _make_rank_iter_stats(\n for attr in _ITERATION_STATS_SCALAR_FIELDS:\n setattr(stats, attr, getattr(rank0_stats, attr))\n \n- # Optional nested stats are copied when present. KV iteration deltas\n- # are attached separately and remain rank-0-only to avoid double-logging\n- # global KV-cache deltas.\n+ # KV snapshots belong to this rank and iteration. Separate KV iteration\n+ # deltas retain their existing rank-0-only export ownership.\n+ # Native setters reject None; default-constructed fields are already absent.\n+ if payload.kv_cache_stats is not None:\n+ stats.kv_cache_stats = _restore_kv_cache_stats(payload.kv_cache_stats)\n+ if payload.cross_kv_cache_stats is not None:\n+ stats.cross_kv_cache_stats = _restore_kv_cache_stats(payload.cross_kv_cache_stats)\n for attr in _ITERATION_STATS_OPTIONAL_FIELDS:\n nested_stats = getattr(rank0_stats, attr)\n if nested_stats is not None:\ndiff --git a/tensorrt_llm/_torch/pyexecutor/scheduler/rank_state.py b/tensorrt_llm/_torch/pyexecutor/scheduler/rank_state.py\nindex dc0526f33ba6..b6c1e4ab21c6 100644\n--- a/tensorrt_llm/_torch/pyexecutor/scheduler/rank_state.py\n+++ b/tensorrt_llm/_torch/pyexecutor/scheduler/rank_state.py\n@@ -6,12 +6,69 @@\n from __future__ import annotations\n \n from dataclasses import MISSING, dataclass, field, fields, replace\n+from typing import ClassVar, NamedTuple\n+\n+\n+class RankKvCacheStats(NamedTuple):\n+ \"\"\"Immutable rank-local KV snapshot containing only transportable scalars.\"\"\"\n+\n+ max_num_blocks: int\n+ free_num_blocks: int\n+ used_num_blocks: int\n+ tokens_per_block: int\n+ alloc_total_blocks: int\n+ alloc_new_blocks: int\n+ reused_blocks: int\n+ missed_blocks: int\n+ cache_hit_rate: float\n+\n+ @classmethod\n+ def wire_size(cls) -> int:\n+ \"\"\"Return the number of scalar fields in a KV snapshot.\n+\n+ Returns:\n+ Number of fields in the named tuple's wire schema.\n+ \"\"\"\n+ return len(cls._fields)\n+\n+ @classmethod\n+ def deserialize(cls, data: list[int | float]) -> RankKvCacheStats:\n+ \"\"\"Restore a KV snapshot from its scalar wire fields.\n+\n+ Args:\n+ data: Eight block counters followed by the floating-point hit rate.\n+\n+ Returns:\n+ The immutable KV snapshot.\n+\n+ Raises:\n+ ValueError: The snapshot has an unexpected number of fields.\n+ \"\"\"\n+ if len(data) != cls.wire_size():\n+ raise ValueError(f\"KV snapshot requires {cls.wire_size()} fields\")\n+ return cls(\n+ int(data[0]),\n+ int(data[1]),\n+ int(data[2]),\n+ int(data[3]),\n+ int(data[4]),\n+ int(data[5]),\n+ int(data[6]),\n+ int(data[7]),\n+ float(data[8]),\n+ )\n \n \n @dataclass\n class RankIterStatsPayload:\n \"\"\"Per-rank iteration payload piggybacked on the ADP allgather.\"\"\"\n \n+ # Legacy scalar widths are independent of the optional snapshot fields.\n+ _ITER_STATS_FIELD_COUNT: ClassVar[int] = 9\n+ _KV_LOAD_FIELD_COUNT: ClassVar[int] = 3\n+ _SNAPSHOT_WIRE_VERSION: ClassVar[int] = -1\n+ _SNAPSHOT_HEADER_SIZE: ClassVar[int] = 4\n+\n has_iter_stats: int = 0\n iter_stats_iter: int = -1\n num_context_requests: int = 0\n@@ -24,10 +81,12 @@ class RankIterStatsPayload:\n kv_used_blocks: int = -1\n kv_total_blocks: int = -1\n kv_load_timestamp_ns: int = 0\n+ kv_cache_stats: RankKvCacheStats | None = None\n+ cross_kv_cache_stats: RankKvCacheStats | None = None\n \n- def serialize(self, include_kv_cache_load: bool = False) -> list[int]:\n+ def serialize(self, include_kv_cache_load: bool = False) -> list[int | float]:\n \"\"\"Serialize to a flat list for allgather transport.\"\"\"\n- values = [\n+ values: list[int | float] = [\n self.has_iter_stats,\n self.iter_stats_iter,\n self.num_context_requests,\n@@ -46,23 +105,78 @@ def serialize(self, include_kv_cache_load: bool = False) -> list[int]:\n self.kv_load_timestamp_ns,\n ]\n )\n+ if self.kv_cache_stats is not None or self.cross_kv_cache_stats is not None:\n+ # The negative version cannot be confused with has_iter_stats (0/1).\n+ # Presence flags frame both snapshots and the independent load fields.\n+ values = [\n+ self._SNAPSHOT_WIRE_VERSION,\n+ int(include_kv_cache_load),\n+ int(self.kv_cache_stats is not None),\n+ int(self.cross_kv_cache_stats is not None),\n+ *values,\n+ ]\n+ for snapshot in (self.kv_cache_stats, self.cross_kv_cache_stats):\n+ if snapshot is not None:\n+ values.extend(snapshot)\n return values\n \n @classmethod\n- def deserialize(cls, data: list[int]) -> RankIterStatsPayload:\n+ def snapshot_payload_size(cls, data: list[int | float]) -> int:\n+ \"\"\"Read the size of a versioned snapshot payload from its header.\n+\n+ Args:\n+ data: Payload header followed by scalar fields and optional rank-state tail.\n+\n+ Returns:\n+ Number of fields belonging to the iteration payload.\n+\n+ Raises:\n+ ValueError: The header is incomplete or contains an unsupported version or flag.\n+ \"\"\"\n+ if (\n+ len(data) < cls._SNAPSHOT_HEADER_SIZE\n+ or data[0] != cls._SNAPSHOT_WIRE_VERSION\n+ or any(flag not in (0, 1) for flag in data[1 : cls._SNAPSHOT_HEADER_SIZE])\n+ ):\n+ raise ValueError(\"Invalid KV snapshot payload header\")\n+ return (\n+ cls._SNAPSHOT_HEADER_SIZE\n+ + cls._ITER_STATS_FIELD_COUNT\n+ + int(data[1]) * cls._KV_LOAD_FIELD_COUNT\n+ + int(data[2] + data[3]) * RankKvCacheStats.wire_size()\n+ )\n+\n+ @classmethod\n+ def deserialize(cls, data: list[int | float]) -> RankIterStatsPayload:\n \"\"\"Deserialize a flat payload, filling omitted trailing defaults.\"\"\"\n values = list(data)\n- payload_fields = fields(cls)\n- if len(values) > len(payload_fields):\n+ if values and values[0] < 0:\n+ expected_size = cls.snapshot_payload_size(values)\n+ if len(values) != expected_size:\n+ raise ValueError(f\"KV snapshot payload requires {expected_size} fields\")\n+ scalar_end = (\n+ cls._SNAPSHOT_HEADER_SIZE\n+ + cls._ITER_STATS_FIELD_COUNT\n+ + int(values[1]) * cls._KV_LOAD_FIELD_COUNT\n+ )\n+ result = cls(*values[cls._SNAPSHOT_HEADER_SIZE : scalar_end])\n+ cursor = scalar_end\n+ if values[2]:\n+ result.kv_cache_stats = RankKvCacheStats.deserialize(\n+ values[cursor : cursor + RankKvCacheStats.wire_size()]\n+ )\n+ cursor += RankKvCacheStats.wire_size()\n+ if values[3]:\n+ result.cross_kv_cache_stats = RankKvCacheStats.deserialize(\n+ values[cursor : cursor + RankKvCacheStats.wire_size()]\n+ )\n+ return result\n+ scalar_field_count = cls._ITER_STATS_FIELD_COUNT + cls._KV_LOAD_FIELD_COUNT\n+ if len(values) > scalar_field_count:\n raise ValueError(\n f\"RankIterStatsPayload has {len(values)} fields, expected at most \"\n- f\"{len(payload_fields)}\"\n+ f\"{scalar_field_count}\"\n )\n- for field_info in payload_fields[len(values) :]:\n- if field_info.default is MISSING and field_info.default_factory is MISSING:\n- raise ValueError(\n- f\"RankIterStatsPayload is missing required field {field_info.name}\"\n- )\n return cls(*values)\n \n \n@@ -84,7 +198,7 @@ def copy_iter_stats_from(self, iter_stats_payload: RankIterStatsPayload | None)\n if iter_stats_payload is not None:\n self.iter_stats = replace(iter_stats_payload)\n \n- def serialize(self, include_kv_cache_load: bool = False) -> list[int]:\n+ def serialize(self, include_kv_cache_load: bool = False) -> list[int | float]:\n \"\"\"Serialize to a flat list for allgather transport.\"\"\"\n return [\n self.rank,\n@@ -99,14 +213,33 @@ def serialize(self, include_kv_cache_load: bool = False) -> list[int]:\n ]\n \n @classmethod\n- def deserialize(cls, data: list[int]) -> RankState:\n+ def deserialize(cls, data: list[int | float]) -> RankState:\n \"\"\"Deserialize from a flat list received via allgather.\"\"\"\n values = list(data)\n prefix_field_count = 4\n rank_state_fields = fields(cls)[:prefix_field_count]\n- max_field_count = prefix_field_count + len(fields(RankIterStatsPayload)) + 4\n if not values:\n raise ValueError(\"RankState payload is missing required field rank\")\n+ if len(values) > prefix_field_count and values[prefix_field_count] < 0:\n+ stats_field_count = RankIterStatsPayload.snapshot_payload_size(\n+ values[prefix_field_count:]\n+ )\n+ if len(values) != prefix_field_count + stats_field_count + 4:\n+ raise ValueError(\"KV snapshot rank state requires four trailing fields\")\n+ else:\n+ # Legacy messages have optional load telemetry and two or four tail\n+ # fields. Keep their framing independent of the Python dataclass size.\n+ telemetry_field_count = (\n+ RankIterStatsPayload._ITER_STATS_FIELD_COUNT\n+ + RankIterStatsPayload._KV_LOAD_FIELD_COUNT\n+ )\n+ telemetry_payload_size = prefix_field_count + telemetry_field_count + 2\n+ stats_field_count = (\n+ telemetry_field_count\n+ if len(values) >= telemetry_payload_size\n+ else RankIterStatsPayload._ITER_STATS_FIELD_COUNT\n+ )\n+ max_field_count = prefix_field_count + stats_field_count + 4\n if len(values) > max_field_count:\n raise ValueError(\n f\"RankState payload has {len(values)} fields, expected at most {max_field_count}\"\n@@ -119,12 +252,6 @@ def deserialize(cls, data: list[int]) -> RankState:\n rank_values.append(field_info.default_factory())\n else:\n raise ValueError(f\"RankState payload is missing required field {field_info.name}\")\n- # The telemetry fields are optional on the wire; forward-work counters\n- # always follow the iteration payload. The full message length identifies\n- # whether telemetry was included in this allgather.\n- telemetry_field_count = len(fields(RankIterStatsPayload))\n- telemetry_payload_size = prefix_field_count + telemetry_field_count + 2\n- stats_field_count = telemetry_field_count if len(values) >= telemetry_payload_size else 9\n stats_end = prefix_field_count + stats_field_count\n return cls(\n rank=rank_values[0],\ndiff --git a/tensorrt_llm/metrics/collector.py b/tensorrt_llm/metrics/collector.py\nindex 35faa80b8c11..d96309c4ebcd 100644\n--- a/tensorrt_llm/metrics/collector.py\n+++ b/tensorrt_llm/metrics/collector.py\n@@ -19,13 +19,15 @@\n from functools import partial\n from typing import TYPE_CHECKING, Dict, List, Optional, Union\n \n+from tensorrt_llm.logger import logger\n+\n+from .enums import MetricNames\n+\n if TYPE_CHECKING:\n- from prometheus_client import CollectorRegistry\n+ from prometheus_client import CollectorRegistry, Counter\n \n from tensorrt_llm.llmapi.llm_args import BaseLlmArgs\n \n-from .enums import MetricNames\n-\n # Upper bound on distinct ``token_position`` label values for the per-position\n # speculative-decoding counters. Each position is one Prometheus time series per\n # model, so this caps label cardinality no matter how deep a request drafts.\n@@ -121,6 +123,7 @@ class MetricsCollector:\n labelname_finish_reason = \"finished_reason\"\n labelname_cache_level = \"cache_level\"\n labelname_cache_tier = \"cache_tier\"\n+ labelname_dp_rank = \"dp_rank\"\n \n @classmethod\n def from_args(\n@@ -192,6 +195,7 @@ def __init__(\n f\"{name} must be strictly increasing, got {buckets}.\")\n self.last_log_time = time.time()\n self.labels = labels\n+ iteration_labelnames = (*self.labels, self.labelname_dp_rank)\n self.metric_prefix = \"trtllm_\"\n \n self.finish_reason_label = {\n@@ -292,51 +296,51 @@ def __init__(\n self.kv_cache_hit_rate = Gauge(name=self.metric_prefix +\n \"kv_cache_hit_rate\",\n documentation=\"KV cache hit rate\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_reused_blocks = Counter(\n name=self.metric_prefix + \"kv_cache_reused_blocks\",\n documentation=\n \"Cumulative number of KV cache blocks reused (cache hits)\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_missed_blocks = Counter(\n name=self.metric_prefix + \"kv_cache_missed_blocks\",\n documentation=\n \"Cumulative number of KV cache blocks missed (cache misses)\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_utilization = Gauge(name=self.metric_prefix +\n \"kv_cache_utilization\",\n documentation=\"KV cache utilization\",\n- labelnames=self.labels.keys())\n- self._prev_reused_blocks = 0\n- self._prev_missed_blocks = 0\n+ labelnames=iteration_labelnames)\n+ self._prev_reused_blocks: dict[str, int] = {}\n+ self._prev_missed_blocks: dict[str, int] = {}\n \n # Per-iteration KV cache gauges\n self.kv_cache_host_utilization = Gauge(\n name=self.metric_prefix + \"kv_cache_host_utilization\",\n documentation=\"KV cache host (secondary) pool utilization\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_iter_reuse_rate = Gauge(\n name=self.metric_prefix + \"kv_cache_iter_reuse_rate\",\n documentation=\"Per-iteration KV cache block reuse rate\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n \n # Per-iteration KV cache counters (monotonically increasing via accumulated deltas)\n self.kv_cache_iter_reused_blocks = Counter(\n name=self.metric_prefix + \"kv_cache_iter_reused_blocks\",\n documentation=\"Total reused KV cache blocks (full + partial)\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_iter_full_reused_blocks = Counter(\n name=self.metric_prefix + \"kv_cache_iter_full_reused_blocks\",\n documentation=\"Total fully reused KV cache blocks\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_iter_partial_reused_blocks = Counter(\n name=self.metric_prefix + \"kv_cache_iter_partial_reused_blocks\",\n documentation=\"Total partially reused KV cache blocks\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_iter_missed_blocks = Counter(\n name=self.metric_prefix + \"kv_cache_iter_missed_blocks\",\n documentation=\"Total missed KV cache blocks (context phase)\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_iter_connector_reused_blocks = Counter(\n name=self.metric_prefix + \"kv_cache_iter_connector_reused_blocks\",\n documentation=\n@@ -344,31 +348,31 @@ def __init__(\n \"from an external store (a subset of the reused blocks). Counted \"\n \"when the load is accepted, before an asynchronous transfer \"\n \"completes.\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_gen_alloc_blocks_total = Counter(\n name=self.metric_prefix + \"kv_cache_gen_alloc_blocks_total\",\n documentation=\"Total blocks allocated during generation phase\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_onboard_bytes_total = Counter(\n name=self.metric_prefix + \"kv_cache_onboard_bytes_total\",\n documentation=\"Total bytes transferred from host to GPU (onboard)\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_offload_bytes_total = Counter(\n name=self.metric_prefix + \"kv_cache_offload_bytes_total\",\n documentation=\"Total bytes transferred from GPU to host (offload)\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_disk_prefetch_blocks_total = Counter(\n name=self.metric_prefix + \"kv_cache_disk_prefetch_blocks_total\",\n documentation=(\n \"Process-lifetime total V2 KV-cache blocks migrated from disk \"\n \"to host by the prefetch mechanism. \"\n \"Resets only when the serving process restarts.\"),\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_intra_device_copy_bytes_total = Counter(\n name=self.metric_prefix + \"kv_cache_intra_device_copy_bytes_total\",\n documentation=\n \"Total bytes copied within GPU (intra-device block copies)\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n \n # Queue & load metrics\n self.num_requests_running = Gauge(\n@@ -426,41 +430,41 @@ def __init__(\n self.kv_cache_max_blocks = Gauge(\n name=self.metric_prefix + \"kv_cache_max_blocks\",\n documentation=\"Maximum number of KV cache blocks\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_free_blocks = Gauge(\n name=self.metric_prefix + \"kv_cache_free_blocks\",\n documentation=\"Number of free KV cache blocks\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_used_blocks = Gauge(\n name=self.metric_prefix + \"kv_cache_used_blocks\",\n documentation=\"Number of used KV cache blocks\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.kv_cache_tokens_per_block = Gauge(\n name=self.metric_prefix + \"kv_cache_tokens_per_block\",\n documentation=\"Number of tokens per KV cache block\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n \n # Inflight batching metrics\n self.num_context_requests = Gauge(\n name=self.metric_prefix + \"num_context_requests\",\n documentation=\"Number of context (prefill) requests\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.num_generation_requests = Gauge(\n name=self.metric_prefix + \"num_generation_requests\",\n documentation=\"Number of generation (decode) requests\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.num_paused_requests = Gauge(\n name=self.metric_prefix + \"num_paused_requests\",\n documentation=\"Number of paused requests\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.num_scheduled_requests = Gauge(\n name=self.metric_prefix + \"num_scheduled_requests\",\n documentation=\"Number of scheduled requests\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.total_context_tokens = Gauge(\n name=self.metric_prefix + \"total_context_tokens\",\n documentation=\"Total number of context tokens\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.avg_decoded_tokens_per_iter = Gauge(\n name=self.metric_prefix + \"avg_decoded_tokens_per_iter\",\n documentation=\"Average number of decoded tokens per iteration\",\n@@ -496,6 +500,7 @@ def __init__(\n self.counter_tokens_cached_prompt.labels(**self.labels)\n self.labels_with_cache_level = {\n **self.labels,\n+ self.labelname_dp_rank: \"0\",\n self.labelname_cache_level: \"\",\n self.labelname_cache_tier: \"\",\n }\n@@ -517,8 +522,8 @@ def __init__(\n labelnames=self.labels_with_cache_level.keys())\n # The configured levels are only known once stats arrive; children are created then so\n # that zero-valued levels are still visible before their first cache hit.\n- self._registered_cache_levels = False\n- self._registered_connector_cache_tier = False\n+ self._registered_cache_levels: set[str] = set()\n+ self._registered_connector_cache_tier: set[str] = set()\n self.histogram_tokens_cached_prompt = Histogram(\n name=self.metric_prefix + \"prompt_cached_tokens_per_request\",\n documentation=\"Histogram of cached prompt tokens per request.\",\n@@ -558,12 +563,12 @@ def __init__(\n name=self.metric_prefix + \"prefill_batch_occupancy\",\n documentation=\n \"Fraction of max active slots occupied by context requests.\",\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n self.histogram_prefill_batch_tokens = Histogram(\n name=self.metric_prefix + \"prefill_batch_tokens\",\n documentation=\"Histogram of total context tokens per iteration.\",\n buckets=[64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768],\n- labelnames=self.labels.keys())\n+ labelnames=iteration_labelnames)\n \n # HTTP error counter\n self.labelname_http_code = \"http_code\"\n@@ -725,9 +730,12 @@ def _log_counter(self, counter, labels: Dict[str, str],\n # Convenience function for logging to counter.\n counter.labels(**self._label_merge(labels)).inc(data)\n \n- def _log_histogram(self, histogram, data: Union[int, float]) -> None:\n+ def _log_histogram(self,\n+ histogram,\n+ data: Union[int, float],\n+ labels: dict[str, str] | None = None) -> None:\n # Convenience function for logging to histogram.\n- histogram.labels(**self.labels).observe(data)\n+ histogram.labels(**self._label_merge(labels)).observe(data)\n \n def _cache_level_labels(self, level: int,\n level_tiers: Optional[List[str]]) -> Dict[str, str]:\n@@ -739,7 +747,8 @@ def _cache_level_labels(self, level: int,\n }\n \n def _log_cached_tokens_by_level(self, counts: Optional[List[int]],\n- level_tiers: Optional[List[str]]) -> None:\n+ level_tiers: Optional[List[str]],\n+ rank: str) -> None:\n \"\"\"Log cached prompt tokens for each configured cache level.\n \n The level count comes from the engine's tier list, so the series are created on the\n@@ -747,19 +756,22 @@ def _log_cached_tokens_by_level(self, counts: Optional[List[int]],\n \"\"\"\n if not counts:\n return\n- if not self._registered_cache_levels:\n+ rank_labels = {self.labelname_dp_rank: rank}\n+ if rank not in self._registered_cache_levels:\n for level in range(len(counts)):\n self.counter_tokens_cached_prompt_by_tier.labels(\n- **self.labels,\n+ **self.labels, **rank_labels,\n **self._cache_level_labels(level, level_tiers))\n- self._registered_cache_levels = True\n+ self._registered_cache_levels.add(rank)\n for level, count in enumerate(counts):\n if count > 0:\n- self._log_counter(self.counter_tokens_cached_prompt_by_tier,\n- self._cache_level_labels(level, level_tiers),\n- count)\n+ self._log_counter(self.counter_tokens_cached_prompt_by_tier, {\n+ **rank_labels,\n+ **self._cache_level_labels(level, level_tiers)\n+ }, count)\n \n- def _log_connector_cached_tokens(self, count: Optional[int]) -> None:\n+ def _log_connector_cached_tokens(self, count: Optional[int],\n+ rank: str) -> None:\n \"\"\"Log cached prompt tokens a KV cache connector loaded from an external store.\n \n Reported only when a connector can serve tokens, so the series appears only then.\n@@ -767,20 +779,50 @@ def _log_connector_cached_tokens(self, count: Optional[int]) -> None:\n if count is None:\n return\n labels = {\n+ self.labelname_dp_rank: rank,\n self.labelname_cache_level: \"\",\n self.labelname_cache_tier: \"connector\",\n }\n- if not self._registered_connector_cache_tier:\n+ if rank not in self._registered_connector_cache_tier:\n self.counter_tokens_cached_prompt_by_tier.labels(\n **self._label_merge(labels))\n- self._registered_connector_cache_tier = True\n+ self._registered_connector_cache_tier.add(rank)\n if count > 0:\n self._log_counter(self.counter_tokens_cached_prompt_by_tier, labels,\n count)\n \n- def _log_gauge(self, gauge, data: Union[int, float]) -> None:\n+ def _log_gauge(self,\n+ gauge,\n+ data: Union[int, float],\n+ labels: dict[str, str] | None = None) -> None:\n # Convenience function for logging to gauge.\n- gauge.labels(**self.labels).set(data)\n+ gauge.labels(**self._label_merge(labels)).set(data)\n+\n+ def _log_cumulative_kv_counter(self, counter: \"Counter\", value: int,\n+ previous: dict[str, int], rank: str, *,\n+ field_name: str) -> None:\n+ \"\"\"Accumulate positive deltas from one rank's ordered snapshots.\n+\n+ A decrease emits a warning and updates the baseline without incrementing\n+ the counter. This does not make stale or reordered snapshots safe.\n+\n+ Args:\n+ counter: Prometheus counter receiving positive increments.\n+ value: Current cumulative value from this rank's cache manager.\n+ previous: Per-rank baselines, updated after processing the snapshot.\n+ rank: Normalized data-parallel rank label.\n+ field_name: Source KV statistics field named in decrease warnings.\n+ \"\"\"\n+ previous_value = previous.get(rank, 0)\n+ delta = value - previous_value\n+ if delta < 0:\n+ logger.warning(\n+ f\"Cumulative KV cache {field_name} decreased for dp_rank={rank} \"\n+ f\"from {previous_value} to {value}; \"\n+ \"skipping increment and updating baseline.\")\n+ elif delta > 0:\n+ self._log_counter(counter, {self.labelname_dp_rank: rank}, delta)\n+ previous[rank] = value\n \n def log_request_metrics_dict(self, metrics_dict: dict) -> None:\n \"\"\"Log per-request metrics from TRTLLM engine responses.\n@@ -914,6 +956,30 @@ def log_iteration_stats(self, iteration_stats: dict) -> None:\n Note:\n - Needs `enable_iter_perf_stats: true` in LLM args to collect iteration-level stats.\n - inflightBatchingStats and specDecodingStats are only present when applicable.\n+ - KV and local scheduling metrics use the dp_rank label, resolved from\n+ attentionDpRank, then rank, then 0 for unranked rows. Other iteration\n+ metrics are rank-0-owned measurements, not global aggregates.\n+ - Rows must arrive once, in producer order within each rank. A decrease\n+ in a rank's cumulative KV count emits a warning and updates its baseline\n+ without incrementing the counter. Stale or reordered rows are unsupported.\n+ \"\"\"\n+ # PyExecutor's TLLM_METRICS_ALL_RANKS path is gated on attention DP,\n+ # so its TP `rank` also identifies the attention-DP rank.\n+ rank = str(\n+ int(\n+ iteration_stats.get(\"attentionDpRank\",\n+ iteration_stats.get(\"rank\", 0))))\n+\n+ if rank == \"0\":\n+ self._log_rank0_iteration_stats(iteration_stats)\n+\n+ self._log_rank_iteration_stats(iteration_stats, rank)\n+\n+ def _log_rank0_iteration_stats(self, iteration_stats: dict) -> None:\n+ \"\"\"Log fields owned by rank 0 using the existing model labels.\n+\n+ Args:\n+ iteration_stats: Serialized iteration measurements from rank 0.\n \"\"\"\n # Top-level queue & load metrics\n if \"numActiveRequests\" in iteration_stats:\n@@ -958,104 +1024,133 @@ def log_iteration_stats(self, iteration_stats: dict) -> None:\n self._log_gauge(self.max_num_tokens_runtime,\n iteration_stats[\"maxNumTokensRuntime\"])\n \n+ if ifb_stats := iteration_stats.get(\"inflightBatchingStats\"):\n+ if \"avgNumDecodedTokensPerIter\" in ifb_stats:\n+ self._log_gauge(self.avg_decoded_tokens_per_iter,\n+ ifb_stats[\"avgNumDecodedTokensPerIter\"])\n+\n+ # Speculative decoding stats are copied from rank 0 by ADP fanout.\n+ if spec_stats := iteration_stats.get(\"specDecodingStats\"):\n+ if \"numDraftTokens\" in spec_stats:\n+ draft_tokens = spec_stats[\"numDraftTokens\"]\n+ if draft_tokens > 0:\n+ self._log_counter(self.counter_spec_decode_num_draft_tokens,\n+ {}, draft_tokens)\n+ if \"numAcceptedTokens\" in spec_stats:\n+ accepted_tokens = spec_stats[\"numAcceptedTokens\"]\n+ if accepted_tokens > 0:\n+ self._log_counter(\n+ self.counter_spec_decode_num_accepted_tokens, {},\n+ accepted_tokens)\n+ if \"acceptanceLength\" in spec_stats:\n+ self._log_gauge(self.spec_decode_acceptance_length,\n+ spec_stats[\"acceptanceLength\"])\n+ if \"draftOverhead\" in spec_stats:\n+ self._log_gauge(self.spec_decode_draft_overhead,\n+ spec_stats[\"draftOverhead\"])\n+\n+ def _log_rank_iteration_stats(self, iteration_stats: dict,\n+ rank: str) -> None:\n+ \"\"\"Log local KV and scheduling measurements for one rank.\n+\n+ Args:\n+ iteration_stats: Serialized iteration measurements for this rank.\n+ rank: Normalized data-parallel rank label.\n+ \"\"\"\n+ rank_labels = {self.labelname_dp_rank: rank}\n+\n # KV cache stats\n if kv_stats := iteration_stats.get(\"kvCacheStats\"):\n cache_hit_rate = kv_stats.get(\"cacheHitRate\")\n if cache_hit_rate is not None:\n- self._log_gauge(self.kv_cache_hit_rate, cache_hit_rate)\n+ self._log_gauge(self.kv_cache_hit_rate,\n+ cache_hit_rate,\n+ labels=rank_labels)\n reused_blocks = kv_stats.get(\"reusedBlocks\")\n if reused_blocks is not None:\n- delta = reused_blocks - self._prev_reused_blocks\n- if delta > 0:\n- self._log_counter(self.kv_cache_reused_blocks, None, delta)\n- self._prev_reused_blocks = reused_blocks\n+ self._log_cumulative_kv_counter(self.kv_cache_reused_blocks,\n+ reused_blocks,\n+ self._prev_reused_blocks,\n+ rank,\n+ field_name=\"reusedBlocks\")\n missed_blocks = kv_stats.get(\"missedBlocks\")\n if missed_blocks is not None:\n- delta = missed_blocks - self._prev_missed_blocks\n- if delta > 0:\n- self._log_counter(self.kv_cache_missed_blocks, None, delta)\n- self._prev_missed_blocks = missed_blocks\n+ self._log_cumulative_kv_counter(self.kv_cache_missed_blocks,\n+ missed_blocks,\n+ self._prev_missed_blocks,\n+ rank,\n+ field_name=\"missedBlocks\")\n if \"usedNumBlocks\" in kv_stats and \"maxNumBlocks\" in kv_stats:\n max_num_blocks = kv_stats[\"maxNumBlocks\"]\n if max_num_blocks:\n utilization = kv_stats[\"usedNumBlocks\"] / max_num_blocks\n- self._log_gauge(self.kv_cache_utilization, utilization)\n+ self._log_gauge(self.kv_cache_utilization,\n+ utilization,\n+ labels=rank_labels)\n if \"maxNumBlocks\" in kv_stats:\n self._log_gauge(self.kv_cache_max_blocks,\n- kv_stats[\"maxNumBlocks\"])\n+ kv_stats[\"maxNumBlocks\"],\n+ labels=rank_labels)\n if \"freeNumBlocks\" in kv_stats:\n self._log_gauge(self.kv_cache_free_blocks,\n- kv_stats[\"freeNumBlocks\"])\n+ kv_stats[\"freeNumBlocks\"],\n+ labels=rank_labels)\n if \"usedNumBlocks\" in kv_stats:\n self._log_gauge(self.kv_cache_used_blocks,\n- kv_stats[\"usedNumBlocks\"])\n+ kv_stats[\"usedNumBlocks\"],\n+ labels=rank_labels)\n if \"tokensPerBlock\" in kv_stats:\n self._log_gauge(self.kv_cache_tokens_per_block,\n- kv_stats[\"tokensPerBlock\"])\n+ kv_stats[\"tokensPerBlock\"],\n+ labels=rank_labels)\n \n # Inflight batching stats\n if ifb_stats := iteration_stats.get(\"inflightBatchingStats\"):\n if \"numContextRequests\" in ifb_stats:\n self._log_gauge(self.num_context_requests,\n- ifb_stats[\"numContextRequests\"])\n+ ifb_stats[\"numContextRequests\"],\n+ labels=rank_labels)\n if \"numGenRequests\" in ifb_stats:\n self._log_gauge(self.num_generation_requests,\n- ifb_stats[\"numGenRequests\"])\n+ ifb_stats[\"numGenRequests\"],\n+ labels=rank_labels)\n if \"numPausedRequests\" in ifb_stats:\n self._log_gauge(self.num_paused_requests,\n- ifb_stats[\"numPausedRequests\"])\n+ ifb_stats[\"numPausedRequests\"],\n+ labels=rank_labels)\n if \"numScheduledRequests\" in ifb_stats:\n self._log_gauge(self.num_scheduled_requests,\n- ifb_stats[\"numScheduledRequests\"])\n+ ifb_stats[\"numScheduledRequests\"],\n+ labels=rank_labels)\n if \"numCtxTokens\" in ifb_stats:\n num_ctx_tokens = ifb_stats[\"numCtxTokens\"]\n- self._log_gauge(self.total_context_tokens, num_ctx_tokens)\n+ self._log_gauge(self.total_context_tokens,\n+ num_ctx_tokens,\n+ labels=rank_labels)\n if num_ctx_tokens > 0:\n self._log_histogram(self.histogram_prefill_batch_tokens,\n- num_ctx_tokens)\n- if \"avgNumDecodedTokensPerIter\" in ifb_stats:\n- self._log_gauge(self.avg_decoded_tokens_per_iter,\n- ifb_stats[\"avgNumDecodedTokensPerIter\"])\n-\n+ num_ctx_tokens,\n+ labels=rank_labels)\n # Prefill batch occupancy: context_requests / max_active_requests\n num_context = ifb_stats.get(\"numContextRequests\", 0)\n max_active = iteration_stats.get(\"maxNumActiveRequests\", 0)\n if max_active and max_active > 0:\n self._log_gauge(self.gauge_prefill_batch_occupancy,\n- num_context / max_active)\n-\n- # Speculative decoding stats\n- if spec_stats := iteration_stats.get(\"specDecodingStats\"):\n- if \"numDraftTokens\" in spec_stats:\n- draft_tokens = spec_stats[\"numDraftTokens\"]\n- if draft_tokens > 0:\n- self._log_counter(self.counter_spec_decode_num_draft_tokens,\n- {}, draft_tokens)\n- if \"numAcceptedTokens\" in spec_stats:\n- accepted_tokens = spec_stats[\"numAcceptedTokens\"]\n- if accepted_tokens > 0:\n- self._log_counter(\n- self.counter_spec_decode_num_accepted_tokens, {},\n- accepted_tokens)\n- if \"acceptanceLength\" in spec_stats:\n- self._log_gauge(self.spec_decode_acceptance_length,\n- spec_stats[\"acceptanceLength\"])\n- if \"draftOverhead\" in spec_stats:\n- self._log_gauge(self.spec_decode_draft_overhead,\n- spec_stats[\"draftOverhead\"])\n+ num_context / max_active,\n+ labels=rank_labels)\n \n # Per-iteration KV cache stats. V2 reports reuse/miss by lifecycle and\n # storage/transfer counters by pool group; legacy V1 uses window stats.\n disk_prefetch_blocks = iteration_stats.get(\"iterDiskPrefetchBlocks\", 0)\n if disk_prefetch_blocks > 0:\n- self._log_counter(self.kv_cache_disk_prefetch_blocks_total, {},\n- disk_prefetch_blocks)\n+ self._log_counter(self.kv_cache_disk_prefetch_blocks_total,\n+ rank_labels, disk_prefetch_blocks)\n \n self._log_cached_tokens_by_level(\n iteration_stats.get(\"iterCachedTokensByLevel\"),\n- iteration_stats.get(\"kvCacheLevelTiers\"))\n+ iteration_stats.get(\"kvCacheLevelTiers\"), rank)\n self._log_connector_cached_tokens(\n- iteration_stats.get(\"iterConnectorCachedTokens\"))\n+ iteration_stats.get(\"iterConnectorCachedTokens\"), rank)\n \n kv_iter = iteration_stats.get(\"kvCacheIterationStats\")\n kv_iter_by_lifecycle = iteration_stats.get(\n@@ -1117,40 +1212,42 @@ def log_iteration_stats(self, iteration_stats: dict) -> None:\n # Gauges\n if total_secondary_max > 0:\n self._log_gauge(self.kv_cache_host_utilization,\n- total_secondary_used / total_secondary_max)\n+ total_secondary_used / total_secondary_max,\n+ labels=rank_labels)\n iter_total = total_reused + total_missed\n if iter_total > 0:\n self._log_gauge(self.kv_cache_iter_reuse_rate,\n- total_reused / iter_total)\n+ total_reused / iter_total,\n+ labels=rank_labels)\n \n # Counters (increment by delta)\n if total_reused > 0:\n- self._log_counter(self.kv_cache_iter_reused_blocks, {},\n+ self._log_counter(self.kv_cache_iter_reused_blocks, rank_labels,\n total_reused)\n if total_full_reused > 0:\n- self._log_counter(self.kv_cache_iter_full_reused_blocks, {},\n- total_full_reused)\n+ self._log_counter(self.kv_cache_iter_full_reused_blocks,\n+ rank_labels, total_full_reused)\n if total_partial_reused > 0:\n- self._log_counter(self.kv_cache_iter_partial_reused_blocks, {},\n- total_partial_reused)\n+ self._log_counter(self.kv_cache_iter_partial_reused_blocks,\n+ rank_labels, total_partial_reused)\n if total_missed > 0:\n- self._log_counter(self.kv_cache_iter_missed_blocks, {},\n+ self._log_counter(self.kv_cache_iter_missed_blocks, rank_labels,\n total_missed)\n if total_connector_reused > 0:\n self._log_counter(self.kv_cache_iter_connector_reused_blocks,\n- {}, total_connector_reused)\n+ rank_labels, total_connector_reused)\n if total_gen_alloc > 0:\n- self._log_counter(self.kv_cache_gen_alloc_blocks_total, {},\n- total_gen_alloc)\n+ self._log_counter(self.kv_cache_gen_alloc_blocks_total,\n+ rank_labels, total_gen_alloc)\n if total_onboard_bytes > 0:\n- self._log_counter(self.kv_cache_onboard_bytes_total, {},\n- total_onboard_bytes)\n+ self._log_counter(self.kv_cache_onboard_bytes_total,\n+ rank_labels, total_onboard_bytes)\n if total_offload_bytes > 0:\n- self._log_counter(self.kv_cache_offload_bytes_total, {},\n- total_offload_bytes)\n+ self._log_counter(self.kv_cache_offload_bytes_total,\n+ rank_labels, total_offload_bytes)\n if total_intra_device_copy_bytes > 0:\n self._log_counter(self.kv_cache_intra_device_copy_bytes_total,\n- {}, total_intra_device_copy_bytes)\n+ rank_labels, total_intra_device_copy_bytes)\n \n def log_request_error(self, http_code: Union[int, str] = \"\") -> None:\n \"\"\"Increment the error counter, labeled by HTTP status code.\"\"\"\ndiff --git a/tests/unittest/_torch/executor/test_adp_router.py b/tests/unittest/_torch/executor/test_adp_router.py\nindex 6b5a2a14cdad..068206650ff4 100644\n--- a/tests/unittest/_torch/executor/test_adp_router.py\n+++ b/tests/unittest/_torch/executor/test_adp_router.py\n@@ -55,6 +55,7 @@\n GenAdmissionConfig,\n GenAdmissionWaitingQueue,\n )\n+from tensorrt_llm._torch.pyexecutor.scheduler.rank_state import RankKvCacheStats\n from tensorrt_llm._torch.pyexecutor.scheduler.waiting_queue import PriorityWaitingQueue\n from tensorrt_llm.bindings.executor import RequestType\n from tensorrt_llm.conversation_params import ConversationParams\n@@ -276,6 +277,147 @@ def test_copy_iter_stats_from_clones_payload(self):\n assert state.iter_stats == payload\n assert state.iter_stats is not payload\n \n+ @pytest.mark.parametrize(\"include_kv_cache_load\", [False, True])\n+ @pytest.mark.parametrize(\"cache_presence\", [(True, False), (False, True), (True, True)])\n+ def test_kv_snapshot_roundtrip_preserves_tail(\n+ self, include_kv_cache_load: bool, cache_presence: tuple[bool, bool]\n+ ) -> None:\n+ \"\"\"Preserve snapshots, optional load telemetry and all routing tail fields.\"\"\"\n+ primary = RankKvCacheStats(100, 80, 20, 16, 40, 30, 7, 5, 0.375)\n+ [comment with results removed]\n+ cross = RankKvCacheStats(0, 0, 0, 0, 0, 0, 0, 0, 0.0)\n+ payload = RankIterStatsPayload(\n+ has_iter_stats=1,\n+ iter_stats_iter=9,\n+ num_gen_requests=5,\n+ kv_used_blocks=22 if include_kv_cache_load else -1,\n+ kv_total_blocks=200 if include_kv_cache_load else -1,\n+ kv_load_timestamp_ns=123 if include_kv_cache_load else 0,\n+ kv_cache_stats=primary if cache_presence[0] else None,\n+ cross_kv_cache_stats=cross if cache_presence[1] else None,\n+ )\n+ state = RankState(\n+ rank=1,\n+ num_active_requests=7,\n+ num_active_tokens=321,\n+ num_retiring_requests=2,\n+ iter_stats=payload,\n+ num_context_requests=3,\n+ num_generation_requests=4,\n+ num_connector_transfers=6,\n+ connector_poll_failed=True,\n+ )\n+\n+ assert RankIterStatsPayload.deserialize(payload.serialize(include_kv_cache_load)) == payload\n+ assert RankState.deserialize(state.serialize(include_kv_cache_load)) == state\n+\n+ def test_kv_snapshot_wire_schema_is_stable(self) -> None:\n+ \"\"\"Pin field order and the complete versioned frame independently of roundtrips.\"\"\"\n+ assert RankKvCacheStats._fields == (\n+ \"max_num_blocks\",\n+ \"free_num_blocks\",\n+ \"used_num_blocks\",\n+ \"tokens_per_block\",\n+ \"alloc_total_blocks\",\n+ \"alloc_new_blocks\",\n+ \"reused_blocks\",\n+ \"missed_blocks\",\n+ \"cache_hit_rate\",\n+ )\n+ state = RankState(\n+ rank=1,\n+ num_active_requests=7,\n+ num_active_tokens=321,\n+ num_retiring_requests=2,\n[... diff truncated: 3 more file(s) not shown]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(moe): static-wrap SMGiB host marshalling overflow\nLabels: run-ci, model: qwen3.5 / 3.6 / 3.8, op: moe\nFiles changed (2): flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_kernel.py, tests/moe/test_b12x_w4a16_large_bank.py\n\n## Description (results removed)\n\n## 📌 Description\n\nA flat expert weight bank larger than 2 GiB kills the SM12x W4A16 fused MoE on\nthe host side, before the kernel is ever launched:\n\n```\nOverflowError: Value overflow: 2684354560 exceeds range of l\n```\n\n### What happens\n\n`_w4a16_fused_moe_launch_flat` flattens each expert bank to rank-1 and hands\nthe raw torch tensor to `fused.compiled(...)`:\n\n```python\nw13_arg = prepared.w13.view(torch.uint8).view(-1) # 2,684,354,560 elements\n...\nfused.compiled(make_ptr(a...), w13_arg, w2_arg, ...)\n```\n\nA raw tensor at that boundary is converted implicitly by the DSL's\n`TensorAdapter`, which does `from_dlpack(arg).mark_layout_dynamic()`. Dynamic\nsizes are packed 32-bit by the runtime when the memref descriptor is built, so\nany bank past `2**31 - 1` overflows in `build_memref_desc`.\n\n### Why it went unnoticed\n\nTwo things have to line up:\n\n* **The uint8 view.** `prepare_w4a16_packed_weights` always produces\n `weight_layout=\"packed\"`, whose flat view is int32 — a 2.5 GiB bank is only\n 671M elements there. The `modelopt` layout flattens to uint8, so the element\n count *is* the byte count. That is the path in the report (b12x / modelopt\n weights consumed zero-copy).\n* **A bank that big.** Consumer SM120 cards usually shard below the boundary;\n the report is on GB10 with 128 GB unified memory, where the full bank for\n Qwen3.6-35B-A3B-NVFP4 (256 experts) crosses it.\n\n### Why the fix is a type correction, not a workaround\n\nThe kernel is compiled against **static-shape** fakes for exactly these two\nparameters — the geometry is part of the compile cache key:\n\n```python\nw13_fake = cute.runtime.make_fake_compact_tensor(\n cutlass.Uint8,\n (num_experts * fc1_cols * (hidden_size // 2),), # compile-time int\n assumed_align=16,\n)\n```\n\nMLIR types:\n\n```\nfake / compiled signature : !cute.memref, \"(N):(1)\">\nstatic from_dlpack : !cute.memref, \"(N):(1)\"> # matches\nimplicit TensorAdapter : !cute.memref, \"(?):(1)\"> # mismatch\n```\n\nThe dynamic wrapper was never type-accurate here; it only worked because the\ndescriptors are ABI-compatible and the kernel indexes with compile-time\nconstants rather than reading the runtime size slot. The 2 GiB boundary is\nwhere that coincidence runs out.\n\nThe fix wraps the two banks explicitly:\n\n```python\nw13_arg = cute.runtime.from_dlpack(w13_arg, assumed_align=16)\nw2_arg = cute.runtime.from_dlpack(w2_arg, assumed_align=16)\n```\n\nThis restores the type the kernel was compiled for, and as a consequence the\nsize never goes through the 32-bit packing path at all — it stays a\ncompile-time constant, as the fakes already declared. `assumed_align=16`\nmirrors the fake declaration.\n\n### Scope\n\nOnly `w13_arg` / `w2_arg` are wrapped. Their runtime shape is a deterministic\nfunction of the compile cache key (`num_experts`, `hidden_size`,\n`intermediate_size`, `weight_layout`, `scale_format`), so pinning them static\ncosts no flexibility.\n\nprinciple cross `2**31` at extreme batch sizes, but their runtime size is only\nrequired to be *at least* the compile-time sample (`numel() >= ...`), so\nstatic-wrapping them would assert a shape that may not hold. Left untouched\ndeliberately; happy to follow up if maintainers want a guard there.\n\n## 🔍 Related Issues\n\nFixes #4706\n\n## 🧪 Tests\n[results removed]\n## Reviewer Notes\n\n* The root cause — dynamic sizes packed 32-bit in `build_memref_desc` — lives\n in the CUTLASS DSL runtime, not in FlashInfer. This PR fixes the call site so\n it stops relying on the dynamic path for parameters that were declared\n static; it does not change or work around the DSL itself.\n VRAM as well as architecture. On a 32 GB SM120 card it runs in a few seconds\n once the kernel is cached.\n* The reporter offered to validate on DGX Spark (GB10). This PR was confirmed\n on consumer SM120 with the exact bank size from the report; an independent\n check on GB10 would be welcome.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Fixed an issue that could prevent large fused mixture-of-experts models from running when expert weight banks exceeded 2 GiB.\n * Large expert weight banks now retain their full size during processing, avoiding overflow errors.\n\n* **Tests**\n * The test verifies successful execution and finite output on supported hardware.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_kernel.py b/flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_kernel.py\nindex 021bd5af618..a1657f361b2 100644\n--- a/flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_kernel.py\n+++ b/flashinfer/fused_moe/cute_dsl/blackwell_sm12x/moe_w4a16_kernel.py\n@@ -5976,6 +5976,14 @@ def _w4a16_fused_moe_launch_flat(\n # identical cache entry instead of silently recompiling with auto tiles.\n force_tile_config=(fc1_tile_k, fc1_tile_n, fc2_tile_k, fc2_tile_n),\n )\n+ # Expert weight banks can exceed 2**31 elements. The implicit TensorAdapter\n+ # conversion marks their layout dynamic, and the DSL runtime packs dynamic\n+ [comment with results removed]\n+ # marshalling. The kernel is compiled against static-shape fakes for these\n+ # parameters, so wrap the banks in a static-layout from_dlpack instead:\n+ # identical MLIR type to the compiled signature, and sizes stay 64-bit.\n+ w13_arg = cute.runtime.from_dlpack(w13_arg, assumed_align=16)\n+ w2_arg = cute.runtime.from_dlpack(w2_arg, assumed_align=16)\n fused.compiled(\n make_ptr(\n _cutlass_element_dtype(element_dtype),\ndiff --git a/tests/moe/test_b12x_w4a16_large_bank.py b/tests/moe/test_b12x_w4a16_large_bank.py\nnew file mode 100644\nindex 00000000000..533a82aebce\n--- /dev/null\n+++ b/tests/moe/test_b12x_w4a16_large_bank.py\n@@ -0,0 +1,146 @@\n+\"\"\"Regression test: SM12x W4A16 MoE with a flat expert weight bank > 2**31\n+elements must not overflow during host-side argument marshalling.\n+\n+The fused-MoE launch flattens each expert weight bank to a rank-1 tensor. In\n+the \"modelopt\" weight layout that flat view is uint8, so a bank larger than\n+2 GiB exceeds int32 range; the implicit TensorAdapter conversion marks the\n+layout dynamic, and dynamic sizes are packed 32-bit by the DSL runtime,\n+raising ``OverflowError: Value overflow: ... exceeds range of l`` before the\n+kernel ever launches. The launch now wraps the banks in a static-layout\n+``from_dlpack`` (matching the static-shape fakes the kernel is compiled\n+against), which keeps sizes 64-bit.\n+\"\"\"\n+\n+import pytest\n+import torch\n+\n+\n+def _is_sm12x_supported():\n+ if not torch.cuda.is_available():\n+ return False\n+ from flashinfer.utils import is_sm120a_supported, is_sm121a_supported\n+\n+ device = torch.device(\"cuda\")\n+ return is_sm120a_supported(device) or is_sm121a_supported(device)\n+\n+\n+def _free_vram_bytes():\n+ if not torch.cuda.is_available():\n+ return 0\n+ free, _total = torch.cuda.mem_get_info()\n+ return free\n+\n+\n+sm120_required = pytest.mark.skipif(\n+ not _is_sm12x_supported(),\n+ reason=\"W4A16 fused MoE requires SM120/SM121\",\n+)\n+\n+# w13 bank 2.5 GiB + w2 bank 1.25 GiB + scales/activations head-room.\n+_REQUIRED_VRAM = 6 * 1024**3\n+\n+\n+@sm120_required\n+@pytest.mark.skipif(\n+ _free_vram_bytes() < _REQUIRED_VRAM,\n+ reason=\"needs ~6 GiB free VRAM for a >2 GiB expert weight bank\",\n+)\n+def test_w4a16_moe_flat_bank_over_int32_max():\n+ from flashinfer.fused_moe.cute_dsl.blackwell_sm12x.moe_w4a16_host import (\n+ plan_w4a16_buffers,\n+ )\n+ from flashinfer.fused_moe.cute_dsl.blackwell_sm12x.moe_w4a16_kernel import (\n+ _scale_fake_int32_elements,\n+ run_w4a16_moe,\n+ )\n+ from flashinfer.fused_moe.cute_dsl.blackwell_sm12x.moe_w4a16_prepare import (\n+ W4A16PackedWeights,\n+ _make_workspace,\n+ )\n+\n+ device = torch.device(\"cuda\")\n+ torch.manual_seed(0)\n+ # E * (2 * n) * (k // 2) = 64 * 8192 * 5120 = 2,684,354,560 uint8 elements:\n+ # the smallest realistic bank past int32 max (matches the report in the\n+ # linked issue, Qwen3.6-35B-A3B-NVFP4 on GB10).\n+ num_experts, hidden_size, intermediate_size = 64, 10240, 4096\n+ m, top_k = 4, 2\n+ fc1_cols = 2 * intermediate_size\n+ bank_elements = num_experts * fc1_cols * (hidden_size // 2)\n+ assert bank_elements > 2**31 - 1\n+\n+ w13 = torch.randint(\n+ 0,\n+ 256,\n+ (num_experts, fc1_cols, hidden_size // 2),\n+ dtype=torch.uint8,\n+ device=device,\n+ )\n+ w2 = torch.randint(\n+ 0,\n+ 256,\n+ (num_experts, hidden_size, intermediate_size // 2),\n+ dtype=torch.uint8,\n+ device=device,\n+ )\n+ n13 = _scale_fake_int32_elements(\n+ num_experts=num_experts,\n+ size_k=hidden_size,\n+ size_n=fc1_cols,\n+ scale_format=\"e4m3_k16\",\n+ )\n+ n2 = _scale_fake_int32_elements(\n+ num_experts=num_experts,\n+ size_k=intermediate_size,\n+ size_n=hidden_size,\n+ scale_format=\"e4m3_k16\",\n+ )\n+ prepared = W4A16PackedWeights(\n+ w13=w13,\n+ w13_scale=torch.full((n13,), 0x3C3C3C3C, dtype=torch.int32, device=device),\n+ w13_global_scale=torch.ones(num_experts, dtype=torch.float32, device=device),\n+ w2=w2,\n+ w2_scale=torch.full((n2,), 0x3C3C3C3C, dtype=torch.int32, device=device),\n+ w2_global_scale=torch.ones(num_experts, dtype=torch.float32, device=device),\n+ workspace=_make_workspace(device),\n+ hidden_size=hidden_size,\n+ intermediate_size=intermediate_size,\n+ num_experts=num_experts,\n+ is_gated=True,\n+ params_dtype=torch.bfloat16,\n+ source_format=\"modelopt\",\n+ w13_layout=\"w13\",\n+ weight_layout=\"modelopt\",\n+ scale_format=\"e4m3_k16\",\n+ )\n+\n+ a = torch.randn(m, hidden_size, dtype=torch.bfloat16, device=device)\n+ logits = torch.randn(m, num_experts, dtype=torch.float32, device=device)\n+ topk_weights, topk_ids = torch.topk(torch.softmax(logits, -1), top_k)\n+ props = torch.cuda.get_device_properties(device)\n+ plan = plan_w4a16_buffers(\n+ prepared,\n+ m=m,\n+ topk=top_k,\n+ route_num_experts=num_experts,\n+ sms=int(props.multi_processor_count),\n+ )\n+ output = torch.zeros(m, hidden_size, dtype=torch.bfloat16, device=device)\n+\n+ # Overflowed at host-side argument marshalling before the fix.\n+ run_w4a16_moe(\n+ a,\n+ prepared,\n+ topk_weights.float().contiguous(),\n+ topk_ids.to(torch.int32).contiguous(),\n+ activation=\"silu\",\n+ intermediate_cache13=torch.empty(\n+ plan.intermediate_cache13_elements, dtype=torch.bfloat16, device=device\n+ ),\n+ intermediate_cache2=torch.empty(\n+ plan.intermediate_cache2_elements, dtype=torch.bfloat16, device=device\n+ ),\n+ output=output,\n+ )\n+ torch.cuda.synchronize()\n+ assert torch.isfinite(output).all()\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(gdn): fence TMEM loads before cg1 shared_acc releases\nLabels: run-ci, op: linear attention\nFiles changed (2): flashinfer/gdn_kernels/blackwell/gated_delta_net_chunked.py, flashinfer/gdn_kernels/blackwell/gated_delta_net_cp_prefill.py\n\n## Description (results removed)\n\n## Summary\n\nFixes #5334.\n\nIn the Blackwell GDN chunked kernel (`compute_group_1_chunk`), two `cg1_shared_acc` consumer releases signaled the producer that the TMEM stage was free while `tcgen05.ld` (`LDTM`) into that stage was still in flight. With `tmem_cg1_shared_acc_stages = 1`, the producer's next `tcgen05.mma` can overwrite cells mid-read.\n\nThis PR adds `cute.arch.fence_view_async_tmem_load()` immediately before:\n\n1. `ks_handle.release()` (after the KS t2r + scale)\n2. `nv_handle.release()` (after the NV t2r + cast loop)\n\nThese match the existing cg0 idiom at `kk0_handle` / `kk1_handle` (and QK epilogue) releases, so the following `SYNCS.ARRIVE` inherits the LDTM scoreboard wait mask.\n\n### Changed vs preserved\n\n| Site | Action |\n|------|--------|\n| `ks_handle.release` | **changed**: add load fence |\n| `nv_handle.release` | **changed**: add load fence |\n| `qs_handle.release` | **preserved**: intervening reg consumer + `fence_view_async_tmem_store` already drains LDTM |\n| `o_qs_handle.release` | **preserved**: same class of lookalike; leave alone |\n| cg0 `kk*` / `qk*` fences | **preserved**: already correct |\n\n### Related\n\n## Diff\n\nTwo lines only in `flashinfer/gdn_kernels/blackwell/gated_delta_net_chunked.py`.\n\n## Verification\n[results removed]\n## Test plan\n[results removed]\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Improved synchronization during internal memory reads to ensure subsequent operations observe updated data consistently.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/gdn_kernels/blackwell/gated_delta_net_chunked.py b/flashinfer/gdn_kernels/blackwell/gated_delta_net_chunked.py\nindex 4a2f851544a..120ed78d9ee 100644\n--- a/flashinfer/gdn_kernels/blackwell/gated_delta_net_chunked.py\n+++ b/flashinfer/gdn_kernels/blackwell/gated_delta_net_chunked.py\n@@ -4525,6 +4525,7 @@ def compute_group_1_chunk(\n )\n for k in cutlass.range(cute.size(tTR_rKS), vectorize=True):\n tTR_rKS[k] = tTR_rKS[k] * tGrCumprod[k]\n+ cute.arch.fence_view_async_tmem_load()\n ks_handle.release()\n for k in cutlass.range(cute.size(tTR_rKS), vectorize=True):\n tRT_rV[k] = tRT_rV[k] - tTR_rKS[k].to(self.io_dtype)\n@@ -4566,6 +4567,7 @@ def compute_group_1_chunk(\n tTR_rNv_inp[None, sub, 0].store(\n tTR_rNv[None, sub, 0].load().to(self.io_dtype)\n )\n+ cute.arch.fence_view_async_tmem_load()\n nv_handle.release()\n \n tTR_rDv = tTR_rNv\ndiff --git a/flashinfer/gdn_kernels/blackwell/gated_delta_net_cp_prefill.py b/flashinfer/gdn_kernels/blackwell/gated_delta_net_cp_prefill.py\nindex 2109283a52b..2e02e19a6ae 100644\n--- a/flashinfer/gdn_kernels/blackwell/gated_delta_net_cp_prefill.py\n+++ b/flashinfer/gdn_kernels/blackwell/gated_delta_net_cp_prefill.py\n@@ -3200,6 +3200,7 @@ def compute_group_1_chunk(\n )\n for k in cutlass.range(cute.size(tTR_rKS), vectorize=True):\n tTR_rKS[k] = tTR_rKS[k] * tGrCumprod[k]\n+ cute.arch.fence_view_async_tmem_load()\n ks_handle.release()\n for k in cutlass.range(cute.size(tTR_rKS), vectorize=True):\n tRT_rV[k] = tRT_rV[k] - tTR_rKS[k].to(self.io_dtype)\n@@ -3241,6 +3242,7 @@ def compute_group_1_chunk(\n tTR_rNv_inp[None, sub, 0].store(\n tTR_rNv[None, sub, 0].load().to(self.io_dtype)\n )\n+ cute.arch.fence_view_async_tmem_load()\n nv_handle.release()\n \n tTR_rDv = tTR_rNv\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(attention): accept non-contiguous index tensors in plan()\nLabels: run-ci, op: attention\nFiles changed (4): flashinfer/decode.py, flashinfer/prefill.py, flashinfer/sparse.py, tests/attention/test_plan_noncontiguous_metadata.py\n\n## Description (results removed)\n\n## 📌 Description\n\n- **CUDA inputs**: in non-CUDA-graph mode, `self._*_buf = indptr.to(self.device)` is a no-op for a strided CUDA view, so the kernel buffers stay strided. `indptr.to(\"cpu\")`, on the other hand, returns a *contiguous* host copy for the planner. The plan and the kernel then disagree about the layout.\n- **CPU inputs**: `.to(\"cpu\")` is a no-op, so the strided host tensor goes straight into the C++ planner.\n\n[table with results removed]\n\n**Fix:** call `.contiguous()` on the index tensors at the top of `plan()` in:\n- `BatchPrefillWithPagedKVCacheWrapper.plan`: `qo_indptr`, `paged_kv_indptr`, `paged_kv_indices`, `paged_kv_last_page_len`\n- `BatchPrefillWithRaggedKVCacheWrapper.plan`: `qo_indptr`, `kv_indptr`, and the optional `o_indptr` / `v_indptr`\n- `BatchDecodeWithPagedKVCacheWrapper._plan_impl` and `fast_decode_plan`: `indptr`, `indices`, `last_page_len`\n- `BlockSparseAttentionWrapper.plan`: `indptr`, `indices`\n- `seq_lens` (when given) in the paged prefill `plan()` and decode `_plan_impl`: it is copied to the host with `seq_lens.cpu()`, which is a no-op for a strided CPU view, and the host copy goes to the native planner. With fa3 paged prefill a strided CPU `seq_lens` was an illegal memory access.\n- the caller-supplied host copies, which go straight to the native planner: `_plan_indptr_host` (the ragged wrapper's `qo_indptr_cpu` / `kv_indptr_cpu`, which it validated for device/shape/dtype but not contiguity) and `fast_decode_plan`'s `global_override_indptr_cpu`. These parameters were added upstream after the first version of this PR.\n\nOut of scope:\n- The MLA planner already rejects non-contiguous metadata (`mla/_batch_mla/_planning.py`).\n- `VariableBlockSparseAttentionWrapper` builds its own indptr via `cat`/`cumsum`, so it is always contiguous.\n\n## 🔍 Related Issues\n\nFixes #5260\n\n## 🧪 Tests\n[results removed]\n## Reviewer Notes\n\n- `BatchAttentionWithAttentionSinkWrapper` subclasses `BatchPrefillWithPagedKVCacheWrapper`, so it inherits the fix and needs no separate change.\n- The C++ launchers still don't check contiguity (`CHECK_INPUT`) on indptr. This PR keeps the change at the Python boundary. Adding C++ checks would also cover direct callers of the low-level modules, and could be a follow-up.\n- Rebased onto current main after the first review round; `seq_lens` and `workspace_size()` coverage came from the earlier CodeRabbit comment, and `fast_decode_plan` coverage was added in this round.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Improved handling of non-contiguous metadata during attention planning and workspace sizing, helping ensure correct results and consistent workspace requirements.\n * Applied across decode, prefill, and block-sparse attention workflows, including planning inputs and optional metadata.\n* **Tests**\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/decode.py b/flashinfer/decode.py\nindex 663c95be066..bbf193dfe80 100644\n--- a/flashinfer/decode.py\n+++ b/flashinfer/decode.py\n@@ -1785,6 +1785,12 @@ def workspace_size(\n \"The size of indices should be less than or equal to the allocated buffer\"\n )\n \n+ # Normalized like plan(): the native size query reads raw pointers (#5260).\n+ indptr = indptr.contiguous()\n+ last_page_len = last_page_len.contiguous()\n+ if seq_lens is not None:\n+ seq_lens = seq_lens.contiguous()\n+\n indptr_host = indptr.to(\"cpu\")\n last_page_len_host = last_page_len.to(\"cpu\")\n if seq_lens is None:\n@@ -2094,6 +2100,13 @@ def _plan_impl(\n * self._float_workspace_buffer.element_size()\n )\n \n+ # Normalized: the planner and kernels read these as raw pointers (#5260).\n+ indptr = indptr.contiguous()\n+ indices = indices.contiguous()\n+ last_page_len = last_page_len.contiguous()\n+ if seq_lens is not None:\n+ seq_lens = seq_lens.contiguous()\n+\n batch_size = len(last_page_len)\n if logits_soft_cap is None:\n logits_soft_cap = 0.0\n@@ -5062,6 +5075,10 @@ def fast_decode_plan(\n compatible prepared graphs are still reused. The copy-elision below is\n specific to the FA2/FA3 module, not cuDNN's metadata contract.\n \"\"\"\n+ # Normalized: kernels read these as raw pointers (#5260); no-op when contiguous.\n+ indptr = indptr.contiguous()\n+ indices = indices.contiguous()\n+ last_page_len = last_page_len.contiguous()\n batch_size = len(last_page_len)\n wants_cudnn = self._backend == \"cudnn\"\n if self._requested_backend == \"auto\":\n@@ -5242,7 +5259,8 @@ def fast_decode_plan(\n )\n \n indptr_host = (\n- global_override_indptr_cpu\n+ # Normalized: the planner reads this as a raw pointer (#5260).\n+ global_override_indptr_cpu.contiguous()\n if global_override_indptr_cpu is not None\n else indptr.cpu()\n )\ndiff --git a/flashinfer/prefill.py b/flashinfer/prefill.py\nindex 73cdb2a3306..7a621a37207 100644\n--- a/flashinfer/prefill.py\n+++ b/flashinfer/prefill.py\n@@ -2657,7 +2657,8 @@ def _plan_indptr_host(indptr, indptr_cpu, name):\n or indptr_cpu.dtype != indptr.dtype\n ):\n raise ValueError(f\"{name} must have the same integer dtype as its indptr\")\n- return indptr_cpu\n+ # Normalized: the planner reads this as a raw pointer (#5260).\n+ return indptr_cpu.contiguous()\n \n \n def _cutlass_plan_work_items(qo_indptr_host: torch.Tensor, num_qo_heads: int) -> int:\n@@ -3373,6 +3374,14 @@ def workspace_size(\n if fixed_split_size is None:\n fixed_split_size = -1\n \n+ # Normalized like plan(): the native size query reads raw pointers (#5260).\n+ qo_indptr = qo_indptr.contiguous()\n+ paged_kv_indptr = paged_kv_indptr.contiguous()\n+ paged_kv_last_page_len = paged_kv_last_page_len.contiguous()\n+ if seq_lens is not None:\n+ seq_lens = seq_lens.contiguous()\n+ # paged_kv_indices is only length-checked here, so it is left as given.\n+\n batch_size = len(qo_indptr) - 1\n qo_indptr_host = qo_indptr.to(\"cpu\")\n total_num_rows = int(qo_indptr_host[-1])\n@@ -3743,6 +3752,14 @@ def plan(\n f\"{self._jit_use_token_head_sf}, plan() passed use_token_head_sf={use_token_head_sf}\"\n )\n \n+ # Normalized: the planner and kernels read these as raw pointers (#5260).\n+ qo_indptr = qo_indptr.contiguous()\n+ paged_kv_indptr = paged_kv_indptr.contiguous()\n+ paged_kv_indices = paged_kv_indices.contiguous()\n+ paged_kv_last_page_len = paged_kv_last_page_len.contiguous()\n+ if seq_lens is not None:\n+ seq_lens = seq_lens.contiguous()\n+\n batch_size = len(qo_indptr) - 1\n self._batch_size = batch_size\n self._num_qo_heads = num_qo_heads\n@@ -5852,6 +5869,14 @@ def plan(\n f\"{self._jit_use_token_head_sf}, plan() passed use_token_head_sf={use_token_head_sf}\"\n )\n \n+ # Normalized: the planner and kernels read these as raw pointers (#5260).\n+ qo_indptr = qo_indptr.contiguous()\n+ kv_indptr = kv_indptr.contiguous()\n+ if o_indptr is not None:\n+ o_indptr = o_indptr.contiguous()\n+ if v_indptr is not None:\n+ v_indptr = v_indptr.contiguous()\n+\n batch_size = len(qo_indptr) - 1\n if len(kv_indptr) != batch_size + 1:\n raise ValueError(\ndiff --git a/flashinfer/sparse.py b/flashinfer/sparse.py\nindex 36cc6358523..51c3c453c68 100644\n--- a/flashinfer/sparse.py\n+++ b/flashinfer/sparse.py\n@@ -670,6 +670,12 @@ def plan(\n kv_data_type = canonicalize_torch_dtype(kv_data_type)\n self._o_dtype = canonicalize_torch_dtype(o_data_type)\n \n+ # Normalized: the planner and kernels read these as raw pointers (#5260).\n+ if indptr is not None:\n+ indptr = indptr.contiguous()\n+ if indices is not None:\n+ indices = indices.contiguous()\n+\n if self._backend != \"vsa_sm100_blk64\" and (\n kv_splits is not None\n or use_clc is not None\ndiff --git a/tests/attention/test_plan_noncontiguous_metadata.py b/tests/attention/test_plan_noncontiguous_metadata.py\nnew file mode 100644\nindex 00000000000..79853f37803\n--- /dev/null\n+++ b/tests/attention/test_plan_noncontiguous_metadata.py\n@@ -0,0 +1,401 @@\n+\"\"\"\n+Copyright (c) 2026 by FlashInfer team.\n+\n+Licensed under the Apache License, Version 2.0 (the \"License\");\n+you may not use this file except in compliance with the License.\n+You may obtain a copy of the License at\n+\n+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+\n+Regression tests for https://github.com/flashinfer-ai/flashinfer/issues/5260.\n+\n+``plan()``, ``fast_decode_plan()`` and ``workspace_size()`` must accept\n+non-contiguous (strided) index tensors -- indptr, indices, last_page_len and\n+``seq_lens``. The host planners and the kernels read them through raw data\n+pointers, and ``.to(device)`` keeps a strided CUDA view strided while\n+``.to(\"cpu\")`` is a no-op for a strided CPU tensor, so before the fix a strided\n+view was misread: illegal memory accesses (fa2 prefill, fa3 paged prefill with\n+``seq_lens``), planner check failures, or silently wrong output (fa3 paged\n+prefill, paged decode, block-sparse). These tensors are tiny and ``plan()``\n+already copies them between host and device, so the fix normalizes them instead\n+of rejecting them.\n+\"\"\"\n+\n+import pytest\n+import torch\n+\n+import flashinfer\n+from flashinfer.utils import is_sm90a_supported\n+\n+NUM_QO_HEADS, NUM_KV_HEADS, HEAD_DIM, PAGE_SIZE = 8, 2, 128, 16\n+DTYPE = torch.float16\n+QO_LENS = [17, 1, 64, 33]\n+KV_LENS = [40, 90, 64, 200]\n+\n+\n+def _strided(t: torch.Tensor) -> torch.Tensor:\n+ \"\"\"Same values as ``t`` but as a stride-2 view with garbage in the gaps.\"\"\"\n+ buf = torch.full((2 * t.numel(),), 12345, dtype=t.dtype, device=t.device)\n+ buf[::2] = t\n+ view = buf[::2]\n+ assert not view.is_contiguous() and torch.equal(view, t)\n+ return view\n+\n+\n+def _indptr(lens) -> torch.Tensor:\n+ return torch.tensor([0] + lens, dtype=torch.int32).cumsum(0, dtype=torch.int32)\n+\n+\n+def _workspace() -> torch.Tensor:\n+ return torch.empty(128 * 1024 * 1024, dtype=torch.uint8, device=\"cuda\")\n+\n+\n+def _paged_metadata():\n+ pages = [(n + PAGE_SIZE - 1) // PAGE_SIZE for n in KV_LENS]\n+ indptr = _indptr(pages)\n+ total = int(indptr[-1])\n+ # Non-trivial page order and a few unused pages.\n+ indices = torch.randperm(total + 7)[:total].to(torch.int32)\n+ last_page_len = torch.tensor(\n+ [(n - 1) % PAGE_SIZE + 1 for n in KV_LENS], dtype=torch.int32\n+ )\n+ kv_cache = torch.randn(\n+ total + 7, 2, PAGE_SIZE, NUM_KV_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\"\n+ )\n+ return indptr, indices, last_page_len, kv_cache\n+\n+\n+def _skip_unsupported(backend: str):\n+ if backend == \"fa3\" and not is_sm90a_supported(torch.device(\"cuda\")):\n+ pytest.skip(\"fa3 requires SM90a\")\n+\n+\n+def _assert_same(ref: torch.Tensor, out: torch.Tensor):\n+ torch.testing.assert_close(out, ref, rtol=1e-3, atol=1e-3)\n+\n+\n+@pytest.mark.parametrize(\"metadata_device\", [\"cuda\", \"cpu\"])\n+@pytest.mark.parametrize(\"backend\", [\"fa2\", \"fa3\"])\n+def test_ragged_prefill_plan_noncontiguous_indptr(metadata_device, backend):\n+ _skip_unsupported(backend)\n+ torch.manual_seed(0)\n+ qo_indptr, kv_indptr = _indptr(QO_LENS), _indptr(KV_LENS)\n+ q = torch.randn(\n+ int(qo_indptr[-1]), NUM_QO_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\"\n+ )\n+ k = torch.randn(\n+ int(kv_indptr[-1]), NUM_KV_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\"\n+ )\n+ v = torch.randn_like(k)\n+\n+ outs = []\n+ for make in (lambda t: t, _strided):\n+ wrapper = flashinfer.BatchPrefillWithRaggedKVCacheWrapper(\n+ _workspace(), \"NHD\", backend=backend\n+ )\n+ wrapper.plan(\n+ make(qo_indptr.to(metadata_device)),\n+ make(kv_indptr.to(metadata_device)),\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ causal=True,\n+ q_data_type=DTYPE,\n+ )\n+ outs.append(wrapper.run(q, k, v))\n+ _assert_same(*outs)\n+\n+\n+@pytest.mark.parametrize(\"metadata_device\", [\"cuda\", \"cpu\"])\n+def test_cudnn_ragged_plan_noncontiguous_optional_offsets(metadata_device):\n+ \"\"\"Independent O/V offset operands honor their values, not storage gaps.\"\"\"\n+ pytest.importorskip(\"cudnn\")\n+ torch.manual_seed(0)\n+ qo_indptr, kv_indptr = _indptr(QO_LENS), _indptr(KV_LENS)\n+ q = torch.randn(\n+ int(qo_indptr[-1]), NUM_QO_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\"\n+ )\n+ k = torch.randn(\n+ int(kv_indptr[-1]), NUM_KV_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\"\n+ )\n+ v = torch.randn_like(k)\n+ results = []\n+ for make in (lambda t: t, _strided):\n+ wrapper = flashinfer.BatchPrefillWithRaggedKVCacheWrapper(\n+ _workspace(), \"NHD\", backend=\"cudnn\"\n+ )\n+ wrapper.plan(\n+ qo_indptr,\n+ kv_indptr,\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ causal=True,\n+ q_data_type=DTYPE,\n+ o_indptr=make(qo_indptr.to(metadata_device)),\n+ v_indptr=make(kv_indptr.to(metadata_device)),\n+ )\n+ results.append(wrapper.run(q, k, v, return_lse=True))\n+ for ref, out in zip(*results, strict=True):\n+ _assert_same(ref, out)\n+\n+\n+@pytest.mark.parametrize(\"pass_seq_lens\", [False, True])\n+@pytest.mark.parametrize(\"metadata_device\", [\"cuda\", \"cpu\"])\n+@pytest.mark.parametrize(\"backend\", [\"fa2\", \"fa3\"])\n+def test_paged_prefill_plan_noncontiguous_metadata(\n+ metadata_device, backend, pass_seq_lens\n+):\n+ _skip_unsupported(backend)\n+ torch.manual_seed(0)\n+ kv_indptr, kv_indices, last_page_len, kv_cache = _paged_metadata()\n+ qo_indptr = _indptr(QO_LENS)\n+ kv_lens = torch.tensor(KV_LENS, dtype=torch.int32)\n+ q = torch.randn(\n+ int(qo_indptr[-1]), NUM_QO_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\"\n+ )\n+\n+ outs = []\n+ for make in (lambda t: t, _strided):\n+ extra = {\"seq_lens\": make(kv_lens.to(metadata_device))} if pass_seq_lens else {}\n+ wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper(\n+ _workspace(), \"NHD\", backend=backend\n+ )\n+ wrapper.plan(\n+ make(qo_indptr.to(metadata_device)),\n+ make(kv_indptr.to(metadata_device)),\n+ make(kv_indices.to(metadata_device)),\n+ make(last_page_len.to(metadata_device)),\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ PAGE_SIZE,\n+ causal=True,\n+ q_data_type=DTYPE,\n+ **extra,\n+ )\n+ outs.append(wrapper.run(q, kv_cache))\n+ _assert_same(*outs)\n+\n+\n+@pytest.mark.parametrize(\"pass_seq_lens\", [False, True])\n+@pytest.mark.parametrize(\"metadata_device\", [\"cuda\", \"cpu\"])\n+@pytest.mark.parametrize(\"use_tensor_cores\", [False, True])\n+def test_paged_decode_plan_noncontiguous_metadata(\n+ metadata_device, use_tensor_cores, pass_seq_lens\n+):\n+ torch.manual_seed(0)\n+ kv_indptr, kv_indices, last_page_len, kv_cache = _paged_metadata()\n+ kv_lens = torch.tensor(KV_LENS, dtype=torch.int32)\n+ q = torch.randn(len(KV_LENS), NUM_QO_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\")\n+\n+ outs = []\n+ for make in (lambda t: t, _strided):\n+ extra = {\"seq_lens\": make(kv_lens.to(metadata_device))} if pass_seq_lens else {}\n+ wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper(\n+ _workspace(), \"NHD\", use_tensor_cores=use_tensor_cores\n+ )\n+ wrapper.plan(\n+ make(kv_indptr.to(metadata_device)),\n+ make(kv_indices.to(metadata_device)),\n+ make(last_page_len.to(metadata_device)),\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ PAGE_SIZE,\n+ q_data_type=DTYPE,\n+ **extra,\n+ )\n+ outs.append(wrapper.run(q, kv_cache))\n+ _assert_same(*outs)\n+\n+\n+@pytest.mark.parametrize(\"metadata_device\", [\"cuda\", \"cpu\"])\n+@pytest.mark.parametrize(\n+ \"wrapper_kind\", [\"decode\", \"decode_tensor_cores\", \"prefill_fa2\"]\n+)\n+def test_workspace_size_noncontiguous_metadata(metadata_device, wrapper_kind):\n+ \"\"\"workspace_size() must size the same problem regardless of strides.\n+\n+ (The prefill fa3 backend has no workspace_size().)\n+ \"\"\"\n+ kv_indptr, kv_indices, last_page_len, _ = _paged_metadata()\n+ qo_indptr = _indptr(QO_LENS)\n+ kv_lens = torch.tensor(KV_LENS, dtype=torch.int32)\n+\n+ sizes = []\n+ for make in (lambda t: t, _strided):\n+ meta = [\n+ make(t.to(metadata_device)) for t in (kv_indptr, kv_indices, last_page_len)\n+ ]\n+ seq_lens = make(kv_lens.to(metadata_device))\n+ if wrapper_kind.startswith(\"decode\"):\n+ wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper(\n+ _workspace(),\n+ \"NHD\",\n+ use_tensor_cores=wrapper_kind == \"decode_tensor_cores\",\n+ )\n+ args = meta\n+ else:\n+ wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper(\n+ _workspace(), \"NHD\", backend=wrapper_kind.split(\"_\")[1]\n+ )\n+ args = [make(qo_indptr.to(metadata_device)), *meta]\n+ sizes.append(\n+ wrapper.workspace_size(\n+ *args,\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ PAGE_SIZE,\n+ q_data_type=DTYPE,\n+ seq_lens=seq_lens,\n+ )\n+ )\n+ assert sizes[0] == sizes[1]\n+\n+\n+@pytest.mark.parametrize(\"metadata_device\", [\"cuda\", \"cpu\"])\n+def test_block_sparse_plan_noncontiguous_metadata(metadata_device):\n+ torch.manual_seed(0)\n+ M, N, R, C = 256, 512, 16, 16\n+ mask = torch.rand(M // R, N // C) < 0.3\n+ mask[:, 0] = True # every block row attends to something\n+ indptr = _indptr(mask.sum(1).tolist())\n+ indices = mask.nonzero()[:, 1].to(torch.int32)\n+ q = torch.randn(M, NUM_QO_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\")\n+ k = torch.randn(N, NUM_KV_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\")\n+ v = torch.randn_like(k)\n+\n+ outs = []\n+ for make in (lambda t: t, _strided):\n+ wrapper = flashinfer.sparse.BlockSparseAttentionWrapper(_workspace())\n+ wrapper.plan(\n+ make(indptr.to(metadata_device)),\n+ make(indices.to(metadata_device)),\n+ M,\n+ N,\n+ R,\n+ C,\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ )\n+ outs.append(wrapper.run(q, k, v))\n+ _assert_same(*outs)\n+\n+\n+def test_fast_decode_plan_noncontiguous_metadata():\n+ \"\"\"``fast_decode_plan`` elides the metadata copies, so it normalizes too.\n+\n+ CUDA metadata only: the function exists to skip the host-to-device copies,\n+ so it hands the caller's tensors straight to the kernel and already faults\n+ on *contiguous* CPU metadata, independently of this fix.\n+ \"\"\"\n+ metadata_device = \"cuda\"\n+ torch.manual_seed(0)\n+ kv_indptr, kv_indices, last_page_len, kv_cache = _paged_metadata()\n+ q = torch.randn(len(KV_LENS), NUM_QO_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\")\n+\n+ outs = []\n+ for make in (lambda t: t, _strided):\n+ # An explicit backend keeps fast_decode_plan on its copy-eliding path\n+ # instead of delegating to plan() for an auto/cuDNN decision. That path\n+ # replans the module a standard plan() built, so warm one first -- the\n+ # same order the multi-step draft backend uses.\n+ wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper(\n+ _workspace(), \"NHD\", backend=\"fa2\"\n+ )\n+ wrapper.plan(\n+ kv_indptr.to(metadata_device),\n+ kv_indices.to(metadata_device),\n+ last_page_len.to(metadata_device),\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ PAGE_SIZE,\n+ q_data_type=DTYPE,\n+ )\n+ flashinfer.decode.fast_decode_plan(\n+ wrapper,\n+ make(kv_indptr.to(metadata_device)),\n+ make(kv_indices.to(metadata_device)),\n+ make(last_page_len.to(metadata_device)),\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ PAGE_SIZE,\n+ q_data_type=DTYPE,\n+ )\n+ outs.append(wrapper.run(q, kv_cache))\n+ _assert_same(*outs)\n+\n+\n+@pytest.mark.parametrize(\"backend\", [\"fa2\", \"fa3\"])\n+def test_ragged_prefill_plan_noncontiguous_indptr_cpu_override(backend):\n+ \"\"\"The optional host copies (``qo_indptr_cpu`` / ``kv_indptr_cpu``) go\n+ straight to the planner, so they need normalizing too.\"\"\"\n+ _skip_unsupported(backend)\n+ torch.manual_seed(0)\n+ qo_indptr, kv_indptr = _indptr(QO_LENS), _indptr(KV_LENS)\n+ q = torch.randn(\n+ int(qo_indptr[-1]), NUM_QO_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\"\n+ )\n+ k = torch.randn(\n+ int(kv_indptr[-1]), NUM_KV_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\"\n+ )\n+ v = torch.randn_like(k)\n+\n+ outs = []\n+ for make in (lambda t: t, _strided):\n+ wrapper = flashinfer.BatchPrefillWithRaggedKVCacheWrapper(\n+ _workspace(), \"NHD\", backend=backend\n+ )\n+ wrapper.plan(\n+ qo_indptr.cuda(),\n+ kv_indptr.cuda(),\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ causal=True,\n+ q_data_type=DTYPE,\n+ qo_indptr_cpu=make(qo_indptr),\n+ kv_indptr_cpu=make(kv_indptr),\n+ )\n+ outs.append(wrapper.run(q, k, v))\n+ _assert_same(*outs)\n+\n+\n+def test_fast_decode_plan_noncontiguous_indptr_override():\n+ \"\"\"``global_override_indptr_cpu`` replaces the host indptr the planner reads.\"\"\"\n+ torch.manual_seed(0)\n+ kv_indptr, kv_indices, last_page_len, kv_cache = _paged_metadata()\n+ q = torch.randn(len(KV_LENS), NUM_QO_HEADS, HEAD_DIM, dtype=DTYPE, device=\"cuda\")\n+\n+ outs = []\n+ for make in (lambda t: t, _strided):\n+ wrapper = flashinfer.BatchDecodeWithPagedKVCacheWrapper(\n+ _workspace(), \"NHD\", backend=\"fa2\"\n+ )\n+ args = (kv_indptr.cuda(), kv_indices.cuda(), last_page_len.cuda())\n+ wrapper.plan(\n+ *args, NUM_QO_HEADS, NUM_KV_HEADS, HEAD_DIM, PAGE_SIZE, q_data_type=DTYPE\n+ )\n+ flashinfer.decode.fast_decode_plan(\n+ wrapper,\n+ *args,\n+ NUM_QO_HEADS,\n+ NUM_KV_HEADS,\n+ HEAD_DIM,\n+ PAGE_SIZE,\n+ q_data_type=DTYPE,\n+ global_override_indptr_cpu=make(kv_indptr),\n+ )\n+ outs.append(wrapper.run(q, kv_cache))\n+ _assert_same(*outs)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(sampling): reserve RNG offsets for the current call\nLabels: run-ci, op: misc\nFiles changed (2): flashinfer/sampling.py, tests/utils/test_sampling.py\n\n## Description (results removed)\n\n## 📌 Description\n\nFix generator-managed RNG offset reservation in sampling, including Philox draw reuse across consecutive speculative sampling calls.\n\n`get_seed_and_offset()` currently advances the generator and returns the advanced offset, so the current call starts beyond the range it just reserved. `chain_speculative_sampling()` also reserves `B * (N + 1)`, while rejection consumes `N + 2` draws per Philox stream: `N + 1` across the two acceptance loops, plus one recovery draw.\n\nFor `B=1, N=3`, consecutive calls currently start at offsets 4 and 8. A rejecting first call consumes offsets 4 through 8, reusing offset 8 in the next call.\n\nThis PR:\n\n- Returns the current offset before advancing the generator to the end of the current call's reservation. This keeps reservations associated with their own calls even when successive call shapes differ.\n- Changes the speculative sampling reservation to `B * (N + 2)`, retaining the existing batch multiplier and four-draw alignment. The example above now starts at offsets 0 and 8, with the first call consuming offsets 0 through 4.\n\n## 🔍 Related Issues\n\nFixes #5637.\n\nThanks to @cudabinary for the detailed report and reproducer.\n\n### ✅ Pre-commit Checks\n[results removed]\n## 🧪 Tests\n[results removed]\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\nThis PR does not change CUDA kernels or non-speculative callers' reservation sizes.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Improved random-number state handling for speculative sampling, helping ensure sufficient state is reserved and generator offsets advance consistently.\n * Explicitly supplied seeds and offsets now reproduce sampling results without further advancing the generator.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/sampling.py b/flashinfer/sampling.py\nindex 12e520760a1..ae3376503de 100644\n--- a/flashinfer/sampling.py\n+++ b/flashinfer/sampling.py\n@@ -55,14 +55,15 @@ def get_seed_and_offset(\n generator = get_default_generators(device)\n # add mutex if multi-trheading needed\n state = generator.get_state()\n- seed, offset = state.view(torch.int64)\n- offset += (increment + 3) // 4 * 4\n+ seed, offset = map(int, state.view(torch.int64))\n+ # Reserve this call's range, leaving the generator at the next unused offset.\n+ next_offset = offset + (increment + 3) // 4 * 4\n generator.set_state(\n torch.tensor(\n- [seed, offset], dtype=torch.int64, device=torch.device(\"cpu\")\n+ [seed, next_offset], dtype=torch.int64, device=torch.device(\"cpu\")\n ).view(torch.uint8)\n )\n- return int(seed), int(offset)\n+ return seed, offset\n \n \n @functools.cache\n@@ -724,7 +725,7 @@ def chain_speculative_sampling(\n batch_size = b\n if seed is None or offset is None:\n seed, offset = get_seed_and_offset(\n- draft_probs.size(0) * (draft_probs.size(1) + 1), generator, device\n+ draft_probs.size(0) * (draft_probs.size(1) + 2), generator, device\n )\n \n maybe_seed_arr, seed_val, maybe_offset_arr, offset_val = (\ndiff --git a/tests/utils/test_sampling.py b/tests/utils/test_sampling.py\nindex 2407e0cfdd2..8861e6ce3b8 100644\n--- a/tests/utils/test_sampling.py\n+++ b/tests/utils/test_sampling.py\n@@ -1202,6 +1202,50 @@ def test_top_k_mask_logits_mixed_k_persistent_loop(dtype):\n )\n \n \n+@pytest.mark.parametrize(\"initial_offset\", [0, 12])\n+def test_get_seed_and_offset_reserves_current_range(initial_offset):\n+ seed = 12345\n+ generator = torch.Generator(device=\"cuda:0\").manual_seed(seed)\n+ generator.set_offset(initial_offset)\n+ expected_offset = initial_offset\n+\n+ for increment in [1, 5, 32, 2, 0]:\n+ actual_seed, actual_offset = flashinfer.sampling.get_seed_and_offset(\n+ increment, generator\n+ )\n+ assert (actual_seed, actual_offset) == (seed, expected_offset)\n+ expected_offset += (increment + 3) // 4 * 4\n+ assert generator.get_offset() == expected_offset\n+ assert generator.initial_seed() == seed\n+\n+\n+def test_chain_speculative_sampling_reserves_current_range():\n+ seed = 12345\n+ generator = torch.Generator(device=\"cuda:0\").manual_seed(seed)\n+\n+ # Rejection consumes N+2 draws: reserve 8 for N=3, then 4 for N=1.\n+ for n, offset, next_offset in [(3, 0, 8), (1, 8, 12)]:\n+ draft_probs = torch.zeros((1, n, 3), device=\"cuda:0\")\n+ draft_probs[..., 0] = 1\n+ draft_token_ids = torch.zeros((1, n), dtype=torch.int32, device=\"cuda:0\")\n+ target_probs = torch.tensor(\n+ [[[0.0, 0.5, 0.5]] + [[0.5, 0.5, 0.0]] * n], device=\"cuda:0\"\n+ )\n+ args = (draft_probs, draft_token_ids, target_probs)\n+\n+ actual = flashinfer.sampling.chain_speculative_sampling(\n+ *args, generator=generator\n+ )\n+ assert generator.get_offset() == next_offset\n+ expected = flashinfer.sampling.chain_speculative_sampling(\n+ *args, generator=generator, seed=seed, offset=offset\n+ )\n+ # Explicit seed/offset must bypass generator reservation.\n+ assert generator.get_offset() == next_offset\n+ for actual_tensor, expected_tensor in zip(actual, expected, strict=True):\n+ torch.testing.assert_close(actual_tensor, expected_tensor, rtol=0, atol=0)\n+\n+\n @pytest.mark.parametrize(\"batch_size\", [1, 99, 989])\n @pytest.mark.parametrize(\"vocab_size\", [111, 32000, 128256])\n @pytest.mark.parametrize(\"num_speculate_tokens\", [1, 3, 5, 7])\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(mamba): preserve FP16 subnormals in software stochastic rounding\nLabels: run-ci, op: linear attention\nFiles changed (2): include/flashinfer/mamba/conversion.cuh, tests/mamba/test_fp16_stochastic_rounding_sw.py\n\n## Description (results removed)\n\n## 📌 Description\n\n`cvt_rs_f16_sw` flushes FP16 subnormals to zero, including exactly representable `2^-24`. Use fixed subnormal spacing and the review-suggested shared add-and-truncate expression for normal/subnormal inputs, preserving signed zero and carry into the smallest normal value. Classify the original Inf/NaN bits before noise and clamp finite overflow to infinity.\n\n## 🔍 Related Issues\n\nNo linked issue. This is a correctness fix, not a performance optimization.\n\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Improved software-based FP16 stochastic rounding for values below the normal range. Very small values round to signed zero, while representable subnormal values are handled more accurately near the transition to the smallest normal value.\n * Preserved exact conversion of values already representable in FP16.\n * Corrected handling of special values and overflow: infinities remain infinite, NaNs use a consistent representation, and finite values that exceed the FP16 range convert to signed infinity.\n\n## Diff\n\n```diff\ndiff --git a/include/flashinfer/mamba/conversion.cuh b/include/flashinfer/mamba/conversion.cuh\nindex 0748674d491..779cd913244 100644\n--- a/include/flashinfer/mamba/conversion.cuh\n+++ b/include/flashinfer/mamba/conversion.cuh\n@@ -190,28 +190,22 @@ __device__ __forceinline__ uint16_t cvt_rs_f16_sw(float x, uint32_t rand13) {\n uint32_t sign = bits & 0x80000000u;\n uint32_t abs_bits = bits & 0x7FFFFFFFu;\n \n- // fp32 has 23 mantissa bits, fp16 has 10. The 13 LSBs are the remainder.\n- [comment with results removed]\n- abs_bits += (rand13 & 0x1FFFu);\n-\n- // Convert to fp16 by truncation.\n- uint32_t f32_exp = (abs_bits >> 23) & 0xFFu;\n- uint32_t f32_mantissa = abs_bits & 0x7FFFFFu;\n-\n- uint16_t f16_bits;\n- if (f32_exp == 0xFF) {\n- f16_bits = (f32_mantissa != 0) ? 0x7E00u : 0x7C00u; // NaN or Inf\n- } else if (f32_exp > 142) { // 127 + 15 = 142 → overflow to Inf\n- f16_bits = 0x7C00u;\n- } else if (f32_exp < 113) { // 127 - 14 = 113 → underflow to zero\n- f16_bits = 0;\n- } else {\n- uint16_t f16_exp = static_cast(f32_exp - 112); // rebias: 127→15\n- uint16_t f16_mantissa = static_cast(f32_mantissa >> 13);\n- f16_bits = (f16_exp << 10) | f16_mantissa;\n+ uint32_t exp = abs_bits >> 23;\n+ uint32_t mantissa = (abs_bits & 0x7FFFFFu) | 0x800000u;\n+ [comment with results removed]\n+ // Subnormals use fixed spacing 2^-24; exp < 90 cannot round up. Guard the\n+ // shift so it is only evaluated in [1, 23]. Keep the common normal path\n+ // in this same add-and-truncate expression instead of an early-return branch.\n+ uint32_t scaled =\n+ exp >= 113 ? abs_bits - (112u << 23) : (exp >= 90 ? mantissa >> (113 - exp) : 0u);\n+ uint32_t f16_bits = min((scaled + (rand13 & 0x1FFFu)) >> 13, 0x7C00u);\n+ [comment with results removed]\n+ // finite overflow into NaN, nor carry a NaN payload into another exponent.\n+ if (abs_bits >= 0x7F800000u) {\n+ f16_bits = abs_bits > 0x7F800000u ? 0x7E00u : 0x7C00u;\n }\n \n- return static_cast(sign >> 16) | f16_bits;\n+ return static_cast(sign >> 16) | static_cast(f16_bits);\n }\n \n // Forward declaration (defined below, after cvt_rs_f16x2_f32).\ndiff --git a/tests/mamba/test_fp16_stochastic_rounding_sw.py b/tests/mamba/test_fp16_stochastic_rounding_sw.py\nnew file mode 100644\nindex 00000000000..e43523bf66d\n--- /dev/null\n+++ b/tests/mamba/test_fp16_stochastic_rounding_sw.py\n@@ -0,0 +1,159 @@\n+\"\"\"FP16 software rounding and hardware-wrapper parity on supported GPUs.\"\"\"\n+\n+import pathlib\n+\n+import pytest\n+import torch\n+from torch.utils.cpp_extension import load_inline\n+\n+from flashinfer.utils import get_compute_capability, is_cvt_rs_supported\n+\n+\n+@pytest.fixture(scope=\"module\")\n+def fp16_sr_sw():\n+ if not torch.cuda.is_available():\n+ pytest.skip(\"Requires CUDA\")\n+ cuda_flags = [\"--expt-relaxed-constexpr\"]\n+ if is_cvt_rs_supported(torch.device(\"cuda\")):\n+ major, minor = get_compute_capability(torch.device(\"cuda\"))\n+ # The architecture-specific target enables the native wrapper paths.\n+ cuda_flags.append(\n+ f\"-gencode=arch=compute_{major}{minor}a,code=sm_{major}{minor}a\"\n+ )\n+ return load_inline(\n+ name=\"test_fp16_sr_sw_subnormals\",\n+ cpp_sources=\"torch::Tensor convert(torch::Tensor x, torch::Tensor noise, int mode);\",\n+ cuda_sources=r\"\"\"\n+#include \n+#include \n+\n+__global__ void convert_kernel(const float* x, const int32_t* noise,\n+ uint16_t* out, int n, int mode) {\n+ int i = blockIdx.x * blockDim.x + threadIdx.x;\n+ if (mode == 2) {\n+ i *= 2;\n+ if (i + 1 < n) {\n+ uint32_t rbits = (noise[i] & 0x1FFFu) | ((noise[i + 1] & 0x1FFFu) << 16);\n+ uint32_t packed = flashinfer::mamba::conversion::cvt_rs_f16x2_f32(\n+ x[i], x[i + 1], rbits);\n+ out[i] = static_cast(packed);\n+ out[i + 1] = static_cast(packed >> 16);\n+ }\n+ } else if (i < n) {\n+ out[i] = mode == 0\n+ ? flashinfer::mamba::conversion::cvt_rs_f16_sw(x[i], noise[i])\n+ : __half_as_ushort(flashinfer::mamba::conversion::cvt_rs_f16_f32(x[i], noise[i]));\n+ }\n+}\n+\n+torch::Tensor convert(torch::Tensor x, torch::Tensor noise, int mode) {\n+ auto out = torch::empty_like(x, x.options().dtype(torch::kFloat16));\n+ convert_kernel<<<(x.numel() + 255) / 256, 256>>>(\n+ x.data_ptr(), noise.data_ptr(),\n+ reinterpret_cast(out.data_ptr()), x.numel(), mode);\n+ return out;\n+}\n+\"\"\",\n+ functions=[\"convert\"],\n+ extra_include_paths=[\n+ str(pathlib.Path(__file__).resolve().parents[2] / \"include\")\n+ ],\n+ extra_cuda_cflags=cuda_flags,\n+ verbose=False,\n+ )\n+\n+\n+@pytest.fixture(params=[0, 1, 2], ids=[\"software\", \"scalar\", \"packed\"])\n+def conversion_mode(request):\n+ return request.param\n+\n+\n+@pytest.mark.parametrize(\"noise\", [0, 1, 4096, 8191])\n+def test_exact_finite_fp16_values(fp16_sr_sw, conversion_mode, noise):\n+ # Both signs of every finite FP16 value, including signed zeros. Conversion\n+ # to FP32 is exact, so stochastic rounding has no discarded bits to round.\n+ positive_bits = torch.arange(0x7C00, dtype=torch.int32)\n+ bits = torch.cat((positive_bits, positive_bits | 0x8000)).to(torch.int16)\n+ expected = bits.view(torch.float16).cuda()\n+ values = expected.float()\n+ random_bits = torch.full_like(values, noise, dtype=torch.int32)\n+ actual = fp16_sr_sw.convert(values, random_bits, conversion_mode)\n+ torch.testing.assert_close(\n+ actual.view(torch.int16), expected.view(torch.int16), rtol=0, atol=0\n+ )\n+\n+\n+def test_subnormal_rounding_boundaries(fp16_sr_sw, conversion_mode):\n+ # Independent reference: fixed subnormal ULPs, calculated in FP64 on CPU.\n+ [comment with results removed]\n+ fractions = torch.tensor(\n+ [\n+ 0,\n+ 2**-15,\n+ 2**-13,\n+ 0.25,\n+ 0.5,\n+ 0.75,\n+ 1,\n+ 1.25,\n+ 1.5,\n+ 1022.5,\n+ 1023,\n+ 1023.5,\n+ 1024,\n+ ],\n+ dtype=torch.float32,\n+ )\n+ fractions = torch.cat(\n+ (\n+ fractions,\n+ torch.nextafter(fractions, torch.full_like(fractions, -float(\"inf\"))),\n+ )\n+ )\n+ fractions = fractions[fractions >= 0]\n+ values = torch.cat((fractions, -fractions)) * 2**-24\n+ values = values.repeat_interleave(8192)\n+ random_bits = torch.arange(8192, dtype=torch.int32).repeat(len(values) // 8192)\n+ magnitude = torch.floor(values.double().abs() * 2**24 + random_bits.double() / 8192)\n+ sign = (values.view(torch.int32) < 0).to(torch.int32) * 0x8000\n+ expected_bits = (magnitude.to(torch.int32) | sign).to(torch.int16)\n+ # High random bits must not influence the 13-bit conversion.\n+ actual = fp16_sr_sw.convert(\n+ values.cuda(), (random_bits | 0xE000).cuda(), conversion_mode\n+ )\n+ torch.testing.assert_close(\n+ actual.view(torch.int16).cpu(), expected_bits, rtol=0, atol=0\n+ )\n+\n+\n+def test_software_special_values(fp16_sr_sw):\n+ # Check both signs, including a NaN payload that would carry into the sign\n+ [comment with results removed]\n+ # not constrained by this software-only canonical-NaN check.\n+ positive = torch.tensor(\n+ [0x7F800000, 0x7F800001, 0x7FC00000, 0x7FFFFFFF], dtype=torch.int64\n+ )\n+ bits = torch.cat((positive, positive | 0x80000000)).to(torch.int32)\n+ values = bits.view(torch.float32).repeat_interleave(8192).cuda()\n+ noise = torch.arange(8192, dtype=torch.int32).repeat(len(bits)).cuda()\n+ expected = (\n+ torch.tensor(\n+ [0x7C00, 0x7E00, 0x7E00, 0x7E00, 0xFC00, 0xFE00, 0xFE00, 0xFE00],\n+ dtype=torch.int32,\n+ )\n+ .to(torch.int16)\n+ .repeat_interleave(8192)\n+ )\n+ actual = fp16_sr_sw.convert(values, noise, 0)\n+ torch.testing.assert_close(actual.view(torch.int16).cpu(), expected, rtol=0, atol=0)\n+\n+\n+def test_finite_overflow_stays_infinite(fp16_sr_sw, conversion_mode):\n+ positive = torch.tensor([0x7F7FFFFF, 0x47800000], dtype=torch.int64)\n+ bits = torch.cat((positive, positive | 0x80000000)).to(torch.int32)\n+ values = bits.view(torch.float32).repeat_interleave(8192).cuda()\n+ noise = torch.arange(8192, dtype=torch.int32).repeat(len(bits)).cuda()\n+ expected = torch.tensor([0x7C00, 0x7C00, 0xFC00, 0xFC00], dtype=torch.int32)\n+ expected = expected.to(torch.int16).repeat_interleave(8192)\n+ actual = fp16_sr_sw.convert(values, noise, conversion_mode)\n+ torch.testing.assert_close(actual.view(torch.int16).cpu(), expected, rtol=0, atol=0)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(moe): keep CuTe-DSL MoE autotune cache keys rank-invariant\nLabels: run-ci, op: moe, v0.7.2, reinforcement learning\nFiles changed (2): flashinfer/fused_moe/cute_dsl/tuner.py, tests/moe/test_cute_dsl_moe_cache_key.py\n\n## Description (results removed)\n\n## 📌 Description\n\nDrop `local_expert_offset` from the persisted autotune cache key of `CuteDslFusedMoERunner` and `CuteDslFusedMoEW4A16Runner`. vLLM's `flashinfer_cutedsl` backend sets it to `ep_rank * local_num_experts`, so under `set_autotune_process_group` EP ranks compute different file keys: the rank that saved the cache hits and skips the timing all-reduce while the other ranks block in it — warm restarts hang (vllm-project/vllm#57423).\n\n## 🔍 Related Issues\n\nFixes #6082. Related: #6006, vllm-project/vllm#57423, vllm-project/vllm#57635.\n\n## 🧪 Tests\n[results removed]\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\n- Verified locally via a CPU-level check of `get_cache_key_extras` (same standard as #6006's test); the multi-rank deadlock itself needs TP>=2 and was not reproduced here.\n- One adjacent finding, out of scope for this PR: `MoERunner._cache_key_extras` in `fused_moe/runners.py` also keys on `experts.local_expert_offset`, so the new-style runners built on it (TrtllmFp4, Cake) look exposed to the same EP warm-start hang. Happy to fold it in or follow up — whichever you prefer.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Distributed Mixture-of-Experts autotuning now shares cache entries across ranks with different local expert slices.\n * Cache entries continue to distinguish configurations with different total expert counts.\n* **Tests**\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/fused_moe/cute_dsl/tuner.py b/flashinfer/fused_moe/cute_dsl/tuner.py\nindex b96260f3584..4ad0b4e4740 100644\n--- a/flashinfer/fused_moe/cute_dsl/tuner.py\n+++ b/flashinfer/fused_moe/cute_dsl/tuner.py\n@@ -712,6 +712,7 @@ def __hash__(self):\n )\n \n def get_cache_key_extras(self, inputs: List[torch.Tensor]) -> tuple:\n+ # No local_expert_offset: EP ranks must share persisted entries (#6082).\n extras: tuple[Any, ...] = (\n self.quant_mode,\n int(self.activation_type),\n@@ -721,7 +722,6 @@ def get_cache_key_extras(self, inputs: List[torch.Tensor]) -> tuple:\n self.situ_beta,\n self.situ_linear_beta,\n self.num_experts,\n- self.local_expert_offset,\n self.use_fused_finalize,\n self.output_dtype,\n self.enable_pdl,\n@@ -1210,7 +1210,6 @@ def get_cache_key_extras(self, inputs: List[torch.Tensor]) -> tuple:\n self.num_experts,\n self.top_k,\n self.num_local_experts,\n- self.local_expert_offset,\n self.use_fused_finalize,\n self.output_dtype,\n self.enable_pdl,\ndiff --git a/tests/moe/test_cute_dsl_moe_cache_key.py b/tests/moe/test_cute_dsl_moe_cache_key.py\nnew file mode 100644\nindex 00000000000..c6b7c0e5b9a\n--- /dev/null\n+++ b/tests/moe/test_cute_dsl_moe_cache_key.py\n@@ -0,0 +1,64 @@\n+# Copyright (c) 2026 by FlashInfer team.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import pytest\n+\n+from flashinfer.cute_dsl import is_cute_dsl_available\n+\n+cute_dsl_available = pytest.mark.skipif(\n+ not is_cute_dsl_available(), reason=\"CuteDSL not available\"\n+)\n+\n+\n+def _runner(runner_cls, **parallel):\n+ kwargs = dict(\n+ num_experts=256,\n+ top_k=8,\n+ num_local_experts=32,\n+ local_expert_offset=0,\n+ )\n+ kwargs.update(parallel)\n+ if runner_cls.__name__ == \"CuteDslFusedMoERunner\":\n+ return runner_cls(forward_impl=lambda *a, **k: None, **kwargs)\n+ return runner_cls(**kwargs)\n+\n+\n+@cute_dsl_available\n+@pytest.mark.parametrize(\n+ \"runner_name\",\n+ [\"CuteDslFusedMoERunner\", \"CuteDslFusedMoEW4A16Runner\"],\n+)\n+def test_cute_dsl_moe_cache_key_is_rank_invariant(runner_name):\n+ \"\"\"Ranks tuned together must share persisted tactics: a cache hit skips the\n+ set_autotune_process_group reduce, so a rank-derived key made only the rank\n+ that saved the cache file hit and deadlocked the others.\"\"\"\n+ from flashinfer.fused_moe.cute_dsl.tuner import (\n+ CuteDslFusedMoERunner,\n+ CuteDslFusedMoEW4A16Runner,\n+ )\n+\n+ runner_cls = {\n+ \"CuteDslFusedMoERunner\": CuteDslFusedMoERunner,\n+ \"CuteDslFusedMoEW4A16Runner\": CuteDslFusedMoEW4A16Runner,\n+ }[runner_name]\n+\n+ def key(**parallel):\n+ return str(_runner(runner_cls, **parallel).get_cache_key_extras([]))\n+\n+ # vLLM's flashinfer_cutedsl backend sets offset = ep_rank * num_local_experts.\n+ assert key(local_expert_offset=0) == key(local_expert_offset=32)\n+ assert key(local_expert_offset=0) == key(local_expert_offset=64)\n+\n+ # Configuration that is NOT rank-derived must still distinguish entries.\n+ assert key(num_experts=256) != key(num_experts=128)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(moe): keep CuTe-DSL MoE autotune cache keys rank-invariant\nLabels: run-ci, op: moe, v0.7.2, reinforcement learning\nFiles changed (2): flashinfer/fused_moe/cute_dsl/tuner.py, tests/moe/test_cute_dsl_moe_cache_key.py\n\n## Description (results removed)\n\n## 📌 Description\n\nDrop `local_expert_offset` from the persisted autotune cache key of `CuteDslFusedMoERunner` and `CuteDslFusedMoEW4A16Runner`. vLLM's `flashinfer_cutedsl` backend sets it to `ep_rank * local_num_experts`, so under `set_autotune_process_group` EP ranks compute different file keys: the rank that saved the cache hits and skips the timing all-reduce while the other ranks block in it — warm restarts hang (vllm-project/vllm#57423).\n\n## 🔍 Related Issues\n\nFixes #6082. Related: #6006, vllm-project/vllm#57423, vllm-project/vllm#57635.\n\n## 🧪 Tests\n[results removed]\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\n- Verified locally via a CPU-level check of `get_cache_key_extras` (same standard as #6006's test); the multi-rank deadlock itself needs TP>=2 and was not reproduced here.\n- One adjacent finding, out of scope for this PR: `MoERunner._cache_key_extras` in `fused_moe/runners.py` also keys on `experts.local_expert_offset`, so the new-style runners built on it (TrtllmFp4, Cake) look exposed to the same EP warm-start hang. Happy to fold it in or follow up — whichever you prefer.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Distributed Mixture-of-Experts autotuning now shares cache entries across ranks with different local expert slices.\n * Cache entries continue to distinguish configurations with different total expert counts.\n* **Tests**\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/fused_moe/cute_dsl/tuner.py b/flashinfer/fused_moe/cute_dsl/tuner.py\nindex b96260f3584..8801458388b 100644\n--- a/flashinfer/fused_moe/cute_dsl/tuner.py\n+++ b/flashinfer/fused_moe/cute_dsl/tuner.py\n@@ -712,6 +712,11 @@ def __hash__(self):\n )\n \n def get_cache_key_extras(self, inputs: List[torch.Tensor]) -> tuple:\n+ # local_expert_offset stays out of the persisted key: ranks tuned under\n+ # set_autotune_process_group must share file entries, since a cache hit\n+ # skips the group reduce. The offset only selects which expert slice is\n+ # profiled; tactic validity follows the profiled shapes, so the timing\n+ # skew it adds is averaged out by that reduce.\n extras: tuple[Any, ...] = (\n self.quant_mode,\n int(self.activation_type),\n@@ -721,7 +726,6 @@ def get_cache_key_extras(self, inputs: List[torch.Tensor]) -> tuple:\n self.situ_beta,\n self.situ_linear_beta,\n self.num_experts,\n- self.local_expert_offset,\n self.use_fused_finalize,\n self.output_dtype,\n self.enable_pdl,\n@@ -1206,11 +1210,15 @@ def __hash__(self):\n )\n \n def get_cache_key_extras(self, inputs: List[torch.Tensor]) -> tuple:\n+ # local_expert_offset stays out of the persisted key: ranks tuned under\n+ # set_autotune_process_group must share file entries, since a cache hit\n+ # skips the group reduce. The offset only selects which expert slice is\n+ # profiled; tactic validity follows the profiled shapes, so the timing\n+ # skew it adds is averaged out by that reduce.\n return (\n self.num_experts,\n self.top_k,\n self.num_local_experts,\n- self.local_expert_offset,\n self.use_fused_finalize,\n self.output_dtype,\n self.enable_pdl,\ndiff --git a/tests/moe/test_cute_dsl_moe_cache_key.py b/tests/moe/test_cute_dsl_moe_cache_key.py\nnew file mode 100644\nindex 00000000000..c6b7c0e5b9a\n--- /dev/null\n+++ b/tests/moe/test_cute_dsl_moe_cache_key.py\n@@ -0,0 +1,64 @@\n+# Copyright (c) 2026 by FlashInfer team.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+import pytest\n+\n+from flashinfer.cute_dsl import is_cute_dsl_available\n+\n+cute_dsl_available = pytest.mark.skipif(\n+ not is_cute_dsl_available(), reason=\"CuteDSL not available\"\n+)\n+\n+\n+def _runner(runner_cls, **parallel):\n+ kwargs = dict(\n+ num_experts=256,\n+ top_k=8,\n+ num_local_experts=32,\n+ local_expert_offset=0,\n+ )\n+ kwargs.update(parallel)\n+ if runner_cls.__name__ == \"CuteDslFusedMoERunner\":\n+ return runner_cls(forward_impl=lambda *a, **k: None, **kwargs)\n+ return runner_cls(**kwargs)\n+\n+\n+@cute_dsl_available\n+@pytest.mark.parametrize(\n+ \"runner_name\",\n+ [\"CuteDslFusedMoERunner\", \"CuteDslFusedMoEW4A16Runner\"],\n+)\n+def test_cute_dsl_moe_cache_key_is_rank_invariant(runner_name):\n+ \"\"\"Ranks tuned together must share persisted tactics: a cache hit skips the\n+ set_autotune_process_group reduce, so a rank-derived key made only the rank\n+ that saved the cache file hit and deadlocked the others.\"\"\"\n+ from flashinfer.fused_moe.cute_dsl.tuner import (\n+ CuteDslFusedMoERunner,\n+ CuteDslFusedMoEW4A16Runner,\n+ )\n+\n+ runner_cls = {\n+ \"CuteDslFusedMoERunner\": CuteDslFusedMoERunner,\n+ \"CuteDslFusedMoEW4A16Runner\": CuteDslFusedMoEW4A16Runner,\n+ }[runner_name]\n+\n+ def key(**parallel):\n+ return str(_runner(runner_cls, **parallel).get_cache_key_extras([]))\n+\n+ # vLLM's flashinfer_cutedsl backend sets offset = ep_rank * num_local_experts.\n+ assert key(local_expert_offset=0) == key(local_expert_offset=32)\n+ assert key(local_expert_offset=0) == key(local_expert_offset=64)\n+\n+ # Configuration that is NOT rank-derived must still distinguish entries.\n+ assert key(num_experts=256) != key(num_experts=128)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(jit): reuse artifacts downloaded by concurrent workers\nLabels: run-ci\nFiles changed (2): flashinfer/jit/cubin_loader.py, tests/test_artifacts.py\n\n## Description (results removed)\n\n## 📌 Description\n\nWhen concurrent workers miss the same artifact cache entry, each currently queues a download and atomically replaces the destination, even after another worker has populated it. Recheck the requested checksum under the existing download lock so waiting workers reuse that artifact and preserve its file identity.\n\n## 🔍 Related Issues\n\nFixes #3507.\n\nRelated to #2987, specifically download coordination (item 2). This is a narrow correction to the existing per-file lock, not the broader sentinel redesign.\n\n## 🧪 Tests\n[results removed]\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\nThe checksum recheck uses the existing `load_cubin()` policy, including `FLASHINFER_CUBIN_CHECKSUM_DISABLED`. Atomic replacement remains in place for artifacts that need downloading. Existing nonpositive-retry behavior is preserved by explicitly returning `None` on the previous fall-through path.\n\nAI assistance was used to implement, test, and review this change.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Artifact retrieval now reuses cached files that match the expected checksum, avoiding unnecessary downloads.\n * Simultaneous requests for the same uncached artifact now share a single download, including when the cache is empty or outdated.\n * Valid zero-byte artifacts are reused from the cache.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/jit/cubin_loader.py b/flashinfer/jit/cubin_loader.py\nindex 285c1735ba3..11eb510b456 100644\n--- a/flashinfer/jit/cubin_loader.py\n+++ b/flashinfer/jit/cubin_loader.py\n@@ -23,11 +23,14 @@\n from urllib.parse import urljoin\n import shutil\n import time\n-from typing import Union\n+from typing import TYPE_CHECKING, Union\n import uuid\n \n import filelock\n \n+if TYPE_CHECKING:\n+ import requests # type: ignore[import-untyped]\n+\n from .core import logger\n from .env import FLASHINFER_CUBIN_DIR\n \n@@ -75,8 +78,10 @@ def download_file(\n delay: int = 5,\n timeout: int = 10,\n lock_timeout: int = 30,\n- session=None,\n-):\n+ session: \"requests.Session | None\" = None,\n+ *,\n+ expected_sha256: str | None = None,\n+) -> bool | None:\n \"\"\"\n Downloads a file from a URL or copies from a local path to a destination.\n If the filesystem supports atomic file rename operations, the destination file is\n@@ -89,6 +94,8 @@ def download_file(\n - delay (int): Initial delay in seconds for exponential backoff (default: 5).\n - timeout (int): Timeout for the HTTP request in seconds (default: 10).\n - lock_timeout (int): Timeout in seconds for the file lock (default: 30).\n+ - expected_sha256 (str | None): Reuse a matching cached file after acquiring\n+ the lock. None preserves unconditional download/copy behavior.\n \n Returns:\n - bool: True if download or copy is successful, False otherwise.\n@@ -106,6 +113,14 @@ def download_file(\n with lock:\n logger.info(f\"Acquired lock for {destination}\")\n \n+ # Another worker may have populated the cache while we waited.\n+ # Preserve that file's identity for readers such as the compiler.\n+ if (\n+ expected_sha256 is not None\n+ and load_cubin(destination, expected_sha256) is not None\n+ ):\n+ return True\n+\n temp_path = f\"{destination}.{uuid.uuid4().hex}.tmp\"\n \n # Handle local file copy\n@@ -168,6 +183,8 @@ def download_file(\n )\n return False\n \n+ return None\n+\n \n def get_meta_hash(\n checksums_bytes: bytes, target_file: str = \"flashinferMetaInfo.h\"\n@@ -202,12 +219,12 @@ def verify_cubin(cubin_path: str, expected_sha256: str) -> bool:\n return True\n \n \n-def load_cubin(cubin_path: str, sha256: str) -> bytes:\n+def load_cubin(cubin_path: str, sha256: str) -> bytes | None:\n \"\"\"\n- Load a cubin from the provide local path and\n+ Load a cubin from the provided local path and\n ensure that the sha256 signature matches.\n \n- Return None on failure.\n+ Return its bytes (which may be empty) on success, or None on failure.\n \"\"\"\n logger.debug(f\"Loading from {cubin_path}\")\n try:\n@@ -225,10 +242,12 @@ def load_cubin(cubin_path: str, sha256: str) -> bytes:\n )\n except Exception:\n pass\n- return b\"\"\n+ return None\n \n \n-def get_artifact(file_name: str, sha256: str, session=None) -> bytes:\n+def get_artifact(\n+ file_name: str, sha256: str, session: \"requests.Session | None\" = None\n+) -> bytes:\n \"\"\"Load an artifact (cubin, header, checksum, etc.) from the local cache.\n \n Checks ``FLASHINFER_CUBIN_DIR / file_name`` first. If the file is missing\n@@ -239,7 +258,7 @@ def get_artifact(file_name: str, sha256: str, session=None) -> bytes:\n \"\"\"\n local_path = str(FLASHINFER_CUBIN_DIR / file_name)\n data = load_cubin(local_path, sha256)\n- if data:\n+ if data is not None:\n return data\n \n if os.getenv(\"FLASHINFER_NO_DOWNLOAD\"):\n@@ -253,8 +272,8 @@ def get_artifact(file_name: str, sha256: str, session=None) -> bytes:\n os.makedirs(os.path.dirname(local_path), exist_ok=True)\n uri = safe_urljoin(FLASHINFER_CUBINS_REPOSITORY, file_name)\n logger.info(f\"Fetching {file_name} from {uri}\")\n- download_file(uri, local_path, session=session)\n- return load_cubin(local_path, sha256)\n+ download_file(uri, local_path, session=session, expected_sha256=sha256)\n+ return load_cubin(local_path, sha256) or b\"\"\n \n \n # Backward-compatible alias\ndiff --git a/tests/test_artifacts.py b/tests/test_artifacts.py\nindex c4f95435045..db3987dcc2e 100644\n--- a/tests/test_artifacts.py\n+++ b/tests/test_artifacts.py\n@@ -1,6 +1,8 @@\n import hashlib\n import logging\n+from concurrent.futures import ThreadPoolExecutor\n from pathlib import Path\n+from threading import Barrier, local\n \n from flashinfer.artifacts import (\n ArtifactPath,\n@@ -13,9 +15,76 @@\n import responses\n \n from flashinfer.jit.cubin_loader import safe_urljoin\n+from flashinfer.jit import cubin_loader\n+\n+\n+@pytest.mark.parametrize(\"cached_content\", [None, b\"stale header\"])\n+@pytest.mark.parametrize(\n+ \"content\", [b\"\", b\"#pragma once\\nenum class Layout { Linear };\\n\"]\n+)\n+def test_concurrent_get_artifact_downloads_once(\n+ tmp_path: Path,\n+ monkeypatch: pytest.MonkeyPatch,\n+ cached_content: bytes | None,\n+ content: bytes,\n+) -> None:\n+ \"\"\"Concurrent cache misses must not replace an already verified artifact.\"\"\"\n+ checksum = hashlib.sha256(content).hexdigest()\n+ destination = tmp_path / \"header.h\"\n+ if cached_content is not None:\n+ destination.write_bytes(cached_content)\n+ monkeypatch.setattr(cubin_loader, \"FLASHINFER_CUBIN_DIR\", tmp_path)\n+ monkeypatch.setattr(\n+ cubin_loader, \"FLASHINFER_CUBINS_REPOSITORY\", \"https://example.test/\"\n+ )\n+ monkeypatch.delenv(\"FLASHINFER_NO_DOWNLOAD\", raising=False)\n+ monkeypatch.delenv(\"FLASHINFER_CUBIN_CHECKSUM_DISABLED\", raising=False)\n+\n+ workers = 4\n+ first_reads = Barrier(workers, timeout=10)\n+ state = local()\n+ load_cubin = cubin_loader.load_cubin\n+\n+ def synchronized_first_read(path: str, sha256: str) -> bytes | None:\n+ \"\"\"Wait for every worker's initial cache read before allowing downloads.\"\"\"\n+ data = load_cubin(path, sha256)\n+ if not getattr(state, \"read_once\", False):\n+ state.read_once = True\n+ # Every worker sees a miss before any worker can start downloading.\n+ first_reads.wait()\n+ return data\n+\n+ monkeypatch.setattr(cubin_loader, \"load_cubin\", synchronized_first_read)\n+ with responses.RequestsMock() as http:\n+ http.add(\n+ responses.GET, \"https://example.test/header.h\", body=content, status=200\n+ )\n+ with ThreadPoolExecutor(max_workers=workers) as pool:\n+ futures = [\n+ pool.submit(cubin_loader.get_artifact, \"header.h\", checksum)\n+ for _ in range(workers)\n+ ]\n+ assert [future.result(timeout=15) for future in futures] == [\n+ content\n+ ] * workers\n+ assert len(http.calls) == 1\n+ assert destination.read_bytes() == content\n+\n+\n+def test_get_artifact_reuses_empty_cache(\n+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch\n+) -> None:\n+ \"\"\"A checksum-valid empty file is a cache hit even when downloads are disabled.\"\"\"\n+ (tmp_path / \"empty.h\").write_bytes(b\"\")\n+ monkeypatch.setattr(cubin_loader, \"FLASHINFER_CUBIN_DIR\", tmp_path)\n+ monkeypatch.setenv(\"FLASHINFER_NO_DOWNLOAD\", \"1\")\n+ monkeypatch.delenv(\"FLASHINFER_CUBIN_CHECKSUM_DISABLED\", raising=False)\n+\n+ assert cubin_loader.get_artifact(\"empty.h\", hashlib.sha256(b\"\").hexdigest()) == b\"\"\n \n \n def test_sanity_check_urllib_behavior():\n+ \"\"\"Check directory and absolute-path handling when joining artifact URLs.\"\"\"\n # We use safe_urljoin which ensures the base is always treated as a directory\n # by adding a trailing slash if needed before calling urljoin.\n base_with_trailing_slash = \"https://example.com/some/path/\"\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(cake_causal_conv1d): the backward no longer stalls behind kernels resident on other streams\nLabels: run-ci, op: misc, op: linear attention\nFiles changed (19): benchmarks/bench_cake_causal_conv1d_train.py, docs/api/mamba.rst, flashinfer/cake_causal_conv1d_train.py, flashinfer/cake_causal_conv1d_train_backend/__init__.py, flashinfer/cake_causal_conv1d_train_backend/build.json, flashinfer/cake_causal_conv1d_train_backend/cake_jit.py, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_binding.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_kernel.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_binding.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_kernel.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_9a07bcaa0223632640ee_binding.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_9a07bcaa0223632640ee_kernel.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_aeff6106e2822f313a0c_binding.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_aeff6106e2822f313a0c_kernel.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_be6f561d1572ef3c852a_binding.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_be6f561d1572ef3c852a_kernel.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_e08749684c395f2ab65e_binding.cu, flashinfer/cake_causal_conv1d_train_backend/csrc/cake_causal_conv1d_train_e08749684c395f2ab65e_kernel.cu, tests/norm/test_cake_causal_conv1d_train.py\n\n## Description (results removed)\n\n`flashinfer.cake_causal_conv1d_train_backend` provides the training path for `flashinfer.mamba` causal conv1d. That path is a width-4 depthwise causal conv with fused SiLU over packed variable-length sequences (`cu_seqlens`), with BF16 activations and FP32 taps `[C, 4]`. The path has two kernels: a forward and a backward that computes dx and a deterministic dweight. This PR replaces only the backward.\n\n[table with results removed]\n\n**NVIDIA B200, `sm_100a`, 148 SMs, driver 580.82.07, CUDA 13.0 (PyTorch 2.14.1+cu130)**\n\n[table with results removed]\n\n**NVIDIA GB300, `sm_103a`, 152 SMs, driver 580.159.03, CUDA 13.0 (PyTorch 2.14.1+cu130)**\n\n[table with results removed]\n\n**NVIDIA R200 (pre-production), `sm_107a`, 212 SMs, driver 620.62, CUDA 13.0 (PyTorch 2.14.1+cu130)**\n\n[table with results removed]\n\n## Diff\n\n```diff\ndiff --git a/benchmarks/bench_cake_causal_conv1d_train.py b/benchmarks/bench_cake_causal_conv1d_train.py\nindex df16b97cdbe..ec350c07f1b 100644\n--- a/benchmarks/bench_cake_causal_conv1d_train.py\n+++ b/benchmarks/bench_cake_causal_conv1d_train.py\n@@ -30,10 +30,21 @@\n cold L2 (``flashinfer.testing.bench_gpu_time(enable_cupti=True)``);\n multi-kernel comparators report the sum of their kernels' GPU time.\n \n+``--side-kernel`` adds, per row and comparator, the backward's wall latency on\n+its stream (CUDA events, median of seven calls after three warm-ups) alone and\n+with a kernel resident on another stream, and their ratio (FlashInfer issue\n+#7038: a cooperative launch waits for such a kernel to finish; the Cake\n+backward is two ordinary launches). ``one-thread`` is the issue's recipe,\n+one CTA of one thread (``torch.cuda._sleep``); ``nccl-like`` a spin kernel of\n+8 CTAs x 512 threads, the footprint of a communication kernel, which takes\n+slots from eight SMs so the displaced CTAs run in a later wave. Information,\n+not a gate: the kernel's own GPU time is unchanged either way.\n+\n Example::\n \n python benchmarks/bench_cake_causal_conv1d_train.py\n python benchmarks/bench_cake_causal_conv1d_train.py --channels 512 --tokens 250340 --json out.json\n+ python benchmarks/bench_cake_causal_conv1d_train.py --channels 512 --tokens 261393 --side-kernel nccl-like\n \"\"\"\n \n from __future__ import annotations\n@@ -63,6 +74,32 @@\n # Four unequal documents: floor(fraction x S) tokens each, nudged off a multiple of 64, the rest last.\n PERF_FRACTIONS = (0.37, 0.29, 0.21)\n SEED = 0\n+# The kernels resident on another stream while the backward is timed (``--side-kernel``): CTAs x threads.\n+SIDE_KERNELS = {\"one-thread\": (1, 1), \"nccl-like\": (8, 512)}\n+ [comment with results removed]\n+SIDE_KERNEL_CYCLES = 10_000_000\n+SIDE_KERNEL_WARMUPS = 3\n+SIDE_KERNEL_SAMPLES = 7\n+\n+# The ``nccl-like`` side kernel: every thread spins on the SM clock for ``cycles``.\n+_SPIN_DECLARATION = (\n+ \"#include \\nvoid spin(int64_t ctas, int64_t threads, int64_t cycles);\"\n+)\n+_SPIN_SOURCE = r\"\"\"\n+#include \n+#include \n+\n+__global__ void spin_kernel(long long cycles) {\n+ const long long start = clock64();\n+ while (clock64() - start < cycles) {\n+ }\n+}\n+\n+void spin(int64_t ctas, int64_t threads, int64_t cycles) {\n+ spin_kernel<<(ctas), static_cast(threads), 0,\n+ at::cuda::getCurrentCUDAStream()>>>(cycles);\n+}\n+\"\"\"\n \n \n def perf_rows() -> list[tuple[int, int]]:\n@@ -95,6 +132,55 @@ def _time(fn: Callable[[], object]) -> float:\n return _median_ms(times)\n \n \n+def side_kernel_launcher(name: str) -> Callable[[], None]:\n+ \"\"\"A launcher of the resident side kernel ``name`` (:data:`SIDE_KERNELS`) on the current stream.\"\"\"\n+\n+ ctas, threads = SIDE_KERNELS[name]\n+ if (ctas, threads) == (1, 1):\n+ return lambda: torch.cuda._sleep(SIDE_KERNEL_CYCLES)\n+ from torch.utils.cpp_extension import load_inline\n+\n+ module = load_inline(\n+ name=\"cake_causal_conv1d_bench_spin\",\n+ cpp_sources=_SPIN_DECLARATION,\n+ cuda_sources=_SPIN_SOURCE,\n+ functions=[\"spin\"],\n+ )\n+ return lambda: module.spin(ctas, threads, SIDE_KERNEL_CYCLES)\n+\n+\n+def _latency_beside(\n+ fn: Callable[[], object], side_kernel: Callable[[], None], device: torch.device\n+) -> tuple[float, float]:\n+ \"\"\"``(alone_ms, beside_ms)``: the median wall latency of ``fn`` on the current stream (CUDA events) over\n+ :data:`SIDE_KERNEL_SAMPLES` calls after :data:`SIDE_KERNEL_WARMUPS`, alone and with ``side_kernel``\n+ resident on another stream (launched there first, then given time to become resident).\"\"\"\n+\n+ side = torch.cuda.Stream(device=device)\n+ start = torch.cuda.Event(enable_timing=True)\n+ end = torch.cuda.Event(enable_timing=True)\n+\n+ def timed(beside: bool) -> float:\n+ torch.cuda.synchronize(device)\n+ if beside:\n+ with torch.cuda.stream(side):\n+ side_kernel()\n+ torch.cuda._sleep(\n+ 1_000_000\n+ ) # let the side kernel become resident before fn's launch\n+ start.record()\n+ fn()\n+ end.record()\n+ torch.cuda.synchronize(device)\n+ return start.elapsed_time(end)\n+\n+ for _ in range(SIDE_KERNEL_WARMUPS):\n+ timed(False)\n+ alone = _median_ms(timed(False) for _ in range(SIDE_KERNEL_SAMPLES))\n+ beside = _median_ms(timed(True) for _ in range(SIDE_KERNEL_SAMPLES))\n+ return alone, beside\n+\n+\n def _doc_ids(tokens: int, cu: torch.Tensor) -> torch.Tensor:\n return torch.bucketize(\n torch.arange(tokens, device=cu.device), cu[1:].long(), right=True\n@@ -246,7 +332,9 @@ def _partial_rows(program: str, channels: int, *, device_index: int) -> int:\n return loader.workspace_layout(record, channels, device_index=device_index)[\"rows\"]\n \n \n-def bench_row(tokens: int, channels: int, *, comparators, device) -> dict:\n+def bench_row(\n+ tokens: int, channels: int, *, comparators, device, side_kernel=None\n+) -> dict:\n generator = torch.Generator(device=device).manual_seed(SEED)\n lens = doc_lengths(tokens)\n cu = torch.tensor(\n@@ -286,6 +374,11 @@ def bench_row(tokens: int, channels: int, *, comparators, device) -> dict:\n for mode in (\"fwd\", \"bwd\", \"step\"):\n nbytes = _bytes(mode, tokens, channels, partial_rows=partial_rows)\n entry[f\"{mode}_gbps\"] = nbytes / (entry[f\"{mode}_ms\"] * 1e-3) / 1e9\n+ if side_kernel is not None:\n+ alone, beside = _latency_beside(lambda: bwd(dy), side_kernel, device)\n+ entry[\"bwd_alone_ms\"] = alone\n+ entry[\"bwd_beside_ms\"] = beside\n+ entry[\"bwd_beside_ratio\"] = beside / alone\n except Exception as exc: # keep the other comparators' rows\n entry[\"error\"] = repr(exc)[:200]\n result[\"comparators\"][comparator.name] = entry\n@@ -309,6 +402,14 @@ def _format(result: dict, names) -> list[str]:\n if gbps is not None:\n line += f\" | cake {gbps:8.0f} GB/s\"\n lines.append(line)\n+ for name in names:\n+ entry = result[\"comparators\"].get(name, {})\n+ if \"bwd_beside_ms\" in entry:\n+ lines.append(\n+ f\"S={result['tokens']:6d} C={result['channels']:5d} bwd beside the side kernel | {name}: \"\n+ f\"alone {entry['bwd_alone_ms'] * 1e3:9.2f} us, beside {entry['bwd_beside_ms'] * 1e3:9.2f} us, \"\n+ f\"{entry['bwd_beside_ratio']:.2f}x\"\n+ )\n return lines\n \n \n@@ -332,6 +433,12 @@ def main(argv: Optional[list[str]] = None) -> int:\n parser.add_argument(\n \"--json\", type=str, default=None, help=\"write all rows to this JSON file\"\n )\n+ parser.add_argument(\n+ \"--side-kernel\",\n+ choices=sorted(SIDE_KERNELS),\n+ default=None,\n+ help=\"also time the backward's wall latency alone and beside this kernel resident on another stream\",\n+ )\n args = parser.parse_args(argv)\n \n device = torch.device(\"cuda\", torch.cuda.current_device())\n@@ -355,9 +462,18 @@ def main(argv: Optional[list[str]] = None) -> int:\n tokens = args.tokens or [P2_TOKENS]\n channels = args.channels or [P1_CHANNELS]\n rows = [(s, c) for s in tokens for c in channels]\n+ side_kernel = (\n+ None if args.side_kernel is None else side_kernel_launcher(args.side_kernel)\n+ )\n results = []\n for tokens, channels in rows:\n- result = bench_row(tokens, channels, comparators=comparators, device=device)\n+ result = bench_row(\n+ tokens,\n+ channels,\n+ comparators=comparators,\n+ device=device,\n+ side_kernel=side_kernel,\n+ )\n results.append(result)\n for line in _format(result, names):\n print(line, flush=True)\n@@ -368,6 +484,7 @@ def main(argv: Optional[list[str]] = None) -> int:\n \"device\": torch.cuda.get_device_name(device),\n \"capability\": list(torch.cuda.get_device_capability(device)),\n \"torch\": torch.__version__,\n+ \"side_kernel\": args.side_kernel,\n \"rows\": results,\n },\n handle,\ndiff --git a/flashinfer/cake_causal_conv1d_train.py b/flashinfer/cake_causal_conv1d_train.py\nindex 7ae573aca15..b977fc38cc7 100644\n--- a/flashinfer/cake_causal_conv1d_train.py\n+++ b/flashinfer/cake_causal_conv1d_train.py\n@@ -32,10 +32,14 @@\n dx[t, c] = bf16(sum_k w[c, k] * dpre[t + 3 - k, c]) # dpre of another document is 0\n dweight[c, k] = sum_t dpre[t, c] * x[t - 3 + k, c] # FP32, fixed order\n \n-in one cooperative launch: ``dweight`` is reduced in a fixed order through a\n-per-CTA FP32 partial workspace (no floating-point atomics), so it is bitwise\n-reproducible for a given ``(S, C, device)``. Nothing is saved from the\n-forward but ``x``, ``w`` and ``cu_seqlens``.\n+in two ordinary launches on one stream: a persistent main program writes\n+``dx`` and one FP32 partial row of ``dweight`` per CTA into a workspace, and a\n+reduce program launched programmatically dependent on it sums the rows in a\n+fixed order (no floating-point atomics), so ``dweight`` is bitwise\n+reproducible for a given ``(S, C, device)``. Neither launch is cooperative:\n+the backward keeps its speed while kernels of other streams (NCCL\n+collectives) are resident, which a whole-device cooperative grid had to wait\n+for. Nothing is saved from the forward but ``x``, ``w`` and ``cu_seqlens``.\n \n Inputs and outputs are contiguous (``C`` a multiple of 8); ``weight`` and\n ``dweight`` are FP32 ``[C, 4]``. ``S``, ``C`` and the document count are\n@@ -147,7 +151,11 @@ def cake_causal_conv1d_train_backward(\n \n Recomputes the FP32 preactivation from ``x``, rounds it to BF16 and takes\n the SiLU derivative of the rounded value (policy A), then produces ``dx``\n- and the FP32 weight gradient in one cooperative launch.\n+ and the FP32 weight gradient in two ordinary launches on the current\n+ stream: the main program writes ``dx`` and per-CTA partial rows of the\n+ weight gradient, and a reduce program launched programmatically dependent\n+ on it sums the rows in a fixed order (no cooperative grid, so kernels\n+ resident on other streams never stall the call).\n \n The architecture's backward route may ship several programs of the kernel;\n a call runs exactly one, chosen by ``C`` through a host-side rule of the\ndiff --git a/flashinfer/cake_causal_conv1d_train_backend/__init__.py b/flashinfer/cake_causal_conv1d_train_backend/__init__.py\nindex 66fd2f23ac6..c79ea7e4534 100644\n--- a/flashinfer/cake_causal_conv1d_train_backend/__init__.py\n+++ b/flashinfer/cake_causal_conv1d_train_backend/__init__.py\n@@ -213,7 +213,7 @@ def _output(\n \n \n def _scalars(scalars: dict[str, int]) -> dict[str, int]:\n- return {key: int(scalars[key]) for key in _loader.LOGICAL_SCALARS}\n+ return {key: int(scalars[key]) for key in _loader.PLAN_SCALARS}\n \n \n def _launch(\n@@ -242,14 +242,17 @@ def cake_causal_conv1d_train_backward_workspace_bytes(\n \"\"\"Bytes of the caller-owned backward workspace for ``C`` channels on ``device``.\n \n The workspace holds the FP32 ``[rows, C, 4]`` ``dweight`` partials of the\n- cooperative backward, one row per ``n_ch_tiles`` CTAs of a program's\n- launch grid (``rows = ceil(grid / n_ch_tiles)``), sized by the largest\n- grid of the architecture's backward programs: the channel count selects\n- the program a call runs, and every program writes and reduces the leading\n- rows of its own grid inside this buffer. It depends on ``C`` and the\n- device only, so it is independent of ``S`` and one buffer serves every\n- token count; the kernel fully writes the rows it reduces, so the buffer\n- needs no zeroing between launches or CUDA Graph replays.\n+ backward's main program, one row per ``n_ch_tiles`` CTAs of a program's\n+ launch grid (``rows = ceil(grid / n_ch_tiles)``, ``grid = grid_mult x\n+ ctas_per_sm x SM count``: the bytes grow with the program's over-\n+ decomposition factor ``grid_mult``), sized by the largest grid of the\n+ architecture's backward programs: the channel count selects the program\n+ a call runs, every program writes the leading rows of its own grid inside\n+ this buffer, and its reduce program sums exactly those. It depends on\n+ ``C`` and the device only, so it is independent of ``S`` and one buffer\n+ serves every token count; the main program fully writes the rows the\n+ reduce program sums, so the buffer needs no zeroing between launches or\n+ CUDA Graph replays.\n \"\"\"\n \n device = torch.device(device)\n@@ -399,10 +402,20 @@ def cake_causal_conv1d_train_backward(\n so a given ``(S, C, device)`` always runs the same program. The\n ``workspace`` is sized for every program of the route\n (:func:`cake_causal_conv1d_train_backward_workspace_bytes`); the selected\n- program uses the leading rows of its own grid. Build every library of\n- the device's architecture (``cake_jit.specs_for_arch``) before capturing\n- a CUDA Graph: the capture holds the program selected for its shape, and\n- no JIT build may happen inside it.\n+ program uses the leading rows of its own grid.\n+\n+ A call is two ordinary launches on the current stream: the selected\n+ program writes ``dx`` and one FP32 partial row of ``dweight`` per CTA,\n+ then the route's reduce program, launched programmatically dependent on\n+ it (the launch latency overlaps the main kernel's tail; the dependency is\n+ a stream-order edge, so the pair captures into a CUDA Graph), sums the\n+ rows per channel in a fixed order. Neither launch is cooperative, so the\n+ backward keeps its speed while kernels of other streams (NCCL collectives)\n+ are resident: a cooperative grid could not start until they finished.\n+ Build every library of the device's architecture\n+ (``cake_jit.specs_for_arch``) before capturing a CUDA Graph: the capture\n+ holds the program selected for its shape, and no JIT build may happen\n+ inside it.\n \"\"\"\n \n x = _require_tensor(x, \"x\")\n@@ -445,17 +458,22 @@ def cake_causal_conv1d_train_backward(\n \"dw\": dw_out,\n \"partial\": partial,\n **_scalars(scalars),\n+ \"main_ctas\": grid_x,\n }\n- for name in names:\n- run_module(name, values, device_index=device_index)\n+ # The main program (an ordinary launch) writes dx and the partial rows; the\n+ # route's reduce program, programmatically dependent on it through its\n+ # binding's launch attribute, sums into dweight on the same stream the rows\n+ # of each channel tile that a grid of main_ctas CTAs wrote.\n+ run_module(names[0], values, device_index=device_index)\n+ run_module(record[\"reduce\"], values, device_index=device_index)\n return dx_out, dw_out\n \n \n class CakeCausalConv1dFunction(torch.autograd.Function):\n \"\"\"Autograd wrapper saving only ``(x, weight, cu_seqlens)`` for the backward.\n \n- ``forward(x, weight, cu_seqlens)`` returns ``y``; the backward launches the\n- fused ``dx`` + deterministic FP32 ``dweight`` kernel of\n+ ``forward(x, weight, cu_seqlens)`` returns ``y``; the backward runs the\n+ fused ``dx`` + deterministic FP32 ``dweight`` pair of launches of\n :func:`cake_causal_conv1d_train_backward` on the incoming gradient\n (materialized as a contiguous BF16 tensor when autograd hands over another\n layout or dtype).\ndiff --git a/flashinfer/cake_causal_conv1d_train_backend/build.json b/flashinfer/cake_causal_conv1d_train_backend/build.json\nindex 820d9ac9d13..1eb684353a7 100644\n--- a/flashinfer/cake_causal_conv1d_train_backend/build.json\n+++ b/flashinfer/cake_causal_conv1d_train_backend/build.json\n@@ -55,57 +55,11 @@\n }\n },\n \"generator\": {\n- \"cake_revision\": \"2147cb368e75839a4023c7545de2fc5466c5c288\",\n+ \"cake_revision\": \"4b8f0be5056eec7e0d4cfe263ead5140663efe67\",\n \"cuda\": \"13.4.92\",\n- \"rendered_at\": \"2026-10-21T03:20:39Z\"\n+ \"rendered_at\": \"2026-10-22T22:45:06Z\"\n },\n \"libraries\": [\n- {\n- \"arch\": \"sm_103a\",\n- \"closure_sha256\": \"2a60c38d7672b2e8bfa8caf958f8e3c5742f60c2ef87d76f82a78c00778d1b3c\",\n- \"entry\": \"run\",\n- \"gencode\": \"-gencode=arch=compute_103a,code=sm_103a\",\n- \"min_cuda\": \"12.9\",\n- \"name\": \"cake_causal_conv1d_train_0a99a2434b55be502f04_sm_103a\",\n- \"nvcc_flags\": [\n- \"--prec-div=true\",\n- \"--prec-sqrt=true\",\n- \"--ftz=false\"\n- ],\n- \"nvcc_flags_if\": [],\n- \"path\": \"aot/cake_causal_conv1d_train_0a99a2434b55be502f04_sm_103a.so\",\n- \"sha256\": {\n- \"csrc/cake_causal_conv1d_train_0a99a2434b55be502f04_binding.cu\": \"7be494fa91bd14f36a1b0afa8347cd4db52dd5dc79182909736007d1e7bc9d90\",\n- \"csrc/cake_causal_conv1d_train_0a99a2434b55be502f04_kernel.cu\": \"f24401dc53d09d7dcae3c66c3df939db819b307f9439abd99a72b74b0bc7e2bf\"\n- },\n- \"sources\": [\n- \"csrc/cake_causal_conv1d_train_0a99a2434b55be502f04_kernel.cu\",\n- \"csrc/cake_causal_conv1d_train_0a99a2434b55be502f04_binding.cu\"\n- ]\n- },\n- {\n- \"arch\": \"sm_107a\",\n- \"closure_sha256\": \"b17a57692f52c84b81d56118ce3c29c8e092161f22f5fdf2bb4adb1436bbcf3c\",\n- \"entry\": \"run\",\n- \"gencode\": \"-gencode=arch=compute_107a,code=sm_107a\",\n- \"min_cuda\": \"13.0\",\n- \"name\": \"cake_causal_conv1d_train_0a99a2434b55be502f04_sm_107a\",\n- \"nvcc_flags\": [\n- \"--prec-div=true\",\n- \"--prec-sqrt=true\",\n- \"--ftz=false\"\n- ],\n- \"nvcc_flags_if\": [],\n- \"path\": \"aot/cake_causal_conv1d_train_0a99a2434b55be502f04_sm_107a.so\",\n- \"sha256\": {\n- \"csrc/cake_causal_conv1d_train_0a99a2434b55be502f04_binding.cu\": \"7be494fa91bd14f36a1b0afa8347cd4db52dd5dc79182909736007d1e7bc9d90\",\n- \"csrc/cake_causal_conv1d_train_0a99a2434b55be502f04_kernel.cu\": \"f24401dc53d09d7dcae3c66c3df939db819b307f9439abd99a72b74b0bc7e2bf\"\n- },\n- \"sources\": [\n- \"csrc/cake_causal_conv1d_train_0a99a2434b55be502f04_kernel.cu\",\n- \"csrc/cake_causal_conv1d_train_0a99a2434b55be502f04_binding.cu\"\n- ]\n- },\n {\n \"arch\": \"sm_100a\",\n \"closure_sha256\": \"053e4624381ef6055fac3af9599e1aa87504607dcc4216d91c3ee348474e824b\",\n@@ -177,48 +131,71 @@\n },\n {\n \"arch\": \"sm_100a\",\n- \"closure_sha256\": \"2bc658f14db522f93317f038921488e2f0ec4fc30bab4b37ee85c34744edb3dc\",\n+ \"closure_sha256\": \"e8002153b24ac987f560b3241d0c1c301e245136c9445aaa74a0afb922302ee3\",\n \"entry\": \"run\",\n \"gencode\": \"-gencode=arch=compute_100a,code=sm_100a\",\n \"min_cuda\": \"12.8\",\n- \"name\": \"cake_causal_conv1d_train_21cc8e5b2b49282a47ef_sm_100a\",\n+ \"name\": \"cake_causal_conv1d_train_37e428406a0cc4a8ca1b_sm_100a\",\n \"nvcc_flags\": [\n \"--prec-div=true\",\n \"--prec-sqrt=true\",\n \"--ftz=false\"\n ],\n \"nvcc_flags_if\": [],\n- \"path\": \"aot/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_sm_100a.so\",\n+ \"path\": \"aot/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_sm_100a.so\",\n \"sha256\": {\n- \"csrc/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_binding.cu\": \"ec6574b45078c89c21f9750199b14cda45511c838eb3050a132c06b5c4361235\",\n- \"csrc/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_kernel.cu\": \"79cfc50e17c4e288f6c0d96f0dfb3545c002b359a4f68a17e79124cb9b47c3f0\"\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_binding.cu\": \"1a45290d23054318c081c5b5e1e53cc79f669aca168235b119bcf2642f91aab5\",\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_kernel.cu\": \"3504df09718d8e734228a87222b7306d66a220d88b4e1ffa09ac7576b594ee30\"\n },\n \"sources\": [\n- \"csrc/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_kernel.cu\",\n- \"csrc/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_binding.cu\"\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_kernel.cu\",\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_binding.cu\"\n ]\n },\n {\n \"arch\": \"sm_103a\",\n- \"closure_sha256\": \"d4a74a9d070f0d590d9774bdbeff261c9d4eaf578c949430b1da0bc5a5438c9d\",\n+ \"closure_sha256\": \"9dd197b64b5ba7e1b98b423ee6d554b732fd952b3c3cdcb7d27ba5b5fa21daee\",\n \"entry\": \"run\",\n \"gencode\": \"-gencode=arch=compute_103a,code=sm_103a\",\n \"min_cuda\": \"12.9\",\n- \"name\": \"cake_causal_conv1d_train_21cc8e5b2b49282a47ef_sm_103a\",\n+ \"name\": \"cake_causal_conv1d_train_37e428406a0cc4a8ca1b_sm_103a\",\n+ \"nvcc_flags\": [\n+ \"--prec-div=true\",\n+ \"--prec-sqrt=true\",\n+ \"--ftz=false\"\n+ ],\n+ \"nvcc_flags_if\": [],\n+ \"path\": \"aot/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_sm_103a.so\",\n+ \"sha256\": {\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_binding.cu\": \"1a45290d23054318c081c5b5e1e53cc79f669aca168235b119bcf2642f91aab5\",\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_kernel.cu\": \"3504df09718d8e734228a87222b7306d66a220d88b4e1ffa09ac7576b594ee30\"\n+ },\n+ \"sources\": [\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_kernel.cu\",\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_binding.cu\"\n+ ]\n+ },\n+ {\n+ \"arch\": \"sm_107a\",\n+ \"closure_sha256\": \"f692b1202b5b0aa993675edd687d0e657c9c3860321ddfbc8a0c53c91d50ec0d\",\n+ \"entry\": \"run\",\n+ \"gencode\": \"-gencode=arch=compute_107a,code=sm_107a\",\n+ \"min_cuda\": \"13.0\",\n+ \"name\": \"cake_causal_conv1d_train_37e428406a0cc4a8ca1b_sm_107a\",\n \"nvcc_flags\": [\n \"--prec-div=true\",\n \"--prec-sqrt=true\",\n \"--ftz=false\"\n ],\n \"nvcc_flags_if\": [],\n- \"path\": \"aot/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_sm_103a.so\",\n+ \"path\": \"aot/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_sm_107a.so\",\n \"sha256\": {\n- \"csrc/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_binding.cu\": \"ec6574b45078c89c21f9750199b14cda45511c838eb3050a132c06b5c4361235\",\n- \"csrc/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_kernel.cu\": \"79cfc50e17c4e288f6c0d96f0dfb3545c002b359a4f68a17e79124cb9b47c3f0\"\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_binding.cu\": \"1a45290d23054318c081c5b5e1e53cc79f669aca168235b119bcf2642f91aab5\",\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_kernel.cu\": \"3504df09718d8e734228a87222b7306d66a220d88b4e1ffa09ac7576b594ee30\"\n },\n \"sources\": [\n- \"csrc/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_kernel.cu\",\n- \"csrc/cake_causal_conv1d_train_21cc8e5b2b49282a47ef_binding.cu\"\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_kernel.cu\",\n+ \"csrc/cake_causal_conv1d_train_37e428406a0cc4a8ca1b_binding.cu\"\n ]\n },\n {\n@@ -430,117 +407,209 @@\n },\n {\n \"arch\": \"sm_100a\",\n- \"closure_sha256\": \"3318336f9009946d7c78a965e4bbaa21b674538586bb64e0f8e8a786b018d857\",\n+ \"closure_sha256\": \"f3bcbc8024220cf96e2c52e928d6fd42635e895ee4f2f894e6963369bb31d112\",\n \"entry\": \"run\",\n \"gencode\": \"-gencode=arch=compute_100a,code=sm_100a\",\n \"min_cuda\": \"12.8\",\n- \"name\": \"cake_causal_conv1d_train_90351ecca30604957251_sm_100a\",\n+ \"name\": \"cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_sm_100a\",\n \"nvcc_flags\": [\n \"--prec-div=true\",\n \"--prec-sqrt=true\",\n \"--ftz=false\"\n ],\n \"nvcc_flags_if\": [],\n- \"path\": \"aot/cake_causal_conv1d_train_90351ecca30604957251_sm_100a.so\",\n+ \"path\": \"aot/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_sm_100a.so\",\n \"sha256\": {\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_binding.cu\": \"34c8d3f1aceb3f8e9a8156add105ba9d9a51d381d81f8c7b5a11626de2fc0ec9\",\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_kernel.cu\": \"e45c70b81fd4318d01e36c1adaf1294c6d43f20b2ffe1c9f0eab0e16690df7a3\"\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_binding.cu\": \"d5fa91dc7db660b8c05442e32809fa474e910a0dff7fc6577962bfff56ddd4c0\",\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_kernel.cu\": \"e9267837f6e6b0128c7a8a43bbc57c062603d951aba134d12d54f4189a466b6c\"\n },\n \"sources\": [\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_kernel.cu\",\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_binding.cu\"\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_kernel.cu\",\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_binding.cu\"\n ]\n },\n {\n \"arch\": \"sm_103a\",\n- \"closure_sha256\": \"16e15c41d41edbbeb737e62c4e423d2b17d5123022c793e15dd7111074d9ab46\",\n+ \"closure_sha256\": \"f7c6b3320e791bc858f1d873ed202a3372396b66db1c9703e037faa44705ac97\",\n \"entry\": \"run\",\n \"gencode\": \"-gencode=arch=compute_103a,code=sm_103a\",\n \"min_cuda\": \"12.9\",\n- \"name\": \"cake_causal_conv1d_train_90351ecca30604957251_sm_103a\",\n+ \"name\": \"cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_sm_103a\",\n+ \"nvcc_flags\": [\n+ \"--prec-div=true\",\n+ \"--prec-sqrt=true\",\n+ \"--ftz=false\"\n+ ],\n+ \"nvcc_flags_if\": [],\n+ \"path\": \"aot/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_sm_103a.so\",\n+ \"sha256\": {\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_binding.cu\": \"d5fa91dc7db660b8c05442e32809fa474e910a0dff7fc6577962bfff56ddd4c0\",\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_kernel.cu\": \"e9267837f6e6b0128c7a8a43bbc57c062603d951aba134d12d54f4189a466b6c\"\n+ },\n+ \"sources\": [\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_kernel.cu\",\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_binding.cu\"\n+ ]\n+ },\n+ {\n+ \"arch\": \"sm_107a\",\n+ \"closure_sha256\": \"5e1d4d3c42a644d9eb8dc824716dd552c1585da2cfc684d046cc9c15a9f6e178\",\n+ \"entry\": \"run\",\n+ \"gencode\": \"-gencode=arch=compute_107a,code=sm_107a\",\n+ \"min_cuda\": \"13.0\",\n+ \"name\": \"cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_sm_107a\",\n \"nvcc_flags\": [\n \"--prec-div=true\",\n \"--prec-sqrt=true\",\n \"--ftz=false\"\n ],\n \"nvcc_flags_if\": [],\n- \"path\": \"aot/cake_causal_conv1d_train_90351ecca30604957251_sm_103a.so\",\n+ \"path\": \"aot/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_sm_107a.so\",\n \"sha256\": {\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_binding.cu\": \"34c8d3f1aceb3f8e9a8156add105ba9d9a51d381d81f8c7b5a11626de2fc0ec9\",\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_kernel.cu\": \"e45c70b81fd4318d01e36c1adaf1294c6d43f20b2ffe1c9f0eab0e16690df7a3\"\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_binding.cu\": \"d5fa91dc7db660b8c05442e32809fa474e910a0dff7fc6577962bfff56ddd4c0\",\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_kernel.cu\": \"e9267837f6e6b0128c7a8a43bbc57c062603d951aba134d12d54f4189a466b6c\"\n },\n \"sources\": [\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_kernel.cu\",\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_binding.cu\"\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_kernel.cu\",\n+ \"csrc/cake_causal_conv1d_train_86b5ecfbd90aca4b52e5_binding.cu\"\n ]\n },\n {\n \"arch\": \"sm_107a\",\n- \"closure_sha256\": \"1ba0f6755cae98e0c6d28317cf3127629e3e0d5d89e84c81a1aa56acf3a01712\",\n+ \"closure_sha256\": \"8efac1f2e8f0fcb716eb23cfe4b2776db3cb865db2d596efd032478cfe010998\",\n \"entry\": \"run\",\n \"gencode\": \"-gencode=arch=compute_107a,code=sm_107a\",\n \"min_cuda\": \"13.0\",\n- \"name\": \"cake_causal_conv1d_train_90351ecca30604957251_sm_107a\",\n+ \"name\": \"cake_causal_conv1d_train_9a07bcaa0223632640ee_sm_107a\",\n \"nvcc_flags\": [\n \"--prec-div=true\",\n \"--prec-sqrt=true\",\n \"--ftz=false\"\n ],\n \"nvcc_flags_if\": [],\n- \"path\": \"aot/cake_causal_conv1d_train_90351ecca30604957251_sm_107a.so\",\n+ \"path\": \"aot/cake_causal_conv1d_train_9a07bcaa0223632640ee_sm_107a.so\",\n \"sha256\": {\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_binding.cu\": \"34c8d3f1aceb3f8e9a8156add105ba9d9a51d381d81f8c7b5a11626de2fc0ec9\",\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_kernel.cu\": \"e45c70b81fd4318d01e36c1adaf1294c6d43f20b2ffe1c9f0eab0e16690df7a3\"\n+ \"csrc/cake_causal_conv1d_train_9a07bcaa0223632640ee_binding.cu\": \"a4edb9897649bbb8d3ed21a4e268d01038a796e2bf182458268c8032053cb06b\",\n+ \"csrc/cake_causal_conv1d_train_9a07bcaa0223632640ee_kernel.cu\": \"ba4ca43db6dd1650cffe8c39b88dd5296f4bccb27db178b87d9adf1caecf7ce7\"\n },\n \"sources\": [\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_kernel.cu\",\n- \"csrc/cake_causal_conv1d_train_90351ecca30604957251_binding.cu\"\n+ \"csrc/cake_causal_conv1d_train_9a07bcaa0223632640ee_kernel.cu\",\n+ \"csrc/cake_causal_conv1d_train_9a07bcaa0223632640ee_binding.cu\"\n ]\n },\n {\n \"arch\": \"sm_107a\",\n- \"closure_sha256\": \"e8388e78a766c81d1d837181af128cc5ada2f12d4835d914670b5961dceb23c5\",\n+ \"closure_sha256\": \"432c58b5b982014f65e93d67f74ef44b5edc8ae6738e29ca3d0cf78b39a0cd6f\",\n \"entry\": \"run\",\n \"gencode\": \"-gencode=arch=compute_107a,code=sm_107a\",\n \"min_cuda\": \"13.0\",\n- \"name\": \"cake_causal_conv1d_train_a3be389511a0f0889469_sm_107a\",\n+ \"name\": \"cake_causal_conv1d_train_aeff6106e2822f313a0c_sm_107a\",\n+ \"nvcc_flags\": [\n+ \"--prec-div=true\",\n+ \"--prec-sqrt=true\",\n+ \"--ftz=false\"\n+ ],\n+ \"nvcc_flags_if\": [],\n+ \"path\": \"aot/cake_causal_conv1d_train_aeff6106e2822f313a0c_sm_107a.so\",\n+ \"sha256\": {\n+ \"csrc/cake_causal_conv1d_train_aeff6106e2822f313a0c_binding.cu\": \"bc2e652ba15bcca5ffd062d3c1d07c41bc99f9a554b7de2ebd5b42d8f6bcd1d3\",\n+ \"csrc/cake_causal_conv1d_train_aeff6106e2822f313a0c_kernel.cu\": \"76d4a94b966bdc0475a343a077c9afa34ea91ec981d442b2a35ade4c858966d5\"\n+ },\n+ \"sources\": [\n+ \"csrc/cake_causal_conv1d_train_aeff6106e2822f313a0c_kernel.cu\",\n+ \"csrc/cake_causal_conv1d_train_aeff6106e2822f313a0c_binding.cu\"\n+ ]\n+ },\n+ {\n+ \"arch\": \"sm_103a\",\n+ \"closure_sha256\": \"16f121a15b281565592a44624ea6fbcec8372cdb3377ef98ed69e9ef43d1e901\",\n+ \"entry\": \"run\",\n[... diff truncated: 14 more file(s) not shown]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(gemm): order the TMEM and DSMEM hand-offs of the cluster split-K BF16 GEMM\nLabels: run-ci, op: gemm\nFiles changed (2): flashinfer/gemm/kernels/dense_bf16_gemm_sm100_splitk.py, tests/gemm/test_mm_bf16_cute_dsl_splitk_sync.py\n\n## Description (results removed)\n\n## 📌 Description\n\nFixes three synchronization defects in the cluster split-K BF16 GEMM (`flashinfer/gemm/kernels/dense_bf16_gemm_sm100_splitk.py`, a runner of `mm_bf16(backend=\"cute-dsl\")`):\n\n1. **TMEM freed before the epilogue reads it (#6786).** The MMA warp made its `bar_tmem_alloc` release arrival and then waited on parity 1, without first waiting for phase 0. If two or more epilogue warps had not yet made their phase-0 arrival, that release arrival counted toward phase 0. The parity-1 wait then returned at once, because `phaseParity` names the current or the immediately preceding phase (PTX ISA, `mbarrier.try_wait`), and `tcgen05.dealloc` ran early. The MMA warp now waits for phase 0 first.\n2. **Cluster-scope acquire of the peer partials.** The owner CTA waited for the peers' `st.async` partials at the default `.acquire.cta`. Their complete-tx releases at `.cluster` scope, which a `.cta` acquire does not synchronize with. The owner now waits with `mbarrier.try_wait.parity.acquire.cluster`.\n3. **tcgen05 fences.** Every mbarrier hand-off of tcgen05 work now has `tcgen05.fence::before_thread_sync` before the arrival and `tcgen05.fence::after_thread_sync` after the wait, following the PTX ISA's canonical tcgen05 synchronization patterns.\n\n[details with results removed]\n\n## 🔍 Related Issues\n\nFixes #6786\n\n## 🧪 Tests\n[results removed]\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\n- Fences: the PTX patterns spell out the MMA-done → `tcgen05.ld` and `tcgen05.ld` → TMEM release → `tcgen05.dealloc` hand-offs. The TMEM-pointer and operands-full → MMA hand-offs are fenced the same way, for one uniform form at no measurable cost.\n- The two new helpers use inline PTX, like the file's existing `mapa` / `st.async` helpers. The wait loop has the same form as CUTLASS's `ClusterBarrier::wait`.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Improved the consistency of split-K BF16 GEMM results across repeated CUDA graph replays and eager launches.\n * Updated synchronization for split-K computations to help ensure results remain stable across supported hardware, including SM100, SM103, and SM107.\n * Verified stability across multiple matrix sizes and split-K configurations, with repeated runs using different activation functions.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/gemm/kernels/dense_bf16_gemm_sm100_splitk.py b/flashinfer/gemm/kernels/dense_bf16_gemm_sm100_splitk.py\nindex b2723b9f14c..ad5e831ab06 100644\n--- a/flashinfer/gemm/kernels/dense_bf16_gemm_sm100_splitk.py\n+++ b/flashinfer/gemm/kernels/dense_bf16_gemm_sm100_splitk.py\n@@ -443,6 +443,55 @@ def _store_shared_remote_v4(\n )\n \n \n+@dsl_user_op\n+def _mbarrier_wait_acquire_cluster(\n+ mbar_ptr: \"cute.Pointer\",\n+ phase: \"Int32\",\n+ *,\n+ loc=None,\n+ ip=None,\n+) -> None:\n+ \"\"\"``cute.arch.mbarrier_wait`` with ``.acquire.cluster`` semantics.\n+\n+ The peers' ``st.async`` complete-tx operations release at cluster scope; the\n+ default ``.acquire.cta`` wait does not synchronize with other CTAs' threads.\n+ \"\"\"\n+ llvm.inline_asm(\n+ None,\n+ [\n+ mbar_ptr.toint(loc=loc, ip=ip).ir_value(),\n+ phase.ir_value(loc=loc, ip=ip),\n+ ],\n+ \"{\\n\\t.reg .pred P1;\\n\\tLAB_WAIT:\\n\\t\"\n+ \"mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 \"\n+ \"P1, [$0], $1, 10000000;\\n\\t\"\n+ \"@P1 bra DONE;\\n\\tbra LAB_WAIT;\\n\\tDONE:\\n\\t}\",\n+ \"r,r\",\n+ has_side_effects=True,\n+ is_align_stack=False,\n+ asm_dialect=llvm.AsmDialect.AD_ATT,\n+ loc=loc,\n+ ip=ip,\n+ )\n+\n+\n+@dsl_user_op\n+def _tcgen05_fence(*, before: bool, loc=None, ip=None) -> None:\n+ \"\"\"``tcgen05.fence::{before,after}_thread_sync`` around an mbarrier hand-off of\n+ tcgen05 work (PTX ISA canonical tcgen05 synchronization patterns).\"\"\"\n+ llvm.inline_asm(\n+ None,\n+ [],\n+ f\"tcgen05.fence::{'before' if before else 'after'}_thread_sync;\",\n+ \"\",\n+ has_side_effects=True,\n+ is_align_stack=False,\n+ asm_dialect=llvm.AsmDialect.AD_ATT,\n+ loc=loc,\n+ ip=ip,\n+ )\n+\n+\n #: Rank that gathers partials and stores the output.\n OWNER_RANK = 0\n \n@@ -774,6 +823,7 @@ def mma_warp(\n ):\n num_tmem_cols = 256\n cute.arch.alloc_tmem(num_tmem_cols, tmem_base_ptr, is_two_cta=False)\n+ _tcgen05_fence(before=True)\n cute.arch.mbarrier_arrive(bar_tmem_alloc)\n cute.arch.relinquish_tmem_alloc_permit(is_two_cta=False)\n \n@@ -784,6 +834,7 @@ def mma_warp(\n for k_tile in cutlass.range(k_tile_count, unroll=1):\n stage = k_tile % self.num_ab_stage\n cute.arch.mbarrier_wait(bar_full + stage, full_phase)\n+ _tcgen05_fence(before=False)\n for k_block in range(mma_inst_tile_k):\n if k_block == 0:\n mma_atom.set(tcgen05.Field.ACCUMULATE, k_tile != 0)\n@@ -802,8 +853,13 @@ def mma_warp(\n \n with cute.arch.elect_one():\n tcgen05.commit(bar_mma_epilog, None, self.cta_group)\n+ # The release arrival must land in phase 1. Made while phase 0 is still\n+ # open, it counts toward phase 0, and the parity-1 wait can then pass\n+ # before the epilogue has read TMEM.\n+ cute.arch.mbarrier_wait(bar_tmem_alloc, 0)\n cute.arch.mbarrier_arrive(bar_tmem_alloc)\n cute.arch.mbarrier_wait(bar_tmem_alloc, 1)\n+ _tcgen05_fence(before=False)\n cute.arch.dealloc_tmem(tmem_ptr, num_tmem_cols, is_two_cta=False)\n \n @cute.experimental.jit\n@@ -826,6 +882,7 @@ def epilog_warp(\n # Wait until MMA publishes the TMEM base pointer.\n cute.arch.mbarrier_arrive(bar_tmem_alloc)\n cute.arch.mbarrier_wait(bar_tmem_alloc, 0)\n+ _tcgen05_fence(before=False)\n \n acc_view = cute.make_tensor(\n cute.arch.retrieve_tmem_ptr(self.acc_dtype, 16, tmem_base_ptr),\n@@ -889,9 +946,11 @@ def epilog_warp(\n rBiasAcc.store(rBias.load().to(self.acc_dtype))\n \n cute.arch.mbarrier_wait(bar_mma_epilog, 0)\n+ _tcgen05_fence(before=False)\n cute_ext.partition_and_copy(thr_t2r, acc_view, rAcc)\n # Make tcgen05.ld visible before TMEM release and RMEM use.\n cute.arch.fence_view_async_tmem_load()\n+ _tcgen05_fence(before=True)\n cute.arch.mbarrier_arrive(bar_tmem_alloc)\n \n # Peers publish FP32 partials; only rank 0 reduces and stores.\n@@ -922,7 +981,7 @@ def epilog_warp(\n cute.arch.mbarrier_arrive_and_expect_tx(\n bar_reduce, self.expected_transaction_bytes\n )\n- cute.arch.mbarrier_wait(bar_reduce, 0)\n+ _mbarrier_wait_acquire_cluster(bar_reduce, Int32(0))\n for peer in cutlass.range_constexpr(self.split_k - 1):\n for value_idx in cutlass.range_constexpr(values_per_thread):\n rAcc[value_idx] = (\ndiff --git a/tests/gemm/test_mm_bf16_cute_dsl_splitk_sync.py b/tests/gemm/test_mm_bf16_cute_dsl_splitk_sync.py\nnew file mode 100644\nindex 00000000000..0abe5924869\n--- /dev/null\n+++ b/tests/gemm/test_mm_bf16_cute_dsl_splitk_sync.py\n@@ -0,0 +1,121 @@\n+\"\"\"Replay stress test for the synchronization of the cluster split-K BF16 GEMM\n+(flashinfer/gemm/kernels/dense_bf16_gemm_sm100_splitk.py, a runner of\n+``mm_bf16(backend=\"cute-dsl\")``).\n+\n+The kernel hands work between warps and CTAs through mbarriers: TMEM allocation\n+and release, MMA completion, and the peers' st.async FP32 partials to the owner\n+CTA. Each case runs one explicit tactic through many CUDA-graph replays and eager\n+back-to-back PDL launches. Consecutive launches use different activations, so a\n+stale partial or accumulator is wrong rather than repeated; outputs are poisoned\n+with NaN before every run; every launch is compared bitwise with the first result,\n+which is itself checked against an FP64 reference.\n+\"\"\"\n+\n+import pytest\n+import torch\n+\n+from flashinfer.utils import get_compute_capability\n+\n+# K = 48 tiles of 128: 24 / 16 / 12 per rank at split 2 / 3 / 4, so the 4-stage\n+# ring wraps several times.\n+_N, _K, _STAGES = 4096, 6144, 4\n+_INPUTS = 4 # distinct activations, cycled over consecutive launches\n+_LAUNCHES = 16 # GEMM launches per graph or eager round\n+_GRAPH_REPLAYS = 500\n+_EAGER_ROUNDS = 20\n+_SLEEP_CYCLES = 4_000_000 # about 2 ms: the eager launches queue up behind it\n+\n+# Kernel tile (mma_m, mma_n) per public M: single row, full and partial M tiles,\n+# both mma_m values.\n+_TILES = {1: (128, 8), 8: (64, 8), 17: (128, 32), 32: (64, 32)}\n+\n+\n+def _require_splitk():\n+ if not torch.cuda.is_available():\n+ pytest.skip(\"CUDA is not available.\")\n+ if get_compute_capability(torch.device(\"cuda\")) not in ((10, 0), (10, 3), (10, 7)):\n+ pytest.skip(\"The cluster split-K kernel requires SM100/SM103/SM107.\")\n+ from flashinfer.cute_dsl.utils import is_cute_dsl_available\n+\n+ if not is_cute_dsl_available():\n+ pytest.skip(\"nvidia-cutlass-dsl is not available.\")\n+\n+\n+@pytest.mark.parametrize(\"m\", sorted(_TILES))\n+@pytest.mark.parametrize(\"split_k\", [2, 3, 4])\n+def test_splitk_replays_are_bitwise_stable(split_k, m):\n+ _require_splitk()\n+ from flashinfer.gemm.kernels.dense_bf16_gemm_sm100_splitk import (\n+ SplitKTactic,\n+ run_splitk_dense,\n+ )\n+\n+ tactic = SplitKTactic(*_TILES[m], split_k, _STAGES)\n+ case = f\"{tactic}, M={m}, N={_N}, K={_K}\"\n+\n+ generator = torch.Generator(device=\"cuda\").manual_seed(100 * split_k + m)\n+ w = torch.randn((_N, _K), device=\"cuda\", generator=generator) / _K**0.5\n+ w = w.to(torch.bfloat16)\n+ acts = torch.randn((_INPUTS, m, _K), device=\"cuda\", generator=generator)\n+ acts = acts.to(torch.bfloat16)\n+ reference = acts.double() @ w.double().T\n+ # The weights are read before the kernel's PDL wait: publish them first.\n+ torch.cuda.synchronize()\n+\n+ def launch(a, out):\n+ run_splitk_dense(a, w.T, None, out, True, tactic)\n+\n+ first = torch.empty((_INPUTS, m, _N), device=\"cuda\", dtype=torch.bfloat16)\n+ for i in range(_INPUTS):\n+ launch(acts[i], first[i])\n+ torch.cuda.synchronize()\n+ torch.testing.assert_close(\n+ first.double(),\n+ reference,\n+ rtol=1e-2,\n+ atol=1e-2,\n+ msg=lambda msg: f\"first result vs FP64 reference ({case}): {msg}\",\n+ )\n+\n+ expected = first[torch.arange(_LAUNCHES, device=\"cuda\") % _INPUTS]\n+ expected = expected.view(torch.int16)\n+ outs = torch.empty((_LAUNCHES, m, _N), device=\"cuda\", dtype=torch.bfloat16)\n+ bad_values = torch.zeros((), device=\"cuda\", dtype=torch.int64)\n+ bad_runs = torch.zeros((), device=\"cuda\", dtype=torch.int64)\n+\n+ def run_and_check():\n+ outs.fill_(float(\"nan\"))\n+ for j in range(_LAUNCHES):\n+ launch(acts[j % _INPUTS], outs[j])\n+ mismatches = (outs.view(torch.int16) != expected).sum()\n+ bad_values.add_(mismatches)\n+ bad_runs.add_((mismatches > 0).long())\n+\n+ def check(mode, runs):\n+ torch.cuda.synchronize()\n+ failed, values = bad_runs.item(), bad_values.item()\n+ assert failed == 0, (\n+ f\"bitwise mismatch between split-K launches ({mode}, {case}): \"\n+ f\"{failed} of {runs} runs of {_LAUNCHES} launches differ from the \"\n+ f\"first result, {values} values in total\"\n+ )\n+ bad_values.zero_()\n+ bad_runs.zero_()\n+\n+ run_and_check() # warm-up outside the graph\n+ graph = torch.cuda.CUDAGraph()\n+ with torch.cuda.graph(graph):\n+ run_and_check()\n+ for _ in range(_GRAPH_REPLAYS):\n+ graph.replay()\n+ check(\"CUDA graph replays\", 1 + _GRAPH_REPLAYS)\n+ del graph\n+\n+ for _ in range(_EAGER_ROUNDS):\n+ torch.cuda._sleep(_SLEEP_CYCLES)\n+ run_and_check()\n+ check(\"eager back-to-back launches\", _EAGER_ROUNDS)\n+\n+\n+if __name__ == \"__main__\":\n+ pytest.main([__file__])\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(moe_ep): pass runtime_max_tokens_per_rank in the multi-rank dispatch test\nLabels: run-ci\nFiles changed (1): tests/moe_ep/test_moe_ep_communication_multirank.py\n\n## Description (results removed)\n\n## Summary\n\n## Changes\n\n## Related Issues\n\nFixes #7689\n\n## Validation\n[results removed]\n## Tests\n[results removed]\n## Summary by CodeRabbit\n\n* **Tests**\n * Updated multirank dispatch/combine correctness tests to use the maximum token count across ranks when validating runtime limits. This is a test-only change and does not alter user-facing behavior.\n\n## Diff\n\n```diff\ndiff --git a/tests/moe_ep/test_moe_ep_communication_multirank.py b/tests/moe_ep/test_moe_ep_communication_multirank.py\nindex f6d8b1db849..8e5fa6c4b1d 100644\n--- a/tests/moe_ep/test_moe_ep_communication_multirank.py\n+++ b/tests/moe_ep/test_moe_ep_communication_multirank.py\n@@ -149,7 +149,7 @@ def test_dispatch_combine_matches_local_reference(backend, top_k):\n try:\n for _ in range(2): # the second round reuses the workspace\n received = comm.dispatch(\n- x, topk_ids, topk_weights, max_tokens_per_rank=int(step_max)\n+ x, topk_ids, topk_weights, runtime_max_tokens_per_rank=int(step_max)\n )\n rows = comm.ep_size * received.tokens_per_rank\n assert received.hidden_states.shape == (rows, hidden)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: Fix test_joint_config_validation_uses_gathered_backends when no GPUs are visible\nLabels: run-ci, op: comm\nFiles changed (1): tests/comm/test_ulysses_communicator.py\n\n## Description (results removed)\n\n## 📌 Description\nzero-GPU CI machines because encoding `cuda:0` raised a device visibility \nerror before the dtype validation could run. This PR patches \n`torch.cuda.device_count()` to return 1 via `monkeypatch` so the test \nvalidates the actual logic (dtype checking) independently of host GPU count.\n\n## 🔍 Related Issues\nCloses #7683\n\n## Summary by CodeRabbit\n\n* **Tests**\n * Made a backend validation test independent of the machine’s available GPU count.\n\n## Diff\n\n```diff\ndiff --git a/tests/comm/test_ulysses_communicator.py b/tests/comm/test_ulysses_communicator.py\nindex 67202c15f53..1da946b165b 100644\n--- a/tests/comm/test_ulysses_communicator.py\n+++ b/tests/comm/test_ulysses_communicator.py\n@@ -1051,9 +1051,13 @@ def test_per_call_dtype_is_pcie_only_and_whitelisted(gloo_pg, monkeypatch):\n pcie.close()\n \n \n-def test_joint_config_validation_uses_gathered_backends():\n+def test_joint_config_validation_uses_gathered_backends(monkeypatch):\n \"\"\"The verdict must be a pure function of the gathered configs, so every\n rank raises (or passes) together whatever backend it requested locally.\"\"\"\n+ # _encode_config range-checks the ordinal against the visible device\n+ # count. The verdict under test does not depend on the machine, so pin\n+ # a count that makes \"cuda:0\" valid even where no GPU is visible.\n+ monkeypatch.setattr(torch.cuda, \"device_count\", lambda: 1)\n encode = UlyssesCommunicator._encode_config\n pcie_int8 = encode(1 << 10, torch.int8, \"cuda:0\", \"pcie\")\n UlyssesCommunicator._validate_configs_jointly(\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(fused_moe): require CUDA 13.0 for the Cake W4A16 programs\nLabels: run-ci, op: moe\nFiles changed (2): flashinfer/fused_moe/cake_w4a16.py, tests/moe/test_cake_w4a16_fused_moe.py\n\n## Description (results removed)\n\n## Summary\n\n## Root cause\n\nptxas adds a software guardrail at `tcgen05.dealloc`. The guardrail keeps a bookkeeping mask in the reserved first 1 KiB of the CTA's shared-memory window and compares it with the columns being deallocated. If they do not match, it traps. In the CUDA 12.9 build, one box of FC1 scale factors overwrites that reserved 1 KiB, so the final dealloc traps. The kernel source never addresses that region, and CUDA 13.0 and 13.4 builds run cleanly. This PR therefore gates the route on the toolkit instead of changing the kernels.\n\nEvidence below comes from cuda-gdb on a B200 (driver 580.82.07) with the CUDA 12.9 image (nvcc 12.9.41), unless noted:\n\n- The trap frame is `$__internal_2_$.cuda_sm10x_tcgen05_guardrail_trap_unallocated_columns_being_dealloced`. In the 12.9 layout, its mask is the word at offset 0x50 of the reserved window.\n- The source computes that destination as `smem + 164864 + stage * 2048 + 1024`, which never falls below the dynamic base. The SASS address arithmetic for the four producer TMA loads is the same in the CUDA 12.9 and CUDA 13.4 builds. The two builds differ only in the E2M1 decode route and the guardrail layout.\n\n## Changes\n\n`flashinfer/fused_moe/cake_w4a16.py`\n- Add `CAKE_W4A16_MIN_CUDA = \"13.0\"`.\n- Add `cake_w4a16_toolkit_unavailable()`. It returns `None`, or a reason string that names the floor and the toolkit found. It uses `flashinfer.jit.cpp_ext.get_cuda_version` and `is_cuda_version_at_least`.\n- `_Programs.handle` raises `RuntimeError(\": \")` before it reads the program's launch record or builds it.\n- Export both new names in `__all__`, and note the floor in the module docstring.\n- `cake_w4a16_available()` keeps its loader-only meaning and does not include the toolkit check.\n\n`tests/moe/test_cake_w4a16_fused_moe.py`\n- The module fixture `cake_programs` skips the GPU tests with the toolkit reason.\n- New CPU test `TestHostLogic::test_toolkit_gate` checks three things: the reason at 12.9, `None` at 13.0 and 13.4, and that the loader refuses `FC1_N8` on 12.9 before it touches the launch record.\n\n## Validation\n[results removed]\n## Related\n\nFixes #7450\n\n## Summary by CodeRabbit\n\n* **Compatibility**\n * Cake W4A16 now requires CUDA 13.0 or later. Older toolkit versions receive a message identifying the minimum and detected versions.\n* **Testing**\n * GPU tests for Cake W4A16 are skipped when the installed CUDA toolkit is unsupported.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/fused_moe/cake_w4a16.py b/flashinfer/fused_moe/cake_w4a16.py\nindex 696d8ec07a7..c05cddfe248 100644\n--- a/flashinfer/fused_moe/cake_w4a16.py\n+++ b/flashinfer/fused_moe/cake_w4a16.py\n@@ -67,7 +67,9 @@\n the route map and gathers the token rows from ``x`` itself, so the route skips\n ``moe_permute`` for it. :func:`cake_w4a16_available` tells\n whether the loader imports and publishes every program, so tests skip cleanly\n-without it.\n+without it. The programs need CUDA :data:`CAKE_W4A16_MIN_CUDA` or newer\n+(:func:`cake_w4a16_toolkit_unavailable` says why an older toolkit cannot run\n+them); the loader refuses to build them on an older toolkit.\n \"\"\"\n \n from __future__ import annotations\n@@ -84,6 +86,7 @@\n from ..utils import device_support_pdl, get_compute_capability, get_device_properties\n \n __all__ = [\n+ \"CAKE_W4A16_MIN_CUDA\",\n \"CELLS\",\n \"FC1_ARGS\",\n \"FC2_ARGS\",\n@@ -95,6 +98,7 @@\n \"cake_w4a16_fused_moe\",\n \"cake_w4a16_grid\",\n \"cake_w4a16_prepare_workspace\",\n+ \"cake_w4a16_toolkit_unavailable\",\n \"cake_w4a16_workspace_size\",\n \"is_cake_w4a16_form\",\n \"select_cell\",\n@@ -246,6 +250,9 @@ def handle(self, kernel: str, cell: Cell, device: torch.device) -> _ProgramHandl\n key = (identifier, target)\n handle = self._handles.get(key)\n if handle is None:\n+ unavailable = cake_w4a16_toolkit_unavailable()\n+ if unavailable is not None:\n+ raise RuntimeError(f\"{identifier}: {unavailable}\")\n record = program.launch_record()\n if not record[\"use_pdl\"] or record[\"cooperative\"]:\n raise RuntimeError(\n@@ -279,6 +286,29 @@ def cake_w4a16_available() -> bool:\n return all(hasattr(loader, identifier) for identifier in PROGRAM_IDENTIFIERS)\n \n \n+# Built with CUDA 12.9, the FC1 programs trap at their TMEM deallocation\n+# (``tcgen05.dealloc``: the ptxas 12.9 tcgen05 guardrail reports unallocated\n+# columns being deallocated after its bookkeeping words in the reserved shared\n+# memory window are overwritten during the kernel); CUDA 13.0 and newer\n+# toolkits build and run the same programs cleanly, so the route refuses an\n+# older toolkit instead of failing inside a launch.\n+CAKE_W4A16_MIN_CUDA = \"13.0\"\n+\n+\n+def cake_w4a16_toolkit_unavailable() -> Optional[str]:\n+ \"\"\"Why this CUDA toolkit cannot run the Cake W4A16 programs, or ``None``.\"\"\"\n+\n+ from ..jit.cpp_ext import get_cuda_version, is_cuda_version_at_least\n+\n+ if is_cuda_version_at_least(CAKE_W4A16_MIN_CUDA):\n+ return None\n+ return (\n+ f\"the Cake W4A16 programs need CUDA {CAKE_W4A16_MIN_CUDA} or newer (built \"\n+ \"with CUDA 12.9 their FC1 kernels trap at the TMEM deallocation guardrail); \"\n+ f\"the CUDA toolkit found is {get_cuda_version()}\"\n+ )\n+\n+\n @functools.cache\n def _sm_count(device_index: int) -> int:\n return int(\ndiff --git a/tests/moe/test_cake_w4a16_fused_moe.py b/tests/moe/test_cake_w4a16_fused_moe.py\nindex 01dbf029a60..9564f335c25 100644\n--- a/tests/moe/test_cake_w4a16_fused_moe.py\n+++ b/tests/moe/test_cake_w4a16_fused_moe.py\n@@ -532,12 +532,15 @@ def compare(\n @pytest.fixture(scope=\"module\")\n def cake_programs() -> None:\n \"\"\"Skip the GPU tests unless the generated loader imports and publishes every\n- program when they run.\"\"\"\n+ program when they run, and the CUDA toolkit can run them.\"\"\"\n if not cake.cake_w4a16_available():\n pytest.skip(\n f\"the Cake W4A16 programs are not present ({cake.LOADER_MODULE} does not \"\n \"import or publishes no program)\"\n )\n+ unavailable = cake.cake_w4a16_toolkit_unavailable()\n+ if unavailable is not None:\n+ pytest.skip(unavailable)\n \n \n @pytest.fixture(scope=\"module\")\n@@ -931,6 +934,46 @@ class Full:\n monkeypatch.setattr(cake._Programs, \"_loader\", staticmethod(lambda: Full))\n assert cake.cake_w4a16_available()\n \n+ def test_toolkit_gate(self, monkeypatch):\n+ \"\"\"``cake_w4a16_toolkit_unavailable`` names the toolkit floor and the\n+ toolkit found below CUDA 13.0 and is ``None`` from 13.0 on; the loader\n+ refuses to build a program on an older toolkit before it reads the\n+ program's launch record.\"\"\"\n+ from packaging.version import Version\n+\n+ from flashinfer.jit import cpp_ext\n+\n+ assert cake.CAKE_W4A16_MIN_CUDA == \"13.0\"\n+ monkeypatch.setattr(cpp_ext, \"get_cuda_version\", lambda: Version(\"12.9\"))\n+ reason = cake.cake_w4a16_toolkit_unavailable()\n+ assert reason is not None\n+ assert \"CUDA 13.0\" in reason and \"12.9\" in reason\n+\n+ class Program:\n+ targets = (\"sm_100a\", \"sm_103a\")\n+\n+ @staticmethod\n+ def target_for(compute_capability):\n+ return \"sm_100a\"\n+\n+ @staticmethod\n+ def launch_record():\n+ raise AssertionError(\"the toolkit gate runs before the launch record\")\n+\n+ class Loader:\n+ FC1_N8 = Program()\n+\n+ monkeypatch.setattr(cake._Programs, \"_loader\", staticmethod(lambda: Loader))\n+ monkeypatch.setattr(cake, \"get_compute_capability\", lambda device: (10, 0))\n+ with pytest.raises(RuntimeError, match=\"FC1_N8: .*CUDA 13.0\"):\n+ cake._Programs().handle(\"FC1\", cake.Cell(8), torch.device(\"cpu\"))\n+\n+ for version in (\"13.0\", \"13.4\"):\n+ monkeypatch.setattr(\n+ cpp_ext, \"get_cuda_version\", lambda v=version: Version(v)\n+ )\n+ assert cake.cake_w4a16_toolkit_unavailable() is None\n+\n def test_cells_and_identifiers(self):\n assert len(cake.CELLS) == 5\n assert len(cake.PROGRAM_IDENTIFIERS) == 10\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(msa_ops): serve SM90 sparse-decode coordinates whose planned route was never delivered (#7222)\nLabels: run-ci, v0.7.3\nFiles changed (3): flashinfer/msa_ops/cake_hopper_sm90.py, tests/cpu/msa_ops/test_cake_hopper_msa_decode_planner.py, tests/msa_ops/test_msa_sm90.py\n\n## Description (results removed)\n\n## 📌 Description\n\n`flashinfer/msa_ops/cake_hopper_sm90.py::plan_sparse_decode` ports the Cake latency model for the SM90 sparse-decode programs and emits one logical route per geometry. It checked the delivered program set (`ROUTES` in `flashinfer/jit/cake_hopper_msa.py`) only for its HALF / persistent replacements, never for the model's own 128-key coordinate. On 132-SM parts (H100 SXM, H200) the model picks three ring stages for nc16 item bands (GQA group > 8) that the export delivered at two stages only, so `_decode_template` reached `route_program`, which raised `KeyError`, and `msa_sparse_decode_attention` crashed instead of computing. `_sm90_dispatch.sparse_decode_sm90` has a CuTe fallback, but it triggers on dtype / shape admission, not on a planner route without a program, so nothing caught this.\n\n**Enumeration (CPU, this tree's `ROUTES`).** `plan_sparse_decode` over `num_sms` {132, 114, 78} x GQA group {1, 4, 8, 9, 16, 17, 32, 33, 48, 49, 64} x KV heads {1, 2, 4, 8} x `seqlen_q` {1, 2, 4, 8} x batch 1..512 x `max_pages` on both sides of the three L2-policy thresholds of `seqlen_q * 16 / max_pages` plus {1, 1024}: 3,784,704 points. Before the fix: 25 distinct routes emitted, 3 of them absent from `ROUTES`, all at 132 SMs (none at 114 or 78), 64,374 points in all. After: 22 distinct routes, all delivered, and every one of the 22 delivered decode programs is emitted by some point (no unreachable program).\n\n[table with results removed]\n\n**Fix (host planner only; no kernel, binding or program change).** After the existing HALF / persistent fallback to the model's pick, the planner now checks the model's own route: if it is not delivered, it serves the two-stage ring of the same head fold, split count and L2 policy, which the export delivers for every split count of both folds (`nc{8,16}:s{1,2,4,8}:st2:{evict_first,none}:main`). The two-stage form keeps the grid, the split scratch and the kernel scalars (st2 admits every split count st3 does, `_max_splits(nc, 2) == 16` for both folds, and it needs less shared memory). If neither route is delivered the planner raises a `ValueError` naming both, from the planner rather than `KeyError` from inside the launch template. The three crashing coordinates now serve `nc16:s2:st2:evict_first`, `nc16:s1:st2:none` and `nc16:s1:st2:evict_first`.\n\nRegenerating the three st3 programs instead is the other option; this PR takes the planner-side fallback because it needs no new program and is what the v0.7.3 window allows. If the export later delivers the st3 routes, the planner serves them automatically and the pin in the CPU test retires itself (it applies only while the model's route is absent).\n\n## 🔍 Related Issues\n\nCloses #7222. The deslop PR #7332 closed the issue while listing this item under \"Not in this PR\" (\"Decode routes without a program\"); the issue was reopened on 2026-10-30 for this item only. Feature owner: yyihuang (#6252, #6140).\n\n## 🧪 Tests\n[results removed]\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\nAI-assisted.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Improved reliability of sparse decoding on SM90 when a preferred execution route is unavailable, by falling back to a supported alternative.\n * When no supported route is available, the planner now reports the unavailable options in its error.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/msa_ops/cake_hopper_sm90.py b/flashinfer/msa_ops/cake_hopper_sm90.py\nindex 84f1d85d5b2..028eff8cc42 100644\n--- a/flashinfer/msa_ops/cake_hopper_sm90.py\n+++ b/flashinfer/msa_ops/cake_hopper_sm90.py\n@@ -96,7 +96,8 @@\n # grid for one-split classes with more items than resident CTAs, and the 64-key (HALF) ring for the two q-len-1\n # classes the same-session ABBA proved (GQA 16x4 q1 b128: HALF STAGES 2 + VSEQ; b16 q1: HALF STAGES 4). Both\n # forms are physical variants of their own: ``plan_sparse_decode`` serves them only when the delivered program set\n-# has their route, otherwise the 128-key variant the latency model picked (``_route_available``).\n+# has their route, otherwise the 128-key variant the latency model picked, or that variant's two-stage ring when the\n+# export has no program for it either (``_route_available``).\n _NC16_LEAN = (\n \"qk\",\n \"v\",\n@@ -477,7 +478,10 @@ def plan_sparse_decode(\n pages inside the launch (``seqlen_q * topk / max_pages`` at or above 1.5), and for the multi-token (MTP) grids\n beyond one wave (re-selection at or above 0.5) or filling a full two-CTAs-per-SM wave (at or above 1.0), whose\n co-scheduled tokens re-select pages that ``evict_first`` has already dropped. When the delivered program set has\n- no route for a HALF / persistent form, the plan falls back to the 128-key variant the model picked.\n+ no route for a HALF / persistent form, the plan falls back to the 128-key variant the model picked; when that\n+ variant's own route was not delivered either (the three-stage nc16 coordinates the model picks on 132-SM parts),\n+ to its two-stage ring form, which the export delivers for every split count of both head folds. A coordinate\n+ with neither route raises ``ValueError`` naming both.\n \"\"\"\n \n group = num_q_heads // num_kv_heads\n@@ -561,6 +565,19 @@ def plan_sparse_decode(\n plan = replace(model, persist=True, ctas=min(base, slots))\n if plan is not model and not _route_available(plan.route):\n plan = model\n+ if not _route_available(plan.route):\n+ # The model's own coordinate was never delivered: on 132 SMs the cost model picks three ring stages for the\n+ # nc16 bands where st3's wave cost beats st2's, but the export has st3 only as nc16:s2:st3:none and the\n+ # persistent nc16:s1:st3:none (#7222). Every nc{8,16} s{1,2,4,8}:st2:{evict_first,none}:main route is\n+ # delivered, so the same grid, split count and scratch run with the two-stage ring: st2 admits every split\n+ # st3 does (``_max_splits(nc, 2)`` is 16 for both folds) and needs less shared memory.\n+ fallback = replace(model, stages=2)\n+ if not _route_available(fallback.route):\n+ raise ValueError(\n+ f\"no Hopper MSA decode program for route {model.route!r} \"\n+ f\"(nor for its two-stage ring form {fallback.route!r})\"\n+ )\n+ plan = fallback\n return plan\n \n \ndiff --git a/tests/cpu/msa_ops/test_cake_hopper_msa_decode_planner.py b/tests/cpu/msa_ops/test_cake_hopper_msa_decode_planner.py\nnew file mode 100644\nindex 00000000000..28aa6094852\n--- /dev/null\n+++ b/tests/cpu/msa_ops/test_cake_hopper_msa_decode_planner.py\n@@ -0,0 +1,166 @@\n+\"\"\"\n+Copyright (c) 2026 by FlashInfer team.\n+\n+Licensed under the Apache License, Version 2.0 (the \"License\");\n+you may not use this file except in compliance with the License.\n+You may obtain a copy of the License at\n+\n+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+\n+Route delivery of the Cake Hopper (SM90) sparse-decode planner, on the CPU.\n+\n+``plan_sparse_decode`` ports the Cake latency model and emits one logical\n+route per decode geometry; ``_decode_template`` resolves it through\n+``route_program``, which raises ``KeyError`` for a route the export did not\n+deliver. The model's own 128-key coordinate went unchecked (#7222): on 132-SM\n+parts the model picks three ring stages for nc16 bands the export delivered at\n+two stages only, so ``msa_sparse_decode_attention`` crashed for GQA groups\n+above 8 at those batch sizes. These checks hold every route the planner emits\n+over the serving grid to the delivered set, pin the three crashing coordinates\n+to a delivered route of the same grid, and the no-route error to a\n+``ValueError`` that names both routes. No CUDA device and no build; the\n+registry is the input, so a regenerated export is checked without an edit.\n+\"\"\"\n+\n+import itertools\n+\n+import pytest\n+\n+from flashinfer.jit import cake_hopper_msa as jm\n+from flashinfer.msa_ops import cake_hopper_sm90 as ch\n+\n+# The sweep's serving grid. SM counts of the Hopper parts (H100 SXM / H200, H100 PCIe, H20); GQA groups\n+# covering both head folds at chunk counts 1, 2 and 4 (nc8 below group 9, else nc16 with\n+# ``ceil(group / 16)`` chunks: the plan depends on the group only through them); KV head counts and\n+# batch sizes whose products cover the model's item-count bands (66 items wide, repeating every\n+# ``2 * num_sms`` items) densely to 512 items and at a stride of at most 8 to 4096.\n+_NUM_SMS = (132, 114, 78)\n+_GROUPS = (4, 16, 32, 64)\n+_KV_HEADS = (1, 4, 8)\n+_SEQLEN_Q = (1, 2, 4, 8)\n+_MAX_BATCH = 512\n+\n+\n+def _page_counts(seqlen_q: int) -> list[int]:\n+ \"\"\"``max_pages`` on both sides of the three L2-policy thresholds of the page re-selection ratio\n+ ``seqlen_q * 16 / max_pages`` (1.5, 1.0, 0.5), plus one page and a long context: the plan depends\n+ on the page count only through those comparisons.\"\"\"\n+ pages = {1, 1024}\n+ for threshold in (1.5, 1.0, 0.5):\n+ edge = int(seqlen_q * 16 / threshold)\n+ pages.update({edge, edge + 1})\n+ return sorted(pages)\n+\n+\n+def _grid():\n+ for num_sms, group, kv_heads, seqlen_q in itertools.product(\n+ _NUM_SMS, _GROUPS, _KV_HEADS, _SEQLEN_Q\n+ ):\n+ for max_pages in _page_counts(seqlen_q):\n+ for batch in range(1, _MAX_BATCH + 1):\n+ yield dict(\n+ total_q=batch * seqlen_q,\n+ num_q_heads=group * kv_heads,\n+ num_kv_heads=kv_heads,\n+ num_sms=num_sms,\n+ seqlen_q=seqlen_q,\n+ max_pages=max_pages,\n+ )\n+\n+\n+def test_every_emitted_decode_route_is_delivered():\n+ \"\"\"The crash of #7222 is a planner route with no program behind it.\"\"\"\n+ undelivered: dict[str, list[dict]] = {}\n+ for point in _grid():\n+ route = ch.plan_sparse_decode(**point).route\n+ if route not in jm.ROUTES:\n+ undelivered.setdefault(route, []).append(point)\n+ assert not undelivered, {\n+ route: (len(points), points[:3]) for route, points in undelivered.items()\n+ }\n+\n+\n+@pytest.mark.parametrize(\n+ \"total_q,num_q_heads,num_kv_heads,seqlen_q,max_pages,model_route,served_route\",\n+ [\n+ # q-len 1, 11+ pages, 265-330 items: the issue's hand case (batch 67, 4 KV heads).\n+ pytest.param(\n+ 67,\n+ 64,\n+ 4,\n+ 1,\n+ 16,\n+ \"decode_v5:nc16:s2:st3:evict_first:main\",\n+ \"decode_v5:nc16:s2:st2:evict_first:main\",\n+ id=\"s2-evict_first\",\n+ ),\n+ # q-len 1, at most 10 pages, 331-396 items: rule C's lean HALF form exists for ``evict_first`` only.\n+ pytest.param(\n+ 83,\n+ 64,\n+ 4,\n+ 1,\n+ 8,\n+ \"decode_v5:nc16:s1:st3:none:main\",\n+ \"decode_v5:nc16:s1:st2:none:main\",\n+ id=\"s1-none\",\n+ ),\n+ # q-len 2, 65+ pages, 332-396 items: the persistent form exists for the default policy only.\n+ pytest.param(\n+ 84,\n+ 64,\n+ 4,\n+ 2,\n+ 65,\n+ \"decode_v5:nc16:s1:st3:evict_first:main\",\n+ \"decode_v5:nc16:s1:st2:evict_first:main\",\n+ id=\"s1-evict_first\",\n+ ),\n+ ],\n+)\n+def test_the_crashing_coordinates_are_served_by_the_two_stage_ring(\n+ total_q, num_q_heads, num_kv_heads, seqlen_q, max_pages, model_route, served_route\n+):\n+ \"\"\"The three coordinates of #7222 on a 132-SM part: the model's three-stage pick was not delivered,\n+ the two-stage ring of the same split count and L2 policy is. A regenerated export that delivers\n+ the model's route serves it instead, so the pin applies only while that route is absent.\"\"\"\n+ plan = ch.plan_sparse_decode(\n+ total_q=total_q,\n+ num_q_heads=num_q_heads,\n+ num_kv_heads=num_kv_heads,\n+ num_sms=132,\n+ seqlen_q=seqlen_q,\n+ max_pages=max_pages,\n+ )\n+ assert plan.route in jm.ROUTES, plan.route\n+ if model_route not in jm.ROUTES:\n+ assert plan.route == served_route\n+ assert (plan.half, plan.persist) == (False, False)\n+\n+\n+def test_a_coordinate_with_no_delivered_program_raises_a_named_error(monkeypatch):\n+ \"\"\"A ``ValueError`` naming the model's route and its two-stage form, from the planner, instead of\n+ ``route_program``'s ``KeyError`` from inside the launch template.\"\"\"\n+ monkeypatch.setattr(ch, \"_route_available\", lambda route: False)\n+ ch.plan_sparse_decode.cache_clear()\n+ try:\n+ with pytest.raises(\n+ ValueError,\n+ match=r\"'decode_v5:nc16:s2:st3:evict_first:main'.*'decode_v5:nc16:s2:st2:evict_first:main'\",\n+ ):\n+ ch.plan_sparse_decode(\n+ total_q=67,\n+ num_q_heads=64,\n+ num_kv_heads=4,\n+ num_sms=132,\n+ seqlen_q=1,\n+ max_pages=16,\n+ )\n+ finally:\n+ ch.plan_sparse_decode.cache_clear()\ndiff --git a/tests/msa_ops/test_msa_sm90.py b/tests/msa_ops/test_msa_sm90.py\nindex 745a629f612..34db80bf0d4 100644\n--- a/tests/msa_ops/test_msa_sm90.py\n+++ b/tests/msa_ops/test_msa_sm90.py\n@@ -61,8 +61,10 @@ def _decode_inputs(\n device=\"cuda\",\n seed=0,\n packed=True,\n+ seqlen_q=1,\n ):\n- \"\"\"One decode token per sequence against a paged, block-sparse fp8 KV cache.\n+ \"\"\"``seqlen_q`` decode tokens per sequence (one by default) against a paged,\n+ block-sparse fp8 KV cache.\n \n Mirrors the shapes the SM90 decode schedule is built for: q is bf16, the KV\n cache is fp8 e4m3 with K and V interleaved in one buffer, and q2k_indices are\n@@ -71,7 +73,7 @@ def _decode_inputs(\n \"\"\"\n torch.manual_seed(seed)\n npages = max_k_tiles * batch\n- total_q = batch\n+ total_q = batch * seqlen_q\n base = (\n torch.randn(npages, num_kv_heads, BLK_KV, 2 * HEAD_DIM, device=device) / 4\n ).to(torch.float8_e4m3fn)\n@@ -262,6 +264,70 @@ def test_sparse_decode_paged_matches_reference(num_qo_heads, num_kv_heads):\n torch.testing.assert_close(out.float(), ref, atol=1e-2, rtol=1e-2)\n \n \n+@sm90_only\n+@pytest.mark.parametrize(\n+ \"batch,seqlen_q,num_qo_heads,num_kv_heads,max_k_tiles,route_at_132_sms\",\n+ [\n+ pytest.param(\n+ 67, 1, 64, 4, 16, \"decode_v5:nc16:s2:st2:evict_first:main\", id=\"q1-s2\"\n+ ),\n+ pytest.param(\n+ 42, 2, 64, 4, 65, \"decode_v5:nc16:s1:st2:evict_first:main\", id=\"q2-s1\"\n+ ),\n+ ],\n+)\n+def test_sparse_decode_serves_the_nc16_bands_planned_at_three_stages(\n+ batch, seqlen_q, num_qo_heads, num_kv_heads, max_k_tiles, route_at_132_sms\n+):\n+ \"\"\"#7222: on 132-SM parts the decode cost model picks three ring stages for\n+ these GQA-16 bands (265-330 items at q-len 1 with 11+ pages, 332-396 items\n+ at q-len 2 with 65+ pages; items = batch * seqlen_q * KV heads), and the\n+ export delivered those nc16 coordinates at two stages only, so\n+ ``route_program`` raised ``KeyError`` from ``_decode_template``. The\n+ planner now serves the band with the two-stage ring of the same split\n+ count; this checks that output against the FP32 oracle. On other SM counts\n+ the model picks a delivered route and this is an ordinary reference check.\n+ \"\"\"\n+ from flashinfer.jit.cake_hopper_msa import ROUTES\n+ from flashinfer.msa_ops import cake_hopper_sm90 as ch\n+\n+ total_q = batch * seqlen_q\n+ num_sms = ch._num_sms(0)\n+ plan = ch.plan_sparse_decode(\n+ total_q=total_q,\n+ num_q_heads=num_qo_heads,\n+ num_kv_heads=num_kv_heads,\n+ num_sms=num_sms,\n+ seqlen_q=seqlen_q,\n+ max_pages=max_k_tiles,\n+ )\n+ assert plan.route in ROUTES, plan.route\n+ if num_sms == 132 and route_at_132_sms.replace(\":st2:\", \":st3:\") not in ROUTES:\n+ # the model's three-stage pick is still undelivered: the band runs on the fallback\n+ assert plan.route == route_at_132_sms\n+\n+ q, k, v, idx, page_table, seqused_k = _decode_inputs(\n+ batch=batch,\n+ num_qo_heads=num_qo_heads,\n+ num_kv_heads=num_kv_heads,\n+ max_k_tiles=max_k_tiles,\n+ seqlen_q=seqlen_q,\n+ )\n+ out = msa_sparse_decode_attention(\n+ q,\n+ k,\n+ v,\n+ idx,\n+ page_table=page_table,\n+ seqused_k=seqused_k,\n+ seqlen_q=seqlen_q,\n+ softmax_scale=1.0 / math.sqrt(HEAD_DIM),\n+ )\n+ cu_q = torch.arange(0, total_q + 1, seqlen_q, dtype=torch.int32, device=\"cuda\")\n+ ref = _prefill_reference(q, k, v, idx, cu_q, page_table, seqused_k)\n+ torch.testing.assert_close(out.float(), ref, atol=1e-2, rtol=1e-2)\n+\n+\n @sm90_only\n def test_topk_select_shape_and_dtype():\n \"\"\"top-k select is the only width SM90 supports (16) and must emit int32.\"\"\"\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(msa_ops sm90): make the single-token CuTe prefill compile and run correctly on the cu12 CuTe DSL\nLabels: run-ci, v0.7.3\nFiles changed (2): flashinfer/msa_ops/cute_dsl/sparse_prefill_single_sm90.py, tests/msa_ops/test_msa_sm90.py\n\n## Description (results removed)\n\n## 📌 Description\n\nnvidia-cutlass-dsl ≥ 4.8 ships cu12 and cu13 builds of its compiler and loads the newest one the CUDA driver supports. CUDA 12 installs on a driver older than R580, including the cu129 H100 nightly lane, therefore run the cu12 build. There, the SM90 one-token-per-CTA sparse prefill (`sparse_prefill_single_sm90.py`) has two bugs:\n\n- **Segfault at compile time (f16 PV body).** `cute.compile` crashes inside the DSL when the last block is peeled after the block loop. The last block now runs inside the loop, with its next-block refills predicated off.\n- **Wrong output at GQA 16 (fp8 PV body).** The cu12 build's ptxas feeds the PV gemm a wrong P for query rows 8–15, giving wrong or NaN output. P is now staged in f32 and each fp8 fragment is written whole.\n\n## 🔍 Related Issues\n\n## 🧪 Tests\n[results removed]\n## Reviewer Notes\n\nBoth bugs are in the cu12 toolchain, not the kernel math; these changes work around them.\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Improved sparse attention results for inputs with short block selections and padded entries.\n* **Tests**\n * Added coverage across multiple query sizes and head counts, checking that outputs remain finite and close to the reference.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/msa_ops/cute_dsl/sparse_prefill_single_sm90.py b/flashinfer/msa_ops/cute_dsl/sparse_prefill_single_sm90.py\nindex a6558167c01..36915421401 100644\n--- a/flashinfer/msa_ops/cute_dsl/sparse_prefill_single_sm90.py\n+++ b/flashinfer/msa_ops/cute_dsl/sparse_prefill_single_sm90.py\n@@ -286,16 +286,6 @@ def __call__(self, pq, pkv, pidx, pcu, ppt, ppfx, po, tq, npg, nb, mpg, stream):\n (MMA_M, PG),\n warpgroup.OperandSource.SMEM,\n )\n- qk_mma2 = sm90_utils.make_trivial_tiled_mma(\n- f8,\n- f8,\n- OperandMajorMode.K,\n- OperandMajorMode.K,\n- self.f32,\n- (1, 1, 1),\n- (MMA_M, PG),\n- warpgroup.OperandSource.SMEM,\n- )\n # f32 accumulation: f16 partial sums over up to TOPK * PG keys cost\n # ~6e-4 relative error and have far less headroom.\n pv_mma = sm90_utils.make_trivial_tiled_mma(\n@@ -345,7 +335,6 @@ class SharedStorage:\n \n self.kernel(\n qk_mma,\n- qk_mma2,\n pv_mma,\n tma_atom,\n gKV,\n@@ -370,7 +359,6 @@ class SharedStorage:\n def kernel(\n self,\n qk_mma,\n- qk_mma2,\n pv_mma,\n tma_atom,\n gKV,\n@@ -511,13 +499,16 @@ def kernel(\n )\n a2b = (tidx, warp, srcT, dstT, cv8, cv16)\n \n- # j runs to nblk-2, so block j+1 always exists: no predicate on the refills.\n # K is refilled as soon as the QK GEMM has drained (a full body of lead\n- # time); V right after the second half-conversion has consumed it.\n- for j in cutlass.range(nblk - 1, unroll=1):\n+ # time); V right after the second half-conversion has consumed it. The\n+ # last block runs in the loop with its refills predicated off rather\n+ # than peeled after it: the peeled copy segfaults the cu12 build of the\n+ # CuTe DSL's compiler at opt-level >= 1 (flashinfer-ai/flashinfer#7915).\n+ for j in cutlass.range(nblk, unroll=1):\n self._p1(j, qk_mma, *a1)\n- pgn = cute.arch.make_warp_uniform(meta[TOPK + j + 1])\n- if warp == 0:\n+ more = j + 1 < nblk\n+ pgn = cute.arch.make_warp_uniform(meta[TOPK + cutlass.min(j + 1, nblk - 1)])\n+ if warp == 0 and more:\n with cute.arch.elect_one():\n cute.arch.mbarrier_arrive_and_expect_tx(mbar + 0, KVBYTES)\n cute.copy(\n@@ -527,7 +518,7 @@ def kernel(\n tma_bar_ptr=mbar + 0,\n )\n self._p2(j, *a2t, 1, *a2b)\n- if warp == 0:\n+ if warp == 0 and more:\n with cute.arch.elect_one():\n cute.arch.mbarrier_arrive_and_expect_tx(mbar + 1, KVBYTES)\n cute.copy(\n@@ -536,8 +527,6 @@ def kernel(\n tKVs[(None, 1)],\n tma_bar_ptr=mbar + 1,\n )\n- self._p1(nblk - 1, qk_mma2, *a1)\n- self._p2(nblk - 1, *a2t, 1, *a2b)\n \n # ---- epilogue ----------------------------------------------------\n for i in cutlass.range_constexpr(2):\n@@ -1054,6 +1043,16 @@ def _blk(\n tma_bar_ptr=mbar + 0,\n )\n \n+ # Each band's P is staged in f32 and the fp8 fragments are written once,\n+ # whole, after both bands. Storing a band straight into p_hi / p_lo (four\n+ # bytes per register, two bands interleaved) fed the PV gemm a wrong band-1\n+ # P under the CUDA 12 ptxas of the cu12 CuTe DSL at -O1 and up: band 1\n+ [comment with results removed]\n+ # (flashinfer-ai/flashinfer#7915). The PTX was the same under cu13, whose\n+ # ptxas got it right. fp8 values are exact in f32, so the round trip\n+ # changes no bit.\n+ phf = cute.make_rmem_tensor_like(p_hi, f32)\n+ plf = cute.make_rmem_tensor_like(p_lo, f32)\n # Only warp 0 owns live rows. Both of its row bands go through the softmax\n # so that the GQA-8 band of zero Q rows stores a finite P.\n if warp == 0:\n@@ -1093,8 +1092,10 @@ def _blk(\n l_i[i] = l_i[i] + (ph.to(f32) + pl.to(f32)).reduce(\n cute.ReductionOp.ADD, f32(0.0), 0\n )\n- _p_half(p_hi, i).store(ph)\n- _p_half(p_lo, i).store(pl)\n+ _p_half(phf, i).store(ph.to(f32))\n+ _p_half(plf, i).store(pl.to(f32))\n+ p_hi.store(phf.load().to(f8))\n+ p_lo.store(plf.load().to(f8))\n \n # P.V into the dead S registers, then f32-added to acc_o: see the per-block\n # promotion in sparse_prefill_sm90.\ndiff --git a/tests/msa_ops/test_msa_sm90.py b/tests/msa_ops/test_msa_sm90.py\nindex 745a629f612..af6713d0ee0 100644\n--- a/tests/msa_ops/test_msa_sm90.py\n+++ b/tests/msa_ops/test_msa_sm90.py\n@@ -1369,6 +1369,68 @@ def test_sparse_prefill_fp32_accuracy(\n assert err < 3e-3, f\"rel-L2 {err:.2e} vs fp32 reference\"\n \n \n+@sm90_only\n+@pytest.mark.parametrize(\"hq\", [8, 16])\n+@pytest.mark.parametrize(\"qlen\", [64, 2048]) # f16 PV body, fp8 PV body\n+@pytest.mark.parametrize(\"nvalid\", [1, 5])\n+def test_single_token_prefill_short_block_lists(hq, qlen, nvalid):\n+ \"\"\"The one-token-per-CTA schedule with -1 padded block lists.\n+\n+ Both PV bodies run their last selected block inside the block loop with the\n+ next-block refills predicated off (#7915), so a list of one block runs the\n+ loop once and refills nothing. 4100 pages has no Cake program, so this\n+ reaches the CuTe DSL schedule on either backend.\n+ \"\"\"\n+ torch.manual_seed(hq + qlen + nvalid)\n+ hkv, prefix_pages = 1, 4100\n+ seq = prefix_pages * BLK_KV + qlen\n+ width = -(-seq // BLK_KV)\n+ page_table = torch.randperm(width, device=\"cuda\").to(torch.int32).view(1, width)\n+ kv = (torch.randn(width, hkv, BLK_KV, 2 * HEAD_DIM, device=\"cuda\") * 0.5).to(\n+ torch.float8_e4m3fn\n+ )\n+ k, v = kv[..., :HEAD_DIM], kv[..., HEAD_DIM:]\n+ q = torch.randn(qlen, hq, HEAD_DIM, device=\"cuda\").to(torch.bfloat16)\n+ cu_q = torch.tensor([0, qlen], dtype=torch.int32, device=\"cuda\")\n+ seqused_k = torch.tensor([seq], dtype=torch.int32, device=\"cuda\")\n+ own = torch.arange(seq - qlen, seq, device=\"cuda\") // BLK_KV\n+ # own block + (nvalid - 1) random older ones, ascending, then -1 padding\n+ score = torch.rand(qlen, width, device=\"cuda\")\n+ score[torch.arange(width, device=\"cuda\")[None, :] >= own[:, None]] = -1.0\n+ older = score.topk(nvalid - 1, dim=-1).indices\n+ sel = torch.cat([older, own[:, None]], dim=-1).sort(dim=-1).values\n+ idx = torch.full((qlen, TOPK), -1, dtype=torch.int32, device=\"cuda\")\n+ idx[:, :nvalid] = sel.to(torch.int32)\n+ idx = idx[None].contiguous()\n+\n+ scale = 1.0 / math.sqrt(HEAD_DIM)\n+ out = msa_sparse_attention(\n+ q,\n+ k,\n+ v,\n+ idx,\n+ cu_q,\n+ page_table=page_table,\n+ seqused_k=seqused_k,\n+ causal=True,\n+ softmax_scale=scale,\n+ )\n+ assert torch.isfinite(out.float()).all()\n+ rows = torch.linspace(0, qlen - 1, 32).long().unique().tolist()\n+ ref = _ref_attn_rows(\n+ q,\n+ kv,\n+ idx,\n+ page_table,\n+ seqused_k,\n+ scale,\n+ rows,\n+ lambda r: (0, seq - qlen + r),\n+ )\n+ err = (out[rows].float() - ref).norm() / ref.norm()\n+ assert err < 3e-3, f\"rel-L2 {err:.2e} vs fp32 reference\"\n+\n+\n @sm90_only\n @pytest.mark.parametrize(\n \"fill\", [\"nan\", \"nan_k_only\", \"nan_v_only\", \"garbage\", \"zeros\"]\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(moe): pad_trtllm_moe_weights helper plus valid_* assert messages and the pad-and-declare contract for unaligned MoE shapes\nLabels: run-ci, op: moe, reinforcement learning\nFiles changed (5): flashinfer/fused_moe/__init__.py, flashinfer/fused_moe/core.py, flashinfer/utils.py, tests/moe/test_trtllm_moe_padded_dims.py, tests/moe/test_trtllm_moe_valid_dims.py\n\n## Description (results removed)\n\n## 📌 Description\n\n## 🔍 Related Issues\n\nFixes #3206. Refs #2482.\n\n## 🧪 Tests\n[results removed]\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\nThe assert message says \"pad to a multiple of 128\" for both helpers even though the plain row shuffle only needs 32, because the MoE kernels tile the weight M dimension in 128-row blocks and `valid_*` rounds up to 128 anyway, so 128 is the padding a caller actually needs. In the helper, things worth a second look are the neutral-scale bytes (`127` for 32-element MX blocks, `0x38` for 16-element NVFP4 blocks), the asymmetric FC2-rows-to-128 vs FC1-K-to-`hidden_alignment` contract (the kernel reads each padded dimension only up to `roundUp(valid, 128)`, GEMM1's K still has to be 256-aligned for a config to exist, GEMM2 computes `roundUp(hidden, 128)` columns and finalize crops to the valid width), and whether the padded MxFP8 scale shapes handed to the kernel match what `trtllm_fp8_block_scale_moe` expects. The MxFP8 rows skip intermediate 176 because no 32-element MX scale block exists for it; that shape is covered for NVFP4 only.\n\n## Summary by CodeRabbit\n\n* **New Features**\n * Added utilities for padding quantized TRT-LLM MoE weights and block scales to kernel-compatible dimensions, while preserving the original valid dimensions.\n* **Documentation**\n * Clarified hidden-size and intermediate-size alignment requirements for FP8 and FP4 block-scale operations, including padding guidance.\n* **Bug Fixes**\n * Unaligned row counts now produce clearer errors that identify the required alignment and suggest zero-padding.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/fused_moe/__init__.py b/flashinfer/fused_moe/__init__.py\nindex 7263ad02396..e5527c71fe6 100644\n--- a/flashinfer/fused_moe/__init__.py\n+++ b/flashinfer/fused_moe/__init__.py\n@@ -163,6 +163,7 @@ def __dir__() -> list[str]:\n RoutingInputMode,\n TrtllmMoERoutingMetadata,\n TrtllmMoERoutingMetadataSlot,\n+ TrtllmMoePaddedWeights,\n convert_to_block_layout,\n cutlass_fused_moe,\n cutlass_fused_moe_workspace_size,\n@@ -172,6 +173,7 @@ def __dir__() -> list[str]:\n gen_cutlass_fused_moe_sm100_module,\n gen_cutlass_fused_moe_sm90_module,\n gen_trtllm_gen_fused_moe_sm100_module,\n+ pad_trtllm_moe_weights,\n reorder_rows_for_gated_act_gemm,\n trtllm_fp4_block_scale_moe,\n trtllm_fp4_block_scale_routed_moe,\n@@ -456,6 +458,8 @@ def __getattr__(name: str):\n \"gen_cutlass_fused_moe_sm100_module\",\n \"gen_cutlass_fused_moe_sm90_module\",\n \"gen_trtllm_gen_fused_moe_sm100_module\",\n+ \"pad_trtllm_moe_weights\",\n+ \"TrtllmMoePaddedWeights\",\n \"reorder_rows_for_gated_act_gemm\",\n \"trtllm_bf16_moe\",\n \"prims_ts_bf16_moe\",\ndiff --git a/flashinfer/fused_moe/core.py b/flashinfer/fused_moe/core.py\nindex c7dd5efa7e1..a3f5f94744b 100644\n--- a/flashinfer/fused_moe/core.py\n+++ b/flashinfer/fused_moe/core.py\n@@ -27,6 +27,7 @@\n Dict,\n List,\n Mapping,\n+ NamedTuple,\n Optional,\n Sequence,\n Tuple,\n@@ -481,6 +482,203 @@ def is_trtllm_moe_supported(\n return True\n \n \n+_TRTLLM_MOE_PAD_HIDDEN_ALIGNMENT = 512\n+_TRTLLM_MOE_PAD_INTERMEDIATE_ALIGNMENT = 128\n+\n+\n+class TrtllmMoePaddedWeights(NamedTuple):\n+ \"\"\"Result of :func:`pad_trtllm_moe_weights`.\n+\n+ ``hidden_size`` and ``intermediate_size`` are the padded sizes the tensors\n+ now have (pad the activations to ``hidden_size`` and pass\n+ ``intermediate_size`` to the MoE op); ``valid_hidden_size`` and\n+ ``valid_intermediate_size`` are the original sizes to pass as the op's\n+ ``valid_hidden_size`` / ``valid_intermediate_size``.\n+ \"\"\"\n+\n+ gemm1_weights: torch.Tensor\n+ gemm1_weights_scale: torch.Tensor\n+ gemm2_weights: torch.Tensor\n+ gemm2_weights_scale: torch.Tensor\n+ hidden_size: int\n+ intermediate_size: int\n+ valid_hidden_size: int\n+ valid_intermediate_size: int\n+\n+\n+def _pad_bytes(t: torch.Tensor, dim: int, size: int, fill: int) -> torch.Tensor:\n+ u8 = t.view(torch.uint8)\n+ pad = size - u8.shape[dim]\n+ if pad < 0:\n+ raise ValueError(f\"cannot pad dim {dim} of {tuple(t.shape)} down to {size}\")\n+ if pad == 0:\n+ return t\n+ shape = list(u8.shape)\n+ shape[dim] = pad\n+ tail = torch.full(shape, fill, dtype=torch.uint8, device=t.device)\n+ return torch.cat([u8, tail], dim=dim).view(t.dtype)\n+\n+\n+def pad_trtllm_moe_weights(\n+ gemm1_weights: torch.Tensor,\n+ gemm1_weights_scale: torch.Tensor,\n+ gemm2_weights: torch.Tensor,\n+ gemm2_weights_scale: torch.Tensor,\n+ hidden_size: int,\n+ intermediate_size: int,\n+ *,\n+ is_gated_act: bool = True,\n+ hidden_alignment: int = _TRTLLM_MOE_PAD_HIDDEN_ALIGNMENT,\n+ intermediate_alignment: int = _TRTLLM_MOE_PAD_INTERMEDIATE_ALIGNMENT,\n+) -> TrtllmMoePaddedWeights:\n+ r\"\"\"Zero-pad block-scaled MoE expert weights to the sizes the trtllm-gen kernels accept.\n+\n+ The trtllm-gen fused MoE kernels (:func:`trtllm_fp8_block_scale_moe` with\n+ MxFP8, :func:`trtllm_fp4_block_scale_moe` with NVFP4 or MxFP4) need\n+ ``intermediate_size`` to be a multiple of 128 and ``hidden_size`` to be a\n+ multiple of the GEMM1 K tile. Models whose expert dimensions are not\n+ (Nemotron Nano: hidden 2688, intermediate 1856, or 928 at TP2) pad their\n+ weights and declare the real sizes through ``valid_hidden_size`` and\n+ ``valid_intermediate_size``; GEMM2 then computes ``roundUp(hidden, 128)``\n+ columns and the finalized output is cropped to the valid width. This helper\n+ performs that padding on already quantized weights and their block scales.\n+\n+ Weights are padded with zeros and block scales with the neutral scale of\n+ their format (E8M0 ``127`` = 1.0 for the 32-element MX blocks, E4M3 ``1.0``\n+ for the 16-element NVFP4 blocks), so a padded element dequantizes to zero.\n+ The kernels read each padded dimension only up to ``roundUp(valid, 128)``,\n+ so that stretch of the pad must dequantize to zero and the rest is never read.\n+ For gated activations the gate and up halves of ``gemm1_weights`` are\n+ padded independently, so the padded tensor is still\n+ ``[gate (intermediate_size rows); up (intermediate_size rows)]`` with the\n+ padded ``intermediate_size``. Pass the result through the usual shuffle\n+ helpers (:func:`reorder_rows_for_gated_act_gemm`,\n+ :func:`~flashinfer.shuffle_matrix_a`, :func:`~flashinfer.shuffle_matrix_sf_a`\n+ or the permute-index helpers) exactly as you would unpadded weights.\n+\n+ Parameters\n+ ----------\n+ gemm1_weights : torch.Tensor\n+ FC1 weights ``[num_experts, F * intermediate_size, hidden_size / elems_per_byte]``\n+ in row-major (unshuffled) layout, one byte per element (``float8_e4m3fn``\n+ or ``uint8``); packed FP4 holds two elements per byte. ``F`` is 2 for\n+ gated activations and 1 otherwise.\n+ gemm1_weights_scale : torch.Tensor\n+ FC1 block scales ``[num_experts, F * intermediate_size, hidden_size / sf_vec_size]``\n+ in linear (non-interleaved) layout, one byte per scale.\n+ gemm2_weights : torch.Tensor\n+ FC2 weights ``[num_experts, hidden_size, intermediate_size / elems_per_byte]``.\n+ gemm2_weights_scale : torch.Tensor\n+ FC2 block scales ``[num_experts, hidden_size, intermediate_size / sf_vec_size]``.\n+ hidden_size : int\n+ The model's (unpadded) hidden size. Must be a multiple of ``sf_vec_size``.\n+ intermediate_size : int\n+ The model's (unpadded) per-rank intermediate size. Must be a multiple of\n+ ``sf_vec_size``.\n+ is_gated_act : bool\n+ Whether FC1 holds gate and up projections (``F = 2``). Default ``True``.\n+ hidden_alignment : int\n+ Alignment of the padded hidden size (GEMM1's K). Default ``512``. Must\n+ be a multiple of 256 for MxFP8 and NVFP4 (128 is rejected or gives\n+ wrong results).\n+ intermediate_alignment : int\n+ Alignment of the padded intermediate size. Default ``128``.\n+\n+ Returns\n+ -------\n+ TrtllmMoePaddedWeights\n+ The padded tensors plus the padded and valid sizes. ``gemm2_weights``\n+ and ``gemm2_weights_scale`` have ``roundUp(hidden_size, 128)`` rows, which\n+ is GEMM2's N when ``valid_hidden_size`` is given; ``gemm1_weights`` has\n+ ``roundUp(hidden_size, hidden_alignment)`` columns, which is the width\n+ to zero-pad the activations to.\n+ \"\"\"\n+ if hidden_alignment % 128 or intermediate_alignment % 128:\n+ raise ValueError(\n+ \"hidden_alignment and intermediate_alignment must be multiples of 128\"\n+ )\n+ for name, t in (\n+ (\"gemm1_weights\", gemm1_weights),\n+ (\"gemm1_weights_scale\", gemm1_weights_scale),\n+ (\"gemm2_weights\", gemm2_weights),\n+ (\"gemm2_weights_scale\", gemm2_weights_scale),\n+ ):\n+ if t.dim() != 3 or t.element_size() != 1:\n+ raise ValueError(\n+ f\"{name} must be a 3-D tensor with one byte per element, got {t.shape} {t.dtype}\"\n+ )\n+ factor = 2 if is_gated_act else 1\n+ num_experts, rows1, cols1 = gemm1_weights.shape\n+ if rows1 != factor * intermediate_size:\n+ raise ValueError(\n+ f\"gemm1_weights has {rows1} rows, expected {factor} * {intermediate_size}\"\n+ )\n+ if hidden_size % cols1 or hidden_size // cols1 not in (1, 2):\n+ raise ValueError(\n+ f\"gemm1_weights has {cols1} columns for hidden_size {hidden_size}; expected 1 or 2 elements per byte\"\n+ )\n+ elems_per_byte = hidden_size // cols1\n+ sf_cols1 = gemm1_weights_scale.shape[2]\n+ if hidden_size % sf_cols1 or hidden_size // sf_cols1 not in (16, 32):\n+ raise ValueError(\n+ f\"gemm1_weights_scale has {sf_cols1} columns for hidden_size {hidden_size}; expected 16 or 32 elements per scale\"\n+ )\n+ sf_vec_size = hidden_size // sf_cols1\n+ if intermediate_size % sf_vec_size or intermediate_size % elems_per_byte:\n+ raise ValueError(\n+ f\"intermediate_size {intermediate_size} must be a multiple of the scale block {sf_vec_size}\"\n+ )\n+ if tuple(gemm1_weights_scale.shape[:2]) != (num_experts, rows1):\n+ raise ValueError(\n+ f\"gemm1_weights_scale {tuple(gemm1_weights_scale.shape)} does not match gemm1_weights {tuple(gemm1_weights.shape)}\"\n+ )\n+ if tuple(gemm2_weights.shape) != (\n+ num_experts,\n+ hidden_size,\n+ intermediate_size // elems_per_byte,\n+ ):\n+ raise ValueError(\n+ f\"gemm2_weights must be [{num_experts}, {hidden_size}, {intermediate_size // elems_per_byte}], got {tuple(gemm2_weights.shape)}\"\n+ )\n+ if tuple(gemm2_weights_scale.shape) != (\n+ num_experts,\n+ hidden_size,\n+ intermediate_size // sf_vec_size,\n+ ):\n+ raise ValueError(\n+ f\"gemm2_weights_scale must be [{num_experts}, {hidden_size}, {intermediate_size // sf_vec_size}], got {tuple(gemm2_weights_scale.shape)}\"\n+ )\n+\n+ # E8M0 127 and E4M3 0x38 both encode 1.0.\n+ neutral_scale = 127 if sf_vec_size == 32 else 0x38\n+ padded_hidden = _round_up(hidden_size, hidden_alignment)\n+ gemm2_rows = _round_up(hidden_size, _TRTLLM_MOE_OUTPUT_HIDDEN_ALIGNMENT)\n+ padded_intermediate = _round_up(intermediate_size, intermediate_alignment)\n+\n+ def pad_fc1(t: torch.Tensor, cols: int, fill: int) -> torch.Tensor:\n+ halves = torch.chunk(t, factor, dim=1)\n+ halves = [_pad_bytes(h, 1, padded_intermediate, fill) for h in halves]\n+ return _pad_bytes(torch.cat(halves, dim=1), 2, cols, fill)\n+\n+ def pad_fc2(t: torch.Tensor, cols: int, fill: int) -> torch.Tensor:\n+ return _pad_bytes(_pad_bytes(t, 1, gemm2_rows, fill), 2, cols, fill)\n+\n+ return TrtllmMoePaddedWeights(\n+ gemm1_weights=pad_fc1(gemm1_weights, padded_hidden // elems_per_byte, 0),\n+ gemm1_weights_scale=pad_fc1(\n+ gemm1_weights_scale, padded_hidden // sf_vec_size, neutral_scale\n+ ),\n+ gemm2_weights=pad_fc2(gemm2_weights, padded_intermediate // elems_per_byte, 0),\n+ gemm2_weights_scale=pad_fc2(\n+ gemm2_weights_scale, padded_intermediate // sf_vec_size, neutral_scale\n+ ),\n+ hidden_size=padded_hidden,\n+ intermediate_size=padded_intermediate,\n+ valid_hidden_size=hidden_size,\n+ valid_intermediate_size=intermediate_size,\n+ )\n+\n+\n def _maybe_get_cached_w3_w1_permute_indices(\n _cache_permute_indices,\n dst_w3_w1_weight: torch.Tensor,\n@@ -6206,12 +6404,27 @@ def trtllm_fp8_block_scale_moe(\n ``roundUp(valid_hidden_size, 128)`` columns (that is what the FC2\n weights, weight scales and bias are sized for) and finalize writes only\n the leading ``valid_hidden_size`` of them. A caller-supplied ``output``\n- must therefore have ``valid_hidden_size`` columns. Default ``None``\n- (use the full ``hidden_size``).\n+ must therefore have ``valid_hidden_size`` columns. For MxFP8 the padded\n+ ``hidden_size`` must be a multiple of 256 (128 is rejected). Default\n+ ``None`` (use the full ``hidden_size``).\n valid_intermediate_size : Optional[int]\n Valid (unpadded) intermediate dimension. When provided,\n ``intermediate_size`` is treated as padded and only the valid region is\n computed. Default ``None`` (use the full ``intermediate_size``).\n+\n+ The kernels tile expert weights in 128-row blocks, so\n+ ``intermediate_size`` (and with it the FC1 row count ``M``) must be a\n+ multiple of ``128``; a model dimension that is not (``1856``, ``928``)\n+ is supported by padding and declaring, not by passing it directly.\n+ Zero-pad the weights to a multiple of ``128`` (the gate and up halves\n+ of FC1 separately, so the rows stay ``[gate; up]`` at the padded\n+ size), fill the padded block scales with a neutral finite value\n+ (E8M0 ``127``, i.e. ``2**0``, for MXFP8; ``1.0`` for the ``float32``\n+ DeepSeek scales), pass the padded size as ``intermediate_size`` and\n+ the real one here. The kernel reads the ``[valid, roundUp(valid, 128))``\n+ stretch of the padding and never reads the rest, so it must hold zeros and\n+ finite scales. ``hidden_size`` follows the same rule through\n+ ``valid_hidden_size``.\n gemm1_bias : Optional[torch.Tensor]\n Optional FC1 bias, float32 (keyword-only). Shape is\n ``[local_num_experts, 2 * intermediate_size]`` for gated activations\n@@ -6486,8 +6699,9 @@ def trtllm_fp8_block_scale_routed_moe(\n ``roundUp(valid_hidden_size, 128)`` columns (that is what the FC2\n weights, weight scales and bias are sized for) and finalize writes only\n the leading ``valid_hidden_size`` of them. A caller-supplied ``output``\n- must therefore have ``valid_hidden_size`` columns. Default ``None``\n- (use the full ``hidden_size``).\n+ must therefore have ``valid_hidden_size`` columns. For MxFP8 the padded\n+ ``hidden_size`` must be a multiple of 256 (128 is rejected). Default\n+ ``None`` (use the full ``hidden_size``).\n valid_intermediate_size : Optional[int]\n Valid (unpadded) intermediate dimension. When provided,\n ``intermediate_size`` is treated as padded and only the valid region is\n@@ -6800,12 +7014,27 @@ def trtllm_fp4_block_scale_moe(\n ``roundUp(valid_hidden_size, 128)`` columns (that is what the FC2\n weights, weight scales and bias are sized for) and finalize writes only\n the leading ``valid_hidden_size`` of them. A caller-supplied ``output``\n- must therefore have ``valid_hidden_size`` columns. Default ``None``\n- (use the full ``hidden_size``).\n+ must therefore have ``valid_hidden_size`` columns. For NVFP4 the padded\n+ ``hidden_size`` must be a multiple of 256 (128 gives wrong results).\n+ Default ``None`` (use the full ``hidden_size``).\n valid_intermediate_size : Optional[int]\n Valid (unpadded) intermediate dimension. When provided,\n ``intermediate_size`` is treated as padded and only the valid region is\n computed. Default ``None`` (use the full ``intermediate_size``).\n+\n+ The kernels tile expert weights in 128-row blocks, so\n+ ``intermediate_size`` (and with it the FC1 row count ``M``) must be a\n+ multiple of ``128``; a model dimension that is not (``1856``, ``928``)\n+ is supported by padding and declaring, not by passing it directly.\n+ Zero-pad the weights to a multiple of ``128`` (the gate and up halves\n+ of FC1 separately, so the rows stay ``[gate; up]`` at the padded\n+ size), fill the padded block scales with a neutral finite value\n+ (E8M0 ``127``, i.e. ``2**0``, for MXFP4; E4M3 ``1.0`` for NVFP4),\n+ pass the padded size as ``intermediate_size`` and the real one here.\n+ The kernel reads the ``[valid, roundUp(valid, 128))``\n+ stretch of the padding and never reads the rest, so it must hold zeros and\n+ finite scales. ``hidden_size`` follows the same rule through\n+ ``valid_hidden_size``.\n workspace_buffer : Optional[torch.Tensor]\n Caller-owned 1-D ``uint8`` CUDA buffer of at least\n :func:`trtllm_fused_moe_workspace_size` bytes. When given, the launch\n@@ -7090,8 +7319,9 @@ def trtllm_fp4_block_scale_routed_moe(\n ``roundUp(valid_hidden_size, 128)`` columns (that is what the FC2\n weights, weight scales and bias are sized for) and finalize writes only\n the leading ``valid_hidden_size`` of them. A caller-supplied ``output``\n- must therefore have ``valid_hidden_size`` columns. Default ``None``\n- (use the full ``hidden_size``).\n+ must therefore have ``valid_hidden_size`` columns. For NVFP4 the padded\n+ ``hidden_size`` must be a multiple of 256 (128 gives wrong results).\n+ Default ``None`` (use the full ``hidden_size``).\n valid_intermediate_size : Optional[int]\n Valid (unpadded) intermediate dimension. When provided,\n ``intermediate_size`` is treated as padded and only the valid region is\ndiff --git a/flashinfer/utils.py b/flashinfer/utils.py\nindex 52f666cd19f..8875b20673e 100644\n--- a/flashinfer/utils.py\n+++ b/flashinfer/utils.py\n@@ -1113,6 +1113,15 @@ def get_shuffle_block_size(epilogue_tile_m: int) -> int:\n return shuffle_block_size\n \n \n+def _unaligned_rows_message(M: int, alignment: int) -> str:\n+ return (\n+ f\"input_tensor.shape[0]={M} must be a multiple of {alignment}. For the trtllm \"\n+ \"block-scale MoE ops (FP8, FP4, MXINT4), zero-pad the unaligned dimension \"\n+ \"(intermediate_size for FC1, hidden_size for FC2) to a multiple of 128 and \"\n+ \"pass valid_intermediate_size / valid_hidden_size.\"\n+ )\n+\n+\n def get_shuffle_matrix_a_row_indices(\n input_tensor: torch.Tensor, epilogue_tile_m: int\n ) -> torch.Tensor:\n@@ -1132,9 +1141,7 @@ def get_shuffle_matrix_a_row_indices(\n shuffle_block_size = get_shuffle_block_size(epilogue_tile_m)\n row_map = srcToDstBlk16RowMap if shuffle_block_size == 16 else srcToDstBlk32RowMap\n \n- assert M % shuffle_block_size == 0, (\n- f\"input_tensor.shape[0] must be multiples of {shuffle_block_size}\"\n- )\n+ assert M % shuffle_block_size == 0, _unaligned_rows_message(M, shuffle_block_size)\n \n # row_indices[new_row] = old_row\n # so row_indices is an array of size M telling us from which old_row\n@@ -1163,7 +1170,7 @@ def get_shuffle_matrix_sf_a_row_indices(\n \n # M, K from the input\n M, K = input_tensor.shape\n- assert M % 128 == 0\n+ assert M % 128 == 0, _unaligned_rows_message(M, 128)\n # K % 4 alignment is not required here, downstream block_scale_interleave kernel pads K to a multiple of 4 internally\n row_indices = get_shuffle_matrix_a_row_indices(input_tensor, epilogue_tile_m)\n \ndiff --git a/tests/moe/test_trtllm_moe_padded_dims.py b/tests/moe/test_trtllm_moe_padded_dims.py\nnew file mode 100644\nindex 00000000000..3ba0eaeac8a\n--- /dev/null\n+++ b/tests/moe/test_trtllm_moe_padded_dims.py\n@@ -0,0 +1,420 @@\n+\"\"\"\n+Copyright (c) 2026 by FlashInfer team.\n+\n+Licensed under the Apache License, Version 2.0 (the \"License\");\n+you may not use this file except in compliance with the License.\n+You may obtain a copy of the License at\n+\n+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+\"\"\"\n+\n+import math\n+\n+import pytest\n+import torch\n+\n+from flashinfer import (\n+ ActivationType,\n+ RoutingMethodType,\n+ reorder_rows_for_gated_act_gemm,\n+ shuffle_matrix_a,\n+ shuffle_matrix_sf_a,\n+)\n+from flashinfer.fp4_quantization import block_scale_interleave\n+from flashinfer.fused_moe import (\n+ pad_trtllm_moe_weights,\n+ trtllm_fp4_block_scale_moe,\n+ trtllm_fp8_block_scale_moe,\n+)\n+from flashinfer.fused_moe.core import (\n+ Fp8QuantizationType,\n+ _maybe_get_cached_w3_w1_permute_indices,\n+ _round_up,\n+ get_w2_permute_indices_with_cache,\n+)\n+from flashinfer.utils import device_support_pdl, get_compute_capability\n+\n+from .trtllm_gen_fused_moe_utils import (\n+ FP4Moe,\n+ FP8BlockScaleMoe,\n+ check_accuracy,\n+ moe_args,\n+ quant_fp4_batches,\n+ routing_reference_renormalize,\n+)\n+from .utils import QuantMode, is_gated_activation\n+\n+# Nemotron Nano expert geometry (TP1 and TP2) and the #3206 TP4 shard.\n+_SHAPES = [(2688, 1856), (2688, 928), (1024, 176)]\n+_CONTAM = 42.0\n+\n+\n+def _skip_unless_sm100():\n+ if not torch.cuda.is_available():\n+ pytest.skip(\"CUDA is required for TRT-LLM MoE kernels.\")\n+ if get_compute_capability(torch.device(\"cuda\"))[0] not in [10]:\n+ pytest.skip(\"TRT-LLM MoE tests are only guaranteed on SM100/SM103 GPUs.\")\n+\n+\n+@pytest.mark.parametrize(\"hidden_size,intermediate_size\", _SHAPES)\n+@pytest.mark.parametrize(\"elems_per_byte,sf_vec_size\", [(1, 32), (2, 16)])\n+@pytest.mark.parametrize(\"is_gated_act\", [True, False])\n+def test_pad_trtllm_moe_weights_round_trip(\n+ hidden_size, intermediate_size, elems_per_byte, sf_vec_size, is_gated_act\n+):\n+ if intermediate_size % sf_vec_size:\n+ pytest.skip(\"intermediate_size must be a multiple of the scale block\")\n+ torch.manual_seed(0)\n+ num_experts = 2\n+ factor = 2 if is_gated_act else 1\n+ rows1 = factor * intermediate_size\n+\n+ def rand_bytes(*shape):\n+ return torch.randint(1, 255, shape, dtype=torch.uint8)\n+\n+ w1 = rand_bytes(num_experts, rows1, hidden_size // elems_per_byte)\n+ s1 = rand_bytes(num_experts, rows1, hidden_size // sf_vec_size)\n+ w2 = rand_bytes(num_experts, hidden_size, intermediate_size // elems_per_byte)\n+ s2 = rand_bytes(num_experts, hidden_size, intermediate_size // sf_vec_size)\n+\n+ padded = pad_trtllm_moe_weights(\n+ w1.view(torch.float8_e4m3fn),\n+ s1,\n+ w2.view(torch.float8_e4m3fn),\n+ s2,\n+ hidden_size,\n+ intermediate_size,\n+ is_gated_act=is_gated_act,\n+ )\n+ pi, ph = padded.intermediate_size, padded.hidden_size\n+ gemm2_rows = _round_up(hidden_size, 128)\n+ assert pi % 128 == 0 and pi >= intermediate_size\n+ assert ph % 512 == 0 and ph >= hidden_size\n+ assert padded.valid_hidden_size == hidden_size\n+ assert padded.valid_intermediate_size == intermediate_size\n+ assert padded.gemm1_weights.dtype == torch.float8_e4m3fn\n+ assert padded.gemm1_weights.shape == (\n+ num_experts,\n+ factor * pi,\n+ ph // elems_per_byte,\n+ )\n+ assert padded.gemm1_weights_scale.shape == (\n+ num_experts,\n+ factor * pi,\n+ ph // sf_vec_size,\n+ )\n+ assert padded.gemm2_weights.shape == (num_experts, gemm2_rows, pi // elems_per_byte)\n+ assert padded.gemm2_weights_scale.shape == (\n+ num_experts,\n+ gemm2_rows,\n+ pi // sf_vec_size,\n+ )\n+\n+ neutral = 127 if sf_vec_size == 32 else 0x38\n+ for src, dst, fill, cols in (\n+ (w1, padded.gemm1_weights.view(torch.uint8), 0, hidden_size // elems_per_byte),\n+ (s1, padded.gemm1_weights_scale, neutral, hidden_size // sf_vec_size),\n+ ):\n+ mask = torch.zeros_like(dst, dtype=torch.bool)\n+ for h in range(factor):\n+ dst_half = dst[:, h * pi : (h + 1) * pi]\n+ src_half = src[:, h * intermediate_size : (h + 1) * intermediate_size]\n+ torch.testing.assert_close(dst_half[:, :intermediate_size, :cols], src_half)\n+ mask[:, h * pi : h * pi + intermediate_size, :cols] = True\n+ assert (dst[~mask] == fill).all()\n+ for src, dst, fill, cols in (\n+ (\n+ w2,\n+ padded.gemm2_weights.view(torch.uint8),\n+ 0,\n+ intermediate_size // elems_per_byte,\n+ ),\n+ (s2, padded.gemm2_weights_scale, neutral, intermediate_size // sf_vec_size),\n+ ):\n+ torch.testing.assert_close(dst[:, :hidden_size, :cols], src)\n+ mask = torch.zeros_like(dst, dtype=torch.bool)\n+ mask[:, :hidden_size, :cols] = True\n+ assert (dst[~mask] == fill).all()\n+\n+\n+def test_pad_trtllm_moe_weights_rejects_mismatched_shapes():\n+ w1 = torch.zeros(2, 2 * 64, 128, dtype=torch.float8_e4m3fn)\n+ s1 = torch.zeros(2, 2 * 64, 128 // 32, dtype=torch.uint8)\n+ w2 = torch.zeros(2, 128, 64, dtype=torch.float8_e4m3fn)\n+ s2 = torch.zeros(2, 128, 64 // 32, dtype=torch.uint8)\n+ pad_trtllm_moe_weights(w1, s1, w2, s2, 128, 64)\n+ with pytest.raises(ValueError):\n+ pad_trtllm_moe_weights(w1, s1, w2, s2, 128, 64, is_gated_act=False)\n+ with pytest.raises(ValueError):\n+ pad_trtllm_moe_weights(w1, s1, w2[:, :64], s2, 128, 64)\n+ with pytest.raises(ValueError):\n+ pad_trtllm_moe_weights(w1, s1, w2, s2, 128, 64, hidden_alignment=256 + 64)\n+\n+\n+def _run_padded_moe(\n+ quant_mode,\n+ activation_type,\n+ valid_hidden_size,\n+ valid_intermediate_size,\n+ hidden_alignment=512,\n+ num_tokens=64,\n+ num_experts=8,\n+ top_k=2,\n+):\n+ \"\"\"Run the padded kernel at ``(valid_hidden_size, valid_intermediate_size)``.\n+\n+ Returns ``(kernel_output, reference_output, tolerances)``; the reference is the\n+ dequant MoE over the unpadded problem.\n+ \"\"\"\n+ torch.manual_seed(0)\n+ device = torch.device(\"cuda:0\")\n+ padding = 8\n+ vh, vi = valid_hidden_size, valid_intermediate_size\n+ gated = is_gated_activation(activation_type)\n+ factor = 2 if gated else 1\n+ activation = activation_type.value\n+\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ moe = FP8BlockScaleMoe(fp8_quantization_type=quant_mode)\n+ else:\n+ moe = FP4Moe(quant_mode=quant_mode)\n+ moe._cache_permute_indices = {}\n+\n+ expert_logits = torch.randn(num_tokens, num_experts, device=device).to(\n+ torch.bfloat16\n+ )\n+ hidden_states = 2 * torch.randn(num_tokens, vh, device=device, dtype=torch.bfloat16)\n+ gemm1_weights = torch.randn(\n+ num_experts, factor * vi, vh, device=device, dtype=torch.bfloat16\n+ ) / math.sqrt(vh)\n+ gemm2_weights = torch.randn(\n+ num_experts, vh, vi, device=device, dtype=torch.bfloat16\n+ ) / math.sqrt(vi)\n+ permute_info, _ = routing_reference_renormalize(\n+ expert_logits, top_k, num_experts, padding\n+ )\n+\n+ # Reference: the unpadded problem through the dequant MoE.\n+ weights_data = moe.quantize_weights(gemm1_weights, gemm2_weights, hidden_states)\n+ inputs_data = moe.quantize_inputs(\n+ hidden_states, weights_data[\"hidden_states_scale_global\"]\n+ )\n+ args_valid = moe_args(\n+ num_tokens,\n+ num_experts,\n+ vh,\n+ vi,\n+ top_k,\n+ padding,\n+ inputs_data[\"hidden_states\"],\n+ inputs_data[\"hidden_states_scale\"],\n+ weights_data[\"hidden_states_scale_global\"],\n+ expert_logits,\n+ weights_data[\"gemm1_weights\"],\n+ weights_data[\"gemm1_scales\"],\n+ weights_data[\"gemm1_scales_global\"],\n+ weights_data[\"gemm2_weights\"],\n+ weights_data[\"gemm2_scales\"],\n+ weights_data[\"gemm2_scales_global\"],\n+ permute_info,\n+ False,\n+ activation,\n+ )\n+ reference_output, args_dequant = moe.compute_reference(args_valid)\n+ reference_output = reference_output.to(torch.float)\n+\n+ # Kernel: pad the linear-layout quantized weights, then shuffle as usual.\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ sf_vec_size = 32\n+ w1_lin = weights_data[\"gemm1_weights\"]\n+ s1_lin = weights_data[\"gemm1_scales\"].reshape(\n+ num_experts, factor * vi, vh // sf_vec_size\n+ )\n+ w2_lin = weights_data[\"gemm2_weights\"]\n+ s2_lin = weights_data[\"gemm2_scales\"].reshape(\n+ num_experts, vh, vi // sf_vec_size\n+ )\n+ else:\n+ sf_vec_size = moe.sf_vec_size\n+ _, s1_lin, _ = quant_fp4_batches(\n+ gemm1_weights, num_experts, moe.is_mxfp4, False\n+ )\n+ _, s2_lin, _ = quant_fp4_batches(\n+ gemm2_weights, num_experts, moe.is_mxfp4, False\n+ )\n+ w1_lin = (\n+ weights_data[\"gemm1_weights\"]\n+ .view(torch.uint8)\n+ .reshape(num_experts, factor * vi, vh // 2)\n+ )\n+ s1_lin = s1_lin.view(torch.uint8).reshape(\n+ num_experts, factor * vi, vh // sf_vec_size\n+ )\n+ w2_lin = (\n+ weights_data[\"gemm2_weights\"]\n+ .view(torch.uint8)\n+ .reshape(num_experts, vh, vi // 2)\n+ )\n+ s2_lin = s2_lin.view(torch.uint8).reshape(num_experts, vh, vi // sf_vec_size)\n+\n+ padded = pad_trtllm_moe_weights(\n+ w1_lin,\n+ s1_lin,\n+ w2_lin,\n+ s2_lin,\n+ vh,\n+ vi,\n+ is_gated_act=gated,\n+ hidden_alignment=hidden_alignment,\n+ )\n+ ph, pi = padded.hidden_size, padded.intermediate_size\n+ gemm2_rows = padded.gemm2_weights.shape[1]\n+ epilogue_tile_m = 128\n+\n+ g1_w, g1_s, g2_w, g2_s = [], [], [], []\n+ for e in range(num_experts):\n+ w1 = padded.gemm1_weights[e].view(torch.uint8)\n+ s1 = padded.gemm1_weights_scale[e].view(torch.uint8)\n+ w2 = padded.gemm2_weights[e].view(torch.uint8)\n+ s2 = padded.gemm2_weights_scale[e].view(torch.uint8)\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ if gated:\n+ w1 = reorder_rows_for_gated_act_gemm(w1)\n+ s1 = reorder_rows_for_gated_act_gemm(s1)\n+ g1_w.append(shuffle_matrix_a(w1, epilogue_tile_m))\n+ g1_s.append(shuffle_matrix_sf_a(s1, epilogue_tile_m))\n+ g2_w.append(shuffle_matrix_a(w2, epilogue_tile_m))\n+ g2_s.append(shuffle_matrix_sf_a(s2, epilogue_tile_m))\n+ else:\n+ p = _maybe_get_cached_w3_w1_permute_indices(\n+ moe._cache_permute_indices, w1, epilogue_tile_m, is_gated_act_gemm=gated\n+ )\n+ g1_w.append(w1[p.to(device)].contiguous())\n+ p = _maybe_get_cached_w3_w1_permute_indices(\n+ moe._cache_permute_indices,\n+ s1,\n+ epilogue_tile_m,\n+ num_elts_per_sf=sf_vec_size,\n+ is_gated_act_gemm=gated,\n+ )\n+ g1_s.append(block_scale_interleave(s1[p.to(device)].contiguous()))\n+ p = get_w2_permute_indices_with_cache(\n+ moe._cache_permute_indices, w2, epilogue_tile_m\n+ )\n+ g2_w.append(w2[p.to(device)].contiguous())\n+ p = get_w2_permute_indices_with_cache(\n+ moe._cache_permute_indices,\n+ s2,\n+ epilogue_tile_m,\n+ num_elts_per_sf=sf_vec_size,\n+ )\n+ g2_s.append(block_scale_interleave(s2[p.to(device)].contiguous()))\n+ gemm1_weights_k = torch.stack(g1_w)\n+ gemm2_weights_k = torch.stack(g2_w)\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ gemm1_weights_k = gemm1_weights_k.view(torch.float8_e4m3fn)\n+ gemm2_weights_k = gemm2_weights_k.view(torch.float8_e4m3fn)\n+ gemm1_scales_k = torch.stack(g1_s).reshape(\n+ num_experts, factor * pi, ph // sf_vec_size\n+ )\n+ gemm2_scales_k = torch.stack(g2_s).reshape(\n+ num_experts, gemm2_rows, pi // sf_vec_size\n+ )\n+\n+ # Poison the activation pad: the kernel must not read past roundUp(valid_hidden_size, 128).\n+ hidden_padded = torch.full(\n+ (num_tokens, ph), _CONTAM, device=device, dtype=torch.bfloat16\n+ )\n+ hidden_padded[:, :vh] = hidden_states\n+ kernel_inputs = moe.quantize_inputs(\n+ hidden_padded, weights_data[\"hidden_states_scale_global\"], is_swizzling=False\n+ )\n+ common = dict(\n+ routing_bias=None,\n+ num_experts=num_experts,\n+ top_k=top_k,\n+ n_group=None,\n+ topk_group=None,\n+ intermediate_size=pi,\n+ local_expert_offset=0,\n+ local_num_experts=num_experts,\n+ routed_scaling_factor=None,\n+ routing_method_type=RoutingMethodType.Renormalize.value,\n+ activation_type=activation,\n+ do_finalize=True,\n+ enable_pdl=device_support_pdl(device),\n+ valid_hidden_size=vh,\n+ valid_intermediate_size=vi,\n+ )\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ out = trtllm_fp8_block_scale_moe(\n+ routing_logits=expert_logits,\n+ hidden_states=kernel_inputs[\"hidden_states\"],\n+ hidden_states_scale=kernel_inputs[\"hidden_states_scale\"],\n+ gemm1_weights=gemm1_weights_k,\n+ gemm1_weights_scale=gemm1_scales_k,\n+ gemm2_weights=gemm2_weights_k,\n+ gemm2_weights_scale=gemm2_scales_k,\n+ use_shuffled_weight=True,\n+ fp8_quantization_type=Fp8QuantizationType.MxFp8,\n+ **common,\n+ )\n+ else:\n+ g1_global = weights_data[\"gemm1_scales_global\"]\n+ g2_global = weights_data[\"gemm2_scales_global\"]\n+ hs_global = weights_data[\"hidden_states_scale_global\"]\n+ c_global_sf = args_dequant.c_global_sf\n+ scale_gate_fc1 = (1.0 / g1_global) * (1.0 / hs_global)\n+ if gated:\n+ scale_c_fc1 = c_global_sf * scale_gate_fc1\n+ else:\n+ scale_c_fc1 = torch.full_like(g1_global, c_global_sf)\n+ scale_c_fc2 = (1.0 / c_global_sf) * (1.0 / g2_global)\n+ out = trtllm_fp4_block_scale_moe(\n+ routing_logits=expert_logits,\n+ hidden_states=kernel_inputs[\"hidden_states\"],\n+ hidden_states_scale=kernel_inputs[\"hidden_states_scale\"],\n+ gemm1_weights=gemm1_weights_k,\n+ gemm1_weights_scale=gemm1_scales_k.view(torch.float8_e4m3fn),\n+ gemm1_bias=None,\n+ gemm1_alpha=None,\n+ gemm1_beta=None,\n+ gemm1_clamp_limit=None,\n+ gemm2_weights=gemm2_weights_k,\n+ gemm2_weights_scale=gemm2_scales_k.view(torch.float8_e4m3fn),\n+ gemm2_bias=None,\n+ output1_scale_scalar=scale_c_fc1,\n+ output1_scale_gate_scalar=scale_gate_fc1,\n+ output2_scale_scalar=scale_c_fc2,\n+ **common,\n+ )\n+ kernel_output = (out[0] if isinstance(out, list) else out).to(torch.float)\n+ return kernel_output, reference_output, moe.get_tolerances()\n+\n+\n+@pytest.mark.parametrize(\n+ \"quant_mode\", [QuantMode.FP8_BLOCK_SCALE_MXFP8, QuantMode.FP4_NVFP4_NVFP4]\n+)\n+@pytest.mark.parametrize(\n+ \"activation_type\", [ActivationType.Swiglu, ActivationType.Relu2]\n+)\n+@pytest.mark.parametrize(\"valid_hidden_size,valid_intermediate_size\", _SHAPES)\n+def test_padded_moe_matches_unpadded_reference(\n+ quant_mode, activation_type, valid_hidden_size, valid_intermediate_size\n+):\n+ _skip_unless_sm100()\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8 and valid_intermediate_size % 32:\n+ pytest.skip(\"MxFP8 needs a 32-aligned intermediate_size\")\n+ kernel_output, reference_output, tol = _run_padded_moe(\n+ quant_mode, activation_type, valid_hidden_size, valid_intermediate_size\n+ )\n+ assert kernel_output.shape == reference_output.shape == (64, valid_hidden_size)\n+ check_accuracy(\n+ reference_output, kernel_output, tol[\"atol\"], tol[\"rtol\"], tol[\"percent\"]\n+ )\ndiff --git a/tests/moe/test_trtllm_moe_valid_dims.py b/tests/moe/test_trtllm_moe_valid_dims.py\nindex ea1bc97ec98..c847ebe3193 100644\n--- a/tests/moe/test_trtllm_moe_valid_dims.py\n+++ b/tests/moe/test_trtllm_moe_valid_dims.py\n@@ -25,7 +25,12 @@\n _round_up,\n _trtllm_moe_output_width,\n )\n-from flashinfer.utils import device_support_pdl, get_compute_capability\n+from flashinfer.utils import (\n+ device_support_pdl,\n+ get_compute_capability,\n+ get_shuffle_matrix_a_row_indices,\n+ get_shuffle_matrix_sf_a_row_indices,\n+)\n \n # The contract mirrored by this file (identical to TensorRT-LLM's\n # mxFp4BlockScaleMoe.cpp / fp4BlockScaleMoe.cpp), for a declared valid_hidden_size:\n@@ -151,6 +156,37 @@ def test_check_valid_hidden_size_supports_finalize_rejects(\n )\n \n \n+_SHUFFLE_ROW_INDEX_HELPERS = [\n+ pytest.param(get_shuffle_matrix_a_row_indices, 32, id=\"a\"),\n+ pytest.param(get_shuffle_matrix_sf_a_row_indices, 128, id=\"sf_a\"),\n+]\n+\n+\n+@pytest.mark.parametrize(\n+ (\"helper\", \"num_rows\"),\n+ [\n+ # Nemotron Nano intermediate sizes (TP1 / TP2) and the #3206 TP4 shard.\n+ pytest.param(get_shuffle_matrix_sf_a_row_indices, 1856, id=\"sf_a-1856\"),\n+ pytest.param(get_shuffle_matrix_sf_a_row_indices, 928, id=\"sf_a-928\"),\n+ pytest.param(get_shuffle_matrix_sf_a_row_indices, 176, id=\"sf_a-176\"),\n+ pytest.param(get_shuffle_matrix_a_row_indices, 176, id=\"a-176\"),\n+ ],\n+)\n+def test_shuffle_row_indices_unaligned_rows_name_valid_dims(helper, num_rows):\n+ weight = torch.empty(num_rows, 64, dtype=torch.uint8)\n+ with pytest.raises(AssertionError, match=\"valid_intermediate_size\"):\n+ helper(weight, epilogue_tile_m=128)\n+\n+\n+@pytest.mark.parametrize((\"helper\", \"alignment\"), _SHUFFLE_ROW_INDEX_HELPERS)\n+@pytest.mark.parametrize(\"num_rows\", [1920, 3712])\n+def test_shuffle_row_indices_aligned_rows_is_permutation(helper, alignment, num_rows):\n+ assert num_rows % alignment == 0\n+ weight = torch.empty(num_rows, 64, dtype=torch.uint8)\n+ row_indices = helper(weight, epilogue_tile_m=128)\n+ assert torch.equal(row_indices.sort().values, torch.arange(num_rows))\n+\n+\n # Numerical test for valid_hidden_size.\n #\n # IMPORTANT: trtllm_mxint4_block_scale_moe consumes mxint4-quantized AND\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(moe): pad_trtllm_moe_weights helper plus valid_* assert messages and the pad-and-declare contract for unaligned MoE shapes\nLabels: run-ci, op: moe, reinforcement learning\nFiles changed (5): flashinfer/fused_moe/__init__.py, flashinfer/fused_moe/core.py, flashinfer/utils.py, tests/moe/test_trtllm_moe_padded_dims.py, tests/moe/test_trtllm_moe_valid_dims.py\n\n## Description (results removed)\n\n## 📌 Description\n\n## 🔍 Related Issues\n\nFixes #3206. Refs #2482.\n\n## 🧪 Tests\n[results removed]\n## 🔬 Experimental Track\n\n```experimental-tests\n#\n#\n```\n\n## Reviewer Notes\n\nThe assert message says \"pad to a multiple of 128\" for both helpers even though the plain row shuffle only needs 32, because the MoE kernels tile the weight M dimension in 128-row blocks and `valid_*` rounds up to 128 anyway, so 128 is the padding a caller actually needs. In the helper, things worth a second look are the neutral-scale bytes (`127` for 32-element MX blocks, `0x38` for 16-element NVFP4 blocks), the asymmetric FC2-rows-to-128 vs FC1-K-to-`hidden_alignment` contract (the kernel reads each padded dimension only up to `roundUp(valid, 128)`, GEMM1's K still has to be 256-aligned for a config to exist, GEMM2 computes `roundUp(hidden, 128)` columns and finalize crops to the valid width), and whether the padded MxFP8 scale shapes handed to the kernel match what `trtllm_fp8_block_scale_moe` expects. The MxFP8 rows skip intermediate 176 because no 32-element MX scale block exists for it; that shape is covered for NVFP4 only.\n\n## Summary by CodeRabbit\n\n* **New Features**\n * Added utilities for padding quantized TRT-LLM MoE weights and block scales to kernel-compatible dimensions, while preserving the original valid dimensions.\n* **Documentation**\n * Clarified hidden-size and intermediate-size alignment requirements for FP8 and FP4 block-scale operations, including padding guidance.\n* **Bug Fixes**\n * Unaligned row counts now produce clearer errors that identify the required alignment and suggest zero-padding.\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/fused_moe/__init__.py b/flashinfer/fused_moe/__init__.py\nindex 7263ad02396..e5527c71fe6 100644\n--- a/flashinfer/fused_moe/__init__.py\n+++ b/flashinfer/fused_moe/__init__.py\n@@ -163,6 +163,7 @@ def __dir__() -> list[str]:\n RoutingInputMode,\n TrtllmMoERoutingMetadata,\n TrtllmMoERoutingMetadataSlot,\n+ TrtllmMoePaddedWeights,\n convert_to_block_layout,\n cutlass_fused_moe,\n cutlass_fused_moe_workspace_size,\n@@ -172,6 +173,7 @@ def __dir__() -> list[str]:\n gen_cutlass_fused_moe_sm100_module,\n gen_cutlass_fused_moe_sm90_module,\n gen_trtllm_gen_fused_moe_sm100_module,\n+ pad_trtllm_moe_weights,\n reorder_rows_for_gated_act_gemm,\n trtllm_fp4_block_scale_moe,\n trtllm_fp4_block_scale_routed_moe,\n@@ -456,6 +458,8 @@ def __getattr__(name: str):\n \"gen_cutlass_fused_moe_sm100_module\",\n \"gen_cutlass_fused_moe_sm90_module\",\n \"gen_trtllm_gen_fused_moe_sm100_module\",\n+ \"pad_trtllm_moe_weights\",\n+ \"TrtllmMoePaddedWeights\",\n \"reorder_rows_for_gated_act_gemm\",\n \"trtllm_bf16_moe\",\n \"prims_ts_bf16_moe\",\ndiff --git a/flashinfer/fused_moe/core.py b/flashinfer/fused_moe/core.py\nindex c7dd5efa7e1..daca090e117 100644\n--- a/flashinfer/fused_moe/core.py\n+++ b/flashinfer/fused_moe/core.py\n@@ -27,6 +27,7 @@\n Dict,\n List,\n Mapping,\n+ NamedTuple,\n Optional,\n Sequence,\n Tuple,\n@@ -481,6 +482,203 @@ def is_trtllm_moe_supported(\n return True\n \n \n+_TRTLLM_MOE_PAD_HIDDEN_ALIGNMENT = 512\n+_TRTLLM_MOE_PAD_INTERMEDIATE_ALIGNMENT = 128\n+\n+\n+class TrtllmMoePaddedWeights(NamedTuple):\n+ \"\"\"Result of :func:`pad_trtllm_moe_weights`.\n+\n+ ``hidden_size`` and ``intermediate_size`` are the padded sizes the tensors\n+ now have (pad the activations to ``hidden_size`` and pass\n+ ``intermediate_size`` to the MoE op); ``valid_hidden_size`` and\n+ ``valid_intermediate_size`` are the original sizes to pass as the op's\n+ ``valid_hidden_size`` / ``valid_intermediate_size``.\n+ \"\"\"\n+\n+ gemm1_weights: torch.Tensor\n+ gemm1_weights_scale: torch.Tensor\n+ gemm2_weights: torch.Tensor\n+ gemm2_weights_scale: torch.Tensor\n+ hidden_size: int\n+ intermediate_size: int\n+ valid_hidden_size: int\n+ valid_intermediate_size: int\n+\n+\n+def _pad_bytes(t: torch.Tensor, dim: int, size: int, fill: int) -> torch.Tensor:\n+ u8 = t.view(torch.uint8)\n+ pad = size - u8.shape[dim]\n+ if pad < 0:\n+ raise ValueError(f\"cannot pad dim {dim} of {tuple(t.shape)} down to {size}\")\n+ if pad == 0:\n+ return t\n+ shape = list(u8.shape)\n+ shape[dim] = pad\n+ tail = torch.full(shape, fill, dtype=torch.uint8, device=t.device)\n+ return torch.cat([u8, tail], dim=dim).view(t.dtype)\n+\n+\n+def pad_trtllm_moe_weights(\n+ gemm1_weights: torch.Tensor,\n+ gemm1_weights_scale: torch.Tensor,\n+ gemm2_weights: torch.Tensor,\n+ gemm2_weights_scale: torch.Tensor,\n+ hidden_size: int,\n+ intermediate_size: int,\n+ *,\n+ is_gated_act: bool = True,\n+ hidden_alignment: int = _TRTLLM_MOE_PAD_HIDDEN_ALIGNMENT,\n+ intermediate_alignment: int = _TRTLLM_MOE_PAD_INTERMEDIATE_ALIGNMENT,\n+) -> TrtllmMoePaddedWeights:\n+ r\"\"\"Zero-pad block-scaled MoE expert weights to the sizes the trtllm-gen kernels accept.\n+\n+ The trtllm-gen fused MoE kernels (:func:`trtllm_fp8_block_scale_moe` with\n+ MxFP8, :func:`trtllm_fp4_block_scale_moe` with NVFP4 or MxFP4) need\n+ ``intermediate_size`` to be a multiple of 128 and ``hidden_size`` to be a\n+ multiple of the GEMM1 K tile. Models whose expert dimensions are not\n+ (Nemotron Nano: hidden 2688, intermediate 1856, or 928 at TP2) pad their\n+ weights and declare the real sizes through ``valid_hidden_size`` and\n+ ``valid_intermediate_size``; GEMM2 then computes ``roundUp(hidden, 128)``\n+ columns and the finalized output is cropped to the valid width. This helper\n+ performs that padding on already quantized weights and their block scales.\n+\n+ Weights are padded with zeros and block scales with the neutral scale of\n+ their format (E8M0 ``127`` = 1.0 for the 32-element MX blocks, E4M3 ``1.0``\n+ for the 16-element NVFP4 blocks), so a padded element dequantizes to zero.\n+ GEMM1 still contracts over the padded hidden size, so this is what keeps the\n+ padded activation columns out of the result.\n+ For gated activations the gate and up halves of ``gemm1_weights`` are\n+ padded independently, so the padded tensor is still\n+ ``[gate (intermediate_size rows); up (intermediate_size rows)]`` with the\n+ padded ``intermediate_size``. Pass the result through the usual shuffle\n+ helpers (:func:`reorder_rows_for_gated_act_gemm`,\n+ :func:`~flashinfer.shuffle_matrix_a`, :func:`~flashinfer.shuffle_matrix_sf_a`\n+ or the permute-index helpers) exactly as you would unpadded weights.\n+\n+ Parameters\n+ ----------\n+ gemm1_weights : torch.Tensor\n+ FC1 weights ``[num_experts, F * intermediate_size, hidden_size / elems_per_byte]``\n+ in row-major (unshuffled) layout, one byte per element (``float8_e4m3fn``\n+ or ``uint8``); packed FP4 holds two elements per byte. ``F`` is 2 for\n+ gated activations and 1 otherwise.\n+ gemm1_weights_scale : torch.Tensor\n+ FC1 block scales ``[num_experts, F * intermediate_size, hidden_size / sf_vec_size]``\n+ in linear (non-interleaved) layout, one byte per scale.\n+ gemm2_weights : torch.Tensor\n+ FC2 weights ``[num_experts, hidden_size, intermediate_size / elems_per_byte]``.\n+ gemm2_weights_scale : torch.Tensor\n+ FC2 block scales ``[num_experts, hidden_size, intermediate_size / sf_vec_size]``.\n+ hidden_size : int\n+ The model's (unpadded) hidden size. Must be a multiple of ``sf_vec_size``.\n+ intermediate_size : int\n+ The model's (unpadded) per-rank intermediate size. Must be a multiple of\n+ ``sf_vec_size``.\n+ is_gated_act : bool\n+ Whether FC1 holds gate and up projections (``F = 2``). Default ``True``.\n+ hidden_alignment : int\n+ Alignment of the padded hidden size (GEMM1's K). Default ``512``. Must\n+ be a multiple of 256 for MxFP8 and NVFP4 (128 is rejected or gives\n+ wrong results).\n+ intermediate_alignment : int\n+ Alignment of the padded intermediate size. Default ``128``.\n+\n+ Returns\n+ -------\n+ TrtllmMoePaddedWeights\n+ The padded tensors plus the padded and valid sizes. ``gemm2_weights``\n+ and ``gemm2_weights_scale`` have ``roundUp(hidden_size, 128)`` rows, which\n+ is GEMM2's N when ``valid_hidden_size`` is given; ``gemm1_weights`` has\n+ ``roundUp(hidden_size, hidden_alignment)`` columns, which is the width\n+ to zero-pad the activations to.\n+ \"\"\"\n+ if hidden_alignment % 128 or intermediate_alignment % 128:\n+ raise ValueError(\n+ \"hidden_alignment and intermediate_alignment must be multiples of 128\"\n+ )\n+ for name, t in (\n+ (\"gemm1_weights\", gemm1_weights),\n+ (\"gemm1_weights_scale\", gemm1_weights_scale),\n+ (\"gemm2_weights\", gemm2_weights),\n+ (\"gemm2_weights_scale\", gemm2_weights_scale),\n+ ):\n+ if t.dim() != 3 or t.element_size() != 1:\n+ raise ValueError(\n+ f\"{name} must be a 3-D tensor with one byte per element, got {t.shape} {t.dtype}\"\n+ )\n+ factor = 2 if is_gated_act else 1\n+ num_experts, rows1, cols1 = gemm1_weights.shape\n+ if rows1 != factor * intermediate_size:\n+ raise ValueError(\n+ f\"gemm1_weights has {rows1} rows, expected {factor} * {intermediate_size}\"\n+ )\n+ if hidden_size % cols1 or hidden_size // cols1 not in (1, 2):\n+ raise ValueError(\n+ f\"gemm1_weights has {cols1} columns for hidden_size {hidden_size}; expected 1 or 2 elements per byte\"\n+ )\n+ elems_per_byte = hidden_size // cols1\n+ sf_cols1 = gemm1_weights_scale.shape[2]\n+ if hidden_size % sf_cols1 or hidden_size // sf_cols1 not in (16, 32):\n+ raise ValueError(\n+ f\"gemm1_weights_scale has {sf_cols1} columns for hidden_size {hidden_size}; expected 16 or 32 elements per scale\"\n+ )\n+ sf_vec_size = hidden_size // sf_cols1\n+ if intermediate_size % sf_vec_size or intermediate_size % elems_per_byte:\n+ raise ValueError(\n+ f\"intermediate_size {intermediate_size} must be a multiple of the scale block {sf_vec_size}\"\n+ )\n+ if tuple(gemm1_weights_scale.shape[:2]) != (num_experts, rows1):\n+ raise ValueError(\n+ f\"gemm1_weights_scale {tuple(gemm1_weights_scale.shape)} does not match gemm1_weights {tuple(gemm1_weights.shape)}\"\n+ )\n+ if tuple(gemm2_weights.shape) != (\n+ num_experts,\n+ hidden_size,\n+ intermediate_size // elems_per_byte,\n+ ):\n+ raise ValueError(\n+ f\"gemm2_weights must be [{num_experts}, {hidden_size}, {intermediate_size // elems_per_byte}], got {tuple(gemm2_weights.shape)}\"\n+ )\n+ if tuple(gemm2_weights_scale.shape) != (\n+ num_experts,\n+ hidden_size,\n+ intermediate_size // sf_vec_size,\n+ ):\n+ raise ValueError(\n+ f\"gemm2_weights_scale must be [{num_experts}, {hidden_size}, {intermediate_size // sf_vec_size}], got {tuple(gemm2_weights_scale.shape)}\"\n+ )\n+\n+ # E8M0 127 and E4M3 0x38 both encode 1.0.\n+ neutral_scale = 127 if sf_vec_size == 32 else 0x38\n+ padded_hidden = _round_up(hidden_size, hidden_alignment)\n+ gemm2_rows = _round_up(hidden_size, _TRTLLM_MOE_OUTPUT_HIDDEN_ALIGNMENT)\n+ padded_intermediate = _round_up(intermediate_size, intermediate_alignment)\n+\n+ def pad_fc1(t: torch.Tensor, cols: int, fill: int) -> torch.Tensor:\n+ halves = torch.chunk(t, factor, dim=1)\n+ halves = [_pad_bytes(h, 1, padded_intermediate, fill) for h in halves]\n+ return _pad_bytes(torch.cat(halves, dim=1), 2, cols, fill)\n+\n+ def pad_fc2(t: torch.Tensor, cols: int, fill: int) -> torch.Tensor:\n+ return _pad_bytes(_pad_bytes(t, 1, gemm2_rows, fill), 2, cols, fill)\n+\n+ return TrtllmMoePaddedWeights(\n+ gemm1_weights=pad_fc1(gemm1_weights, padded_hidden // elems_per_byte, 0),\n+ gemm1_weights_scale=pad_fc1(\n+ gemm1_weights_scale, padded_hidden // sf_vec_size, neutral_scale\n+ ),\n+ gemm2_weights=pad_fc2(gemm2_weights, padded_intermediate // elems_per_byte, 0),\n+ gemm2_weights_scale=pad_fc2(\n+ gemm2_weights_scale, padded_intermediate // sf_vec_size, neutral_scale\n+ ),\n+ hidden_size=padded_hidden,\n+ intermediate_size=padded_intermediate,\n+ valid_hidden_size=hidden_size,\n+ valid_intermediate_size=intermediate_size,\n+ )\n+\n+\n def _maybe_get_cached_w3_w1_permute_indices(\n _cache_permute_indices,\n dst_w3_w1_weight: torch.Tensor,\n@@ -6206,12 +6404,27 @@ def trtllm_fp8_block_scale_moe(\n ``roundUp(valid_hidden_size, 128)`` columns (that is what the FC2\n weights, weight scales and bias are sized for) and finalize writes only\n the leading ``valid_hidden_size`` of them. A caller-supplied ``output``\n- must therefore have ``valid_hidden_size`` columns. Default ``None``\n- (use the full ``hidden_size``).\n+ must therefore have ``valid_hidden_size`` columns. For MxFP8 the padded\n+ ``hidden_size`` must be a multiple of 256 (128 is rejected). Default\n+ ``None`` (use the full ``hidden_size``).\n valid_intermediate_size : Optional[int]\n Valid (unpadded) intermediate dimension. When provided,\n ``intermediate_size`` is treated as padded and only the valid region is\n computed. Default ``None`` (use the full ``intermediate_size``).\n+\n+ The kernels tile expert weights in 128-row blocks, so\n+ ``intermediate_size`` (and with it the FC1 row count ``M``) must be a\n+ multiple of ``128``; a model dimension that is not (``1856``, ``928``)\n+ is supported by padding and declaring, not by passing it directly.\n+ Zero-pad the weights to a multiple of ``128`` (the gate and up halves\n+ of FC1 separately, so the rows stay ``[gate; up]`` at the padded\n+ size), fill the padded block scales with a neutral finite value\n+ (E8M0 ``127``, i.e. ``2**0``, for MXFP8; ``1.0`` for the ``float32``\n+ DeepSeek scales), pass the padded size as ``intermediate_size`` and\n+ the real one here. The kernel reads the ``[valid, roundUp(valid, 128))``\n+ stretch of the padding and never reads the rest, so it must hold zeros and\n+ finite scales. ``hidden_size`` follows the same rule through\n+ ``valid_hidden_size``.\n gemm1_bias : Optional[torch.Tensor]\n Optional FC1 bias, float32 (keyword-only). Shape is\n ``[local_num_experts, 2 * intermediate_size]`` for gated activations\n@@ -6486,8 +6699,9 @@ def trtllm_fp8_block_scale_routed_moe(\n ``roundUp(valid_hidden_size, 128)`` columns (that is what the FC2\n weights, weight scales and bias are sized for) and finalize writes only\n the leading ``valid_hidden_size`` of them. A caller-supplied ``output``\n- must therefore have ``valid_hidden_size`` columns. Default ``None``\n- (use the full ``hidden_size``).\n+ must therefore have ``valid_hidden_size`` columns. For MxFP8 the padded\n+ ``hidden_size`` must be a multiple of 256 (128 is rejected). Default\n+ ``None`` (use the full ``hidden_size``).\n valid_intermediate_size : Optional[int]\n Valid (unpadded) intermediate dimension. When provided,\n ``intermediate_size`` is treated as padded and only the valid region is\n@@ -6800,12 +7014,27 @@ def trtllm_fp4_block_scale_moe(\n ``roundUp(valid_hidden_size, 128)`` columns (that is what the FC2\n weights, weight scales and bias are sized for) and finalize writes only\n the leading ``valid_hidden_size`` of them. A caller-supplied ``output``\n- must therefore have ``valid_hidden_size`` columns. Default ``None``\n- (use the full ``hidden_size``).\n+ must therefore have ``valid_hidden_size`` columns. For NVFP4 the padded\n+ ``hidden_size`` must be a multiple of 256 (128 gives wrong results).\n+ Default ``None`` (use the full ``hidden_size``).\n valid_intermediate_size : Optional[int]\n Valid (unpadded) intermediate dimension. When provided,\n ``intermediate_size`` is treated as padded and only the valid region is\n computed. Default ``None`` (use the full ``intermediate_size``).\n+\n+ The kernels tile expert weights in 128-row blocks, so\n+ ``intermediate_size`` (and with it the FC1 row count ``M``) must be a\n+ multiple of ``128``; a model dimension that is not (``1856``, ``928``)\n+ is supported by padding and declaring, not by passing it directly.\n+ Zero-pad the weights to a multiple of ``128`` (the gate and up halves\n+ of FC1 separately, so the rows stay ``[gate; up]`` at the padded\n+ size), fill the padded block scales with a neutral finite value\n+ (E8M0 ``127``, i.e. ``2**0``, for MXFP4; E4M3 ``1.0`` for NVFP4),\n+ pass the padded size as ``intermediate_size`` and the real one here.\n+ The kernel reads the ``[valid, roundUp(valid, 128))``\n+ stretch of the padding and never reads the rest, so it must hold zeros and\n+ finite scales. ``hidden_size`` follows the same rule through\n+ ``valid_hidden_size``.\n workspace_buffer : Optional[torch.Tensor]\n Caller-owned 1-D ``uint8`` CUDA buffer of at least\n :func:`trtllm_fused_moe_workspace_size` bytes. When given, the launch\n@@ -7090,8 +7319,9 @@ def trtllm_fp4_block_scale_routed_moe(\n ``roundUp(valid_hidden_size, 128)`` columns (that is what the FC2\n weights, weight scales and bias are sized for) and finalize writes only\n the leading ``valid_hidden_size`` of them. A caller-supplied ``output``\n- must therefore have ``valid_hidden_size`` columns. Default ``None``\n- (use the full ``hidden_size``).\n+ must therefore have ``valid_hidden_size`` columns. For NVFP4 the padded\n+ ``hidden_size`` must be a multiple of 256 (128 gives wrong results).\n+ Default ``None`` (use the full ``hidden_size``).\n valid_intermediate_size : Optional[int]\n Valid (unpadded) intermediate dimension. When provided,\n ``intermediate_size`` is treated as padded and only the valid region is\ndiff --git a/flashinfer/utils.py b/flashinfer/utils.py\nindex 52f666cd19f..8875b20673e 100644\n--- a/flashinfer/utils.py\n+++ b/flashinfer/utils.py\n@@ -1113,6 +1113,15 @@ def get_shuffle_block_size(epilogue_tile_m: int) -> int:\n return shuffle_block_size\n \n \n+def _unaligned_rows_message(M: int, alignment: int) -> str:\n+ return (\n+ f\"input_tensor.shape[0]={M} must be a multiple of {alignment}. For the trtllm \"\n+ \"block-scale MoE ops (FP8, FP4, MXINT4), zero-pad the unaligned dimension \"\n+ \"(intermediate_size for FC1, hidden_size for FC2) to a multiple of 128 and \"\n+ \"pass valid_intermediate_size / valid_hidden_size.\"\n+ )\n+\n+\n def get_shuffle_matrix_a_row_indices(\n input_tensor: torch.Tensor, epilogue_tile_m: int\n ) -> torch.Tensor:\n@@ -1132,9 +1141,7 @@ def get_shuffle_matrix_a_row_indices(\n shuffle_block_size = get_shuffle_block_size(epilogue_tile_m)\n row_map = srcToDstBlk16RowMap if shuffle_block_size == 16 else srcToDstBlk32RowMap\n \n- assert M % shuffle_block_size == 0, (\n- f\"input_tensor.shape[0] must be multiples of {shuffle_block_size}\"\n- )\n+ assert M % shuffle_block_size == 0, _unaligned_rows_message(M, shuffle_block_size)\n \n # row_indices[new_row] = old_row\n # so row_indices is an array of size M telling us from which old_row\n@@ -1163,7 +1170,7 @@ def get_shuffle_matrix_sf_a_row_indices(\n \n # M, K from the input\n M, K = input_tensor.shape\n- assert M % 128 == 0\n+ assert M % 128 == 0, _unaligned_rows_message(M, 128)\n # K % 4 alignment is not required here, downstream block_scale_interleave kernel pads K to a multiple of 4 internally\n row_indices = get_shuffle_matrix_a_row_indices(input_tensor, epilogue_tile_m)\n \ndiff --git a/tests/moe/test_trtllm_moe_padded_dims.py b/tests/moe/test_trtllm_moe_padded_dims.py\nnew file mode 100644\nindex 00000000000..7dd90f7deb4\n--- /dev/null\n+++ b/tests/moe/test_trtllm_moe_padded_dims.py\n@@ -0,0 +1,420 @@\n+\"\"\"\n+Copyright (c) 2026 by FlashInfer team.\n+\n+Licensed under the Apache License, Version 2.0 (the \"License\");\n+you may not use this file except in compliance with the License.\n+You may obtain a copy of the License at\n+\n+ http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+\"\"\"\n+\n+import math\n+\n+import pytest\n+import torch\n+\n+from flashinfer import (\n+ ActivationType,\n+ RoutingMethodType,\n+ reorder_rows_for_gated_act_gemm,\n+ shuffle_matrix_a,\n+ shuffle_matrix_sf_a,\n+)\n+from flashinfer.fp4_quantization import block_scale_interleave\n+from flashinfer.fused_moe import (\n+ pad_trtllm_moe_weights,\n+ trtllm_fp4_block_scale_moe,\n+ trtllm_fp8_block_scale_moe,\n+)\n+from flashinfer.fused_moe.core import (\n+ Fp8QuantizationType,\n+ _maybe_get_cached_w3_w1_permute_indices,\n+ _round_up,\n+ get_w2_permute_indices_with_cache,\n+)\n+from flashinfer.utils import device_support_pdl, get_compute_capability\n+\n+from .trtllm_gen_fused_moe_utils import (\n+ FP4Moe,\n+ FP8BlockScaleMoe,\n+ check_accuracy,\n+ moe_args,\n+ quant_fp4_batches,\n+ routing_reference_renormalize,\n+)\n+from .utils import QuantMode, is_gated_activation\n+\n+# Nemotron Nano expert geometry (TP1 and TP2) and the #3206 TP4 shard.\n+_SHAPES = [(2688, 1856), (2688, 928), (1024, 176)]\n+_CONTAM = 42.0\n+\n+\n+def _skip_unless_sm100():\n+ if not torch.cuda.is_available():\n+ pytest.skip(\"CUDA is required for TRT-LLM MoE kernels.\")\n+ if get_compute_capability(torch.device(\"cuda\"))[0] not in [10]:\n+ pytest.skip(\"TRT-LLM MoE tests are only guaranteed on SM100/SM103 GPUs.\")\n+\n+\n+@pytest.mark.parametrize(\"hidden_size,intermediate_size\", _SHAPES)\n+@pytest.mark.parametrize(\"elems_per_byte,sf_vec_size\", [(1, 32), (2, 16)])\n+@pytest.mark.parametrize(\"is_gated_act\", [True, False])\n+def test_pad_trtllm_moe_weights_round_trip(\n+ hidden_size, intermediate_size, elems_per_byte, sf_vec_size, is_gated_act\n+):\n+ if intermediate_size % sf_vec_size:\n+ pytest.skip(\"intermediate_size must be a multiple of the scale block\")\n+ torch.manual_seed(0)\n+ num_experts = 2\n+ factor = 2 if is_gated_act else 1\n+ rows1 = factor * intermediate_size\n+\n+ def rand_bytes(*shape):\n+ return torch.randint(1, 255, shape, dtype=torch.uint8)\n+\n+ w1 = rand_bytes(num_experts, rows1, hidden_size // elems_per_byte)\n+ s1 = rand_bytes(num_experts, rows1, hidden_size // sf_vec_size)\n+ w2 = rand_bytes(num_experts, hidden_size, intermediate_size // elems_per_byte)\n+ s2 = rand_bytes(num_experts, hidden_size, intermediate_size // sf_vec_size)\n+\n+ padded = pad_trtllm_moe_weights(\n+ w1.view(torch.float8_e4m3fn),\n+ s1,\n+ w2.view(torch.float8_e4m3fn),\n+ s2,\n+ hidden_size,\n+ intermediate_size,\n+ is_gated_act=is_gated_act,\n+ )\n+ pi, ph = padded.intermediate_size, padded.hidden_size\n+ gemm2_rows = _round_up(hidden_size, 128)\n+ assert pi % 128 == 0 and pi >= intermediate_size\n+ assert ph % 512 == 0 and ph >= hidden_size\n+ assert padded.valid_hidden_size == hidden_size\n+ assert padded.valid_intermediate_size == intermediate_size\n+ assert padded.gemm1_weights.dtype == torch.float8_e4m3fn\n+ assert padded.gemm1_weights.shape == (\n+ num_experts,\n+ factor * pi,\n+ ph // elems_per_byte,\n+ )\n+ assert padded.gemm1_weights_scale.shape == (\n+ num_experts,\n+ factor * pi,\n+ ph // sf_vec_size,\n+ )\n+ assert padded.gemm2_weights.shape == (num_experts, gemm2_rows, pi // elems_per_byte)\n+ assert padded.gemm2_weights_scale.shape == (\n+ num_experts,\n+ gemm2_rows,\n+ pi // sf_vec_size,\n+ )\n+\n+ neutral = 127 if sf_vec_size == 32 else 0x38\n+ for src, dst, fill, cols in (\n+ (w1, padded.gemm1_weights.view(torch.uint8), 0, hidden_size // elems_per_byte),\n+ (s1, padded.gemm1_weights_scale, neutral, hidden_size // sf_vec_size),\n+ ):\n+ mask = torch.zeros_like(dst, dtype=torch.bool)\n+ for h in range(factor):\n+ dst_half = dst[:, h * pi : (h + 1) * pi]\n+ src_half = src[:, h * intermediate_size : (h + 1) * intermediate_size]\n+ torch.testing.assert_close(dst_half[:, :intermediate_size, :cols], src_half)\n+ mask[:, h * pi : h * pi + intermediate_size, :cols] = True\n+ assert (dst[~mask] == fill).all()\n+ for src, dst, fill, cols in (\n+ (\n+ w2,\n+ padded.gemm2_weights.view(torch.uint8),\n+ 0,\n+ intermediate_size // elems_per_byte,\n+ ),\n+ (s2, padded.gemm2_weights_scale, neutral, intermediate_size // sf_vec_size),\n+ ):\n+ torch.testing.assert_close(dst[:, :hidden_size, :cols], src)\n+ mask = torch.zeros_like(dst, dtype=torch.bool)\n+ mask[:, :hidden_size, :cols] = True\n+ assert (dst[~mask] == fill).all()\n+\n+\n+def test_pad_trtllm_moe_weights_rejects_mismatched_shapes():\n+ w1 = torch.zeros(2, 2 * 64, 128, dtype=torch.float8_e4m3fn)\n+ s1 = torch.zeros(2, 2 * 64, 128 // 32, dtype=torch.uint8)\n+ w2 = torch.zeros(2, 128, 64, dtype=torch.float8_e4m3fn)\n+ s2 = torch.zeros(2, 128, 64 // 32, dtype=torch.uint8)\n+ pad_trtllm_moe_weights(w1, s1, w2, s2, 128, 64)\n+ with pytest.raises(ValueError):\n+ pad_trtllm_moe_weights(w1, s1, w2, s2, 128, 64, is_gated_act=False)\n+ with pytest.raises(ValueError):\n+ pad_trtllm_moe_weights(w1, s1, w2[:, :64], s2, 128, 64)\n+ with pytest.raises(ValueError):\n+ pad_trtllm_moe_weights(w1, s1, w2, s2, 128, 64, hidden_alignment=256 + 64)\n+\n+\n+def _run_padded_moe(\n+ quant_mode,\n+ activation_type,\n+ valid_hidden_size,\n+ valid_intermediate_size,\n+ hidden_alignment=512,\n+ num_tokens=64,\n+ num_experts=8,\n+ top_k=2,\n+):\n+ \"\"\"Run the padded kernel at ``(valid_hidden_size, valid_intermediate_size)``.\n+\n+ Returns ``(kernel_output, reference_output, tolerances)``; the reference is the\n+ dequant MoE over the unpadded problem.\n+ \"\"\"\n+ torch.manual_seed(0)\n+ device = torch.device(\"cuda:0\")\n+ padding = 8\n+ vh, vi = valid_hidden_size, valid_intermediate_size\n+ gated = is_gated_activation(activation_type)\n+ factor = 2 if gated else 1\n+ activation = activation_type.value\n+\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ moe = FP8BlockScaleMoe(fp8_quantization_type=quant_mode)\n+ else:\n+ moe = FP4Moe(quant_mode=quant_mode)\n+ moe._cache_permute_indices = {}\n+\n+ expert_logits = torch.randn(num_tokens, num_experts, device=device).to(\n+ torch.bfloat16\n+ )\n+ hidden_states = 2 * torch.randn(num_tokens, vh, device=device, dtype=torch.bfloat16)\n+ gemm1_weights = torch.randn(\n+ num_experts, factor * vi, vh, device=device, dtype=torch.bfloat16\n+ ) / math.sqrt(vh)\n+ gemm2_weights = torch.randn(\n+ num_experts, vh, vi, device=device, dtype=torch.bfloat16\n+ ) / math.sqrt(vi)\n+ permute_info, _ = routing_reference_renormalize(\n+ expert_logits, top_k, num_experts, padding\n+ )\n+\n+ # Reference: the unpadded problem through the dequant MoE.\n+ weights_data = moe.quantize_weights(gemm1_weights, gemm2_weights, hidden_states)\n+ inputs_data = moe.quantize_inputs(\n+ hidden_states, weights_data[\"hidden_states_scale_global\"]\n+ )\n+ args_valid = moe_args(\n+ num_tokens,\n+ num_experts,\n+ vh,\n+ vi,\n+ top_k,\n+ padding,\n+ inputs_data[\"hidden_states\"],\n+ inputs_data[\"hidden_states_scale\"],\n+ weights_data[\"hidden_states_scale_global\"],\n+ expert_logits,\n+ weights_data[\"gemm1_weights\"],\n+ weights_data[\"gemm1_scales\"],\n+ weights_data[\"gemm1_scales_global\"],\n+ weights_data[\"gemm2_weights\"],\n+ weights_data[\"gemm2_scales\"],\n+ weights_data[\"gemm2_scales_global\"],\n+ permute_info,\n+ False,\n+ activation,\n+ )\n+ reference_output, args_dequant = moe.compute_reference(args_valid)\n+ reference_output = reference_output.to(torch.float)\n+\n+ # Kernel: pad the linear-layout quantized weights, then shuffle as usual.\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ sf_vec_size = 32\n+ w1_lin = weights_data[\"gemm1_weights\"]\n+ s1_lin = weights_data[\"gemm1_scales\"].reshape(\n+ num_experts, factor * vi, vh // sf_vec_size\n+ )\n+ w2_lin = weights_data[\"gemm2_weights\"]\n+ s2_lin = weights_data[\"gemm2_scales\"].reshape(\n+ num_experts, vh, vi // sf_vec_size\n+ )\n+ else:\n+ sf_vec_size = moe.sf_vec_size\n+ _, s1_lin, _ = quant_fp4_batches(\n+ gemm1_weights, num_experts, moe.is_mxfp4, False\n+ )\n+ _, s2_lin, _ = quant_fp4_batches(\n+ gemm2_weights, num_experts, moe.is_mxfp4, False\n+ )\n+ w1_lin = (\n+ weights_data[\"gemm1_weights\"]\n+ .view(torch.uint8)\n+ .reshape(num_experts, factor * vi, vh // 2)\n+ )\n+ s1_lin = s1_lin.view(torch.uint8).reshape(\n+ num_experts, factor * vi, vh // sf_vec_size\n+ )\n+ w2_lin = (\n+ weights_data[\"gemm2_weights\"]\n+ .view(torch.uint8)\n+ .reshape(num_experts, vh, vi // 2)\n+ )\n+ s2_lin = s2_lin.view(torch.uint8).reshape(num_experts, vh, vi // sf_vec_size)\n+\n+ padded = pad_trtllm_moe_weights(\n+ w1_lin,\n+ s1_lin,\n+ w2_lin,\n+ s2_lin,\n+ vh,\n+ vi,\n+ is_gated_act=gated,\n+ hidden_alignment=hidden_alignment,\n+ )\n+ ph, pi = padded.hidden_size, padded.intermediate_size\n+ gemm2_rows = padded.gemm2_weights.shape[1]\n+ epilogue_tile_m = 128\n+\n+ g1_w, g1_s, g2_w, g2_s = [], [], [], []\n+ for e in range(num_experts):\n+ w1 = padded.gemm1_weights[e].view(torch.uint8)\n+ s1 = padded.gemm1_weights_scale[e].view(torch.uint8)\n+ w2 = padded.gemm2_weights[e].view(torch.uint8)\n+ s2 = padded.gemm2_weights_scale[e].view(torch.uint8)\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ if gated:\n+ w1 = reorder_rows_for_gated_act_gemm(w1)\n+ s1 = reorder_rows_for_gated_act_gemm(s1)\n+ g1_w.append(shuffle_matrix_a(w1, epilogue_tile_m))\n+ g1_s.append(shuffle_matrix_sf_a(s1, epilogue_tile_m))\n+ g2_w.append(shuffle_matrix_a(w2, epilogue_tile_m))\n+ g2_s.append(shuffle_matrix_sf_a(s2, epilogue_tile_m))\n+ else:\n+ p = _maybe_get_cached_w3_w1_permute_indices(\n+ moe._cache_permute_indices, w1, epilogue_tile_m, is_gated_act_gemm=gated\n+ )\n+ g1_w.append(w1[p.to(device)].contiguous())\n+ p = _maybe_get_cached_w3_w1_permute_indices(\n+ moe._cache_permute_indices,\n+ s1,\n+ epilogue_tile_m,\n+ num_elts_per_sf=sf_vec_size,\n+ is_gated_act_gemm=gated,\n+ )\n+ g1_s.append(block_scale_interleave(s1[p.to(device)].contiguous()))\n+ p = get_w2_permute_indices_with_cache(\n+ moe._cache_permute_indices, w2, epilogue_tile_m\n+ )\n+ g2_w.append(w2[p.to(device)].contiguous())\n+ p = get_w2_permute_indices_with_cache(\n+ moe._cache_permute_indices,\n+ s2,\n+ epilogue_tile_m,\n+ num_elts_per_sf=sf_vec_size,\n+ )\n+ g2_s.append(block_scale_interleave(s2[p.to(device)].contiguous()))\n+ gemm1_weights_k = torch.stack(g1_w)\n+ gemm2_weights_k = torch.stack(g2_w)\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ gemm1_weights_k = gemm1_weights_k.view(torch.float8_e4m3fn)\n+ gemm2_weights_k = gemm2_weights_k.view(torch.float8_e4m3fn)\n+ gemm1_scales_k = torch.stack(g1_s).reshape(\n+ num_experts, factor * pi, ph // sf_vec_size\n+ )\n+ gemm2_scales_k = torch.stack(g2_s).reshape(\n+ num_experts, gemm2_rows, pi // sf_vec_size\n+ )\n+\n+ # GEMM1 contracts over the padded hidden: poison the pad so only zero weights can hide it.\n+ hidden_padded = torch.full(\n+ (num_tokens, ph), _CONTAM, device=device, dtype=torch.bfloat16\n+ )\n+ hidden_padded[:, :vh] = hidden_states\n+ kernel_inputs = moe.quantize_inputs(\n+ hidden_padded, weights_data[\"hidden_states_scale_global\"], is_swizzling=False\n+ )\n+ common = dict(\n+ routing_bias=None,\n+ num_experts=num_experts,\n+ top_k=top_k,\n+ n_group=None,\n+ topk_group=None,\n+ intermediate_size=pi,\n+ local_expert_offset=0,\n+ local_num_experts=num_experts,\n+ routed_scaling_factor=None,\n+ routing_method_type=RoutingMethodType.Renormalize.value,\n+ activation_type=activation,\n+ do_finalize=True,\n+ enable_pdl=device_support_pdl(device),\n+ valid_hidden_size=vh,\n+ valid_intermediate_size=vi,\n+ )\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8:\n+ out = trtllm_fp8_block_scale_moe(\n+ routing_logits=expert_logits,\n+ hidden_states=kernel_inputs[\"hidden_states\"],\n+ hidden_states_scale=kernel_inputs[\"hidden_states_scale\"],\n+ gemm1_weights=gemm1_weights_k,\n+ gemm1_weights_scale=gemm1_scales_k,\n+ gemm2_weights=gemm2_weights_k,\n+ gemm2_weights_scale=gemm2_scales_k,\n+ use_shuffled_weight=True,\n+ fp8_quantization_type=Fp8QuantizationType.MxFp8,\n+ **common,\n+ )\n+ else:\n+ g1_global = weights_data[\"gemm1_scales_global\"]\n+ g2_global = weights_data[\"gemm2_scales_global\"]\n+ hs_global = weights_data[\"hidden_states_scale_global\"]\n+ c_global_sf = args_dequant.c_global_sf\n+ scale_gate_fc1 = (1.0 / g1_global) * (1.0 / hs_global)\n+ if gated:\n+ scale_c_fc1 = c_global_sf * scale_gate_fc1\n+ else:\n+ scale_c_fc1 = torch.full_like(g1_global, c_global_sf)\n+ scale_c_fc2 = (1.0 / c_global_sf) * (1.0 / g2_global)\n+ out = trtllm_fp4_block_scale_moe(\n+ routing_logits=expert_logits,\n+ hidden_states=kernel_inputs[\"hidden_states\"],\n+ hidden_states_scale=kernel_inputs[\"hidden_states_scale\"],\n+ gemm1_weights=gemm1_weights_k,\n+ gemm1_weights_scale=gemm1_scales_k.view(torch.float8_e4m3fn),\n+ gemm1_bias=None,\n+ gemm1_alpha=None,\n+ gemm1_beta=None,\n+ gemm1_clamp_limit=None,\n+ gemm2_weights=gemm2_weights_k,\n+ gemm2_weights_scale=gemm2_scales_k.view(torch.float8_e4m3fn),\n+ gemm2_bias=None,\n+ output1_scale_scalar=scale_c_fc1,\n+ output1_scale_gate_scalar=scale_gate_fc1,\n+ output2_scale_scalar=scale_c_fc2,\n+ **common,\n+ )\n+ kernel_output = (out[0] if isinstance(out, list) else out).to(torch.float)\n+ return kernel_output, reference_output, moe.get_tolerances()\n+\n+\n+@pytest.mark.parametrize(\n+ \"quant_mode\", [QuantMode.FP8_BLOCK_SCALE_MXFP8, QuantMode.FP4_NVFP4_NVFP4]\n+)\n+@pytest.mark.parametrize(\n+ \"activation_type\", [ActivationType.Swiglu, ActivationType.Relu2]\n+)\n+@pytest.mark.parametrize(\"valid_hidden_size,valid_intermediate_size\", _SHAPES)\n+def test_padded_moe_matches_unpadded_reference(\n+ quant_mode, activation_type, valid_hidden_size, valid_intermediate_size\n+):\n+ _skip_unless_sm100()\n+ if quant_mode == QuantMode.FP8_BLOCK_SCALE_MXFP8 and valid_intermediate_size % 32:\n+ pytest.skip(\"MxFP8 needs a 32-aligned intermediate_size\")\n+ kernel_output, reference_output, tol = _run_padded_moe(\n+ quant_mode, activation_type, valid_hidden_size, valid_intermediate_size\n+ )\n+ assert kernel_output.shape == reference_output.shape == (64, valid_hidden_size)\n+ check_accuracy(\n+ reference_output, kernel_output, tol[\"atol\"], tol[\"rtol\"], tol[\"percent\"]\n+ )\ndiff --git a/tests/moe/test_trtllm_moe_valid_dims.py b/tests/moe/test_trtllm_moe_valid_dims.py\nindex ea1bc97ec98..68f280db41c 100644\n--- a/tests/moe/test_trtllm_moe_valid_dims.py\n+++ b/tests/moe/test_trtllm_moe_valid_dims.py\n@@ -25,7 +25,12 @@\n _round_up,\n _trtllm_moe_output_width,\n )\n-from flashinfer.utils import device_support_pdl, get_compute_capability\n+from flashinfer.utils import (\n+ device_support_pdl,\n+ get_compute_capability,\n+ get_shuffle_matrix_a_row_indices,\n+ get_shuffle_matrix_sf_a_row_indices,\n+)\n \n # The contract mirrored by this file (identical to TensorRT-LLM's\n # mxFp4BlockScaleMoe.cpp / fp4BlockScaleMoe.cpp), for a declared valid_hidden_size:\n@@ -151,6 +156,38 @@ def test_check_valid_hidden_size_supports_finalize_rejects(\n )\n \n \n+_SHUFFLE_ROW_INDEX_HELPERS = [\n+ pytest.param(get_shuffle_matrix_a_row_indices, 32, id=\"a\"),\n+ pytest.param(get_shuffle_matrix_sf_a_row_indices, 128, id=\"sf_a\"),\n+]\n+\n+\n+@pytest.mark.parametrize(\n+ (\"helper\", \"num_rows\"),\n+ [\n+ # Nemotron Nano intermediate sizes (TP1 / TP2) and the #3206 TP4 shape,\n+ # none of which the trtllm weight shuffle accepts without pad-and-declare.\n+ pytest.param(get_shuffle_matrix_sf_a_row_indices, 1856, id=\"sf_a-1856\"),\n+ pytest.param(get_shuffle_matrix_sf_a_row_indices, 928, id=\"sf_a-928\"),\n+ pytest.param(get_shuffle_matrix_sf_a_row_indices, 176, id=\"sf_a-176\"),\n+ pytest.param(get_shuffle_matrix_a_row_indices, 176, id=\"a-176\"),\n+ ],\n+)\n+def test_shuffle_row_indices_unaligned_rows_name_valid_dims(helper, num_rows):\n+ weight = torch.empty(num_rows, 64, dtype=torch.uint8)\n+ with pytest.raises(AssertionError, match=\"valid_intermediate_size\"):\n+ helper(weight, epilogue_tile_m=128)\n+\n+\n+@pytest.mark.parametrize((\"helper\", \"alignment\"), _SHUFFLE_ROW_INDEX_HELPERS)\n+@pytest.mark.parametrize(\"num_rows\", [1920, 3712])\n+def test_shuffle_row_indices_aligned_rows_is_permutation(helper, alignment, num_rows):\n+ assert num_rows % alignment == 0\n+ weight = torch.empty(num_rows, 64, dtype=torch.uint8)\n+ row_indices = helper(weight, epilogue_tile_m=128)\n+ assert torch.equal(row_indices.sort().values, torch.arange(num_rows))\n+\n+\n # Numerical test for valid_hidden_size.\n #\n # IMPORTANT: trtllm_mxint4_block_scale_moe consumes mxint4-quantized AND\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(b: honour deterministic_output in the fused MoE decode heuristic and the tuner validation\nLabels: run-ci, reinforcement learning\nFiles changed (3): flashinfer/experimental/b12x/moe/fused_moe/_impl.py, flashinfer/experimental/b12x/moe/fused_moe/_tuning.py, tests/experimental/b12x/moe/test_fused_moe_variant_selection.py\n\n## Description (results removed)\n\n## 📌 Description\n\nFour commits, one per gap:\n\n1. `_heuristic_dynamic_route_mode` forwards `bool(query.deterministic_output)`, so deterministic plans resolve to grouped routing. This is the one-line fix from #7281 by @bandham-manikanta, kept here with its original authorship because the second commit depends on it. #7281 can be closed in favour of this PR, or merged first and this PR rebased on top; either order works.\n3. `_materialize_tuning` validates the tuned route with `bool(query.deterministic_output)`, so the tuning space offers no `direct` route for deterministic queries. This was #8563, folded in here.\n\n## 🔍 Related Issues\n\nFixes #6941. Supersedes #7281 (first commit, same authorship) and #8563 (third commit, folded in).\n\n## 🧪 Tests\n[results removed]\n## Reviewer Notes\n\nThe micro guard in the heuristic sits after every backend choice, so it also applies to the non-`w4a8_mx` quant modes that `select_tp_moe_backend` can send to micro; `_tp_core_workspace_plan` already treats `deterministic_output` as dynamic-only, so no micro path loses behaviour it had. The tuner-side micro rejection mirrors that guard for tuned configs. `query.deterministic_output` is `bool | None` and `bool(None)` is `False`, so an unset flag keeps the old behaviour everywhere. Existing tuning caches that recorded a `direct` or `micro` choice for a deterministic query are not invalidated and the query schema version is not bumped; `TUNING.lower` re-runs `_materialize_tuning`, so loading such a choice now raises `ValueError` at materialisation instead of `RuntimeError` at launch (`direct`) or running non-deterministically (`micro`).\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/experimental/b12x/moe/fused_moe/_impl.py b/flashinfer/experimental/b12x/moe/fused_moe/_impl.py\nindex 413d0524a0c..1e25b4af0f1 100644\n--- a/flashinfer/experimental/b12x/moe/fused_moe/_impl.py\n+++ b/flashinfer/experimental/b12x/moe/fused_moe/_impl.py\n@@ -2668,7 +2668,7 @@ def _heuristic_dynamic_route_mode(\n routed_rows=query.routed_rows,\n num_experts=query.num_experts,\n n=dynamic_n,\n- deterministic_output=False,\n+ deterministic_output=bool(query.deterministic_output),\n planned_tile_m=planned_tile_m,\n )\n if (\n@@ -2835,6 +2835,8 @@ def _heuristic_moe_decode_config(\n and query.routed_rows > _DIRECT_ROUTING_MAX_ROUTED_ROWS\n ):\n backend = \"dynamic\"\n+ if backend == \"micro\" and query.deterministic_output:\n+ backend = \"dynamic\"\n dynamic_tile_m = None\n dynamic_route_mode = None\n if backend == \"dynamic\":\ndiff --git a/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py b/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py\nindex e0c788853ce..de5f59ec2d9 100644\n--- a/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py\n+++ b/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py\n@@ -623,6 +623,8 @@ def _materialize_tuning(query, device, choice):\n raise ValueError(\"compact W4A8 micro requires BF16 activations\")\n if config.backend == \"micro\" and not _policy_micro_supported(effective_query):\n raise ValueError(\"micro MoE does not support this concrete query\")\n+ if config.backend == \"micro\" and query.deterministic_output:\n+ raise ValueError(\"micro MoE has no deterministic combine\")\n if config.backend == \"dynamic\":\n if (\n effective_query.quant_mode in {\"w6a8_mx\", \"w8a8_mx\"}\n@@ -641,7 +643,7 @@ def _materialize_tuning(query, device, choice):\n n=_dynamic_kernel_intermediate_size(\n query.intermediate_size, effective_query.quant_mode\n ),\n- deterministic_output=False,\n+ deterministic_output=bool(query.deterministic_output),\n planned_tile_m=config.dynamic_tile_m,\n )\n except RuntimeError as exc:\ndiff --git a/tests/experimental/b12x/moe/test_fused_moe_variant_selection.py b/tests/experimental/b12x/moe/test_fused_moe_variant_selection.py\nindex 99375c262bf..edb3aa5a60e 100644\n--- a/tests/experimental/b12x/moe/test_fused_moe_variant_selection.py\n+++ b/tests/experimental/b12x/moe/test_fused_moe_variant_selection.py\n@@ -172,6 +172,104 @@ def test_nonverifier_tuning_routes_retain_cyclic_coverage(tokens):\n )\n \n \n+@pytest.mark.parametrize(\"deterministic_output\", [True, False])\n+def test_tuning_space_offers_direct_route_only_to_nondeterministic_queries(\n+ deterministic_output,\n+):\n+ from b12x.preparation import DeviceIdentity, FrozenMapping\n+ from b12x.moe.fused_moe._tuning import TUNING, MoeDecodeQuery\n+\n+ query = MoeDecodeQuery(\n+ quant_mode=\"w4a8_mx\",\n+ quant_modes=(\"w4a8_mx\",),\n+ source_format=\"fp4_e8m0_k32\",\n+ activation=\"silu\",\n+ io_dtype=\"bfloat16\",\n+ num_experts=384,\n+ hidden_size=2048,\n+ intermediate_size=2304,\n+ top_k=8,\n+ num_tokens=1,\n+ routed_rows=8,\n+ route_num_experts=384,\n+ route_logits_dtype=\"float32\",\n+ apply_router_weight_on_input=False,\n+ collect_activation_amax=False,\n+ deterministic_output=deterministic_output,\n+ swiglu_limit=None,\n+ swiglu_alpha=1.702,\n+ swiglu_beta=1.0,\n+ w13_layout=\"fused\",\n+ weight_layouts=(\"fused\",),\n+ w4a16_weight_layout=None,\n+ w4a16_scale_format=None,\n+ w4a16_block_size_m=None,\n+ fast_math=True,\n+ numerical_recipe=None,\n+ controls=FrozenMapping(),\n+ )\n+ device = DeviceIdentity(\n+ vendor=\"nvidia\",\n+ compute_capability=(12, 0),\n+ sm_count=170,\n+ product_name=\"NVIDIA GeForce RTX 5090\",\n+ )\n+ route_modes = {\n+ config.dynamic_route_mode\n+ for _, config in TUNING.choices(query, device)\n+ if config.backend == \"dynamic\"\n+ }\n+ assert \"grouped\" in route_modes\n+ assert (\"direct\" in route_modes) == (not deterministic_output)\n+\n+\n+@pytest.mark.parametrize(\"deterministic_output\", [True, False])\n+def test_tuning_space_offers_micro_only_to_nondeterministic_queries(\n+ deterministic_output,\n+):\n+ from b12x.preparation import DeviceIdentity, FrozenMapping\n+ from b12x.moe.fused_moe._tuning import TUNING, MoeDecodeQuery\n+\n+ query = MoeDecodeQuery(\n+ quant_mode=\"w4a8_mx\",\n+ quant_modes=(\"w4a8_mx\",),\n+ source_format=\"fp4_e8m0_k32\",\n+ activation=\"silu\",\n+ io_dtype=\"bfloat16\",\n+ num_experts=384,\n+ hidden_size=5120,\n+ intermediate_size=2304,\n+ top_k=6,\n+ num_tokens=1,\n+ routed_rows=6,\n+ route_num_experts=384,\n+ route_logits_dtype=\"float32\",\n+ apply_router_weight_on_input=False,\n+ collect_activation_amax=False,\n+ deterministic_output=deterministic_output,\n+ swiglu_limit=10.0,\n+ swiglu_alpha=1.702,\n+ swiglu_beta=1.0,\n+ w13_layout=\"w31\",\n+ weight_layouts=(\"w31\",),\n+ w4a16_weight_layout=None,\n+ w4a16_scale_format=None,\n+ w4a16_block_size_m=None,\n+ fast_math=True,\n+ numerical_recipe=None,\n+ controls=FrozenMapping(),\n+ )\n+ device = DeviceIdentity(\n+ vendor=\"nvidia\",\n+ compute_capability=(12, 0),\n+ sm_count=170,\n+ product_name=\"NVIDIA GeForce RTX 5090\",\n+ )\n+ backends = {config.backend for _, config in TUNING.choices(query, device)}\n+ assert \"dynamic\" in backends\n+ assert (\"micro\" in backends) == (not deterministic_output)\n+\n+\n def test_variant_for_preserves_exact_counts_and_reuses_prefill_capacity():\n variants = {count: _Variant(count) for count in (1, 2, 4, 8, 125, 128)}\n assert variant_for(variants, 4) is variants[4]\n@@ -436,3 +534,130 @@ def compile_direct(*, m, topk_ids_dtype, **kwargs):\n )\n assert program_keys(launch) == expected_programs\n assert len(compiled) == 2\n+\n+\n+@pytest.mark.parametrize(\"deterministic_output\", [True, False])\n+def test_heuristic_dynamic_route_mode_respects_deterministic_output(\n+ deterministic_output,\n+):\n+ from b12x.preparation import FrozenMapping, DeviceIdentity\n+ from b12x.moe.fused_moe._tuning import MoeDecodeQuery\n+ from flashinfer.experimental.b12x.moe.fused_moe._impl import (\n+ _heuristic_dynamic_route_mode,\n+ _dynamic_direct_routing_selected,\n+ _dynamic_kernel_intermediate_size,\n+ )\n+\n+ query = MoeDecodeQuery(\n+ quant_mode=\"w4a8_mx\",\n+ quant_modes=(\"w4a8_mx\",),\n+ source_format=\"mxfp8\",\n+ activation=\"silu\",\n+ io_dtype=\"bfloat16\",\n+ num_experts=384,\n+ hidden_size=2048,\n+ intermediate_size=2304,\n+ top_k=8,\n+ num_tokens=1,\n+ routed_rows=8,\n+ route_num_experts=384,\n+ route_logits_dtype=\"float32\",\n+ apply_router_weight_on_input=False,\n+ collect_activation_amax=False,\n+ deterministic_output=deterministic_output,\n+ swiglu_limit=None,\n+ swiglu_alpha=1.702,\n+ swiglu_beta=1.0,\n+ w13_layout=\"fused\",\n+ weight_layouts=(\"fused\",),\n+ w4a16_weight_layout=None,\n+ w4a16_scale_format=None,\n+ w4a16_block_size_m=None,\n+ fast_math=True,\n+ numerical_recipe=None,\n+ controls=FrozenMapping(),\n+ )\n+ device = DeviceIdentity(\n+ vendor=\"nvidia\",\n+ compute_capability=(8, 0),\n+ sm_count=108,\n+ product_name=\"NVIDIA A100-PCIE-40GB\",\n+ )\n+ planned_tile_m = 16\n+ route_mode = _heuristic_dynamic_route_mode(\n+ query,\n+ device,\n+ planned_tile_m=planned_tile_m,\n+ )\n+ if deterministic_output:\n+ assert route_mode == \"grouped\"\n+ else:\n+ assert route_mode == \"direct\"\n+\n+ dynamic_n = _dynamic_kernel_intermediate_size(\n+ query.intermediate_size, query.quant_mode\n+ )\n+ is_direct = _dynamic_direct_routing_selected(\n+ route_mode=route_mode,\n+ quant_mode=query.quant_mode,\n+ activation=query.activation,\n+ routed_rows=query.routed_rows,\n+ num_experts=query.num_experts,\n+ n=dynamic_n,\n+ deterministic_output=bool(query.deterministic_output),\n+ planned_tile_m=planned_tile_m,\n+ )\n+ assert is_direct == (not deterministic_output)\n+\n+\n+@pytest.mark.parametrize(\"deterministic_output\", [True, False])\n+def test_heuristic_decode_config_keeps_deterministic_queries_off_micro(\n+ deterministic_output,\n+):\n+ from b12x.preparation import FrozenMapping, DeviceIdentity\n+ from b12x.moe.fused_moe._tuning import MoeDecodeQuery\n+ from flashinfer.experimental.b12x.moe.fused_moe._impl import (\n+ _heuristic_moe_decode_config,\n+ )\n+\n+ query = MoeDecodeQuery(\n+ quant_mode=\"w4a8_mx\",\n+ quant_modes=(\"w4a8_mx\",),\n+ source_format=\"fp4_e8m0_k32\",\n+ activation=\"silu\",\n+ io_dtype=\"bfloat16\",\n+ num_experts=384,\n+ hidden_size=5120,\n+ intermediate_size=2304,\n+ top_k=6,\n+ num_tokens=1,\n+ routed_rows=6,\n+ route_num_experts=384,\n+ route_logits_dtype=\"float32\",\n+ apply_router_weight_on_input=False,\n+ collect_activation_amax=False,\n+ deterministic_output=deterministic_output,\n+ swiglu_limit=10.0,\n+ swiglu_alpha=1.702,\n+ swiglu_beta=1.0,\n+ w13_layout=\"w31\",\n+ weight_layouts=(\"w31\",),\n+ w4a16_weight_layout=None,\n+ w4a16_scale_format=None,\n+ w4a16_block_size_m=None,\n+ fast_math=True,\n+ numerical_recipe=None,\n+ controls=FrozenMapping(),\n+ )\n+ device = DeviceIdentity(\n+ vendor=\"nvidia\",\n+ compute_capability=(12, 0),\n+ sm_count=170,\n+ product_name=\"NVIDIA GeForce RTX 5090\",\n+ )\n+ config = _heuristic_moe_decode_config(query, device)\n+ if deterministic_output:\n+ assert config.backend == \"dynamic\"\n+ assert config.dynamic_route_mode == \"grouped\"\n+ else:\n+ assert config.backend == \"micro\"\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: flashinfer-ai/flashinfer\nPull request: fix(b: honour deterministic_output in the fused MoE decode heuristic and the tuner validation\nLabels: run-ci, reinforcement learning\nFiles changed (3): flashinfer/experimental/b12x/moe/fused_moe/_impl.py, flashinfer/experimental/b12x/moe/fused_moe/_tuning.py, tests/experimental/b12x/moe/test_fused_moe_variant_selection.py\n\n## Description (results removed)\n\n## 📌 Description\n\nFour commits, one per gap:\n\n1. `_heuristic_dynamic_route_mode` forwards `bool(query.deterministic_output)`, so deterministic plans resolve to grouped routing. This is the one-line fix from #7281 by @bandham-manikanta, kept here with its original authorship because the second commit depends on it. #7281 can be closed in favour of this PR, or merged first and this PR rebased on top; either order works.\n3. `_materialize_tuning` validates the tuned route with `bool(query.deterministic_output)`, so the tuning space offers no `direct` route for deterministic queries. This was #8563, folded in here.\n\n## 🔍 Related Issues\n\nFixes #6941. Supersedes #7281 (first commit, same authorship) and #8563 (third commit, folded in).\n\n## 🧪 Tests\n[results removed]\n## Reviewer Notes\n\nThe micro guard in the heuristic sits after every backend choice, so it also applies to the non-`w4a8_mx` quant modes that `select_tp_moe_backend` can send to micro; `_tp_core_workspace_plan` already treats `deterministic_output` as dynamic-only, so no micro path loses behaviour it had. The tuner-side micro rejection mirrors that guard for tuned configs. `query.deterministic_output` is `bool | None` and `bool(None)` is `False`, so an unset flag keeps the old behaviour everywhere. Existing tuning caches that recorded a `direct` or `micro` choice for a deterministic query are not invalidated and the query schema version is not bumped; `TUNING.lower` re-runs `_materialize_tuning`, so loading such a choice now raises `ValueError` at materialisation instead of `RuntimeError` at launch (`direct`) or running non-deterministically (`micro`).\n\n## Diff\n\n```diff\ndiff --git a/flashinfer/experimental/b12x/moe/fused_moe/_impl.py b/flashinfer/experimental/b12x/moe/fused_moe/_impl.py\nindex 413d0524a0c..1e25b4af0f1 100644\n--- a/flashinfer/experimental/b12x/moe/fused_moe/_impl.py\n+++ b/flashinfer/experimental/b12x/moe/fused_moe/_impl.py\n@@ -2668,7 +2668,7 @@ def _heuristic_dynamic_route_mode(\n routed_rows=query.routed_rows,\n num_experts=query.num_experts,\n n=dynamic_n,\n- deterministic_output=False,\n+ deterministic_output=bool(query.deterministic_output),\n planned_tile_m=planned_tile_m,\n )\n if (\n@@ -2835,6 +2835,8 @@ def _heuristic_moe_decode_config(\n and query.routed_rows > _DIRECT_ROUTING_MAX_ROUTED_ROWS\n ):\n backend = \"dynamic\"\n+ if backend == \"micro\" and query.deterministic_output:\n+ backend = \"dynamic\"\n dynamic_tile_m = None\n dynamic_route_mode = None\n if backend == \"dynamic\":\ndiff --git a/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py b/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py\nindex e0c788853ce..12068ac805e 100644\n--- a/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py\n+++ b/flashinfer/experimental/b12x/moe/fused_moe/_tuning.py\n@@ -641,7 +641,7 @@ def _materialize_tuning(query, device, choice):\n n=_dynamic_kernel_intermediate_size(\n query.intermediate_size, effective_query.quant_mode\n ),\n- deterministic_output=False,\n+ deterministic_output=bool(query.deterministic_output),\n planned_tile_m=config.dynamic_tile_m,\n )\n except RuntimeError as exc:\ndiff --git a/tests/experimental/b12x/moe/test_fused_moe_variant_selection.py b/tests/experimental/b12x/moe/test_fused_moe_variant_selection.py\nindex 99375c262bf..ba9ff297022 100644\n--- a/tests/experimental/b12x/moe/test_fused_moe_variant_selection.py\n+++ b/tests/experimental/b12x/moe/test_fused_moe_variant_selection.py\n@@ -172,6 +172,57 @@ def test_nonverifier_tuning_routes_retain_cyclic_coverage(tokens):\n )\n \n \n+@pytest.mark.parametrize(\"deterministic_output\", [True, False])\n+def test_tuning_space_offers_direct_route_only_to_nondeterministic_queries(\n+ deterministic_output,\n+):\n+ from b12x.preparation import DeviceIdentity, FrozenMapping\n+ from b12x.moe.fused_moe._tuning import TUNING, MoeDecodeQuery\n+\n+ query = MoeDecodeQuery(\n+ quant_mode=\"w4a8_mx\",\n+ quant_modes=(\"w4a8_mx\",),\n+ source_format=\"fp4_e8m0_k32\",\n+ activation=\"silu\",\n+ io_dtype=\"bfloat16\",\n+ num_experts=384,\n+ hidden_size=2048,\n+ intermediate_size=2304,\n+ top_k=8,\n+ num_tokens=1,\n+ routed_rows=8,\n+ route_num_experts=384,\n+ route_logits_dtype=\"float32\",\n+ apply_router_weight_on_input=False,\n+ collect_activation_amax=False,\n+ deterministic_output=deterministic_output,\n+ swiglu_limit=None,\n+ swiglu_alpha=1.702,\n+ swiglu_beta=1.0,\n+ w13_layout=\"fused\",\n+ weight_layouts=(\"fused\",),\n+ w4a16_weight_layout=None,\n+ w4a16_scale_format=None,\n+ w4a16_block_size_m=None,\n+ fast_math=True,\n+ numerical_recipe=None,\n+ controls=FrozenMapping(),\n+ )\n+ device = DeviceIdentity(\n+ vendor=\"nvidia\",\n+ compute_capability=(12, 0),\n+ sm_count=170,\n+ product_name=\"NVIDIA GeForce RTX 5090\",\n+ )\n+ route_modes = {\n+ config.dynamic_route_mode\n+ for _, config in TUNING.choices(query, device)\n+ if config.backend == \"dynamic\"\n+ }\n+ assert \"grouped\" in route_modes\n+ assert (\"direct\" in route_modes) == (not deterministic_output)\n+\n+\n def test_variant_for_preserves_exact_counts_and_reuses_prefill_capacity():\n variants = {count: _Variant(count) for count in (1, 2, 4, 8, 125, 128)}\n assert variant_for(variants, 4) is variants[4]\n@@ -436,3 +487,130 @@ def compile_direct(*, m, topk_ids_dtype, **kwargs):\n )\n assert program_keys(launch) == expected_programs\n assert len(compiled) == 2\n+\n+\n+@pytest.mark.parametrize(\"deterministic_output\", [True, False])\n+def test_heuristic_dynamic_route_mode_respects_deterministic_output(\n+ deterministic_output,\n+):\n+ from b12x.preparation import FrozenMapping, DeviceIdentity\n+ from b12x.moe.fused_moe._tuning import MoeDecodeQuery\n+ from flashinfer.experimental.b12x.moe.fused_moe._impl import (\n+ _heuristic_dynamic_route_mode,\n+ _dynamic_direct_routing_selected,\n+ _dynamic_kernel_intermediate_size,\n+ )\n+\n+ query = MoeDecodeQuery(\n+ quant_mode=\"w4a8_mx\",\n+ quant_modes=(\"w4a8_mx\",),\n+ source_format=\"mxfp8\",\n+ activation=\"silu\",\n+ io_dtype=\"bfloat16\",\n+ num_experts=384,\n+ hidden_size=2048,\n+ intermediate_size=2304,\n+ top_k=8,\n+ num_tokens=1,\n+ routed_rows=8,\n+ route_num_experts=384,\n+ route_logits_dtype=\"float32\",\n+ apply_router_weight_on_input=False,\n+ collect_activation_amax=False,\n+ deterministic_output=deterministic_output,\n+ swiglu_limit=None,\n+ swiglu_alpha=1.702,\n+ swiglu_beta=1.0,\n+ w13_layout=\"fused\",\n+ weight_layouts=(\"fused\",),\n+ w4a16_weight_layout=None,\n+ w4a16_scale_format=None,\n+ w4a16_block_size_m=None,\n+ fast_math=True,\n+ numerical_recipe=None,\n+ controls=FrozenMapping(),\n+ )\n+ device = DeviceIdentity(\n+ vendor=\"nvidia\",\n+ compute_capability=(8, 0),\n+ sm_count=108,\n+ product_name=\"NVIDIA A100-PCIE-40GB\",\n+ )\n+ planned_tile_m = 16\n+ route_mode = _heuristic_dynamic_route_mode(\n+ query,\n+ device,\n+ planned_tile_m=planned_tile_m,\n+ )\n+ if deterministic_output:\n+ assert route_mode == \"grouped\"\n+ else:\n+ assert route_mode == \"direct\"\n+\n+ dynamic_n = _dynamic_kernel_intermediate_size(\n+ query.intermediate_size, query.quant_mode\n+ )\n+ is_direct = _dynamic_direct_routing_selected(\n+ route_mode=route_mode,\n+ quant_mode=query.quant_mode,\n+ activation=query.activation,\n+ routed_rows=query.routed_rows,\n+ num_experts=query.num_experts,\n+ n=dynamic_n,\n+ deterministic_output=bool(query.deterministic_output),\n+ planned_tile_m=planned_tile_m,\n+ )\n+ assert is_direct == (not deterministic_output)\n+\n+\n+@pytest.mark.parametrize(\"deterministic_output\", [True, False])\n+def test_heuristic_decode_config_keeps_deterministic_queries_off_micro(\n+ deterministic_output,\n+):\n+ from b12x.preparation import FrozenMapping, DeviceIdentity\n+ from b12x.moe.fused_moe._tuning import MoeDecodeQuery\n+ from flashinfer.experimental.b12x.moe.fused_moe._impl import (\n+ _heuristic_moe_decode_config,\n+ )\n+\n+ query = MoeDecodeQuery(\n+ quant_mode=\"w4a8_mx\",\n+ quant_modes=(\"w4a8_mx\",),\n+ source_format=\"fp4_e8m0_k32\",\n+ activation=\"silu\",\n+ io_dtype=\"bfloat16\",\n+ num_experts=384,\n+ hidden_size=5120,\n+ intermediate_size=2304,\n+ top_k=6,\n+ num_tokens=1,\n+ routed_rows=6,\n+ route_num_experts=384,\n+ route_logits_dtype=\"float32\",\n+ apply_router_weight_on_input=False,\n+ collect_activation_amax=False,\n+ deterministic_output=deterministic_output,\n+ swiglu_limit=10.0,\n+ swiglu_alpha=1.702,\n+ swiglu_beta=1.0,\n+ w13_layout=\"w31\",\n+ weight_layouts=(\"w31\",),\n+ w4a16_weight_layout=None,\n+ w4a16_scale_format=None,\n+ w4a16_block_size_m=None,\n+ fast_math=True,\n+ numerical_recipe=None,\n+ controls=FrozenMapping(),\n+ )\n+ device = DeviceIdentity(\n+ vendor=\"nvidia\",\n+ compute_capability=(12, 0),\n+ sm_count=170,\n+ product_name=\"NVIDIA GeForce RTX 5090\",\n+ )\n+ config = _heuristic_moe_decode_config(query, device)\n+ if deterministic_output:\n+ assert config.backend == \"dynamic\"\n+ assert config.dynamic_route_mode == \"grouped\"\n+ else:\n+ assert config.backend == \"micro\"\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: Fix 24486: TP: allows the usage of 4-10 gpus for stepfun and laguna\nLabels: merge ready\nFiles changed (1): src/llama-model.cpp\n\n## Description (results removed)\n\n## Overview\n\nThis fixes https://github.com/ggml-org/llama.cpp/issues/24486 and allows the usage of 4-10 and probably more gpu's. I cannot test with <4 because of too little vram.\n\n## Requirements\n\n- AI usage disclosure: Yes I used llama.cpp and qwen3.5 122b as an advanced grep tool for discovering the codebase all code comes from me (as little as there is).\n\n## Diff\n\n```diff\ndiff --git a/src/llama-model.cpp b/src/llama-model.cpp\nindex 803a8329e9db..4e0ed9705a9f 100644\n--- a/src/llama-model.cpp\n+++ b/src/llama-model.cpp\n@@ -849,6 +849,13 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str\n return {blck_size_perf};\n }\n \n+ if (ud->model->arch == LLM_ARCH_STEP35 || ud->model->arch == LLM_ARCH_LAGUNA) {\n+ GGML_ASSERT(segments.size() == 1);\n+ if (std::regex_match(tensor_name, pattern_attn_gate_weight)) {\n+ return {hparams.n_head(il) / hparams.n_head_kv(il)};\n+ }\n+ }\n+\n // everything else\n GGML_ASSERT(segments.size() == 1);\n return {1};\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: server : fix usage.completion_tokens undercount with n > 1\nLabels: server\nFiles changed (2): tools/server/server-context.cpp, tools/server/tests/unit/test_chat_completion.py\n\n## Description (results removed)\n\n## Overview\n\nFix incorrect usage reporting for OpenAI requests with `n > 1`.\n\nFixes #29451.\n\nWhen multiple choices are requested, the server only keeps the usage from the first result. This causes `completion_tokens` and `total_tokens` to be undercounted.\n\nSum `completion_tokens` across all choices and recalculate `total_tokens`, while counting `prompt_tokens` once.\n\nThe issue can be reproduced with the script provided in #29451. With `n=4`, for example, four completions are returned but `completion_tokens` only reports the tokens from one choice.\n\n## Requirements\n\n* I have read and agree with the [[contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md)](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md)\n\n* AI usage disclosure: YES — AI was used to help review the code and run the test.\n\n## Diff\n\n```diff\ndiff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp\nindex e95fb63ab3cc..b4f1c7e57642 100644\n--- a/tools/server/server-context.cpp\n+++ b/tools/server/server-context.cpp\n@@ -4367,10 +4367,20 @@ std::unique_ptr server_routes::handle_completions_impl(\n res->ok(arr[0]);\n } else if (res_type == TASK_RESPONSE_TYPE_OAI_CHAT || res_type == TASK_RESPONSE_TYPE_OAI_CMPL) {\n // if multiple results in OAI format, we need to re-format them\n+ json & usage = arr[0][\"usage\"];\n json & choices = arr[0][\"choices\"];\n for (size_t i = 1; i < arr.size(); i++) {\n choices.push_back(std::move(arr[i][\"choices\"][0]));\n }\n+\n+ // OAI counts generated tokens across all choices\n+ int64_t n_completion_tokens = 0;\n+ for (auto & item : arr) {\n+ n_completion_tokens += item[\"usage\"][\"completion_tokens\"].get();\n+ }\n+ usage[\"completion_tokens\"] = n_completion_tokens;\n+ usage[\"total_tokens\"] = usage[\"prompt_tokens\"].get() + n_completion_tokens;\n+\n res->ok(arr[0]);\n } else {\n // multi-results, non-OAI compat\ndiff --git a/tools/server/tests/unit/test_chat_completion.py b/tools/server/tests/unit/test_chat_completion.py\nindex 0258b539ed87..afbcef030664 100644\n--- a/tools/server/tests/unit/test_chat_completion.py\n+++ b/tools/server/tests/unit/test_chat_completion.py\n@@ -587,6 +587,10 @@ def test_chat_completions_multiple_choices():\n for choice in res.body[\"choices\"]:\n assert \"assistant\" == choice[\"message\"][\"role\"]\n assert choice[\"finish_reason\"] == \"length\"\n+ # each choice generates max_tokens tokens, usage counts them all\n+ # ref: https://github.com/ggml-org/llama.cpp/issues/29451\n+ assert res.body[\"usage\"][\"completion_tokens\"] == 16\n+ assert res.body[\"usage\"][\"total_tokens\"] == res.body[\"usage\"][\"prompt_tokens\"] + 16\n \n \n def test_chat_completions_token_count():\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: sycl: fix prompt-processing regression after Q4_0/Q8_0 weight reorder\nLabels: ggml, merge ready, SYCL\nFiles changed (2): ggml/src/ggml-sycl/convert.cpp, ggml/src/ggml-sycl/dequantize.hpp\n\n## Description (results removed)\n\n## Overview\n\nThis PR fixes a prompt-processing slowdown on Q4_0 and Q8_0 models that starts after the first decode and persists for the rest of the session, so every multi-turn chat runs at the slow rate.\n\nThe kernels now use the same per-element mapping as `dequantize_block` / `dequantize_block` for the plain layout (one work-item per packed byte for Q4_0, two values per work-item for Q8_0) in 256-wide work-groups, so reads and writes are contiguous across a sub-group. They launch with `ceil_div` + `downsample_sycl_global_range` like `convert_unary_nc_sycl`, and loop over the global range so a shrunken work-group still covers every element.\n\nThe fp32 GEMM fallback now asserts that a reordered `src0` is converted with its full row range, since the reorder kernels locate the scales from the element count. The fp16 path already had this check.\n\nRepro with: `llama-bench -m -ngl 99 -fa 1 -ctk q8_0 -ctv q8_0 -ub 1024 -p 512 -n 32 -d 0,1`\n\nArc Pro B50 (Battlemage), Qwen3.5-9B Q4_0:\n\n[table with results removed]\n\nArc Pro B50, Qwen3.5-2B Q8_0:\n\n[table with results removed]\n\n### Correctness\n[results removed]\n## Requirements\n\n- I have read and agree with the [contributing guidelines](htta.cpp/blob/master/CONTRIBUTING.md)\n- AI usage disclosure: Yes: coded and debugged with the assistlaude Fable 5.1\n\n## Diff\n\n```diff\ndiff --git a/ggml/src/ggml-sycl/convert.cpp b/ggml/src/ggml-sycl/convert.cpp\nindex 67dfeb9f943e..8ba26d3a9f23 100644\n--- a/ggml/src/ggml-sycl/convert.cpp\n+++ b/ggml/src/ggml-sycl/convert.cpp\n@@ -158,16 +158,16 @@ static void dequantize_row_q4_0_sycl_reorder(const void *vx, dst_t *y, const int\n dpct::has_capability_or_fail(stream->get_device(),\n {sycl::aspect::fp16});\n \n- int constexpr WARP_K = WARP_SIZE * QK4_0;\n- const int n_warp = (k + WARP_K - 1) / WARP_K;\n- GGML_ASSERT(k % 2 == 0);\n- stream->parallel_for(sycl::nd_range<3>(sycl::range<3>(1, 1, n_warp) *\n- sycl::range<3>(1, 1, WARP_SIZE),\n- sycl::range<3>(1, 1, WARP_SIZE)),\n- [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(WARP_SIZE)]]{\n+ GGML_ASSERT(k % QK4_0 == 0);\n+ const int64_t n_groups = ceil_div(k / 2, SYCL_DEQUANTIZE_BLOCK_SIZE);\n+ // decrease global range when it exceeds the max int; the kernel loops to cover the rest\n+ const int64_t wg_size = downsample_sycl_global_range(n_groups, SYCL_DEQUANTIZE_BLOCK_SIZE);\n+ stream->parallel_for(sycl::nd_range<3>(sycl::range<3>(1, 1, n_groups) *\n+ sycl::range<3>(1, 1, wg_size),\n+ sycl::range<3>(1, 1, wg_size)),\n+ [=](sycl::nd_item<3> item_ct1) {\n dequantize_block_q4_0_reorder(vx, y, k, item_ct1);\n });\n-\n }\n \n template \n@@ -177,16 +177,16 @@ static void dequantize_row_q8_0_sycl_reorder(const void *vx, dst_t *y, const int\n dpct::has_capability_or_fail(stream->get_device(),\n {sycl::aspect::fp16});\n \n- int constexpr WARP_K = WARP_SIZE * QK8_0;\n- const int n_warp = (k + WARP_K - 1) / WARP_K;\n GGML_ASSERT(k % QK8_0 == 0);\n- stream->parallel_for(sycl::nd_range<3>(sycl::range<3>(1, 1, n_warp) *\n- sycl::range<3>(1, 1, WARP_SIZE),\n- sycl::range<3>(1, 1, WARP_SIZE)),\n- [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(WARP_SIZE)]]{\n+ const int64_t n_groups = ceil_div(k / 2, SYCL_DEQUANTIZE_BLOCK_SIZE);\n+ // decrease global range when it exceeds the max int; the kernel loops to cover the rest\n+ const int64_t wg_size = downsample_sycl_global_range(n_groups, SYCL_DEQUANTIZE_BLOCK_SIZE);\n+ stream->parallel_for(sycl::nd_range<3>(sycl::range<3>(1, 1, n_groups) *\n+ sycl::range<3>(1, 1, wg_size),\n+ sycl::range<3>(1, 1, wg_size)),\n+ [=](sycl::nd_item<3> item_ct1) {\n dequantize_block_q8_0_reorder(vx, y, k, item_ct1);\n });\n-\n }\n \n template \ndiff --git a/ggml/src/ggml-sycl/dequantize.hpp b/ggml/src/ggml-sycl/dequantize.hpp\nindex 14529a26beb3..48ee651ad68c 100644\n--- a/ggml/src/ggml-sycl/dequantize.hpp\n+++ b/ggml/src/ggml-sycl/dequantize.hpp\n@@ -818,61 +818,43 @@ static void dequantize_block_q4_0(const void * __restrict__ vx, dst_t * __restri\n }\n \n template\n-static void dequantize_block_q4_0_reorder(const void * __restrict__ vx, dst_t * __restrict__ yy, int64_t nb32,\n+static void dequantize_block_q4_0_reorder(const void * __restrict__ vx, dst_t * __restrict__ yy, int64_t k,\n const sycl::nd_item<3> &item_ct1) {\n-\n- const int64_t i = item_ct1.get_group(2);\n- auto k=nb32;\n- // assume 32 threads\n- const int64_t tid = item_ct1.get_local_id(2);\n- const int lane_ib = i * WARP_SIZE + tid;\n-\n- if (lane_ib >= k / QK4_0) {\n- return;\n+ // one thread per qs byte, like dequantize_block; the reorder layout makes the byte reads contiguous\n+ // grid-stride loop because the launcher may shrink the work-group to keep the global range below INT_MAX\n+ // float math, not dequantize_q4_0_reorder: that helper computes in half with GGML_SYCL_F16, which changes f32 output\n+ const sycl::half * d_ptr = (const sycl::half *) ((const uint8_t *) vx + k/2);\n+ const int64_t stride = item_ct1.get_local_range(2) * item_ct1.get_group_range(2);\n+\n+ for (int64_t iq = item_ct1.get_global_id(2); iq < k/2; iq += stride) {\n+ const int64_t ib = iq / (QK4_0/2);\n+ const int64_t iqs = iq % (QK4_0/2);\n+ const int vq = ((const uint8_t *) vx)[iq];\n+ const float d = float(d_ptr[ib]);\n+\n+ dst_t * y = yy + ib*QK4_0 + iqs;\n+ y[0] = d * ((vq & 0xF) - 8);\n+ y[QK4_0/2] = d * ((vq >> 4) - 8);\n }\n-\n- dst_t * y_ptr = yy + lane_ib * QK4_0;\n-\n- auto qs = (const uint8_t*)vx + lane_ib * QK4_0 / 2;\n- auto s_ptr = (const sycl::half*)((const uint8_t*)vx + k / 2) + lane_ib;\n-\n- const float d = float(*s_ptr);\n-\n-#pragma unroll\n- for (int l = 0; l < QK4_0 / 2; ++l) {\n- int vq = qs[l];\n- y_ptr[l + 0] = d * ((vq & 0xF) - 8);\n- y_ptr[l + 16] = d * ((vq >> 4) - 8);\n- }\n-\n }\n \n // Dequantize Q8_0 from reorder layout: [all qs (k bytes)][all d values]\n-// Each thread handles one block of QK8_0 elements.\n template\n static void dequantize_block_q8_0_reorder(const void * __restrict__ vx, dst_t * __restrict__ yy, int64_t k,\n const sycl::nd_item<3> &item_ct1) {\n-\n- const int64_t i = item_ct1.get_group(2);\n- const int64_t tid = item_ct1.get_local_id(2);\n- const int lane_ib = i * WARP_SIZE + tid;\n-\n- if (lane_ib >= k / QK8_0) {\n- return;\n- }\n-\n- dst_t * y_ptr = yy + lane_ib * QK8_0;\n-\n- auto qs = (const int8_t*)vx + lane_ib * QK8_0;\n- auto s_ptr = (const sycl::half*)((const uint8_t*)vx + k) + lane_ib;\n-\n- const float d = float(*s_ptr);\n-\n-#pragma unroll\n- for (int l = 0; l < QK8_0; ++l) {\n- y_ptr[l] = d * qs[l];\n+ // two values per thread, like dequantize_block; the reorder layout keeps all qs contiguous\n+ // grid-stride loop because the launcher may shrink the work-group to keep the global range below INT_MAX\n+ // float math, not dequantize_q8_0_reorder: that helper computes in half with GGML_SYCL_F16, which changes f32 output\n+ const int8_t * qs = (const int8_t *) vx;\n+ const sycl::half * d_ptr = (const sycl::half *) ((const uint8_t *) vx + k);\n+ const int64_t stride = 2 * item_ct1.get_local_range(2) * item_ct1.get_group_range(2);\n+\n+ for (int64_t i = 2 * item_ct1.get_global_id(2); i < k; i += stride) {\n+ const float d = float(d_ptr[i / QK8_0]);\n+\n+ yy[i + 0] = d * qs[i + 0];\n+ yy[i + 1] = d * qs[i + 1];\n }\n-\n }\n \n template\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: llama-quant : fix 4D tensor quantization using ggml_nrows() and name-based expert detection\nLabels: testing, merge ready\nFiles changed (2): src/llama-quant.cpp, tests/snapshots/deepseek-v3.1.schema\n\n## Description (results removed)\n\n## Overview\n\nFix quantization of 4D tensors by using `ggml_nrows()` to count rows, and detect expert tensors by name instead of by shape.\n\nFixes #29916 in https://github.com/ggml-org/llama.cpp/commit/64d1bbb254298a6714c3302b54526082c71c04f7. The row count was computed from `ne[1]` and `ne[2]` only, ignoring `ne[3]`. For tensors like `a.conv1d.0.weight [3, 3, 1, 128]` this produces the wrong size and trips the `gguf_get_tensor_size(...) == new_size` assert. `ggml_nrows()` is now used instead. Other places in `src/llama-quant.cpp` that ignored `ne[3]` are fixed as well.\n\n[details with results removed]\n\n[details with results removed]\n\nOn top of that, we previously used `tensor->ne[2] > 1` to detect expert tensors, but that did not cover all cases and required some hard-coded exclusions for the bailingmoe3 model. Expert tensors are now identified by `_exps.` or `_chexps.` in their name. This new implementation does not break existing models, and it even caught an edge case where the attention weights for deepseek-v3.1 were wrongly treated as expert tensors when they should be quantized as `Q8_0` instead. The test schema has also been updated.\n\n## Requirements\n\n- AI usage disclosure: YES. AI was used for solution exploration and code generation. Every line of generated code has been reviewed by me.\n\n## Log files\n- [reproduced.log](https://github.com/user-attachments/files/33674908/reproduced.log)\n- [after-fix.log](https://github.com/user-attachments/files/33674906/after-fix.log)\n\n## Diff\n\n```diff\ndiff --git a/src/llama-quant.cpp b/src/llama-quant.cpp\nindex b8f96bcef30f..a879701d4e97 100644\n--- a/src/llama-quant.cpp\n+++ b/src/llama-quant.cpp\n@@ -161,6 +161,12 @@ static tensor_category tensor_get_category(const std::string & tensor_name) {\n return tensor_category::OTHER;\n }\n \n+// check if tensor is a MoE expert tensor (used by GGML_OP_MUL_MAT_ID)\n+static bool tensor_is_expert(const std::string & tensor_name) {\n+ return tensor_name.find(\"_exps.\") != std::string::npos ||\n+ tensor_name.find(\"_chexps.\") != std::string::npos;\n+}\n+\n // check if category is for attention-v-like tensors (more sensitive to quantization)\n static bool category_is_attn_v(tensor_category cat) {\n return cat == tensor_category::ATTENTION_V ||\n@@ -296,7 +302,7 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param\n // trivial checks first -- no string ops needed\n if (params->only_copy) return false;\n \n- // quantize only 2D and 3D tensors (experts)\n+ // quantize only 2D+ tensors (matrices, experts, conv kernels)\n if (ggml_n_dims(tensor) < 2) return false;\n \n const std::string name = ggml_get_name(tensor);\n@@ -538,12 +544,7 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type\n } else if (ftype == LLAMA_FTYPE_MOSTLY_MXFP4_MOE) {\n // MoE tensors -> MXFP4\n // other tensors -> Q8_0\n- // MLA projection tensors are also 3D, so match expert tensor roles explicitly.\n- const bool is_bailingmoe3_expert = arch == LLM_ARCH_BAILINGMOE3 &&\n- (category == tensor_category::FFN_UP ||\n- category == tensor_category::FFN_GATE ||\n- category == tensor_category::FFN_DOWN);\n- if (tensor->ne[2] > 1 && (arch != LLM_ARCH_BAILINGMOE3 || is_bailingmoe3_expert)) {\n+ if (tensor_is_expert(name)) {\n new_type = GGML_TYPE_MXFP4;\n } else {\n new_type = GGML_TYPE_Q8_0;\n@@ -1304,11 +1305,11 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::\n if (it == imatrix_data->end()) {\n LLAMA_LOG_INFO(\"\\n====== %s: did not find weights for %s\\n\", __func__, tensor->name);\n } else {\n- if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {\n+ if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]*tensor->ne[3]) {\n imatrix = it->second.data();\n } else {\n LLAMA_LOG_INFO(\"\\n====== %s: imatrix size %d is different from tensor size %d for %s\\n\", __func__,\n- int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);\n+ int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name);\n \n // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix\n // this is a significant error and it may be good idea to abort the process if this happens,\n@@ -1316,7 +1317,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::\n // tok_embd should be ignored in this case, since it always causes this warning\n if (!tensor_name_match_token_embd(tensor->name)) {\n throw std::runtime_error(format(\"imatrix size %d is different from tensor size %d for %s\",\n- int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));\n+ int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name));\n }\n }\n }\n@@ -1338,7 +1339,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::\n \n const int64_t n_per_row = tensor->ne[0];\n const int64_t nrows_per_expert = tensor->ne[1];\n- const int64_t nrows_total = tensor->ne[1] * tensor->ne[2];\n+ const int64_t nrows_total = ggml_nrows(tensor);\n \n const size_t row_size_src = ggml_row_size(tensor->type, n_per_row);\n const size_t row_size_dst = ggml_row_size(new_type, n_per_row);\ndiff --git a/tests/snapshots/deepseek-v3.1.schema b/tests/snapshots/deepseek-v3.1.schema\nindex 0e9dfd6ed4a7..117a76833f4f 100644\n--- a/tests/snapshots/deepseek-v3.1.schema\n+++ b/tests/snapshots/deepseek-v3.1.schema\n@@ -2927,430 +2927,552 @@ blk.60.attn_k_b.weight q4_0\n [MXFP4_MOE] mxfp4\n output.weight q8_0\n token_embd.weight q8_0\n+blk.0.attn_k_b.weight q8_0\n blk.0.attn_kv_a_mqa.weight q8_0\n blk.0.attn_output.weight q8_0\n blk.0.attn_q_a.weight q8_0\n blk.0.attn_q_b.weight q8_0\n+blk.0.attn_v_b.weight q8_0\n blk.0.ffn_down.weight q8_0\n blk.0.ffn_gate.weight q8_0\n blk.0.ffn_up.weight q8_0\n+blk.1.attn_k_b.weight q8_0\n blk.1.attn_kv_a_mqa.weight q8_0\n blk.1.attn_output.weight q8_0\n blk.1.attn_q_a.weight q8_0\n blk.1.attn_q_b.weight q8_0\n+blk.1.attn_v_b.weight q8_0\n blk.1.ffn_down.weight q8_0\n blk.1.ffn_gate.weight q8_0\n blk.1.ffn_up.weight q8_0\n+blk.2.attn_k_b.weight q8_0\n blk.2.attn_kv_a_mqa.weight q8_0\n blk.2.attn_output.weight q8_0\n blk.2.attn_q_a.weight q8_0\n blk.2.attn_q_b.weight q8_0\n+blk.2.attn_v_b.weight q8_0\n blk.2.ffn_down.weight q8_0\n blk.2.ffn_gate.weight q8_0\n blk.2.ffn_up.weight q8_0\n+blk.3.attn_k_b.weight q8_0\n blk.3.attn_kv_a_mqa.weight q8_0\n blk.3.attn_output.weight q8_0\n blk.3.attn_q_a.weight q8_0\n blk.3.attn_q_b.weight q8_0\n+blk.3.attn_v_b.weight q8_0\n blk.3.ffn_down_shexp.weight q8_0\n blk.3.ffn_gate_shexp.weight q8_0\n blk.3.ffn_up_shexp.weight q8_0\n+blk.4.attn_k_b.weight q8_0\n blk.4.attn_kv_a_mqa.weight q8_0\n blk.4.attn_output.weight q8_0\n blk.4.attn_q_a.weight q8_0\n blk.4.attn_q_b.weight q8_0\n+blk.4.attn_v_b.weight q8_0\n blk.4.ffn_down_shexp.weight q8_0\n blk.4.ffn_gate_shexp.weight q8_0\n blk.4.ffn_up_shexp.weight q8_0\n+blk.5.attn_k_b.weight q8_0\n blk.5.attn_kv_a_mqa.weight q8_0\n blk.5.attn_output.weight q8_0\n blk.5.attn_q_a.weight q8_0\n blk.5.attn_q_b.weight q8_0\n+blk.5.attn_v_b.weight q8_0\n blk.5.ffn_down_shexp.weight q8_0\n blk.5.ffn_gate_shexp.weight q8_0\n blk.5.ffn_up_shexp.weight q8_0\n+blk.6.attn_k_b.weight q8_0\n blk.6.attn_kv_a_mqa.weight q8_0\n blk.6.attn_output.weight q8_0\n blk.6.attn_q_a.weight q8_0\n blk.6.attn_q_b.weight q8_0\n+blk.6.attn_v_b.weight q8_0\n blk.6.ffn_down_shexp.weight q8_0\n blk.6.ffn_gate_shexp.weight q8_0\n blk.6.ffn_up_shexp.weight q8_0\n+blk.7.attn_k_b.weight q8_0\n blk.7.attn_kv_a_mqa.weight q8_0\n blk.7.attn_output.weight q8_0\n blk.7.attn_q_a.weight q8_0\n blk.7.attn_q_b.weight q8_0\n+blk.7.attn_v_b.weight q8_0\n blk.7.ffn_down_shexp.weight q8_0\n blk.7.ffn_gate_shexp.weight q8_0\n blk.7.ffn_up_shexp.weight q8_0\n+blk.8.attn_k_b.weight q8_0\n blk.8.attn_kv_a_mqa.weight q8_0\n blk.8.attn_output.weight q8_0\n blk.8.attn_q_a.weight q8_0\n blk.8.attn_q_b.weight q8_0\n+blk.8.attn_v_b.weight q8_0\n blk.8.ffn_down_shexp.weight q8_0\n blk.8.ffn_gate_shexp.weight q8_0\n blk.8.ffn_up_shexp.weight q8_0\n+blk.9.attn_k_b.weight q8_0\n blk.9.attn_kv_a_mqa.weight q8_0\n blk.9.attn_output.weight q8_0\n blk.9.attn_q_a.weight q8_0\n blk.9.attn_q_b.weight q8_0\n+blk.9.attn_v_b.weight q8_0\n blk.9.ffn_down_shexp.weight q8_0\n blk.9.ffn_gate_shexp.weight q8_0\n blk.9.ffn_up_shexp.weight q8_0\n+blk.10.attn_k_b.weight q8_0\n blk.10.attn_kv_a_mqa.weight q8_0\n blk.10.attn_output.weight q8_0\n blk.10.attn_q_a.weight q8_0\n blk.10.attn_q_b.weight q8_0\n+blk.10.attn_v_b.weight q8_0\n blk.10.ffn_down_shexp.weight q8_0\n blk.10.ffn_gate_shexp.weight q8_0\n blk.10.ffn_up_shexp.weight q8_0\n+blk.11.attn_k_b.weight q8_0\n blk.11.attn_kv_a_mqa.weight q8_0\n blk.11.attn_output.weight q8_0\n blk.11.attn_q_a.weight q8_0\n blk.11.attn_q_b.weight q8_0\n+blk.11.attn_v_b.weight q8_0\n blk.11.ffn_down_shexp.weight q8_0\n blk.11.ffn_gate_shexp.weight q8_0\n blk.11.ffn_up_shexp.weight q8_0\n+blk.12.attn_k_b.weight q8_0\n blk.12.attn_kv_a_mqa.weight q8_0\n blk.12.attn_output.weight q8_0\n blk.12.attn_q_a.weight q8_0\n blk.12.attn_q_b.weight q8_0\n+blk.12.attn_v_b.weight q8_0\n blk.12.ffn_down_shexp.weight q8_0\n blk.12.ffn_gate_shexp.weight q8_0\n blk.12.ffn_up_shexp.weight q8_0\n+blk.13.attn_k_b.weight q8_0\n blk.13.attn_kv_a_mqa.weight q8_0\n blk.13.attn_output.weight q8_0\n blk.13.attn_q_a.weight q8_0\n blk.13.attn_q_b.weight q8_0\n+blk.13.attn_v_b.weight q8_0\n blk.13.ffn_down_shexp.weight q8_0\n blk.13.ffn_gate_shexp.weight q8_0\n blk.13.ffn_up_shexp.weight q8_0\n+blk.14.attn_k_b.weight q8_0\n blk.14.attn_kv_a_mqa.weight q8_0\n blk.14.attn_output.weight q8_0\n blk.14.attn_q_a.weight q8_0\n blk.14.attn_q_b.weight q8_0\n+blk.14.attn_v_b.weight q8_0\n blk.14.ffn_down_shexp.weight q8_0\n blk.14.ffn_gate_shexp.weight q8_0\n blk.14.ffn_up_shexp.weight q8_0\n+blk.15.attn_k_b.weight q8_0\n blk.15.attn_kv_a_mqa.weight q8_0\n blk.15.attn_output.weight q8_0\n blk.15.attn_q_a.weight q8_0\n blk.15.attn_q_b.weight q8_0\n+blk.15.attn_v_b.weight q8_0\n blk.15.ffn_down_shexp.weight q8_0\n blk.15.ffn_gate_shexp.weight q8_0\n blk.15.ffn_up_shexp.weight q8_0\n+blk.16.attn_k_b.weight q8_0\n blk.16.attn_kv_a_mqa.weight q8_0\n blk.16.attn_output.weight q8_0\n blk.16.attn_q_a.weight q8_0\n blk.16.attn_q_b.weight q8_0\n+blk.16.attn_v_b.weight q8_0\n blk.16.ffn_down_shexp.weight q8_0\n blk.16.ffn_gate_shexp.weight q8_0\n blk.16.ffn_up_shexp.weight q8_0\n+blk.17.attn_k_b.weight q8_0\n blk.17.attn_kv_a_mqa.weight q8_0\n blk.17.attn_output.weight q8_0\n blk.17.attn_q_a.weight q8_0\n blk.17.attn_q_b.weight q8_0\n+blk.17.attn_v_b.weight q8_0\n blk.17.ffn_down_shexp.weight q8_0\n blk.17.ffn_gate_shexp.weight q8_0\n blk.17.ffn_up_shexp.weight q8_0\n+blk.18.attn_k_b.weight q8_0\n blk.18.attn_kv_a_mqa.weight q8_0\n blk.18.attn_output.weight q8_0\n blk.18.attn_q_a.weight q8_0\n blk.18.attn_q_b.weight q8_0\n+blk.18.attn_v_b.weight q8_0\n blk.18.ffn_down_shexp.weight q8_0\n blk.18.ffn_gate_shexp.weight q8_0\n blk.18.ffn_up_shexp.weight q8_0\n+blk.19.attn_k_b.weight q8_0\n blk.19.attn_kv_a_mqa.weight q8_0\n blk.19.attn_output.weight q8_0\n blk.19.attn_q_a.weight q8_0\n blk.19.attn_q_b.weight q8_0\n+blk.19.attn_v_b.weight q8_0\n blk.19.ffn_down_shexp.weight q8_0\n blk.19.ffn_gate_shexp.weight q8_0\n blk.19.ffn_up_shexp.weight q8_0\n+blk.20.attn_k_b.weight q8_0\n blk.20.attn_kv_a_mqa.weight q8_0\n blk.20.attn_output.weight q8_0\n blk.20.attn_q_a.weight q8_0\n blk.20.attn_q_b.weight q8_0\n+blk.20.attn_v_b.weight q8_0\n blk.20.ffn_down_shexp.weight q8_0\n blk.20.ffn_gate_shexp.weight q8_0\n blk.20.ffn_up_shexp.weight q8_0\n+blk.21.attn_k_b.weight q8_0\n blk.21.attn_kv_a_mqa.weight q8_0\n blk.21.attn_output.weight q8_0\n blk.21.attn_q_a.weight q8_0\n blk.21.attn_q_b.weight q8_0\n+blk.21.attn_v_b.weight q8_0\n blk.21.ffn_down_shexp.weight q8_0\n blk.21.ffn_gate_shexp.weight q8_0\n blk.21.ffn_up_shexp.weight q8_0\n+blk.22.attn_k_b.weight q8_0\n blk.22.attn_kv_a_mqa.weight q8_0\n blk.22.attn_output.weight q8_0\n blk.22.attn_q_a.weight q8_0\n blk.22.attn_q_b.weight q8_0\n+blk.22.attn_v_b.weight q8_0\n blk.22.ffn_down_shexp.weight q8_0\n blk.22.ffn_gate_shexp.weight q8_0\n blk.22.ffn_up_shexp.weight q8_0\n+blk.23.attn_k_b.weight q8_0\n blk.23.attn_kv_a_mqa.weight q8_0\n blk.23.attn_output.weight q8_0\n blk.23.attn_q_a.weight q8_0\n blk.23.attn_q_b.weight q8_0\n+blk.23.attn_v_b.weight q8_0\n blk.23.ffn_down_shexp.weight q8_0\n blk.23.ffn_gate_shexp.weight q8_0\n blk.23.ffn_up_shexp.weight q8_0\n+blk.24.attn_k_b.weight q8_0\n blk.24.attn_kv_a_mqa.weight q8_0\n blk.24.attn_output.weight q8_0\n blk.24.attn_q_a.weight q8_0\n blk.24.attn_q_b.weight q8_0\n+blk.24.attn_v_b.weight q8_0\n blk.24.ffn_down_shexp.weight q8_0\n blk.24.ffn_gate_shexp.weight q8_0\n blk.24.ffn_up_shexp.weight q8_0\n+blk.25.attn_k_b.weight q8_0\n blk.25.attn_kv_a_mqa.weight q8_0\n blk.25.attn_output.weight q8_0\n blk.25.attn_q_a.weight q8_0\n blk.25.attn_q_b.weight q8_0\n+blk.25.attn_v_b.weight q8_0\n blk.25.ffn_down_shexp.weight q8_0\n blk.25.ffn_gate_shexp.weight q8_0\n blk.25.ffn_up_shexp.weight q8_0\n+blk.26.attn_k_b.weight q8_0\n blk.26.attn_kv_a_mqa.weight q8_0\n blk.26.attn_output.weight q8_0\n blk.26.attn_q_a.weight q8_0\n blk.26.attn_q_b.weight q8_0\n+blk.26.attn_v_b.weight q8_0\n blk.26.ffn_down_shexp.weight q8_0\n blk.26.ffn_gate_shexp.weight q8_0\n blk.26.ffn_up_shexp.weight q8_0\n+blk.27.attn_k_b.weight q8_0\n blk.27.attn_kv_a_mqa.weight q8_0\n blk.27.attn_output.weight q8_0\n blk.27.attn_q_a.weight q8_0\n blk.27.attn_q_b.weight q8_0\n+blk.27.attn_v_b.weight q8_0\n blk.27.ffn_down_shexp.weight q8_0\n blk.27.ffn_gate_shexp.weight q8_0\n blk.27.ffn_up_shexp.weight q8_0\n+blk.28.attn_k_b.weight q8_0\n blk.28.attn_kv_a_mqa.weight q8_0\n blk.28.attn_output.weight q8_0\n blk.28.attn_q_a.weight q8_0\n blk.28.attn_q_b.weight q8_0\n+blk.28.attn_v_b.weight q8_0\n blk.28.ffn_down_shexp.weight q8_0\n blk.28.ffn_gate_shexp.weight q8_0\n blk.28.ffn_up_shexp.weight q8_0\n+blk.29.attn_k_b.weight q8_0\n blk.29.attn_kv_a_mqa.weight q8_0\n blk.29.attn_output.weight q8_0\n blk.29.attn_q_a.weight q8_0\n blk.29.attn_q_b.weight q8_0\n+blk.29.attn_v_b.weight q8_0\n blk.29.ffn_down_shexp.weight q8_0\n blk.29.ffn_gate_shexp.weight q8_0\n blk.29.ffn_up_shexp.weight q8_0\n+blk.30.attn_k_b.weight q8_0\n blk.30.attn_kv_a_mqa.weight q8_0\n blk.30.attn_output.weight q8_0\n blk.30.attn_q_a.weight q8_0\n blk.30.attn_q_b.weight q8_0\n+blk.30.attn_v_b.weight q8_0\n blk.30.ffn_down_shexp.weight q8_0\n blk.30.ffn_gate_shexp.weight q8_0\n blk.30.ffn_up_shexp.weight q8_0\n+blk.31.attn_k_b.weight q8_0\n blk.31.attn_kv_a_mqa.weight q8_0\n blk.31.attn_output.weight q8_0\n blk.31.attn_q_a.weight q8_0\n blk.31.attn_q_b.weight q8_0\n+blk.31.attn_v_b.weight q8_0\n blk.31.ffn_down_shexp.weight q8_0\n blk.31.ffn_gate_shexp.weight q8_0\n blk.31.ffn_up_shexp.weight q8_0\n+blk.32.attn_k_b.weight q8_0\n blk.32.attn_kv_a_mqa.weight q8_0\n blk.32.attn_output.weight q8_0\n blk.32.attn_q_a.weight q8_0\n blk.32.attn_q_b.weight q8_0\n+blk.32.attn_v_b.weight q8_0\n blk.32.ffn_down_shexp.weight q8_0\n blk.32.ffn_gate_shexp.weight q8_0\n blk.32.ffn_up_shexp.weight q8_0\n+blk.33.attn_k_b.weight q8_0\n blk.33.attn_kv_a_mqa.weight q8_0\n blk.33.attn_output.weight q8_0\n blk.33.attn_q_a.weight q8_0\n blk.33.attn_q_b.weight q8_0\n+blk.33.attn_v_b.weight q8_0\n blk.33.ffn_down_shexp.weight q8_0\n blk.33.ffn_gate_shexp.weight q8_0\n blk.33.ffn_up_shexp.weight q8_0\n+blk.34.attn_k_b.weight q8_0\n blk.34.attn_kv_a_mqa.weight q8_0\n blk.34.attn_output.weight q8_0\n blk.34.attn_q_a.weight q8_0\n blk.34.attn_q_b.weight q8_0\n+blk.34.attn_v_b.weight q8_0\n blk.34.ffn_down_shexp.weight q8_0\n blk.34.ffn_gate_shexp.weight q8_0\n blk.34.ffn_up_shexp.weight q8_0\n+blk.35.attn_k_b.weight q8_0\n blk.35.attn_kv_a_mqa.weight q8_0\n blk.35.attn_output.weight q8_0\n blk.35.attn_q_a.weight q8_0\n blk.35.attn_q_b.weight q8_0\n+blk.35.attn_v_b.weight q8_0\n blk.35.ffn_down_shexp.weight q8_0\n blk.35.ffn_gate_shexp.weight q8_0\n blk.35.ffn_up_shexp.weight q8_0\n+blk.36.attn_k_b.weight q8_0\n blk.36.attn_kv_a_mqa.weight q8_0\n blk.36.attn_output.weight q8_0\n blk.36.attn_q_a.weight q8_0\n blk.36.attn_q_b.weight q8_0\n+blk.36.attn_v_b.weight q8_0\n blk.36.ffn_down_shexp.weight q8_0\n blk.36.ffn_gate_shexp.weight q8_0\n blk.36.ffn_up_shexp.weight q8_0\n+blk.37.attn_k_b.weight q8_0\n blk.37.attn_kv_a_mqa.weight q8_0\n blk.37.attn_output.weight q8_0\n blk.37.attn_q_a.weight q8_0\n blk.37.attn_q_b.weight q8_0\n+blk.37.attn_v_b.weight q8_0\n blk.37.ffn_down_shexp.weight q8_0\n blk.37.ffn_gate_shexp.weight q8_0\n blk.37.ffn_up_shexp.weight q8_0\n+blk.38.attn_k_b.weight q8_0\n blk.38.attn_kv_a_mqa.weight q8_0\n blk.38.attn_output.weight q8_0\n blk.38.attn_q_a.weight q8_0\n blk.38.attn_q_b.weight q8_0\n+blk.38.attn_v_b.weight q8_0\n blk.38.ffn_down_shexp.weight q8_0\n blk.38.ffn_gate_shexp.weight q8_0\n blk.38.ffn_up_shexp.weight q8_0\n+blk.39.attn_k_b.weight q8_0\n blk.39.attn_kv_a_mqa.weight q8_0\n blk.39.attn_output.weight q8_0\n blk.39.attn_q_a.weight q8_0\n blk.39.attn_q_b.weight q8_0\n+blk.39.attn_v_b.weight q8_0\n blk.39.ffn_down_shexp.weight q8_0\n blk.39.ffn_gate_shexp.weight q8_0\n blk.39.ffn_up_shexp.weight q8_0\n+blk.40.attn_k_b.weight q8_0\n blk.40.attn_kv_a_mqa.weight q8_0\n blk.40.attn_output.weight q8_0\n blk.40.attn_q_a.weight q8_0\n blk.40.attn_q_b.weight q8_0\n+blk.40.attn_v_b.weight q8_0\n blk.40.ffn_down_shexp.weight q8_0\n blk.40.ffn_gate_shexp.weight q8_0\n blk.40.ffn_up_shexp.weight q8_0\n+blk.41.attn_k_b.weight q8_0\n blk.41.attn_kv_a_mqa.weight q8_0\n blk.41.attn_output.weight q8_0\n blk.41.attn_q_a.weight q8_0\n blk.41.attn_q_b.weight q8_0\n+blk.41.attn_v_b.weight q8_0\n blk.41.ffn_down_shexp.weight q8_0\n blk.41.ffn_gate_shexp.weight q8_0\n blk.41.ffn_up_shexp.weight q8_0\n+blk.42.attn_k_b.weight q8_0\n blk.42.attn_kv_a_mqa.weight q8_0\n blk.42.attn_output.weight q8_0\n blk.42.attn_q_a.weight q8_0\n blk.42.attn_q_b.weight q8_0\n+blk.42.attn_v_b.weight q8_0\n blk.42.ffn_down_shexp.weight q8_0\n blk.42.ffn_gate_shexp.weight q8_0\n blk.42.ffn_up_shexp.weight q8_0\n+blk.43.attn_k_b.weight q8_0\n blk.43.attn_kv_a_mqa.weight q8_0\n blk.43.attn_output.weight q8_0\n blk.43.attn_q_a.weight q8_0\n blk.43.attn_q_b.weight q8_0\n+blk.43.attn_v_b.weight q8_0\n blk.43.ffn_down_shexp.weight q8_0\n blk.43.ffn_gate_shexp.weight q8_0\n blk.43.ffn_up_shexp.weight q8_0\n+blk.44.attn_k_b.weight q8_0\n blk.44.attn_kv_a_mqa.weight q8_0\n blk.44.attn_output.weight q8_0\n blk.44.attn_q_a.weight q8_0\n blk.44.attn_q_b.weight q8_0\n+blk.44.attn_v_b.weight q8_0\n blk.44.ffn_down_shexp.weight q8_0\n blk.44.ffn_gate_shexp.weight q8_0\n blk.44.ffn_up_shexp.weight q8_0\n+blk.45.attn_k_b.weight q8_0\n blk.45.attn_kv_a_mqa.weight q8_0\n blk.45.attn_output.weight q8_0\n blk.45.attn_q_a.weight q8_0\n blk.45.attn_q_b.weight q8_0\n+blk.45.attn_v_b.weight q8_0\n blk.45.ffn_down_shexp.weight q8_0\n blk.45.ffn_gate_shexp.weight q8_0\n blk.45.ffn_up_shexp.weight q8_0\n+blk.46.attn_k_b.weight q8_0\n blk.46.attn_kv_a_mqa.weight q8_0\n blk.46.attn_output.weight q8_0\n blk.46.attn_q_a.weight q8_0\n blk.46.attn_q_b.weight q8_0\n+blk.46.attn_v_b.weight q8_0\n blk.46.ffn_down_shexp.weight q8_0\n blk.46.ffn_gate_shexp.weight q8_0\n blk.46.ffn_up_shexp.weight q8_0\n+blk.47.attn_k_b.weight q8_0\n blk.47.attn_kv_a_mqa.weight q8_0\n blk.47.attn_output.weight q8_0\n blk.47.attn_q_a.weight q8_0\n blk.47.attn_q_b.weight q8_0\n+blk.47.attn_v_b.weight q8_0\n blk.47.ffn_down_shexp.weight q8_0\n blk.47.ffn_gate_shexp.weight q8_0\n blk.47.ffn_up_shexp.weight q8_0\n+blk.48.attn_k_b.weight q8_0\n blk.48.attn_kv_a_mqa.weight q8_0\n blk.48.attn_output.weight q8_0\n blk.48.attn_q_a.weight q8_0\n blk.48.attn_q_b.weight q8_0\n+blk.48.attn_v_b.weight q8_0\n blk.48.ffn_down_shexp.weight q8_0\n blk.48.ffn_gate_shexp.weight q8_0\n blk.48.ffn_up_shexp.weight q8_0\n+blk.49.attn_k_b.weight q8_0\n blk.49.attn_kv_a_mqa.weight q8_0\n blk.49.attn_output.weight q8_0\n blk.49.attn_q_a.weight q8_0\n blk.49.attn_q_b.weight q8_0\n+blk.49.attn_v_b.weight q8_0\n blk.49.ffn_down_shexp.weight q8_0\n blk.49.ffn_gate_shexp.weight q8_0\n blk.49.ffn_up_shexp.weight q8_0\n+blk.50.attn_k_b.weight q8_0\n blk.50.attn_kv_a_mqa.weight q8_0\n blk.50.attn_output.weight q8_0\n blk.50.attn_q_a.weight q8_0\n blk.50.attn_q_b.weight q8_0\n+blk.50.attn_v_b.weight q8_0\n blk.50.ffn_down_shexp.weight q8_0\n blk.50.ffn_gate_shexp.weight q8_0\n blk.50.ffn_up_shexp.weight q8_0\n+blk.51.attn_k_b.weight q8_0\n blk.51.attn_kv_a_mqa.weight q8_0\n blk.51.attn_output.weight q8_0\n blk.51.attn_q_a.weight q8_0\n blk.51.attn_q_b.weight q8_0\n+blk.51.attn_v_b.weight q8_0\n blk.51.ffn_down_shexp.weight q8_0\n blk.51.ffn_gate_shexp.weight q8_0\n blk.51.ffn_up_shexp.weight q8_0\n+blk.52.attn_k_b.weight q8_0\n blk.52.attn_kv_a_mqa.weight q8_0\n blk.52.attn_output.weight q8_0\n blk.52.attn_q_a.weight q8_0\n blk.52.attn_q_b.weight q8_0\n+blk.52.attn_v_b.weight q8_0\n blk.52.ffn_down_shexp.weight q8_0\n blk.52.ffn_gate_shexp.weight q8_0\n blk.52.ffn_up_shexp.weight q8_0\n+blk.53.attn_k_b.weight q8_0\n blk.53.attn_kv_a_mqa.weight q8_0\n blk.53.attn_output.weight q8_0\n blk.53.attn_q_a.weight q8_0\n blk.53.attn_q_b.weight q8_0\n+blk.53.attn_v_b.weight q8_0\n blk.53.ffn_down_shexp.weight q8_0\n blk.53.ffn_gate_shexp.weight q8_0\n blk.53.ffn_up_shexp.weight q8_0\n+blk.54.attn_k_b.weight q8_0\n blk.54.attn_kv_a_mqa.weight q8_0\n blk.54.attn_output.weight q8_0\n blk.54.attn_q_a.weight q8_0\n blk.54.attn_q_b.weight q8_0\n+blk.54.attn_v_b.weight q8_0\n blk.54.ffn_down_shexp.weight q8_0\n blk.54.ffn_gate_shexp.weight q8_0\n blk.54.ffn_up_shexp.weight q8_0\n+blk.55.attn_k_b.weight q8_0\n blk.55.attn_kv_a_mqa.weight q8_0\n blk.55.attn_output.weight q8_0\n blk.55.attn_q_a.weight q8_0\n blk.55.attn_q_b.weight q8_0\n+blk.55.attn_v_b.weight q8_0\n blk.55.ffn_down_shexp.weight q8_0\n blk.55.ffn_gate_shexp.weight q8_0\n blk.55.ffn_up_shexp.weight q8_0\n+blk.56.attn_k_b.weight q8_0\n blk.56.attn_kv_a_mqa.weight q8_0\n blk.56.attn_output.weight q8_0\n blk.56.attn_q_a.weight q8_0\n blk.56.attn_q_b.weight q8_0\n+blk.56.attn_v_b.weight q8_0\n blk.56.ffn_down_shexp.weight q8_0\n blk.56.ffn_gate_shexp.weight q8_0\n blk.56.ffn_up_shexp.weight q8_0\n+blk.57.attn_k_b.weight q8_0\n blk.57.attn_kv_a_mqa.weight q8_0\n blk.57.attn_output.weight q8_0\n blk.57.attn_q_a.weight q8_0\n blk.57.attn_q_b.weight q8_0\n+blk.57.attn_v_b.weight q8_0\n blk.57.ffn_down_shexp.weight q8_0\n blk.57.ffn_gate_shexp.weight q8_0\n blk.57.ffn_up_shexp.weight q8_0\n+blk.58.attn_k_b.weight q8_0\n blk.58.attn_kv_a_mqa.weight q8_0\n blk.58.attn_output.weight q8_0\n blk.58.attn_q_a.weight q8_0\n blk.58.attn_q_b.weight q8_0\n+blk.58.attn_v_b.weight q8_0\n blk.58.ffn_down_shexp.weight q8_0\n blk.58.ffn_gate_shexp.weight q8_0\n blk.58.ffn_up_shexp.weight q8_0\n+blk.59.attn_k_b.weight q8_0\n blk.59.attn_kv_a_mqa.weight q8_0\n blk.59.attn_output.weight q8_0\n blk.59.attn_q_a.weight q8_0\n blk.59.attn_q_b.weight q8_0\n+blk.59.attn_v_b.weight q8_0\n blk.59.ffn_down_shexp.weight q8_0\n blk.59.ffn_gate_shexp.weight q8_0\n blk.59.ffn_up_shexp.weight q8_0\n+blk.60.attn_k_b.weight q8_0\n blk.60.attn_kv_a_mqa.weight q8_0\n blk.60.attn_output.weight q8_0\n blk.60.attn_q_a.weight q8_0\n blk.60.attn_q_b.weight q8_0\n+blk.60.attn_v_b.weight q8_0\n blk.60.ffn_down_shexp.weight q8_0\n blk.60.ffn_gate_shexp.weight q8_0\n blk.60.ffn_up_shexp.weight q8_0\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: hybrid dna tokenizer fixes\nLabels: merge ready, conversion\nFiles changed (9): conversion/base.py, conversion/llama.py, conversion/qwen.py, gguf-py/gguf/constants.py, gguf-py/gguf/gguf_writer.py, src/llama-arch.cpp, src/llama-arch.h, src/llama-vocab.cpp, src/llama-vocab.h\n\n## Description (results removed)\n\n## Overview\n\n* Added automatic tagging of DNA in plain text\n* N-padded tail tokens: a partial last k-mer is padded with N, where the vocab has these tokens\n* Explicit tag handling to match HF tokenizer\n\n## Requirements\n\n- AI usage disclosure: Yes for docs and tests\n\n## Diff\n\n```diff\ndiff --git a/conversion/base.py b/conversion/base.py\nindex 14a52f01d4e3..dec1d43222ea 100644\n--- a/conversion/base.py\n+++ b/conversion/base.py\n@@ -10,6 +10,7 @@\n import os\n import re\n import sys\n+import tempfile\n from enum import IntEnum\n from pathlib import Path\n from hashlib import sha256\n@@ -2169,20 +2170,34 @@ def _set_vocab_whitespace(self) -> None:\n special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)\n special_vocab.add_to_gguf(self.gguf_writer)\n \n+ def _is_hybriddna(self) -> bool:\n+ tokenizer_config_file = self.dir_model / \"tokenizer_config.json\"\n+ if not tokenizer_config_file.is_file():\n+ return False\n+ with open(tokenizer_config_file, \"r\", encoding=\"utf-8\") as f:\n+ return json.load(f).get(\"tokenizer_class\") == \"HybridDNATokenizer\"\n+\n def _set_vocab_hybriddna(self):\n from transformers import AutoTokenizer\n tokenizer = AutoTokenizer.from_pretrained(self.dir_model, trust_remote_code=True)\n- vocab_size = self.hparams.get(\"vocab_size\", len(tokenizer.vocab)) # ty: ignore[unresolved-attribute]\n- assert max(tokenizer.vocab.values()) < vocab_size # ty: ignore[unresolved-attribute]\n+ vocab = tokenizer.get_vocab()\n+ vocab_size = self.hparams.get(\"vocab_size\", len(vocab))\n+ assert max(vocab.values()) < vocab_size\n \n- reverse_vocab = {id_: encoded_tok for encoded_tok, id_ in tokenizer.vocab.items()} # ty: ignore[unresolved-attribute]\n- # k-mers can share text with a base-vocab BPE token (e.g. CCCCCC) and get\n- # dropped by get_vocab(); a reserved marker suffix (U+E000) keeps each\n- # k-mer's own id (llama.cpp strips it on detokenization)\n- for kmer in tokenizer.kmers: # ty: ignore[unresolved-attribute]\n+ reverse_vocab = {id_: encoded_tok for encoded_tok, id_ in vocab.items()}\n+ # k-mers can share text with a base-vocab BPE token (e.g. CCCCCC) and get dropped by get_vocab()\n+ # a reserved marker suffix (U+E000) keeps each k-mer's own id (llama.cpp strips it on detokenization)\n+ # tail=\"pad_n\" (Carbon-14B) adds N-padded tail tokens (\"CT\" -> \"CTNNNN\") that get the same marker\n+ # llama.cpp detects them to pad with N and strips the padding on detokenization, tail=\"char\" is unsupported\n+ tail = getattr(tokenizer, \"tail\", \"pad_a\")\n+ if tokenizer.k != 6 or tail not in (\"pad_a\", \"pad_n\"):\n+ raise NotImplementedError(f\"HybridDNATokenizer with k={tokenizer.k}, tail={tail!r}\")\n+ for kmer in [*tokenizer.kmers, *getattr(tokenizer, \"npad_tokens\", [])]:\n reverse_vocab[tokenizer.dna_token_to_id[kmer]] = kmer + \"\\ue000\" # ty: ignore[unresolved-attribute]\n- added_vocab = tokenizer.get_added_vocab() # ty: ignore[unresolved-attribute]\n- added_tokens_decoder = tokenizer.added_tokens_decoder # ty: ignore[unresolved-attribute]\n+ # older HybridDNATokenizer versions (Carbon-500M/3B/8B) do not register the base tokenizer's added tokens (<|im_start|>, , ...) as their own\n+ # but they are still encoded as special tokens: take their types from the base tokenizer\n+ base_tokenizer = getattr(tokenizer, \"_base_tokenizer\", tokenizer)\n+ added_tokens_decoder = {**base_tokenizer.added_tokens_decoder, **tokenizer.added_tokens_decoder} # ty: ignore[unresolved-attribute]\n \n tokens: list[str] = []\n toktypes: list[int] = []\n@@ -2192,7 +2207,7 @@ def _set_vocab_hybriddna(self):\n toktypes.append(gguf.TokenType.UNUSED)\n else:\n token: str = reverse_vocab[i]\n- if token in added_vocab:\n+ if i in added_tokens_decoder:\n if added_tokens_decoder[i].special or self.does_token_look_special(token):\n toktypes.append(gguf.TokenType.CONTROL)\n else:\n@@ -2204,10 +2219,19 @@ def _set_vocab_hybriddna(self):\n tokpre = self.get_vocab_base_pre(tokenizer)\n self.gguf_writer.add_tokenizer_model(\"hybriddna\")\n self.gguf_writer.add_tokenizer_pre(tokpre)\n+ self.gguf_writer.add_dna_auto_tags(getattr(tokenizer, \"auto_dna_tags\", False))\n self.gguf_writer.add_token_list(tokens)\n self.gguf_writer.add_token_types(toktypes)\n \n special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True)\n+ if not special_vocab.merges:\n+ # Carbon-500M/3B/8B ship only tokenizer.py, no tokenizer.json\n+ # take the merges and special token ids from the base BPE tokenizer, keeping the model's own chat template (if any)\n+ with tempfile.TemporaryDirectory() as tmp:\n+ base_tokenizer.save_pretrained(tmp)\n+ base_special_vocab = gguf.SpecialVocab(Path(tmp), load_merges=True)\n+ base_special_vocab.chat_template = special_vocab.chat_template\n+ special_vocab = base_special_vocab\n special_vocab.add_to_gguf(self.gguf_writer)\n \n def _set_vocab_qwen(self):\ndiff --git a/conversion/llama.py b/conversion/llama.py\nindex 41d8c2309281..b04f54d41912 100644\n--- a/conversion/llama.py\n+++ b/conversion/llama.py\n@@ -129,8 +129,9 @@ def set_vocab(self):\n tokenizer_config_json = json.load(f)\n if (add_prefix_space := tokenizer_config_json.get(\"add_prefix_space\")) is not None:\n self.gguf_writer.add_add_space_prefix(add_prefix_space)\n- if tokenizer_config_json.get(\"tokenizer_class\") == \"HybridDNATokenizer\":\n- return self._set_vocab_hybriddna()\n+\n+ if self._is_hybriddna():\n+ return self._set_vocab_hybriddna()\n \n try:\n self._set_vocab_sentencepiece()\ndiff --git a/conversion/qwen.py b/conversion/qwen.py\nindex 0c0d0c1edc4d..e1013dd5318e 100644\n--- a/conversion/qwen.py\n+++ b/conversion/qwen.py\n@@ -59,6 +59,10 @@ class Qwen2Model(TextModel):\n model_arch = gguf.MODEL_ARCH.QWEN2\n \n def set_vocab(self):\n+ # HuggingFaceBio/Carbon-14B: Qwen3 with the HybridDNATokenizer (Qwen3 BPE plus DNA 6-mers)\n+ if self._is_hybriddna():\n+ self._set_vocab_hybriddna()\n+ return\n try:\n self._set_vocab_sentencepiece()\n except FileNotFoundError:\ndiff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py\nindex e098efae42ec..8c19e22dabca 100644\n--- a/gguf-py/gguf/constants.py\n+++ b/gguf-py/gguf/constants.py\n@@ -366,6 +366,7 @@ class Tokenizer:\n ADD_BOS = \"tokenizer.ggml.add_bos_token\"\n ADD_EOS = \"tokenizer.ggml.add_eos_token\"\n ADD_SEP = \"tokenizer.ggml.add_sep_token\"\n+ DNA_AUTO_TAGS = \"tokenizer.ggml.dna_auto_tags\"\n ADD_PREFIX = \"tokenizer.ggml.add_space_prefix\"\n REMOVE_EXTRA_WS = \"tokenizer.ggml.remove_extra_whitespaces\"\n PRECOMPILED_CHARSMAP = \"tokenizer.ggml.precompiled_charsmap\"\ndiff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py\nindex 93ec95eb648e..7becd74af9f1 100644\n--- a/gguf-py/gguf/gguf_writer.py\n+++ b/gguf-py/gguf/gguf_writer.py\n@@ -1314,6 +1314,9 @@ def add_add_eos_token(self, value: bool) -> None:\n def add_add_sep_token(self, value: bool) -> None:\n self.add_bool(Keys.Tokenizer.ADD_SEP, value)\n \n+ def add_dna_auto_tags(self, value: bool) -> None:\n+ self.add_bool(Keys.Tokenizer.DNA_AUTO_TAGS, value)\n+\n def add_add_space_prefix(self, value: bool) -> None:\n self.add_bool(Keys.Tokenizer.ADD_PREFIX, value)\n \ndiff --git a/src/llama-arch.cpp b/src/llama-arch.cpp\nindex ffa35bdea7d4..961011a2c760 100644\n--- a/src/llama-arch.cpp\n+++ b/src/llama-arch.cpp\n@@ -430,6 +430,7 @@ static const std::map LLM_KV_NAMES = {\n { LLM_KV_TOKENIZER_ADD_BOS, \"tokenizer.ggml.add_bos_token\" },\n { LLM_KV_TOKENIZER_ADD_EOS, \"tokenizer.ggml.add_eos_token\" },\n { LLM_KV_TOKENIZER_ADD_SEP, \"tokenizer.ggml.add_sep_token\" },\n+ { LLM_KV_TOKENIZER_DNA_AUTO_TAGS, \"tokenizer.ggml.dna_auto_tags\" },\n { LLM_KV_TOKENIZER_ADD_PREFIX, \"tokenizer.ggml.add_space_prefix\" },\n { LLM_KV_TOKENIZER_REMOVE_EXTRA_WS, \"tokenizer.ggml.remove_extra_whitespaces\" },\n { LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP, \"tokenizer.ggml.precompiled_charsmap\" },\ndiff --git a/src/llama-arch.h b/src/llama-arch.h\nindex 14ce29ab3238..3ea86c601d4d 100644\n--- a/src/llama-arch.h\n+++ b/src/llama-arch.h\n@@ -394,6 +394,7 @@ enum llm_kv {\n LLM_KV_TOKENIZER_ADD_BOS,\n LLM_KV_TOKENIZER_ADD_EOS,\n LLM_KV_TOKENIZER_ADD_SEP,\n+ LLM_KV_TOKENIZER_DNA_AUTO_TAGS,\n LLM_KV_TOKENIZER_ADD_PREFIX,\n LLM_KV_TOKENIZER_REMOVE_EXTRA_WS,\n LLM_KV_TOKENIZER_PRECOMPILED_CHARSMAP,\ndiff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp\nindex 05d2527dc073..a237a4b044e1 100644\n--- a/src/llama-vocab.cpp\n+++ b/src/llama-vocab.cpp\n@@ -1776,16 +1776,15 @@ struct llm_tokenizer_plamo2_session {\n // text at load\n static const std::string dna_kmer_marker = \"\\xee\\x80\\x80\";\n \n+// HybridDNATokenizer (HuggingFaceBio/Carbon-*): text inside ... is cut into fixed 6-mers, everything else goes through the base BPE\n+// Mirrors HybridDNATokenizer.encode, with optional tagging of untagged DNA (auto_dna_tags, Carbon-14B) and tail=\"pad_n\" vocab, whose dedicated tokens pad a trailing partial k-mer with N instead of A (\"CT\" -> \"CTNNNN\")\n struct llm_tokenizer_hybriddna_session : llm_tokenizer_bpe_session {\n llm_tokenizer_hybriddna_session(const llama_vocab & vocab, const llm_tokenizer_bpe & tokenizer) : llm_tokenizer_bpe_session{vocab, tokenizer}, vocab{vocab} {}\n \n void tokenize(const std::string & text, std::vector & output) override {\n- static const std::string open_tag = \"\";\n- static const std::string close_tag = \"\";\n-\n- const auto dna_begin_id = vocab.text_to_token(open_tag);\n- const auto dna_end_id = vocab.text_to_token(close_tag);\n- const auto dna_oov_id = vocab.text_to_token(\"\");\n+ dna_begin_id = vocab.text_to_token(open_tag);\n+ dna_end_id = vocab.text_to_token(close_tag);\n+ dna_oov_id = vocab.text_to_token(\"\");\n \n // Fall back to plain BPE if the DNA pieces aren't in the vocab.\n if (dna_begin_id == LLAMA_TOKEN_NULL || dna_end_id == LLAMA_TOKEN_NULL || dna_oov_id == LLAMA_TOKEN_NULL) {\n@@ -1793,63 +1792,187 @@ struct llm_tokenizer_hybriddna_session : llm_tokenizer_bpe_session {\n return;\n }\n \n- const size_t k = 6;\n- size_t pos = 0;\n+ pad_char = vocab.text_to_token(\"A\" + std::string(k - 1, 'N') + dna_kmer_marker) != LLAMA_TOKEN_NULL ? 'N' : 'A';\n \n+ // split on explicit tags as HybridDNATokenizer._split_by_dna_tags does; only the text outside them is auto-tagged\n+ size_t pos = 0;\n while (pos < text.size()) {\n const size_t start = text.find(open_tag, pos);\n- if (start == std::string::npos) {\n- if (pos < text.size()) {\n- llm_tokenizer_bpe_session::tokenize(text.substr(pos), output);\n- }\n+ const size_t end = text.find(close_tag, pos);\n+\n+ if (start == std::string::npos && end == std::string::npos) {\n+ tokenize_text(text.substr(pos), output);\n break;\n }\n- if (start > pos) {\n- llm_tokenizer_bpe_session::tokenize(text.substr(pos, start - pos), output);\n+ if (start == std::string::npos || end < start) {\n+ // as in _split_by_dna_tags, text before a without a matching is DNA (no begin token)\n+ tokenize_dna(text.substr(pos, end - pos), false, true, output);\n+ pos = end + close_tag.size();\n+ continue;\n }\n- output.push_back(dna_begin_id);\n \n- const size_t content_start = start + open_tag.size();\n- const size_t end = text.find(close_tag, content_start);\n- const size_t content_end = (end == std::string::npos) ? text.size() : end;\n-\n- emit_dna_kmers(text.substr(content_start, content_end - content_start), k, dna_oov_id, output);\n+ tokenize_text(text.substr(pos, start - pos), output);\n \n+ const size_t content_start = start + open_tag.size();\n if (end == std::string::npos) {\n+ // an unterminated runs to the end of the text (no end token)\n+ tokenize_dna(text.substr(content_start), true, false, output);\n break;\n }\n- output.push_back(dna_end_id);\n+ tokenize_dna(text.substr(content_start, end - content_start), true, true, output);\n pos = end + close_tag.size();\n }\n }\n \n private:\n- void emit_dna_kmers(const std::string & raw, size_t k, llama_token oov_id, std::vector & output) {\n- std::string seq = raw;\n- for (char & c : seq) {\n- if (c >= 'a' && c <= 'z') {\n- c = char(c - 32);\n+ static bool is_letter(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }\n+ static bool is_acgt (char c) { return c == 'A' || c == 'C' || c == 'G' || c == 'T'; }\n+ static char to_upper (char c) { return c >= 'a' && c <= 'z' ? char(c - 32) : c; }\n+\n+ // IUPAC nucleotide codes, either case (HybridDNATokenizer.IUPAC_RUN_RE)\n+ static bool is_iupac(char c) {\n+ c = to_upper(c);\n+ return std::string(\"ACGTRYSWKMBDHVN\").find(c) != std::string::npos;\n+ }\n+\n+ // HybridDNATokenizer._normalize_spaced_dna: join displays like \"ACGTA CGTAC ...\" when they hold at least twelve bases\n+ // (at least six chunks of 1-5 uppercase ACGT separated by spaces or tabs, not touching a letter)\n+ static std::string normalize_spaced_dna(const std::string & text) {\n+ const auto is_blank = [](char c) { return c == ' ' || c == '\\t'; };\n+ std::string out;\n+ size_t p = 0;\n+ while (p < text.size()) {\n+ if (is_acgt(text[p]) && (p == 0 || !is_letter(text[p - 1]))) {\n+ size_t match_end = std::string::npos;\n+ size_t chunk = p;\n+ for (int n_chunks = 1; ; n_chunks++) {\n+ size_t chunk_end = chunk;\n+ while (chunk_end < text.size() && chunk_end - chunk < 5 && is_acgt(text[chunk_end])) {\n+ chunk_end++;\n+ }\n+ if (chunk_end == chunk) {\n+ break;\n+ }\n+ if (n_chunks >= 6 && (chunk_end == text.size() || !is_letter(text[chunk_end]))) {\n+ match_end = chunk_end; // the regex is greedy, so the last valid end wins\n+ }\n+ size_t next = chunk_end;\n+ while (next < text.size() && is_blank(text[next])) {\n+ next++;\n+ }\n+ if (next == chunk_end) {\n+ break;\n+ }\n+ chunk = next;\n+ }\n+ if (match_end != std::string::npos) {\n+ std::string seq;\n+ for (size_t i = p; i < match_end; i++) {\n+ if (!is_blank(text[i])) {\n+ seq += text[i];\n+ }\n+ }\n+ out += seq.size() >= 12 ? seq : text.substr(p, match_end - p);\n+ p = match_end;\n+ continue;\n+ }\n }\n+ out += text[p++];\n }\n+ return out;\n+ }\n \n- // k-mers carry the reserved marker suffix; a non-ACGT k-mer simply\n- // isn't in the vocab and falls back to \n- auto kmer_token = [&](const std::string & kmer) {\n- const auto tok = vocab.text_to_token(kmer + dna_kmer_marker);\n- return tok != LLAMA_TOKEN_NULL ? tok : oov_id;\n+ // text outside explicit tags: with auto_dna_tags, tag DNA runs as HybridDNATokenizer._auto_tag_text_segment does\n+ [comment with results removed]\n+ void tokenize_text(const std::string & raw, std::vector & output) {\n+ auto bpe = [&](const std::string & piece) {\n+ if (!piece.empty()) {\n+ llm_tokenizer_bpe_session::tokenize(piece, output);\n+ }\n };\n+ if (!vocab.get_dna_auto_tags()) {\n+ bpe(raw);\n+ return;\n+ }\n \n+ const std::string text = normalize_spaced_dna(raw);\n+ size_t prev = 0;\n size_t i = 0;\n- for (; i + k <= seq.size(); i += k) {\n- output.push_back(kmer_token(seq.substr(i, k)));\n+ while (i < text.size()) {\n+ if (!is_iupac(text[i])) {\n+ i++;\n+ continue;\n+ }\n+ size_t j = i;\n+ size_t n_ambiguous = 0;\n+ for (; j < text.size() && is_iupac(text[j]); j++) {\n+ n_ambiguous += !is_acgt(to_upper(text[j]));\n+ }\n+ const size_t len = j - i;\n+ if ((n_ambiguous == 0 && len >= 6) || (n_ambiguous > 0 && len >= 12 && 5 * n_ambiguous <= len)) {\n+ bpe(text.substr(prev, i - prev));\n+ tokenize_dna(text.substr(i, len), true, true, output);\n+ prev = j;\n+ }\n+ i = j;\n+ }\n+ bpe(text.substr(prev));\n+ }\n+\n+ // HybridDNATokenizer._process_dna_sequence: strip, uppercase, then one token per k bases\n+ // a k-mer with anything but ACGT is , and a trailing partial k-mer is right-padded with pad_char\n+ void tokenize_dna(const std::string & content, bool has_start, bool has_end, std::vector & output) {\n+ if (has_start) {\n+ output.push_back(dna_begin_id);\n+ }\n+\n+ auto cpts = unicode_cpts_from_utf8(content);\n+ size_t first = 0;\n+ size_t last = cpts.size();\n+ while (first < last && unicode_cpt_flags_from_cpt(cpts[first]).is_whitespace) {\n+ first++;\n+ }\n+ while (last > first && unicode_cpt_flags_from_cpt(cpts[last - 1]).is_whitespace) {\n+ last--;\n+ }\n+\n+ // k-mers carry the reserved marker suffix, so they never resolve to a base-vocab token\n+ auto kmer_token = [&](size_t from, size_t to) {\n+ std::string kmer;\n+ for (size_t i = from; i < to; i++) {\n+ const uint32_t c = cpts[i] < 128 ? (uint32_t) to_upper((char) cpts[i]) : cpts[i];\n+ if (c > 127 || !is_acgt((char) c)) {\n+ return dna_oov_id;\n+ }\n+ kmer += (char) c;\n+ }\n+ kmer.append(k - kmer.size(), pad_char);\n+ const auto tok = vocab.text_to_token(kmer + dna_kmer_marker);\n+ return tok != LLAMA_TOKEN_NULL ? tok : dna_oov_id;\n+ };\n+\n+ size_t i = first;\n+ for (; i + k <= last; i += k) {\n+ output.push_back(kmer_token(i, i + k));\n+ }\n+ if (i < last) {\n+ output.push_back(kmer_token(i, last));\n }\n- if (i < seq.size()) {\n- std::string kmer = seq.substr(i);\n- kmer.append(k - kmer.size(), 'A');\n- output.push_back(kmer_token(kmer));\n+\n+ if (has_end) {\n+ output.push_back(dna_end_id);\n }\n }\n \n+ const std::string open_tag = \"\";\n+ const std::string close_tag = \"\";\n+ const size_t k = 6;\n+\n+ llama_token dna_begin_id = LLAMA_TOKEN_NULL;\n+ llama_token dna_end_id = LLAMA_TOKEN_NULL;\n+ llama_token dna_oov_id = LLAMA_TOKEN_NULL;\n+ char pad_char = 'A';\n+\n const llama_vocab & vocab;\n };\n \n@@ -1957,6 +2080,7 @@ struct llama_vocab::impl {\n bool add_bos = false;\n bool add_eos = false;\n bool add_sep = false;\n+ bool dna_auto_tags = false; // hybriddna: tag untagged DNA runs before tokenizing\n bool ignore_merges = false;\n bool clean_spaces = false; // clean_up_tokenization_spaces\n bool remove_extra_whitespaces = false;\n@@ -2689,6 +2813,12 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {\n if (text.size() > dna_kmer_marker.size()\n && text.compare(text.size() - dna_kmer_marker.size(), dna_kmer_marker.size(), dna_kmer_marker) == 0) {\n text.erase(text.size() - dna_kmer_marker.size());\n+ // tail=\"pad_n\": \"CTNNNN\" detokenizes to its real bases \"CT\"\n+ // full k-mers are ACGT only, so only N-padded tail tokens end in N\n+ const size_t last_base = text.find_last_not_of('N');\n+ if (last_base != std::string::npos) {\n+ text.erase(last_base + 1);\n+ }\n }\n }\n }\n@@ -2781,6 +2911,9 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {\n if (ml.get_key(LLM_KV_TOKENIZER_ADD_SEP, temp, false)) {\n add_sep = temp;\n }\n+ if (ml.get_key(LLM_KV_TOKENIZER_DNA_AUTO_TAGS, temp, false)) {\n+ dna_auto_tags = temp;\n+ }\n \n // workaround for Gemma 4\n // ref: https://github.com/ggml-org/llama.cpp/pull/21500\n@@ -4312,6 +4445,10 @@ bool llama_vocab::get_add_sep() const {\n return pimpl->add_sep;\n }\n \n+bool llama_vocab::get_dna_auto_tags() const {\n+ return pimpl->dna_auto_tags;\n+}\n+\n bool llama_vocab::get_ignore_merges() const {\n return pimpl->ignore_merges;\n }\ndiff --git a/src/llama-vocab.h b/src/llama-vocab.h\nindex 898a23ae6e2e..415acd22bf40 100644\n--- a/src/llama-vocab.h\n+++ b/src/llama-vocab.h\n@@ -149,6 +149,7 @@ struct llama_vocab {\n bool get_add_bos () const;\n bool get_add_eos () const;\n bool get_add_sep () const;\n+ bool get_dna_auto_tags () const;\n bool get_ignore_merges () const;\n bool get_clean_spaces () const;\n bool get_remove_extra_whitespaces () const;\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: fix exhausting CPU and MEM caused by dry sequence breaker\nLabels: documentation, testing, server\nFiles changed (5): include/llama.h, src/llama-sampler.cpp, tests/test-server-component.cpp, tools/server/README.md, tools/server/server-schema.cpp\n\n## Description (results removed)\n\n## Overview\nThis PR fixes #30833 by adding a count check in two places. I indeed found the massive CPU and memory cost with `dry_sequence_breakers` enabled and with a massive number of breakers, like 10000; it may take several minutes to finish initializing the dry breakers. I fix this by adding checks to remove redundancy and limit this kind of waste of resources.\n\n### Causes:\nThe duplicate check in the current sampler is leaky and incomplete.\nIn: function `get_overlapping_token_sequences`:\n```\nsrc/llama-sampler.cpp:3361: \n// Ensure we don't already have a duplicate matching tokenization\n while(traversing this range of processed breakers) \n if found same tokenization (even the second element [tail] is the same )\n do not put in the vector\n```\nHowever, this is incomplete because it only covers cases where we cannot find an entire match of `str` in the `word`.\n**And to detokenize every time we call 'get_overlapping_token_sequences', we just repeated detokenizing the whole vocab_words array, which is really a big cost.** \n**Also, in the function `get_overlapping_token_sequences` , the call of `vocab.tokenize(str.substr(i)) ` is indeed repetitive as it is related only to `i`.**\n\n### Solutions\n\nI managed to solve this issue with four modification:\nModification 1: src/llama-sampler.cpp (3659~3683):\n```c\nsrc/llama-sampler:3661: std::unordered_set seen_breakers;\nsrc/llama-sampler:3675:\nif (!seen_breakers.insert(sequence_break).second) continue; // skip overlap check for duplicate breaker\nif (seen_breakers.size() > LLAMA_DRY_MAX_SEQ_BREAKERS) break; // truncate\n```\nModification 2: We need to inform users about this, so I also add this mechanism to the HTTP request. What we can do in `llama_sampler_init_dry` is only: **truncate + LLAMA_LOG_WARN**. Coded in the same way as in `llama-sampler.cpp` (also, to report errors is to count, and we need to remove the duplicate breakers before we count them).\nWe just report HTTP 400 to users if the size exceeds the limit.\n> While you may believe that this is an inconsistency because we do not report errors or stop in that case, this is acceptable, because dealing with the size of a single breaker exceeding 40 chars is just a WARN.\nCoded like:\n```c\n if (sequence_break.size() > MAX_CHAR_LEN) {\n LLAMA_LOG_WARN(\"truncating DRY sequence breaker to %d characters\\n\", MAX_CHAR_LEN);\n sequence_break.resize(MAX_CHAR_LEN);\n```\n\nModification 3: predetokenized outside `get_overlapping_token_sequences` in `llama_sampler_init_dry`:\n```\n std::vector vocab_words;\n vocab_words.reserve(vocab->n_tokens());\n for (llama_token token_id = 0; token_id < (llama_token) vocab->n_tokens(); ++token_id) {\n vocab_words.push_back(vocab->detokenize({token_id}, true));\n }\n```\nModification 4: cache the repetitive visit of tail of `i`, using `tail_cache[i]` to cache this. \n\n### Tests\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/include/llama.h b/include/llama.h\nindex 3af6e22233ef..ae54e661bea6 100644\n--- a/include/llama.h\n+++ b/include/llama.h\n@@ -1564,6 +1564,10 @@ extern \"C\" {\n float penalty_freq, // must be finite, 0.0 = disabled\n float penalty_present); // must be finite, 0.0 = disabled\n \n+ /// maximum number of distinct DRY sequence breakers, duplicates not counted\n+ /// processing each breaker scans the entire vocabulary, so the init cost is O(num_breakers x n_vocab)\n+ #define LLAMA_DRY_MAX_SEQ_BREAKERS 64\n+\n /// @details DRY sampler, designed by p-e-w, as described in: https://github.com/oobabooga/text-generation-webui/pull/5677, porting Koboldcpp implementation authored by pi6am: https://github.com/LostRuins/koboldcpp/pull/982\n LLAMA_API struct llama_sampler * llama_sampler_init_dry(\n const struct llama_vocab * vocab,\ndiff --git a/src/llama-sampler.cpp b/src/llama-sampler.cpp\nindex 521c5718e130..9004efa20df7 100644\n--- a/src/llama-sampler.cpp\n+++ b/src/llama-sampler.cpp\n@@ -18,6 +18,7 @@\n #include \n #include \n #include \n+#include \n #include \n \n // the ring buffer works similarly to std::deque, but with a fixed capacity\n@@ -3333,9 +3334,13 @@ struct llama_sampler_dry {\n };\n \n // Ported from Koboldcpp, original PR: https://github.com/LostRuins/koboldcpp/pull/982 (Original author: pi6am)\n-static void get_overlapping_token_sequences(const llama_vocab & vocab, const std::string& str, std::unordered_multimap>& token_sequences, int max_tail_len = -1) {\n- for (llama_token token_id = 0; token_id < (llama_token) vocab.n_tokens(); token_id++) {\n- std::string word = vocab.detokenize({token_id}, true);\n+static void get_overlapping_token_sequences(const llama_vocab & vocab, const std::vector & vocab_words, const std::string& str, std::unordered_multimap>& token_sequences, int max_tail_len = -1) {\n+ // the tail tokenization only depends on how many characters of str were matched, so compute each one at most once\n+ std::vector> tail_cache(str.size() + 1);\n+ std::vector tail_cached(str.size() + 1, false);\n+\n+ for (llama_token token_id = 0; token_id < (llama_token) vocab_words.size(); token_id++) {\n+ const std::string & word = vocab_words[token_id];\n if (word.find(str) != std::string::npos) {\n token_sequences.emplace(token_id, std::vector());\n } else {\n@@ -3352,10 +3357,14 @@ static void get_overlapping_token_sequences(const llama_vocab & vocab, const std\n }\n }\n if (match) {\n- std::vector tokenization = vocab.tokenize(str.substr(i), false, false);\n- if (max_tail_len >= 0 && tokenization.size() > (size_t)max_tail_len) {\n- tokenization.resize(max_tail_len);\n+ if (!tail_cached[i]) {\n+ tail_cache[i] = vocab.tokenize(str.substr(i), false, false);\n+ if (max_tail_len >= 0 && tail_cache[i].size() > (size_t)max_tail_len) {\n+ tail_cache[i].resize(max_tail_len);\n+ }\n+ tail_cached[i] = true;\n }\n+ const std::vector & tokenization = tail_cache[i];\n \n // Ensure we don't already have a duplicate matching tokenization\n auto its = token_sequences.equal_range(token_id);\n@@ -3656,6 +3665,16 @@ struct llama_sampler * llama_sampler_init_dry(const struct llama_vocab * vocab,\n \n if (dry_enabled && seq_breakers != nullptr && num_breakers > 0) {\n // Process sequence breakers\n+ // each distinct breaker costs a full vocabulary scan: drop duplicates and stop at the cap\n+ std::unordered_set seen_breakers;\n+\n+ // detokenize the vocabulary once instead of rescanning it for every breaker\n+ std::vector vocab_words;\n+ vocab_words.reserve(vocab->n_tokens());\n+ for (llama_token token_id = 0; token_id < (llama_token) vocab->n_tokens(); ++token_id) {\n+ vocab_words.push_back(vocab->detokenize({token_id}, true));\n+ }\n+\n for (size_t i = 0; i < num_breakers; ++i) {\n if (seq_breakers[i] == nullptr || std::strlen(seq_breakers[i]) == 0) {\n LLAMA_LOG_WARN(\"skipping null or empty DRY sequence breaker at index %zu\\n\", i);\n@@ -3663,17 +3682,22 @@ struct llama_sampler * llama_sampler_init_dry(const struct llama_vocab * vocab,\n }\n \n std::string sequence_break(seq_breakers[i]);\n- if (sequence_break.empty()) {\n- LLAMA_LOG_WARN(\"skipping empty DRY sequence breaker\\n\");\n- continue;\n- }\n-\n if (sequence_break.size() > MAX_CHAR_LEN) {\n LLAMA_LOG_WARN(\"truncating DRY sequence breaker to %d characters\\n\", MAX_CHAR_LEN);\n sequence_break.resize(MAX_CHAR_LEN);\n }\n \n- get_overlapping_token_sequences(*vocab, sequence_break, processed_breakers, MAX_SEQ_LEN);\n+ if (!seen_breakers.insert(sequence_break).second) {\n+ continue;\n+ }\n+\n+ if (seen_breakers.size() > LLAMA_DRY_MAX_SEQ_BREAKERS) {\n+ LLAMA_LOG_WARN(\"ignoring DRY sequence breaker at index %zu: more than %d distinct breakers\\n\",\n+ i, LLAMA_DRY_MAX_SEQ_BREAKERS);\n+ break;\n+ }\n+\n+ get_overlapping_token_sequences(*vocab, vocab_words, sequence_break, processed_breakers, MAX_SEQ_LEN);\n }\n }\n \ndiff --git a/tools/server/server-schema.cpp b/tools/server/server-schema.cpp\nindex 1e2dce8886dc..0a14a9620961 100644\n--- a/tools/server/server-schema.cpp\n+++ b/tools/server/server-schema.cpp\n@@ -2,6 +2,8 @@\n \n #include \"json-schema-to-grammar.h\"\n \n+#include \n+\n namespace server_schema {\n \n //\n@@ -246,6 +248,23 @@ std::vector> make_llama_cmpl_schema(const common_params &\n if (ctx.params.sampling.dry_sequence_breakers.empty()) {\n throw std::runtime_error(\"Error: dry_sequence_breakers must be a non-empty array of strings\");\n }\n+\n+ // each distinct breaker costs a full vocabulary scan at sampler init, so dedupe before counting\n+ std::unordered_set seen;\n+ std::vector unique_breakers;\n+\n+ for (const auto & breaker : ctx.params.sampling.dry_sequence_breakers) {\n+ if (seen.insert(breaker).second) {\n+ unique_breakers.push_back(breaker);\n+ }\n+ }\n+\n+ if (unique_breakers.size() > LLAMA_DRY_MAX_SEQ_BREAKERS) {\n+ throw std::runtime_error(string_format(\n+ \"Error: dry_sequence_breakers must contain at most %d distinct entries\", LLAMA_DRY_MAX_SEQ_BREAKERS));\n+ }\n+\n+ ctx.params.sampling.dry_sequence_breakers = std::move(unique_breakers);\n }));\n \n // handle both \"json_schema\" and \"grammar\"\n\n[1 documentation file diff(s) omitted]\ndiff --git a/tests/test-server-component.cpp b/tests/test-server-component.cpp\nindex 92eeec055b48..0d2329cf7399 100644\n--- a/tests/test-server-component.cpp\n+++ b/tests/test-server-component.cpp\n@@ -2,6 +2,7 @@\n \n #include \"../tools/server/server-common.h\"\n #include \"../tools/server/server-decision.h\"\n+#include \"../tools/server/server-schema.h\"\n \n #include \n #include \n@@ -490,6 +491,42 @@ static void test_decision_depth(testing & t) {\n });\n }\n \n+// DRY sequence breakers\n+//\n+\n+static void test_dry_sequence_breakers(testing & t) {\n+ common_params params_base;\n+\n+ const auto eval = [&](const json & data) {\n+ return server_schema::eval_llama_cmpl_schema(nullptr, params_base, {}, data);\n+ };\n+\n+ {\n+ json data;\n+ data[\"dry_sequence_breakers\"] = json::array({\"ab\", \"ab\", \"cd\", \"ab\"});\n+ const auto params = eval(data);\n+ const std::vector expected = {\"ab\", \"cd\"};\n+ t.assert_true(\"duplicates removed, order kept\", params.sampling.dry_sequence_breakers == expected);\n+ }\n+\n+ {\n+ std::vector many;\n+ for (int i = 0; i <= LLAMA_DRY_MAX_SEQ_BREAKERS; ++i) {\n+ many.push_back(\"b\" + std::to_string(i));\n+ }\n+ json data;\n+ data[\"dry_sequence_breakers\"] = many;\n+\n+ bool thrown = false;\n+ try {\n+ eval(data);\n+ } catch (const std::exception &) {\n+ thrown = true;\n+ }\n+ t.assert_true(\"more than the cap is rejected\", thrown);\n+ }\n+}\n+\n int main(int argc, char ** argv) {\n testing t;\n \n@@ -511,6 +548,7 @@ int main(int argc, char ** argv) {\n t.test(\"decision_escape\", test_decision_escape);\n t.test(\"rerank_template\", test_rerank_template);\n t.test(\"decision_depth\", test_decision_depth);\n+ t.test(\"dry_sequence_breakers\", test_dry_sequence_breakers);\n \n return t.summary();\n }\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: sycl: fix f32 to q2_0/q4_0/q5_0 rounding in CPY\nLabels: testing, ggml, merge ready, SYCL, Apple Metal\nFiles changed (2): ggml/src/ggml-metal/kernels/quantize.h, ggml/src/ggml-sycl/cpy.hpp\n\n## Description (results removed)\n\nThe device rounds three things differently from the CPU, by one ulp each: the reciprocal of 1.0f/d, the fused multiply and add in x*id + 8.5f (q4_0) and + 16.5f (q5_0), and the (int)(x + 0.5f) round in q2_0. f16/bf16 inputs sit on exact .5 ties, so one ulp flips the quantised value.\n\nThe fix is in ggml/src/ggml-sycl/cpy.hpp: correctly rounded division, round half away from zero by truncation, and a no-op fmin so the multiply and add don't fuse. Only the f32 to qX_0 block functions change.\n\nFrom review: ggml/src/ggml-metal/kernels/quantize.h gets the `#pragma METAL fp math_mode(safe)` that quantize_q2_0 was missing (the other quantizers already have it).\n\nSET_ROWS 511/511, GET_ROWS 216/216, DUP 10/10, MUL_MAT 2273/2273, both builds.\n\nArc B580 12GB, i5-13400, Ubuntu 24.04, icpx 2025.3.3, NEO 26.35, Release with -DGGML_SYCL=ON -DGGML_SYCL_TARGET=INTEL.\n\nNot done: perf not re-measured, no full CI. q4_1 and q5_1 need a follow-up, the matching fix only agreed with an IEEE CPU reference, not the normal fast-fp build.\n\nRef #28384.\n\n- I have read and agree with the contributing guidelines\n- AI usage disclosure: Claude found the causes, wrote the fix and ran the tests. I reviewed the change and the results.\n\n## Diff\n\n```diff\ndiff --git a/ggml/src/ggml-metal/kernels/quantize.h b/ggml/src/ggml-metal/kernels/quantize.h\nindex 0741b22253ed..d3ba8884a521 100644\n--- a/ggml/src/ggml-metal/kernels/quantize.h\n+++ b/ggml/src/ggml-metal/kernels/quantize.h\n@@ -20,6 +20,7 @@ void quantize_q1_0(device const float * src, device block_q1_0 & dst) {\n }\n \n void quantize_q2_0(device const float * src, device block_q2_0 & dst) {\n+#pragma METAL fp math_mode(safe)\n float amax = 0.0f;\n for (int j = 0; j < QK2_0; j++) {\n float a = fabs(src[j]);\ndiff --git a/ggml/src/ggml-sycl/cpy.hpp b/ggml/src/ggml-sycl/cpy.hpp\nindex 34bae1b2dd18..9d63960810bb 100644\n--- a/ggml/src/ggml-sycl/cpy.hpp\n+++ b/ggml/src/ggml-sycl/cpy.hpp\n@@ -70,8 +70,22 @@ inline void cpy_blck_f32_q1_0(const char * cxi, char * cdsti) {\n }\n }\n \n-inline int round_nearest_int(float x) {\n- return (int)(x >= 0.0f ? x + 0.5f : x - 0.5f);\n+// exact roundf (half away from zero); x + 0.5f carries for x = 0.5 - 2^-25, and sycl::round is not exact under fast fp\n+inline int round_half_away_int(float x) {\n+ const float t = sycl::trunc(x);\n+ return (int) (sycl::fabs(x - t) >= 0.5f ? t + sycl::copysign(1.0f, x) : t);\n+}\n+\n+ [comment with results removed]\n+// so pick the approximation or a neighbour by smallest exact FMA residual\n+inline float div_correctly_rounded(float a, float b) {\n+ const float y = a / b;\n+ const float lo = sycl::nextafter(y, -INFINITY);\n+ const float hi = sycl::nextafter(y, INFINITY);\n+ const float e = sycl::fabs(sycl::fma(-b, y, a));\n+ const float el = sycl::fabs(sycl::fma(-b, lo, a));\n+ const float eh = sycl::fabs(sycl::fma(-b, hi, a));\n+ return el < e && el <= eh ? lo : (eh < e ? hi : y);\n }\n \n inline void cpy_blck_f32_q2_0(const char * cxi, char * cdsti) {\n@@ -85,7 +99,7 @@ inline void cpy_blck_f32_q2_0(const char * cxi, char * cdsti) {\n }\n \n const float d = amax;\n- const float id = d > 0.0f ? 1.0f / d : 0.0f;\n+ const float id = d > 0.0f ? div_correctly_rounded(1.0f, d) : 0.0f;\n \n dsti->d = d;\n \n@@ -94,7 +108,7 @@ inline void cpy_blck_f32_q2_0(const char * cxi, char * cdsti) {\n }\n \n for (int j = 0; j < QK2_0; ++j) {\n- int q = round_nearest_int(xi[j] * id) + 1;\n+ int q = round_half_away_int(xi[j] * id) + 1;\n q = dpct::max(0, dpct::min(3, q));\n \n const int byte_index = j / 4;\n@@ -378,7 +392,7 @@ inline void cpy_blck_f32_q4_0(const char * cxi, char * cdsti) {\n }\n \n const float d = vmax / -8;\n- const float id = d ? 1.0f / d : 0.0f;\n+ const float id = d ? div_correctly_rounded(1.0f, d) : 0.0f;\n \n dsti->d = d;\n \n@@ -386,8 +400,9 @@ inline void cpy_blck_f32_q4_0(const char * cxi, char * cdsti) {\n const float x0 = xi[0 + j] * id;\n const float x1 = xi[QK4_0 / 2 + j] * id;\n \n- const uint8_t xi0 = dpct::min(15, (int8_t) (x0 + 8.5f));\n- const uint8_t xi1 = dpct::min(15, (int8_t) (x1 + 8.5f));\n+ // no-op fmin stops x * id + 8.5f being fused into an FMA, so x * id is rounded as on the CPU\n+ const uint8_t xi0 = dpct::min(15, (int8_t) (sycl::fmin(x0, 6.5f) + 8.5f));\n+ const uint8_t xi1 = dpct::min(15, (int8_t) (sycl::fmin(x1, 6.5f) + 8.5f));\n \n dsti->qs[j] = xi0;\n dsti->qs[j] |= xi1 << 4;\n@@ -442,7 +457,7 @@ inline void cpy_blck_f32_q5_0(const char * cxi, char * cdsti) {\n }\n \n const float d = vmax / -16;\n- const float id = d ? 1.0f / d : 0.0f;\n+ const float id = d ? div_correctly_rounded(1.0f, d) : 0.0f;\n \n dsti->d = d;\n \n@@ -451,8 +466,9 @@ inline void cpy_blck_f32_q5_0(const char * cxi, char * cdsti) {\n const float x0 = xi[0 + j] * id;\n const float x1 = xi[QK5_0 / 2 + j] * id;\n \n- const uint8_t xi0 = dpct::min(31, (int8_t) (x0 + 16.5f));\n- const uint8_t xi1 = dpct::min(31, (int8_t) (x1 + 16.5f));\n+ // fmin: no FMA, see cpy_blck_f32_q4_0\n+ const uint8_t xi0 = dpct::min(31, (int8_t) (sycl::fmin(x0, 14.5f) + 16.5f));\n+ const uint8_t xi1 = dpct::min(31, (int8_t) (sycl::fmin(x1, 14.5f) + 16.5f));\n \n dsti->qs[j] = (xi0 & 0xf) | ((xi1 & 0xf) << 4);\n qh |= ((xi0 & 0x10u) >> 4) << (j + 0);\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: llama : fix rotation of attention tensors in layers with shared KV\nLabels: model\nFiles changed (5): src/llama-hparams.cpp, src/llama-model-saver.cpp, src/llama-model.cpp, src/models/gemma3n.cpp, src/models/gemma4.cpp\n\n## Description (results removed)\n\n## Overview\n\nFixes the rotation of attention tensors for layers that reuse another layer's KV cache.\n\nFor these layers, the attention tensors need to use the source layer's rotation so that Q and KV heads are on the same device.\n\nA nice side effect is that we move Gemma-specific logic out of `llama-model.cpp` into Gemma-specific files.\n\nExisting discussion of this PR here: https://github.com/ggml-org/llama.cpp/pull/31401#issuecomment-6513787403 + https://github.com/ggml-org/llama.cpp/pull/31401#issuecomment-6514490360\n\n## Requirements\n\n- AI usage disclosure: YES. Opus 5.5 helped investigate and fix the bug. I heavily modified its output. (Claude's initial approach was bad for long-term maintenance.)\n\n## Diff\n\n```diff\ndiff --git a/src/llama-hparams.cpp b/src/llama-hparams.cpp\nindex 9b4244567202..f05b5d6bbb38 100644\n--- a/src/llama-hparams.cpp\n+++ b/src/llama-hparams.cpp\n@@ -319,20 +319,7 @@ uint32_t llama_hparams::n_embd_head_v_mla() const {\n }\n \n bool llama_hparams::has_kv(uint32_t il) const {\n- if (kv_source(il) != il) {\n- return false;\n- }\n-\n- if (n_layer_kv_from_start >= 0) {\n- if (il < (uint32_t) n_layer_kv_from_start) {\n- return true;\n- }\n-\n- return false;\n- }\n-\n- // by default, all layers have kv\n- return true;\n+ return kv_source(il) == il;\n }\n \n uint32_t llama_hparams::kv_source(uint32_t il) const {\ndiff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp\nindex 5c2d7a82209a..a08e173e9eed 100644\n--- a/src/llama-model-saver.cpp\n+++ b/src/llama-model-saver.cpp\n@@ -307,10 +307,12 @@ void llama_model_saver::add_kv_from_model() {\n add_kv(LLM_KV_ATTENTION_INDEXER_KPOOL_SELECT_TAIL, hparams.indexer_kpool_select_tail);\n add_kv(LLM_KV_ATTENTION_INDEXER_LOCAL_BLOCKS, hparams.indexer_local_blocks);\n add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, hparams.is_indexer_full_impl, true);\n- for (uint32_t il = 0; il < hparams.n_layer(); ++il) {\n- if (hparams.kv_source(il) != il) {\n- add_kv(LLM_KV_ATTENTION_KV_SOURCE_MAP, hparams.kv_source_impl, true);\n- break;\n+ if (hparams.n_layer_kv_from_start < 0) {\n+ for (uint32_t il = 0; il < hparams.n_layer(); ++il) {\n+ if (hparams.kv_source(il) != il) {\n+ add_kv(LLM_KV_ATTENTION_KV_SOURCE_MAP, hparams.kv_source_impl, true);\n+ break;\n+ }\n }\n }\n add_kv(LLM_KV_ATTENTION_RECURRENT_LAYERS, hparams.is_recr_impl, true);\ndiff --git a/src/llama-model.cpp b/src/llama-model.cpp\nindex 83aed0144f95..c4a5b64fd231 100644\n--- a/src/llama-model.cpp\n+++ b/src/llama-model.cpp\n@@ -486,7 +486,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str\n GGML_ASSERT(length_prefix != std::string::npos);\n prefix = tensor_name.substr(0, length_prefix + 1);\n il = std::stoull(tensor_name.substr(4, length_prefix));\n- rotation = get_il_eff(il) % ud->n_devices;\n+ const bool is_attn = tensor_name.compare(prefix.size(), 5, \"attn_\") == 0;\n+ // attention heads must be on the same device as the KV of the source layer\n+ rotation = get_il_eff(is_attn ? hparams.kv_source(il) : il) % ud->n_devices;\n } else if (tensor_name.substr(0, 6) == \"cache_\") {\n const size_t layer_index_start = tensor_name.find(\"_l\", 6);\n GGML_ASSERT(layer_index_start != std::string::npos);\n@@ -3280,14 +3282,8 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params,\n llama_kv_cache::layer_share_cb share = nullptr;\n \n if (arch == LLM_ARCH_GEMMA3N || arch == LLM_ARCH_GEMMA4) {\n- reuse = [&](uint32_t il) {\n- GGML_ASSERT(hparams.n_layer_kv_from_start >= 2);\n-\n- if (il >= (uint32_t)hparams.n_layer_kv_from_start) {\n- return hparams.n_layer_kv_from_start - (hparams.is_swa(il) ? 2 : 1);\n- }\n-\n- return -1;\n+ reuse = [&](int32_t il) -> int32_t {\n+ return hparams.has_kv(il) ? -1 : (int32_t) hparams.kv_source(il);\n };\n }\n \ndiff --git a/src/models/gemma3n.cpp b/src/models/gemma3n.cpp\nindex 7848f9f59c88..7f12b1747547 100644\n--- a/src/models/gemma3n.cpp\n+++ b/src/models/gemma3n.cpp\n@@ -7,6 +7,11 @@ void llama_model_gemma3n::load_arch_hparams(llama_model_loader & ml) {\n hparams.n_layer_kv_from_start = 20;\n hparams.f_attention_scale = 1.0f;\n \n+ // shared layers read the KV of the last layer with own KV and the same SWA type\n+ for (uint32_t il = hparams.n_layer_kv_from_start; il < hparams.n_layer_all; il++) {\n+ hparams.kv_source_impl[il] = hparams.n_layer_kv_from_start - (hparams.is_swa(il) ? 2 : 1);\n+ }\n+\n ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa, false);\n ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa);\n ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);\ndiff --git a/src/models/gemma4.cpp b/src/models/gemma4.cpp\nindex 42d6a7d47ad9..d0b2b3a5b473 100644\n--- a/src/models/gemma4.cpp\n+++ b/src/models/gemma4.cpp\n@@ -11,6 +11,12 @@ void llama_model_gemma4::load_arch_hparams(llama_model_loader & ml) {\n hparams.n_layer_kv_from_start = hparams.n_layer_all - (int32_t)n_kv_shared_layers;\n hparams.f_attention_scale = 1.0f; // Gemma4 uses self.scaling = 1.0 (no pre-attn scaling)\n \n+ // shared layers read the KV of the last layer with own KV and the same SWA type\n+ GGML_ASSERT(hparams.n_layer_kv_from_start >= 2);\n+ for (uint32_t il = hparams.n_layer_kv_from_start; il < hparams.n_layer_all; il++) {\n+ hparams.kv_source_impl[il] = hparams.n_layer_kv_from_start - (hparams.is_swa(il) ? 2 : 1);\n+ }\n+\n ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa, false);\n ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all, false);\n ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa);\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: kvcache-ai/Mooncake\nPull request: [Bugfix][TransferEngine] Register HIP IPC memory at allocation granularity\nLabels: run-ci, Transfer Engine, Installation, Tests, size/M\nFiles changed (7): mooncake-transfer-engine/include/transfer_metadata.h, mooncake-transfer-engine/include/transport/hip_transport/hip_transport.h, mooncake-transfer-engine/src/transfer_metadata.cpp, mooncake-transfer-engine/src/transport/hip_transport/hip_transport.cpp, mooncake-transfer-engine/src/transport/rdma_transport/rdma_transport.cpp, mooncake-transfer-engine/src/transport/tcp_transport/tcp_transport.cpp, mooncake-wheel/tests/test_transfer_sub_allocation_on_hip.py\n\n## Description (results removed)\n\n## Description\n\nFixes #3546.\n\n`hipIpcGetMemHandle` always exports the entire `hipMalloc` allocation, but the\nHIP IPC registration path recorded the caller's sub-range address as the buffer\nbase. The reader's relocation (`dest_addr - entry.addr + shm_addr`) therefore\ncollapsed every sub-range onto the allocation base, and each buffer silently\nreturned the first buffer's bytes with `rc=0`. Framework caching allocators\nsub-allocate constantly, so any caller registering individual tensors out of one\nallocation is affected — including `batch_register_memory`, which loops over the\nsame function.\n\nThe CUDA IPC paths had exactly this bug and it was fixed by registering the\nallocation base instead of the requested range — #1622 for\n`intranode_nvlink_transport` and #1831 for TENT. The HIP port was missed: its only\n`hipMemGetAddressRange` calls are in the fabric-memory branch and in the free\nlogic, never in the IPC branch. This applies the same fix there: resolve the real\nbase with `hipMemGetAddressRange`, skip allocations already exported, take the IPC\nhandle for the base, record the whole allocation in `BufferDesc`, and key\nunregistration off that base as well, matching\n`IntraNodeNvlinkTransport::registerLocalMemory` and `unregisterLocalMemory`.\n\n## Module\n\n- [ ] CI/CD\n- [ ] Docs\n- [ ] Other\n\n## Type of Change\n\n- [x] Bug fix\n- [ ] New feature\n- [ ] Refactor\n- [ ] Breaking change\n- [ ] Other\n\n(`torch.version.hip == 7.2.26015-fc0010cf6a`), Python 3.10.9, built from `main` @\n`f90ae69` with `-DUSE_HIP=ON -DCMAKE_HIP_ARCHITECTURES=gfx942`.\n\nThe reproducer in #3546 goes from `got [1, 1, 1, 1]` to `got [1, 2, 3, 4]`, and\nflips back when the pre-fix `engine.so` is swapped in again.\n\n**Test commands:**\n[results removed]\n**Test results:**\n[results removed]\n## Checklist\n\n- [x] For changes >500 LOC: I have filed an RFC issue — n/a, 48 lines excluding tests\n\nthe clang-format 20 C/C++ hook. I did not run `--all-files`, since it rewrites\nfiles unrelated to this change.\n\nQoder was used for the investigation, the patch and the test.\n\n## Diff\n\n```diff\ndiff --git a/mooncake-transfer-engine/include/transfer_metadata.h b/mooncake-transfer-engine/include/transfer_metadata.h\nindex 6d7cdb935a..20678f0a17 100644\n--- a/mooncake-transfer-engine/include/transfer_metadata.h\n+++ b/mooncake-transfer-engine/include/transfer_metadata.h\n@@ -280,6 +280,13 @@ class TransferMetadata {\n // ERR_ADDRESS_NOT_REGISTERED means no matching local entry was present.\n int removeLocalMemoryBuffer(void *addr, bool update_metadata);\n \n+ // Removes the buffer at addr only when pred accepts the entry, so\n+ // transports sharing an address in the local buffer list remove only\n+ // their own entries.\n+ int removeLocalMemoryBuffer(\n+ void *addr, const std::function &pred,\n+ bool update_metadata);\n+\n // Rebuilds interned NIC paths on `desc` before insert. The caller must\n // exclusively own `desc`; do not pass a live descriptor from the metadata\n // map (copy first, as refreshLocalDeviceDesc does).\ndiff --git a/mooncake-transfer-engine/include/transport/hip_transport/hip_transport.h b/mooncake-transfer-engine/include/transport/hip_transport/hip_transport.h\nindex a8f48c35d0..145569b63f 100644\n--- a/mooncake-transfer-engine/include/transport/hip_transport/hip_transport.h\n+++ b/mooncake-transfer-engine/include/transport/hip_transport/hip_transport.h\n@@ -9,6 +9,8 @@\n #include \n #include \n #include \n+#include \n+#include \n #include \n #include \n \n@@ -90,6 +92,14 @@ class HipTransport : public Transport {\n bool use_fabric_mem_;\n \n std::mutex register_mutex_;\n+ // Registered sub-range address → its hipMalloc base; base → live alias\n+ // count. One IPC registration per base, removed by the last unregister.\n+ std::unordered_map registered_addr_to_base_;\n+ std::unordered_map registered_base_refs_;\n+ // Addresses registerLocalMemory deliberately skipped (e.g. host memory\n+ // left to other transports), distinguishing them from never-registered\n+ // ones at unregister time.\n+ std::unordered_set skipped_addrs_;\n \n // Stream and event pools for async operations\n StreamPool stream_pool_;\ndiff --git a/mooncake-transfer-engine/src/transfer_metadata.cpp b/mooncake-transfer-engine/src/transfer_metadata.cpp\nindex f9b56fca4f..b3a055dd0d 100644\n--- a/mooncake-transfer-engine/src/transfer_metadata.cpp\n+++ b/mooncake-transfer-engine/src/transfer_metadata.cpp\n@@ -1853,6 +1853,13 @@ int TransferMetadata::addLocalMemoryBuffer(const BufferDesc &buffer_desc,\n \n int TransferMetadata::removeLocalMemoryBuffer(void *addr,\n bool update_metadata) {\n+ return removeLocalMemoryBuffer(\n+ addr, [](const BufferDesc &) { return true; }, update_metadata);\n+}\n+\n+int TransferMetadata::removeLocalMemoryBuffer(\n+ void *addr, const std::function &pred,\n+ bool update_metadata) {\n bool addr_exist = false;\n {\n RWSpinlock::WriteGuard guard(segment_lock_);\n@@ -1860,12 +1867,13 @@ int TransferMetadata::removeLocalMemoryBuffer(void *addr,\n auto new_segment_desc = std::make_shared(*segment_desc);\n for (auto iter = new_segment_desc->buffers.begin();\n iter != new_segment_desc->buffers.end(); ++iter) {\n- if (iter->addr == (uint64_t)addr\n+ if ((iter->addr == (uint64_t)addr\n #ifdef USE_CXL\n- || (iter->offset + new_segment_desc->cxl_base_addr) ==\n- (uint64_t)addr\n+ || (iter->offset + new_segment_desc->cxl_base_addr) ==\n+ (uint64_t)addr\n #endif\n- ) {\n+ ) &&\n+ pred(*iter)) {\n new_segment_desc->buffers.erase(iter);\n addr_exist = true;\n new_segment_desc->rebuildBufferRangeIndex();\ndiff --git a/mooncake-transfer-engine/src/transport/hip_transport/hip_transport.cpp b/mooncake-transfer-engine/src/transport/hip_transport/hip_transport.cpp\nindex e24978bc42..4e2fc042cd 100644\n--- a/mooncake-transfer-engine/src/transport/hip_transport/hip_transport.cpp\n+++ b/mooncake-transfer-engine/src/transport/hip_transport/hip_transport.cpp\n@@ -656,6 +656,22 @@ Status HipTransport::submitTransferTask(\n return Status::OK();\n }\n \n+namespace {\n+\n+// Matches the descs this transport published into the shared local buffer\n+// list. Under multi-protocol the protocol field is authoritative; without it,\n+// the serialized IPC/fabric handle is the discriminator (only GPU-IPC\n+// transports fill shm_name, and they never coexist with HIP in one build).\n+bool isOwnDesc(const TransferMetadata::BufferDesc& desc) {\n+#ifdef ENABLE_MULTI_PROTOCOL\n+ return desc.protocol == \"hip\";\n+#else\n+ return !desc.shm_name.empty();\n+#endif\n+}\n+\n+} // namespace\n+\n int HipTransport::registerLocalMemory(void* addr, size_t length,\n const std::string& location,\n bool remote_accessible,\n@@ -684,27 +700,65 @@ int HipTransport::registerLocalMemory(void* addr, size_t length,\n LOG(INFO) << \"HipTransport: skipping non-device memory \" << addr\n << \", leaving it to other transports\";\n }\n+ skipped_addrs_.insert((uint64_t)addr);\n+ return 0;\n+ }\n+\n+ // Resolve the true hipMalloc base address. Framework caching\n+ // allocators (PyTorch, etc.) sub-allocate tensors within larger\n+ // hipMalloc segments. hipIpcGetMemHandle always returns a handle for\n+ // the entire segment, so we must register at segment granularity or\n+ // relocateSharedMemoryAddress() maps every sub-range back onto the\n+ // segment base and the peer silently reads the wrong bytes.\n+ void* base_ptr = nullptr;\n+ size_t alloc_size = 0;\n+ if (!checkHip(hipMemGetAddressRange((hipDeviceptr_t*)&base_ptr,\n+ &alloc_size, (hipDeviceptr_t)addr),\n+ \"HipTransport: hipMemGetAddressRange failed\")) {\n+ return -1;\n+ }\n+\n+ // Re-registering the same address is idempotent; a new sub-range of\n+ // an already exported allocation just takes another reference.\n+ uint64_t base = (uint64_t)base_ptr;\n+ if (!registered_addr_to_base_.emplace((uint64_t)addr, base).second) {\n+ return 0;\n+ }\n+ auto it = registered_base_refs_.find(base);\n+ if (it != registered_base_refs_.end()) {\n+ it->second++;\n return 0;\n }\n \n // Get IPC handle\n hipIpcMemHandle_t handle;\n- if (!checkHip(hipIpcGetMemHandle(&handle, addr),\n+ if (!checkHip(hipIpcGetMemHandle(&handle, base_ptr),\n \"HipTransport: hipIpcGetMemHandle failed\")) {\n+ registered_addr_to_base_.erase((uint64_t)addr);\n return -1;\n }\n \n // Register buffer with metadata\n (void)remote_accessible;\n BufferDesc desc;\n- desc.addr = (uint64_t)addr;\n- desc.length = length;\n+ desc.addr = (uint64_t)base_ptr;\n+ desc.length = alloc_size;\n desc.name = location;\n desc.shm_name = serializeBinaryData(&handle, sizeof(hipIpcMemHandle_t));\n #ifdef ENABLE_MULTI_PROTOCOL\n desc.protocol = \"hip\";\n #endif\n- return metadata_->addLocalMemoryBuffer(desc, true);\n+ int rc = metadata_->addLocalMemoryBuffer(desc, true);\n+ if (rc == 0) {\n+ registered_base_refs_[base] = 1;\n+ } else {\n+ // addLocalMemoryBuffer appends the desc before publishing it;\n+ // drop the leftover so a failed registration leaves nothing\n+ // behind for a later rollback or unregister to miss.\n+ metadata_->removeLocalMemoryBuffer((void*)base, isOwnDesc, false);\n+ registered_addr_to_base_.erase((uint64_t)addr);\n+ }\n+ return rc;\n }\n \n // Fabric memory registration\n@@ -716,6 +770,7 @@ int HipTransport::registerLocalMemory(void* addr, size_t length,\n LOG(WARNING) << \"Memory region \" << addr\n << \" is not allocated by hipMemCreate, \"\n << \"but it can be used as local buffer\";\n+ skipped_addrs_.insert((uint64_t)addr);\n return 0;\n }\n \n@@ -732,15 +787,38 @@ int HipTransport::registerLocalMemory(void* addr, size_t length,\n real_size = (length + granularity - 1) & ~(granularity - 1);\n }\n \n+ // Sub-ranges of one allocation share its page-granular registration.\n+ // Track aliases and reference-count them like the IPC path so an\n+ // unregister cannot consume another alias's registration. The\n+ // shareable handle for the page is exported only once, so drop the\n+ // retained allocation handle on these fast paths.\n+ uint64_t page = (uint64_t)real_addr;\n+ if (!registered_addr_to_base_.emplace((uint64_t)addr, page).second) {\n+ (void)hipMemRelease(handle);\n+ return 0;\n+ }\n+ auto refs_it = registered_base_refs_.find(page);\n+ if (refs_it != registered_base_refs_.end()) {\n+ refs_it->second++;\n+ (void)hipMemRelease(handle);\n+ return 0;\n+ }\n+\n // Export shareable handle\n hipxFabricHandle export_handle_raw = {};\n if (!checkHip(\n hipMemExportToShareableHandle(&export_handle_raw, handle,\n HIPX_MEM_HANDLE_TYPE_FABRIC, 0),\n \"HipTransport: hipMemExportToShareableHandle failed\")) {\n+ registered_addr_to_base_.erase((uint64_t)addr);\n+ (void)hipMemRelease(handle);\n return -1;\n }\n export_handle_raw.pid = getpid();\n+ // The shareable handle keeps the allocation alive on its own; drop\n+ // the reference taken above so registrations do not accumulate\n+ // retains over the process lifetime.\n+ (void)hipMemRelease(handle);\n \n (void)remote_accessible;\n BufferDesc desc;\n@@ -749,12 +827,54 @@ int HipTransport::registerLocalMemory(void* addr, size_t length,\n desc.name = location;\n desc.shm_name = serializeBinaryData((const void*)&export_handle_raw,\n sizeof(hipxFabricHandle));\n- return metadata_->addLocalMemoryBuffer(desc, true);\n+#ifdef ENABLE_MULTI_PROTOCOL\n+ desc.protocol = \"hip\";\n+#endif\n+ int rc = metadata_->addLocalMemoryBuffer(desc, true);\n+ if (rc == 0) {\n+ registered_base_refs_[page] = 1;\n+ } else {\n+ // addLocalMemoryBuffer appends the desc before publishing it;\n+ // drop the leftover so a failed registration leaves nothing\n+ // behind for a later rollback or unregister to miss.\n+ metadata_->removeLocalMemoryBuffer(real_addr, isOwnDesc, false);\n+ registered_addr_to_base_.erase((uint64_t)addr);\n+ }\n+ return rc;\n }\n }\n \n int HipTransport::unregisterLocalMemory(void* addr, bool update_metadata) {\n- return metadata_->removeLocalMemoryBuffer(addr, update_metadata);\n+ // Hold register_mutex_ through the metadata removal, mirroring the\n+ // register path, so a concurrent register of another sub-range cannot\n+ // republish the buffer in between.\n+ std::lock_guard lock(register_mutex_);\n+ auto alias_it = registered_addr_to_base_.find((uint64_t)addr);\n+ if (alias_it == registered_addr_to_base_.end()) {\n+ // The address is not one we registered. If it equals a live base or\n+ // page, slab-level cleanup must not drop the shared registration\n+ // while its aliases are still alive.\n+ if (registered_base_refs_.count((uint64_t)addr)) {\n+ return ERR_ADDRESS_NOT_REGISTERED;\n+ }\n+ // Skipped registrations belong to another transport; addresses we\n+ // never saw are invalid or repeated unregisters.\n+ if (skipped_addrs_.erase((uint64_t)addr) > 0) {\n+ return 0;\n+ }\n+ return ERR_ADDRESS_NOT_REGISTERED;\n+ }\n+ uint64_t base = alias_it->second;\n+ registered_addr_to_base_.erase(alias_it);\n+ skipped_addrs_.erase((uint64_t)addr);\n+ // Both maps are updated in pairs under this mutex, so the base always\n+ // has a refcount entry here. Only the last alias removes the shared\n+ // registration, whether it is keyed by IPC allocation base or fabric\n+ // physical page.\n+ if (--registered_base_refs_[base] > 0) return 0;\n+ registered_base_refs_.erase(base);\n+ return metadata_->removeLocalMemoryBuffer((void*)base, isOwnDesc,\n+ update_metadata);\n }\n \n int HipTransport::relocateSharedMemoryAddress(uint64_t& dest_addr,\ndiff --git a/mooncake-transfer-engine/src/transport/rdma_transport/rdma_transport.cpp b/mooncake-transfer-engine/src/transport/rdma_transport/rdma_transport.cpp\nindex ce7c855ff6..ea30b1225f 100644\n--- a/mooncake-transfer-engine/src/transport/rdma_transport/rdma_transport.cpp\n+++ b/mooncake-transfer-engine/src/transport/rdma_transport/rdma_transport.cpp\n@@ -47,6 +47,22 @@\n \n namespace mooncake {\n \n+namespace {\n+\n+// Mirrors the ownership test the submit path already uses (see the\n+// buffer.protocol checks below): descs published by this transport, plus\n+// legacy descs with no protocol field. Without this, RDMA's removal can\n+// erase a same-address desc belonging to HIP/nvlink, which now filter.\n+bool isOwnRdmaDesc(const TransferMetadata::BufferDesc &desc) {\n+#ifdef ENABLE_MULTI_PROTOCOL\n+ return desc.protocol.empty() || desc.protocol == \"rdma\";\n+#else\n+ return desc.shm_name.empty();\n+#endif\n+}\n+\n+} // namespace\n+\n static bool MCIbRelaxedOrderingEnabled = false;\n static int MCIbRelaxedOrderingMode = 2;\n \n@@ -583,7 +599,7 @@ int RdmaTransport::registerLocalMemoryInternal(void *addr, size_t length,\n size_t n = std::min(committed, chunks.size());\n for (size_t ri = 0; ri < n; ++ri) {\n int rc = metadata_->removeLocalMemoryBuffer(\n- chunks[ri].first, /*update_metadata=*/false);\n+ chunks[ri].first, isOwnRdmaDesc, /*update_metadata=*/false);\n if (rc)\n LOG(WARNING) << \"Rollback: failed to remove metadata for chunk \"\n \"at \"\n@@ -792,7 +808,8 @@ int RdmaTransport::unregisterLocalMemoryInternal(void *addr,\n // chunk); publish once after all removals, below.\n for (uint64_t ca : chunk_addrs) {\n int rc = metadata_->removeLocalMemoryBuffer(\n- reinterpret_cast(ca), /*update_metadata=*/false);\n+ reinterpret_cast(ca), isOwnRdmaDesc,\n+ /*update_metadata=*/false);\n // ERR_ADDRESS_NOT_REGISTERED means an earlier attempt already\n // removed this chunk's metadata and then failed partway through\n // deregistration: tolerate it so the retry reaches the MR cleanup.\n@@ -854,7 +871,8 @@ int RdmaTransport::unregisterLocalMemoryInternal(void *addr,\n return first_err;\n }\n \n- int rc = metadata_->removeLocalMemoryBuffer(addr, update_metadata);\n+ int rc = metadata_->removeLocalMemoryBuffer(addr, isOwnRdmaDesc,\n+ update_metadata);\n // A missing metadata entry does NOT prove the MRs are gone: a partial\n // ibv_dereg_mr failure on an earlier attempt leaves live MRs behind it.\n // But a missing entry also occurs for an address that was never a\ndiff --git a/mooncake-transfer-engine/src/transport/tcp_transport/tcp_transport.cpp b/mooncake-transfer-engine/src/transport/tcp_transport/tcp_transport.cpp\nindex ca69c3c5eb..02194435d0 100644\n--- a/mooncake-transfer-engine/src/transport/tcp_transport/tcp_transport.cpp\n+++ b/mooncake-transfer-engine/src/transport/tcp_transport/tcp_transport.cpp\n@@ -486,7 +486,18 @@ int TcpTransport::registerLocalMemory(void* addr, size_t length,\n }\n \n int TcpTransport::unregisterLocalMemory(void* addr, bool update_metadata) {\n- return metadata_->removeLocalMemoryBuffer(addr, update_metadata);\n+ // Remove only the descs this transport published. Under multi-protocol\n+ // the protocol field is authoritative; otherwise ours are the entries\n+ // without a serialized IPC handle.\n+ static const std::function own_desc =\n+ [](const BufferDesc& desc) {\n+#ifdef ENABLE_MULTI_PROTOCOL\n+ return desc.protocol == \"tcp\";\n+#else\n+ return desc.shm_name.empty();\n+#endif\n+ };\n+ return metadata_->removeLocalMemoryBuffer(addr, own_desc, update_metadata);\n }\n \n int TcpTransport::registerLocalMemoryBatch(\ndiff --git a/mooncake-wheel/tests/test_transfer_sub_allocation_on_hip.py b/mooncake-wheel/tests/test_transfer_sub_allocation_on_hip.py\nnew file mode 100644\nindex 0000000000..47f665fc1d\n--- /dev/null\n+++ b/mooncake-wheel/tests/test_transfer_sub_allocation_on_hip.py\n@@ -0,0 +1,223 @@\n+\"\"\"Cross-process HIP IPC transfer of sub-allocated device buffers.\n+\n+hipIpcGetMemHandle exports the whole allocation, so a buffer registered as a\n+sub-range of one must still read back its own bytes and not the bytes at the\n+allocation base. Two processes are required: a loopback transfer inside a single\n+process never opens an IPC handle.\n+\"\"\"\n+\n+import multiprocessing as mp\n+import queue\n+import unittest\n+\n+import torch\n+\n+BUFFERS = 4\n+NBYTES = 1024 * 1024\n+EXPECTED = [i + 1 for i in range(BUFFERS)]\n+TIMEOUT = 120\n+\n+\n+def _engine():\n+ from mooncake.engine import TransferEngine\n+\n+ engine = TransferEngine()\n+ assert engine.initialize(\"127.0.0.1\", \"P2PHANDSHAKE\", \"hip\", \"\") == 0\n+ return engine\n+\n+\n+def _sub_ranges_of_one_allocation():\n+ torch.cuda.set_device(0)\n+ pool = torch.zeros(BUFFERS * NBYTES, dtype=torch.uint8, device=\"cuda:0\")\n+ return [pool[i * NBYTES : (i + 1) * NBYTES] for i in range(BUFFERS)]\n+\n+\n+def _source(meta, done, result):\n+ try:\n+ views = _sub_ranges_of_one_allocation()\n+ for view, value in zip(views, EXPECTED):\n+ view.fill_(value)\n+ torch.cuda.synchronize()\n+\n+ engine = _engine()\n+ addresses = [view.data_ptr() for view in views]\n+ rc = engine.batch_register_memory(addresses, [NBYTES] * BUFFERS)\n+ assert rc == 0, f\"batch_register_memory returned {rc}\"\n+\n+ meta.put((f\"127.0.0.1:{engine.get_rpc_port()}\", addresses))\n+ done.get(timeout=TIMEOUT)\n+\n+ # `views` is still alive, so this is last-alias teardown of the shared\n+ # registration, not an unregister-after-free.\n+ rc = engine.batch_unregister_memory(addresses)\n+ assert rc == 0, f\"batch_unregister_memory returned {rc}\"\n+ result.put((\"source\", None))\n+ except Exception as e: # noqa: BLE001\n+ result.put((\"source\", str(e)))\n+\n+\n+def _sink(meta, result):\n+ try:\n+ segment, addresses = meta.get(timeout=TIMEOUT)\n+ views = _sub_ranges_of_one_allocation()\n+\n+ engine = _engine()\n+ rc = engine.batch_register_memory(\n+ [view.data_ptr() for view in views], [NBYTES] * BUFFERS\n+ )\n+ assert rc == 0, f\"batch_register_memory returned {rc}\"\n+ for view, address in zip(views, addresses):\n+ read = engine.transfer_sync_read(segment, view.data_ptr(), address, NBYTES)\n+ assert read == 0, f\"transfer_sync_read returned {read}\"\n+ torch.cuda.synchronize()\n+\n+ observed = []\n+ for view in views:\n+ value = int(view[0])\n+ observed.append(value if bool(torch.all(view == value)) else \"mixed\")\n+\n+ # Report the payload before unregistering so a failure below surfaces\n+ # as itself, not as a missing result.\n+ result.put((\"sink\", observed))\n+ rc = engine.batch_unregister_memory([view.data_ptr() for view in views])\n+ assert rc == 0, f\"batch_unregister_memory returned {rc}\"\n+ result.put((\"sink\", None))\n+ except Exception as e: # noqa: BLE001\n+ result.put((\"sink\", str(e)))\n+\n+\n+def _alias_lifecycle(result):\n+ try:\n+ torch.cuda.set_device(0)\n+ # Offset into the allocation so no sub-range starts at its base.\n+ pool = torch.zeros((BUFFERS + 1) * NBYTES, dtype=torch.uint8, device=\"cuda:0\")\n+ views = [pool[(i + 1) * NBYTES : (i + 2) * NBYTES] for i in range(BUFFERS)]\n+ engine = _engine()\n+ addresses = [view.data_ptr() for view in views]\n+\n+ for address in addresses:\n+ assert engine.register_memory(address, NBYTES) == 0\n+\n+ # A double unregister of one alias fails but must not consume\n+ # another alias's reference on the shared registration.\n+ assert engine.unregister_memory(addresses[0]) == 0\n+ assert engine.unregister_memory(addresses[0]) != 0\n+ for address in addresses[1:]:\n+ assert engine.unregister_memory(address) == 0\n+\n+ # The last unregister removed the registration, so no alias of the\n+ # allocation can be released again.\n+ assert engine.unregister_memory(addresses[-1]) != 0\n+ result.put((\"alias\", None))\n+ except Exception as e: # noqa: BLE001\n+ result.put((\"alias\", str(e)))\n+\n+\n+def _base_alias_lifecycle(result):\n+ try:\n+ torch.cuda.set_device(0)\n+ # The first sub-range starts at the allocation base, so HIP's\n+ # base-keyed entry and the caller-keyed entries published by the\n+ # other transports share an address.\n+ views = _sub_ranges_of_one_allocation()\n+ engine = _engine()\n+ addresses = [view.data_ptr() for view in views]\n+\n+ for address in addresses:\n+ assert engine.register_memory(address, NBYTES) == 0\n+\n+ # A double unregister of the base-address view must fail without\n+ # disturbing the entries the other aliases still hold (#3548 review:\n+ # the transports used to delete each other's same-address entries).\n+ assert engine.unregister_memory(addresses[0]) == 0\n+ assert engine.unregister_memory(addresses[0]) != 0\n+ for address in addresses[1:]:\n+ assert engine.unregister_memory(address) == 0\n+\n+ # The registration is fully torn down; every alias now fails.\n+ assert engine.unregister_memory(addresses[-1]) != 0\n+ result.put((\"base_alias\", None))\n+ except Exception as e: # noqa: BLE001\n+ result.put((\"base_alias\", str(e)))\n+\n+\n+class TestTransferSubAllocationOnHip(unittest.TestCase):\n+ def setUp(self):\n+ if not torch.cuda.is_available():\n+ raise unittest.SkipTest(\"ROCm device not available\")\n+ if not getattr(torch.version, \"hip\", None):\n+ raise unittest.SkipTest(\"PyTorch is not built with HIP support\")\n+\n+ def test_each_sub_range_reads_its_own_bytes(self):\n+ # spawn: the children initialize HIP, which a forked process cannot do.\n+ ctx = mp.get_context(\"spawn\")\n+ meta, done, result = ctx.Queue(), ctx.Queue(), ctx.Queue()\n+ source = ctx.Process(target=_source, args=(meta, done, result))\n+ sink = ctx.Process(target=_sink, args=(meta, result))\n+ source.start()\n+ sink.start()\n+ observed = None\n+ try:\n+ finished = set()\n+ while len(finished) < 2:\n+ who, payload = result.get(timeout=TIMEOUT)\n+ if isinstance(payload, str):\n+ self.fail(f\"{who} failed: {payload}\")\n+ if payload is not None:\n+ observed = payload\n+ # Transfers are done; let the source tear down its\n+ # registration while its tensors are still alive.\n+ done.put(True)\n+ else:\n+ finished.add(who)\n+ except queue.Empty:\n+ self.fail(f\"no result: source={source.exitcode} sink={sink.exitcode}\")\n+ finally:\n+ done.put(True)\n+ for process in (sink, source):\n+ process.join(TIMEOUT)\n+ if process.is_alive():\n+ process.terminate()\n+ process.join()\n+\n+ self.assertEqual(observed, EXPECTED)\n+\n+ def test_alias_registration_lifecycle(self):\n+ ctx = mp.get_context(\"spawn\")\n+ result = ctx.Queue()\n+ child = ctx.Process(target=_alias_lifecycle, args=(result,))\n+ child.start()\n+ try:\n+ _, payload = result.get(timeout=TIMEOUT)\n+ except queue.Empty:\n+ self.fail(f\"no result: exitcode={child.exitcode}\")\n+ finally:\n+ child.join(TIMEOUT)\n+ if child.is_alive():\n+ child.terminate()\n+ child.join()\n+\n+ if payload is not None:\n+ self.fail(f\"alias failed: {payload}\")\n+\n+ def test_base_address_view_double_unregister(self):\n+ ctx = mp.get_context(\"spawn\")\n+ result = ctx.Queue()\n+ child = ctx.Process(target=_base_alias_lifecycle, args=(result,))\n+ child.start()\n+ try:\n+ _, payload = result.get(timeout=TIMEOUT)\n+ except queue.Empty:\n+ self.fail(f\"no result: exitcode={child.exitcode}\")\n+ finally:\n+ child.join(TIMEOUT)\n+ if child.is_alive():\n+ child.terminate()\n+ child.join()\n+\n+ if payload is not None:\n+ self.fail(f\"base_alias failed: {payload}\")\n+\n+\n+if __name__ == \"__main__\":\n+ unittest.main()\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: kvcache-ai/Mooncake\nPull request: [Bugfix] Recover classic RDMA contexts when PORT_ACTIVE is missed\nLabels: run-ci, Transfer Engine, P1\nFiles changed (6): mooncake-transfer-engine/include/transport/rdma_transport/rdma_context.h, mooncake-transfer-engine/include/transport/rdma_transport/worker_pool.h, mooncake-transfer-engine/src/transport/rdma_transport/rdma_context.cpp, mooncake-transfer-engine/src/transport/rdma_transport/worker_pool.cpp, mooncake-transfer-engine/tests/CMakeLists.txt, mooncake-transfer-engine/tests/worker_pool_rail_state_test.cpp\n\n## Description (results removed)\n\n## Description\n\nFixes #4694.\n\nA classic `WorkerPool` that processes `IBV_EVENT_PORT_ERR` disables its\ncontext and disconnects endpoints. The only thing that arms recovery\nafterwards is the `IBV_EVENT_PORT_ACTIVE` branch. If that event is\nnever read, `recovery_activate_after_ns_` stays 0, `maybeActivateRecoveredContext()`\nis a no-op, and the rail stays inactive until the process restarts.\n\n#3799 already added this safety net for TENT (`Workers::resumePausedContexts()`,\na 1 Hz `ibv_query_port`). Classic still drains the async fd, but it\nnever got the poll.\n\n## What changed\n\n- Add `RdmaContext::queryPortState()` for the classic engine.\n- On the 1 Hz monitor tick, if the context is inactive because of a\n fatal async event and no recovery is armed, query the port.\n- On `IBV_PORT_ACTIVE`, call `scheduleContextRecovery()` so the\n existing 30 s delayed GID probe from #2959 still decides when the\n RNIC is reused. Intermediate port states stay inactive.\n- Do not steal a breaker-owned pause: local-WC TTL recovery still owns\n that path.\n- Hardware-free unit tests via `WorkerPoolTestPeer` and `--wrap` of\n `queryPortState`. No IB device required.\n\n@ironashram this follows the fix you outlined on #4694. Sorry I opened it without checking with you first. You wrote that you were happy to send the PR yourself — if you still want to, say so and I will close this one so you can take it.\n\n## Test plan\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/mooncake-transfer-engine/include/transport/rdma_transport/rdma_context.h b/mooncake-transfer-engine/include/transport/rdma_transport/rdma_context.h\nindex 642ca255b0..db4ad13499 100644\n--- a/mooncake-transfer-engine/include/transport/rdma_transport/rdma_context.h\n+++ b/mooncake-transfer-engine/include/transport/rdma_transport/rdma_context.h\n@@ -276,6 +276,12 @@ class RdmaContext {\n GidRefreshResult refreshCurrentGid(std::string *previous_gid = nullptr,\n std::string *next_gid = nullptr);\n \n+ // Read the port's current state from the hardware. The monitor worker\n+ // polls this for event-disabled contexts so a link that came back without\n+ // a usable IBV_EVENT_PORT_ACTIVE is still noticed. Returns -1 and leaves\n+ // *state untouched if no device is open or the query fails.\n+ int queryPortState(ibv_port_state *state) const;\n+\n ibv_context *context() const { return context_; }\n \n RdmaTransport &engine() const { return engine_; }\ndiff --git a/mooncake-transfer-engine/include/transport/rdma_transport/worker_pool.h b/mooncake-transfer-engine/include/transport/rdma_transport/worker_pool.h\nindex aeb6b287b8..6dbb474ca5 100644\n--- a/mooncake-transfer-engine/include/transport/rdma_transport/worker_pool.h\n+++ b/mooncake-transfer-engine/include/transport/rdma_transport/worker_pool.h\n@@ -97,8 +97,17 @@ class WorkerPool {\n GidRefreshResult refreshPublishedLocalGid();\n bool handleContextEvent(ibv_event_type event_type, bool injected_for_test,\n struct ibv_async_event *event = nullptr);\n- void scheduleContextRecovery(uint64_t delay_ns = kContextRecoveryDelayNs);\n+ void scheduleContextRecovery(uint64_t delay_ns = kContextRecoveryDelayNs,\n+ bool override_breaker = true);\n void maybeActivateRecoveredContext();\n+ // Safety net for a PORT_ERR whose PORT_ACTIVE never arrived. At most the\n+ // 1 Hz monitor tick calls this, and only when context_disabling_event_\n+ // is IBV_EVENT_PORT_ERR. On IBV_PORT_ACTIVE it arms the same delayed GID\n+ // probe as the event path. DEVICE_FATAL, CQ_ERR, WQ_FATAL and LID_CHANGE\n+ // stay inactive: the probe does not rebuild a failed CQ or device.\n+ // Breaker-owned pauses are left alone so TTL reactivation still owns\n+ // local-WC downtime.\n+ void resumePausedContext();\n bool hasAvailablePeerRailAlternative(Transport::Slice *slice,\n const std::string &failed_peer_path);\n \n@@ -153,6 +162,9 @@ class WorkerPool {\n \n std::atomic submitted_slice_count_, processed_slice_count_;\n std::atomic recovery_activate_after_ns_{0};\n+ // Fatal async event that owns the inactive context, or -1 when none does.\n+ // The 1 Hz port poll resumes only IBV_EVENT_PORT_ERR.\n+ std::atomic context_disabling_event_{-1};\n \n // Rail state management: peer_nic_path -> RailState\n std::unordered_map rail_states_;\ndiff --git a/mooncake-transfer-engine/src/transport/rdma_transport/rdma_context.cpp b/mooncake-transfer-engine/src/transport/rdma_transport/rdma_context.cpp\nindex da6a30384a..f8bc58f9ca 100644\n--- a/mooncake-transfer-engine/src/transport/rdma_transport/rdma_context.cpp\n+++ b/mooncake-transfer-engine/src/transport/rdma_transport/rdma_context.cpp\n@@ -1520,6 +1520,18 @@ GidRefreshResult RdmaContext::refreshCurrentGid(std::string *previous_gid,\n return GidRefreshResult::CHANGED;\n }\n \n+int RdmaContext::queryPortState(ibv_port_state *state) const {\n+ if (!state || !context_) return -1;\n+ ibv_port_attr port_attr;\n+ if (ibv_query_port(context_, port_, &port_attr)) {\n+ PLOG(WARNING) << \"Failed to query state of port \"\n+ << static_cast(port_) << \" on \" << device_name_;\n+ return -1;\n+ }\n+ *state = port_attr.state;\n+ return 0;\n+}\n+\n int RdmaContext::openRdmaDevice(const std::string &device_name, uint8_t port,\n int gid_index) {\n int num_devices = 0;\ndiff --git a/mooncake-transfer-engine/src/transport/rdma_transport/worker_pool.cpp b/mooncake-transfer-engine/src/transport/rdma_transport/worker_pool.cpp\nindex 6306b5be65..732d5add4e 100644\n--- a/mooncake-transfer-engine/src/transport/rdma_transport/worker_pool.cpp\n+++ b/mooncake-transfer-engine/src/transport/rdma_transport/worker_pool.cpp\n@@ -537,6 +537,7 @@ bool WorkerPool::tryReactivateContext(uint64_t now_ns) {\n }\n breaker_reactivate_after_ns_ = 0;\n context_failure_count_.store(0, std::memory_order_relaxed);\n+ context_disabling_event_.store(-1, std::memory_order_relaxed);\n context_.set_active(true);\n return true;\n }\n@@ -554,6 +555,8 @@ void WorkerPool::resetContextBreaker(bool context_active) {\n std::lock_guard lock(context_state_lock_);\n breaker_reactivate_after_ns_ = 0;\n context_failure_count_.store(0, std::memory_order_relaxed);\n+ if (context_active)\n+ context_disabling_event_.store(-1, std::memory_order_relaxed);\n context_.set_active(context_active);\n }\n \n@@ -1325,8 +1328,11 @@ bool WorkerPool::handleContextEvent(ibv_event_type event_type,\n recovery_activate_after_ns_.store(0, std::memory_order_relaxed);\n // The async event now owns this context's inactive state. Clear the\n // local-WC breaker deadline so its TTL cannot resurrect a context that\n- // a DEVICE_FATAL/PORT_ERR took down.\n+ // a DEVICE_FATAL/PORT_ERR took down. Remember which event it was: the\n+ // 1 Hz port poll may resume only PORT_ERR.\n resetContextBreaker(false);\n+ context_disabling_event_.store(static_cast(event_type),\n+ std::memory_order_relaxed);\n refreshPublishedLocalTopology();\n \n /**\n@@ -1377,12 +1383,16 @@ bool WorkerPool::handleContextEvent(ibv_event_type event_type,\n return true;\n }\n \n-void WorkerPool::scheduleContextRecovery(uint64_t delay_ns) {\n+void WorkerPool::scheduleContextRecovery(uint64_t delay_ns,\n+ bool override_breaker) {\n std::lock_guard lock(context_state_lock_);\n // A redundant PORT_ACTIVE on an in-service context is not recovery\n // evidence: preserve its local-WC streak and do not arm a probe that\n // could later override a new local-WC trip.\n if (context_.active()) return;\n+ // The 1 Hz port poll must not steal a breaker-owned pause: the port is\n+ // expected to still be ACTIVE while local-WC TTL recovery runs.\n+ if (!override_breaker && breaker_reactivate_after_ns_ != 0) return;\n \n // Event recovery owns this inactive period. Cancel only the breaker\n // deadline; a successful GID probe below resets the failure count.\n@@ -1429,6 +1439,36 @@ void WorkerPool::maybeActivateRecoveredContext() {\n << \" is now active after recovery delay\";\n }\n \n+void WorkerPool::resumePausedContext() {\n+ if (context_.active()) return;\n+ if (recovery_activate_after_ns_.load(std::memory_order_relaxed) != 0)\n+ return;\n+ {\n+ std::lock_guard lock(context_state_lock_);\n+ if (breaker_reactivate_after_ns_ != 0) return;\n+ }\n+ // CQ_ERR / DEVICE_FATAL / WQ_FATAL / LID_CHANGE leave the same inactive\n+ // state, but the port is often still ACTIVE. Republishing that RNIC does\n+ // not rebuild the failed CQ or device, so only a missed PORT_ACTIVE is\n+ // eligible for this poll.\n+ if (context_disabling_event_.load(std::memory_order_relaxed) !=\n+ static_cast(IBV_EVENT_PORT_ERR))\n+ return;\n+\n+ ibv_port_state state;\n+ if (context_.queryPortState(&state) != 0) return;\n+ // Only a fully active port carries traffic. Intermediate states\n+ // (INIT/ARMED/ACTIVE_DEFER) mean the link is still settling, so leave\n+ // the context inactive and re-check on the next tick.\n+ if (state != IBV_PORT_ACTIVE) return;\n+\n+ LOG(WARNING) << \"Worker: Context \" << context_.deviceName()\n+ << \" port reports ACTIVE without an IBV_EVENT_PORT_ACTIVE \"\n+ \"event\";\n+ scheduleContextRecovery(kContextRecoveryDelayNs,\n+ /*override_breaker=*/false);\n+}\n+\n bool WorkerPool::hasAvailablePeerRailAlternative(\n Transport::Slice *slice, const std::string &failed_peer_path) {\n auto peer_segment_desc =\n@@ -1524,6 +1564,9 @@ void WorkerPool::monitorWorker() {\n // Drop expired active-connect pause entries so the map doesn't grow\n // for peers that are never re-attempted after their pause lapses.\n context_.pruneConnectPause();\n+ // Safety net for a recovery event that never reached us. See\n+ // issue #4694; TENT's equivalent is Workers::resumePausedContexts.\n+ resumePausedContext();\n last_reset_ts = current_ts;\n }\n \ndiff --git a/mooncake-transfer-engine/tests/worker_pool_rail_state_test.cpp b/mooncake-transfer-engine/tests/worker_pool_rail_state_test.cpp\nindex db1129c601..7aeaeb2aa1 100644\n--- a/mooncake-transfer-engine/tests/worker_pool_rail_state_test.cpp\n+++ b/mooncake-transfer-engine/tests/worker_pool_rail_state_test.cpp\n@@ -63,6 +63,7 @@ using namespace mooncake;\n #ifdef __linux__\n namespace {\n std::function gid_probe;\n+std::function port_state_probe;\n }\n \n // Wrap the device probe, leaving the actual WorkerPool recovery path intact.\n@@ -74,6 +75,13 @@ extern \"C\" GidRefreshResult wrapRefreshCurrentGid(RdmaContext *, std::string *,\n std::string *) {\n return gid_probe ? gid_probe() : GidRefreshResult::FAILED;\n }\n+\n+extern \"C\" int\n+wrapQueryPortState(const RdmaContext *, ibv_port_state *state) asm(\n+ \"__wrap__ZNK8mooncake11RdmaContext14queryPortStateEP14ibv_port_state\");\n+extern \"C\" int wrapQueryPortState(const RdmaContext *, ibv_port_state *state) {\n+ return port_state_probe ? port_state_probe(state) : -1;\n+}\n #endif\n \n namespace mooncake {\n@@ -170,6 +178,10 @@ class WorkerPoolTestPeer {\n pool.maybeActivateRecoveredContext();\n }\n \n+ static void resumePausedContext(WorkerPool &pool) {\n+ pool.resumePausedContext();\n+ }\n+\n static int contextFailureThreshold() {\n return WorkerPool::kLocalCompletionFailureThreshold;\n }\n@@ -206,6 +218,7 @@ class WorkerPoolRailStateTest : public ::testing::Test {\n void TearDown() override {\n #ifdef __linux__\n gid_probe = {};\n+ port_state_probe = {};\n #endif\n worker_pool_.reset();\n context_.reset();\n@@ -538,6 +551,98 @@ TEST_F(WorkerPoolRailStateTest, FatalEventCancelsPendingGidProbe) {\n EXPECT_FALSE(\n WorkerPoolTestPeer::tryReactivateContext(*worker_pool_, UINT64_MAX));\n }\n+\n+TEST_F(WorkerPoolRailStateTest,\n+ PortPollArmsRecoveryWhenPortActiveEventIsMissed) {\n+ WorkerPoolTestPeer::contextEvent(*worker_pool_, IBV_EVENT_PORT_ERR);\n+ ASSERT_FALSE(WorkerPoolTestPeer::contextActive(*worker_pool_));\n+ ASSERT_EQ(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), 0u);\n+\n+ port_state_probe = [](ibv_port_state *state) {\n+ *state = IBV_PORT_DOWN;\n+ return 0;\n+ };\n+ WorkerPoolTestPeer::resumePausedContext(*worker_pool_);\n+ EXPECT_EQ(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), 0u);\n+\n+ port_state_probe = [](ibv_port_state *state) {\n+ *state = IBV_PORT_INIT;\n+ return 0;\n+ };\n+ WorkerPoolTestPeer::resumePausedContext(*worker_pool_);\n+ EXPECT_EQ(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), 0u);\n+\n+ port_state_probe = [](ibv_port_state *state) {\n+ *state = IBV_PORT_ACTIVE;\n+ return 0;\n+ };\n+ WorkerPoolTestPeer::resumePausedContext(*worker_pool_);\n+ EXPECT_NE(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), 0u);\n+ EXPECT_FALSE(WorkerPoolTestPeer::contextActive(*worker_pool_))\n+ << \"missed PORT_ACTIVE must reuse the delayed GID probe, not enable \"\n+ \"the context immediately\";\n+\n+ gid_probe = [] { return GidRefreshResult::UNCHANGED; };\n+ WorkerPoolTestPeer::setRecoveryActivateAfter(*worker_pool_, 1);\n+ WorkerPoolTestPeer::recoverContext(*worker_pool_);\n+ EXPECT_TRUE(WorkerPoolTestPeer::contextActive(*worker_pool_));\n+ EXPECT_EQ(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), 0u);\n+}\n+\n+TEST_F(WorkerPoolRailStateTest, PortPollLeavesNonPortErrFatalEventsInactive) {\n+ port_state_probe = [](ibv_port_state *state) {\n+ *state = IBV_PORT_ACTIVE;\n+ return 0;\n+ };\n+ const ibv_event_type events[] = {\n+ IBV_EVENT_DEVICE_FATAL,\n+ IBV_EVENT_CQ_ERR,\n+ IBV_EVENT_WQ_FATAL,\n+ IBV_EVENT_LID_CHANGE,\n+ };\n+ for (ibv_event_type event : events) {\n+ WorkerPoolTestPeer::contextEvent(*worker_pool_, event);\n+ EXPECT_FALSE(WorkerPoolTestPeer::contextActive(*worker_pool_));\n+ EXPECT_EQ(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), 0u);\n+ WorkerPoolTestPeer::resumePausedContext(*worker_pool_);\n+ EXPECT_EQ(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), 0u)\n+ << ibv_event_type_str(event);\n+ EXPECT_FALSE(WorkerPoolTestPeer::contextActive(*worker_pool_))\n+ << ibv_event_type_str(event);\n+ }\n+}\n+\n+TEST_F(WorkerPoolRailStateTest, PortPollDoesNotStealBreakerOwnedPause) {\n+ WorkerPoolTestPeer::setContextActive(*worker_pool_, true);\n+ for (int i = 0; i < WorkerPoolTestPeer::contextFailureThreshold(); ++i)\n+ WorkerPoolTestPeer::markLocalContextFailure(*worker_pool_);\n+ ASSERT_FALSE(WorkerPoolTestPeer::contextActive(*worker_pool_));\n+ ASSERT_NE(WorkerPoolTestPeer::breakerReactivateAfter(*worker_pool_), 0u);\n+\n+ port_state_probe = [](ibv_port_state *state) {\n+ *state = IBV_PORT_ACTIVE;\n+ return 0;\n+ };\n+ WorkerPoolTestPeer::resumePausedContext(*worker_pool_);\n+ EXPECT_EQ(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), 0u);\n+ EXPECT_NE(WorkerPoolTestPeer::breakerReactivateAfter(*worker_pool_), 0u);\n+ EXPECT_FALSE(WorkerPoolTestPeer::contextActive(*worker_pool_));\n+}\n+\n+TEST_F(WorkerPoolRailStateTest, PortPollLeavesArmedEventRecoveryAlone) {\n+ WorkerPoolTestPeer::setContextActive(*worker_pool_, false);\n+ WorkerPoolTestPeer::contextEvent(*worker_pool_, IBV_EVENT_PORT_ACTIVE);\n+ const uint64_t armed =\n+ WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_);\n+ ASSERT_NE(armed, 0u);\n+\n+ port_state_probe = [](ibv_port_state *state) {\n+ *state = IBV_PORT_ACTIVE;\n+ return 0;\n+ };\n+ WorkerPoolTestPeer::resumePausedContext(*worker_pool_);\n+ EXPECT_EQ(WorkerPoolTestPeer::recoveryActivateAfter(*worker_pool_), armed);\n+}\n #endif\n \n } // namespace\n\n[1 documentation file diff(s) omitted]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/speculators\nPull request: Add unit tests, type annotations, and docstrings for train utilities (fixes #1092)\nLabels: ready\nFiles changed (2): src/speculators/train/vocab_mapping.py, tests/unit/train/test_vocab_mapping.py\n\n## Description (results removed)\n\n## Purpose\nFixes #1092 (vocab_mapping part). Adds missing unit tests, type annotations, and docstrings for `speculators.train.vocab_mapping`, plus small discrepancies found along the way:\n- `save_token_frequency_distribution()` now returns the saved `Path`, matching its docstring (previously returned `None`).\n- `__all__` in `vocab_mapping.py` now exports all four public functions.\n- `combine_token_frequency_distributions()`: fixed `Counter[str]` → `Counter[int]` typing.\n- `get_target_vocab_size()` gains type hints and a docstring; Optional args are narrowed directly so mypy can verify them.\nNote: `__all__` entries are sorted to satisfy the repo's RUF022 lint rule (slightly different order than suggested in the issue).\nNote: the `noise_transforms.py` part of the original scope was dropped on rebase — upstream #1211 removed noise transforms entirely (\"seen to not have an impact on training quality, while significantly slowing down data loading\").\n\n## Tests\n[results removed]\n## Checklist\n- [x] (Optional) The necessary documentation update. — docstrings added/updated in the touched module; no separate docs pages needed.\n\n## Diff\n\n```diff\ndiff --git a/src/speculators/train/vocab_mapping.py b/src/speculators/train/vocab_mapping.py\nindex ac1e5a302..11c82cc8c 100644\n--- a/src/speculators/train/vocab_mapping.py\n+++ b/src/speculators/train/vocab_mapping.py\n@@ -13,6 +13,8 @@\n \n __all__ = [\n \"build_vocab_mappings_from_distribution\",\n+ \"combine_token_frequency_distributions\",\n+ \"get_target_vocab_size\",\n \"save_token_frequency_distribution\",\n ]\n \n@@ -20,7 +22,7 @@\n def save_token_frequency_distribution(\n dataset: HFDataset,\n output_path: Path | str = \"./token_freq.pt\",\n-):\n+) -> Path:\n \"\"\"Save token frequency distribution from the dataset.\n \n Args:\n@@ -39,7 +41,7 @@ def save_token_frequency_distribution(\n \"it (or pass a different output path) when the dataset or target \"\n \"model changed.\"\n )\n- return\n+ return path\n \n token_freq: Counter[int] = Counter()\n for item in tqdm(dataset, desc=\"Counting token frequencies\"):\n@@ -54,6 +56,7 @@ def save_token_frequency_distribution(\n token_freq_dict = dict(token_freq)\n Path(path).parent.mkdir(parents=True, exist_ok=True)\n torch.save(token_freq_dict, path)\n+ return path\n \n \n def combine_token_frequency_distributions(\n@@ -64,7 +67,7 @@ def combine_token_frequency_distributions(\n token_freq_dicts = [\n torch.load(path, weights_only=True) for path in token_freq_paths\n ]\n- combined_token_freq: Counter[str] = Counter()\n+ combined_token_freq: Counter[int] = Counter()\n for token_freq_dict in token_freq_dicts:\n combined_token_freq.update(token_freq_dict)\n combined_token_freq_dict = dict(combined_token_freq)\n@@ -107,10 +110,26 @@ def build_vocab_mappings_from_distribution(\n \n \n def get_target_vocab_size(\n- target_vocab_size,\n- target_model_path,\n+ target_vocab_size: int | None,\n+ target_model_path: str | Path | None,\n trust_remote_code: bool = False,\n-):\n+) -> int:\n+ \"\"\"Resolve the target vocabulary size.\n+\n+ Args:\n+ target_vocab_size: Explicitly configured target vocabulary size, if any.\n+ target_model_path: HuggingFace model path to read the vocabulary size\n+ from when ``target_vocab_size`` is not given.\n+ trust_remote_code: Whether to trust remote code when loading the model\n+ config.\n+\n+ Returns:\n+ The resolved target vocabulary size.\n+\n+ Raises:\n+ ValueError: If both or neither of ``target_vocab_size`` and\n+ ``target_model_path`` are provided.\n+ \"\"\"\n has_vocab = target_vocab_size is not None\n has_model = target_model_path is not None\n \n@@ -120,9 +139,14 @@ def get_target_vocab_size(\n if not has_vocab and not has_model:\n raise ValueError(\"Must specify either target-vocab-size or target-model-path\")\n \n- if has_vocab:\n+ if target_vocab_size is not None:\n return target_vocab_size\n \n+ if target_model_path is None:\n+ # Unreachable: validated above, but needed for mypy narrowing since\n+ # it cannot narrow through the has_model boolean.\n+ raise ValueError(\"Must specify either target-vocab-size or target-model-path\")\n+\n config = AutoConfig.from_pretrained(\n target_model_path,\n trust_remote_code=trust_remote_code,\ndiff --git a/tests/unit/train/test_vocab_mapping.py b/tests/unit/train/test_vocab_mapping.py\nnew file mode 100644\nindex 000000000..56e5737eb\n--- /dev/null\n+++ b/tests/unit/train/test_vocab_mapping.py\n@@ -0,0 +1,103 @@\n+\"\"\"Tests for speculators.train.vocab_mapping.\"\"\"\n+\n+import torch\n+\n+from speculators.train.vocab_mapping import (\n+ build_vocab_mappings_from_distribution,\n+ combine_token_frequency_distributions,\n+ save_token_frequency_distribution,\n+)\n+\n+\n+class _FakeDataset:\n+ \"\"\"Minimal iterable stub exposing input_ids/loss_mask items.\"\"\"\n+\n+ def __init__(self, items):\n+ self._items = items\n+\n+ def __iter__(self):\n+ return iter(self._items)\n+\n+\n+def test_build_vocab_mappings_ranks_by_frequency():\n+ token_freq = {5: 10, 3: 20, 7: 5}\n+\n+ draft_to_target, target_to_draft = build_vocab_mappings_from_distribution(\n+ token_freq, draft_vocab_size=2, target_vocab_size=10\n+ )\n+\n+ # top-2 by frequency are tokens 3 and 5; offsets encode\n+ # target_id = draft_idx + draft_to_target[draft_idx]\n+ assert draft_to_target.tolist() == [3, 4]\n+ for draft_idx, offset in enumerate(draft_to_target.tolist()):\n+ assert draft_idx + offset in (3, 5)\n+ assert target_to_draft.dtype == torch.bool\n+ assert target_to_draft.tolist() == [\n+ False,\n+ False,\n+ False,\n+ True,\n+ False,\n+ True,\n+ False,\n+ False,\n+ False,\n+ False,\n+ ]\n+\n+\n+def test_build_vocab_mappings_pads_with_smallest_missing_ids():\n+ token_freq = {2: 5}\n+\n+ draft_to_target, target_to_draft = build_vocab_mappings_from_distribution(\n+ token_freq, draft_vocab_size=4, target_vocab_size=8\n+ )\n+\n+ # only token 2 observed: pad with 0, 1, 3 -> sorted [0, 1, 2, 3]\n+ assert draft_to_target.tolist() == [0, 0, 0, 0]\n+ for draft_idx, offset in enumerate(draft_to_target.tolist()):\n+ assert draft_idx + offset in (0, 1, 2, 3)\n+ assert target_to_draft.sum().item() == 4\n+\n+\n+def test_combine_token_frequency_distributions(tmp_path):\n+ first = tmp_path / \"freq1.pt\"\n+ second = tmp_path / \"freq2.pt\"\n+ out = tmp_path / \"combined.pt\"\n+ torch.save({1: 2, 2: 3}, first)\n+ torch.save({2: 4, 3: 5}, second)\n+\n+ combine_token_frequency_distributions([first, second], out)\n+\n+ assert torch.load(out, weights_only=True) == {1: 2, 2: 7, 3: 5}\n+\n+\n+def test_save_token_frequency_distribution_returns_path(tmp_path):\n+ dataset = _FakeDataset(\n+ [\n+ {\n+ \"input_ids\": torch.tensor([1, 2, 2, 3]),\n+ \"loss_mask\": torch.tensor([1, 1, 0, 1]),\n+ },\n+ {\n+ \"input_ids\": torch.tensor([2, 3, 3]),\n+ \"loss_mask\": torch.tensor([0, 1, 1]),\n+ },\n+ ]\n+ )\n+ out = tmp_path / \"freq.pt\"\n+\n+ result = save_token_frequency_distribution(dataset, out)\n+\n+ assert result == out\n+ assert torch.load(out, weights_only=True) == {1: 1, 2: 1, 3: 3}\n+\n+\n+def test_save_token_frequency_distribution_reuses_existing_file(tmp_path):\n+ out = tmp_path / \"freq.pt\"\n+ torch.save({9: 9}, out)\n+\n+ result = save_token_frequency_distribution(_FakeDataset([]), out)\n+\n+ assert result == out\n+ assert torch.load(out, weights_only=True) == {9: 9}\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/speculators\nPull request: fix(trainer): RuntimeError Allocator for npu is not a DeviceAllocator\nLabels: ready\nFiles changed (2): src/speculators/train/trainer.py, tests/unit/train/test_step_timer.py\n\n## Description (results removed)\n\n## Purpose\n\nFix the `RuntimeError: Allocator for npu is not a DeviceAllocator` in `_StepTimer.mark()` when running on Ascend NPU.\n\n`torch.accelerator.memory_allocated()` assumes the backend registers a `c10::CachingDeviceAllocator`. `torch_npu` registers its own `NPUCachingAllocator`, which does not inherit from the former. As a result, the generic accelerator API throws a `RuntimeError` instead of returning `0`. Previously, training would crash on the first `mark()` call of any instrumented step.\n\n## Testing\n[results removed]\n## Checklist\n\nI have filled in:\n\n---\n[image] [image]\nNeed help on this PR? Tag @codesmith-bot with what you need.\n\n## Diff\n\n```diff\ndiff --git a/src/speculators/train/trainer.py b/src/speculators/train/trainer.py\nindex f1eba103c..9a7297620 100644\n--- a/src/speculators/train/trainer.py\n+++ b/src/speculators/train/trainer.py\n@@ -80,7 +80,34 @@ def mark(self, name: str) -> None:\n torch.accelerator.synchronize()\n self._marks[name] = time.perf_counter()\n if torch.accelerator.is_available():\n- self._memory[name] = torch.accelerator.memory_allocated() / (1024**2)\n+ acc = torch.accelerator.current_accelerator()\n+ # torch.accelerator.memory_allocated() may raise on backends\n+ # whose allocator is not a c10::CachingDeviceAllocator (e.g.\n+ # Ascend NPU, where torch_npu registers its own\n+ # NPUCachingAllocator). Fall back to the backend-native API\n+ # via torch.. This assumes the backend\n+ # package (e.g. torch_npu) has already been imported by the\n+ # environment so that torch. is populated.\n+ try:\n+ mem_bytes = torch.accelerator.memory_allocated()\n+ except RuntimeError:\n+ if acc is None:\n+ root_logger.debug(\n+ \"accelerator is None, skipping memory tracking\"\n+ )\n+ return\n+ backend = getattr(torch, acc.type, None)\n+ if backend is None or not hasattr(backend, \"memory_allocated\"):\n+ root_logger.debug(\n+ \"no backend-native memory_allocated for %s, skipping\",\n+ acc.type,\n+ )\n+ return\n+ root_logger.debug(\n+ \"using backend-native memory_allocated for %s\", acc.type\n+ )\n+ mem_bytes = backend.memory_allocated()\n+ self._memory[name] = mem_bytes / (1024**2)\n \n def mark_value(self, name: str, value: float) -> None:\n if self.enabled:\ndiff --git a/tests/unit/train/test_step_timer.py b/tests/unit/train/test_step_timer.py\nindex 844333de8..42e6821ae 100644\n--- a/tests/unit/train/test_step_timer.py\n+++ b/tests/unit/train/test_step_timer.py\n@@ -141,3 +141,160 @@ def test_zero_step_ms_returns_zero_throughput():\n assert profile is not None\n assert profile[\"tokens_per_s\"] == 0.0\n assert profile[\"fetch_frac\"] == 0.0\n+\n+\n+class _FakeDevice:\n+ def __init__(self, device_type: str):\n+ self.type = device_type\n+\n+\n+class _StubBackend:\n+ \"\"\"Minimal stub backend module exposing ``memory_allocated``.\"\"\"\n+\n+ def __init__(self, mem_bytes: int) -> None:\n+ self._mem_bytes = mem_bytes\n+\n+ def memory_allocated(self) -> int:\n+ return self._mem_bytes\n+\n+\n+class _EmptyBackend:\n+ \"\"\"Stub backend with no ``memory_allocated`` attribute.\"\"\"\n+\n+\n+def test_memory_fallback_uses_backend_native_api():\n+ \"\"\"Generic accelerator API raises RuntimeError; falls back to backend-native.\n+\n+ This is a backend-agnostic fallback: when torch.accelerator.memory_allocated()\n+ fails on any device type, the code tries torch..memory_allocated()\n+ instead. We simulate this on a CPU-only CI by patching the accelerator\n+ APIs and injecting a stub backend module.\n+ \"\"\"\n+ stub_backend = _StubBackend(mem_bytes=42 * 1024**2) # 42 MiB\n+\n+ fake_device = _FakeDevice(\"fake_device\")\n+\n+ with (\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.is_available\",\n+ return_value=True,\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.current_accelerator\",\n+ return_value=fake_device,\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.memory_allocated\",\n+ side_effect=RuntimeError(\"Allocator is not a DeviceAllocator\"),\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.fake_device\",\n+ stub_backend,\n+ create=True,\n+ ),\n+ patch(\"speculators.train.trainer.torch.accelerator.synchronize\"),\n+ patch(\n+ \"speculators.train.trainer.time.perf_counter\",\n+ return_value=1.0,\n+ ),\n+ ):\n+ timer = _StepTimer(enabled=True)\n+ timer.mark(\"fwd\")\n+\n+ assert timer._memory[\"fwd\"] == 42.0\n+\n+\n+def test_memory_fallback_skips_when_backend_missing():\n+ \"\"\"Generic API raises RuntimeError and no backend module exists -> skip.\"\"\"\n+ fake_device = _FakeDevice(\"privateuse1\")\n+\n+ with (\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.is_available\",\n+ return_value=True,\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.current_accelerator\",\n+ return_value=fake_device,\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.memory_allocated\",\n+ side_effect=RuntimeError(\"not a DeviceAllocator\"),\n+ ),\n+ patch(\"speculators.train.trainer.torch.accelerator.synchronize\"),\n+ patch(\n+ \"speculators.train.trainer.time.perf_counter\",\n+ return_value=1.0,\n+ ),\n+ ):\n+ timer = _StepTimer(enabled=True)\n+ timer.mark(\"fwd\")\n+\n+ assert \"fwd\" not in timer._memory\n+\n+\n+def test_memory_fallback_skips_when_backend_lacks_memory_allocated():\n+ \"\"\"Backend module exists but has no memory_allocated -> skip silently.\"\"\"\n+ # _EmptyBackend has no memory_allocated attribute, so hasattr returns False\n+ # and the trainer skips memory recording for this step.\n+ stub_backend = _EmptyBackend()\n+\n+ fake_device = _FakeDevice(\"fake_device\")\n+\n+ with (\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.is_available\",\n+ return_value=True,\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.current_accelerator\",\n+ return_value=fake_device,\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.memory_allocated\",\n+ side_effect=RuntimeError(\"not a DeviceAllocator\"),\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.fake_device\",\n+ stub_backend,\n+ create=True,\n+ ),\n+ patch(\"speculators.train.trainer.torch.accelerator.synchronize\"),\n+ patch(\n+ \"speculators.train.trainer.time.perf_counter\",\n+ return_value=1.0,\n+ ),\n+ ):\n+ timer = _StepTimer(enabled=True)\n+ timer.mark(\"fwd\")\n+\n+ assert \"fwd\" not in timer._memory\n+\n+\n+def test_memory_happy_path_still_works():\n+ \"\"\"Generic accelerator API succeeds (CUDA-like) - memory recorded normally.\"\"\"\n+ fake_device = _FakeDevice(\"cuda\")\n+\n+ with (\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.is_available\",\n+ return_value=True,\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.current_accelerator\",\n+ return_value=fake_device,\n+ ),\n+ patch(\n+ \"speculators.train.trainer.torch.accelerator.memory_allocated\",\n+ return_value=100 * 1024**2,\n+ ),\n+ patch(\"speculators.train.trainer.torch.accelerator.synchronize\"),\n+ patch(\n+ \"speculators.train.trainer.time.perf_counter\",\n+ return_value=1.0,\n+ ),\n+ ):\n+ timer = _StepTimer(enabled=True)\n+ timer.mark(\"fwd\")\n+\n+ assert timer._memory[\"fwd\"] == 100.0\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/speculators\nPull request: fix(data): don't store the messages column for text-only prepare-data\nLabels: ready\nFiles changed (4): src/speculators/data_generation/preprocessing.py, src/speculators/data_generation/vllm_client.py, src/speculators/train/data.py, tests/integration/datagen/test_render_boundary.py\n\n## Description (results removed)\n\n## Purpose\n\nPreprocessing now records per row whether the conversation is multimodal, and after `map` drops `messages` when no row is. Multimodal datasets keep the column as before. When several sources are combined, the decision is made per source; `build_client_item` treats the resulting `None` messages as text-only. `has_multimodal_content` now counts only non-text parts, so text-only part lists (`[{\"type\": \"text\", ...}]`) also drop the column.\n\n## Tests\n[results removed]\n## Checklist\n\nI have filled in:\n\n---\n[image] [image]\nNeed help on this PR? Tag @codesmith-bot with what you need.\n\n## Diff\n\n```diff\ndiff --git a/src/speculators/data_generation/preprocessing.py b/src/speculators/data_generation/preprocessing.py\nindex 677868d02..868f8cef2 100644\n--- a/src/speculators/data_generation/preprocessing.py\n+++ b/src/speculators/data_generation/preprocessing.py\n@@ -17,6 +17,7 @@\n from speculators.data_generation.logging_utils import PipelineLogger\n from speculators.data_generation.render_client import render_conversation\n from speculators.data_generation.torch_utils import set_default_torch_num_threads\n+from speculators.data_generation.vllm_client import has_multimodal_content\n from speculators.train.vocab_mapping import save_token_frequency_distribution\n \n __all__ = [\n@@ -430,7 +431,9 @@ def _append_boundary_rows(\n if status == \"kept\":\n num_kept += 1\n if \"messages\" in results:\n- results[\"messages\"].append(_adapt_conv_for_vllm(row[\"conv\"]))\n+ messages = _adapt_conv_for_vllm(row[\"conv\"])\n+ results[\"messages\"].append(messages)\n+ results[\"is_multimodal\"].append(has_multimodal_content(messages))\n \n return num_kept, num_unsupervised, num_maybe_truncated\n \n@@ -510,6 +513,7 @@ def _preprocess_batch(\n # original messages -- token ids alone cannot carry the images.\n if is_multimodal:\n results[\"messages\"] = []\n+ results[\"is_multimodal\"] = []\n \n if not conversations:\n log.warning(f\"No conversations key found. Keys: {list(examples.keys())}\")\n@@ -637,10 +641,28 @@ def build_speculator_training_dataset(\n keep_in_memory=True, # skip caching\n )\n \n+ dataset = _drop_unused_messages(dataset)\n dataset.set_format(type=\"torch\")\n return dataset\n \n \n+def _drop_unused_messages(dataset: HFDataset) -> HFDataset:\n+ \"\"\"Drop the ``messages`` column when no row is multimodal.\n+\n+ Processor-based models write ``messages`` for every row, but the trainer\n+ only forwards it for multimodal rows, so a text-only dataset would store\n+ the full conversation text unused. Decided after ``map`` rather than per\n+ batch so every map shard keeps the same schema.\n+ \"\"\"\n+ if \"is_multimodal\" not in dataset.column_names:\n+ return dataset\n+ drop = [\"is_multimodal\"]\n+ if not any(dataset[\"is_multimodal\"]):\n+ log.info(\"No multimodal rows: not storing the messages column\")\n+ drop.append(\"messages\")\n+ return dataset.remove_columns(drop)\n+\n+\n def _load_hf_dataset(spec: str) -> tuple[HFDataset, None]:\n \"\"\"Load an arbitrary HuggingFace dataset from an ``hf:`` spec.\n \ndiff --git a/src/speculators/data_generation/vllm_client.py b/src/speculators/data_generation/vllm_client.py\nindex 12dc98c9d..5deb66cb0 100644\n--- a/src/speculators/data_generation/vllm_client.py\n+++ b/src/speculators/data_generation/vllm_client.py\n@@ -130,6 +130,20 @@ class ClientItem(TypedDict):\n instead of passing `token_ids` to Completions API.\"\"\"\n \n \n+def has_multimodal_content(messages: list[dict]) -> bool:\n+ \"\"\"True when any turn carries non-text content (images, video, audio).\n+\n+ Turns store ``content`` as a plain string or, after ``_adapt_conv_for_vllm``,\n+ as a list of typed parts, e.g. ``[{\"type\": \"text\", ...}, {\"type\": \"image_url\",\n+ ...}]``. Only a part whose type is not ``text`` makes the turn multimodal.\n+ \"\"\"\n+ return any(\n+ isinstance(m.get(\"content\"), list)\n+ and any(part.get(\"type\") != \"text\" for part in m[\"content\"])\n+ for m in messages\n+ )\n+\n+\n async def _poll_lock_async(fd, poll_interval):\n while True:\n try:\ndiff --git a/src/speculators/train/data.py b/src/speculators/train/data.py\nindex 241e4d6a1..474537359 100644\n--- a/src/speculators/train/data.py\n+++ b/src/speculators/train/data.py\n@@ -17,6 +17,7 @@\n DEFAULT_REQUEST_TIMEOUT,\n ClientItem,\n generate_hidden_states,\n+ has_multimodal_content,\n )\n from speculators.train.recovery import (\n RECOVERY_METADATA_KEY,\n@@ -55,16 +56,6 @@ def create_empty_sample(\n }\n \n \n-def _has_multimodal_content(messages: list[dict]) -> bool:\n- \"\"\"True when any turn carries non-text content (images, video, audio).\n-\n- Text-only turns store ``content`` as a plain string. Multimodal turns\n- (produced by ``_adapt_conv_for_vllm``) store it as a list of typed parts,\n- e.g. ``[{\"type\": \"text\", ...}, {\"type\": \"image_url\", ...}]``.\n- \"\"\"\n- return any(isinstance(m.get(\"content\"), list) for m in messages)\n-\n-\n def build_client_item(dataset_item: dict) -> ClientItem:\n \"\"\"Build a request payload for vLLM hidden-state extraction.\n \n@@ -89,8 +80,10 @@ def build_client_item(dataset_item: dict) -> ClientItem:\n \"\"\"\n out_dict: dict = {\"input_ids\": dataset_item[\"input_ids\"].tolist()}\n \n- if \"messages\" in dataset_item and _has_multimodal_content(dataset_item[\"messages\"]):\n- out_dict[\"messages\"] = dataset_item[\"messages\"]\n+ # A text-only source concatenated with a multimodal one has None messages.\n+ messages = dataset_item.get(\"messages\")\n+ if messages is not None and has_multimodal_content(messages):\n+ out_dict[\"messages\"] = messages\n \n return cast(\"ClientItem\", out_dict)\n \ndiff --git a/tests/integration/datagen/test_render_boundary.py b/tests/integration/datagen/test_render_boundary.py\nindex e4b2b3d15..ab210c8cb 100644\n--- a/tests/integration/datagen/test_render_boundary.py\n+++ b/tests/integration/datagen/test_render_boundary.py\n@@ -13,7 +13,8 @@\n import pytest\n import torch\n from datasets import Dataset as HFDataset\n-from datasets import load_from_disk\n+from datasets import concatenate_datasets, load_from_disk\n+from transformers import ProcessorMixin\n \n from speculators.data_generation import preprocessing, render_client\n from speculators.data_generation.preprocessing import (\n@@ -21,7 +22,7 @@\n build_speculator_training_dataset,\n )\n from speculators.data_generation.vllm_client import InvalidResponseError\n-from speculators.train.data import CollateFn\n+from speculators.train.data import CollateFn, build_client_item\n \n # Neither build path below reads the processor: the missing-endpoint guard\n # raises before it is used, and speculator-format rows skip rendering entirely.\n@@ -337,3 +338,81 @@ def test_loss_mask_stays_boolean_after_save_load_and_collation(tmp_path, mask):\n )\n assert batch[\"loss_mask\"].dtype == torch.bool\n assert batch[\"loss_mask\"].tolist() == [[False, False, True, True, False, False]]\n+\n+\n+class _ProcessorMixinStub(ProcessorMixin):\n+ \"\"\"Routes preprocessing down the multimodal path; never called.\"\"\"\n+\n+ def __init__(self):\n+ pass\n+\n+\n+def _build_with_processor(monkeypatch, conversations: list[list[dict]]) -> HFDataset:\n+ # One row per conversation; the conv itself is what `messages` would store.\n+ monkeypatch.setattr(\n+ preprocessing,\n+ \"_render_conversation_rows\",\n+ lambda conv, *a, **k: [\n+ {\"input_ids\": [1, 2, 3], \"loss_mask\": [0, 1, 1], \"conv\": conv}\n+ ],\n+ )\n+ return build_speculator_training_dataset(\n+ HFDataset.from_dict({\"conversations\": conversations}),\n+ cast(\"ProcessorLike\", _ProcessorMixinStub()),\n+ num_proc=1,\n+ render_endpoint=\"http://x\",\n+ )\n+\n+\n+def test_processor_text_only_rows_do_not_store_messages(monkeypatch):\n+ # The trainer only forwards `messages` for multimodal rows, so a text-only\n+ # prep through a processor-based model should not keep the column.\n+ dataset = _build_with_processor(monkeypatch, [_conv(2), _conv(2)])\n+ assert len(dataset) == 2\n+ assert \"messages\" not in dataset.column_names\n+ assert \"is_multimodal\" not in dataset.column_names\n+\n+\n+def test_processor_multimodal_rows_keep_messages(monkeypatch):\n+ image = {\"type\": \"image\", \"url\": \"http://x/a.png\", \"text\": None}\n+ text = {\"type\": \"text\", \"url\": None, \"text\": \"what is this?\"}\n+ conv = [\n+ {\"role\": \"user\", \"content\": [image, text]},\n+ {\"role\": \"assistant\", \"content\": [{**text, \"text\": \"a cat\"}]},\n+ ]\n+ dataset = _build_with_processor(monkeypatch, [conv])\n+ assert \"is_multimodal\" not in dataset.column_names\n+ user_parts = dataset[0][\"messages\"][0][\"content\"]\n+ assert user_parts[0][\"image_url\"] == {\"url\": \"http://x/a.png\"}\n+ assert build_client_item(dataset[0])[\"messages\"] == dataset[0][\"messages\"]\n+\n+\n+def test_processor_text_part_lists_do_not_store_messages(monkeypatch):\n+ # Content given as a list of text parts carries no media either.\n+ conv = [\n+ {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"hi\"}]},\n+ {\"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"hello\"}]},\n+ ]\n+ dataset = _build_with_processor(monkeypatch, [conv])\n+ assert \"messages\" not in dataset.column_names\n+\n+\n+def test_mixed_text_and_multimodal_sources_build_client_items(monkeypatch):\n+ # Concatenating a text-only source with a multimodal one fills the\n+ # text-only rows' `messages` with None; those rows must still send ids.\n+ image = {\"type\": \"image\", \"url\": \"http://x/a.png\", \"text\": None}\n+ text = {\"type\": \"text\", \"url\": None, \"text\": \"what is this?\"}\n+ conv = [\n+ {\"role\": \"user\", \"content\": [image, text]},\n+ {\"role\": \"assistant\", \"content\": [{**text, \"text\": \"a cat\"}]},\n+ ]\n+ dataset = concatenate_datasets(\n+ [\n+ _build_with_processor(monkeypatch, [_conv(2)]),\n+ _build_with_processor(monkeypatch, [conv]),\n+ ]\n+ )\n+ dataset.set_format(type=\"torch\")\n+ text_item, mm_item = (build_client_item(dataset[i]) for i in range(2))\n+ assert \"messages\" not in text_item\n+ assert mm_item[\"messages\"] == dataset[1][\"messages\"]\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][MRV2] Fix DiffusionGemma runtime OOM via tiled logits projection\nLabels: bug, ready, mrv2\nFiles changed (4): tests/v1/worker/test_gpu_diffusion_sampler.py, vllm/model_executor/models/diffusion_gemma.py, vllm/v1/worker/gpu/model_runner.py, vllm/v1/worker/gpu/model_states/interface.py\n\n## Description (results removed)\n\n## Purpose\n\n- Fixes #50699: full-batch logits grow with concurrency and OOM the first decode batch\n- Project logits per tile in the sampler; reserve the transient during profiling via a `profile_run` hook\n- Not a duplicate: #46155 is an opt-in env-var sampler; this fixes the default path\n\n## Test Plan\n[results removed]\n## Test Result\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/diffusion_gemma.py b/vllm/model_executor/models/diffusion_gemma.py\nindex f2f49cf03297..7feeaf5d51d3 100644\n--- a/vllm/model_executor/models/diffusion_gemma.py\n+++ b/vllm/model_executor/models/diffusion_gemma.py\n@@ -16,7 +16,7 @@\n \n from __future__ import annotations\n \n-from collections.abc import Iterable, Sequence\n+from collections.abc import Callable, Iterable, Sequence\n from types import SimpleNamespace\n from typing import Any\n \n@@ -909,6 +909,13 @@ def __init__(\n def get_supported_generation_tasks(self):\n return (\"generate\",)\n \n+ def compute_sample_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:\n+ return hidden_states\n+\n+ def dummy_sampler_run(self, sampler: Any, hidden_states: torch.Tensor) -> bool:\n+ sampler.profile_run(hidden_states)\n+ return True\n+\n def custom_sampler(self, sampler: Any) -> tuple[Any, Any] | None:\n diffusion_config = self.vllm_config.diffusion_config\n gen = self.gen_config\n@@ -931,6 +938,7 @@ def custom_sampler(self, sampler: Any) -> tuple[Any, Any] | None:\n diffusion_config=diffusion_config,\n vocab_size=self.model_config.get_vocab_size(),\n diffusion_states=self.diffusion_states,\n+ compute_logits=self.model.compute_logits,\n t_min=gen[\"t_min\"],\n t_max=gen[\"t_max\"],\n entropy_bound=entropy_bound,\n@@ -1143,6 +1151,7 @@ def __init__(\n vocab_size: int,\n diffusion_states: DiffusionGemmaRequestStates,\n *,\n+ compute_logits: Callable[[torch.Tensor], torch.Tensor],\n confidence_threshold: float,\n t_min: float,\n t_max: float,\n@@ -1154,6 +1163,7 @@ def __init__(\n tp_size: int = 1,\n tp_group_name: str = \"\",\n ):\n+ self.compute_logits = compute_logits\n self.sampling_states = sampler.sampling_states\n self.logprob_token_ids_state = sampler.logprob_token_ids_state\n self.req_states = sampler.req_states\n@@ -1262,6 +1272,24 @@ def penalties_state(self):\n # post_update treats None bin counts as \"no penalty bookkeeping\".\n return _NO_PENALTIES_STATE\n \n+ @torch.inference_mode()\n+ def profile_run(self, hidden_states: torch.Tensor) -> None:\n+ CL = self.canvas_length\n+ device = hidden_states.device\n+ bounds = np.array([0, CL], dtype=np.int32)\n+ dummy_batch = SimpleNamespace(\n+ num_reqs=1,\n+ num_draft_tokens=CL,\n+ idx_mapping_np=np.zeros(1, dtype=np.int32),\n+ idx_mapping=torch.zeros(1, dtype=torch.int64, device=device),\n+ cu_num_logits_np=bounds,\n+ query_start_loc_np=bounds,\n+ query_start_loc=torch.tensor(bounds, device=device),\n+ )\n+ self.diffusion_states.add_request(0)\n+ self(hidden_states.new_zeros((CL, hidden_states.shape[-1])), dummy_batch)\n+ self.diffusion_states.add_request(0)\n+\n # ------------------------------------------------------------------\n # Prefill\n # ------------------------------------------------------------------\n@@ -1359,12 +1387,12 @@ def _build_output(\n \n def __call__(\n self,\n- logits: torch.Tensor,\n+ hidden_states: torch.Tensor,\n input_batch: Any,\n draft_logits: torch.Tensor | None = None,\n ) -> SamplerOutput:\n num_reqs = input_batch.num_reqs\n- device = logits.device\n+ device = hidden_states.device\n \n if input_batch.num_draft_tokens == 0:\n return self._handle_prefill(input_batch, device)\n@@ -1398,26 +1426,7 @@ def __call__(\n valid_canvas_len_np.astype(np.int64), device=device\n )\n \n- # Per-request top_k/top_p, mirroring the AR sampler. Masked tokens\n- # become -inf and survive the temperature scaling in the compiled\n- # step, so Gumbel sampling, probs, and entropy all see the filtered\n- # distribution. The committed argmax (always the top-1 token) is\n- # unaffected; only the canvas exploration is constrained. Applied\n- # before canvas padding so phantom positions stay uniform.\n- if num_decode > 0:\n- top_k, top_p, has_topp_only_rows = self.sampling_states.get_top_k_top_p(\n- decode_slots.repeat_interleave(\n- valid_canvas_len, output_size=int(valid_canvas_len_np.sum())\n- ),\n- decode_slots_np,\n- logits.shape[-1],\n- )\n- if top_k is not None or top_p is not None:\n- logits = apply_top_k_top_p(\n- logits.float(), top_k, top_p, has_topp_only_rows=has_topp_only_rows\n- )\n-\n- [comment with results removed]\n+ [comment with results removed]\n # below gather and pad a request to the tile's width.\n row_starts_np = np.concatenate(\n ([0], np.cumsum(valid_canvas_len_np)[:-1])\n@@ -1443,23 +1452,18 @@ def __call__(\n embed_weight = self.embed_weight\n vocab_size = self.vocab_size\n sc_vocab_start, sc_vocab_end = self.sc_vocab_start, self.sc_vocab_end\n+ per_row = None\n if allowed is not None:\n- assert logits.shape[-1] == allowed.numel()\n embed_weight = self.embed_weight[allowed]\n sc_vocab_start, sc_vocab_end = 0, allowed.numel()\n elif states.constrained and num_decode > 0:\n # The decode slots do not share one set, so this step runs over\n # the full vocabulary. Mask each constrained request's rows to\n- # its own set so it reads the same as on the shared path. The\n- # helper masks a copy, since the runner owns `logits`: one\n- # full-vocab copy per step, as for top_k/top_p above.\n+ # its own set so it reads the same as on the shared path.\n per_row = [\n None if ids is None else states.allowed_tensor(ids)\n for ids in (states.constrained.get(s) for s in decode_slots_np.tolist())\n ]\n- logits = _mask_rows_to_allowed(\n- logits, row_starts_np, valid_canvas_len_np, per_row\n- )\n \n slots_np = input_batch.idx_mapping_np[:num_reqs]\n max_num_logprobs = self.sampling_states.max_num_logprobs(slots_np)\n@@ -1473,8 +1477,9 @@ def __call__(\n # tile runs the compiled step at that width over [:, :W] views of the\n # state, so a narrow read pays for its own rows rather than the served\n # canvas. Widths ascend, so the last tile's canvas-to-draft copy (over\n- # all slots) is the widest. The fp32 pipeline keeps several live\n- # [tile * W, vocab] copies, so a tile is also bounded by free memory.\n+ # all slots) is the widest. Each tile projects its own logits, and the\n+ # fp32 pipeline keeps several live [tile * W, vocab] copies, so a tile\n+ # is also bounded by free memory.\n widths_np = states.canvas_width_np[decode_slots_np]\n order = np.argsort(widths_np, kind=\"stable\")\n free = torch.accelerator.get_memory_info()[0] if num_decode > 0 else 0\n@@ -1484,10 +1489,11 @@ def __call__(\n run_end = run_start\n while run_end < num_decode and widths_np[order[run_end]] == W:\n run_end += 1\n- # Transient [tile * W, vocab] tensors: the softmax in the embedding\n- # dtype for self-conditioning, plus the fp32 scaled logits when\n- # logprobs are wanted (pad for allocator overhead).\n- budget = max(1, int(free * 0.5) // max(W * self.vocab_size * 4 * 3, 1))\n+ # Transient [tile * W, vocab] tensors: the projected fp32 logits and\n+ # their top_k/top_p or allowed-set copy, the softmax in the\n+ # embedding dtype for self-conditioning, plus the fp32 scaled\n+ # logits when logprobs are wanted (pad for allocator overhead).\n+ budget = max(1, int(free * 0.5) // max(W * self.vocab_size * 4 * 5, 1))\n for t0 in range(run_start, run_end, budget):\n sel_np = order[t0 : min(t0 + budget, run_end)]\n n = len(sel_np)\n@@ -1496,21 +1502,54 @@ def __call__(\n tile_valid = valid_canvas_len[sel]\n tile_valid_np = valid_canvas_len_np[sel_np]\n contiguous = bool((sel_np == np.arange(sel_np[0], sel_np[0] + n)).all())\n+ phantom = None\n if contiguous and tile_valid_np.min() == W:\n r0 = int(row_starts_np[sel_np[0]])\n- tile_logits = logits[r0 : r0 + n * W]\n+ tile_hidden = hidden_states[r0 : r0 + n * W]\n else:\n # Pad each request to W. Phantom positions are zeroed:\n # uniform logits, high entropy, argmax 0, never committed.\n # masked_fill, not multiply, so -inf from top_k/top_p\n- # filtering above cannot turn a phantom row into NaN.\n+ # filtering below cannot turn a phantom row into NaN.\n ar = torch.arange(W, device=device)\n src = (row_starts[sel].unsqueeze(1) + ar.unsqueeze(0)).clamp_max(\n- logits.shape[0] - 1\n+ hidden_states.shape[0] - 1\n+ )\n+ phantom = (ar.unsqueeze(0) >= tile_valid.unsqueeze(1)).reshape(\n+ -1, 1\n+ )\n+ tile_hidden = hidden_states[src.reshape(-1)].masked_fill_(\n+ phantom, 0\n+ )\n+ tile_logits = self.compute_logits(tile_hidden)\n+ if allowed is not None:\n+ assert tile_logits.shape[-1] == allowed.numel()\n+\n+ # Per-request top_k/top_p, mirroring the AR sampler. Masked\n+ # tokens become -inf and survive the temperature scaling, so\n+ # Gumbel sampling, probs, and entropy all see the filtered\n+ # distribution. The committed argmax (always the top-1 token)\n+ # is unaffected; only the canvas exploration is constrained.\n+ top_k, top_p, has_topp_only_rows = self.sampling_states.get_top_k_top_p(\n+ tile_slots.repeat_interleave(W, output_size=n * W),\n+ decode_slots_np[sel_np],\n+ tile_logits.shape[-1],\n+ )\n+ if top_k is not None or top_p is not None:\n+ tile_logits = apply_top_k_top_p(\n+ tile_logits.float(),\n+ top_k,\n+ top_p,\n+ has_topp_only_rows=has_topp_only_rows,\n )\n- valid = ar.unsqueeze(0) < tile_valid.unsqueeze(1)\n- tile_logits = logits[src.reshape(-1)].masked_fill_(\n- ~valid.reshape(-1, 1), 0\n+ if phantom is not None:\n+ tile_logits.masked_fill_(phantom, 0)\n+ if per_row is not None:\n+ tile_logits = _mask_rows_to_allowed(\n+ tile_logits,\n+ np.arange(n) * W,\n+ tile_valid_np,\n+ [per_row[i] for i in sel_np],\n )\n compute_sc = (\n not states.single_step_slots\ndiff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py\nindex 268e137882ff..c82fda0d1021 100644\n--- a/vllm/v1/worker/gpu/model_runner.py\n+++ b/vllm/v1/worker/gpu/model_runner.py\n@@ -1008,13 +1008,15 @@ def _dummy_run(\n \n @torch.inference_mode()\n def _dummy_sampler_run(self, hidden_states: torch.Tensor) -> None:\n+ assert self.sampler is not None\n+ if self.model_state.dummy_sampler_run(self.sampler, hidden_states):\n+ return\n num_reqs = hidden_states.shape[0]\n logits = self.model.compute_logits(hidden_states)\n dummy_input_batch = InputBatch.make_dummy(\n num_reqs, num_reqs, self.input_buffers\n )\n \n- assert self.sampler is not None\n # Default pass: compiles the kernels the first real step uses (logits in\n # the model dtype, no per-request processing).\n self.sampler(logits, dummy_input_batch)\n@@ -1679,7 +1681,7 @@ def sample(\n logits = logits[:, : self.vocab_size]\n else:\n sample_hidden_states = hidden_states[input_batch.logits_indices]\n- logits = self.model.compute_logits(sample_hidden_states)\n+ logits = self.model_state.compute_sample_logits(sample_hidden_states)\n \n # A diffusion prefill has no logit rows even when a bitmask row\n # arrived for it.\ndiff --git a/vllm/v1/worker/gpu/model_states/interface.py b/vllm/v1/worker/gpu/model_states/interface.py\nindex 98eb552dd304..fa49f470b1e3 100644\n--- a/vllm/v1/worker/gpu/model_states/interface.py\n+++ b/vllm/v1/worker/gpu/model_states/interface.py\n@@ -253,6 +253,17 @@ def custom_sampler(self, sampler: Any) -> tuple[Any, Any] | None:\n \"\"\"\n return None\n \n+ def compute_sample_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:\n+ \"\"\"Project the sampled hidden states to the logits fed to the sampler.\"\"\"\n+ return cast(Any, self.model).compute_logits(hidden_states)\n+\n+ def dummy_sampler_run(self, sampler: Any, hidden_states: torch.Tensor) -> bool:\n+ \"\"\"Run a model-specific sampler profiling pass.\n+\n+ Return ``True`` to skip the default dummy sampler run.\n+ \"\"\"\n+ return False\n+\n num_new_sampled_tokens_per_step: int = 1\n \"\"\"New tokens sampled on each decode step \n (excluding accepted draft tokens, a.k.a num bonus tokens).\"\"\"\n\ndiff --git a/tests/v1/worker/test_gpu_diffusion_sampler.py b/tests/v1/worker/test_gpu_diffusion_sampler.py\nnew file mode 100644\nindex 000000000000..17ba78f4c7b2\n--- /dev/null\n+++ b/tests/v1/worker/test_gpu_diffusion_sampler.py\n@@ -0,0 +1,144 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+\"\"\"DiffusionSampler projects logits tile-by-tile (#50699): sampling outputs\n+must not depend on the tile size, and peak memory must scale with the tile,\n+not the batch.\"\"\"\n+\n+from types import SimpleNamespace\n+\n+import numpy as np\n+import pytest\n+import torch\n+\n+from vllm.model_executor.models import diffusion_gemma as dg\n+from vllm.sampling_params import SamplingParams\n+from vllm.v1.worker.gpu.sample.logprob import LogprobTokenIdsState\n+from vllm.v1.worker.gpu.sample.states import SamplingStates\n+\n+pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason=\"requires CUDA\")\n+\n+DEVICE = \"cuda\"\n+\n+\n+def _make_sampler(num_reqs, canvas_len, vocab, hidden, weight, top_k=0):\n+ states = dg.DiffusionGemmaRequestStates(\n+ max_num_reqs=num_reqs,\n+ canvas_length=canvas_len,\n+ vocab_size=vocab,\n+ max_denoising_steps=8,\n+ device=torch.device(DEVICE),\n+ hidden_size=hidden,\n+ stability_threshold=2,\n+ )\n+ base = SimpleNamespace(\n+ sampling_states=SamplingStates(num_reqs, vocab),\n+ logprob_token_ids_state=LogprobTokenIdsState(num_reqs, torch.device(DEVICE)),\n+ req_states=SimpleNamespace(\n+ draft_tokens=torch.zeros(\n+ num_reqs, canvas_len, dtype=torch.int64, device=DEVICE\n+ )\n+ ),\n+ logprobs_mode=\"raw_logprobs\",\n+ )\n+ sampler = dg.DiffusionSampler(\n+ sampler=base,\n+ diffusion_config=SimpleNamespace(canvas_length=canvas_len),\n+ vocab_size=vocab,\n+ diffusion_states=states,\n+ compute_logits=lambda h: h @ weight.t(),\n+ confidence_threshold=0.5,\n+ t_min=0.0,\n+ t_max=0.0,\n+ entropy_bound=0.1,\n+ embed_weight=weight,\n+ normalizer=torch.tensor(1.0, device=DEVICE),\n+ )\n+ for i in range(num_reqs):\n+ sampler.add_request(i, SamplingParams(top_k=top_k))\n+ states.is_encoder_phase[i] = False\n+ sampler.apply_staged_writes()\n+ return sampler, states\n+\n+\n+def _make_batch(num_reqs, valid_lens):\n+ cu = np.zeros(num_reqs + 1, dtype=np.int64)\n+ cu[1:] = np.cumsum(valid_lens)\n+ qsl_np = cu.astype(np.int32)\n+ return SimpleNamespace(\n+ num_reqs=num_reqs,\n+ num_draft_tokens=int(max(valid_lens)),\n+ idx_mapping_np=np.arange(num_reqs, dtype=np.intp),\n+ idx_mapping=torch.arange(num_reqs, dtype=torch.int64, device=DEVICE),\n+ cu_num_logits_np=cu,\n+ query_start_loc_np=qsl_np,\n+ query_start_loc=torch.from_numpy(qsl_np).to(DEVICE),\n+ )\n+\n+\n+@pytest.mark.parametrize(\"top_k\", [0, 4])\n+def test_tiled_projection_matches_full(monkeypatch, top_k):\n+ \"\"\"Deterministic outputs (t_min=t_max=0) are identical for group=1 tiling\n+ and a single full-batch pass, including a truncated (padded) canvas.\"\"\"\n+ num_reqs, canvas_len, vocab, hidden = 4, 16, 1024, 32\n+ torch.manual_seed(0)\n+ weight = torch.randn(vocab, hidden, device=DEVICE)\n+ valid_lens = [canvas_len, canvas_len, canvas_len, canvas_len - 3]\n+ hs = torch.randn(sum(valid_lens), hidden, device=DEVICE)\n+\n+ results = []\n+ for free in (2**60, 0):\n+ torch.manual_seed(0)\n+ sampler, states = _make_sampler(\n+ num_reqs, canvas_len, vocab, hidden, weight, top_k\n+ )\n+ monkeypatch.setattr(\n+ torch.accelerator, \"get_memory_info\", lambda free=free: (free, 2**60)\n+ )\n+ out = sampler(hs.clone(), _make_batch(num_reqs, valid_lens))\n+ results.append((out, states))\n+\n+ (out_full, st_full), (out_tiled, st_tiled) = results\n+ torch.testing.assert_close(st_full.argmax_canvas, st_tiled.argmax_canvas)\n+ torch.testing.assert_close(st_full.is_encoder_phase, st_tiled.is_encoder_phase)\n+ torch.testing.assert_close(st_full.confident, st_tiled.confident)\n+ torch.testing.assert_close(st_full.step, st_tiled.step)\n+ torch.testing.assert_close(out_full.sampled_token_ids, out_tiled.sampled_token_ids)\n+ torch.testing.assert_close(out_full.num_sampled, out_tiled.num_sampled)\n+\n+\n+def test_tiling_bounds_peak_memory(monkeypatch):\n+ \"\"\"Forced group=1 tiling must not materialize full-batch logits.\"\"\"\n+ num_reqs, canvas_len, vocab, hidden = 8, 64, 32768, 64\n+ torch.manual_seed(0)\n+ weight = torch.randn(vocab, hidden, device=DEVICE)\n+ valid_lens = [canvas_len] * num_reqs\n+ hs = torch.randn(num_reqs * canvas_len, hidden, device=DEVICE)\n+\n+ peaks = {}\n+ for name, free in ((\"full\", 2**60), (\"tiled\", 0)):\n+ torch.manual_seed(0)\n+ sampler, _ = _make_sampler(num_reqs, canvas_len, vocab, hidden, weight)\n+ monkeypatch.setattr(\n+ torch.accelerator, \"get_memory_info\", lambda free=free: (free, 2**60)\n+ )\n+ sampler(hs.clone(), _make_batch(num_reqs, valid_lens))\n+ torch.accelerator.synchronize()\n+ torch.accelerator.reset_peak_memory_stats()\n+ base = torch.accelerator.memory_allocated()\n+ sampler(hs.clone(), _make_batch(num_reqs, valid_lens))\n+ torch.accelerator.synchronize()\n+ peaks[name] = torch.accelerator.max_memory_allocated() - base\n+\n+ assert peaks[\"tiled\"] < peaks[\"full\"] / 2\n+\n+\n+def test_profile_run_resets_state():\n+ \"\"\"profile_run exercises the decode pipeline for KV sizing, then leaves\n+ slot 0 freshly initialized.\"\"\"\n+ num_reqs, canvas_len, vocab, hidden = 2, 16, 1024, 32\n+ torch.manual_seed(0)\n+ weight = torch.randn(vocab, hidden, device=DEVICE)\n+ sampler, states = _make_sampler(num_reqs, canvas_len, vocab, hidden, weight)\n+ sampler.profile_run(torch.zeros(num_reqs, hidden, device=DEVICE))\n+ assert bool(states.is_encoder_phase[0])\n+ assert int(states.step[0]) == 0\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Spec Decode] DFlash/DSpark no longer drop the last prefix-cache block (mamba align context recompute)\nLabels: bug, ready, dflash, scheduler\nFiles changed (4): tests/test_config.py, tests/v1/core/test_scheduler.py, vllm/config/speculative.py, vllm/v1/core/sched/scheduler.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #53477. DFlash and DSpark preserve the target KV cache and do not require the EAGLE-style trailing prefix-cache block drop. Scoping that drop correctly restores reusable Mamba checkpoints in `--mamba-cache-mode align` and prevents full-context recomputation on subsequent replies.\n\n## Claims\n\n- DFlash/DSpark no longer drop the last prefix-cache block solely because `SpeculativeConfig.use_eagle()` also matches those methods.\n\n## Validation\n[results removed]\n## Details\n\n### Root cause\n\n`SpeculativeConfig.use_eagle()` is a broad predicate for speculative decoding that reads target hidden states, and it intentionally matches `eagle`, `eagle3`, `mtp`, `dflash`, and `dspark`. #53388 derived `use_eagle_block_drop()` from that broad predicate.\n\nEAGLE-style drafters construct a position's draft KV from the target hidden state **and the next token**. DFlash/DSpark construct it from the target hidden state alone. Therefore only EAGLE/EAGLE3/MTP need the trailing EAGLE block drop; both DFlash and DSpark preserve the target KV cache.\n\nFor a prompt shorter than two Mamba blocks, the spurious back-off produced this sequence:\n\n1. `last_cache_position == 0`, so the prompt was a single chunk ending off the Mamba block grid.\n2. Mamba align mode only materializes a reusable recurrent state at a block-aligned chunk end.\n3. `HybridKVCacheCoordinator.find_longest_cache_hit()` converged the next turn's hit to zero, causing full-context recomputation.\n\n### Implementation\n\n- `vllm/config/speculative.py`: add `needs_eagle_block_drop()` for the precise EAGLE/EAGLE3/MTP capability, and compose `use_eagle_block_drop()` from it plus `disable_eagle_block_drop`.\n- `vllm/v1/core/sched/scheduler.py`: reuse `needs_eagle_block_drop()` in the warning condition. The existing split back-off, `KVCacheManager(use_eagle=...)`, offloading, and Mooncake paths now receive `False` for DFlash/DSpark without changing `use_eagle()`.\n- `tests/test_config.py`: parameterize the existing config test over EAGLE3/MTP (drop) and DFlash/DSpark (no drop), both with the opt-out enabled and disabled.\n- `tests/v1/core/test_scheduler.py`: set the now-separate `use_eagle_block_drop` scheduler value in the Mamba-align EAGLE fixture.\n\nThe change is limited to the prefix-cache trailing-block policy. EAGLE/EAGLE3/MTP retain the previous default behavior, and the existing explicit opt-out remains available.\n\n### Related work and duplication\n\nNo open PR addresses #53477. Related work includes #53388 (merged opt-out for EAGLE trailing-block dropping), #30877 (Mamba align prefix caching), #42971, and #44082. None previously corrected the DFlash/DSpark classification.\n\n## Diff\n\n```diff\ndiff --git a/vllm/config/speculative.py b/vllm/config/speculative.py\nindex 630a8705cbf5..1f4a04ef0c12 100644\n--- a/vllm/config/speculative.py\n+++ b/vllm/config/speculative.py\n@@ -2052,6 +2052,15 @@ def use_eagle(self) -> bool:\n # TODO(ben): Refactor this so the naming is clearer\n return self.method in (\"eagle\", \"eagle3\", \"mtp\", \"dflash\", \"dspark\")\n \n+ def needs_eagle_block_drop(self) -> bool:\n+ \"\"\"Whether draft KV at a position depends on the next token.\n+\n+ EAGLE-style drafters build a position's draft KV from its hidden state\n+ and the next token. DFlash/DSpark build it from the target hidden state\n+ alone, so only EAGLE/EAGLE3/MTP require the trailing-block drop.\n+ \"\"\"\n+ return self.use_eagle() and not (self.use_dflash() or self.use_dspark())\n+\n def is_xpress(self) -> bool:\n \"\"\"Whether the dflash draft carries an XPress refiner.\n \n@@ -2069,8 +2078,8 @@ def is_xpress(self) -> bool:\n )\n \n def use_eagle_block_drop(self) -> bool:\n- \"\"\"Whether volatile trailing cache blocks should be discarded.\"\"\"\n- return self.use_eagle() and not self.disable_eagle_block_drop\n+ \"\"\"Whether the volatile trailing prefix-cache block should be dropped.\"\"\"\n+ return self.needs_eagle_block_drop() and not self.disable_eagle_block_drop\n \n def use_dflash(self) -> bool:\n return self.method == \"dflash\"\ndiff --git a/vllm/v1/core/sched/scheduler.py b/vllm/v1/core/sched/scheduler.py\nindex e277df75c8f4..844f29e01343 100644\n--- a/vllm/v1/core/sched/scheduler.py\n+++ b/vllm/v1/core/sched/scheduler.py\n@@ -321,7 +321,10 @@ def __init__(\n )\n self.use_eagle = speculative_config.use_eagle()\n self.use_eagle_block_drop = speculative_config.use_eagle_block_drop()\n- if self.use_eagle and not self.use_eagle_block_drop:\n+ if (\n+ speculative_config.needs_eagle_block_drop()\n+ and speculative_config.disable_eagle_block_drop\n+ ):\n logger.warning(\n \"EAGLE trailing prefix-cache block dropping is disabled. \"\n \"This is experimental and may affect speculative-token \"\n\ndiff --git a/tests/test_config.py b/tests/test_config.py\nindex 985af6284561..5334cbd2081f 100644\n--- a/tests/test_config.py\n+++ b/tests/test_config.py\n@@ -3587,8 +3587,14 @@ def test_draft_sample_method_probabilistic_is_accepted():\n assert speculative_config.draft_sample_method == \"probabilistic\"\n \n \n+@pytest.mark.parametrize(\n+ (\"method\", \"drops_block\"),\n+ [(\"eagle3\", True), (\"mtp\", True), (\"dflash\", False), (\"dspark\", False)],\n+)\n @pytest.mark.parametrize(\"disable_eagle_block_drop\", [False, True])\n def test_eagle_block_drop_can_be_disabled_without_disabling_eagle(\n+ method: str,\n+ drops_block: bool,\n disable_eagle_block_drop: bool,\n ):\n # Start from an ngram config to avoid loading model metadata: these predicates\n@@ -3598,10 +3604,12 @@ def test_eagle_block_drop_can_be_disabled_without_disabling_eagle(\n num_speculative_tokens=3,\n disable_eagle_block_drop=disable_eagle_block_drop,\n )\n- speculative_config.method = \"eagle3\"\n+ speculative_config.method = method\n \n assert speculative_config.use_eagle()\n- assert speculative_config.use_eagle_block_drop() is not disable_eagle_block_drop\n+ assert speculative_config.use_eagle_block_drop() is (\n+ drops_block and not disable_eagle_block_drop\n+ )\n \n \n def test_draft_sample_method_gumbel_is_rejected():\ndiff --git a/tests/v1/core/test_scheduler.py b/tests/v1/core/test_scheduler.py\nindex ef5f9c232e28..fe199d809ee5 100644\n--- a/tests/v1/core/test_scheduler.py\n+++ b/tests/v1/core/test_scheduler.py\n@@ -5075,6 +5075,7 @@ def test_mamba_align_eagle_schedules_encoder_at_boundary():\n )\n scheduler.need_mamba_block_aligned_split = True\n scheduler.use_eagle = True\n+ scheduler.use_eagle_block_drop = True\n scheduler.num_prefill_lookahead = 1\n scheduler.max_num_encoder_input_tokens = 2048\n scheduler.encoder_cache_manager = EncoderCacheManager(cache_size=2048)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Core] Copy every overlaid KV view in copy_kv_cache_blocks_inplace\nLabels: bug, ready\nFiles changed (2): tests/v1/worker/test_attn_utils.py, vllm/v1/worker/utils.py\n\n## Description (results removed)\n\n## Purpose\n\nFor Kimi-K3 (3 KDA groups + 1 MLA group, block_size 5760, kernel page 64) the KDA view `(num_blocks, 1, 1, 814080)` int8 comes first, so the MLA view `(num_blocks*90, 1, 64, 576)` bf16 of the same tensor is skipped and an MLA block copy moves only 814080 of its 6635520 bytes, i.e. the first 706 of 5760 token slots. The whole-storage fast path would hide this, but it is not taken when several tensors live in one allocation.\n\n## Fix\n\n### Why the deduplication key includes view geometry\n\nThe key answers: \"Has this view's block copy already been performed?\" The same starting address does not imply the same copy coverage.\n\n```text\nOne scheduler block:\nbyte offset 0 24 64\n |--------------|--------------------------|\nMamba view | state data |\nAttention view | full KV data |\n```\n\nThe two views have these properties:\n\n[table with results removed]\n\nThe attention view splits each scheduler block into two kernel pages: each page contains `1 * 8 * 2 = 16` int16 elements, so the two pages cover `2 * 16 * 2 = 64` bytes.\n\nWhen copying block 0 to block 2, with the Mamba view visited first:\n\n2. **After the fix:** the views have different geometry keys. The Mamba view copies the first 24 bytes, and the attention view subsequently copies all 64 bytes. The overlapping 24 bytes are copied from the same source block to the same destination block, so the extra copy is redundant but harmless.\n\nThis example deliberately uses two tensor regions in one storage. The whole-storage fast path requires `storage.nbytes() == num_blocks * scheduler_block_stride`; here that is `512 == 4 * 64`, which is false. The fallback copies the current view's logical elements, so the narrow view cannot cover the full attention block. With a single 256-byte region, the whole-storage fast path would copy the full block and hide the bug.\n\nThe new key describes both the starting location and the layout:\n\n```python\nkey = (\n cache.device,\n cache.data_ptr(),\n tuple(cache.shape),\n tuple(cache.stride()),\n cache.element_size(),\n)\n```\n\n- `device` and `data_ptr()` identify where the view starts.\n- `shape` describes its logical extent.\n- `stride()` describes where its elements lie. For example, two views starting at `a` with shape `(3,)` can select `[a, b, c]` with stride 1 or `[a, c, e]` with stride 2.\n- `element_size()` converts element-based strides to byte distances: stride 2 means 2 bytes for int8 but 4 bytes for int16.\n\n## Test Plan\n[results removed]\n## Notes\n\n- No open PR touches `copy_kv_cache_blocks_inplace` (searched `copy_kv_cache_blocks_inplace`, `kv_cache_block_copies`, `CoW block copy hybrid`).\n- AI-assisted (Claude Code); the analysis, fix and test were reviewed line by line and the tests above were run by the submitter.\n\nhttps://claude.ai/code/session_013hMcjaJa8vC9zEZeipxDfd\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/worker/utils.py b/vllm/v1/worker/utils.py\nindex d10cdcec6453..5a254c481eb0 100644\n--- a/vllm/v1/worker/utils.py\n+++ b/vllm/v1/worker/utils.py\n@@ -916,12 +916,22 @@ def copy_kv_cache_blocks_inplace(\n \n indices_np = np.array(kv_cache_block_copies, dtype=np.int64)\n indices: torch.Tensor | None = None\n- seen: set[tuple[torch.device, int]] = set()\n+ seen: set[tuple[Any, ...]] = set()\n copied_storages: set[tuple[torch.device, int]] = set()\n for cache in kv_caches:\n # Layers sharing KV (cross-layer sharing) alias the same view; copy it\n- # once. data_ptr distinguishes per-layer views of a shared allocation.\n- key = (cache.device, cache.data_ptr())\n+ # once. Hybrid models overlay layers of different kinds on one tensor,\n+ # so views at the same address can differ in geometry (a Mamba state\n+ # view spans only the leading bytes of a block that an attention view\n+ # spans in full); each geometry must be copied, so the key covers the\n+ # view's shape and strides and not just its address.\n+ key = (\n+ cache.device,\n+ cache.data_ptr(),\n+ tuple(cache.shape),\n+ tuple(cache.stride()),\n+ cache.element_size(),\n+ )\n if key in seen:\n continue\n seen.add(key)\n\ndiff --git a/tests/v1/worker/test_attn_utils.py b/tests/v1/worker/test_attn_utils.py\nindex 76e0e42dae61..2d59898a5f70 100644\n--- a/tests/v1/worker/test_attn_utils.py\n+++ b/tests/v1/worker/test_attn_utils.py\n@@ -883,3 +883,47 @@ def test_packed_token_cache_cannot_be_split():\n packed = torch.zeros(3, 1, 2048, 1152, dtype=torch.uint8)[:, :, :1024]\n with pytest.raises(ValueError, match=\"cannot be split\"):\n map_kv_caches_to_kernel_blocks({\"layer.0\": packed}, [group])\n+\n+\n+def test_copy_kv_cache_blocks_overlaid_views_copy_whole_block():\n+ \"\"\"Hybrid overlays: a Mamba state view and an attention view of one tensor\n+ share a base address but span different bytes per block, and several such\n+ tensors live in one allocation (so the whole-storage fast path is off).\n+ The copy must cover the attention span even though the narrow Mamba view\n+ is encountered first; otherwise the pages past the Mamba state size in\n+ the destination block keep whatever they held before.\"\"\"\n+ num_blocks = 4\n+ num_tensors = 2\n+ block_stride = 64 # bytes per scheduler block in every tensor\n+ state_bytes = 24 # Mamba state occupies only the leading bytes of a block\n+ tensor_bytes = num_blocks * block_stride\n+ raw = torch.arange(num_tensors * tensor_bytes, dtype=torch.int32).to(torch.uint8)\n+ storage = raw.untyped_storage()\n+\n+ caches: list[torch.Tensor] = []\n+ for tensor_idx in range(num_tensors):\n+ base = tensor_idx * tensor_bytes\n+ mamba = torch.empty(0, dtype=torch.int8)\n+ mamba.set_(storage)\n+ mamba = mamba.as_strided(\n+ (num_blocks, 1, 1, state_bytes), (block_stride, 1, 1, 1), base\n+ )\n+ # 2 kernel pages of 8 int16 per scheduler block cover the whole block.\n+ attn = torch.empty(0, dtype=torch.int16)\n+ attn.set_(storage)\n+ attn = attn.as_strided((num_blocks * 2, 1, 8, 2), (16, 16, 2, 1), base // 2)\n+ assert mamba.data_ptr() == attn.data_ptr()\n+ caches += [mamba, attn]\n+\n+ expected = raw.view(num_tensors, num_blocks, block_stride).clone()\n+ expected[:, 2] = expected[:, 0]\n+\n+ copy_kv_cache_blocks_inplace(\n+ caches,\n+ num_blocks,\n+ [KVCacheBlockCopy(src_block_id=0, dst_block_id=2)],\n+ )\n+\n+ torch.testing.assert_close(\n+ raw.view(num_tensors, num_blocks, block_stride), expected\n+ )\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Tool Calling] Tool parser non-streaming parse drops post-tool-call text that streaming returns\nLabels: bug, ready, tool-calling, deepseek\nFiles changed (2): tests/tool_parsers/test_deepseekv3_tool_parser.py, vllm/tool_parsers/deepseekv3_tool_parser.py\n\n## Description (results removed)\n\n## Purpose\n\nFixes https://github.com/vllm-project/vllm/issues/56263\n\nFor a model output that contains text before AND after a tool call, the two delivery modes disagree: streaming returns the post-tool text, non-streaming drops it. The tool parser is inconsistent with its own streaming mode.\n\n## Changes made\n\n## Test Plan\n[results removed]\n## Test Result\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/tool_parsers/deepseekv3_tool_parser.py b/vllm/tool_parsers/deepseekv3_tool_parser.py\nindex 649eded2878f..9e18bdcd899a 100644\n--- a/vllm/tool_parsers/deepseekv3_tool_parser.py\n+++ b/vllm/tool_parsers/deepseekv3_tool_parser.py\n@@ -109,7 +109,13 @@ def extract_tool_calls(\n )\n )\n \n- content = model_output[: model_output.find(self.tool_calls_start_token)]\n+ tool_calls_start = model_output.find(self.tool_calls_start_token)\n+ tool_calls_end = model_output.rfind(self.tool_calls_end_token)\n+ content = model_output[:tool_calls_start]\n+ if tool_calls_end != -1:\n+ content += model_output[\n+ tool_calls_end + len(self.tool_calls_end_token) :\n+ ]\n return ExtractedToolCallInformation(\n tools_called=True,\n tool_calls=tool_calls,\n\ndiff --git a/tests/tool_parsers/test_deepseekv3_tool_parser.py b/tests/tool_parsers/test_deepseekv3_tool_parser.py\nindex 27fbae0920bb..e0d2897e917e 100644\n--- a/tests/tool_parsers/test_deepseekv3_tool_parser.py\n+++ b/tests/tool_parsers/test_deepseekv3_tool_parser.py\n@@ -8,6 +8,7 @@\n ToolParserTestConfig,\n ToolParserTests,\n )\n+from tests.tool_parsers.utils import run_tool_extraction\n from vllm.tokenizers import TokenizerLike, get_tokenizer\n \n \n@@ -90,3 +91,31 @@ def test_config(self) -> ToolParserTestConfig:\n ),\n },\n )\n+\n+ @pytest.mark.parametrize(\"streaming\", [False, True])\n+ def test_preserves_text_after_tool_call(\n+ self,\n+ tool_parser,\n+ streaming: bool,\n+ ) -> None:\n+ model_output = (\n+ \"let me check the weather.\"\n+ \"<|tool▁calls▁begin|>\"\n+ \"<|tool▁call▁begin|>function<|tool▁sep|>get_weather\\n\"\n+ \"```json\\n\"\n+ '{\"city\": \"Paris\"}\\n'\n+ \"```<|tool▁call▁end|>\"\n+ \"<|tool▁calls▁end|>\"\n+ \"It is 30 degrees.\"\n+ )\n+\n+ content, tool_calls = run_tool_extraction(\n+ tool_parser,\n+ model_output,\n+ streaming=streaming,\n+ )\n+\n+ assert content == \"let me check the weather.It is 30 degrees.\"\n+ assert len(tool_calls) == 1\n+ assert tool_calls[0].function.name == \"get_weather\"\n+ assert tool_calls[0].function.arguments == '{\"city\": \"Paris\"}'\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][MoE] Respect padded row strides in top-k routing\nLabels: bug, ready\nFiles changed (2): csrc/moe/topk_softmax_kernels.cu, tests/kernels/moe/test_fused_topk.py\n\n## Description (results removed)\n\n## Purpose\n\nFixes #56900.\n\nInductor can produce router logits with padded physical rows, for example shape\n`[M, 60]` and stride `(64, 1)`. The native MoE top-k path used\n`blockIdx.x * num_experts` to locate each input row, so it read the wrong logits\nwhenever the physical row stride differed from `num_experts`. This silently\nchanged expert routing under compilation.\n\nThis change:\n\n- propagates `gating_output.stride(0)` to the native top-k launcher;\n- uses the existing unfused softmax/sigmoid plus top-k path for padded rows;\n- allocates the required workspace for padded power-of-two expert counts;\n- keeps packed rows on the existing specialized path; and\n logical/physical row widths.\n\nThe input-row offset is `int64_t` because PyTorch tensor strides are 64-bit;\nthis also avoids 32-bit wraparound in the input address calculation. Open PR\n[#53131](https://github.com/vllm-project/vllm/pull/53131) independently widens\npacked-row pointer arithmetic more broadly, but it does not propagate\n`stride(0)` or handle padded rows. The two changes overlap only on the\ninput-offset width; this PR addresses the separate functional stride bug.\n\nNo open PR referencing #56900 or implementing padded-row support for this\nkernel was found before submission.\n\n## Test Plan\n[results removed]\n## Test Result\n[results removed]\n## AI assistance\n\nAI assistance was used for root-cause analysis, implementation drafting, and\nvalidation planning. I reviewed every changed line and ran the tests and model\nevaluation reported above.\n\n## Diff\n\n```diff\ndiff --git a/csrc/moe/topk_softmax_kernels.cu b/csrc/moe/topk_softmax_kernels.cu\nindex b687e95f75e8..b9e8b319b462 100644\n--- a/csrc/moe/topk_softmax_kernels.cu\n+++ b/csrc/moe/topk_softmax_kernels.cu\n@@ -78,7 +78,8 @@ enum ScoringFunc {\n // in the softmax kernel when we extend this module to support expert-choice routing.\n template \n __launch_bounds__(TPB) __global__\n- void moeSoftmax(const InputType* input, const bool* finished, float* output, const int num_cols)\n+ void moeSoftmax(const InputType* input, const bool* finished, float* output, const int num_cols,\n+ const int64_t input_row_stride)\n {\n using BlockReduce = cub::BlockReduce;\n __shared__ typename BlockReduce::TempStorage tmpStorage;\n@@ -86,7 +87,8 @@ __launch_bounds__(TPB) __global__\n __shared__ float normalizing_factor;\n __shared__ float float_max;\n \n- const int thread_row_offset = blockIdx.x * num_cols;\n+ const int64_t input_row_offset = blockIdx.x * input_row_stride;\n+ const int output_row_offset = blockIdx.x * num_cols;\n \n float threadData(-FLT_MAX);\n \n@@ -98,8 +100,7 @@ __launch_bounds__(TPB) __global__\n \n for (int ii = threadIdx.x; ii < num_cols; ii += TPB)\n {\n- const int idx = thread_row_offset + ii;\n- const float val = toFloat(input[idx]);\n+ const float val = toFloat(input[input_row_offset + ii]);\n threadData = max(val, threadData);\n }\n \n@@ -114,8 +115,7 @@ __launch_bounds__(TPB) __global__\n \n for (int ii = threadIdx.x; ii < num_cols; ii += TPB)\n {\n- const int idx = thread_row_offset + ii;\n- const float val = toFloat(input[idx]);\n+ const float val = toFloat(input[input_row_offset + ii]);\n threadData += expf(val - float_max);\n }\n \n@@ -129,20 +129,21 @@ __launch_bounds__(TPB) __global__\n \n for (int ii = threadIdx.x; ii < num_cols; ii += TPB)\n {\n- const int idx = thread_row_offset + ii;\n- const float val = toFloat(input[idx]);\n+ const float val = toFloat(input[input_row_offset + ii]);\n float softmax_val = expf(val - float_max) * normalizing_factor;\n // Clamp NaN/Inf to 0 to prevent duplicate expert IDs downstream.\n if (isnan(softmax_val) || isinf(softmax_val)) softmax_val = 0.f;\n- output[idx] = softmax_val;\n+ output[output_row_offset + ii] = softmax_val;\n }\n }\n \n template \n __launch_bounds__(TPB) __global__\n- void moeSigmoid(const InputType* input, const bool* finished, float* output, const int num_cols)\n+ void moeSigmoid(const InputType* input, const bool* finished, float* output, const int num_cols,\n+ const int64_t input_row_stride)\n {\n- const int thread_row_offset = blockIdx.x * num_cols;\n+ const int64_t input_row_offset = blockIdx.x * input_row_stride;\n+ const int output_row_offset = blockIdx.x * num_cols;\n \n // Don't touch finished rows.\n if ((finished != nullptr) && finished[blockIdx.x])\n@@ -152,12 +153,11 @@ __launch_bounds__(TPB) __global__\n \n for (int ii = threadIdx.x; ii < num_cols; ii += TPB)\n {\n- const int idx = thread_row_offset + ii;\n- const float val = toFloat(input[idx]);\n+ const float val = toFloat(input[input_row_offset + ii]);\n float sigmoid_val = 1.0f / (1.0f + __expf(-val));\n // Clamp NaN/Inf to 0 to prevent duplicate expert IDs downstream.\n if (isnan(sigmoid_val) || isinf(sigmoid_val)) sigmoid_val = 0.f;\n- output[idx] = sigmoid_val;\n+ output[output_row_offset + ii] = sigmoid_val;\n }\n }\n \n@@ -688,6 +688,7 @@ void topkGatingKernelLauncher(\n float* workspace,\n const int num_tokens,\n const int num_experts,\n+ const int64_t input_row_stride,\n const int topk,\n const bool renormalize,\n const float* bias,\n@@ -703,6 +704,28 @@ void topkGatingKernelLauncher(\n static constexpr int BYTES_PER_LDG_MULTIPLE_64 =\n (std::is_same_v || std::is_same_v) ? 4 : 8;\n #endif\n+ // Inductor can pad GEMM outputs (for example, a [M, 60] view with a row\n+ // stride of 64). The fused kernels assume packed rows, so use the\n+ // stride-aware unfused path for row-padded inputs.\n+ if (input_row_stride != num_experts) {\n+ STD_TORCH_CHECK(workspace != nullptr,\n+ \"workspace must be provided for row-padded gating output.\");\n+ static constexpr int TPB = 256;\n+ if constexpr (SF == SCORING_SOFTMAX) {\n+ moeSoftmax<<>>(\n+ gating_output, nullptr, workspace, num_experts, input_row_stride);\n+ } else if constexpr (SF == SCORING_SIGMOID) {\n+ moeSigmoid<<>>(\n+ gating_output, nullptr, workspace, num_experts, input_row_stride);\n+ } else {\n+ STD_TORCH_CHECK(false, \"Unsupported scoring func\");\n+ }\n+ moeTopK<<>>(\n+ workspace, nullptr, topk_weights, topk_indices, token_expert_indices,\n+ num_experts, topk, 0, num_experts, renormalize, bias,\n+ routed_scaling_factor, is_padding);\n+ return;\n+ }\n switch (num_experts) {\n case 1:\n LAUNCH_TOPK(1, WARPS_PER_TB, BYTES_PER_LDG_POWER_OF_2);\n@@ -771,10 +794,10 @@ void topkGatingKernelLauncher(\n static constexpr int TPB = 256;\n if constexpr (SF == SCORING_SOFTMAX) {\n moeSoftmax<<>>(\n- gating_output, nullptr, workspace, num_experts);\n+ gating_output, nullptr, workspace, num_experts, input_row_stride);\n } else if constexpr (SF == SCORING_SIGMOID) {\n moeSigmoid<<>>(\n- gating_output, nullptr, workspace, num_experts);\n+ gating_output, nullptr, workspace, num_experts, input_row_stride);\n } else {\n STD_TORCH_CHECK(false, \"Unsupported scoring func\");\n }\n@@ -831,7 +854,7 @@ void dispatch_topk_launch(\n topk_indices.mutable_data_ptr(),\n token_expert_indices.mutable_data_ptr(),\n softmax_workspace.mutable_data_ptr(),\n- num_tokens, num_experts, topk, renormalize,\n+ num_tokens, num_experts, gating_output.stride(0), topk, renormalize,\n bias_ptr, routed_scaling_factor, stream, is_padding_ptr);\n } else if (topk_indices.scalar_type() == torch::headeronly::ScalarType::UInt32) {\n vllm::moe::topkGatingKernelLauncher(\n@@ -840,7 +863,7 @@ void dispatch_topk_launch(\n topk_indices.mutable_data_ptr(),\n token_expert_indices.mutable_data_ptr(),\n softmax_workspace.mutable_data_ptr(),\n- num_tokens, num_experts, topk, renormalize,\n+ num_tokens, num_experts, gating_output.stride(0), topk, renormalize,\n bias_ptr, routed_scaling_factor, stream, is_padding_ptr);\n } else {\n STD_TORCH_CHECK(topk_indices.scalar_type() == torch::headeronly::ScalarType::Long);\n@@ -850,7 +873,7 @@ void dispatch_topk_launch(\n topk_indices.mutable_data_ptr(),\n token_expert_indices.mutable_data_ptr(),\n softmax_workspace.mutable_data_ptr(),\n- num_tokens, num_experts, topk, renormalize,\n+ num_tokens, num_experts, gating_output.stride(0), topk, renormalize,\n bias_ptr, routed_scaling_factor, stream, is_padding_ptr);\n }\n }\n@@ -864,12 +887,17 @@ void topk_softmax(\n std::optional bias,\n std::optional is_padding)\n {\n+ STD_TORCH_CHECK(gating_output.dim() == 2,\n+ \"gating_output must be a 2D tensor\");\n const int num_experts = gating_output.size(-1);\n+ STD_TORCH_CHECK(num_experts == 1 || gating_output.stride(1) == 1,\n+ \"gating_output's last dimension must be contiguous\");\n const auto num_tokens = gating_output.numel() / num_experts;\n const int topk = topk_weights.size(-1);\n \n const bool is_pow_2 = (num_experts != 0) && ((num_experts & (num_experts - 1)) == 0);\n- const bool needs_workspace = !is_pow_2 || num_experts > 256;\n+ const bool needs_workspace = !is_pow_2 || num_experts > 256 ||\n+ gating_output.stride(0) != num_experts;\n const int64_t workspace_size = needs_workspace ? num_tokens * num_experts : 0;\n \n torch::stable::accelerator::DeviceGuard guard(gating_output.get_device_index());\n@@ -905,12 +933,17 @@ void topk_sigmoid(\n double routed_scaling_factor,\n std::optional is_padding)\n {\n+ STD_TORCH_CHECK(gating_output.dim() == 2,\n+ \"gating_output must be a 2D tensor\");\n const int num_experts = gating_output.size(-1);\n+ STD_TORCH_CHECK(num_experts == 1 || gating_output.stride(1) == 1,\n+ \"gating_output's last dimension must be contiguous\");\n const auto num_tokens = gating_output.numel() / num_experts;\n const int topk = topk_weights.size(-1);\n \n const bool is_pow_2 = (num_experts != 0) && ((num_experts & (num_experts - 1)) == 0);\n- const bool needs_workspace = !is_pow_2 || num_experts > 256;\n+ const bool needs_workspace = !is_pow_2 || num_experts > 256 ||\n+ gating_output.stride(0) != num_experts;\n const int64_t workspace_size = needs_workspace ? num_tokens * num_experts : 0;\n \n torch::stable::accelerator::DeviceGuard guard(gating_output.get_device_index());\ndiff --git a/tests/kernels/moe/test_fused_topk.py b/tests/kernels/moe/test_fused_topk.py\nindex 06a00fe06147..1a349acf1695 100644\n--- a/tests/kernels/moe/test_fused_topk.py\n+++ b/tests/kernels/moe/test_fused_topk.py\n@@ -89,6 +89,60 @@ def test_fused_topk(\n torch.testing.assert_close(topk_ids_ref.to(torch.int32), topk_ids, atol=0, rtol=0)\n \n \n+@pytest.mark.skipif(\n+ not current_platform.is_cuda_alike(),\n+ reason=\"This test is skipped on non-CUDA platform.\",\n+)\n+@pytest.mark.parametrize(\"num_experts,padded_num_experts\", [(60, 64), (64, 72)])\n+@pytest.mark.parametrize(\"scoring_func\", [\"softmax\", \"sigmoid\"])\n+def test_fused_topk_padded_row_stride(\n+ num_experts: int,\n+ padded_num_experts: int,\n+ scoring_func: str,\n+):\n+ \"\"\"Regression test for row-padded router logits produced by Inductor.\"\"\"\n+ torch.manual_seed(0)\n+ num_tokens = 33\n+ hidden_size = 128\n+ topk = 4\n+ dtype = torch.bfloat16\n+\n+ hidden_states = torch.randn((num_tokens, hidden_size), dtype=dtype, device=\"cuda\")\n+ storage = torch.full(\n+ (num_tokens, padded_num_experts),\n+ 1e4,\n+ dtype=dtype,\n+ device=\"cuda\",\n+ )\n+ gating_output = storage[:, :num_experts]\n+ gating_output.copy_(\n+ torch.linspace(-4, 4, num_experts, dtype=dtype, device=\"cuda\").expand(\n+ num_tokens, -1\n+ )\n+ )\n+ assert gating_output.stride() == (padded_num_experts, 1)\n+ assert not gating_output.is_contiguous()\n+\n+ topk_weights_ref, topk_ids_ref = torch_topk(\n+ gating_output=gating_output,\n+ topk=topk,\n+ renormalize=True,\n+ scoring_func=scoring_func,\n+ )\n+ topk_weights, topk_ids, _ = fused_topk(\n+ hidden_states=hidden_states,\n+ gating_output=gating_output,\n+ topk=topk,\n+ renormalize=True,\n+ scoring_func=scoring_func,\n+ )\n+\n+ torch.testing.assert_close(\n+ topk_weights_ref.to(torch.float32), topk_weights, atol=1e-2, rtol=1e-2\n+ )\n+ torch.testing.assert_close(topk_ids_ref.to(torch.int32), topk_ids, atol=0, rtol=0)\n+\n+\n @pytest.mark.skipif(\n not current_platform.is_cuda_alike(),\n reason=\"This test is skipped on non-CUDA platform.\",\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] [Frontend] Preserve prompt_logprobs in /v1/completions/derender\nLabels: bug, frontend, ready\nFiles changed (4): tests/entrypoints/scale_out/derender/test_derender.py, tests/entrypoints/scale_out/derender/test_derender_stream.py, vllm/entrypoints/scale_out/derender/serving.py, vllm/renderers/online_derenderer.py\n\n## Description (results removed)\n\nFixes #57929\n\n**Updated:** Chat fills `prompt_logprobs` inside `_derender_chat`, in the same background call that decodes the text \n\n**AI Assistance** \nCo-Authored-By: ZCode GLM 5.3 / Claude\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/scale_out/derender/serving.py b/vllm/entrypoints/scale_out/derender/serving.py\nindex 28468becd19e..d338d679c754 100644\n--- a/vllm/entrypoints/scale_out/derender/serving.py\n+++ b/vllm/entrypoints/scale_out/derender/serving.py\n@@ -172,7 +172,7 @@ async def derender_chat_response(\n )\n \n try:\n- choices = await self.online_derenderer.derender_chat(\n+ choices, prompt_logprobs = await self.online_derenderer.derender_chat(\n request.generate_response,\n request.chat_request,\n request.prompt_token_ids,\n@@ -205,7 +205,7 @@ async def derender_chat_response(\n created=int(time.time()),\n choices=choices,\n usage=usage,\n- prompt_logprobs=gen.prompt_logprobs,\n+ prompt_logprobs=prompt_logprobs,\n prompt_token_ids=(\n gen.prompt_token_ids\n if request.chat_request is not None\ndiff --git a/vllm/renderers/online_derenderer.py b/vllm/renderers/online_derenderer.py\nindex cad4877ec2e2..5c1b632f7bc0 100644\n--- a/vllm/renderers/online_derenderer.py\n+++ b/vllm/renderers/online_derenderer.py\n@@ -47,6 +47,7 @@\n resolve_finish_reason,\n )\n from vllm.logger import init_logger\n+from vllm.logprobs import Logprob, PromptLogprobs\n from vllm.outputs import CompletionOutput\n from vllm.parser import Parser, ParserManager\n from vllm.renderers import BaseRenderer\n@@ -147,7 +148,7 @@ async def derender_chat(\n generate_response: GenerateTokensResponse,\n chat_request: ChatCompletionRequest | None = None,\n prompt_token_ids: list[int] | None = None,\n- ) -> list[ChatCompletionResponseChoice]:\n+ ) -> tuple[list[ChatCompletionResponseChoice], PromptLogprobs | None]:\n return await self._derender_chat_async(\n generate_response, chat_request, prompt_token_ids\n )\n@@ -258,7 +259,7 @@ def _derender_chat(\n generate_response: GenerateTokensResponse,\n chat_request: ChatCompletionRequest | None = None,\n prompt_token_ids: list[int] | None = None,\n- ) -> list[ChatCompletionResponseChoice]:\n+ ) -> tuple[list[ChatCompletionResponseChoice], PromptLogprobs | None]:\n tokenizer = self.renderer.get_tokenizer()\n choices: list[ChatCompletionResponseChoice] = []\n \n@@ -353,7 +354,10 @@ def _derender_chat(\n )\n )\n \n- return choices\n+ prompt_logprobs = _resolve_prompt_logprobs(\n+ generate_response.prompt_logprobs, tokenizer\n+ )\n+ return choices, prompt_logprobs\n \n async def derender_text_choices(\n self,\n@@ -951,6 +955,7 @@ def _derender_completion(\n seed_state = _seed_stream_state(\n tokenizer, seed_ids, skip_special_tokens=skip_special\n )\n+ prompt_logprobs = _resolve_prompt_logprobs(gen.prompt_logprobs, tokenizer)\n for choice in gen.choices:\n if not choice.token_ids:\n raise ValueError(\n@@ -989,6 +994,7 @@ def _derender_completion(\n gen.prompt_token_ids if return_token_ids else None\n ),\n token_ids=choice.token_ids if return_token_ids else None,\n+ prompt_logprobs=prompt_logprobs,\n )\n )\n total_completion_tokens += len(choice.token_ids)\n@@ -1279,6 +1285,56 @@ def _completion_top_logprobs_limit(\n )\n \n \n+def _resolve_prompt_logprobs(\n+ prompt_logprobs: PromptLogprobs | None, tokenizer: TokenizerLike\n+) -> PromptLogprobs | None:\n+ \"\"\"Fill missing ``decoded_token`` values in prompt logprobs.\n+\n+ A ``--tokens-only`` generate server has no tokenizer, so it returns\n+ ``decoded_token=None``. Mirrors LogprobsProcessor._update_prompt_logprobs\n+ in v1/engine/logprobs.py: decode each token id, then fix U+FFFD using the\n+ preceding prompt tokens (the first entry of each earlier position).\n+ \"\"\"\n+ if prompt_logprobs is None:\n+ return None\n+\n+ missing = list(\n+ dict.fromkeys(\n+ tid\n+ for entry in prompt_logprobs\n+ if entry is not None\n+ for tid, lp in entry.items()\n+ if lp.decoded_token is None\n+ )\n+ )\n+ if not missing:\n+ return prompt_logprobs\n+ # Ids with no vocab entry decode to \"\", as for output logprobs.\n+ decoded = {\n+ tid: text\n+ for tid, (text, _) in zip(missing, decode_token_ids(missing, tokenizer))\n+ }\n+\n+ resolved: PromptLogprobs = []\n+ context_token_ids: list[int] = []\n+ for entry in prompt_logprobs:\n+ if not entry:\n+ resolved.append(entry)\n+ continue\n+ new_entry: dict[int, Logprob] = {}\n+ for tid, lp in entry.items():\n+ if lp.decoded_token is None:\n+ text = decoded[tid]\n+ if text.endswith(\"\\ufffd\"):\n+ text = _correct_decoded_token(tid, context_token_ids, tokenizer)\n+ lp = Logprob(lp.logprob, lp.rank, text)\n+ new_entry[tid] = lp\n+ resolved.append(new_entry)\n+ # The prompt token is always inserted first by the engine.\n+ context_token_ids.append(next(iter(entry)))\n+ return resolved\n+\n+\n def _resolve_logprobs(\n logprobs: GenerateLogProbs,\n tokenizer: TokenizerLike,\n\ndiff --git a/tests/entrypoints/scale_out/derender/test_derender.py b/tests/entrypoints/scale_out/derender/test_derender.py\nindex 667635eb9fc7..93ba9bf70581 100644\n--- a/tests/entrypoints/scale_out/derender/test_derender.py\n+++ b/tests/entrypoints/scale_out/derender/test_derender.py\n@@ -19,6 +19,7 @@\n )\n from vllm.renderers.online_derenderer import OnlineDerenderer\n from vllm.tokenizers import get_tokenizer\n+from vllm.tokenizers.detokenizer_utils import convert_ids_list_to_tokens\n \n MODEL_NAME = \"hmellor/tiny-random-LlamaForCausalLM\"\n \n@@ -522,6 +523,7 @@ def _make_completion_generate_response(\n request_id: str,\n kv_transfer_params: dict | None = None,\n logprobs: dict | None = None,\n+ prompt_logprobs: list | None = None,\n ) -> dict:\n return {\n \"request_id\": request_id,\n@@ -533,7 +535,7 @@ def _make_completion_generate_response(\n \"logprobs\": logprobs,\n }\n ],\n- \"prompt_logprobs\": None,\n+ \"prompt_logprobs\": prompt_logprobs,\n \"kv_transfer_params\": kv_transfer_params,\n }\n \n@@ -737,6 +739,81 @@ async def test_derender_completion_logprobs(client):\n assert logprobs[\"text_offset\"][0] == 0\n \n \n+@pytest.mark.asyncio\n+async def test_derender_completion_prompt_logprobs_passthrough(client):\n+ \"\"\"Each GenerateResponse's prompt_logprobs reaches that prompt's choices.\n+\n+ Regression test: /v1/completions/derender used to drop the prompt\n+ logprobs the engine had already computed and returned, while the direct\n+ /v1/completions endpoint attaches them to every choice of the prompt.\n+ \"\"\"\n+ gr1 = await _render_completion(client, \"Hello\")\n+ gr2 = await _render_completion(client, \"World\")\n+ tok = get_tokenizer(MODEL_NAME)\n+ # A --tokens-only generate server has no tokenizer: decoded_token is null.\n+ plp1 = [None, {str(gr1[\"token_ids\"][0]): {\"logprob\": -0.5, \"rank\": 1}}]\n+ plp2 = [None, {str(gr2[\"token_ids\"][0]): {\"logprob\": -0.25, \"rank\": 2}}]\n+\n+ response = await client.post(\n+ \"/v1/completions/derender\",\n+ json={\n+ \"model\": MODEL_NAME,\n+ \"generate_responses\": [\n+ _make_completion_generate_response(\n+ gr1[\"token_ids\"][:3], gr1[\"request_id\"], prompt_logprobs=plp1\n+ ),\n+ _make_completion_generate_response(\n+ gr2[\"token_ids\"][:3], gr2[\"request_id\"], prompt_logprobs=plp2\n+ ),\n+ ],\n+ },\n+ )\n+ assert response.status_code == 200\n+ choices = response.json()[\"choices\"]\n+ assert len(choices) == 2\n+ for choice, gr, plp in zip(choices, (gr1, gr2), (plp1, plp2)):\n+ tid = gr[\"token_ids\"][0]\n+ (text,) = convert_ids_list_to_tokens(tok, [tid])\n+ entry = choice[\"prompt_logprobs\"][1][str(tid)]\n+ assert plp[1] is not None\n+ assert choice[\"prompt_logprobs\"][0] is None\n+ assert entry[\"decoded_token\"] == text\n+ assert entry[\"logprob\"] == plp[1][str(tid)][\"logprob\"]\n+ assert entry[\"rank\"] == plp[1][str(tid)][\"rank\"]\n+\n+\n+@pytest.mark.asyncio\n+async def test_derender_chat_prompt_logprobs_decoded_token(client):\n+ \"\"\"Null decoded_token is filled (unknown ids as \"\"); given ones and empty\n+ entries are kept.\"\"\"\n+ gen_req = await _render_chat(client)\n+ ids = gen_req[\"token_ids\"][:3]\n+ tok = get_tokenizer(MODEL_NAME)\n+ plp = [\n+ None,\n+ {str(ids[0]): {\"logprob\": -0.5, \"rank\": 1}},\n+ {str(ids[1]): {\"logprob\": -0.1, \"rank\": 1, \"decoded_token\": \"kept\"}},\n+ {},\n+ {str(len(tok) + 1000): {\"logprob\": -1.0, \"rank\": 1}},\n+ ]\n+ response = await client.post(\n+ \"/v1/chat/completions/derender\",\n+ json={\n+ \"model\": MODEL_NAME,\n+ \"generate_response\": _make_generate_response(ids, prompt_logprobs=plp),\n+ },\n+ )\n+ assert response.status_code == 200\n+ out = response.json()[\"prompt_logprobs\"]\n+ assert (\n+ out[1][str(ids[0])][\"decoded_token\"]\n+ == (convert_ids_list_to_tokens(tok, [ids[0]])[0])\n+ )\n+ assert out[2][str(ids[1])][\"decoded_token\"] == \"kept\"\n+ assert out[3] == {}\n+ assert out[4][str(len(tok) + 1000)][\"decoded_token\"] == \"\"\n+\n+\n @pytest.mark.asyncio\n async def test_derender_completion_kv_transfer_params_passthrough(client):\n \"\"\"kv_transfer_params passes through to CompletionResponse.\"\"\"\n@@ -1608,7 +1685,7 @@ def _derender_hermes_chat(\n )\n )\n \n- (choice,) = derenderer._derender_chat(response, request)\n+ (choice,), _ = derenderer._derender_chat(response, request)\n return choice\n \n \n@@ -1767,7 +1844,7 @@ def test_derender_batch_trims_stop_like_engine(\n messages=[{\"role\": \"user\", \"content\": \"Count\"}],\n **request_kwargs,\n )\n- (choice,) = derenderer._derender_chat(response, request)\n+ (choice,), _ = derenderer._derender_chat(response, request)\n output_text = choice.message.content\n else:\n request = CompletionRequest(model=MODEL_NAME, prompt=\"Count\", **request_kwargs)\ndiff --git a/tests/entrypoints/scale_out/derender/test_derender_stream.py b/tests/entrypoints/scale_out/derender/test_derender_stream.py\nindex c58f9cf0034f..ca25c90b27c2 100644\n--- a/tests/entrypoints/scale_out/derender/test_derender_stream.py\n+++ b/tests/entrypoints/scale_out/derender/test_derender_stream.py\n@@ -345,7 +345,7 @@ def test_non_streaming_derender_initializes_parser_prefix(\n tools=_WEATHER_TOOLS,\n )\n \n- choices = derenderer._derender_chat(response, request)\n+ choices, _ = derenderer._derender_chat(response, request)\n \n parser.set_prompt_token_ids.assert_called_once_with([11, 12])\n assert choices[0].message.tool_calls[0].function.name == \"tool\"\n@@ -409,7 +409,7 @@ def batch_content(token_ids: list[int], finish_reason: str) -> str:\n response = GenerateTokensResponse(\n request_id=\"test\", prompt_token_ids=[11, 12], choices=[choice]\n )\n- return derenderer._derender_chat(response, request)[0].message.content\n+ return derenderer._derender_chat(response, request)[0][0].message.content\n \n # Same decode window and seeding; \"length\" never drops a token.\n expected = batch_content(\n@@ -743,7 +743,7 @@ async def test_chat_batch_seeded_via_explicit_prompt_token_ids(\n self, derenderer, leading_space_ids\n ):\n prompt_ids, output_ids, expected = leading_space_ids\n- choices = await derenderer.derender_chat(\n+ choices, _ = await derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"t\",\n choices=[\n@@ -761,7 +761,7 @@ async def test_chat_batch_seeded_via_generate_response_fallback(\n self, derenderer, leading_space_ids\n ):\n prompt_ids, output_ids, expected = leading_space_ids\n- choices = await derenderer.derender_chat(\n+ choices, _ = await derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"t\",\n choices=[\n@@ -780,7 +780,7 @@ async def test_chat_batch_explicit_takes_precedence_over_fallback(\n ):\n prompt_ids, output_ids, expected = leading_space_ids\n wrong_ids = tokenizer.encode(\"a different prompt\", add_special_tokens=False)\n- choices = await derenderer.derender_chat(\n+ choices, _ = await derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"t\",\n choices=[\n@@ -799,7 +799,7 @@ async def test_chat_batch_without_prompt_context_stays_unseeded(\n self, derenderer, leading_space_ids\n ):\n _, output_ids, _ = leading_space_ids\n- choices = await derenderer.derender_chat(\n+ choices, _ = await derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"t\",\n choices=[\n@@ -1887,7 +1887,7 @@ async def test_stream_matches_batch(self, harmony_derenderer, harmony_encode):\n reasoning = \"\".join(d.reasoning or \"\" for d in deltas)\n content = \"\".join(d.content or \"\" for d in deltas)\n \n- batch_choices = await harmony_derenderer.derender_chat(\n+ batch_choices, _ = await harmony_derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"test-harmony-batch\",\n choices=[\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Sampler] Fix split top-p masking every token for huge logits (thinking_token_budget + spec decode emits token 0)\nLabels: bug, ready\nFiles changed (2): tests/v1/sample/test_topk_topp_sampler.py, vllm/v1/sample/ops/topk_topp_triton.py\n\n## Description (results removed)\n\n## Purpose\n\nThis affects `thinking_token_budget` with speculative decoding (MTP, on both the V1 runner and Model Runner V2) and any `top_p < 1`, including a model's `generation_config` default. When the budget is reached, the request emits token id 0 (`` for NemotronH) until `max_tokens` instead of the forced ``. Greedy requests and `top_p=1.0` are not affected.\n\n**Root cause.** The bug is in the split-row top-p pipeline (#54651), not in the thinking-budget code. `_topp_sb_mask_kernel` in `vllm/v1/sample/ops/topk_topp_triton.py` runs on CUDA for batches of 64 rows or fewer, for rows with top-p and without an active top-k. It finds its pivot in probability space but masks in logit space:\n\n```python\npivot_logit = tl.log(pivot) + logZ + M\nkeep = x > pivot_logit\n```\n\n- In the V1 rejection sampler, `softmax` gives NaN, the draft is rejected, and `sample_recovered_tokens_kernel` falls back to `recovered_id = 0`.\n- In the MRV2 verifier (`_resample_kernel`), argmax over an all `-inf` row returns index 0.\n\nSpec decode exposes the bug because the forced verification rows go through `apply_top_k_top_p`: V1 via `apply_sampling_constraints`, MRV2 via `SamplingStates.apply_top_k_top_p`. Non-spec decoding is safe only in the default configuration, where the fused FlashInfer sampler is used. If processed-logprobs mode is on, or the FlashInfer sampler is unavailable, non-spec sampling goes through the same Triton path and hits the same bug.\n\nThe monolithic `_topk_topp_kernel` (batches over 64) is left alone on purpose. Its `max_sample` estimate (avg + 10·std of a sample block) is far below 1e9, so `sum_exp` overflows to inf and the pivot becomes NaN. Its `not (final_pivot < max_logit)` guard then disables top-p for that row. Sampling stays correct because the 1e9 logit dominates the softmax.\n\nThis is not a duplicate of #54906 or #39573. Those were reported on v0.28.1 and v0.19, which predate the split pipeline (#54651, 2026-09-03), and they describe the budget being ignored rather than token-0 output. No open PR or issue covers split top-p masking with large logits. #55414 touches the same kernel, but only to precompile variants.\n\n## Known related follow-ups (out of scope)\n\n- Thinking-budget forcing uses a `1e9` sentinel logit. Masking every other token to `-inf` and keeping the forced logit (\"mask-and-bump\") would stop producing extreme values that downstream sampling ops must tolerate.\n- The `nomask = pivot * Z >= 1` guard in `_topp_sb_combine` is stale: pivots are always strictly below `hi = 1/Z`.\n- Duplicate matching uses inconsistent tolerances: `abs(a - b) < 1e-9` in the step/combine kernels versus exact equality in the mask kernel.\n\n## Test Plan\n[results removed]\n## Related issues\n\n- Related to #54906, but a different bug. #54906 reports the budget being ignored (reasoning continues) on MRV2 only, with `top_k=20` set. Rows with an active top-k go through the monolithic `_topk_topp_kernel`, not the split top-p path fixed here, so this PR is not expected to fix #54906.\n- Same symptom family as #39573 (closed), which was reported on v0.19, before the split top-p pipeline (#54651) existed.\n\n## Test Result\n[results removed]\n## AI assistance\n\nThis change was investigated and drafted with AI assistance (Claude). The submitter reviewed every changed line and ran the tests listed above.\n\nSigned-off-by: Gilad Zamoscinski <>\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/sample/ops/topk_topp_triton.py b/vllm/v1/sample/ops/topk_topp_triton.py\nindex 6945adc6627c..870aba02bf3e 100755\n--- a/vllm/v1/sample/ops/topk_topp_triton.py\n+++ b/vllm/v1/sample/ops/topk_topp_triton.py\n@@ -1480,8 +1480,6 @@ def _topp_sb_mask_kernel(\n return\n if fin < 0.0:\n fin = best_fin\n- logZ = tl.log(Z)\n- pivot_logit = tl.log(pivot) + logZ + M\n # numdup/numkeep are exact small integers held in fp32.\n ties = numkeep < numdup\n num_preceding = 0.0\n@@ -1507,15 +1505,12 @@ def _topp_sb_mask_kernel(\n for i in range(start, end, BLOCK):\n mask_n = i + offs < end\n x = tl.load(ROW + i + offs, mask=mask_n, other=-float(\"inf\"))\n- keep = x > pivot_logit\n+ # Mask in probability space (bitwise the step kernels' predicate);\n+ # the logit-space pivot rounds to M for huge |M|.\n+ prob = tl.exp(x - M) / Z\n+ keep = (prob > pivot) | (x == M)\n if ties:\n- # Match the boundary value in probability space with exact\n- # equality: `dup` is a probability computed by the step kernels\n- # as exp(x - M) / Z, so recomputing it here with the same ops\n- # reproduces it bitwise on any platform. (The log/exp round-trip\n- [comment with results removed]\n- # absolute tolerance.)\n- dmask = tl.exp(x - M) / Z == dup\n+ dmask = prob == dup\n cum = tl.cumsum(dmask.to(tl.int32)).to(tl.float32) + num_preceding\n keep_dup = dmask & (cum <= numkeep)\n keep = keep & (~dmask | keep_dup)\n\ndiff --git a/tests/v1/sample/test_topk_topp_sampler.py b/tests/v1/sample/test_topk_topp_sampler.py\nindex 93b71a5d9503..924f0703d3e5 100644\n--- a/tests/v1/sample/test_topk_topp_sampler.py\n+++ b/tests/v1/sample/test_topk_topp_sampler.py\n@@ -871,6 +871,38 @@ def test_topp_tie_break_deterministic(self):\n )\n assert len(kept_idx) == pytorch_kept\n \n+ # Both sizes take the split top-p pipeline (64 is its max batch). 1e9 / 0.6\n+ # models the forced logit after temperature=0.6.\n+ @pytest.mark.parametrize(\"batch_size\", [4, 64], ids=[\"split\", \"split-boundary\"])\n+ @pytest.mark.parametrize(\n+ \"forced_logit\", [1e9, 1e9 / 0.6], ids=[\"1e9\", \"1e9_over_temp0.6\"]\n+ )\n+ def test_topp_keeps_forced_huge_logit(self, batch_size: int, forced_logit: float):\n+ \"\"\"A forced logit of huge magnitude must survive top-p.\n+\n+ Regression: thinking-budget forcing writes 1e9 to the end-of-thinking\n+ logit. The split top-p mask kernel mapped its pivot back to logit\n+ space as log(pivot) + log(Z) + M, which fp32 rounds to M at that\n+ magnitude, so every token was masked and sampling produced token 0.\n+ \"\"\"\n+ from vllm.v1.sample.ops.topk_topp_triton import apply_top_k_top_p_triton\n+\n+ vocab_size, forced_token = 131072, 13\n+ logits = torch.randn(\n+ batch_size, vocab_size, generator=self.generator, dtype=torch.float32\n+ )\n+ logits[:, forced_token] = forced_logit\n+ p = torch.full((batch_size,), 0.95, dtype=torch.float32)\n+\n+ result = apply_top_k_top_p_triton(logits.clone(), None, p)\n+ assert (result[:, forced_token] == forced_logit).all()\n+ probs = result.softmax(dim=-1)\n+ assert not probs.isnan().any()\n+ assert (probs.argmax(dim=-1) == forced_token).all()\n+ if current_platform.is_cuda_alike():\n+ # Split path only; the monolithic kernel leaves this row unmasked.\n+ assert ((result != float(\"-inf\")).sum(-1) == 1).all()\n+\n def test_topp_ties_across_blocks(self):\n \"\"\"The split top-p tie budget must carry across a slice's blocks.\n \n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Parser] Stream DeepSeek V4/V3.2 string tool arguments incrementally\nLabels: bug, ready, tool-calling, deepseek, verified, DSv4, DSv4.1\nFiles changed (7): tests/parser/engine/test_deepseek_v4.py, tests/parser/engine/test_deepseek_v41.py, tests/tool_parsers/test_deepseekv32_tool_parser.py, tests/tool_parsers/test_deepseekv4_tool_parser.py, vllm/parser/deepseek_v32.py, vllm/parser/deepseek_v4.py, vllm/parser/deepseek_v41.py\n\n## Description (results removed)\n\n## Purpose\n\nFixes #52846.\n\nDeepSeek V4, V4.1 and V3.2 streamed a long string tool argument as one fragment when `` arrived. The configs set `arg_structural_chars=frozenset(\">\")`, so the engine skipped every plain body delta.\n\nThe fix now uses the per-parser `arg_value_extender` hook, the same way GLM (#61253) and Gemma4 (#61494) do. The earlier engine-level gate change is dropped.\n\n- `vllm/parser/deepseek_v4.py`: `_dsml_arg_value_extender` returns an extender while the last parameter is an open `string=\"true\"` value. Each delta streams as escaped JSON text without rerunning the converter. It stops on a parameter tag, keeping a tail so a tag split across deltas is caught.\n- Wired into `deepseek_v4_config`, `deepseek_v32_config`, and `deepseek_v41_config` (spaced DSML tags via `functools.partial`).\n- `_param_patterns`: the trailing-partial regex holds back an unfinished next `<|DSML|parameter` tag, so a streamed value never includes it (implicit close case).\n\n## Test Plan\n[results removed]\n## Test Result\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/parser/deepseek_v32.py b/vllm/parser/deepseek_v32.py\nindex de6634cf7368..ae5f33a09961 100644\n--- a/vllm/parser/deepseek_v32.py\n+++ b/vllm/parser/deepseek_v32.py\n@@ -28,6 +28,7 @@\n DSML_PARAM_CLOSE,\n DSML_PARAM_START,\n _dsml_arg_converter,\n+ _dsml_arg_value_extender,\n _unwrap_wrapper_args,\n )\n from vllm.parser.engine.events import EventType\n@@ -115,6 +116,7 @@ def deepseek_v32_config() -> ParserEngineConfig:\n },\n arg_converter=_dsml_arg_converter,\n arg_structural_chars=frozenset(\">\"),\n+ arg_value_extender=_dsml_arg_value_extender,\n strip_content_whitespace_with_tools=False,\n tool_args_json=False,\n )\ndiff --git a/vllm/parser/deepseek_v4.py b/vllm/parser/deepseek_v4.py\nindex 49ef63736531..f18b4ad46f9b 100644\n--- a/vllm/parser/deepseek_v4.py\n+++ b/vllm/parser/deepseek_v4.py\n@@ -28,6 +28,7 @@\n from vllm.parser.engine.events import EventType\n from vllm.parser.engine.parser_engine import ParserEngine\n from vllm.parser.engine.parser_engine_config import (\n+ ArgValueExtender,\n ParserEngineConfig,\n ParserState,\n Transition,\n@@ -64,24 +65,46 @@ def _param_patterns(\n \n The ``string`` attribute is optional: the model sometimes omits it, and\n dropping such a parameter hands the client a tool call with no arguments.\n+ The trailing-partial regex captures the open value up to the end of the\n+ text; ``_match_open_param`` holds back an unfinished next parameter tag\n+ so a streamed string value never includes it.\n \"\"\"\n start, close = re.escape(param_start), re.escape(param_close)\n head = rf'{start}\\s+name=\"([^\"]+)\"(?:\\s+string=\"([^\"]*)\")?\\s*>'\n return (\n re.compile(rf\"{head}(.*?)(?:{close}|(?={start}\\s+name=))\", re.DOTALL),\n- re.compile(rf\"{head}(.*)$\", re.DOTALL),\n+ re.compile(rf\"{head}(.*)\\Z\", re.DOTALL),\n )\n \n \n _PARAM_RE, _PARTIAL_PARAM_RE = _param_patterns(DSML_PARAM_START, DSML_PARAM_CLOSE)\n \n \n+def _match_open_param(\n+ raw_args: str, pos: int, partial_param_re: re.Pattern, param_start: str\n+) -> tuple[str, str | None, str, bool] | None:\n+ \"\"\"Return (name, is_str, value, held_back) for the trailing open param.\n+\n+ An unfinished next parameter tag (``param_start`` with no ``>`` after it)\n+ is cut from the value; ``held_back`` reports whether that happened.\n+ \"\"\"\n+ pm = partial_param_re.search(raw_args, pos)\n+ if pm is None:\n+ return None\n+ value = pm.group(3)\n+ cut = value.find(param_start, value.rfind(\">\") + 1)\n+ if cut >= 0:\n+ return pm.group(1), pm.group(2), value[:cut], True\n+ return pm.group(1), pm.group(2), value, False\n+\n+\n def _dsml_arg_converter(\n raw_args: str,\n partial: bool,\n *,\n param_re: re.Pattern = _PARAM_RE,\n partial_param_re: re.Pattern = _PARTIAL_PARAM_RE,\n+ param_start: str = DSML_PARAM_START,\n ) -> str:\n params: dict[str, object] = {}\n \n@@ -100,9 +123,11 @@ def _dsml_arg_converter(\n last_end = m.end()\n \n if partial:\n- pm = partial_param_re.search(raw_args, last_end)\n- if pm:\n- name, is_str, value = pm.group(1), pm.group(2), pm.group(3)\n+ open_param = _match_open_param(\n+ raw_args, last_end, partial_param_re, param_start\n+ )\n+ if open_param:\n+ name, is_str, value, _ = open_param\n if is_str == \"true\":\n params[name] = value\n else:\n@@ -112,6 +137,44 @@ def _dsml_arg_converter(\n return json.dumps(params, ensure_ascii=False)\n \n \n+def _dsml_arg_value_extender(\n+ raw_args: str,\n+ *,\n+ param_re: re.Pattern = _PARAM_RE,\n+ partial_param_re: re.Pattern = _PARTIAL_PARAM_RE,\n+ param_start: str = DSML_PARAM_START,\n+ param_close: str = DSML_PARAM_CLOSE,\n+) -> ArgValueExtender | None:\n+ # ``arg_structural_chars`` skips every delta without ``>``, so a long\n+ # string value would wait for its closing tag. Extend the open trailing\n+ # ``string=\"true\"`` value instead. The lexer can flush a held partial\n+ # tag as text, so keep a tail to catch a tag split across deltas.\n+ names = set()\n+ last_end = 0\n+ for m in param_re.finditer(raw_args):\n+ names.add(m.group(1))\n+ last_end = m.end()\n+ open_param = _match_open_param(raw_args, last_end, partial_param_re, param_start)\n+ if open_param is None:\n+ return None\n+ name, is_str, _, held_back = open_param\n+ if is_str != \"true\" or name in names or held_back:\n+ return None\n+\n+ keep = max(len(param_start), len(param_close)) - 1\n+ tail = raw_args[-keep:]\n+\n+ def extend(delta: str) -> str | None:\n+ nonlocal tail\n+ text = tail + delta\n+ if param_start in text or param_close in text:\n+ return None\n+ tail = text[-keep:]\n+ return json.dumps(delta, ensure_ascii=False)[1:-1]\n+\n+ return extend\n+\n+\n def _unwrap_wrapper_args(\n args_json: str,\n tools: list[Tool] | None,\n@@ -238,6 +301,7 @@ def deepseek_v4_config(thinking: bool = False) -> ParserEngineConfig:\n },\n arg_converter=_dsml_arg_converter,\n arg_structural_chars=frozenset(\">\"),\n+ arg_value_extender=_dsml_arg_value_extender,\n strip_content_whitespace_with_tools=False,\n tool_args_json=False,\n )\ndiff --git a/vllm/parser/deepseek_v41.py b/vllm/parser/deepseek_v41.py\nindex 84216005102a..76c7ad19bfd3 100644\n--- a/vllm/parser/deepseek_v41.py\n+++ b/vllm/parser/deepseek_v41.py\n@@ -8,6 +8,7 @@\n from vllm.parser.deepseek_v4 import (\n DeepSeekV4Parser,\n _dsml_arg_converter,\n+ _dsml_arg_value_extender,\n _param_patterns,\n deepseek_v4_config,\n )\n@@ -46,6 +47,14 @@ def deepseek_v41_config(thinking: bool = False) -> ParserEngineConfig:\n _dsml_arg_converter,\n param_re=_PARAM_RE,\n partial_param_re=_PARTIAL_PARAM_RE,\n+ param_start=DSML_PARAM_START,\n+ ),\n+ arg_value_extender=functools.partial(\n+ _dsml_arg_value_extender,\n+ param_re=_PARAM_RE,\n+ partial_param_re=_PARTIAL_PARAM_RE,\n+ param_start=DSML_PARAM_START,\n+ param_close=DSML_PARAM_CLOSE,\n ),\n )\n \n\ndiff --git a/tests/parser/engine/test_deepseek_v4.py b/tests/parser/engine/test_deepseek_v4.py\nindex f5b66d9dc1cb..3bf67b2a759a 100644\n--- a/tests/parser/engine/test_deepseek_v4.py\n+++ b/tests/parser/engine/test_deepseek_v4.py\n@@ -33,6 +33,7 @@\n DSML_TOOL_START_VARIANTS,\n DeepSeekV4Parser,\n _dsml_arg_converter,\n+ _dsml_arg_value_extender,\n _unwrap_wrapper_args,\n deepseek_v4_config,\n )\n@@ -1302,6 +1303,55 @@ def test_eos_not_leaked_when_reasoning_never_ends(self, chunk_size):\n assert output.tool_calls == []\n \n \n+# ── Open string values stream without re-running the converter (#52846) ──\n+\n+\n+class TestArgValueExtender:\n+ def test_stops_at_split_param_close(self):\n+ extend = _dsml_arg_value_extender(\n+ \"<\" + _PARAM_OPEN.format(name=\"k\", is_str=\"true\") + \"x\"\n+ )\n+ assert extend is not None\n+ assert [extend(d) for d in ['a\"\\n', \"\"]] == [\n+ 'a\\\\\"\\\\n',\n+ \" b\" + partial_tag\n+ )\n+ assert json.loads(_dsml_arg_converter(raw_args, True)) == {\"k\": \"a > b\"}\n+ assert _dsml_arg_value_extender(raw_args) is None\n+\n+ def test_arms_on_value_ending_in_newline(self):\n+ raw_args = \"<\" + _PARAM_OPEN.format(name=\"k\", is_str=\"true\") + \"def f():\\n\"\n+ assert json.loads(_dsml_arg_converter(raw_args, True)) == {\"k\": \"def f():\\n\"}\n+ assert _dsml_arg_value_extender(raw_args) is not None\n+\n+\n # ── Malformed DSML markup must not leak into content (#51914) ─────────\n \n _WRAPPER_VARIANTS = list(DSML_TOOL_START_VARIANTS)\ndiff --git a/tests/parser/engine/test_deepseek_v41.py b/tests/parser/engine/test_deepseek_v41.py\nindex 0b78c4d61785..75ef0bf044c9 100644\n--- a/tests/parser/engine/test_deepseek_v41.py\n+++ b/tests/parser/engine/test_deepseek_v41.py\n@@ -148,3 +148,52 @@ def test_python_argument_conversion_and_partial_values():\n \"bare\": 7,\n \"text\": \" a b\"}\n+ assert config.arg_value_extender(raw) is None\n+\n+\n+def test_long_string_argument_streams_before_close():\n+ [comment with results removed]\n+ # buffered until the closing parameter tag arrived.\n+ body = \"A\" * 4096\n+ text = (\n+ '<|DSML| calls>\\n<|DSML| invoke name=\"emit\">\\n'\n+ f'<|DSML| parameter name=\"text\" string=\"true\">{body}'\n+ \"\\n\\n\"\n+ )\n+ tools = [\n+ {\n+ \"type\": \"function\",\n+ \"function\": {\n+ \"name\": \"emit\",\n+ \"parameters\": {\n+ \"type\": \"object\",\n+ \"properties\": {\"text\": {\"type\": \"string\"}},\n+ },\n+ },\n+ }\n+ ]\n+ tokenizer, tokens = tokenizer_for(text, False)\n+ parser = parser_for(tokenizer, {\"thinking\": False})\n+ results = replay_streaming(\n+ parser, tokens, chunk_size=32, finished_on_last=True, tools=tools\n+ )\n+ arg_chunks = [\n+ tool_call.function.arguments\n+ for result in results\n+ if result\n+ for tool_call in result.tool_calls or []\n+ if tool_call.function and tool_call.function.arguments\n+ ]\n+ assert len(arg_chunks) > len(body) // 64\n+ assert json.loads(\"\".join(arg_chunks)) == {\"text\": body}\ndiff --git a/tests/tool_parsers/test_deepseekv32_tool_parser.py b/tests/tool_parsers/test_deepseekv32_tool_parser.py\nindex 40ad6033d3bf..3783ca8a78bb 100644\n--- a/tests/tool_parsers/test_deepseekv32_tool_parser.py\n+++ b/tests/tool_parsers/test_deepseekv32_tool_parser.py\n@@ -969,6 +969,45 @@ def test_emits_arguments_before_invoke_completes(self, parser):\n assert combined # some partial args emitted\n assert combined.startswith('{\"k\"')\n \n+ def test_long_string_argument_streams_before_close(self):\n+ \"\"\"A string body has no \">\" and must not be buffered until\n+ arrives (GitHub #52846).\"\"\"\n+ tool = ChatCompletionToolsParam(\n+ function=FunctionDefinition(\n+ name=\"emit\",\n+ parameters={\n+ \"type\": \"object\",\n+ \"properties\": {\"text\": {\"type\": \"string\"}},\n+ },\n+ ),\n+ )\n+ parser = make_parser(tools=[tool])\n+ body = \"A\" * 4096\n+ chunks = [\n+ f'{FC_START}\\n{INV_START}emit\">\\n{PARAM_START}text\" string=\"true\">',\n+ *(body[i : i + 32] for i in range(0, len(body), 32)),\n+ f\"{PARAM_END}\\n{INV_END}\\n{FC_END}\",\n+ ]\n+ per_chunk_args = []\n+ prev = \"\"\n+ for chunk in chunks:\n+ result = parser.extract_tool_calls_streaming(\n+ previous_text=prev,\n+ current_text=prev + chunk,\n+ delta_text=chunk,\n+ previous_token_ids=[],\n+ current_token_ids=[],\n+ delta_token_ids=[1],\n+ request=make_request(),\n+ )\n+ prev += chunk\n+ per_chunk_args.append(\n+ self._reconstruct_args([result]) if result is not None else \"\"\n+ )\n+\n+ assert sum(1 for args in per_chunk_args[1:-1] if args) > 1\n+ assert json.loads(\"\".join(per_chunk_args)) == {\"text\": body}\n+\n def test_no_marker_leak_chunked(self, parser):\n \"\"\"Chunked streaming must NOT leak DSML start-marker fragments\n as content (GitHub #40801).\"\"\"\ndiff --git a/tests/tool_parsers/test_deepseekv4_tool_parser.py b/tests/tool_parsers/test_deepseekv4_tool_parser.py\nindex e79465ed9b32..f730e29b9ad5 100644\n--- a/tests/tool_parsers/test_deepseekv4_tool_parser.py\n+++ b/tests/tool_parsers/test_deepseekv4_tool_parser.py\n@@ -254,6 +254,84 @@ def test_streaming_emits_incremental_argument_chunks():\n }\n \n \n+def _stream_param_body(properties: dict, param_open: str, body: str) -> list[str]:\n+ \"\"\"Stream one parameter body in 32-char chunks, one argument list per chunk.\"\"\"\n+ tool = ChatCompletionToolsParam(\n+ function=FunctionDefinition(\n+ name=\"emit\",\n+ parameters={\"type\": \"object\", \"properties\": properties},\n+ ),\n+ )\n+ parser = make_parser(tools=[tool])\n+ chunks = [\n+ f'{TC_START}\\n{INV_START}emit\">\\n{param_open}',\n+ *(body[i : i + 32] for i in range(0, len(body), 32)),\n+ f\"{PARAM_END}\\n{INV_END}\\n{TC_END}\",\n+ ]\n+ per_chunk_args = []\n+ previous_text = \"\"\n+ for delta_text in chunks:\n+ current_text = previous_text + delta_text\n+ delta = parser.extract_tool_calls_streaming(\n+ previous_text=previous_text,\n+ current_text=current_text,\n+ delta_text=delta_text,\n+ previous_token_ids=[],\n+ current_token_ids=[],\n+ delta_token_ids=[1],\n+ request=make_request(),\n+ )\n+ previous_text = current_text\n+ per_chunk_args.append(\n+ \"\".join(\n+ tool_call.function.arguments\n+ for tool_call in (delta.tool_calls if delta else [])\n+ if tool_call.function and tool_call.function.arguments\n+ )\n+ )\n+ return per_chunk_args\n+\n+\n+def test_streaming_long_string_argument_is_incremental():\n+ [comment with results removed]\n+ # buffered until arrived.\n+ body = \"A\" * 4096\n+ per_chunk_args = _stream_param_body(\n+ {\"text\": {\"type\": \"string\"}},\n+ f'{PARAM_START}text\" string=\"true\">',\n+ body,\n+ )\n+\n+ body_chunks = per_chunk_args[1:-1]\n+ assert sum(1 for args in body_chunks if args) > 1\n+ assert json.loads(\"\".join(per_chunk_args)) == {\"text\": body}\n+\n+\n+def test_streaming_non_string_argument_is_withheld_until_close():\n+ body = \"1\" * 128\n+ per_chunk_args = _stream_param_body(\n+ {\"count\": {\"type\": \"integer\"}},\n+ f'{PARAM_START}count\" string=\"false\">',\n+ body,\n+ )\n+\n+ assert not any(per_chunk_args[1:-1])\n+ assert json.loads(\"\".join(per_chunk_args)) == {\"count\": int(body)}\n+\n+\n+def test_streaming_string_argument_with_markup_is_incremental():\n+ body = '
x > y
\\n' * 64\n+ per_chunk_args = _stream_param_body(\n+ {\"html\": {\"type\": \"string\"}},\n+ f'{PARAM_START}html\" string=\"true\">',\n+ body,\n+ )\n+\n+ body_chunks = per_chunk_args[1:-1]\n+ assert sum(1 for args in body_chunks if args) > 1\n+ assert json.loads(\"\".join(per_chunk_args)) == {\"html\": body}\n+\n+\n def _with_strict(\n tools: list[ChatCompletionToolsParam],\n ) -> list[ChatCompletionToolsParam]:\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Spec Decode] Align MRV2 lm_head LoRA with logits rows\nLabels: bug, mrv2, verified\nFiles changed (3): tests/v1/worker/test_mrv2_lmhead_lora.py, vllm/v1/worker/gpu/lora_utils.py, vllm/v1/worker/gpu/model_runner.py\n\n## Description (results removed)\n\n## Purpose\n\nFixes #59161.\n\nModel Runner V2 built the lm_head LoRA mapping with one id per request. Under speculative decoding each request owns one bonus row plus one row per draft token (`cu_num_logits`), so an lm_head adapter missed its own request or landed on a neighbor. `make_lora_inputs` now repeats each request id by `np.diff(cu_num_logits_np)`.\n\nAdaptive verification and MRV2 PCP both reject LoRA at startup, so those counts do not need a later refresh. With LoRA on, `cu_num_logits_np` is exact.\n\n## Test Plan\n[results removed]\n## Test Result\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/worker/gpu/lora_utils.py b/vllm/v1/worker/gpu/lora_utils.py\nindex eb81a83662a1..738221317ef3 100644\n--- a/vllm/v1/worker/gpu/lora_utils.py\n+++ b/vllm/v1/worker/gpu/lora_utils.py\n@@ -96,9 +96,12 @@ def make_lora_inputs(\n req_ids: list[str],\n idx_mapping: np.ndarray,\n num_scheduled_tokens: np.ndarray,\n+ num_logits: np.ndarray,\n ) -> tuple[tuple[int, ...], tuple[int, ...], set[LoRARequest]]:\n lora_ids = self.lora_ids[idx_mapping]\n- prompt_lora_mapping = tuple(lora_ids)\n+ # One lm_head id per logits row: 1 + num_drafts rows per request\n+ # under spec decode.\n+ prompt_lora_mapping = tuple(lora_ids.repeat(num_logits))\n token_lora_mapping = tuple(lora_ids.repeat(num_scheduled_tokens))\n active_lora_requests: set[LoRARequest] = self.get_activate_loras(req_ids)\n return prompt_lora_mapping, token_lora_mapping, active_lora_requests\ndiff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py\nindex c1622ba8cda2..4b78637d4612 100644\n--- a/vllm/v1/worker/gpu/model_runner.py\n+++ b/vllm/v1/worker/gpu/model_runner.py\n@@ -1895,6 +1895,7 @@ def execute_model(\n input_batch.req_ids,\n input_batch.idx_mapping_np,\n input_batch.num_scheduled_tokens,\n+ np.diff(input_batch.cu_num_logits_np),\n )\n self._set_active_loras(*lora_inputs)\n else:\n\ndiff --git a/tests/v1/worker/test_mrv2_lmhead_lora.py b/tests/v1/worker/test_mrv2_lmhead_lora.py\nnew file mode 100644\nindex 000000000000..341854ad9875\n--- /dev/null\n+++ b/tests/v1/worker/test_mrv2_lmhead_lora.py\n@@ -0,0 +1,61 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+\n+import numpy as np\n+import pytest\n+\n+from vllm.lora.request import LoRARequest\n+from vllm.v1.worker.gpu.lora_utils import LoraState\n+\n+pytestmark = [pytest.mark.cpu_test, pytest.mark.skip_global_cleanup]\n+\n+\n+def test_prompt_lora_mapping_aligns_with_spec_decode_logits_rows():\n+ \"\"\"lm_head LoRA ids follow logits rows, not requests.\n+\n+ Under speculative decoding cu_num_logits is one bonus row plus each\n+ draft row. A per-request mapping writes the adapter onto a neighbor.\n+ \"\"\"\n+ state = LoraState(max_num_reqs=4)\n+ lora_b = LoRARequest(\"adapter-b\", 5, \"/tmp/adapter-b\")\n+ # State slots are not batch order: slot 1 is req-a, slot 0 is req-b.\n+ state.add_request(\"req-a\", 1, None)\n+ state.add_request(\"req-b\", 0, lora_b)\n+\n+ idx_mapping = np.array([1, 0], dtype=np.int32)\n+ # req-a: 1 bonus + 2 drafts. req-b: 1 bonus and no drafts.\n+ cu_num_logits = np.array([0, 3, 4], dtype=np.int32)\n+ num_logits = np.diff(cu_num_logits).astype(np.int32)\n+ # Query length is independent: req-a is still prefilling.\n+ num_scheduled = np.array([8, 1], dtype=np.int32)\n+\n+ prompt, token, requests = state.make_lora_inputs(\n+ [\"req-a\", \"req-b\"],\n+ idx_mapping,\n+ num_scheduled,\n+ num_logits,\n+ )\n+\n+ assert num_logits.tolist() == [3, 1]\n+ assert prompt == (0, 0, 0, 5)\n+ assert len(prompt) == int(cu_num_logits[-1])\n+ assert token == (0,) * 8 + (5,)\n+ assert requests == {lora_b}\n+\n+\n+def test_prompt_lora_mapping_repeats_for_multiple_sampled_tokens():\n+ \"\"\"Multiple sampled tokens per step still get one lm_head id per row.\"\"\"\n+ state = LoraState(max_num_reqs=2)\n+ lora = LoRARequest(\"adapter\", 3, \"/tmp/adapter\")\n+ state.add_request(\"req-a\", 0, lora)\n+ state.add_request(\"req-b\", 1, None)\n+ # Two logits rows per request, no drafts.\n+ num_logits = np.array([2, 2], dtype=np.int32)\n+ prompt, token, _requests = state.make_lora_inputs(\n+ [\"req-a\", \"req-b\"],\n+ np.array([0, 1], dtype=np.int32),\n+ np.array([2, 2], dtype=np.int32),\n+ num_logits,\n+ )\n+ assert prompt == (3, 3, 0, 0)\n+ assert token == (3, 3, 0, 0)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Preserve fp16 in legacy fused MoE LoRA\nLabels: bug, verified\nFiles changed (2): tests/lora/test_fused_moe_lora_kernel.py, vllm/lora/ops/triton_ops/fused_moe_lora_op.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #59920. Preserve the input dtype in the legacy fused MoE LoRA GEMM instead of unconditionally converting operands to bfloat16.\n\n## Claims\n Prevents silent fp16-to-bfloat16 conversion in the legacy shrink/expand kernel.\nKeeps both Triton descriptor and pointer-load paths aligned with the hidden-state input dtype.\nExtends large-rank fallback correctness coverage to fp16 and bf16.\n\n## Validation\n[results removed]\n## Details\n\nThe legacy two-kernel path previously cast both dot operands to `tl.bfloat16` to work around ROCm type inference across TMA and pointer-load branches. That changes fp16 LoRA arithmetic and can produce incorrect outputs. The kernel now derives the dot dtype from the input pointer element type and casts both operands to that type. The large-rank fallback test is parameterized over the existing fp16 and bf16 dtype matrix.\n\n## Diff\n\n```diff\ndiff --git a/vllm/lora/ops/triton_ops/fused_moe_lora_op.py b/vllm/lora/ops/triton_ops/fused_moe_lora_op.py\nindex 18bef4406ba8..09336c355392 100644\n--- a/vllm/lora/ops/triton_ops/fused_moe_lora_op.py\n+++ b/vllm/lora/ops/triton_ops/fused_moe_lora_op.py\n@@ -1131,11 +1131,13 @@ def _fused_moe_lora_kernel(\n )\n a_ptrs += BLOCK_SIZE_K * SPLIT_K * stride_ak\n \n- # Cast operands to matching dtype for tl.dot. On ROCm, Triton's\n- # compiler may infer different types for a and b when merging\n- # if/else branches (TMA desc path returns fp32, tl.load returns\n- # the pointer's element type).\n- accumulator += tl.dot(a.to(tl.bfloat16), b.to(tl.bfloat16))\n+ # Cast operands to the input dtype for tl.dot. On ROCm, Triton's\n+ # compiler may infer different types for a and b when merging if/else\n+ # branches (TMA desc path returns fp32, tl.load returns the pointer's\n+ # element type). Casting to bfloat16 here silently changes fp16 LoRA\n+ # operands and can produce incorrect results.\n+ dot_dtype = a_ptr.dtype.element_ty\n+ accumulator += tl.dot(a.to(dot_dtype), b.to(dot_dtype))\n \n if MUL_ROUTED_WEIGHT:\n moe_weight = tl.load(topk_weights_ptr + offs_token, mask=token_mask, other=0.0)\n\ndiff --git a/tests/lora/test_fused_moe_lora_kernel.py b/tests/lora/test_fused_moe_lora_kernel.py\nindex 11e4d31f87b8..340ea4978618 100644\n--- a/tests/lora/test_fused_moe_lora_kernel.py\n+++ b/tests/lora/test_fused_moe_lora_kernel.py\n@@ -365,11 +365,13 @@ def test_fused_moe_lora_kernel(\n @pytest.mark.parametrize(\"max_lora_rank\", [128, 256])\n @pytest.mark.parametrize(\"add_inputs\", [True, False])\n @pytest.mark.parametrize(\"num_slices\", [1, 2])\n+@pytest.mark.parametrize(\"dtype\", DTYPES)\n @pytest.mark.parametrize(\"device\", DEVICES)\n def test_fused_moe_lora_kernel_large_rank_fallback(\n max_lora_rank,\n add_inputs,\n num_slices,\n+ dtype,\n device,\n ):\n \"\"\"Ranks above the one-shot limit fall back to shrink/expand kernels.\"\"\"\n@@ -384,8 +386,6 @@ def test_fused_moe_lora_kernel_large_rank_fallback(\n N = 256\n K = 256\n block_size = 16\n- dtype = torch.bfloat16\n-\n topk_ids, topk_weights, token_lora_mapping, lora_ids = sample_data(\n num_tokens, num_sequences, max_loras, num_experts, top_k_num\n )\n@@ -424,19 +424,35 @@ def test_fused_moe_lora_kernel_large_rank_fallback(\n add_inputs=add_inputs,\n )\n \n+ strict_fp16 = dtype == torch.float16 and max_lora_rank == 256\n+ if strict_fp16:\n+ # An fp32 oracle is needed to catch an unintended fp16 -> bf16 cast.\n+ reference_hidden_states = hidden_states.float()\n+ reference_lora_a = [lora_a.float() for lora_a in lora_a_stacked]\n+ reference_lora_b = [lora_b.float() for lora_b in lora_b_stacked]\n+ else:\n+ reference_hidden_states = hidden_states\n+ reference_lora_a = lora_a_stacked\n+ reference_lora_b = lora_b_stacked\n+\n expected = use_torch(\n- hidden_states,\n+ reference_hidden_states,\n token_lora_mapping,\n topk_ids,\n- lora_a_stacked,\n- lora_b_stacked,\n+ reference_lora_a,\n+ reference_lora_b,\n top_k_num,\n num_slices,\n )\n if add_inputs:\n- expected += residual\n+ expected += residual.to(expected.dtype)\n \n- torch.testing.assert_close(output, expected, atol=2e-2, rtol=2e-2)\n+ if strict_fp16:\n+ # This separates the fp16 dot path from the old bf16-cast path while\n+ # allowing normal fp16 accumulation and output-rounding error.\n+ torch.testing.assert_close(output.float(), expected, atol=1e-2, rtol=8e-4)\n+ else:\n+ torch.testing.assert_close(output, expected, atol=2e-2, rtol=2e-2)\n \n \n def use_fused_moe_lora_kernel_naive(\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Resolve eager_break_during_capture at call time, not import time\nLabels: bug, ready, torch.compile, nvidia\nFiles changed (2): tests/v1/cudagraph/test_breakable_cudagraph.py, vllm/compilation/breakable_cudagraph.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #59940. `@eager_break_during_capture` decided whether to wrap a function when the decorated module was\nimported. With `VLLM_BATCH_INVARIANT=1`, the breakable-graph flag is turned on later, inside `VllmConfig` (#57586).\nAny import of `attention.py` before that point leaves `unified_attention_with_output` unwrapped, and FA2 then produces\nwrong tokens for short prefills. This PR makes the decorator always return its wrapper, so the setting is read at call\ntime. It's a 2-line removal plus CPU tests.\n\n## Claims\n\n- Breakable-graph eager breaks no longer depend on import order. In-process and default-fork engines with a cold\n model-info cache now get the wrapped attention op.\n active.\n- Every current and future user of the decorator is covered (33 sites, plus those added by #46372 and #57881), with no\n new imports.\n\n## Validation\n[results removed]\n## Details\n\n- **Root cause:** `vllm/compilation/breakable_cudagraph.py` had `if not is_breakable_cudagraph_enabled(): return fn`.\n On a cold model-info cache, `ModelConfig` construction imports `attention.py` via `registry._save_modelinfo_to_cache`\n → `weight_utils.atomic_writer` before `VllmConfig._maybe_enable_breakable_cudagraph` sets the env. Forked engine\n cores inherit the bare op. First reported by @Taimys in #58918 and in the #57311 thread.\n- **Scope beyond batch invariance:** as @LioEinaudi pointed out in #59940, the other branch of\n `_maybe_enable_breakable_cudagraph` (`_uses_breakable_cudagraph_by_default`, #52861) sets the same env var after the\n same early import, for the `DEFAULT_BREAKABLE_CUDAGRAPH_ARCHITECTURES` models on CUDA, with no\n `VLLM_BATCH_INVARIANT` involved. The ordering hazard is the same and this change covers it. I only validated the\n `VLLM_BATCH_INVARIANT=1` path above, and I did not run those models, so I can't say whether their outputs are\n affected.\n- **Why this isn't a duplicate of #57311:** #57311 (open) removes that particular import chain, and @Taimys confirmed it\n fixes that trigger on L20. The decorator stays import-order dependent, though: with #57311 applied on main and a warm\n cache, a user script that imports `vllm.model_executor.model_loader` before building `LLM` still ends up with the\n unwrapped op (verified by inspecting the op, not by comparing outputs). #53293 fixed the same root cause for Ray only. This PR removes the\n dependence at its source and works alongside #57311.\n- **Dynamo:** the wrapper's thread-local lookup traces without a graph break (`fullgraph=True` test), so no\n `is_compiling()` fast path is needed.\n `VLLM_BATCH_INVARIANT=1` FA2 run in the BI test suite)?\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/compilation/breakable_cudagraph.py b/vllm/compilation/breakable_cudagraph.py\nindex fbe86a51a4b6..3f2dd51f6b73 100644\n--- a/vllm/compilation/breakable_cudagraph.py\n+++ b/vllm/compilation/breakable_cudagraph.py\n@@ -95,8 +95,6 @@ def eager_break_during_capture(fn: F) -> F:\n def unified_attention_with_output(...):\n ...\n \"\"\"\n- if not is_breakable_cudagraph_enabled():\n- return fn\n \n @functools.wraps(fn)\n def wrapper(*args: Any, **kwargs: Any) -> Any:\n\ndiff --git a/tests/v1/cudagraph/test_breakable_cudagraph.py b/tests/v1/cudagraph/test_breakable_cudagraph.py\nindex 1b9a79a6ef2c..4e19912f4fef 100644\n--- a/tests/v1/cudagraph/test_breakable_cudagraph.py\n+++ b/tests/v1/cudagraph/test_breakable_cudagraph.py\n@@ -28,11 +28,10 @@\n def _enable_breakable_cudagraph(monkeypatch: pytest.MonkeyPatch):\n \"\"\"Enable breakable cudagraphs for this module's tests only.\n \n- eager_break_during_capture reads the env at decoration time, which\n- happens inside the test bodies, so a per-test fixture suffices.\n- monkeypatch restores the env so other test files running in the same\n- pytest process are unaffected (a module-level os.environ assignment\n- used to leak into test_cudagraph_dispatch.py and break it).\n+ A per-test fixture suffices. monkeypatch restores the env so other\n+ test files running in the same pytest process are unaffected (a\n+ module-level os.environ assignment used to leak into\n+ test_cudagraph_dispatch.py and break it).\n \"\"\"\n import vllm.envs as envs\n \n@@ -144,6 +143,99 @@ def f(x):\n assert calls == [3]\n \n \n+@pytest.mark.parametrize(\"enabled\", [False, True])\n+def test_decorator_passthrough_returns_fn_result(\n+ monkeypatch: pytest.MonkeyPatch, enabled: bool\n+):\n+ from vllm.compilation.breakable_cudagraph import eager_break_during_capture\n+\n+ if not enabled:\n+ monkeypatch.delenv(\"VLLM_USE_BREAKABLE_CUDAGRAPH\")\n+ sentinel = object()\n+\n+ @eager_break_during_capture\n+ def f():\n+ return sentinel\n+\n+ assert f() is sentinel\n+\n+\n+def test_decorator_breaks_when_enabled_after_decoration(\n+ monkeypatch: pytest.MonkeyPatch,\n+):\n+ \"\"\"VllmConfig can enable breakable cudagraphs after the decorated module\n+ was imported (e.g. on a cold model-info cache); the op must still break.\"\"\"\n+ from vllm.compilation.breakable_cudagraph import (\n+ BreakableCUDAGraphCapture,\n+ eager_break_during_capture,\n+ )\n+\n+ monkeypatch.delenv(\"VLLM_USE_BREAKABLE_CUDAGRAPH\")\n+\n+ @eager_break_during_capture\n+ def op(x):\n+ return x + 1\n+\n+ monkeypatch.setenv(\"VLLM_USE_BREAKABLE_CUDAGRAPH\", \"1\")\n+\n+ class _Capture:\n+ _capturing = True\n+\n+ def __init__(self):\n+ self.eager = []\n+\n+ def add_eager(self, fn):\n+ self.eager.append(fn)\n+ return fn()\n+\n+ capture = _Capture()\n+ BreakableCUDAGraphCapture._tls.active = capture\n+ assert op(1) == 2\n+ assert len(capture.eager) == 1\n+\n+\n+def test_attention_op_breaks_when_imported_before_enable(tmp_path):\n+ \"\"\"Importing the attention module before the flag is set must still yield\n+ the breakable wrapper (functools.wraps copies __name__/__wrapped__, so\n+ compare code objects).\"\"\"\n+ import os\n+ import subprocess\n+ import sys\n+\n+ env = {k: v for k, v in os.environ.items() if k != \"VLLM_USE_BREAKABLE_CUDAGRAPH\"}\n+ env[\"VLLM_CACHE_ROOT\"] = str(tmp_path)\n+ code = (\n+ \"import vllm.model_executor.layers.attention.attention as a\\n\"\n+ \"import vllm.compilation.breakable_cudagraph as b\\n\"\n+ \"c = a.unified_attention_with_output.__code__\\n\"\n+ \"w = b.eager_break_during_capture(lambda: None).__code__\\n\"\n+ \"assert (c.co_filename, c.co_name) == (w.co_filename, w.co_name), c\\n\"\n+ )\n+ subprocess.run([sys.executable, \"-c\", code], env=env, check=True)\n+\n+\n+@pytest.mark.parametrize(\"enabled\", [False, True])\n+def test_decorated_op_traces_without_graph_break(\n+ monkeypatch: pytest.MonkeyPatch, enabled: bool\n+):\n+ from vllm.compilation.breakable_cudagraph import eager_break_during_capture\n+\n+ if not enabled:\n+ monkeypatch.delenv(\"VLLM_USE_BREAKABLE_CUDAGRAPH\")\n+\n+ @eager_break_during_capture\n+ def op(x):\n+ return x * 2 + 1\n+\n+ def f(x):\n+ return op(x).sin()\n+\n+ torch._dynamo.reset()\n+ x = torch.randn(4)\n+ compiled = torch.compile(f, fullgraph=True, backend=\"eager\")\n+ torch.testing.assert_close(compiled(x), f(x))\n+\n+\n # ---------------------------------------------------------------------------\n # BreakableCUDAGraphCapture: thread-local + nested rejection\n # ---------------------------------------------------------------------------\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Core] Count unscheduled running requests toward max_loras\nLabels: bug, verified, scheduler\nFiles changed (3): tests/v1/core/test_scheduler.py, tests/v1/core/utils.py, vllm/v1/core/sched/scheduler.py\n\n## Description (results removed)\n\n## Overview\n\nCount the LoRA adapters of all running requests, not only those scheduled in the current step, when deciding whether a waiting request fits within `max_loras`. Without this, a skipped running request lets a request with another adapter in, and the next batch holds more than `max_loras` adapters and trips an assertion in `Scheduler.schedule()`.\n\nFixes #60301\n\n## Claims\n\n- With `--max-loras N`, a waiting request whose adapter would exceed `N` once a currently skipped running request resumes is no longer admitted early. This happens with pipeline parallelism and also on a single GPU, e.g. when a multimodal request is skipped because the step's encoder budget is used up.\n- Fixes `AssertionError` in `schedule()` (`assert len(scheduled_loras) <= self.lora_config.max_loras`), which escapes the engine core busy loop and kills the engine.\n- No behavior change when every running request is scheduled in the step.\n- One-line source change (the iterable the set is built from) plus its comment; `create_scheduler` in the scheduler test helpers gains a `lora_config` argument.\n\n## Validation\n[results removed]\n## Details\n\nRoot cause: `Scheduler.schedule()` seeds `scheduled_loras` from `scheduled_running_reqs` (`scheduler.py:869-877` on `main`) and the waiting loop admits a request only if its adapter fits in that set (`:918-929`). A running request is skipped in a step when it has nothing to schedule yet: with PP>1 once its prompt is fully scheduled but the output is pending (the `num_new_tokens == 0` case documented in the running loop), and through the other `continue` paths of the running loop (`next_decode_eligible_step` cadence for V2 + PP + async, DP prefill deferral, EC connector and encoder budget waits). Its adapter is then missing from the set, a request with another adapter is admitted, and once the skipped request is scheduled again both end up in one batch. The running loop does not consult `max_loras`, so the existing `assert` is the first thing to notice.\n\nFix: seed the set from `self.running`. Every request enters `self.running` through the waiting-loop admission check, so the number of distinct adapters among running requests stays at most `max_loras` and the assert holds. This is how the V0 scheduler counted (`curr_loras` was built from all running sequence groups), and what `LoRAConfig.max_loras` (\"Max number of LoRAs in a single batch\") requires. The variable keeps its name since it is still the set the waiting loop extends as it admits requests.\n\nNot a duplicate: I searched issues and PRs on `vllm-project/vllm` for `max_loras`, `scheduled_loras`, `LoRA scheduler`, `LoRA pipeline`, `LoRA async`, `max_loras assertion` and `no free lora slots`, and open PRs for `scheduler.py lora` and `LoRA schedule running requests`. Nothing reports or fixes this. Closest hits: #15422 (merged, introduced the current seeding), #14495 (closed feature request about \"No free lora slots\" for over-full batches, predates #15422), #17003 (usage question), #10840 (closed, a V0 LoRA scheduling policy), and the open priority-preemption PRs above.\n\nThis PR was co-authored with Claude.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/core/sched/scheduler.py b/vllm/v1/core/sched/scheduler.py\nindex 3e475a85ab20..2dc738587a31 100644\n--- a/vllm/v1/core/sched/scheduler.py\n+++ b/vllm/v1/core/sched/scheduler.py\n@@ -941,12 +941,13 @@ def schedule(self, throttle_prefills: bool = False) -> SchedulerOutput:\n duplicate_encoder_inputs,\n )\n \n- # Record the LoRAs in scheduled_running_reqs\n+ # Record the LoRAs of all running requests, including those not\n+ # scheduled in this step, which can join a later batch.\n scheduled_loras: set[int] = set()\n if self.lora_config:\n scheduled_loras = set(\n req.lora_request.lora_int_id\n- for req in scheduled_running_reqs\n+ for req in self.running\n if req.lora_request and req.lora_request.lora_int_id > 0\n )\n assert len(scheduled_loras) <= self.lora_config.max_loras\n\ndiff --git a/tests/v1/core/test_scheduler.py b/tests/v1/core/test_scheduler.py\nindex 03dd48255842..9a45ddaeb85b 100644\n--- a/tests/v1/core/test_scheduler.py\n+++ b/tests/v1/core/test_scheduler.py\n@@ -14,6 +14,7 @@\n CacheConfig,\n ECTransferConfig,\n KVTransferConfig,\n+ LoRAConfig,\n ModelConfig,\n SchedulerConfig,\n SpeculativeConfig,\n@@ -30,6 +31,7 @@\n )\n from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorStats\n from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import MultiConnector\n+from vllm.lora.request import LoRARequest\n from vllm.multimodal.inputs import (\n MultiModalFeatureSpec,\n MultiModalKwargsItem,\n@@ -409,6 +411,73 @@ def test_async_scheduling_pp_allows_rescheduling_with_output_placeholders():\n assert req.request_id in output.num_scheduled_tokens\n \n \n+def test_max_loras_counts_running_request_awaiting_output():\n+ \"\"\"PP: a running request with its prompt fully scheduled is skipped until\n+ its output returns, but still holds its LoRA slot, so a request with\n+ another adapter must not be admitted in the meantime.\"\"\"\n+ scheduler = create_scheduler(\n+ pipeline_parallel_size=2, lora_config=LoRAConfig(max_loras=1)\n+ )\n+ req_a, req_b = create_requests(num_requests=2, num_tokens=8, req_ids=[\"a\", \"b\"])\n+ req_a.lora_request = LoRARequest(\"lora-a\", 1, \"/path/a\")\n+ req_b.lora_request = LoRARequest(\"lora-b\", 2, \"/path/b\")\n+\n+ scheduler.add_request(req_a)\n+ assert scheduler.schedule().num_scheduled_tokens == {\"a\": 8}\n+\n+ scheduler.add_request(req_b)\n+ assert scheduler.schedule().num_scheduled_tokens == {}\n+ assert req_b.status == RequestStatus.WAITING\n+\n+\n+def test_max_loras_counts_running_request_skipped_for_encoder_budget():\n+ \"\"\"No PP: a running request skipped because earlier requests used up the\n+ step's encoder compute budget still holds its LoRA slot.\"\"\"\n+ scheduler = create_scheduler(lora_config=LoRAConfig(max_loras=2))\n+ scheduler.max_num_encoder_input_tokens = 100\n+ scheduler.encoder_cache_manager = EncoderCacheManager(cache_size=1000)\n+ # a: two 100-token images, one per step; b: image at 50, after a's.\n+ req_a, req_b = create_requests(\n+ num_requests=2,\n+ num_tokens=300,\n+ mm_positions=[\n+ [\n+ PlaceholderRange(offset=0, length=100),\n+ PlaceholderRange(offset=150, length=100),\n+ ],\n+ [PlaceholderRange(offset=50, length=100)],\n+ ],\n+ req_ids=[\"a\", \"b\"],\n+ )\n+ (req_c,) = create_requests(num_requests=1, num_tokens=10, req_ids=[\"c\"])\n+ req_a.lora_request = LoRARequest(\"lora-a\", 1, \"/path/a\")\n+ req_b.lora_request = LoRARequest(\"lora-b\", 2, \"/path/b\")\n+ req_c.lora_request = LoRARequest(\"lora-c\", 3, \"/path/c\")\n+\n+ scheduler.add_request(req_a)\n+ scheduler.add_request(req_b)\n+ output = scheduler.schedule()\n+ assert output.num_scheduled_tokens == {\"a\": 150, \"b\": 50}\n+ scheduler.update_from_output(\n+ output,\n+ ModelRunnerOutput(\n+ req_ids=[\"a\", \"b\"],\n+ req_id_to_index={\"a\": 0, \"b\": 1},\n+ sampled_token_ids=[[], []],\n+ logprobs=None,\n+ prompt_logprobs_dict={},\n+ pooler_output=[],\n+ ),\n+ )\n+\n+ # a's second image uses the whole encoder budget, so b is skipped; c\n+ # (a third adapter) must still wait.\n+ scheduler.add_request(req_c)\n+ output = scheduler.schedule()\n+ assert output.num_scheduled_tokens == {\"a\": 150}\n+ assert req_c.status == RequestStatus.WAITING\n+\n+\n def test_cached_request_data_resumed_all_token_ids_mrv1_only():\n \"\"\"all_token_ids carries a resumed request's token ids to the connector\n for the V1 model runner, but is skipped entirely for the V2 model runner.\ndiff --git a/tests/v1/core/utils.py b/tests/v1/core/utils.py\nindex 25e9373888db..4833e29df8f1 100644\n--- a/tests/v1/core/utils.py\n+++ b/tests/v1/core/utils.py\n@@ -10,6 +10,7 @@\n DiffusionConfig,\n ECTransferConfig,\n KVTransferConfig,\n+ LoRAConfig,\n ModelConfig,\n MultiModalConfig,\n ObservabilityConfig,\n@@ -89,6 +90,7 @@ def create_scheduler(\n scheduling_policy: SchedulerPolicy = \"fcfs\",\n diffusion_canvas_length: int | None = None,\n scheduler_cls: type[Scheduler] | None = None,\n+ lora_config: LoRAConfig | None = None,\n ) -> Scheduler | AsyncScheduler:\n \"\"\"Create scheduler under test.\n \n@@ -216,6 +218,7 @@ def create_scheduler(\n speculative_config=speculative_config,\n diffusion_config=diffusion_config,\n ec_transfer_config=ec_transfer_config,\n+ lora_config=lora_config,\n observability_config=ObservabilityConfig(\n per_request_spec_decode_metrics=per_request_spec_decode_metrics,\n ),\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Tool Parser] Parse multi-line JSON arguments in the DeepSeek V3 and V3.1 parsers\nLabels: bug, ready, tool-calling, deepseek\nFiles changed (4): tests/tool_parsers/test_deepseekv31_tool_parser.py, tests/tool_parsers/test_deepseekv3_tool_parser.py, vllm/tool_parsers/deepseekv31_tool_parser.py, vllm/tool_parsers/deepseekv3_tool_parser.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #60342. The `deepseek_v3` and `deepseek_v31` tool parsers lose tool calls whose JSON arguments the model pretty-prints over several lines: their regexes match the arguments with `.`, which stops at a newline.\n\n## Claims\n\n- Tool calls with multi-line JSON arguments are now parsed by `deepseek_v3` and `deepseek_v31`, in both streaming and non-streaming mode.\n\n## Validation\n[results removed]\n## Details\n\n- Root cause: `DeepSeekV3ToolParser` matches `function_arguments` with `.*` (`` .*[^\\n`] `` when streaming), and `DeepSeekV31ToolParser` with `.*?` / `.*`. Without `re.DOTALL`, `.` doesn't match `\\n`, so the non-streaming regex finds nothing and the streaming regex captures only the first line of the arguments.\n- Fix: only the arguments group uses `[\\s\\S]`. It stays non-greedy in the regexes used with `findall`, so parallel calls still split at the first closing tag. The type and function-name groups keep `.`, so a name can't span lines and the whole pattern doesn't need `re.DOTALL`.\n- The Rust frontend's parsers (`rust/src/parser/src/tool/deepseek_json`) don't use a regex here; `take_json_object` scans the object by brace depth, so from reading the code they already handle pretty-printed arguments. Only the Python parsers change.\n- Related PRs: #60361 (opened a few minutes before this one, still a draft) makes the same change to the V3 regexes and leaves V3.1 for later; this PR covers both parsers. #47503 edits the same DeepSeek-V3 regexes to accept an optional newline before the JSON fence, which is a different case, so whichever merges second needs a small rebase. #55473 wraps these regexes with timeouts and is independent.\n\nAI assistance was used for this change (tracking down the cause, writing the tests and this description). I reviewed every changed line and ran the tests above.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/tool_parsers/deepseekv31_tool_parser.py b/vllm/tool_parsers/deepseekv31_tool_parser.py\nindex ff5f605f511f..9bf6675a2d08 100644\n--- a/vllm/tool_parsers/deepseekv31_tool_parser.py\n+++ b/vllm/tool_parsers/deepseekv31_tool_parser.py\n@@ -43,12 +43,13 @@ def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n self.tool_call_start_token: str = \"<|tool▁call▁begin|>\"\n self.tool_call_end_token: str = \"<|tool▁call▁end|>\"\n \n+ # The arguments may be pretty-printed over several lines.\n self.tool_call_regex = re.compile(\n- r\"<|tool▁call▁begin|>(?P.*?)<|tool▁sep|>(?P.*?)<|tool▁call▁end|>\"\n+ r\"<|tool▁call▁begin|>(?P.*?)<|tool▁sep|>(?P[\\s\\S]*?)<|tool▁call▁end|>\"\n )\n \n self.stream_tool_call_portion_regex = re.compile(\n- r\"(?P.*)<|tool▁sep|>(?P.*)\"\n+ r\"(?P.*)<|tool▁sep|>(?P[\\s\\S]*)\"\n )\n \n self.stream_tool_call_name_regex = re.compile(\ndiff --git a/vllm/tool_parsers/deepseekv3_tool_parser.py b/vllm/tool_parsers/deepseekv3_tool_parser.py\nindex 9e18bdcd899a..ec6a8ba907f1 100644\n--- a/vllm/tool_parsers/deepseekv3_tool_parser.py\n+++ b/vllm/tool_parsers/deepseekv3_tool_parser.py\n@@ -46,12 +46,13 @@ def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n self.tool_call_start_token: str = \"<|tool▁call▁begin|>\"\n self.tool_call_end_token: str = \"<|tool▁call▁end|>\"\n \n+ # The arguments may be pretty-printed over several lines.\n self.tool_call_regex = re.compile(\n- r\"<|tool▁call▁begin|>(?P.*)<|tool▁sep|>(?P.*)\\n```json\\n(?P.*)\\n```<|tool▁call▁end|>\"\n+ r\"<|tool▁call▁begin|>(?P.*)<|tool▁sep|>(?P.*)\\n```json\\n(?P[\\s\\S]*?)\\n```<|tool▁call▁end|>\"\n )\n \n self.stream_tool_call_portion_regex = re.compile(\n- r\"(?P.*)<|tool▁sep|>(?P.*)\\n```json\\n(?P.*[^\\n`])\"\n+ r\"(?P.*)<|tool▁sep|>(?P.*)\\n```json\\n(?P[\\s\\S]*[^\\n`])\"\n )\n \n self.stream_tool_call_name_regex = re.compile(\n\ndiff --git a/tests/tool_parsers/test_deepseekv31_tool_parser.py b/tests/tool_parsers/test_deepseekv31_tool_parser.py\nindex 43597b1d1844..f90d471fab20 100644\n--- a/tests/tool_parsers/test_deepseekv31_tool_parser.py\n+++ b/tests/tool_parsers/test_deepseekv31_tool_parser.py\n@@ -1,8 +1,11 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import json\n+\n import pytest\n \n+from tests.tool_parsers.utils import run_tool_extraction\n from vllm.tokenizers import get_tokenizer\n from vllm.tool_parsers.deepseekv31_tool_parser import (\n DeepSeekV31ToolParser,\n@@ -59,3 +62,22 @@ def test_extract_tool_calls_with_multiple_tools(parser):\n \n # prefix is content\n assert result.content == \"some prefix text\"\n+\n+\n+@pytest.mark.parametrize(\"streaming\", [True, False])\n+def test_extract_tool_calls_with_multiline_arguments(parser, streaming):\n+ # The model may pretty-print the JSON arguments over several lines.\n+ args = {\"x\": 1, \"y\": [1, 2]}\n+ model_output = (\n+ \"<|tool▁calls▁begin|>\"\n+ f\"<|tool▁call▁begin|>foo<|tool▁sep|>{json.dumps(args, indent=2)}\"\n+ \"<|tool▁call▁end|>\"\n+ '<|tool▁call▁begin|>bar<|tool▁sep|>{\"y\":2}<|tool▁call▁end|>'\n+ \"<|tool▁calls▁end|>\"\n+ )\n+\n+ _, tool_calls = run_tool_extraction(parser, model_output, streaming=streaming)\n+\n+ assert [call.function.name for call in tool_calls] == [\"foo\", \"bar\"]\n+ assert json.loads(tool_calls[0].function.arguments) == args\n+ assert json.loads(tool_calls[1].function.arguments) == {\"y\": 2}\ndiff --git a/tests/tool_parsers/test_deepseekv3_tool_parser.py b/tests/tool_parsers/test_deepseekv3_tool_parser.py\nindex e0d2897e917e..ff64661000cb 100644\n--- a/tests/tool_parsers/test_deepseekv3_tool_parser.py\n+++ b/tests/tool_parsers/test_deepseekv3_tool_parser.py\n@@ -1,6 +1,7 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import json\n \n import pytest\n \n@@ -92,6 +93,32 @@ def test_config(self) -> ToolParserTestConfig:\n },\n )\n \n+ def test_multiline_json_arguments(self, tool_parser, streaming: bool):\n+ # The model may pretty-print the JSON arguments over several lines.\n+ weather = {\"city\": \"Tokyo\", \"unit\": \"celsius\"}\n+ hotels = {\"location\": \"Tokyo\", \"check_in\": \"2025-01-15\"}\n+ model_output = (\n+ \"<|tool▁calls▁begin|>\"\n+ \"<|tool▁call▁begin|>function<|tool▁sep|>get_weather\\n\"\n+ f\"```json\\n{json.dumps(weather, indent=2)}\\n```<|tool▁call▁end|>\"\n+ \"<|tool▁call▁begin|>function<|tool▁sep|>search_hotels\\n\"\n+ f\"```json\\n{json.dumps(hotels, indent=2)}\\n```<|tool▁call▁end|>\"\n+ \"<|tool▁calls▁end|>\"\n+ )\n+\n+ _, tool_calls = run_tool_extraction(\n+ tool_parser, model_output, streaming=streaming\n+ )\n+\n+ assert [call.function.name for call in tool_calls] == [\n+ \"get_weather\",\n+ \"search_hotels\",\n+ ]\n+ assert [json.loads(call.function.arguments) for call in tool_calls] == [\n+ weather,\n+ hotels,\n+ ]\n+\n @pytest.mark.parametrize(\"streaming\", [False, True])\n def test_preserves_text_after_tool_call(\n self,\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fall back from DeepGEMM and FlashInfer sampling when nvcc is missing\nLabels: bug, ready\nFiles changed (4): tests/utils_/test_deep_gemm_utils.py, tests/v1/sample/test_topk_topp_sampler.py, vllm/utils/deep_gemm.py, vllm/v1/sample/ops/topk_topp_sampler.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #60261. On a host with no CUDA toolkit, vLLM picks DeepGEMM for block-FP8 linear layers. DeepGEMM's JIT then asserts in `process_weights_after_loading`. With this PR, `is_deep_gemm_supported()` checks for the nvcc that DeepGEMM's JIT will use, and the FlashInfer top-k/top-p sampler checks `has_flashinfer()`. Both now fall back instead of crashing.\n\n## Claims\n\n- Block-FP8 models load on a host without a CUDA toolkit. vLLM selects `CutlassFp8BlockScaledMMKernel` and logs one warning that says why DeepGEMM is off.\n- When `has_flashinfer()` is False, the FlashInfer top-k/top-p sampler is not used. vLLM falls back to native sampling. If `VLLM_USE_FLASHINFER_SAMPLER=1` is set, it raises the existing `RuntimeError`.\n- Hosts with a CUDA toolkit still use DeepGEMM and the FlashInfer sampler.\n\n## Validation\n[results removed]\n## Details\n\n**DeepGEMM change.** The new `_deep_gemm_nvcc_path()` follows `find_cuda_toolkit()` at the pinned DeepJIT commit `3732a3b9`, the submodule of the DeepGEMM fork `1e1842a8` in `cmake/external_projects/deepgemm.cmake`:\n\n- The CUDA home is `CUDA_HOME`, else `CUDA_PATH`, else two levels above `which nvcc`, else `/usr/local/cuda`. It must exist.\n- nvcc is `DG_JIT_NVCC_COMPILER`. If that is not set, it is `DJ_JIT_NVCC_COMPILER`. If that is empty or not set, it is `/bin/nvcc`. It must be executable.\n\nThis is the same approach `has_flashinfer()` already uses for FlashInfer (commit `1fde8ff7d`, #58360). The change adds about 40 lines of non-test code.\n\n**Tests.** The new `tests/utils_/test_deep_gemm_utils.py` covers the toolkit search. Buildkite already runs it through `pytest -v -s utils_`. The new `test_flashinfer_sampler_fallback_when_flashinfer_disabled` covers the sampler gate. It only needs CUDA, so it also runs on the 16-SM `v1/sample` lane.\n\n**Needs maintainer attention.**\n\n**Limitations.**\n\n- The check only tests that nvcc exists. DeepJIT also asserts that nvcc is CUDA 12.9 or newer. A host with CUDA 12.4–12.8, or with no host compiler, still crashes as before. Covering that would need a subprocess call at kernel selection time.\n- Some DeepGEMM users still check only `has_deep_gemm()`: the sparse attention indexers, `vllm/v1/attention/backends/mla/indexer.py` and `vllm/v1/worker/ubatch_utils.py`. Without a toolkit they can still reach the assertion. They are not on this model's path, and several have no other kernel to fall back to.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/utils/deep_gemm.py b/vllm/utils/deep_gemm.py\nindex b995d19d893e..ecbeec380a48 100644\n--- a/vllm/utils/deep_gemm.py\n+++ b/vllm/utils/deep_gemm.py\n@@ -9,6 +9,7 @@\n import functools\n import importlib\n import os\n+import shutil\n from collections.abc import Callable\n from enum import Enum\n from typing import Any, NoReturn\n@@ -109,13 +110,45 @@ def from_oracle(cls) -> \"DeepGemmQuantScaleFMT\":\n return cached\n \n \n+_DEFAULT_CUDA_HOME = \"/usr/local/cuda\"\n+\n+\n+def _deep_gemm_nvcc_path() -> str | None:\n+ \"\"\"Return the nvcc DeepGEMM's JIT would run, or None if it is missing.\n+\n+ Mirrors ``deep_jit::CUDA::find_cuda_toolkit()``, which DeepGEMM runs on\n+ the first use of any kernel and which asserts when the toolkit is missing.\n+ \"\"\"\n+ cuda_home = os.environ.get(\"CUDA_HOME\") or os.environ.get(\"CUDA_PATH\")\n+ if not cuda_home:\n+ nvcc = shutil.which(\"nvcc\")\n+ cuda_home = (\n+ os.path.dirname(os.path.dirname(nvcc)) if nvcc else _DEFAULT_CUDA_HOME\n+ )\n+ if not os.path.exists(cuda_home):\n+ return None\n+ nvcc = os.environ.get(\n+ \"DG_JIT_NVCC_COMPILER\", os.environ.get(\"DJ_JIT_NVCC_COMPILER\")\n+ ) or os.path.join(cuda_home, \"bin\", \"nvcc\")\n+ return shutil.which(nvcc)\n+\n+\n @functools.cache\n def is_deep_gemm_supported() -> bool:\n \"\"\"Return `True` if DeepGEMM is supported on the current platform.\n Currently, only Hopper and Blackwell GPUs are supported.\n \"\"\"\n is_supported_arch = current_platform.support_deep_gemm()\n- return is_supported_arch and envs.VLLM_USE_DEEP_GEMM and has_deep_gemm()\n+ if not (is_supported_arch and envs.VLLM_USE_DEEP_GEMM and has_deep_gemm()):\n+ return False\n+ if _deep_gemm_nvcc_path() is None:\n+ logger.warning_once(\n+ \"DeepGEMM kernels are disabled: DeepGEMM JIT-compiles its kernels \"\n+ \"with nvcc, which is missing (CUDA_HOME, CUDA_PATH, PATH or \"\n+ \"/usr/local/cuda). Set CUDA_HOME to a CUDA toolkit to enable them.\"\n+ )\n+ return False\n+ return True\n \n \n @functools.cache\ndiff --git a/vllm/v1/sample/ops/topk_topp_sampler.py b/vllm/v1/sample/ops/topk_topp_sampler.py\nindex 14ee9b7064f4..9a02d864fc39 100644\n--- a/vllm/v1/sample/ops/topk_topp_sampler.py\n+++ b/vllm/v1/sample/ops/topk_topp_sampler.py\n@@ -13,6 +13,7 @@\n from vllm.platforms import CpuArchEnum, current_platform\n from vllm.platforms.interface import DeviceCapability\n from vllm.triton_utils import HAS_TRITON\n+from vllm.utils.flashinfer import has_flashinfer\n \n if HAS_TRITON:\n from vllm.v1.sample.ops.topk_topp_triton import (\n@@ -128,7 +129,9 @@ def flashinfer_sampler_supported() -> bool:\n capability = current_platform.get_device_capability()\n assert capability is not None\n unsupported_reason: str | None = None\n- if not FlashInferBackend.supports_compute_capability(capability):\n+ if not has_flashinfer():\n+ unsupported_reason = \"FlashInfer kernels are disabled\"\n+ elif not FlashInferBackend.supports_compute_capability(capability):\n unsupported_reason = (\n f\"unsupported compute capability {capability.as_version_str()}\"\n )\n\ndiff --git a/tests/utils_/test_deep_gemm_utils.py b/tests/utils_/test_deep_gemm_utils.py\nnew file mode 100644\nindex 000000000000..f64430cbc509\n--- /dev/null\n+++ b/tests/utils_/test_deep_gemm_utils.py\n@@ -0,0 +1,60 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+from collections.abc import Iterator\n+from pathlib import Path\n+\n+import pytest\n+\n+import vllm.utils.deep_gemm as dg\n+\n+\n+def _make_exe(path: Path) -> None:\n+ path.parent.mkdir(parents=True, exist_ok=True)\n+ path.touch(mode=0o755)\n+\n+\n+@pytest.fixture\n+def default_cuda_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:\n+ \"\"\"Hide any real toolkit and redirect /usr/local/cuda.\"\"\"\n+ for var in (\n+ \"CUDA_HOME\",\n+ \"CUDA_PATH\",\n+ \"DG_JIT_NVCC_COMPILER\",\n+ \"DJ_JIT_NVCC_COMPILER\",\n+ ):\n+ monkeypatch.delenv(var, raising=False)\n+ monkeypatch.setenv(\"PATH\", str(tmp_path / \"empty\"))\n+ home = tmp_path / \"usr_local_cuda\"\n+ monkeypatch.setattr(dg, \"_DEFAULT_CUDA_HOME\", str(home))\n+ return home\n+\n+\n+@pytest.fixture(autouse=True)\n+def deep_gemm_installed(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:\n+ \"\"\"Pretend DeepGEMM is importable on a GPU it supports.\"\"\"\n+ monkeypatch.setattr(dg.current_platform, \"support_deep_gemm\", lambda: True)\n+ monkeypatch.setattr(dg, \"has_deep_gemm\", lambda: True)\n+ monkeypatch.setenv(\"VLLM_USE_DEEP_GEMM\", \"1\")\n+ dg.is_deep_gemm_supported.cache_clear()\n+ yield\n+ dg.is_deep_gemm_supported.cache_clear()\n+\n+\n+def test_deep_gemm_unsupported_without_nvcc(default_cuda_home: Path):\n+ \"\"\"Wheel-only installs have no CUDA toolkit, so DeepGEMM's JIT cannot run\n+ and block FP8 must fall back to another kernel (#60261).\"\"\"\n+ assert not dg.is_deep_gemm_supported()\n+\n+\n+def test_deep_gemm_finds_toolkit_off_path(default_cuda_home: Path):\n+ _make_exe(default_cuda_home / \"bin\" / \"nvcc\")\n+ assert dg.is_deep_gemm_supported()\n+\n+\n+def test_deep_gemm_trusts_cuda_home(\n+ default_cuda_home: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path\n+):\n+ \"\"\"DeepGEMM's JIT does not look past CUDA_HOME, even when it is wrong.\"\"\"\n+ _make_exe(default_cuda_home / \"bin\" / \"nvcc\")\n+ monkeypatch.setenv(\"CUDA_HOME\", str(tmp_path / \"missing\"))\n+ assert not dg.is_deep_gemm_supported()\ndiff --git a/tests/v1/sample/test_topk_topp_sampler.py b/tests/v1/sample/test_topk_topp_sampler.py\nindex 924f0703d3e5..6d421cdd803c 100644\n--- a/tests/v1/sample/test_topk_topp_sampler.py\n+++ b/tests/v1/sample/test_topk_topp_sampler.py\n@@ -205,6 +205,22 @@ def fake_normalize_cuda_arch(major, minor):\n flashinfer_sampler_supported()\n \n \n+@pytest.mark.skipif(not current_platform.is_cuda(), reason=\"Requires CUDA\")\n+def test_flashinfer_sampler_fallback_when_flashinfer_disabled(monkeypatch):\n+ \"\"\"Without flashinfer-cubin, nvcc or ninja, FlashInfer cannot build its\n+ sampling kernels, so the sampler must fall back to native sampling.\"\"\"\n+ from vllm.v1.sample.ops import topk_topp_sampler\n+\n+ monkeypatch.setattr(topk_topp_sampler, \"has_flashinfer\", lambda: False)\n+\n+ monkeypatch.delenv(\"VLLM_USE_FLASHINFER_SAMPLER\", raising=False)\n+ assert topk_topp_sampler.flashinfer_sampler_supported() is False\n+\n+ monkeypatch.setenv(\"VLLM_USE_FLASHINFER_SAMPLER\", \"1\")\n+ with pytest.raises(RuntimeError, match=\"FlashInfer kernels are disabled\"):\n+ topk_topp_sampler.flashinfer_sampler_supported()\n+\n+\n # =============================================================================\n # Triton kernel tests\n # =============================================================================\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Benchmark] Support boolean sweep plot filters\nLabels: bug, performance, ready\nFiles changed (2): tests/benchmarks/test_plot_filters.py, vllm/benchmarks/sweep/plot.py\n\n## Description (results removed)\n\nFixes #60629.\n\nPlotEqualTo and PlotNotEqualTo now parse `true`/`false` as booleans when filtering boolean columns, while preserving existing string and numeric filtering behavior.\n\n### Tests\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/benchmarks/sweep/plot.py b/vllm/benchmarks/sweep/plot.py\nindex 6b36a7acc601..d5d702a9dab3 100644\n--- a/vllm/benchmarks/sweep/plot.py\n+++ b/vllm/benchmarks/sweep/plot.py\n@@ -31,10 +31,10 @@ class PlotFilterBase(ABC):\n def parse_str(cls, s: str):\n for op_key in PLOT_FILTERS:\n if op_key in s:\n- key, value = s.split(op_key)\n+ key, _, value = s.partition(op_key)\n return PLOT_FILTERS[op_key](\n- key,\n- value.removeprefix(op_key).strip(\"'\").strip('\"'),\n+ key.strip(),\n+ value.removeprefix(op_key).strip().strip(\"'\").strip('\"'),\n )\n else:\n raise ValueError(\n@@ -48,16 +48,29 @@ def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n raise NotImplementedError\n \n \n+def _parse_filter_target(series, target: str) -> float | bool | str:\n+ \"\"\"Parse a filter target using the column's value type when needed.\"\"\"\n+ if target.casefold() in (\"true\", \"false\"):\n+ dtype_kind = getattr(series.dtype, \"kind\", None)\n+ non_null_values = series.dropna()\n+ is_boolean = dtype_kind == \"b\" or (\n+ len(non_null_values) > 0\n+ and all(isinstance(value, bool) for value in non_null_values)\n+ )\n+ if is_boolean:\n+ return target.casefold() == \"true\"\n+\n+ try:\n+ return float(target)\n+ except ValueError:\n+ return target\n+\n+\n @dataclass\n class PlotEqualTo(PlotFilterBase):\n @override\n def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n- target: float | str\n- try:\n- target = float(self.target)\n- except ValueError:\n- target = self.target\n-\n+ target = _parse_filter_target(df[self.var], self.target)\n return df[df[self.var] == target]\n \n \n@@ -65,12 +78,7 @@ def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n class PlotNotEqualTo(PlotFilterBase):\n @override\n def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n- target: float | str\n- try:\n- target = float(self.target)\n- except ValueError:\n- target = self.target\n-\n+ target = _parse_filter_target(df[self.var], self.target)\n return df[df[self.var] != target]\n \n \n@@ -137,8 +145,10 @@ class PlotBinner:\n def parse_str(cls, s: str):\n for op_key in PLOT_BINNERS:\n if op_key in s:\n- key, value = s.split(op_key)\n- return PLOT_BINNERS[op_key](key, float(value.removeprefix(op_key)))\n+ key, _, value = s.partition(op_key)\n+ return PLOT_BINNERS[op_key](\n+ key.strip(), float(value.removeprefix(op_key).strip())\n+ )\n else:\n raise ValueError(\n f\"Invalid operator for plot binner '{s}'. \"\n\ndiff --git a/tests/benchmarks/test_plot_filters.py b/tests/benchmarks/test_plot_filters.py\nindex 2b58a99125e6..b6b13f55861d 100644\n--- a/tests/benchmarks/test_plot_filters.py\n+++ b/tests/benchmarks/test_plot_filters.py\n@@ -4,6 +4,7 @@\n import pytest\n \n from vllm.benchmarks.sweep.plot import (\n+ PlotBinner,\n PlotEqualTo,\n PlotFilterBase,\n PlotFilters,\n@@ -37,6 +38,13 @@ def setup_method(self):\n }\n )\n \n+ self.df_boolean = pd.DataFrame(\n+ {\n+ \"enable_prefix_caching\": [True, False],\n+ \"request_rate\": [10, 20],\n+ }\n+ )\n+\n @pytest.mark.parametrize(\n \"target,expected_count\",\n [\n@@ -78,6 +86,45 @@ def test_not_equal_to_inf_float(self):\n # Should exclude float('inf') entries\n assert len(result) == 3\n \n+ def test_equal_to_boolean(self):\n+ \"\"\"Boolean filter targets should match JSON boolean columns.\"\"\"\n+ filter_obj = PlotFilters.parse_str(\"enable_prefix_caching==true\")\n+\n+ result = filter_obj.apply(self.df_boolean)\n+\n+ assert result[\"request_rate\"].tolist() == [10]\n+\n+ def test_not_equal_to_boolean(self):\n+ \"\"\"Boolean inequality should exclude only the matching rows.\"\"\"\n+ filter_obj = PlotFilters.parse_str(\"enable_prefix_caching!=true\")\n+\n+ result = filter_obj.apply(self.df_boolean)\n+\n+ assert result[\"request_rate\"].tolist() == [20]\n+\n+ def test_boolean_target_is_literal_for_string_column(self):\n+ \"\"\"String labels named true/false must keep string comparisons.\"\"\"\n+ df = pd.DataFrame({\"label\": [\"true\", \"false\"]})\n+\n+ result = PlotFilters.parse_str(\"label==true\").apply(df)\n+\n+ assert result[\"label\"].tolist() == [\"true\"]\n+\n+ def test_boolean_filter_with_missing_values(self):\n+ \"\"\"Nullable boolean columns keep missing rows out of either match.\"\"\"\n+ df = pd.DataFrame(\n+ {\n+ \"enabled\": pd.Series([True, False, None], dtype=\"boolean\"),\n+ \"request_rate\": [10, 20, 30],\n+ }\n+ )\n+\n+ equal = PlotFilters.parse_str(\"enabled==false\").apply(df)\n+ not_equal = PlotFilters.parse_str(\"enabled!=false\").apply(df)\n+\n+ assert equal[\"request_rate\"].tolist() == [20]\n+ assert not_equal[\"request_rate\"].tolist() == [10]\n+\n @pytest.mark.parametrize(\n \"target,expected_count\",\n [\n@@ -158,6 +205,20 @@ def test_parse_str_inf_edge_case(self):\n assert filter_obj.var == \"request_rate\"\n assert filter_obj.target == \"inf\"\n \n+ def test_parse_str_preserves_operator_in_quoted_target(self):\n+ \"\"\"Only the first operator separates a filter's variable and target.\"\"\"\n+ filter_obj = PlotFilterBase.parse_str('model==\"foo==bar\"')\n+\n+ assert filter_obj.var == \"model\"\n+ assert filter_obj.target == \"foo==bar\"\n+\n+ def test_parse_str_strips_variable_whitespace(self):\n+ \"\"\"Whitespace around a filter expression should not alter its column.\"\"\"\n+ filter_obj = PlotFilterBase.parse_str(\" request_rate >= 10.0 \")\n+\n+ assert filter_obj.var == \"request_rate\"\n+ assert filter_obj.target == \"10.0\"\n+\n def test_parse_multiple_filters(self):\n \"\"\"Test parsing multiple filters.\"\"\"\n filters = PlotFilters.parse_str(\"request_rate>5.0,value<=40\")\n@@ -169,3 +230,10 @@ def test_parse_empty_filter(self):\n \"\"\"Test parsing empty filter string.\"\"\"\n filters = PlotFilters.parse_str(\"\")\n assert len(filters) == 0\n+\n+ def test_parse_binner_strips_whitespace(self):\n+ \"\"\"Whitespace around a bin expression should not break parsing.\"\"\"\n+ binner = PlotBinner.parse_str(\" request_rate % 5 \")\n+\n+ assert binner.var == \"request_rate\"\n+ assert binner.bin_size == 5\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fix Triton prefill attention OutOfResources on GPUs with 99KiB shared memory\nLabels: bug, ready\nFiles changed (2): tests/kernels/attention/test_triton_prefill_attention.py, vllm/v1/attention/ops/triton_prefill_attention.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #60847.\n\n`google/embeddinggemma-2` crashes in engine warmup with Triton `OutOfResources` (`Required: 163840, Hardware limit: 101376`) on GPUs with 99 KiB of shared memory per block, such as RTX 30/40/50 cards and L4. The cause is that `context_attention_fwd` picks its tile size from the dtype and compute capability only. This change keeps halving the tile on CUDA until its Q, K and P tiles fit the device's opt-in shared memory per block.\n\nCompared with #60848, this fix:\n\nCompared with #60631, this fix:\n\n- Also fixes the reported model in float32. With [#60631](https://github.com/vllm-project/vllm/issues/60631), `vllm serve google/embeddinggemma-2 --runner pooling --dtype float32` still dies at engine start with `OutOfResources ... Required: 135168, Hardware limit: 101376`, from the same `context_attention_fwd` launch.\n\n## Claims\n\n- Tiles that already launched do not change. Output is bitwise the same for every configuration that worked before.\n\n## Validation\n[results removed]\n## Details\n\nRoot cause: `context_attention_fwd` sets `BLOCK_M = BLOCK_N = BLOCK` from `get_block_size(dtype)`. That returns 128 for bf16/fp16 on any GPU with capability 8.0 or higher, and 32 for fp32. The only other rule is `if Lk >= 512: BLOCK = min(BLOCK, 32)`. The kernel keeps a Q tile, a K tile and a P tile in shared memory. For bf16, head size 256 and BLOCK 128, that is `2 * (128*256 + 128*256 + 128*128) = 163840` bytes. A100 (166912) and H100/B200 (232448) have room for it, but sm_86, sm_89, sm_120 and sm_121 GPUs have only 101376. EmbeddingGemma2 has head size 256 on its sliding layers and 512 on its full layers, so vLLM forces `TRITON_ATTN`. Its bidirectional layers go through `_forward_encoder_attention` → `context_attention_fwd`. The 512 layers already get BLOCK 32 and fit. The 256 layers do not fit. The same problem breaks bf16/fp16 head size 192 and fp32 head size 512 (135168 bytes).\n\nFix: on CUDA, after the existing choices, halve BLOCK until `element_size * BLOCK * (2 * D + BLOCK)` fits in `get_max_shared_memory_bytes()` (`cudaDevAttrMaxSharedMemoryPerBlockOptin`). Here D is `next_power_of_2(Lk)`. BLOCK never goes below 16, the smallest tile `tl.dot` accepts. The result is cached per (block, head size, element size), so each call costs one cache lookup.\n\nThe formula comes from `_fwd_kernel.warmup().metadata.shared` on sm_120. For large head sizes it matches the real use exactly. For small head sizes it is higher than the real use. This holds for all 60 configurations measured. I do not claim it is an upper bound on every GPU: a review found that it under-counts fp16 use on sm_75, but the tiles it picks there still fit.\n\nEffect on 99 KiB GPUs: head sizes up to 128 keep 128. bf16/fp16 head size 192 or 256 goes from 128 to 64 (73728 bytes). fp32 head size 512 goes from 32 to 16. On A100, bf16 head size 256 keeps 128 and fp32 head size 512 keeps 32.\n\nLimitations:\n\n- ROCm does not change (there is an `is_cuda()` gate). The formula was measured on NVIDIA's Triton backend. On MI300 (65536 bytes of LDS) it would shrink the common head-size-128 tile, and I could not check if that is needed. Head-size-256 encoder attention on 64 KiB ROCm GPUs may have the same bug. I did not test it.\n- `get_max_shared_memory_bytes()` reads GPU 0 and keeps the first value it reads. On a host with mixed GPU types, the limit comes from one GPU. Other users of this helper have the same limit.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/attention/ops/triton_prefill_attention.py b/vllm/v1/attention/ops/triton_prefill_attention.py\nindex 9e8482b5ecdd..da6569262f53 100644\n--- a/vllm/v1/attention/ops/triton_prefill_attention.py\n+++ b/vllm/v1/attention/ops/triton_prefill_attention.py\n@@ -25,11 +25,14 @@\n \n # Adapted from\n # https://github.com/ModelTC/lightllm/blob/f2a54f0912293f683bf1d1695fd12c4098a5bf82/lightllm/models/llama/triton_kernel/context_flashattention_nopad.py#L1\n+from functools import cache\n+\n import torch\n \n from vllm.platforms import current_platform\n from vllm.triton_utils import tl, triton\n from vllm.utils.math_utils import RCP_LN2\n+from vllm.utils.mem_utils import get_max_shared_memory_bytes\n \n \n def _prefer_narrow_kv_tile() -> bool:\n@@ -223,6 +226,15 @@ def get_block_size(dtype: torch.dtype) -> int:\n return 64\n \n \n+@cache\n+def _fit_block_to_shared_memory(block: int, head_dim: int, element_size: int) -> int:\n+ \"\"\"Halve the tile until its Q, K and P tiles fit in shared memory.\"\"\"\n+ max_shared_mem = get_max_shared_memory_bytes()\n+ while block > 16 and element_size * block * (2 * head_dim + block) > max_shared_mem:\n+ block //= 2\n+ return block\n+\n+\n def context_attention_fwd(\n q: torch.Tensor,\n k: torch.Tensor,\n@@ -247,6 +259,10 @@ def context_attention_fwd(\n BLOCK = get_block_size(q.dtype)\n if Lk >= 512:\n BLOCK = min(BLOCK, 32)\n+ if current_platform.is_cuda():\n+ BLOCK = _fit_block_to_shared_memory(\n+ BLOCK, triton.next_power_of_2(Lk), q.element_size()\n+ )\n \n sm_scale = 1.0 / (Lq**0.5) if softmax_scale is None else softmax_scale\n # rescale with 1/ln(2) for triton exp2\n\ndiff --git a/tests/kernels/attention/test_triton_prefill_attention.py b/tests/kernels/attention/test_triton_prefill_attention.py\nindex e9b90251a492..90dccf6f425b 100644\n--- a/tests/kernels/attention/test_triton_prefill_attention.py\n+++ b/tests/kernels/attention/test_triton_prefill_attention.py\n@@ -80,7 +80,7 @@ def ref_masked_attention(\n @pytest.mark.parametrize(\"max_seq_len\", [1024])\n @pytest.mark.parametrize(\"H_Q\", [32])\n @pytest.mark.parametrize(\"H_KV\", [32, 8])\n-@pytest.mark.parametrize(\"D\", [128])\n+@pytest.mark.parametrize(\"D\", [128, 256, 512])\n @pytest.mark.parametrize(\"is_causal\", [True, False])\n @pytest.mark.parametrize(\"dtype\", [torch.float32, torch.bfloat16])\n def test_context_attention(\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Kernel] Sync cluster before DSMEM stores in ll_bf16 split-K router GEMM\nLabels: bug\nFiles changed (1): vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_splitk.py\n\n## Description (results removed)\n\n## Purpose\n\nFix: all threads `cluster_arrive_relaxed()` after pipeline init. DMA warps `cluster_wait()` after committing stage 0, and MMA warps wait at the start of their branch. So every peer is resident before the epilogue's `st.shared::cluster`, and the wait stays out of the PDL prologue (split suggested by @LopezCastroRoberto).\n\n## Reproduction\n\nThis uses @Skyseaee's single-GPU harness ([comment](https://github.com/vllm-project/vllm/pull/61463#issuecomment-6210051133)). It runs the router GEMM in a CUDA graph, concurrent with non-cluster copy kernels that write to mapped pinned host memory:\n```bash\nnvcc -O3 -shared -Xcompiler -fPIC -arch=sm_103a copy.cu -o libhostcopy.so\npython -u router_probe.py --tag --mode direct --seconds 120\n```\n\n[table with results removed]\n\n## Test results\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_splitk.py b/vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_splitk.py\nindex 2ae3d599227d..1a67b398e6ae 100644\n--- a/vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_splitk.py\n+++ b/vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_splitk.py\n@@ -357,6 +357,9 @@ def kernel(\n consumer_group=consumer_group,\n )\n \n+ # Peer CTAs must be running before the epilogue's DSMEM stores.\n+ cute.arch.cluster_arrive_relaxed()\n+\n # Round-robin split-K: split z handles tiles z, z+split_k, ...\n K_total = cute.size(mA, mode=[1])\n k_tile_count = cute.size(gA, mode=[2])\n@@ -402,6 +405,7 @@ def kernel(\n pred=tApA,\n )\n mainloop_pipeline.producer_commit(producer_state)\n+ cute.arch.cluster_wait()\n producer_state.advance()\n \n for k_tile in cutlass.range(\n@@ -428,6 +432,7 @@ def kernel(\n mainloop_pipeline.producer_tail(producer_state)\n \n else:\n+ cute.arch.cluster_wait()\n # MMA warps with k-phase interleaving\n cute.arch.setmaxregister_increase(232) # large MMA fragments\n \n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Honor OPT token embedding width for prompt embeddings\nLabels: bug, ready, ci/build, cpu\nFiles changed (9): tests/entrypoints/openai/completion/test_prompt_validation.py, tests/models/language/generation/test_common.py, tests/models/registry.py, tests/renderers/chat_utils/test_prompt_embeds.py, tests/renderers/test_completions.py, tests/renderers/test_prompt_embeds_payload_validation.py, tests/tokenizers_/test_detokenize.py, vllm/config/model.py, vllm/renderers/embed_utils.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #61709. Use OPT's token embedding width for prompt embedding validation and runner buffers so `facebook/opt-350m` works with `--enable-prompt-embeds`.\n\n## Claims\n\n- Accept OPT-350m's 512-wide prompt embeddings and reject its incompatible 1024-wide hidden states.\n- Allocate 512-wide input buffers for both model runners, matching `embed_input_ids()` and the decoder's `project_in` input.\n- Preserve CLIP/SigLIP text embedding validation when their projection width differs from their hidden size.\n\n## Validation\n[results removed]\n## Details\n\nAdd `word_embed_proj_dim` to the input-buffer size lookup and use it for request validation when present. Validation otherwise retains `get_hidden_size()`: using the buffer accessor wholesale would change CLIP/SigLIP validation to their projection width. Both runners share the corrected buffer accessor; no runner-specific branches or inference synchronization are added.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/config/model.py b/vllm/config/model.py\nindex 1dcf092229df..7a883eac547c 100644\n--- a/vllm/config/model.py\n+++ b/vllm/config/model.py\n@@ -1622,8 +1622,8 @@ def get_hidden_size(self) -> int:\n def get_inputs_embeds_size(self) -> int:\n # The size of inputs_embeds is usually identical to the size\n # of the hidden states, however there are exceptions, such as\n- # embedding models like CLIP and SigLIP\n- names = (\"projection_dim\", \"projection_size\")\n+ # OPT's projected token embeddings and embedding models like CLIP/SigLIP.\n+ names = (\"word_embed_proj_dim\", \"projection_dim\", \"projection_size\")\n return getattr_iter(\n self.hf_text_config, names, default_factory=self.get_hidden_size\n )\ndiff --git a/vllm/renderers/embed_utils.py b/vllm/renderers/embed_utils.py\nindex 981aeee3fb09..69ff920fa873 100644\n--- a/vllm/renderers/embed_utils.py\n+++ b/vllm/renderers/embed_utils.py\n@@ -91,11 +91,17 @@ def safe_load_prompt_embeds(\n parameter=\"prompt_embeds\",\n )\n \n- # Pin each tensor to the model's hidden_size. Validating here\n+ # Pin each tensor to the model's text embedding width. Validating here\n # also transitively guarantees cross-tensor consistency for requests that\n # include multiple `prompt_embeds` parts, which is required by downstream\n # concatenation in `_build_mixed_prompt_embeds`.\n- expected_hidden_size = model_config.get_hidden_size()\n+ # OPT projects token embeddings to hidden_size inside its decoder. CLIP\n+ # and SigLIP still accept text embeddings at hidden_size, not projection_dim.\n+ expected_hidden_size = getattr(\n+ model_config.hf_text_config,\n+ \"word_embed_proj_dim\",\n+ model_config.get_hidden_size(),\n+ )\n if tensor.shape[1] != expected_hidden_size:\n raise VLLMValidationError(\n f\"`prompt_embeds` hidden_size {tensor.shape[1]} does not match \"\n\ndiff --git a/tests/entrypoints/openai/completion/test_prompt_validation.py b/tests/entrypoints/openai/completion/test_prompt_validation.py\nindex 6c40037e07c9..7eecf6afbfcb 100644\n--- a/tests/entrypoints/openai/completion/test_prompt_validation.py\n+++ b/tests/entrypoints/openai/completion/test_prompt_validation.py\n@@ -64,6 +64,7 @@ def test_load_prompt_embeds(\n model_config = Mock(spec=ModelConfig)\n model_config.enable_prompt_embeds = True\n model_config.get_hidden_size.return_value = hidden_size\n+ model_config.hf_text_config = object()\n model_config.dtype = dtype\n \n # construct arbitrary tensors of various dtypes, layouts, and sizes.\ndiff --git a/tests/models/language/generation/test_common.py b/tests/models/language/generation/test_common.py\nindex 450e8badcebe..c65f8327aa13 100644\n--- a/tests/models/language/generation/test_common.py\n+++ b/tests/models/language/generation/test_common.py\n@@ -75,6 +75,9 @@\n \"facebook/opt-125m\", # opt\n marks=[pytest.mark.core_model, pytest.mark.cpu_model],\n ),\n+ pytest.param(\n+ \"facebook/opt-350m\", # opt with projected token embeddings\n+ ),\n pytest.param(\n \"microsoft/phi-2\", # phi\n marks=[pytest.mark.core_model, pytest.mark.slow_test],\ndiff --git a/tests/models/registry.py b/tests/models/registry.py\nindex dbb97991a247..f9dfafb40479 100644\n--- a/tests/models/registry.py\n+++ b/tests/models/registry.py\n@@ -462,7 +462,8 @@ def check_available_online(\n \"OlmoHybridForCausalLM\": _HfExamplesInfo(\"allenai/Olmo-Hybrid-7B\"),\n \"OlmoeForCausalLM\": _HfExamplesInfo(\"allenai/OLMoE-1B-7B-0924-Instruct\"),\n \"OPTForCausalLM\": _HfExamplesInfo(\n- \"facebook/opt-125m\", {\"1b\": \"facebook/opt-iml-max-1.3b\"}\n+ \"facebook/opt-125m\",\n+ {\"350m\": \"facebook/opt-350m\", \"1b\": \"facebook/opt-iml-max-1.3b\"},\n ),\n \"OrionForCausalLM\": _HfExamplesInfo(\n \"OrionStarAI/Orion-14B-Chat\", trust_remote_code=True\ndiff --git a/tests/renderers/chat_utils/test_prompt_embeds.py b/tests/renderers/chat_utils/test_prompt_embeds.py\nindex d6f1673ca79a..c036a950b5af 100644\n--- a/tests/renderers/chat_utils/test_prompt_embeds.py\n+++ b/tests/renderers/chat_utils/test_prompt_embeds.py\n@@ -105,6 +105,7 @@ def _make_mock_model_config(*, enable_prompt_embeds: bool = True) -> mock.MagicM\n # `safe_load_prompt_embeds` pins each tensor to the model's hidden_size\n # and dtype, so the mock must return concrete values.\n mc.get_hidden_size.return_value = _MOCK_HIDDEN_SIZE\n+ mc.hf_text_config = object()\n mc.dtype = _MOCK_DTYPE\n return mc\n \ndiff --git a/tests/renderers/test_completions.py b/tests/renderers/test_completions.py\nindex 4fac06380750..9d37ff78d1ad 100644\n--- a/tests/renderers/test_completions.py\n+++ b/tests/renderers/test_completions.py\n@@ -34,6 +34,7 @@ class MockModelConfig:\n tokenizer_revision = None\n tokenizer_mode = \"auto\"\n hf_config = MockHFConfig()\n+ hf_text_config = hf_config\n encoder_config: dict[str, Any] | None = None\n enable_prompt_embeds: bool = True\n skip_tokenizer_init: bool = False\ndiff --git a/tests/renderers/test_prompt_embeds_payload_validation.py b/tests/renderers/test_prompt_embeds_payload_validation.py\nindex bec28c4c49ac..d8342f52ee96 100644\n--- a/tests/renderers/test_prompt_embeds_payload_validation.py\n+++ b/tests/renderers/test_prompt_embeds_payload_validation.py\n@@ -65,6 +65,40 @@ def _saved_tensor(tensor: torch.Tensor) -> bytes:\n return buffer.getvalue()\n \n \n+@pytest.mark.parametrize(\n+ \"model, hidden_size, input_size, buffer_size\",\n+ [\n+ (\"facebook/opt-350m\", 1024, 512, 512),\n+ (\"facebook/opt-125m\", 768, 768, 768),\n+ (\"openai/clip-vit-base-patch32\", 512, 512, 1024),\n+ (\"google/siglip-base-patch16-224\", 768, 768, 1024),\n+ ],\n+)\n+def test_prompt_embeds_input_width(model, hidden_size, input_size, buffer_size):\n+ \"\"\"OPT uses its token width; dual encoders retain their text input width.\"\"\"\n+ from vllm.config import ModelConfig\n+\n+ config = ModelConfig(\n+ model=model,\n+ dtype=\"float32\",\n+ enable_prompt_embeds=True,\n+ )\n+ if \"opt-\" not in model:\n+ config.hf_text_config.projection_dim = buffer_size\n+ assert config.get_hidden_size() == hidden_size\n+ assert config.get_inputs_embeds_size() == buffer_size\n+\n+ tensor = torch.randn(4, input_size)\n+ loaded = safe_load_prompt_embeds(config, _encode(_saved_tensor(tensor)))\n+ torch.testing.assert_close(loaded, tensor)\n+\n+ wrong_size = hidden_size if hidden_size != input_size else input_size + 1\n+ with pytest.raises(VLLMValidationError, match=\"does not match\"):\n+ safe_load_prompt_embeds(\n+ config, _encode(_saved_tensor(torch.randn(4, wrong_size)))\n+ )\n+\n+\n UNPARSABLE_PAYLOADS = [\n pytest.param(b\"\", id=\"empty\"),\n pytest.param(b\"\\x80\", id=\"single-byte\"),\ndiff --git a/tests/tokenizers_/test_detokenize.py b/tests/tokenizers_/test_detokenize.py\nindex 1dd2a000a6fa..37e7252d2def 100644\n--- a/tests/tokenizers_/test_detokenize.py\n+++ b/tests/tokenizers_/test_detokenize.py\n@@ -15,6 +15,7 @@\n )\n from vllm.tokenizers.mistral import MistralTokenizer\n from vllm.tokenizers.protocol import TokenizerLike\n+from vllm.transformers_utils.repo_utils import with_retry\n from vllm.v1.engine import EngineCoreRequest\n from vllm.v1.engine.detokenizer import (\n FastIncrementalDetokenizer,\n@@ -95,10 +96,13 @@ def _run_incremental_decode(\n \n @pytest.fixture\n def tokenizer(tokenizer_name):\n- return (\n- MistralTokenizer.from_pretrained(tokenizer_name)\n- if \"mistral\" in tokenizer_name\n- else AutoTokenizer.from_pretrained(tokenizer_name)\n+ return with_retry(\n+ lambda: (\n+ MistralTokenizer.from_pretrained(tokenizer_name)\n+ if \"mistral\" in tokenizer_name\n+ else AutoTokenizer.from_pretrained(tokenizer_name)\n+ ),\n+ log_msg=f\"Error loading tokenizer {tokenizer_name}\",\n )\n \n \n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Kernel] Fill K-padded output in silu_and_mul_nvfp4_quant\nLabels: bug, ready, quantization\nFiles changed (3): csrc/quantization/fp4/activation_nvfp4_quant_fusion_kernels.cu, tests/kernels/quantization/nvfp4_utils.py, tests/kernels/quantization/test_silu_mul_nvfp4_quant.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #48898. Under torch.compile, NVFP4 models whose per-rank MLP width K is 16 mod 32 (e.g. Qwen2.5-72B / Qwen2.5-VL-72B at TP=8, K = 3696) produce garbage once a batch has more than one token. The SiluMul+NVFP4 fusion replaces the K-padded `scaled_fp4_quant` of the CUTLASS NVFP4 linear (#42774) with `silu_and_mul_nvfp4_quant`, which writes that buffer with the unpadded row pitch. #63382 fixed the padded scale factors of this kernel; the row pitch is what remains.\n\n## Claims\n\n- `silu_and_mul_nvfp4_quant` writes a K-padded output the way `scaled_fp4_quant(..., padded_n=...)` does: row pitch and scale tile from the output width, zero data in the padding.\n\n## Validation\n[results removed]\n## Details\n\n**Duplicate check.** #63382 fixed the padded scale factors but not the row pitch, so #48898 still reproduces on main (table above). #49092 and #49093 came out of the same investigation and fix other problems. #59467 (open) rewrites this kernel to add GELU-tanh; whichever lands second carries the padded-output handling, and I can rebase this one onto it.\n\n**CI coverage and limitations.** The kernel test needs SM100+ and is skipped on CI's L4 runners; the `(B200) Fusion and Compile` job runs the two fusion tests. I validated on SM120 only, with a CUDA 13.4 build (16-element path; the 8-element path of CUDA < 12.9 builds has the same change but was not run). The model-level check used the narrowed 0.5B model on one GPU, not a TP=8 72B deployment.\n\n**AI assistance.** This PR was prepared with AI assistance (Claude Code), which traced the root cause, wrote the fix and tests, ran the validation above and drafted this description.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/csrc/quantization/fp4/activation_nvfp4_quant_fusion_kernels.cu b/csrc/quantization/fp4/activation_nvfp4_quant_fusion_kernels.cu\nindex 269e50cfdf4a..fa70bc0ff325 100644\n--- a/csrc/quantization/fp4/activation_nvfp4_quant_fusion_kernels.cu\n+++ b/csrc/quantization/fp4/activation_nvfp4_quant_fusion_kernels.cu\n@@ -38,7 +38,8 @@ namespace vllm {\n template \n __global__ void __launch_bounds__(512, VLLM_BLOCKS_PER_SM(512))\n silu_mul_cvt_fp16_to_fp4(int32_t numRows, int32_t numCols,\n- int32_t num_packed_cols, int32_t num_padded_cols,\n+ int32_t outputCols, int32_t num_packed_cols,\n+ int32_t num_padded_cols,\n Type const* __restrict__ in,\n float const* __restrict__ SFScale,\n uint32_t* __restrict__ out,\n@@ -55,7 +56,7 @@ __global__ void __launch_bounds__(512, VLLM_BLOCKS_PER_SM(512))\n #endif\n \n // Precompute SF layout parameter (constant for entire kernel).\n- int32_t const numKTiles = (numCols + 63) / 64;\n+ int32_t const numKTiles = (outputCols + 63) / 64;\n \n int const sf_m = round_up(numRows, 128);\n \n@@ -116,15 +117,17 @@ __global__ void __launch_bounds__(512, VLLM_BLOCKS_PER_SM(512))\n *sf_out = 0;\n }\n \n- if (valid) {\n+ // Columns from numCols to outputCols are the K padding of the output\n+ // (scaled_fp4_quant's padded_n); out_val is zero there.\n+ if (rowIdx < numRows && elem_idx < outputCols) {\n if constexpr (CVT_FP4_PACK16) {\n- int64_t outOffset = rowIdx * (numCols / 8) + colIdx * 2;\n+ int64_t outOffset = rowIdx * (outputCols / 8) + colIdx * 2;\n uint64_t packed64 =\n (uint64_t(out_val.hi) << 32) | uint64_t(out_val.lo);\n reinterpret_cast(out)[outOffset >> 1] = packed64;\n } else {\n int64_t outOffset =\n- rowIdx * (numCols / CVT_FP4_ELTS_PER_THREAD) + colIdx;\n+ rowIdx * (outputCols / CVT_FP4_ELTS_PER_THREAD) + colIdx;\n reinterpret_cast(out)[outOffset] = out_val;\n }\n }\n@@ -141,8 +144,12 @@ void silu_and_mul_nvfp4_quant_sm1xxa(\n torch::stable::Tensor& input_sf) {\n int32_t m = input.size(0);\n int32_t n = input.size(1) / 2;\n+ int32_t output_n = output.size(1) * 2;\n \n STD_TORCH_CHECK(n % 16 == 0, \"The N dimension must be multiple of 16.\");\n+ STD_TORCH_CHECK(output_n % 16 == 0 && output_n >= n,\n+ \"The output tensor width must be a multiple of 16 and hold \"\n+ \"the input.\");\n STD_TORCH_CHECK(\n input.scalar_type() == torch::headeronly::ScalarType::Half ||\n input.scalar_type() == torch::headeronly::ScalarType::BFloat16,\n@@ -165,7 +172,7 @@ void silu_and_mul_nvfp4_quant_sm1xxa(\n \n // The swizzled scale tensor is padded to 128 rows x 4 scale columns; the\n // grid covers the padding so the kernel can initialize it.\n- int sf_n_int = int(vllm::round_up(n / CVT_FP4_SF_VEC_SIZE, 4) / 4);\n+ int sf_n_int = int(vllm::round_up(output_n / CVT_FP4_SF_VEC_SIZE, 4) / 4);\n int num_padded_cols =\n sf_n_int * 4 * CVT_FP4_SF_VEC_SIZE / CVT_FP4_ELTS_PER_THREAD;\n \n@@ -195,8 +202,8 @@ void silu_and_mul_nvfp4_quant_sm1xxa(\n config.numAttrs = use_pdl ? 1 : 0;\n config.attrs = attrs;\n cudaLaunchKernelEx(&config, vllm::silu_mul_cvt_fp16_to_fp4,\n- m, n, num_packed_cols, num_padded_cols, input_ptr,\n- input_sf_ptr,\n+ m, n, output_n, num_packed_cols, num_padded_cols,\n+ input_ptr, input_sf_ptr,\n reinterpret_cast(output_ptr),\n reinterpret_cast(sf_out));\n });\ndiff --git a/tests/kernels/quantization/nvfp4_utils.py b/tests/kernels/quantization/nvfp4_utils.py\nindex 04f7943ae630..87f20e1fcc18 100644\n--- a/tests/kernels/quantization/nvfp4_utils.py\n+++ b/tests/kernels/quantization/nvfp4_utils.py\n@@ -20,7 +20,7 @@ def convert_swizzled_to_linear(a_sf_swizzled: torch.Tensor, m, k, block_size):\n tmp = torch.reshape(a_sf_swizzled, (1, m_tiles, k_tiles, 32, 4, 4))\n tmp = torch.permute(tmp, (0, 1, 4, 3, 2, 5))\n out = tmp.reshape(m_tiles * 128, k_tiles * f // block_size)\n- return out[0:m, 0:k]\n+ return out[0:m, 0 : k // block_size]\n \n \n def convert_swizzled_8x4_layout_to_linear(\ndiff --git a/tests/kernels/quantization/test_silu_mul_nvfp4_quant.py b/tests/kernels/quantization/test_silu_mul_nvfp4_quant.py\nindex 8c0f931a2c98..86e7abc798d2 100644\n--- a/tests/kernels/quantization/test_silu_mul_nvfp4_quant.py\n+++ b/tests/kernels/quantization/test_silu_mul_nvfp4_quant.py\n@@ -11,6 +11,7 @@\n from vllm._custom_ops import scaled_fp4_quant\n from vllm.model_executor.layers.activation import SiluAndMul\n from vllm.platforms import current_platform\n+from vllm.utils.math_utils import round_up\n from vllm.utils.torch_utils import set_random_seed\n \n if not current_platform.has_device_capability(100):\n@@ -23,7 +24,21 @@\n FP8_DTYPE = current_platform.fp8_dtype()\n \n DTYPES = [torch.float16, torch.bfloat16]\n-SHAPES = [(128, 256), (128, 128), (256, 256), (256, 128), (1, 256), (64, 256)]\n+# (M, 2 * K). K = 48, 80 and 3696 (Qwen2.5-72B down_proj at TP=8) are 16 mod 32, so\n+# the NVFP4 linear pads K.\n+SHAPES = [\n+ (128, 256),\n+ (128, 128),\n+ (256, 256),\n+ (256, 128),\n+ (1, 256),\n+ (64, 256),\n+ (1, 96),\n+ (5, 96),\n+ (130, 96),\n+ (130, 160),\n+ (2, 7392),\n+]\n BLOCK_SIZE = 16\n \n \n@@ -41,15 +56,19 @@ def test_silu_mul_nvfp4_quant(\n \n x = torch.randn(shape, dtype=dtype)\n \n- # ref op\n- ref_output = SiluAndMul().forward_native(x)\n+ # ref op, rounded once from fp32 like the kernel, and quantized into the K-padded\n+ # buffer that the CUTLASS NVFP4 linear uses\n+ ref_output = SiluAndMul().forward_native(x.float()).to(dtype)\n+ k = ref_output.shape[1]\n ref_global_scale = (FLOAT8_E4M3_MAX * FLOAT4_E2M1_MAX) / torch.abs(\n ref_output\n ).max().to(torch.float32)\n- ref_output_quant, ref_block_scale = scaled_fp4_quant(ref_output, ref_global_scale)\n+ ref_output_quant, ref_block_scale = scaled_fp4_quant(\n+ ref_output, ref_global_scale, padded_n=round_up(k, 32)\n+ )\n \n- # fused op\n- fused_output_quant = torch.empty_like(ref_output_quant)\n+ # fused op, into an output holding stale bytes as under torch.compile buffer reuse\n+ fused_output_quant = torch.full_like(ref_output_quant, 0xFF)\n fused_block_scale = torch.empty_like(ref_block_scale)\n torch.ops._C.silu_and_mul_nvfp4_quant(\n fused_output_quant, fused_block_scale, x, ref_global_scale\n@@ -64,6 +83,9 @@ def test_silu_mul_nvfp4_quant(\n assert fused_block_scale.dtype == FP8_DTYPE\n assert ref_block_scale.shape == fused_block_scale.shape\n \n+ # check K padding: zero data beyond K\n+ assert not fused_output_quant[:, k // 2 :].any()\n+\n # check dequantized output\n ref_output_dequant = dequantize_nvfp4_to_dtype(\n ref_output_quant, ref_block_scale, ref_global_scale, dtype, device\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fix Opencv video backend frames count missing for WebM video inputs\nLabels: bug, ready, multi-modality\nFiles changed (3): tests/multimodal/test_video.py, tests/multimodal/utils.py, vllm/multimodal/video_decoders/opencv.py\n\n## Description (results removed)\n\n## Overview\n- Fix #60518 with a method to avoid decoding/unpacking all frames duplicately\n\n## Claims\n**Metadata recovery time (best of 4 runs)**\n\n[table with results removed]\n\n## Details\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/multimodal/video_decoders/opencv.py b/vllm/multimodal/video_decoders/opencv.py\nindex 3ca141c738c4..88d7fb837551 100644\n--- a/vllm/multimodal/video_decoders/opencv.py\n+++ b/vllm/multimodal/video_decoders/opencv.py\n@@ -38,7 +38,9 @@ def decode_opencv(\n int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),\n )\n- source = loader_cls._prepare_source(OpenCVVideoBackendMixin.get_video_metadata(cap))\n+ source = loader_cls._prepare_source(\n+ OpenCVVideoBackendMixin.get_video_metadata(data)\n+ )\n frame_idx = loader_cls.compute_frames_index_to_sample(\n source=source, target=target, **sampling_kwargs\n )\n@@ -74,10 +76,34 @@ def open_video_capture(cls, data: bytes) -> \"cv2.VideoCapture\":\n raise ValueError(\"Could not open video stream\")\n return cap\n \n+ @classmethod\n+ def demux_count_frames(cls, data: bytes) -> int:\n+ \"\"\"Count frames with OpenCV's demuxer-only mode.\"\"\"\n+ # NOTE: buf must stay referenced until after release().\n+ # OpenCV's Python stream binding does not safely own the stream object\n+ buf = BytesIO(data)\n+ demux_cap = cv2.VideoCapture(\n+ buf, cls.get_cv2_video_api(), [cv2.CAP_PROP_FORMAT, -1]\n+ )\n+ count = 0\n+ while demux_cap.grab():\n+ count += 1\n+ demux_cap.release()\n+ if count == 0:\n+ raise ValueError(\"Could not determine the number of video frames\")\n+ return count\n+\n @staticmethod\n- def get_video_metadata(cap: \"cv2.VideoCapture\") -> VideoSourceMetadata:\n+ def get_video_metadata(data: bytes) -> VideoSourceMetadata:\n+ cap = OpenCVVideoBackendMixin.open_video_capture(data)\n total_frames_num = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n original_fps = cap.get(cv2.CAP_PROP_FPS)\n+ if total_frames_num <= 0:\n+ # Streamed WebM/MKV and raw H.264 miss frame count in headers;\n+ # We need to use demux frames count for retrieval\n+ total_frames_num = OpenCVVideoBackendMixin.demux_count_frames(data)\n+ duration = total_frames_num / original_fps if original_fps > 0 else 0\n+ return VideoSourceMetadata(total_frames_num, original_fps, duration)\n # CAP_PROP_FRAME_COUNT counts every physical sample in the container,\n # overstating the presentable frames when an mp4 edit list hides the\n # decode lead-in (e.g. a lossless `ffmpeg -ss ... -c copy` trim).\n@@ -87,7 +113,7 @@ def get_video_metadata(cap: \"cv2.VideoCapture\") -> VideoSourceMetadata:\n # may land mid-stream on corrupt files, so only trust it when the\n # stream really ends there. A one-frame tolerance keeps mere header\n # miscounts from being \"corrected\".\n- if total_frames_num > 0 and cap.set(cv2.CAP_PROP_POS_AVI_RATIO, 1.0):\n+ if cap.set(cv2.CAP_PROP_POS_AVI_RATIO, 1.0):\n visible_frames = int(cap.get(cv2.CAP_PROP_POS_FRAMES))\n at_stream_end = not cap.grab()\n cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n\ndiff --git a/tests/multimodal/test_video.py b/tests/multimodal/test_video.py\nindex 1c7730a37ef8..16334fdb0dc7 100644\n--- a/tests/multimodal/test_video.py\n+++ b/tests/multimodal/test_video.py\n@@ -49,7 +49,9 @@\n \n from .utils import (\n create_edit_list_trimmed_video,\n+ create_live_webm_video,\n create_long_gop_video,\n+ create_raw_h264_video,\n create_video_from_image,\n )\n \n@@ -1261,8 +1263,8 @@ def test_qwen3_vl_unknown_source_fps_matches_hf(\n the metadata carries the fps HF assumes, which the frame timestamps use.\"\"\"\n get_video_metadata = OpenCVVideoBackendMixin.get_video_metadata\n \n- def unknown_fps(cap) -> VideoSourceMetadata:\n- return get_video_metadata(cap)._replace(original_fps=0.0, duration=0.0)\n+ def unknown_fps(data) -> VideoSourceMetadata:\n+ return get_video_metadata(data)._replace(original_fps=0.0, duration=0.0)\n \n monkeypatch.setattr(\n OpenCVVideoBackendMixin, \"get_video_metadata\", staticmethod(unknown_fps)\n@@ -1476,6 +1478,36 @@ def test_video_backend_handles_edit_list_trimmed_video(\n assert qwen_frames.shape[0] >= 4\n \n \n+def test_opencv_demux_counts_frames_when_video_header_lacks_metadata(\n+ monkeypatch: pytest.MonkeyPatch,\n+):\n+ \"\"\"Streamed WebM and raw H.264 carry no frame count/duration in their\n+ headers, so OpenCV reports a bogus negative ``CAP_PROP_FRAME_COUNT``.\n+ The loader must count the frames via a demux-only pass, without\n+ decoding.\n+ \"\"\"\n+ with monkeypatch.context() as m:\n+ m.setenv(\"VLLM_VIDEO_LOADER_BACKEND\", \"opencv\")\n+ loader = VIDEO_LOADER_REGISTRY.load(\"opencv\")\n+\n+ webm_data = create_live_webm_video(num_frames=20, fps=10)\n+ frames, metadata = loader.load_bytes(webm_data, backend=\"opencv\")\n+ assert frames.shape[0] == 20\n+ assert metadata[\"total_num_frames\"] == 20\n+ assert metadata[\"duration\"] == pytest.approx(2.0)\n+\n+ h264_data = create_raw_h264_video(num_frames=20, fps=25)\n+ frames, metadata = loader.load_bytes(h264_data, backend=\"opencv\")\n+ assert frames.shape[0] == 20\n+ assert metadata[\"total_num_frames\"] == 20\n+ assert metadata[\"duration\"] == pytest.approx(0.8)\n+\n+ # The Qwen samplers used to raise on the bogus negative frame count.\n+ qwen_frames, qwen_metadata = Qwen2VLVideoBackend.load_bytes(webm_data)\n+ assert qwen_metadata[\"total_num_frames\"] == 20\n+ assert qwen_frames.shape[0] >= 4\n+\n+\n # ============================================================================\n # Frame Recovery Tests\n # ============================================================================\ndiff --git a/tests/multimodal/utils.py b/tests/multimodal/utils.py\nindex 23a05a094422..d74f68453146 100644\n--- a/tests/multimodal/utils.py\n+++ b/tests/multimodal/utils.py\n@@ -1,6 +1,8 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import io\n+\n import cv2\n import numpy as np\n import numpy.typing as npt\n@@ -77,8 +79,6 @@ def create_long_gop_video(\n The marker lets a test recover which frame the decoder actually returned,\n independent of any metadata label.\n \"\"\"\n- import io\n-\n import av\n \n buf = io.BytesIO()\n@@ -103,6 +103,63 @@ def create_long_gop_video(\n return buf.getvalue()\n \n \n+def create_live_webm_video(\n+ num_frames: int = 20,\n+ fps: int = 10,\n+ width: int = 64,\n+ height: int = 64,\n+) -> bytes:\n+ \"\"\"Encode a WebM stream without container duration or frame-count metadata.\n+\n+ The ``live`` muxing option mimics writing to a pipe: the Segment size is\n+ unknown and no Duration or Cues elements are written, so decoder backends\n+ cannot learn the frame count from the header.\n+ \"\"\"\n+ import av\n+\n+ buf = io.BytesIO()\n+ with av.open(buf, mode=\"w\", format=\"webm\", options={\"live\": \"1\"}) as container:\n+ stream = container.add_stream(\"libvpx\", rate=fps)\n+ stream.width = width\n+ stream.height = height\n+ stream.pix_fmt = \"yuv420p\"\n+ for i in range(num_frames):\n+ img = np.zeros((height, width, 3), dtype=np.uint8)\n+ img[:, :, 1] = i % 256\n+ frame = av.VideoFrame.from_ndarray(img, format=\"rgb24\")\n+ for packet in stream.encode(frame):\n+ container.mux(packet)\n+ for packet in stream.encode():\n+ container.mux(packet)\n+ return buf.getvalue()\n+\n+\n+def create_raw_h264_video(\n+ num_frames: int = 20,\n+ fps: int = 25,\n+ width: int = 64,\n+ height: int = 64,\n+) -> bytes:\n+ \"\"\"Encode a raw H.264 Annex B elementary stream (no container metadata).\"\"\"\n+ import av\n+\n+ buf = io.BytesIO()\n+ with av.open(buf, mode=\"w\", format=\"h264\") as container:\n+ stream = container.add_stream(\"h264\", rate=fps)\n+ stream.width = width\n+ stream.height = height\n+ stream.pix_fmt = \"yuv420p\"\n+ for i in range(num_frames):\n+ img = np.zeros((height, width, 3), dtype=np.uint8)\n+ img[:, :, 1] = i % 256\n+ frame = av.VideoFrame.from_ndarray(img, format=\"rgb24\")\n+ for packet in stream.encode(frame):\n+ container.mux(packet)\n+ for packet in stream.encode():\n+ container.mux(packet)\n+ return buf.getvalue()\n+\n+\n def create_edit_list_trimmed_video(\n num_frames: int = 90,\n trim_start_frame: int = 60,\n@@ -117,8 +174,6 @@ def create_edit_list_trimmed_video(\n trailing frames are presentable — the shape produced by lossless trims\n (e.g. ``ffmpeg -ss ... -c copy``). Returns (video_bytes, visible_frames).\n \"\"\"\n- import io\n-\n import av\n \n src = create_long_gop_video(num_frames=num_frames, fps=fps)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][ROCm][Qwen4Exp] Remap Quark layer names for the MTP draft model\nLabels: bug, rocm, ready, qwen\nFiles changed (3): tests/models/qwen4_exp/test_config.py, vllm/models/qwen4_exp/amd/mtp.py, vllm/models/qwen4_exp/nvidia/mtp.py\n\n## Description (results removed)\n\n## Overview\n\nRemap Quark's layer names (`exclude`, `layer_quant_config`) for the Qwen4Exp MTP draft (both AMD and NVIDIA copies) so that checkpoint names (`mtp.layers.0.*`) match the draft's layer names (`mtp.layers.48.*`), the same way `ignored_layers`, `exclude_modules` and ModelOpt `quantized_layers` are already remapped (#55513) in both copies.\n\nRelated checkpoint fix:https://huggingface.co/amd/Qwen3.8-Flash-Next-Quark-MXFP4/commit/89d245391842bf53fb9b0700646843c1f40de341.\n\n**Checkpoint status:** AMD has updated `config.json` on both `amd/Qwen3.8-Flash-Next-Quark-MXFP4` and the `-PLEFP8` sibling with literal `mtp.layers.0.*` names only -- no catch-all regex -- matching the convention other AMD checkpoints use (e.g. `amd/Qwen3.5-397B`). Per AMD's confirmation on the checkpoint discussion linked above and the model card's own Reproduction section: without MTP, the formal `vllm/vllm-openai-rocm:v0.32.0` release runs the checkpoint as documented; with MTP enabled, that release does not remap Quark's exclude list for the draft, so this PR is required for MTP to load at all -- this is the checkpoint as shipped, not a hypothetical variant.\n\n## Claims\n\n- Bug fix: with a Quark checkpoint whose `exclude` list names MTP modules by checkpoint index (the form Quark exports), BF16 MTP layers are no longer built as quantized layers.\n- Per-layer Quark schemes (`layer_quant_config`) for MTP modules are applied to the draft as well.\n- No functional change for the target model, for no-MTP serving, or for ModelOpt checkpoints.\n- Scope: entries in Quark `exclude` and keys of `layer_quant_config` that **start with** `mtp.layers..` (for `i < mtp_num_hidden_layers`) are rewritten to `mtp.layers..`; this includes globs such as `mtp.layers.0.*`. Entries that start with `re:` or `*`, and non-MTP names, are left exactly as written, matching the existing `ignored_layers`/`exclude_modules`/`quantized_layers` remaps.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause.** The AMD Qwen4Exp draft builds its layers as `mtp.layers.`, while checkpoints name them `mtp.layers.`. `_make_draft_vllm_config` shifts the checkpoint names in `ignored_layers`, `exclude_modules` and `quantized_layers`, but `QuarkConfig` keeps its layer names inside `quant_config` (`exclude`, `layer_quant_config`), which was not touched. Every literal MTP entry there was dead for the draft, so `QuarkConfig.get_quant_method` fell through to the global scheme (MXFP4) for BF16 MTP modules.\n\n**Fix.** Rename them through Quark's existing hook for this, `QuarkConfig.apply_vllm_mapper`, with a `WeightsMapper` prefix map `mtp.layers..` -> `mtp.layers..`. The mapper is built in the draft rather than declared as a class-level `hf_to_vllm_mapper` because the target index depends on `num_hidden_layers`.\n\n**Why keep the layer offset.** Qwen3-Next removed the same offset in #25079 and Qwen3.5 builds its MTP layer as `mtp.layers.{idx}` (#34110), so their checkpoint names match without a remap. Qwen4Exp's offset (introduced with the model in #53896) is now relied on: #60023 documents `--kv-cache-dtype-skip-layers 48` to keep only the MTP layer's KV cache unquantized, and that option selects layers by index; the offset also keeps index-keyed PLE layer assignment (`ple_layer_ids`) off the draft. Renumbering would change both silently, so this PR keeps the offset and completes the existing remap.\n\n**Scope.** AMD and NVIDIA Qwen4Exp MTP drafts; Quark only.\n\n**Related.** Not duplicated by: #49900 (strips the synthetic `draft_model.` root for draft-model drafters), #59040 (`mtp.fc` in `qwen3_5_mtp.py`).\n\n**CI.** The unit test runs on CPU in the existing Qwen4Exp test file. The end-to-end validation above was run outside CI.\n\nAI assistance (Claude Code) was used for this change.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/models/qwen4_exp/amd/mtp.py b/vllm/models/qwen4_exp/amd/mtp.py\nindex 7a73ac8f33ed..a096aaccb9a5 100644\n--- a/vllm/models/qwen4_exp/amd/mtp.py\n+++ b/vllm/models/qwen4_exp/amd/mtp.py\n@@ -119,6 +119,7 @@ def _remap_mtp_weight_name(name: str) -> str | None:\n def _make_draft_vllm_config(\n vllm_config: VllmConfig,\n mtp_start_layer_idx: int,\n+ num_mtp_layers: int,\n ) -> VllmConfig:\n \"\"\"Ensure that the draft model config is set in the vLLM config.\"\"\"\n speculative_config = vllm_config.speculative_config\n@@ -151,6 +152,15 @@ def _make_draft_vllm_config(\n \"quantized_layers\",\n _remap_quantized_layers(quantized_layers, mtp_start_layer_idx),\n )\n+ if draft_quant_config.get_name() == \"quark\":\n+ draft_quant_config.apply_vllm_mapper(\n+ WeightsMapper(\n+ orig_to_new_prefix={\n+ f\"mtp.layers.{i}.\": f\"mtp.layers.{mtp_start_layer_idx + i}.\"\n+ for i in range(num_mtp_layers)\n+ }\n+ )\n+ )\n \n draft_vllm_config = replace(\n vllm_config,\n@@ -195,6 +205,7 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = \"\") -> None:\n draft_vllm_config = _make_draft_vllm_config(\n vllm_config,\n self.mtp_start_layer_idx,\n+ self.num_mtp_layers,\n )\n with set_current_vllm_config(draft_vllm_config, prefix=prefix):\n # residual_linear_shared fusion: fc_embedding projects the token\ndiff --git a/vllm/models/qwen4_exp/nvidia/mtp.py b/vllm/models/qwen4_exp/nvidia/mtp.py\nindex 0aed17c69975..d005e67bad27 100644\n--- a/vllm/models/qwen4_exp/nvidia/mtp.py\n+++ b/vllm/models/qwen4_exp/nvidia/mtp.py\n@@ -125,6 +125,7 @@ def _remap_mtp_weight_name(name: str) -> str | None:\n def _make_draft_vllm_config(\n vllm_config: VllmConfig,\n mtp_start_layer_idx: int,\n+ num_mtp_layers: int,\n ) -> VllmConfig:\n \"\"\"Ensure that the draft model config is set in the vLLM config.\"\"\"\n speculative_config = vllm_config.speculative_config\n@@ -157,6 +158,15 @@ def _make_draft_vllm_config(\n \"quantized_layers\",\n _remap_quantized_layers(quantized_layers, mtp_start_layer_idx),\n )\n+ if draft_quant_config.get_name() == \"quark\":\n+ draft_quant_config.apply_vllm_mapper(\n+ WeightsMapper(\n+ orig_to_new_prefix={\n+ f\"mtp.layers.{i}.\": f\"mtp.layers.{mtp_start_layer_idx + i}.\"\n+ for i in range(num_mtp_layers)\n+ }\n+ )\n+ )\n \n draft_vllm_config = replace(\n vllm_config,\n@@ -195,6 +205,7 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = \"\") -> None:\n draft_vllm_config = _make_draft_vllm_config(\n vllm_config,\n self.mtp_start_layer_idx,\n+ self.num_mtp_layers,\n )\n # The proposer replaces this with the target model's buffer.\n topk_indices_buffer = None\n\ndiff --git a/tests/models/qwen4_exp/test_config.py b/tests/models/qwen4_exp/test_config.py\nindex bb01acdd8431..261fc497a6da 100644\n--- a/tests/models/qwen4_exp/test_config.py\n+++ b/tests/models/qwen4_exp/test_config.py\n@@ -163,6 +163,56 @@ def test_qwen4_exp_mtp_remaps_mixed_precision_layer_indices(backend: str) -> Non\n }\n \n \n+@spawn_new_process_for_each_test\n+@pytest.mark.parametrize(\"backend\", [\"amd\", \"nvidia\"])\n+def test_qwen4_exp_mtp_remaps_quark_layer_names(backend: str) -> None:\n+ from vllm.model_executor.layers.fused_moe import (\n+ RoutedExperts,\n+ UnquantizedFusedMoEMethod,\n+ )\n+ from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig\n+\n+ mtp_module = import_module(f\"vllm.models.qwen4_exp.{backend}.mtp\")\n+\n+ # `re:mtp\\.fc_hidden`, not a catch-all `re:mtp\\..*`: a broad regex would\n+ # already exclude layer 48's experts on its own (`re:` entries are never\n+ # remapped), masking the bug this test is meant to catch.\n+ exclude = [\"lm_head\", \"mtp.layers.0.mlp.experts.0.gate_proj\", r\"re:mtp\\.fc_hidden\"]\n+ checkpoint_config = {\n+ \"exclude\": exclude,\n+ \"layer_quant_config\": {\"mtp.layers.0.self_attn.q_proj\": {}},\n+ }\n+ vllm_config = SimpleNamespace(\n+ speculative_config=SimpleNamespace(draft_model_config=object())\n+ )\n+ with (\n+ patch.object(\n+ mtp_module,\n+ \"get_draft_quant_config\",\n+ return_value=QuarkConfig(checkpoint_config),\n+ ),\n+ patch.object(mtp_module, \"replace\", return_value=SimpleNamespace()),\n+ ):\n+ draft_config = mtp_module._make_draft_vllm_config(vllm_config, 48, 1)\n+\n+ remapped = draft_config.quant_config.quant_config\n+ assert remapped[\"exclude\"] == [\n+ \"lm_head\",\n+ \"mtp.layers.48.mlp.experts.0.gate_proj\",\n+ r\"re:mtp\\.fc_hidden\",\n+ ]\n+ assert remapped[\"layer_quant_config\"] == {\"mtp.layers.48.self_attn.q_proj\": {}}\n+ assert exclude[1] == \"mtp.layers.0.mlp.experts.0.gate_proj\"\n+\n+ # Without the remap, layer 48's experts fall through to the global MXFP4\n+ # scheme instead of being treated as unquantized bf16 -- assert the\n+ # decision `get_quant_method` actually makes, not just the exclude list.\n+ _, _, method_cls = draft_config.quant_config.get_quant_method_target(\n+ \"mtp.layers.48.mlp.experts\", RoutedExperts\n+ )\n+ assert method_cls is UnquantizedFusedMoEMethod\n+\n+\n @pytest.mark.parametrize(\"wrapped_config\", [False, True])\n def test_qwen4_exp_mtp_override_sets_draft_config(\n wrapped_config: bool,\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][EPLB] Move 1-byte expert tensors as uint8 views\nLabels: bug, ready, verified\nFiles changed (2): tests/distributed/test_eplb_execute.py, vllm/model_executor/models/interfaces.py\n\n## Description (results removed)\n\n## Purpose\n\nFixes #51567.\n\nWith `communicator=torch_nccl`:\n\n```text\nFile \"vllm/v1/worker/gpu_worker.py\", line 572, in determine_available_memory\nFile \"vllm/v1/worker/gpu/eplb_utils.py\", line 126, in step\nFile \"vllm/distributed/eplb/eplb_state.py\", line 580, in step\n...\nFile \"torch/distributed/distributed_c10d.py\", line 4280, in all_gather\n work = group.allgather([tensor_list], [tensor], opts)\nTypeError: Input tensor data type is not supported for NCCL process group: Float8_e8m0fnu\n```\n\nWith `communicator=pynccl`:\n\n```text\nFile \"vllm/distributed/eplb/eplb_communicator.py\", line 756, in create_eplb_communicator\n return _create_pynccl()\nFile \"vllm/distributed/eplb/eplb_communicator.py\", line 693, in _create_pynccl\n raise RuntimeError(\nRuntimeError: EPLB communicator 'pynccl' requested but expert weights contain unsupported dtypes: (torch.float8_e8m0fnu).\n```\n\n## When this triggers\n\n1. EPLB is enabled (`--enable-eplb`, with EP).\n2. The experts use MX quantization (MXFP4/MXFP8 with E8M0 block scales).\n3. After post-processing, the backend stores an expert tensor in a 1-byte dtype that NCCL/RCCL does not support. For example:\n - Marlin MXFP4 MoE: `mxfp4_marlin_process_scales()` returns scales as `float8_e8m0fnu`.\n - ROCm AITER MXFP4: expert weights are viewed as `float4_e2m1fn_x2` (`oracle/mxfp4.py`).\n - Humming MXFP4 (my repro): scales are stored as `float8_e8m0fnu`.\n\n Backends that keep these tensors as `uint8` are not affected.\n4. The tensor is returned by `get_expert_weights()`, so it is registered for EPLB transport.\n\nConverting at load time is not enough. DeepSeek-V4/V4.1 loaders already view checkpoint E8M0 scales as `uint8`, but the backend's kernel-format conversion writes `float8_e8m0fnu` back into the parameter. The fix therefore belongs where the tensors are registered for EPLB, not in individual loaders or backends.\n\n## Root cause\n\n- `torch_nccl` raises `TypeError` inside `all_gather`.\n- `pynccl` rejects the dtype earlier, when the communicator is created.\n\n## Fix\n\nEPLB only copies expert bytes between ranks. It never reduces them, so the numeric dtype does not matter to the transport. In `MixtureOfExperts.set_eplb_state()`, every 1-byte expert tensor is now registered as `w.view(torch.uint8)`:\n\n- The view keeps the shape, stride, and storage, so a rearrange writes directly into the parameter that the kernels read in the original dtype.\n- Applying the view at this registration point covers `FusedMoE` layers, models with their own `get_expert_weights()` (for example DeepSeek-V4 MegaMoE), and elastic EP re-registration.\n- 1-byte dtypes that NCCL already supports (`int8`, `uint8`, `float8_e4m3fn`) move the same bytes as before.\n\n## Test Plan\n[results removed]\n## Test Result\n[results removed]\n## AI assistance\n\nThis PR was prepared with AI assistance (Claude). I reviewed every changed line and ran the tests above.\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/interfaces.py b/vllm/model_executor/models/interfaces.py\nindex 818c1610500e..bd0a6881c7a9 100644\n--- a/vllm/model_executor/models/interfaces.py\n+++ b/vllm/model_executor/models/interfaces.py\n@@ -1109,8 +1109,14 @@ def set_eplb_state(\n \"\"\"\n self.expert_weights = []\n for layer_idx, layer in enumerate(self.moe_layers):\n- # Register the expert weights.\n- self.expert_weights.append(list(layer.get_expert_weights()))\n+ # Register the expert weights. EPLB only moves bytes, so 1-byte\n+ # dtypes NCCL lacks (e.g. E8M0, FP4x2) go as uint8 views.\n+ self.expert_weights.append(\n+ [\n+ w.view(torch.uint8) if w.element_size() == 1 else w\n+ for w in layer.get_expert_weights()\n+ ]\n+ )\n layer.set_eplb_state(\n moe_layer_idx=layer_idx,\n expert_load_view=expert_load_view,\n\ndiff --git a/tests/distributed/test_eplb_execute.py b/tests/distributed/test_eplb_execute.py\nindex acdb9f39fcac..6d0f89248d47 100644\n--- a/tests/distributed/test_eplb_execute.py\n+++ b/tests/distributed/test_eplb_execute.py\n@@ -2,6 +2,7 @@\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n import random\n+from types import SimpleNamespace\n \n import pytest\n import torch\n@@ -23,11 +24,33 @@\n ensure_model_parallel_initialized,\n get_tp_group,\n )\n+from vllm.model_executor.models.interfaces import MixtureOfExperts\n from vllm.platforms import current_platform\n \n from .eplb_utils import distributed_run, set_env_vars_and_device\n \n \n+@pytest.mark.parametrize(\"dtype\", [torch.float8_e8m0fnu, torch.float4_e2m1fn_x2])\n+def test_set_eplb_state_registers_byte_dtypes_as_uint8_views(dtype):\n+ \"\"\"NCCL lacks these dtypes, so EPLB must see their bytes as uint8 views\n+ sharing storage with the parameter the kernel reads.\"\"\"\n+ weight = torch.zeros(2, 8, dtype=torch.int32)\n+ scale = torch.zeros(2, 4, dtype=torch.uint8).view(dtype)\n+ layer = SimpleNamespace(\n+ get_expert_weights=lambda: [weight, scale],\n+ set_eplb_state=lambda **_: None,\n+ )\n+ model = SimpleNamespace(moe_layers=[layer])\n+ empty = torch.empty(0)\n+ MixtureOfExperts.set_eplb_state(model, empty, empty, empty)\n+\n+ registered_weight, registered_scale = model.expert_weights[0]\n+ assert registered_weight is weight\n+ assert registered_scale.dtype == torch.uint8\n+ registered_scale.fill_(127)\n+ assert torch.equal(scale.view(torch.uint8), registered_scale)\n+\n+\n @pytest.mark.skipif(not torch.cuda.is_available(), reason=\"requires CUDA\")\n def test_gloo_receive_staging_does_not_force_gpu_sync(monkeypatch):\n \"\"\"Gloo receives must reach the GPU without an implicit pageable copy.\"\"\"\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [ROCm][Bugfix] Stop declaring the MXFP4 MoE intermediate padding to AITER\nLabels: bug, rocm, quantization, verified\nFiles changed (3): tests/kernels/moe/test_ocp_mx_moe.py, tests/kernels/moe/test_rocm_aiter_moe.py, vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py\n\n## Description (results removed)\n\n## Purpose\n\nThe AMD CI job `dsv41-mono-decode-numerics-amd` goes red intermittently with\n\n```\nAssertionError: (0, 1, (973, 973), 'residual', nan)\n```\n\n(e.g. https://buildkite.com/vllm/ci/builds/94971). The NaN comes from AITER, on\nvLLM's ordinary MoE path, not from the mono kernels the test compares against.\n\nAITER's a8w4 MoE (FP8 activations x MXFP4 weights) allocates several scratch\nbuffers with `torch.empty`, sized for the padded sorted length, and reads them\nwhere the producing kernel never wrote. In FP8/E8M0 a garbage `0xFF` byte is\nNaN, so a whole token row of the output comes back NaN. It only happens with a\nnon-zero `intermediate_pad`, at decode-sized batches, after larger calls have\nRoot cause, a standalone repro and a fix are filed upstream:\n\n- https://github.com/ROCm/aiter/issues/6565\n- https://github.com/ROCm/aiter/pull/6568\n\n## This change\n\nStop declaring `intermediate_pad` to AITER on the MXFP4 path. It is redundant\nthere, and dropping it keeps the call off the buggy AITER path.\n\nWhy it is redundant — the padded region is zero at the point AITER sees it, and\nstays zero through every step between allocation and the kernel call:\n\n| step | padded region | where |\n|---|---|---|\n| allocation | `torch.zeros` for `w13`/`w2`, their scales and `w13_bias`/`w2_bias`, at the **padded** intermediate size | `Mxfp4MoEMethod.create_weights` |\n| checkpoint load | the destination is narrowed to the loaded shard before the copy, so the padded rows are never written — this is deliberate, the helper is named for it and its docstring calls out \"padding ... on the shard (intermediate) dimension (e.g. for MXFP4 GEMM)\" | `RoutedExperts._narrow_expert_data_for_padding`, used by `_load_w13` / `_load_w2` right before `expert_data.copy_()` |\n| weight shuffle | pure `view` + `permute` (asserts `N % 16 == 0`, `K % 32 == 0`, no re-padding), so zeros stay zeros | `aiter.ops.shuffle.shuffle_weight` |\n| scale shuffle | re-pads the scale to 256 rows / 8 cols, but fills the pad with `0x7F` (E8M0 = 1.0) before copying, so it is never garbage | `aiter.utility.fp4_utils.e8m0_shuffle` |\n\nSo for the padded columns the kernel computes\n\n- stage 1: `x @ 0 = 0` (gate and up are both zero there, and the bias is zero,\n so the activation output is exactly `silu(0) * 0 = 0`)\n- stage 2: `0 @ 0 = 0`\n\nExact zeros also mean the padded columns cannot disturb the stage-2 activation\nquantization: `amax` over an MX group is unaffected by zeros, whether or not a\ngroup straddles real and padded columns.\n\nTwo things are deliberately left alone:\n\n- **`hidden_pad`** — the activation columns it covers are not guaranteed to be\n zero, so dropping it would not be equivalent.\n- **SITU** (`activation == MoEActivation.SITU`, the a16w4 FlyDSL port used by\n Kimi K3) — that kernel consumes the pad. The surrounding code already skips\n through unrounded\"), and on that path AITER keys its own scratch\n initialization on the value: `_alloc = torch.zeros if inter_dim_pad > 0 else\n torch.empty` in `aiter/ops/flydsl/moe_kernels.py`. Zeroing the declaration\n there would *remove* an initialization that is currently happening, which is\n the opposite of what this PR is for.\n\nThis is a workaround and should be reverted once the AITER fix is merged and\npinned. The surrounding code already carries a similar TODO about AITER padding\nbehaviour.\n\n## Test Result\n[results removed]\n## Scope and limits\n\n- Validated on DeepSeek-V4.1-Flash at TP4 (`model_dim=5120`, per-rank\n intermediate 576 padded to 640, E=384, topk=6). Other MXFP4 models on this\n path (e.g. gpt-oss with INTERLEAVE) are covered by the same zero-fill\n argument but were not run here, so reviewers may prefer a narrower gate.\n- The zero-fill chain above is established from the code, with the citations in\n the table. It is not confirmed by a run against a real MXFP4 checkpoint that\n actually has padding: the test that exercises this path uses a random-weight\n loader which also zero-fills the padding, and every MXFP4 checkpoint we have\n locally has `moe_intermediate_size = 2048`, which is already aligned per rank\n (pad = 0). DeepSeek-V4.1-Flash (2304) is the one that pads, and the local copy\n of it is FP8 rather than MXFP4.\n- Models whose per-rank intermediate size is already 128-aligned get\n `intermediate_pad == 0` and are unaffected either way.\n- The `VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4` opt-in is a sub-case of\n `use_mxfp4_w4a16`, so it is covered by this change as well. The same\n zero-fill argument applies to it, but it runs different kernels and was not\n exercised here.\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py b/vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py\nindex 724afa3d57cd..37a73d15e382 100644\n--- a/vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py\n+++ b/vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py\n@@ -241,6 +241,7 @@ def aiter_moe_pads(\n intermediate_pad: int,\n activation: MoEActivation,\n use_mxfp4_w4a4: bool,\n+ use_mxfp4_w4a16: bool,\n tp_size: int,\n ) -> tuple[int, int]:\n \"\"\"Round the padding deltas to what AITER's MoE dispatch expects.\n@@ -248,8 +249,9 @@ def aiter_moe_pads(\n SITU's A16W4 FlyDSL kernel pads per gate/up half, so its pads pass through\n unrounded. Otherwise the pads are rounded to AITER's CK/FlyDSL tile\n granularity, and at tp_size == 1 the intermediate pad is doubled for the\n- fused gate/up weight. The W4A4 SiLU path doubles it inside AITER, so it is\n- passed undoubled; doubling it here as well masks live intermediate rows.\n+ fused gate/up weight. The W4A4 SiLU and W4A16 paths double it inside AITER,\n+ so it is passed undoubled; doubling it here as well masks live\n+ intermediate rows.\n \n Where AITER doubles it (v0.1.24.post1):\n - CK-Tile stage 1, aiter/fused_moe.py:\n@@ -264,7 +266,11 @@ def aiter_moe_pads(\n \"\"\"\n if activation == MoEActivation.SITU:\n return hidden_pad, intermediate_pad\n- double = tp_size == 1 and not (use_mxfp4_w4a4 and activation == MoEActivation.SILU)\n+ double = (\n+ tp_size == 1\n+ and not use_mxfp4_w4a16\n+ and not (use_mxfp4_w4a4 and activation == MoEActivation.SILU)\n+ )\n return (\n hidden_pad // 128 * 128,\n intermediate_pad // 64 * 64 * (2 if double else 1),\n@@ -421,9 +427,20 @@ def rocm_aiter_fused_experts(\n intermediate_pad,\n activation,\n quant_config.use_mxfp4_w4a4,\n+ quant_config.use_mxfp4_w4a16,\n moe_config.tp_size,\n )\n \n+ # AITER's bias-less W4A16 FlyDSL stage 1 leaves the padded intermediate\n+ # columns unwritten (ROCm/aiter#6598); the padded weights are zero, so\n+ # declare no pad there. SITU zeroes its own scratch on a non-zero pad.\n+ if (\n+ quant_config.use_mxfp4_w4a16\n+ and bias1 is None\n+ and activation != MoEActivation.SITU\n+ ):\n+ intermediate_pad = 0\n+\n # AITER's stage1 GEMM needs gate_mode to match how weights were shuffled\n # at load time (oracle/mxfp4.py).\n from aiter.ops.flydsl.moe_common import GateMode\n\ndiff --git a/tests/kernels/moe/test_ocp_mx_moe.py b/tests/kernels/moe/test_ocp_mx_moe.py\nindex a799fc6c39d2..851da4e26ca3 100644\n--- a/tests/kernels/moe/test_ocp_mx_moe.py\n+++ b/tests/kernels/moe/test_ocp_mx_moe.py\n@@ -2083,21 +2083,28 @@ class MockLayer:\n \n \n @pytest.mark.parametrize(\"intermediate_size_unpadded\", [640, 704])\n+@pytest.mark.parametrize(\n+ (\"backend_name\", \"activation_name\"),\n+ [(\"AITER_MXFP4_MXFP4\", \"SILU\"), (\"AITER_MXFP4_BF16\", \"SWIGLUOAI\")],\n+)\n @pytest.mark.skipif(not ROCM_GFX950, reason=\"Requires GFX950\")\n @pytest.mark.skipif(not ROCM_AITER_AVAILABLE, reason=\"Requires AITER\")\n @torch.inference_mode()\n-def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n+def test_aiter_mxfp4_moe_pad_masks_only_padding(\n intermediate_size_unpadded: int,\n+ backend_name: str,\n+ activation_name: str,\n monkeypatch: pytest.MonkeyPatch,\n ):\n- \"\"\"At MoE tp_size == 1 the W4A4 MoE masks the padding and nothing else.\n+ \"\"\"At MoE tp_size == 1 the MXFP4 MoE masks the padding and nothing else.\n \n The experts are stored 768 wide with zeros past the real width, so the\n layer computes the same function whether the kernel is told that the tail\n is padding or not. A pad that is doubled twice (once by vLLM, once inside\n AITER for the fused gate/up weight) masks live intermediate rows as well.\n- 640 stored at 768 is Qwen3.8 Flash Next's shape at TP1 and under expert\n- parallelism before the W4A4 intermediate was aligned to 128.\n+ 640 stored at 768 is Qwen3.8 Flash Next's W4A4 shape at TP1 and under\n+ expert parallelism before the W4A4 intermediate was aligned to 128. The\n+ W4A16 case uses gpt-oss's interleaved, biased layout.\n \"\"\"\n import vllm.distributed.parallel_state as ps\n from vllm.config import VllmConfig, set_current_vllm_config\n@@ -2120,7 +2127,9 @@ def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n monkeypatch.setattr(ps, \"_TP\", types.SimpleNamespace(world_size=1))\n monkeypatch.setattr(rocm_aiter_ops, \"_AITER_ENABLED\", True)\n \n- backend = Mxfp4MoeBackend.AITER_MXFP4_MXFP4\n+ backend = Mxfp4MoeBackend[backend_name]\n+ activation = MoEActivation[activation_name]\n+ gpt_oss = backend == Mxfp4MoeBackend.AITER_MXFP4_BF16\n experts_cls = backend_to_kernel_cls(backend)[0]\n num_experts, topk, num_tokens = 8, 2, 64\n hidden_size, intermediate_size = 512, 768\n@@ -2130,12 +2139,24 @@ def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n w13 = torch.randn(\n num_experts, 2 * intermediate_size, hidden_size, dtype=dtype, device=device\n )\n- w13[:, intermediate_size_unpadded:intermediate_size] = 0\n- w13[:, intermediate_size + intermediate_size_unpadded :] = 0\n w2 = torch.randn(\n num_experts, hidden_size, intermediate_size, dtype=dtype, device=device\n )\n w2[..., intermediate_size_unpadded:] = 0\n+ w13_bias = w2_bias = None\n+ if gpt_oss:\n+ # Checkpoint layout: gate/up rows interleaved, padding at the end.\n+ w13[:, 2 * intermediate_size_unpadded :] = 0\n+ w13_bias = torch.randn(\n+ num_experts, 2 * intermediate_size, dtype=torch.float32, device=device\n+ )\n+ w13_bias[:, 2 * intermediate_size_unpadded :] = 0\n+ w2_bias = torch.randn(\n+ num_experts, hidden_size, dtype=torch.float32, device=device\n+ )\n+ else:\n+ w13[:, intermediate_size_unpadded:intermediate_size] = 0\n+ w13[:, intermediate_size + intermediate_size_unpadded :] = 0\n w13_q, w13_scale = dynamic_mxfp4_quant(w13.reshape(-1, hidden_size))\n w2_q, w2_scale = dynamic_mxfp4_quant(w2.reshape(-1, intermediate_size))\n w13_q = w13_q.reshape(num_experts, 2 * intermediate_size, -1)\n@@ -2144,7 +2165,7 @@ def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n w2_scale = w2_scale.reshape(num_experts, hidden_size, -1)\n \n layer = types.SimpleNamespace(w13_input_scale=None, w2_input_scale=None)\n- w13_q, w2_q, w13_scale, w2_scale, _, _ = (\n+ w13_q, w2_q, w13_scale, w2_scale, w13_bias, w2_bias = (\n convert_gpt_oss_weight_to_mxfp4_moe_kernel_format(\n mxfp4_backend=backend,\n layer=layer,\n@@ -2152,8 +2173,8 @@ def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n w2_weight=w2_q,\n w13_weight_scale=w13_scale,\n w2_weight_scale=w2_scale,\n- w13_bias=None,\n- w2_bias=None,\n+ w13_bias=w13_bias,\n+ w2_bias=w2_bias,\n )\n )\n weights = (w13_q, w2_q, w13_scale, w2_scale)\n@@ -2176,14 +2197,18 @@ def run(unpadded: int) -> torch.Tensor:\n num_local_experts=num_experts,\n num_logical_experts=num_experts,\n moe_parallel_config=FusedMoEParallelConfig.make_no_parallel(),\n- activation=MoEActivation.SILU,\n+ activation=activation,\n in_dtype=dtype,\n device=device,\n routing_method=RoutingMethodType.Renormalize,\n intermediate_size_per_partition_unpadded=unpadded,\n )\n quant_config = make_mxfp4_moe_quant_config(\n- mxfp4_backend=backend, w1_scale=w13_scale, w2_scale=w2_scale\n+ mxfp4_backend=backend,\n+ w1_scale=w13_scale,\n+ w2_scale=w2_scale,\n+ w1_bias=w13_bias,\n+ w2_bias=w2_bias,\n )\n with set_current_vllm_config(VllmConfig()):\n kernel = make_mxfp4_moe_kernel(\n@@ -2199,7 +2224,7 @@ def run(unpadded: int) -> torch.Tensor:\n w2=w2_q,\n topk_weights=topk_weights,\n topk_ids=topk_ids,\n- activation=MoEActivation.SILU,\n+ activation=activation,\n global_num_experts=num_experts,\n expert_map=None,\n apply_router_weight_on_input=False,\ndiff --git a/tests/kernels/moe/test_rocm_aiter_moe.py b/tests/kernels/moe/test_rocm_aiter_moe.py\nindex d40758a3e6a6..53d33ada1d05 100644\n--- a/tests/kernels/moe/test_rocm_aiter_moe.py\n+++ b/tests/kernels/moe/test_rocm_aiter_moe.py\n@@ -637,22 +637,28 @@ def test_aiter_moe_padding_env_var(\n \n \n @pytest.mark.parametrize(\n- (\"activation\", \"use_mxfp4_w4a4\", \"tp_size\", \"pads\", \"expected\"),\n+ (\"activation\", \"use_mxfp4_w4a4\", \"use_mxfp4_w4a16\", \"tp_size\", \"pads\", \"expected\"),\n [\n # W4A4 SiLU: AITER doubles the pad itself, at TP1 (and EP) as at TP2.\n- (\"SILU\", True, 1, (0, 64), (0, 64)),\n- (\"SILU\", True, 1, (0, 128), (0, 128)),\n- (\"SILU\", True, 2, (0, 64), (0, 64)),\n- # gpt-oss W4A16 at TP1 keeps the doubled pad.\n- (\"SWIGLUOAI\", False, 1, (0, 192), (0, 384)),\n+ (\"SILU\", True, False, 1, (0, 64), (0, 64)),\n+ (\"SILU\", True, False, 1, (0, 128), (0, 128)),\n+ (\"SILU\", True, False, 2, (0, 64), (0, 64)),\n+ # gpt-oss W4A16: AITER doubles the pad itself, at TP1 as at TP2.\n+ (\"SWIGLUOAI\", False, True, 1, (0, 192), (0, 192)),\n+ (\"SWIGLUOAI\", False, True, 2, (0, 96), (0, 64)),\n # BF16 SiLU at TP1 keeps the doubled pad.\n- (\"SILU\", False, 1, (0, 192), (0, 384)),\n+ (\"SILU\", False, False, 1, (0, 192), (0, 384)),\n # SITU passes through unrounded.\n- (\"SITU\", False, 1, (40, 96), (40, 96)),\n+ (\"SITU\", False, True, 1, (40, 96), (40, 96)),\n ],\n )\n def test_aiter_moe_pads(\n- activation, use_mxfp4_w4a4, tp_size, pads: tuple[int, int], expected\n+ activation,\n+ use_mxfp4_w4a4,\n+ use_mxfp4_w4a16,\n+ tp_size,\n+ pads: tuple[int, int],\n+ expected,\n ):\n from vllm.model_executor.layers.fused_moe.activation import MoEActivation\n from vllm.model_executor.layers.fused_moe.experts.rocm_aiter_moe import (\n@@ -660,7 +666,9 @@ def test_aiter_moe_pads(\n )\n \n assert (\n- aiter_moe_pads(*pads, MoEActivation[activation], use_mxfp4_w4a4, tp_size)\n+ aiter_moe_pads(\n+ *pads, MoEActivation[activation], use_mxfp4_w4a4, use_mxfp4_w4a16, tp_size\n+ )\n == expected\n )\n \n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [ROCm][Bugfix] Stop declaring the MXFP4 MoE intermediate padding to AITER\nLabels: bug, rocm, quantization, verified\nFiles changed (3): tests/kernels/moe/test_ocp_mx_moe.py, tests/kernels/moe/test_rocm_aiter_moe.py, vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py\n\n## Description (results removed)\n\n## Purpose\n\nThe AMD CI job `dsv41-mono-decode-numerics-amd` goes red intermittently with\n\n```\nAssertionError: (0, 1, (973, 973), 'residual', nan)\n```\n\n(e.g. https://buildkite.com/vllm/ci/builds/94971). The NaN comes from AITER, on\nvLLM's ordinary MoE path, not from the mono kernels the test compares against.\n\nAITER's a8w4 MoE (FP8 activations x MXFP4 weights) allocates several scratch\nbuffers with `torch.empty`, sized for the padded sorted length, and reads them\nwhere the producing kernel never wrote. In FP8/E8M0 a garbage `0xFF` byte is\nNaN, so a whole token row of the output comes back NaN. It only happens with a\nnon-zero `intermediate_pad`, at decode-sized batches, after larger calls have\nRoot cause, a standalone repro and a fix are filed upstream:\n\n- https://github.com/ROCm/aiter/issues/6565\n- https://github.com/ROCm/aiter/pull/6568\n\n## This change\n\nStop declaring `intermediate_pad` to AITER on the MXFP4 path. It is redundant\nthere, and dropping it keeps the call off the buggy AITER path.\n\nWhy it is redundant — the padded region is zero at the point AITER sees it, and\nstays zero through every step between allocation and the kernel call:\n\n| step | padded region | where |\n|---|---|---|\n| allocation | `torch.zeros` for `w13`/`w2`, their scales and `w13_bias`/`w2_bias`, at the **padded** intermediate size | `Mxfp4MoEMethod.create_weights` |\n| checkpoint load | the destination is narrowed to the loaded shard before the copy, so the padded rows are never written — this is deliberate, the helper is named for it and its docstring calls out \"padding ... on the shard (intermediate) dimension (e.g. for MXFP4 GEMM)\" | `RoutedExperts._narrow_expert_data_for_padding`, used by `_load_w13` / `_load_w2` right before `expert_data.copy_()` |\n| weight shuffle | pure `view` + `permute` (asserts `N % 16 == 0`, `K % 32 == 0`, no re-padding), so zeros stay zeros | `aiter.ops.shuffle.shuffle_weight` |\n| scale shuffle | re-pads the scale to 256 rows / 8 cols, but fills the pad with `0x7F` (E8M0 = 1.0) before copying, so it is never garbage | `aiter.utility.fp4_utils.e8m0_shuffle` |\n\nSo for the padded columns the kernel computes\n\n- stage 1: `x @ 0 = 0` (gate and up are both zero there, and the bias is zero,\n so the activation output is exactly `silu(0) * 0 = 0`)\n- stage 2: `0 @ 0 = 0`\n\nExact zeros also mean the padded columns cannot disturb the stage-2 activation\nquantization: `amax` over an MX group is unaffected by zeros, whether or not a\ngroup straddles real and padded columns.\n\nTwo things are deliberately left alone:\n\n- **`hidden_pad`** — the activation columns it covers are not guaranteed to be\n zero, so dropping it would not be equivalent.\n- **SITU** (`activation == MoEActivation.SITU`, the a16w4 FlyDSL port used by\n Kimi K3) — that kernel consumes the pad. The surrounding code already skips\n through unrounded\"), and on that path AITER keys its own scratch\n initialization on the value: `_alloc = torch.zeros if inter_dim_pad > 0 else\n torch.empty` in `aiter/ops/flydsl/moe_kernels.py`. Zeroing the declaration\n there would *remove* an initialization that is currently happening, which is\n the opposite of what this PR is for.\n\nThis is a workaround and should be reverted once the AITER fix is merged and\npinned. The surrounding code already carries a similar TODO about AITER padding\nbehaviour.\n\n## Test Result\n[results removed]\n## Scope and limits\n\n- Validated on DeepSeek-V4.1-Flash at TP4 (`model_dim=5120`, per-rank\n intermediate 576 padded to 640, E=384, topk=6). Other MXFP4 models on this\n path (e.g. gpt-oss with INTERLEAVE) are covered by the same zero-fill\n argument but were not run here, so reviewers may prefer a narrower gate.\n- The zero-fill chain above is established from the code, with the citations in\n the table. It is not confirmed by a run against a real MXFP4 checkpoint that\n actually has padding: the test that exercises this path uses a random-weight\n loader which also zero-fills the padding, and every MXFP4 checkpoint we have\n locally has `moe_intermediate_size = 2048`, which is already aligned per rank\n (pad = 0). DeepSeek-V4.1-Flash (2304) is the one that pads, and the local copy\n of it is FP8 rather than MXFP4.\n- Models whose per-rank intermediate size is already 128-aligned get\n `intermediate_pad == 0` and are unaffected either way.\n- The `VLLM_ROCM_USE_AITER_MOE_A4W4_DSV4` opt-in is a sub-case of\n `use_mxfp4_w4a16`, so it is covered by this change as well. The same\n zero-fill argument applies to it, but it runs different kernels and was not\n exercised here.\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py b/vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py\nindex 501dd9ba43ce..3f805fe612a5 100644\n--- a/vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py\n+++ b/vllm/model_executor/layers/fused_moe/experts/rocm_aiter_moe.py\n@@ -241,6 +241,7 @@ def aiter_moe_pads(\n intermediate_pad: int,\n activation: MoEActivation,\n use_mxfp4_w4a4: bool,\n+ use_mxfp4_w4a16: bool,\n tp_size: int,\n ) -> tuple[int, int]:\n \"\"\"Round the padding deltas to what AITER's MoE dispatch expects.\n@@ -248,8 +249,9 @@ def aiter_moe_pads(\n SITU's A16W4 FlyDSL kernel pads per gate/up half, so its pads pass through\n unrounded. Otherwise the pads are rounded to AITER's CK/FlyDSL tile\n granularity, and at tp_size == 1 the intermediate pad is doubled for the\n- fused gate/up weight. The W4A4 SiLU path doubles it inside AITER, so it is\n- passed undoubled; doubling it here as well masks live intermediate rows.\n+ fused gate/up weight. The W4A4 SiLU and W4A16 paths double it inside AITER,\n+ so it is passed undoubled; doubling it here as well masks live\n+ intermediate rows.\n \n Where AITER doubles it (v0.1.24.post1):\n - CK-Tile stage 1, aiter/fused_moe.py:\n@@ -264,7 +266,11 @@ def aiter_moe_pads(\n \"\"\"\n if activation == MoEActivation.SITU:\n return hidden_pad, intermediate_pad\n- double = tp_size == 1 and not (use_mxfp4_w4a4 and activation == MoEActivation.SILU)\n+ double = (\n+ tp_size == 1\n+ and not use_mxfp4_w4a16\n+ and not (use_mxfp4_w4a4 and activation == MoEActivation.SILU)\n+ )\n return (\n hidden_pad // 128 * 128,\n intermediate_pad // 64 * 64 * (2 if double else 1),\n@@ -407,9 +413,25 @@ def rocm_aiter_fused_experts(\n intermediate_pad,\n activation,\n quant_config.use_mxfp4_w4a4,\n+ quant_config.use_mxfp4_w4a16,\n moe_config.tp_size,\n )\n \n+ # For W4A16 paths, declare no intermediate padding so AITER's CK-Tile\n+ # stage-1 kernel processes the full weight width without the per-column\n+ # skip overhead. Two reasons this is safe:\n+ #\n+ # - Bias-less (DSv4.1): FlyDSL stage-1 leaves padded columns unwritten\n+ # (ROCm/aiter#6598); zero weights give zero output there.\n+ # - Biased (gpt-oss): GptOssMxfp4MoEMethod.get_fused_moe_quant_config\n+ # already pre-pads w1_bias to match the padded weight width so the\n+ # CK-Tile kernel's stride-kargs.N bias access is correct. Padded\n+ # weight columns are zero, padded bias entries are zero → zero output.\n+ #\n+ # SITU zeroes its own scratch on a non-zero pad so it is excluded.\n+ if quant_config.use_mxfp4_w4a16 and activation != MoEActivation.SITU:\n+ intermediate_pad = 0\n+\n # AITER's stage1 GEMM needs gate_mode to match how weights were\n # shuffled at load time (oracle/mxfp4.py). gpt-oss uses INTERLEAVE;\n # DeepSeek V4.1 a4w4 uses SEPARATED (see below).\ndiff --git a/vllm/model_executor/layers/quantization/mxfp4.py b/vllm/model_executor/layers/quantization/mxfp4.py\nindex 6288a47bcde0..a9599b8e8bb5 100644\n--- a/vllm/model_executor/layers/quantization/mxfp4.py\n+++ b/vllm/model_executor/layers/quantization/mxfp4.py\n@@ -420,6 +420,27 @@ def get_fused_moe_quant_config(\n w1_scale = layer.w13_weight_scale\n w2_scale = layer.w2_weight_scale\n \n+ # The AITER CK-Tile stage-1 kernel indexes the bias tensor with stride\n+ # kargs.N (the full padded output width). When weights are padded to a\n+ # CK-Tile tile boundary the bias must be padded to match so the kernel\n+ # accesses the correct per-expert row. Pad once at load time with zeros;\n+ # the padded weight columns are also zero so those output positions end up\n+ # as zero without any in-kernel masking. The forward pass can then pass\n+ # intermediate_pad=0 for the biased path, eliminating the column-skip\n+ # overhead in the CK-Tile kernel (see rocm_aiter_moe.py).\n+ if (\n+ w1_bias is not None\n+ and self.moe.intermediate_size_per_partition_unpadded is not None\n+ ):\n+ inter_pad = (\n+ self.moe.intermediate_size_per_partition\n+ - self.moe.intermediate_size_per_partition_unpadded\n+ )\n+ if inter_pad > 0:\n+ w1_bias = torch.nn.functional.pad(\n+ w1_bias, (0, 2 * inter_pad), value=0.0\n+ )\n+\n return make_mxfp4_moe_quant_config(\n mxfp4_backend=self.mxfp4_backend,\n w1_scale=w1_scale,\n\ndiff --git a/tests/kernels/moe/test_ocp_mx_moe.py b/tests/kernels/moe/test_ocp_mx_moe.py\nindex 6727789195b3..45f305a840b5 100644\n--- a/tests/kernels/moe/test_ocp_mx_moe.py\n+++ b/tests/kernels/moe/test_ocp_mx_moe.py\n@@ -1897,21 +1897,28 @@ class MockLayer:\n \n \n @pytest.mark.parametrize(\"intermediate_size_unpadded\", [640, 704])\n+@pytest.mark.parametrize(\n+ (\"backend_name\", \"activation_name\"),\n+ [(\"AITER_MXFP4_MXFP4\", \"SILU\"), (\"AITER_MXFP4_BF16\", \"SWIGLUOAI\")],\n+)\n @pytest.mark.skipif(not ROCM_GFX950, reason=\"Requires GFX950\")\n @pytest.mark.skipif(not ROCM_AITER_AVAILABLE, reason=\"Requires AITER\")\n @torch.inference_mode()\n-def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n+def test_aiter_mxfp4_moe_pad_masks_only_padding(\n intermediate_size_unpadded: int,\n+ backend_name: str,\n+ activation_name: str,\n monkeypatch: pytest.MonkeyPatch,\n ):\n- \"\"\"At MoE tp_size == 1 the W4A4 MoE masks the padding and nothing else.\n+ \"\"\"At MoE tp_size == 1 the MXFP4 MoE masks the padding and nothing else.\n \n The experts are stored 768 wide with zeros past the real width, so the\n layer computes the same function whether the kernel is told that the tail\n is padding or not. A pad that is doubled twice (once by vLLM, once inside\n AITER for the fused gate/up weight) masks live intermediate rows as well.\n- 640 stored at 768 is Qwen3.8 Flash Next's shape at TP1 and under expert\n- parallelism before the W4A4 intermediate was aligned to 128.\n+ 640 stored at 768 is Qwen3.8 Flash Next's W4A4 shape at TP1 and under\n+ expert parallelism before the W4A4 intermediate was aligned to 128. The\n+ W4A16 case uses gpt-oss's interleaved, biased layout.\n \"\"\"\n import vllm.distributed.parallel_state as ps\n from vllm.config import VllmConfig, set_current_vllm_config\n@@ -1934,7 +1941,9 @@ def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n monkeypatch.setattr(ps, \"_TP\", types.SimpleNamespace(world_size=1))\n monkeypatch.setattr(rocm_aiter_ops, \"_AITER_ENABLED\", True)\n \n- backend = Mxfp4MoeBackend.AITER_MXFP4_MXFP4\n+ backend = Mxfp4MoeBackend[backend_name]\n+ activation = MoEActivation[activation_name]\n+ gpt_oss = backend == Mxfp4MoeBackend.AITER_MXFP4_BF16\n experts_cls = backend_to_kernel_cls(backend)[0]\n num_experts, topk, num_tokens = 8, 2, 64\n hidden_size, intermediate_size = 512, 768\n@@ -1944,12 +1953,24 @@ def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n w13 = torch.randn(\n num_experts, 2 * intermediate_size, hidden_size, dtype=dtype, device=device\n )\n- w13[:, intermediate_size_unpadded:intermediate_size] = 0\n- w13[:, intermediate_size + intermediate_size_unpadded :] = 0\n w2 = torch.randn(\n num_experts, hidden_size, intermediate_size, dtype=dtype, device=device\n )\n w2[..., intermediate_size_unpadded:] = 0\n+ w13_bias = w2_bias = None\n+ if gpt_oss:\n+ # Checkpoint layout: gate/up rows interleaved, padding at the end.\n+ w13[:, 2 * intermediate_size_unpadded :] = 0\n+ w13_bias = torch.randn(\n+ num_experts, 2 * intermediate_size, dtype=torch.float32, device=device\n+ )\n+ w13_bias[:, 2 * intermediate_size_unpadded :] = 0\n+ w2_bias = torch.randn(\n+ num_experts, hidden_size, dtype=torch.float32, device=device\n+ )\n+ else:\n+ w13[:, intermediate_size_unpadded:intermediate_size] = 0\n+ w13[:, intermediate_size + intermediate_size_unpadded :] = 0\n w13_q, w13_scale = dynamic_mxfp4_quant(w13.reshape(-1, hidden_size))\n w2_q, w2_scale = dynamic_mxfp4_quant(w2.reshape(-1, intermediate_size))\n w13_q = w13_q.reshape(num_experts, 2 * intermediate_size, -1)\n@@ -1958,7 +1979,7 @@ def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n w2_scale = w2_scale.reshape(num_experts, hidden_size, -1)\n \n layer = types.SimpleNamespace(w13_input_scale=None, w2_input_scale=None)\n- w13_q, w2_q, w13_scale, w2_scale, _, _ = (\n+ w13_q, w2_q, w13_scale, w2_scale, w13_bias, w2_bias = (\n convert_gpt_oss_weight_to_mxfp4_moe_kernel_format(\n mxfp4_backend=backend,\n layer=layer,\n@@ -1966,8 +1987,8 @@ def test_aiter_mxfp4_w4a4_moe_pad_masks_only_padding(\n w2_weight=w2_q,\n w13_weight_scale=w13_scale,\n w2_weight_scale=w2_scale,\n- w13_bias=None,\n- w2_bias=None,\n+ w13_bias=w13_bias,\n+ w2_bias=w2_bias,\n )\n )\n weights = (w13_q, w2_q, w13_scale, w2_scale)\n@@ -1990,14 +2011,18 @@ def run(unpadded: int) -> torch.Tensor:\n num_local_experts=num_experts,\n num_logical_experts=num_experts,\n moe_parallel_config=FusedMoEParallelConfig.make_no_parallel(),\n- activation=MoEActivation.SILU,\n+ activation=activation,\n in_dtype=dtype,\n device=device,\n routing_method=RoutingMethodType.Renormalize,\n intermediate_size_per_partition_unpadded=unpadded,\n )\n quant_config = make_mxfp4_moe_quant_config(\n- mxfp4_backend=backend, w1_scale=w13_scale, w2_scale=w2_scale\n+ mxfp4_backend=backend,\n+ w1_scale=w13_scale,\n+ w2_scale=w2_scale,\n+ w1_bias=w13_bias,\n+ w2_bias=w2_bias,\n )\n with set_current_vllm_config(VllmConfig()):\n kernel = make_mxfp4_moe_kernel(\n@@ -2013,7 +2038,7 @@ def run(unpadded: int) -> torch.Tensor:\n w2=w2_q,\n topk_weights=topk_weights,\n topk_ids=topk_ids,\n- activation=MoEActivation.SILU,\n+ activation=activation,\n global_num_experts=num_experts,\n expert_map=None,\n apply_router_weight_on_input=False,\ndiff --git a/tests/kernels/moe/test_rocm_aiter_moe.py b/tests/kernels/moe/test_rocm_aiter_moe.py\nindex 8240e6ca0239..f2212dd39267 100644\n--- a/tests/kernels/moe/test_rocm_aiter_moe.py\n+++ b/tests/kernels/moe/test_rocm_aiter_moe.py\n@@ -637,22 +637,28 @@ def test_aiter_moe_padding_env_var(\n \n \n @pytest.mark.parametrize(\n- (\"activation\", \"use_mxfp4_w4a4\", \"tp_size\", \"pads\", \"expected\"),\n+ (\"activation\", \"use_mxfp4_w4a4\", \"use_mxfp4_w4a16\", \"tp_size\", \"pads\", \"expected\"),\n [\n # W4A4 SiLU: AITER doubles the pad itself, at TP1 (and EP) as at TP2.\n- (\"SILU\", True, 1, (0, 64), (0, 64)),\n- (\"SILU\", True, 1, (0, 128), (0, 128)),\n- (\"SILU\", True, 2, (0, 64), (0, 64)),\n- # gpt-oss W4A16 at TP1 keeps the doubled pad.\n- (\"SWIGLUOAI\", False, 1, (0, 192), (0, 384)),\n+ (\"SILU\", True, False, 1, (0, 64), (0, 64)),\n+ (\"SILU\", True, False, 1, (0, 128), (0, 128)),\n+ (\"SILU\", True, False, 2, (0, 64), (0, 64)),\n+ # gpt-oss W4A16: AITER doubles the pad itself, at TP1 as at TP2.\n+ (\"SWIGLUOAI\", False, True, 1, (0, 192), (0, 192)),\n+ (\"SWIGLUOAI\", False, True, 2, (0, 96), (0, 64)),\n # BF16 SiLU at TP1 keeps the doubled pad.\n- (\"SILU\", False, 1, (0, 192), (0, 384)),\n+ (\"SILU\", False, False, 1, (0, 192), (0, 384)),\n # SITU passes through unrounded.\n- (\"SITU\", False, 1, (40, 96), (40, 96)),\n+ (\"SITU\", False, True, 1, (40, 96), (40, 96)),\n ],\n )\n def test_aiter_moe_pads(\n- activation, use_mxfp4_w4a4, tp_size, pads: tuple[int, int], expected\n+ activation,\n+ use_mxfp4_w4a4,\n+ use_mxfp4_w4a16,\n+ tp_size,\n+ pads: tuple[int, int],\n+ expected,\n ):\n from vllm.model_executor.layers.fused_moe.activation import MoEActivation\n from vllm.model_executor.layers.fused_moe.experts.rocm_aiter_moe import (\n@@ -660,7 +666,9 @@ def test_aiter_moe_pads(\n )\n \n assert (\n- aiter_moe_pads(*pads, MoEActivation[activation], use_mxfp4_w4a4, tp_size)\n+ aiter_moe_pads(\n+ *pads, MoEActivation[activation], use_mxfp4_w4a4, use_mxfp4_w4a16, tp_size\n+ )\n == expected\n )\n \n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][LoRA] Apply text-only LoRAs to the LM of multimodal wrappers\nLabels: bug, ready, verified\nFiles changed (2): tests/lora/test_lora_manager.py, vllm/lora/model_manager.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #48019. A LoRA trained on the text-only `*ForCausalLM` of a multimodal model silently does nothing when served on the multimodal wrapper. This resolves such adapters on the model side, in `LoRAModelManager._get_lora_layer_weights`, so it works for every multimodal wrapper without per-model mapper rules.\n\nThis builds on #49525 by @fooSynaptic (co-author), which fixes the same bug through a `WeightsMapper` fallback and only covers wrappers whose mapper has a `model.language_model.` rule. This PR covers those wrappers too, plus the ones without such a rule.\n\n## Claims\n\n- Text-named adapters (`model.layers.*` / `lm_head`) now apply to the language model of multimodal wrappers, including wrappers with no `model.language_model.` mapper rule or a different LM prefix (`llm.`, `model.text_model.`), e.g. Llama4, DeepSeek-V4, MiniCPM-V, Idefics3/SmolVLM.\n\n## Validation\n[results removed]\n## Details\n\n**Fix.** When a LoRA module has no exact match and lives under `get_mm_mapping().language_model`, look it up by its text-only name: the remainder after the prefix, or the remainder under `model.` when the prefix holds a bare decoder. All lookups, including packed (`qkv_proj`, `gate_up_proj`) and MoE packing, go through this function; text-named entries consumed by packing are dropped like the other sub-module entries.\n\n- The lookup is driven by the model's real modules, so there is no double-mapping risk (e.g. `model.language_model. -> model.` mappers) and no effect on layers owned by other PP ranks.\n- No change to base-weight loading or to any model's `hf_to_vllm_mapper`.\n- No new validation or error path, and no separate name-matching logic: the fallback lives inside the existing lookup, so any future \"adapter matches nothing\" check can reuse `_get_lora_layer_weights` and stay consistent with what is actually applied.\n\n---\n\nAI assistance (Claude Code) was used to write the patch and tests. I reviewed every changed line and ran the tests above.\n\n## Diff\n\n```diff\ndiff --git a/vllm/lora/model_manager.py b/vllm/lora/model_manager.py\nindex a7f9f02e77af..9eac678fb95b 100644\n--- a/vllm/lora/model_manager.py\n+++ b/vllm/lora/model_manager.py\n@@ -871,8 +871,7 @@ def _create_merged_loras_inplace(self, lora_model: LoRAModel) -> None:\n module_name,\n )\n )\n- for module in packed_module_names:\n- lora_model.loras.pop(module, None)\n+ self._pop_lora_weights(lora_model, packed_module_names)\n continue\n if self._is_non_gated_moe and len(replacement_loras) > 0:\n replacement_loras = self._pad_lora_pairs_to_triplets(\n@@ -891,8 +890,7 @@ def _create_merged_loras_inplace(self, lora_model: LoRAModel) -> None:\n # entries that were loaded but did not contribute to the\n # packed result. Without this they would keep extra CPU\n # memory alive after pack_moe.\n- for module in packed_module_names:\n- lora_model.loras.pop(module, None)\n+ self._pop_lora_weights(lora_model, packed_module_names)\n \n for lora in lora_model.loras.values():\n lora.optimize()\n@@ -1128,7 +1126,7 @@ def _convert_3d_to_2d_moe_lora(\n down_proj_lora.lora_b = [w1_b, down_b, w3_b]\n # Drop the redundant base_layer entry to avoid double pin_memory\n # and to keep the activation path looking up only the wrapper key.\n- lora_model.loras.pop(module_name + \".base_layer\", None)\n+ self._pop_lora_weights(lora_model, [module_name + \".base_layer\"])\n \n def _slice_moe_lora_ep(\n self,\n@@ -1224,15 +1222,57 @@ def _get_lora_layer_weights(\n if self.is_pooling_model and not lora_model.check_lora_name(module_name):\n # If it's a pool model, and the layer name is not found,\n # remove the prefix 'model.' and search again.\n- module_name = module_name.removeprefix(\"model.\")\n- if lora_model.check_lora_name(module_name):\n- org_module_name = module_name\n+ stripped_name = module_name.removeprefix(\"model.\")\n+ if lora_model.check_lora_name(stripped_name):\n+ org_module_name = stripped_name\n logger.info_once(\n \"For the pool model, successfully loaded the LoRA weights \"\n \"after removing the prefix 'model.'.\"\n )\n+ if not lora_model.check_lora_name(org_module_name):\n+ text_name = self._get_text_lora_name(lora_model, module_name)\n+ if text_name is not None:\n+ org_module_name = text_name\n return lora_model.get_lora(org_module_name)\n \n+ def _pop_lora_weights(self, lora_model: LoRAModel, module_names: list[str]) -> None:\n+ for module in module_names:\n+ lora_model.loras.pop(module, None)\n+ if text_name := self._get_text_lora_name(lora_model, module):\n+ lora_model.loras.pop(text_name)\n+\n+ def _get_text_lora_name(\n+ self, lora_model: LoRAModel, module_name: str\n+ ) -> str | None:\n+ for name in self._get_text_lora_names(module_name):\n+ if lora_model.check_lora_name(name):\n+ logger.info_once(\n+ \"Loaded text-only LoRA weights for the language model of a \"\n+ \"multimodal model.\"\n+ )\n+ return name\n+ return None\n+\n+ def _get_text_lora_names(self, module_name: str) -> list[str]:\n+ \"\"\"Names a text-only adapter uses for a language-model module.\n+\n+ Adapters trained on the text-only `*ForCausalLM` (e.g. PEFT on\n+ `Qwen3_5ForCausalLM`) name modules `model.layers.*` / `lm_head`, while\n+ multimodal wrappers mount the language model under a prefix such as\n+ `language_model.` or `llm.`. If the prefix holds a `*ForCausalLM`, the\n+ text name is the remainder; if it holds a bare decoder, it is the\n+ remainder under `model.`.\n+ \"\"\"\n+ if not getattr(self, \"supports_mm\", False):\n+ return []\n+ lm_prefix = self.mm_mapping.language_model[0].rstrip(\".\") + \".\"\n+ if not module_name.startswith(lm_prefix):\n+ return []\n+ name = module_name.removeprefix(lm_prefix)\n+ if name.startswith((\"model.\", \"lm_head\")):\n+ return [name]\n+ return [f\"model.{name}\", name]\n+\n def _get_module_to_save_weights(\n self, lora_model: LoRAModel, module_name: str\n ) -> LoRAFullModuleWeights | None:\n\ndiff --git a/tests/lora/test_lora_manager.py b/tests/lora/test_lora_manager.py\nindex ffb064ebfbdc..0d1ffdd61f51 100644\n--- a/tests/lora/test_lora_manager.py\n+++ b/tests/lora/test_lora_manager.py\n@@ -30,6 +30,7 @@\n from vllm.lora.request import LoRARequest\n from vllm.lora.worker_manager import LRUCacheWorkerLoRAManager, WorkerLoRAManager\n from vllm.model_executor.layers.fused_moe import GateLinear\n+from vllm.model_executor.models.module_mapping import MultiModelKeys\n from vllm.platforms import current_platform\n \n from .utils import create_peft_lora\n@@ -138,6 +139,46 @@ def test_from_lora_tensors(qwen3_lora_files, device):\n assert lora.lora_a.shape[0] == 8\n \n \n+@pytest.mark.parametrize(\"is_pooling_model\", [False, True])\n+@pytest.mark.parametrize(\n+ \"lm_prefix,module_name,text_name\",\n+ [\n+ (\n+ \"language_model\",\n+ \"language_model.model.layers.0.self_attn.o_proj\",\n+ \"model.layers.0.self_attn.o_proj\",\n+ ),\n+ (\"language_model\", \"language_model.lm_head\", \"lm_head\"),\n+ (\n+ \"model.text_model\",\n+ \"model.text_model.layers.0.self_attn.o_proj\",\n+ \"model.layers.0.self_attn.o_proj\",\n+ ),\n+ ],\n+)\n+def test_text_only_lora_binds_to_multimodal_language_model(\n+ lm_prefix, module_name, text_name, is_pooling_model\n+):\n+ \"\"\"An adapter trained on the text-only *ForCausalLM must apply to the\n+ language model of a multimodal wrapper instead of silently doing nothing.\"\"\"\n+ manager = LoRAModelManager.__new__(LoRAModelManager)\n+ manager.is_pooling_model = is_pooling_model\n+ manager.supports_mm = True\n+ manager.mm_mapping = MultiModelKeys.from_string_field(language_model=lm_prefix)\n+\n+ def weights(name):\n+ return LoRALayerWeights(name, 8, 16, torch.zeros(8, 4), torch.zeros(4, 8))\n+\n+ text_lora = weights(text_name)\n+ adapter = LoRAModel(1, 8, {text_name: text_lora})\n+ assert manager._get_lora_layer_weights(adapter, module_name) is text_lora\n+ assert manager._get_lora_layer_weights(adapter, \"visual.blocks.0.proj\") is None\n+\n+ exact_lora = weights(module_name)\n+ adapter = LoRAModel(1, 8, {text_name: text_lora, module_name: exact_lora})\n+ assert manager._get_lora_layer_weights(adapter, module_name) is exact_lora\n+\n+\n def create_lora(\n lora_id: int, model: nn.Module, sub_modules: list[str], device: torch.device\n ) -> LoRAModel:\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Honor add_generation_prompt and continue_final_message in the DeepSeek V4.1 tokenizer\nLabels: bug, ready, tool-calling, deepseek, verified, DSv4.1\nFiles changed (5): tests/parser/engine/test_deepseek_v41.py, tests/tokenizers_/test_deepseek_v41.py, vllm/parser/deepseek_v41.py, vllm/tokenizers/deepseek_v41.py, vllm/tokenizers/deepseek_v41_encoding.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #64431. Python-frontend part of #46256 on DeepSeek V4.1 (`vllm/tokenizers/deepseek_v41_encoding.py`).\n\nThe V4.1 encoder ignores `add_generation_prompt` and `continue_final_message`. When the last message is an assistant message, the prompt always ends at `<|end▁of▁sentence|>` without an `<|Assistant|>` turn prefix, so the model returns empty or garbled text with HTTP 200. With `continue_final_message=true`, the final message is still closed with EOS, so the reply cannot continue it.\n\nThis PR makes the V4.1 encoder honor both controls, and declares turn boundaries for the V4.1 parser so that the prompt-aware reasoning start from #61857 also applies to V4.1. It is the Python counterpart of the Rust-frontend fix in #62189 and uses the same semantics. The encoder change is a port of #57882 by @xijiaat (closed without review; credited as co-author of the commit) onto current `main` (after #60792, image order, and #62199, the 1017 reference encoding).\n\n**Related, not duplicates:** #62199 (merged) and #62196 (open) sync turn handling with the 1017 reference encoder (tool-result turns) and do not touch the generation controls. #62459 (open) fixes a conversation whose final message is `system`; this PR leaves that case to it and only changes conversations that end with an assistant message. #62887 (open) fixes `continue_final_message` only, by setting `wo_eos` on the final assistant message; this PR also covers `add_generation_prompt`. #64493 (draft) makes the same change for V3.2.\n\n## Claims\n\n- `add_generation_prompt=true` (the default): when the final message is an assistant message, the prompt now equals the DeepSeek reference encoding of the conversation followed by the reference assistant turn prefix, `<|Assistant|>` in thinking mode and `<|Assistant|>` in chat mode. The comparison is token-for-token. Earlier assistant messages keep their EOS.\n- `continue_final_message=true`: the final assistant message is left open (no EOS). If it ends inside its reasoning, the reasoning is left open as well. A request without a final assistant message is rejected with HTTP 400 (before, the flag was ignored and the request returned 200).\n- A final assistant message that is already left open with `wo_eos` (only possible when calling `encode_messages` directly; requests cannot set it) gets no new assistant turn, so it renders exactly as before.\n- With `turn_boundary_tokens` declared, the V4.1 parser starts in content when the current turn's prompt already closed reasoning (for example a continued answer after ``). A `` in an earlier turn does not count.\n- Fixes empty and garbled replies on DeepSeek-V4.1-Flash with the Python frontend: 210/280 empty replies before this change, 2/280 after (both remaining ones hit `max_tokens` while still reasoning).\n\n## Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/parser/deepseek_v41.py b/vllm/parser/deepseek_v41.py\nindex 76c7ad19bfd3..fb98861c4268 100644\n--- a/vllm/parser/deepseek_v41.py\n+++ b/vllm/parser/deepseek_v41.py\n@@ -20,6 +20,9 @@\n DSML_INVOKE_END = \"\"\n DSML_PARAM_START = \"<|DSML| parameter\"\n DSML_PARAM_CLOSE = \"\"\n+# Turn markers, so a prompt-closed reasoning block is only honored in the\n+# current turn (continue_final_message, or a template that skips thinking).\n+DEEPSEEK_TURN_BOUNDARY_TOKENS = frozenset({\"<|User|>\", \"<|Assistant|>\"})\n \n _PARAM_RE, _PARTIAL_PARAM_RE = _param_patterns(DSML_PARAM_START, DSML_PARAM_CLOSE)\n \n@@ -38,6 +41,7 @@ def deepseek_v41_config(thinking: bool = False) -> ParserEngineConfig:\n return replace(\n config,\n name=\"deepseek_v41\",\n+ turn_boundary_tokens=DEEPSEEK_TURN_BOUNDARY_TOKENS,\n terminals={**config.terminals, **terminal_overrides},\n token_id_terminals={\n key: terminal_overrides.get(key, value)\ndiff --git a/vllm/tokenizers/deepseek_v41.py b/vllm/tokenizers/deepseek_v41.py\nindex b628a34a8532..fecbae5e34df 100644\n--- a/vllm/tokenizers/deepseek_v41.py\n+++ b/vllm/tokenizers/deepseek_v41.py\n@@ -127,6 +127,8 @@ def apply_chat_template(\n drop_thinking=kwargs.get(\"drop_thinking\", True),\n reasoning_effort=effort,\n image_order=image_order,\n+ add_generation_prompt=kwargs.get(\"add_generation_prompt\", True),\n+ continue_final_message=kwargs.get(\"continue_final_message\", False),\n )\n if kwargs.get(\"tokenize\", True):\n tokenizer_kwargs = {\ndiff --git a/vllm/tokenizers/deepseek_v41_encoding.py b/vllm/tokenizers/deepseek_v41_encoding.py\nindex b25fe57c2b61..e6befedc9751 100644\n--- a/vllm/tokenizers/deepseek_v41_encoding.py\n+++ b/vllm/tokenizers/deepseek_v41_encoding.py\n@@ -332,6 +332,8 @@ def render_message(\n drop_thinking: bool = True,\n reasoning_effort: Union[str, int, None] = None,\n image_order: Optional[List[int]] = None,\n+ add_generation_prompt: bool = True,\n+ continue_final_message: bool = False,\n ) -> str:\n \"\"\"\n Render a single message at the given index into its V4.1 encoded string form.\n@@ -350,7 +352,8 @@ def render_message(\n response_format = msg.get(\"response_format\")\n tool_calls = msg.get(\"tool_calls\")\n reasoning_content = msg.get(\"reasoning_content\")\n- wo_eos = msg.get(\"wo_eos\", False)\n+ is_last = index == len(messages) - 1\n+ wo_eos = msg.get(\"wo_eos\", False) or (is_last and continue_final_message)\n \n # Collect source indices only from content that survives preprocessing.\n if image_order is not None:\n@@ -475,6 +478,14 @@ def render_message(\n thinking_part = (\n thinking_template.format(reasoning_content=rc) + thinking_end_token\n )\n+ if (\n+ is_last\n+ and continue_final_message\n+ and rc\n+ and not summary_content\n+ and not tc_content\n+ ):\n+ thinking_part = rc\n else:\n thinking_part = \"\"\n \n@@ -493,6 +504,10 @@ def render_message(\n else:\n raise NotImplementedError(f\"Unknown role: {role}\")\n \n+ # Historical assistant separators are needed even without a generation prompt.\n+ if is_last and not add_generation_prompt:\n+ return prompt\n+\n # Append transition tokens based on what follows\n if index + 1 < len(messages) and messages[index + 1].get(\"role\") not in [\n \"assistant\",\n@@ -521,8 +536,11 @@ def render_message(\n )\n prompt += task_sp_token\n \n- elif messages[index].get(\"role\") in [\"user\", \"developer\"] or (\n- messages[index].get(\"role\") == \"system\" and index > 0\n+ elif (\n+ messages[index].get(\"role\") in [\"user\", \"developer\"]\n+ or (messages[index].get(\"role\") == \"system\" and index > 0)\n+ # A final assistant message left open by wo_eos is not followed by a turn.\n+ or (is_last and role == \"assistant\" and not wo_eos)\n ):\n # Normal generation: append Assistant + thinking token\n # (mid-conversation system messages also trigger the assistant header)\n@@ -567,8 +585,17 @@ def encode_messages(\n add_default_bos_token: bool = True,\n reasoning_effort: Union[str, int, None] = None,\n image_order: Optional[List[int]] = None,\n+ add_generation_prompt: bool = True,\n+ continue_final_message: bool = False,\n ) -> str:\n \"\"\"Encode preprocessed (text-only) messages into the V4.1 prompt format.\"\"\"\n+ if continue_final_message:\n+ if not messages or messages[-1].get(\"role\") != \"assistant\":\n+ raise ValueError(\n+ \"continue_final_message requires a final assistant message\"\n+ )\n+ add_generation_prompt = False\n+\n context = context if context else []\n \n # Preprocess: merge tool messages and sort tool results\n@@ -603,6 +630,8 @@ def encode_messages(\n drop_thinking=effective_drop_thinking,\n reasoning_effort=reasoning_effort,\n image_order=image_order,\n+ add_generation_prompt=add_generation_prompt,\n+ continue_final_message=continue_final_message,\n )\n \n return prompt\n\ndiff --git a/tests/parser/engine/test_deepseek_v41.py b/tests/parser/engine/test_deepseek_v41.py\nindex 75ef0bf044c9..430aafb76351 100644\n--- a/tests/parser/engine/test_deepseek_v41.py\n+++ b/tests/parser/engine/test_deepseek_v41.py\n@@ -27,7 +27,7 @@\n \n \n def tokenizer_for(text, special_calls):\n- vocab = {\"\": 50, \"\": 51}\n+ vocab = {\"\": 50, \"\": 51, \"<|User|>\": 54, \"<|Assistant|>\": 55}\n if special_calls:\n vocab |= {\"<|DSML| calls>\": 52, \"\": 53}\n tokens: list[tuple[int, str]] = []\n@@ -132,6 +132,54 @@ def test_reasoning_adapter_controls_and_usage(\n assert not parser.is_reasoning_end([51, 100, 50])\n \n \n+@pytest.mark.parametrize(\"streaming\", [False, True])\n+@pytest.mark.parametrize(\n+ (\"prompt_token_ids\", \"text\", \"expected_reasoning\", \"expected_content\"),\n+ [\n+ # continue_final_message: the current turn already closed reasoning.\n+ ([54, 100, 55, 50, 101, 51, 102], \"12\", \"\", \"12\"),\n+ # A closed block in an earlier turn does not end this turn's reasoning.\n+ (\n+ [54, 100, 55, 50, 101, 51, 102, 54, 103, 55, 50],\n+ \"Plan.12\",\n+ \"Plan.\",\n+ \"12\",\n+ ),\n+ ],\n+)\n+def test_prompt_closed_reasoning_is_scoped_to_current_turn(\n+ streaming,\n+ prompt_token_ids,\n+ text,\n+ expected_reasoning,\n+ expected_content,\n+):\n+ tokenizer, tokens = tokenizer_for(text, False)\n+ parser = parser_for(tokenizer, {\"thinking\": True})\n+ output_ids = [tid for tid, _ in tokens]\n+ if streaming:\n+ output = collect_output(\n+ replay_streaming(\n+ parser,\n+ tokens,\n+ chunk_size=1,\n+ finished_on_last=True,\n+ prompt_token_ids=prompt_token_ids,\n+ )\n+ )\n+ reasoning, content = output.reasoning, output.content\n+ else:\n+ parser.set_prompt_token_ids(prompt_token_ids)\n+ reasoning, content, _ = parser.parse(\n+ text, _test_request(), model_output_token_ids=output_ids\n+ )\n+ assert (reasoning or \"\") == expected_reasoning\n+ assert content == expected_content\n+ assert (parser.reasoning_parser.count_reasoning_tokens(output_ids) == 0) == (\n+ not expected_reasoning\n+ )\n+\n+\n def test_python_argument_conversion_and_partial_values():\n converter = deepseek_v41_config().arg_converter\n assert converter is not None\ndiff --git a/tests/tokenizers_/test_deepseek_v41.py b/tests/tokenizers_/test_deepseek_v41.py\nindex 664c1c07cc52..e85a362b591d 100644\n--- a/tests/tokenizers_/test_deepseek_v41.py\n+++ b/tests/tokenizers_/test_deepseek_v41.py\n@@ -48,6 +48,9 @@ def test_reference_encoder_fixtures(case_id):\n thinking_mode = case.get(\"thinking_mode\") or \"chat\"\n expected = (FIXTURES / \"deepseek_v41\" / f\"test_output_{case_id}.txt\").read_text()\n \n+ # The reference encodes a conversation that ends with an assistant message as\n+ # closed history, which is add_generation_prompt=False here.\n+ final_assistant = messages[-1][\"role\"] == \"assistant\"\n if any(m[\"role\"] == \"latest_reminder\" for m in messages):\n # latest_reminder is not an API role.\n assert case.get(\"tools\") is None\n@@ -55,14 +58,21 @@ def test_reference_encoder_fixtures(case_id):\n messages,\n thinking_mode=thinking_mode,\n reasoning_effort=case.get(\"reasoning_effort\"),\n+ add_generation_prompt=not final_assistant,\n )\n else:\n- prompt = render(\n- messages,\n+ kwargs = dict(\n tools=case.get(\"tools\"),\n thinking=thinking_mode == \"thinking\",\n reasoning_effort=case.get(\"reasoning_effort\"),\n )\n+ prompt = render(messages, add_generation_prompt=not final_assistant, **kwargs)\n+ if final_assistant:\n+ # By default a new assistant turn follows the final assistant message.\n+ opener = \"<|Assistant|>\" + (\n+ \"\" if thinking_mode == \"thinking\" else \"\"\n+ )\n+ assert render(messages, **kwargs) == expected + opener\n assert prompt == expected\n \n \n@@ -403,3 +413,101 @@ def test_dropped_developer_only_image_leaves_text_prompt(render_with_media):\n assert \"<|deepseek_image|>\" not in prompt[\"prompt\"]\n assert \"multi_modal_data\" not in prompt\n assert \"multi_modal_uuids\" not in prompt\n+\n+\n+@pytest.mark.parametrize(\"thinking\", [False, True])\n+@pytest.mark.parametrize(\"final_role\", [\"user\", \"developer\", \"system\", \"assistant\"])\n+def test_generation_prompt_only_controls_final_turn(thinking, final_role):\n+ messages = [\n+ {\"role\": \"user\", \"content\": \"first question\"},\n+ {\"role\": \"assistant\", \"content\": \"first answer\"},\n+ {\"role\": \"user\", \"content\": \"second question\"},\n+ {\"role\": final_role, \"content\": \"final message\"},\n+ ]\n+ original = copy.deepcopy(messages)\n+ closed = render(messages, thinking=thinking, add_generation_prompt=False)\n+ opened = render(messages, thinking=thinking, add_generation_prompt=True)\n+ cue = \"<|Assistant|>\" + (\"\" if thinking else \"\")\n+\n+ assert opened == closed + cue\n+ assert \"first answer<|end▁of▁sentence|>\" in closed\n+ assert \"<|User|>first question<|Assistant|>\" in closed\n+ assert messages == original\n+\n+\n+@pytest.mark.parametrize(\"thinking\", [False, True])\n+def test_continue_final_message_preserves_historical_eos(thinking):\n+ messages = [\n+ {\"role\": \"user\", \"content\": \"first question\"},\n+ {\"role\": \"assistant\", \"content\": \"first answer\"},\n+ {\"role\": \"user\", \"content\": \"second question\"},\n+ {\"role\": \"assistant\", \"content\": \"The answer is \"},\n+ ]\n+ original = copy.deepcopy(messages)\n+ closed = render(messages, thinking=thinking, add_generation_prompt=False)\n+ continued = render(\n+ messages,\n+ thinking=thinking,\n+ add_generation_prompt=False,\n+ continue_final_message=True,\n+ )\n+ assert closed == continued + \"<|end▁of▁sentence|>\"\n+ assert continued.endswith(\"The answer is \")\n+ assert \"first answer<|end▁of▁sentence|>\" in continued\n+ assert messages == original\n+\n+\n+def test_continue_final_message_through_chat_request():\n+ request = ChatCompletionRequest(\n+ model=\"deepseek-ai/DeepSeek-V4.1-Flash\",\n+ messages=[\n+ {\"role\": \"user\", \"content\": \"Finish this sentence.\"},\n+ {\"role\": \"assistant\", \"content\": \"The answer is \"},\n+ ],\n+ continue_final_message=True,\n+ )\n+ kwargs = request.build_chat_params(None, \"auto\").get_apply_chat_template_kwargs()\n+ assert render(request.messages, **kwargs).endswith(\"The answer is \")\n+\n+\n+def test_continue_final_reasoning_keeps_thinking_open():\n+ messages = [\n+ {\"role\": \"user\", \"content\": \"Explain your answer.\"},\n+ {\"role\": \"assistant\", \"content\": None, \"reasoning\": \"Let me consider \"},\n+ ]\n+ assert render(messages, continue_final_message=True).endswith(\n+ \"<|Assistant|>Let me consider \"\n+ )\n+\n+\n+@pytest.mark.parametrize(\"thinking_mode\", [\"chat\", \"thinking\"])\n+@pytest.mark.parametrize(\n+ \"final\",\n+ [\n+ {\"content\": \"The answer is \"},\n+ {\"content\": \"\", \"reasoning_content\": \"Let me consider \"},\n+ {\"content\": \"\", \"tool_calls\": [tool_call(\"search\")]},\n+ ],\n+)\n+def test_open_final_message_gets_no_generation_prompt(thinking_mode, final):\n+ # A final assistant message left open with wo_eos is never followed by a\n+ # new assistant turn, whatever add_generation_prompt says.\n+ messages = [\n+ {\"role\": \"user\", \"content\": \"question\"},\n+ {\"role\": \"assistant\", \"wo_eos\": True, **final},\n+ ]\n+\n+ def encode(**kwargs):\n+ return encode_messages(\n+ copy.deepcopy(messages), thinking_mode=thinking_mode, **kwargs\n+ )\n+\n+ closed = encode(add_generation_prompt=False)\n+ assert not closed.endswith(\"<|end▁of▁sentence|>\")\n+ assert encode() == closed\n+\n+\n+@pytest.mark.parametrize(\"messages\", [[], [{\"role\": \"user\", \"content\": \"hello\"}]])\n+def test_continue_final_message_requires_assistant(messages):\n+ with pytest.raises(ValueError, match=\"final assistant\"):\n+ render(messages, continue_final_message=True)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Frontend] Normalize beam search scores by generated length\nLabels: bug, frontend, ready\nFiles changed (5): tests/samplers/test_beam_search_online.py, vllm/entrypoints/generate/beam_search/offline.py, vllm/entrypoints/generate/beam_search/online.py, vllm/entrypoints/generate/beam_search/utils.py, vllm/sampling_params.py\n\n## Description (results removed)\n\n## Overview\n\nBeam search divides each beam's cumulative log-prob (a sum over the *generated* tokens) by `(prompt + generated length) ** length_penalty`. It should divide by the generated length only, as Transformers does. With any non-trivial prompt, the prompt length dominates the denominator, so `length_penalty` stops having an effect and beams that hit EOS early win, often with an empty completion. This affects `LLM.beam_search` and `use_beam_search` on `/v1/completions`, `/v1/chat/completions` and speech-to-text, which all share `create_sort_beams_key_function`.\n\nFixes #2606, which was auto-closed as stale. The earlier fix in #7007 targeted the old V0 `sequence.py` and was never merged, and the bug carried over into the current frontend implementation.\n\n## Claims\n\n- Beams are ranked by `cum_logprob / num_generated_tokens ** length_penalty`, counting a terminating EOS token, as in Transformers' [`_update_finished_beams`](https://github.com/huggingface/transformers/blob/09a71e5b32a747dbc7805599457e67c956ef212f/src/transformers/generation/utils.py#L3531): `topk_log_probs / ((cur_len + 1 - decoder_prompt_len) ** length_penalty)`. Transformers fixed the same bug in huggingface/transformers#27351.\n- Beam search no longer prefers empty completions. On `tests/prompts/example.txt` without trailing newlines, the top beam on `main` is EOS-only for 8 of 8 prompts (HF: 1 of 8). With this PR it is 1 of 8.\n- HF parity improves. On the exact prompts `tests/samplers/test_beam_search.py` uses, the top beam matches HF on 8/8 prompts instead of 6/8.\n- `length_penalty` changes the result again for long prompts. On `main`, the same beam wins for every value from 0 to 2.\n- `BeamSearchParams.length_penalty` now has a docstring describing these semantics.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause.** `get_beam_search_score` divided by `len(tokens)`. `tokens` starts as the prompt (`BeamSearchInstance` and the online path's `tokens=prompt_token_ids`), but `cum_logprob` only sums generated tokens. The helper was adapted from an old Transformers `BeamHypotheses.add` that had the same bug. huggingface/transformers#27351 (v4.36) fixed it there, noting it \"would cause an unexpected bias towards generating shorter sequences\".\n\n**Why `len(x.logprobs)`.** Every path that extends or completes a beam appends exactly one logprobs entry and adds that token's log-prob to `cum_logprob`. That covers offline steps, online running beams, EOS beams and aborted beams. `tokens` can't be used, because the online path drops the EOS from `tokens` unless `include_stop_str_in_output` is set. The `max(..., 1)` guard still covers a beam aborted before generating anything.\n\n**Not changed.** Two differences from Transformers remain:\n- vLLM finalizes every EOS candidate among each beam's top `2 * beam_width` logprobs; Transformers only finalizes those in the global top `num_beams`.\n- vLLM has no early-stopping heuristic.\n\n**Related.**\n- #59506 adds overflow handling to the same function. It is orthogonal, but it needs a rebase onto the new `(num_generated_tokens, cumulative_logprob, length_penalty)` signature.\n- The Rust-frontend beam search in #47705 ports the old formula, including unit tests that encode it. The same `logprobs.len()` change applies there.\n- RFC #61880 plans to reuse `get_beam_search_score` for HF-parity scoring.\n\n**Not a duplicate.** I searched open and closed issues and PRs for `beam search length penalty`, `length_penalty`, `get_beam_search_score`, `beam search normalization` and `beam search shorter`. The only related hits are #2606, the stale V0 PR #7007, and #59506 (overflow only). I also checked every open PR touching `vllm/entrypoints/generate/beam_search/` (#59506, #60327, #60550, #52621, #36285, #60787, #49541, #47705): none changes the normalization.\n\n**AI assistance.** This PR was prepared with AI assistance (Claude Code). It helped locate the bug, write the change and test, and run the validation above. I reviewed every changed line and the results.\n\ncc @DarkLight1337\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/generate/beam_search/offline.py b/vllm/entrypoints/generate/beam_search/offline.py\nindex c109fc75c8e5..e458ba99282f 100644\n--- a/vllm/entrypoints/generate/beam_search/offline.py\n+++ b/vllm/entrypoints/generate/beam_search/offline.py\n@@ -136,7 +136,7 @@ def beam_search(\n self.llm_engine.input_processor.generation_config_fields,\n tokenizer.eos_token_id,\n )\n- sort_beams_key = create_sort_beams_key_function(eos_token_ids, length_penalty)\n+ sort_beams_key = create_sort_beams_key_function(length_penalty)\n instances: list[BeamSearchInstance] = []\n \n for lora_req, prompt, prompt_priority in zip(\ndiff --git a/vllm/entrypoints/generate/beam_search/online.py b/vllm/entrypoints/generate/beam_search/online.py\nindex 45949dd6b5f8..f353c90c8e43 100644\n--- a/vllm/entrypoints/generate/beam_search/online.py\n+++ b/vllm/entrypoints/generate/beam_search/online.py\n@@ -78,7 +78,7 @@ async def beam_search(\n self.engine_client.input_processor.generation_config_fields,\n tokenizer.eos_token_id,\n )\n- sort_beams_key = create_sort_beams_key_function(eos_token_ids, length_penalty)\n+ sort_beams_key = create_sort_beams_key_function(length_penalty)\n all_beams = [\n BeamSearchSequence(\n orig_prompt=prompt,\ndiff --git a/vllm/entrypoints/generate/beam_search/utils.py b/vllm/entrypoints/generate/beam_search/utils.py\nindex d0480420de7c..d009008cb5a0 100644\n--- a/vllm/entrypoints/generate/beam_search/utils.py\n+++ b/vllm/entrypoints/generate/beam_search/utils.py\n@@ -139,30 +139,26 @@ def __init__(\n \n \n def get_beam_search_score(\n- tokens: list[int],\n+ num_generated_tokens: int,\n cumulative_logprob: float,\n- eos_token_ids: set[int],\n length_penalty: float = 1.0,\n ) -> float:\n \"\"\"Calculate the beam search score with length penalty.\n \n- Adapted from\n+ Like Transformers, the length counts the generated tokens, including a\n+ terminating EOS token. Adapted from\n \n- https://github.com/huggingface/transformers/blob/ccb92be23def445f2afdea94c31286f84b89eb5b/src/transformers/generation/beam_search.py#L938\n+ https://github.com/huggingface/transformers/blob/09a71e5b32a747dbc7805599457e67c956ef212f/src/transformers/generation/utils.py#L3531\n \"\"\"\n- seq_len = len(tokens)\n- if tokens[-1] in eos_token_ids:\n- seq_len -= 1\n+ # An aborted beam may not have generated any tokens.\n+ return cumulative_logprob / (max(num_generated_tokens, 1) ** length_penalty)\n \n- # An aborted beam may contain only an EOS prompt token.\n- return cumulative_logprob / (max(seq_len, 1) ** length_penalty)\n \n-\n-def create_sort_beams_key_function(eos_token_ids: set[int], length_penalty: float):\n+def create_sort_beams_key_function(length_penalty: float):\n def sort_beams_key(x: BeamSearchSequence) -> float:\n- return get_beam_search_score(\n- x.tokens, x.cum_logprob, eos_token_ids, length_penalty\n- )\n+ # `logprobs` has one entry per generated token, including an EOS token\n+ # that `tokens` omits unless include_stop_str_in_output is set.\n+ return get_beam_search_score(len(x.logprobs), x.cum_logprob, length_penalty)\n \n return sort_beams_key\n \ndiff --git a/vllm/sampling_params.py b/vllm/sampling_params.py\nindex a0ff63615566..466c19e6bb74 100644\n--- a/vllm/sampling_params.py\n+++ b/vllm/sampling_params.py\n@@ -1506,6 +1506,9 @@ class BeamSearchParams(\n ignore_eos: bool = False\n temperature: float = 0.0\n length_penalty: float = 1.0\n+ \"\"\"Exponent on the number of generated tokens (including a final EOS) that\n+ normalizes a beam's cumulative log-probability when ranking beams, as in\n+ Transformers. Values above 0 favor longer beams, below 0 shorter ones.\"\"\"\n include_stop_str_in_output: bool = False\n structured_outputs: StructuredOutputsParams | None = None\n skip_special_tokens: bool = True\n\ndiff --git a/tests/samplers/test_beam_search_online.py b/tests/samplers/test_beam_search_online.py\nindex 9afda98eff3b..2381f6b8da57 100644\n--- a/tests/samplers/test_beam_search_online.py\n+++ b/tests/samplers/test_beam_search_online.py\n@@ -211,6 +211,63 @@ async def generate(engine_prompt, sampling_params, *args, **kwargs):\n assert all(not p.stop_token_ids for p in engine_params)\n \n \n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\"offline\", [False, True])\n+async def test_beam_search_score_ignores_prompt_length(\n+ monkeypatch, offline: bool\n+) -> None:\n+ \"\"\"Beams are ranked by generated length only, as in Transformers.\"\"\"\n+ [comment with results removed]\n+ prompt_len = 50\n+ prompt: TokensInput = {\"type\": \"token\", \"prompt_token_ids\": [1] * prompt_len}\n+ params = BeamSearchParams(\n+ beam_width=1, max_tokens=2, length_penalty=1.0, watermarking=False\n+ )\n+ eos = _Tokenizer.eos_token_id\n+ # Mean logprobs: [eos] -1.0, [11, eos] -0.85, [11, 11] -0.8.\n+ results = []\n+ for logprobs in (\n+ {eos: Logprob(-1.0), 11: Logprob(-1.5)},\n+ {11: Logprob(-0.1), eos: Logprob(-0.2)},\n+ ):\n+ result = await anext(\n+ _EngineClient().generate(prompt, SamplingParams(watermarking=False))\n+ )\n+ result.outputs[0].logprobs = [logprobs]\n+ results.append(result)\n+\n+ def step_result(engine_prompt) -> RequestOutput:\n+ return results[len(engine_prompt[\"prompt_token_ids\"]) - prompt_len]\n+\n+ if offline:\n+ offline_serving = _OfflineServing()\n+ monkeypatch.setattr(\n+ _OfflineServing,\n+ \"_beam_search_step\",\n+ BeamSearchOfflineMixin._beam_search_step,\n+ )\n+\n+ def render_and_run_requests(*, prompts, **kwargs):\n+ return [step_result(p) for p in prompts]\n+\n+ monkeypatch.setattr(\n+ offline_serving, \"_render_and_run_requests\", render_and_run_requests\n+ )\n+ beam = offline_serving.beam_search(cast(list, [prompt]), params)[0].sequences[0]\n+ assert beam.tokens[prompt_len:] == [11, 11]\n+ else:\n+\n+ async def generate(engine_prompt, *args, **kwargs):\n+ yield step_result(engine_prompt)\n+\n+ online_serving = _AsyncServing()\n+ monkeypatch.setattr(online_serving.engine_client, \"generate\", generate)\n+ output = (\n+ await anext(online_serving.beam_search(prompt, \"request\", params))\n+ ).outputs[0]\n+ assert output.token_ids == [11, 11]\n+\n+\n @pytest.mark.asyncio\n @pytest.mark.parametrize(\"priority\", [None, -9, 12])\n async def test_beam_search_preserves_priority_for_every_step(monkeypatch, priority):\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] shm_broadcast: poll the notify socket from busy readers\nLabels: bug, ready\nFiles changed (2): tests/distributed/test_shm_broadcast.py, vllm/distributed/device_communicators/shm_broadcast.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #63026. A local SHM reader that keeps reading (which is the normal state under load) never touches its `CONFLATE` notify socket, and libzmq queues an internal command for every write notification until it does. Reader memory then grows with every message. This PR polls the notify socket from `SpinCondition.record_read()` at most once per second.\n\n## Claims\n\n- Reader-side memory stays bounded under sustained load. Before this change, every message added ~41 B to the reader's libzmq mailbox. That affects each worker's RPC broadcast reader (2 messages per step) and EngineCore's response readers (one per replying worker; all of them reply when a KV connector is used).\n\n## Validation\n[results removed]\n## Details\n\n**Root cause.** In libzmq 4.3.5, `ypipe_conflate_t::flush()` returns `reader_awake`, and nothing ever sets that to true. A `CONFLATE` session pipe also gets HWM -1 (unlimited). So for every notification it receives, the reader's I/O thread posts an `activate_read` command to the SUB socket's mailbox. Those commands are only processed when the application calls into the socket. libzmq documents this under `ZMQ_CONFLATE` in `zmq_setsockopt(3)`: \"If recv is not called on the inbound socket, the queue and memory will grow with each message received. Use ZMQ_EVENTS to trigger the conflation of the messages.\" `SpinCondition.wait()` polls only after `busy_loop_s` (1 s) without a read, which never happens while the engine is stepping. The backlog is cleared only after the reader idles for more than 1 s. EngineCore's response readers stay stuck until the next request arrives, and RSS may not come back down even then.\n\n**Why `poll()` and not just `recv()`.** When a message is already in the pipe, `recv(NOBLOCK)` returns it without processing commands, so the backlog keeps growing (last column in the standalone table above). `poll()` goes through `ZMQ_EVENTS`, which processes them.\n\n**Correctness.** Notifications are only wake-up hints; the SHM flags are authoritative. The writer always sets the written flag (with a fence) before it notifies. So if a busy read consumes a notification, the slot it announced is already visible to the next `acquire_read()` check. The socket is only used by the reader thread, the same thread that runs `wait()`. Cancellation goes through a separate socket.\n\n**Interval.** 1 s matches the default `busy_loop_s` and the interval used by vllm-project/vllm-ascend#19140, which is the Ascend-side workaround for the same issue. That patch can be dropped once this lands. At most ~1 s worth of commands can accumulate. I kept the interval as a separate constant instead of reusing `busy_loop_s`, because #52814 would make that window configurable down to ~0.\n\n**Not a duplicate.** #58917 changes the writer's HWM so that notifications are not dropped. It does not touch the reader mailbox, and it would actually remove the incidental rate cap that currently limits this growth. #52814 and #52848 change the busy window and sleep. No open PR services the reader's notify socket.\n\nAI assistance (Claude Code) was used to investigate and write this change. I reviewed every changed line and ran the tests above.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/distributed/device_communicators/shm_broadcast.py b/vllm/distributed/device_communicators/shm_broadcast.py\nindex fcdd9376c9e1..1c007b2cd2aa 100644\n--- a/vllm/distributed/device_communicators/shm_broadcast.py\n+++ b/vllm/distributed/device_communicators/shm_broadcast.py\n@@ -69,6 +69,10 @@\n # written-flag. Bounds lost-notify recovery latency to ~5s while the periodic\n # wakeup stays negligible (one flag check per reader every 5s).\n SHM_READER_RECHECK_INTERVAL_MS = 5000\n+# How often a busy reader polls its notify socket. CONFLATE keeps one message,\n+# but libzmq still queues an internal command per notification until the socket\n+# is polled, so a reader that never goes idle would grow without bound.\n+SHM_NOTIFY_POLL_INTERVAL_S = 2.0\n \n \n from_bytes_big = functools.partial(int.from_bytes, byteorder=\"big\")\n@@ -141,6 +145,8 @@ def __init__(\n if is_reader:\n # Time of last shm buffer read\n self.last_read = time.monotonic()\n+ # Time a busy reader last polled the notify socket\n+ self.last_notify_poll = self.last_read\n \n # Time to keep busy-looping on the shm buffer before going idle\n self.busy_loop_s = busy_loop_s\n@@ -183,6 +189,12 @@ def __init__(\n \n def record_read(self):\n self.last_read = time.monotonic()\n+ if self.last_read - self.last_notify_poll >= SHM_NOTIFY_POLL_INTERVAL_S:\n+ self.last_notify_poll = self.last_read\n+ # poll() makes libzmq process the queued commands; a bare recv()\n+ # returns the pending message without doing so.\n+ if self.local_notify_socket.poll(timeout=0):\n+ self.local_notify_socket.recv(flags=zmq.NOBLOCK, copy=False)\n \n def cancel(self):\n # Sends cancellation ping that will cause the reader to wake up.\n\ndiff --git a/tests/distributed/test_shm_broadcast.py b/tests/distributed/test_shm_broadcast.py\nindex 0e6efd10429b..9b15b607f1a4 100644\n--- a/tests/distributed/test_shm_broadcast.py\n+++ b/tests/distributed/test_shm_broadcast.py\n@@ -668,6 +668,33 @@ def poll_timeout(*, timeout: int | None = None):\n socket.close(linger=0)\n \n \n+def test_busy_reader_consumes_write_notifications():\n+ \"\"\"A reader that never goes idle must still service its notify socket,\n+ otherwise libzmq queues a command per notification and memory grows with\n+ every message read.\n+ \"\"\"\n+ writer = MessageQueue(\n+ n_reader=1,\n+ n_local_reader=1,\n+ max_chunk_bytes=1024,\n+ max_chunks=1,\n+ )\n+ reader = MessageQueue.create_from_handle(writer.export_handle(), rank=0)\n+ notify_socket = reader._spin_condition.local_notify_socket\n+ try:\n+ writer.wait_until_ready()\n+ reader.wait_until_ready()\n+\n+ writer.enqueue(\"payload\")\n+ assert notify_socket.poll(timeout=5000)\n+ with mock.patch.object(shm_broadcast, \"SHM_NOTIFY_POLL_INTERVAL_S\", 0):\n+ assert reader.dequeue(timeout=5) == \"payload\"\n+ assert not notify_socket.poll(timeout=0)\n+ finally:\n+ writer.shutdown()\n+ reader.shutdown()\n+\n+\n def test_acquire_read_releases_slot_when_reader_raises():\n writer = MessageQueue(\n n_reader=1,\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Frontend] Honor token ID logprob overrides on derender paths\nLabels: bug, documentation, frontend, ready\nFiles changed (14): docs/serving/online_serving/derenderer.md, docs/serving/online_serving/token_in_token_out.md, tests/entrypoints/scale_out/derender/test_derender.py, tests/entrypoints/scale_out/derender/test_derender_stream.py, tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py, tests/entrypoints/scale_out/render/test_render.py, tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py, tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py, vllm/entrypoints/launchers/api_server/app_state.py, vllm/entrypoints/launchers/render/app_state.py, vllm/entrypoints/scale_out/render/serving.py, vllm/entrypoints/scale_out/token_in_token_out/protocol.py, vllm/entrypoints/scale_out/token_in_token_out/serving.py, vllm/renderers/online_derenderer.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #63162: honor the tri-state `return_tokens_as_token_ids` override on both disaggregated derender paths, including generate streaming after merged #63103.\n\n## Claims\n\n- Explicit request true/false overrides the answering server's flag; omitted/null falls back to that server's setting.\n- `/render` omits the new context key when null, preserving legacy generate compatibility for default requests. Explicit overrides require an upgraded generate node.\n\n## Validation\n[results removed]\n## Details\n\nThe request override was dropped at render serialization, generate used only its server flag, and separate derender always decoded. A nullable `ParseContext` field preserves explicit false; field-level null omission prevents adding an unknown key for older generate nodes. Each answering path resolves the override against its own server default. Placeholder formatting reuses the existing helper; decoded logprobs retain the existing decoder and UTF-8 fallback repair.\n\nDuplicate searches found only this PR and merged #60082/#63103; neither merged feature includes this request-override fix. The affected logprobs docs explain precedence and rolling upgrade behavior. AI assistance was used for implementation, tests, documentation and review preparation.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/launchers/api_server/app_state.py b/vllm/entrypoints/launchers/api_server/app_state.py\nindex 682e5882204e..949a0b0977a2 100644\n--- a/vllm/entrypoints/launchers/api_server/app_state.py\n+++ b/vllm/entrypoints/launchers/api_server/app_state.py\n@@ -119,6 +119,7 @@ async def init_app_state(\n default_chat_template_kwargs=default_chat_template_kwargs,\n reasoning_effort_map=args.reasoning_effort_map,\n log_error_stack=args.log_error_stack,\n+ return_tokens_as_token_ids=args.return_tokens_as_token_ids,\n )\n \n state.serving_tokenization = ServingTokenization(\ndiff --git a/vllm/entrypoints/launchers/render/app_state.py b/vllm/entrypoints/launchers/render/app_state.py\nindex 3152d354e363..4a4e13d0497b 100644\n--- a/vllm/entrypoints/launchers/render/app_state.py\n+++ b/vllm/entrypoints/launchers/render/app_state.py\n@@ -94,6 +94,7 @@ async def init_render_app_state(\n default_chat_template_kwargs=default_chat_template_kwargs,\n reasoning_effort_map=args.reasoning_effort_map,\n log_error_stack=args.log_error_stack,\n+ return_tokens_as_token_ids=args.return_tokens_as_token_ids,\n )\n \n state.openai_serving_models = model_registry\ndiff --git a/vllm/entrypoints/scale_out/render/serving.py b/vllm/entrypoints/scale_out/render/serving.py\nindex f64562538bb8..d72cc05ae7ad 100644\n--- a/vllm/entrypoints/scale_out/render/serving.py\n+++ b/vllm/entrypoints/scale_out/render/serving.py\n@@ -233,6 +233,7 @@ def _build_parse_context(\n tool_choice=request.tool_choice,\n parallel_tool_calls=request.parallel_tool_calls,\n include_reasoning=request.include_reasoning,\n+ return_tokens_as_token_ids=request.return_tokens_as_token_ids,\n # Like the derenderer, Harmony output is parsed without template\n # kwargs.\n chat_template_kwargs=(\ndiff --git a/vllm/entrypoints/scale_out/token_in_token_out/protocol.py b/vllm/entrypoints/scale_out/token_in_token_out/protocol.py\nindex e0c30ddce01b..83fceac173b4 100644\n--- a/vllm/entrypoints/scale_out/token_in_token_out/protocol.py\n+++ b/vllm/entrypoints/scale_out/token_in_token_out/protocol.py\n@@ -68,6 +68,9 @@ class ParseContext(BaseModel):\n ) = \"none\"\n parallel_tool_calls: bool | None = True\n include_reasoning: bool = True\n+ return_tokens_as_token_ids: bool | None = Field(\n+ default=None, exclude_if=lambda value: value is None\n+ )\n chat_template_kwargs: dict[str, JsonValue] = Field(default_factory=dict)\n \"\"\"Template kwargs with the render server's defaults already applied,\n without the API server only entries a handler keeps out of the engine.\"\"\"\ndiff --git a/vllm/entrypoints/scale_out/token_in_token_out/serving.py b/vllm/entrypoints/scale_out/token_in_token_out/serving.py\nindex 1f4af4ad9b83..8a733e069ea6 100644\n--- a/vllm/entrypoints/scale_out/token_in_token_out/serving.py\n+++ b/vllm/entrypoints/scale_out/token_in_token_out/serving.py\n@@ -471,7 +471,7 @@ async def serve_tokens_full_generator(\n sampling_params: SamplingParams = request.sampling_params\n derender_mode = request.output_mode == \"derender\"\n text_mode = request.output_mode == \"text\" or derender_mode\n- tokenizer = self._logprobs_tokenizer(text_mode)\n+ tokenizer = self._logprobs_tokenizer(request, text_mode)\n num_logprobs, top_limit = self._logprob_settings(sampling_params, derender_mode)\n \n try:\n@@ -693,7 +693,7 @@ async def serve_tokens_stream_generator(\n derender_mode = request.output_mode == \"derender\"\n assert derender_mode == (processors is not None)\n text_mode = request.output_mode == \"text\" or derender_mode\n- tokenizer = self._logprobs_tokenizer(text_mode)\n+ tokenizer = self._logprobs_tokenizer(request, text_mode)\n num_logprobs, top_limit = self._logprob_settings(sampling_params, derender_mode)\n response_cls = _STREAM_RESPONSE_CLS[request.output_mode]\n role_sent = [False] * sampling_params.n\n@@ -902,13 +902,16 @@ def _logprob_settings(\n )\n return sampling_params.logprobs, None\n \n- def _logprobs_tokenizer(self, text_mode: bool) -> TokenizerLike | None:\n- \"\"\"Tokenizer that resolves logprob tokens, or None for placeholders.\n-\n- ``--return-tokens-as-token-ids`` keeps placeholders at every level, as\n- it does on ``/v1/completions``.\n- \"\"\"\n- if not text_mode or self.return_tokens_as_token_ids:\n+ def _logprobs_tokenizer(\n+ self, request: GenerateRequest, text_mode: bool\n+ ) -> TokenizerLike | None:\n+ \"\"\"Tokenizer that resolves logprob tokens, or None for placeholders.\"\"\"\n+ return_tokens_as_token_ids = self.return_tokens_as_token_ids\n+ if request.output_mode == \"derender\" and request.parse_context is not None:\n+ override = request.parse_context.return_tokens_as_token_ids\n+ if override is not None:\n+ return_tokens_as_token_ids = override\n+ if not text_mode or return_tokens_as_token_ids:\n return None\n return self.renderer.tokenizer\n \ndiff --git a/vllm/renderers/online_derenderer.py b/vllm/renderers/online_derenderer.py\nindex 2816ffc22db9..e57f432e4212 100644\n--- a/vllm/renderers/online_derenderer.py\n+++ b/vllm/renderers/online_derenderer.py\n@@ -11,6 +11,7 @@\n chat_top_logprobs_limit,\n completion_top_logprobs_limit,\n decode_token_ids,\n+ format_token_id_placeholder,\n )\n from vllm.entrypoints.openai.chat_completion.message_assembly import (\n assemble_chat_message_fields,\n@@ -85,10 +86,12 @@ def __init__(\n default_chat_template_kwargs: dict[str, Any] | None = None,\n reasoning_effort_map: dict[str, str] | None = None,\n log_error_stack: bool = False,\n+ return_tokens_as_token_ids: bool = False,\n ) -> None:\n self.model_config = model_config\n self.renderer = renderer\n self.request_logger = request_logger\n+ self.return_tokens_as_token_ids = return_tokens_as_token_ids\n \n # EOS ids the engine stops on, loaded once like InputProcessor does.\n self._eos_token_id = renderer.get_eos_token_id()\n@@ -200,6 +203,13 @@ def _drop_stop_token(\n return token_ids, stop_reason\n return token_ids[:-1], stop_reason\n \n+ def _return_tokens_as_token_ids(\n+ self, request: ChatCompletionRequest | CompletionRequest | None\n+ ) -> bool:\n+ if request is not None and request.return_tokens_as_token_ids is not None:\n+ return request.return_tokens_as_token_ids\n+ return self.return_tokens_as_token_ids\n+\n def _decode_output(\n self,\n tokenizer: TokenizerLike,\n@@ -303,6 +313,7 @@ def _derender_chat(\n and not hide_metadata\n )\n top_limit = _chat_top_logprobs_limit(chat_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(chat_request)\n \n for choice in generate_response.choices:\n if not choice.token_ids:\n@@ -313,6 +324,7 @@ def _derender_chat(\n choice.logprobs,\n tokenizer,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n if choice.logprobs is not None and not hide_metadata\n else None\n@@ -701,6 +713,7 @@ async def derender_chat_stream(\n \n return_token_ids = chat_request is not None and chat_request.return_token_ids\n top_limit = _chat_top_logprobs_limit(chat_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(chat_request)\n for choice in generate_chunk.choices:\n delta_tids = choice.token_ids or []\n text_tids, stop_reason = self._drop_stop_token(\n@@ -721,6 +734,7 @@ async def derender_chat_stream(\n tokenizer,\n initial_context_token_ids=state.logprob_context_token_ids,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n \n include_role = not updated_state.role_sent\n@@ -804,6 +818,7 @@ def _derender_chat_stream_parsed(\n \"\"\"\n tokenizer = self.renderer.get_tokenizer()\n top_limit = _chat_top_logprobs_limit(chat_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(chat_request)\n \n processor = ChatStreamProcessor(\n chat_request,\n@@ -908,6 +923,7 @@ def _replay(token_ids: list[int], chunk_lens: list[int]) -> None:\n tokenizer,\n initial_context_token_ids=state.logprob_context_token_ids,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n logprob_context = _logprob_context_tail(\n state.logprob_context_token_ids, delta_tids\n@@ -1006,6 +1022,9 @@ def _derender_completion(\n total_completion_tokens = 0\n index = 0\n top_limit = _completion_top_logprobs_limit(completion_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(\n+ completion_request\n+ )\n return_token_ids = (\n completion_request is not None and completion_request.return_token_ids\n )\n@@ -1045,6 +1064,7 @@ def _derender_completion(\n choice.logprobs,\n tokenizer,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n completion_logprobs = _convert_chat_logprobs_to_completion_logprobs(\n resolved, choice.logprobs\n@@ -1126,6 +1146,9 @@ async def derender_completion_stream(\n updated_state = state\n \n top_limit = _completion_top_logprobs_limit(completion_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(\n+ completion_request\n+ )\n return_token_ids = (\n completion_request is not None and completion_request.return_token_ids\n )\n@@ -1149,6 +1172,7 @@ async def derender_completion_stream(\n tokenizer,\n initial_context_token_ids=state.logprob_context_token_ids,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n completion_logprobs = _convert_chat_logprobs_to_completion_logprobs(\n resolved,\n@@ -1414,6 +1438,7 @@ def _resolve_logprobs(\n tokenizer: TokenizerLike,\n initial_context_token_ids: Sequence[int] = (),\n top_limit: int | None = None,\n+ return_tokens_as_token_ids: bool = False,\n ) -> ChatCompletionLogProbs:\n \"\"\"Convert generate's integer-id logprobs to the OpenAI chat shape.\n \n@@ -1440,10 +1465,13 @@ def _resolve_logprobs(\n entry.top_logprobs if top_limit is None else entry.top_logprobs[:top_limit]\n )\n # One batch per position: the sampled id and its kept top-k ids.\n- (token_str, token_bytes), *top_decoded = decode_token_ids(\n- [entry.token_id, *(top.token_id for top in top_entries)],\n- tokenizer,\n+ token_ids = [entry.token_id, *(top.token_id for top in top_entries)]\n+ decoded = (\n+ [(format_token_id_placeholder(tid), None) for tid in token_ids]\n+ if return_tokens_as_token_ids\n+ else decode_token_ids(token_ids, tokenizer)\n )\n+ (token_str, token_bytes), *top_decoded = decoded\n \n if token_str.endswith(\"\\ufffd\"):\n token_str = _correct_decoded_token(\n\n[2 documentation file diff(s) omitted]\ndiff --git a/tests/entrypoints/scale_out/derender/test_derender.py b/tests/entrypoints/scale_out/derender/test_derender.py\nindex c457245d3df4..64bf9c216747 100644\n--- a/tests/entrypoints/scale_out/derender/test_derender.py\n+++ b/tests/entrypoints/scale_out/derender/test_derender.py\n@@ -25,8 +25,9 @@\n \n \n @pytest.fixture(scope=\"module\")\n-def server():\n- with RemoteLaunchRenderServer(MODEL_NAME, []) as remote_server:\n+def server(request):\n+ args = getattr(request, \"param\", [])\n+ with RemoteLaunchRenderServer(MODEL_NAME, args) as remote_server:\n yield remote_server\n \n \n@@ -1970,3 +1971,54 @@ async def test_derender_completion_preserves_requested_token_ids(\n )\n assert choices[0].token_ids == (token_ids if return_token_ids else None)\n assert choices[0].prompt_token_ids == (prompt_ids if return_token_ids else None)\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\n+ (\"server\", \"server_flag\"),\n+ [([], False), ([\"--return-tokens-as-token-ids\"], True)],\n+ indirect=[\"server\"],\n+ scope=\"module\",\n+)\n+@pytest.mark.parametrize(\"endpoint\", [\"chat\", \"completion\"])\n+@pytest.mark.parametrize(\"override\", [None, False, True])\n+async def test_derender_logprob_override(\n+ client, tokenizer, server_flag, endpoint, override\n+):\n+ \"\"\"An explicit false must override a true render-server default.\"\"\"\n+ token_id = tokenizer.convert_tokens_to_ids(\"▁true\")\n+ logprobs = _make_generate_logprobs(token_id)\n+ logprobs[\"content\"][0][\"top_logprobs\"][0][\"token_id\"] = token_id\n+ generated = _make_generate_response(\n+ [token_id], finish_reason=\"length\", logprobs=logprobs\n+ )\n+ original = (\n+ {\"messages\": [], \"logprobs\": True, \"top_logprobs\": 1}\n+ if endpoint == \"chat\"\n+ else {\"prompt\": \"Hi\", \"logprobs\": 1}\n+ )\n+ if override is not None:\n+ original[\"return_tokens_as_token_ids\"] = override\n+ payload = (\n+ {\"chat_request\": original, \"generate_response\": generated}\n+ if endpoint == \"chat\"\n+ else {\"completion_request\": original, \"generate_responses\": [generated]}\n+ )\n+ response = await client.post(\n+ f\"/v1/{'chat/completions' if endpoint == 'chat' else 'completions'}/derender\",\n+ json=payload,\n+ )\n+ response.raise_for_status()\n+ placeholders = server_flag if override is None else override\n+ expected = f\"token_id:{token_id}\" if placeholders else \" true\"\n+ choice = response.json()[\"choices\"][0]\n+ if endpoint == \"chat\":\n+ entry = choice[\"logprobs\"][\"content\"][0]\n+ assert (entry[\"token\"], entry[\"bytes\"]) == (\n+ expected,\n+ None if placeholders else list(b\" true\"),\n+ )\n+ assert entry[\"top_logprobs\"][0][\"token\"] == expected\n+ else:\n+ assert choice[\"logprobs\"][\"tokens\"] == [expected]\n+ assert choice[\"logprobs\"][\"top_logprobs\"] == [{expected: -2.0}]\ndiff --git a/tests/entrypoints/scale_out/derender/test_derender_stream.py b/tests/entrypoints/scale_out/derender/test_derender_stream.py\nindex a002279a9826..893aaa17365e 100644\n--- a/tests/entrypoints/scale_out/derender/test_derender_stream.py\n+++ b/tests/entrypoints/scale_out/derender/test_derender_stream.py\n@@ -2263,8 +2263,9 @@ async def test_too_many_choices_rejected(self):\n \n \n @pytest.fixture(scope=\"module\")\n-def server():\n- with RemoteLaunchRenderServer(MODEL_NAME, []) as remote_server:\n+def server(request):\n+ args = getattr(request, \"param\", [])\n+ with RemoteLaunchRenderServer(MODEL_NAME, args) as remote_server:\n yield remote_server\n \n \n@@ -2833,3 +2834,66 @@ async def test_stream_parsed_missing_prompt_token_ids_rejected(parser_client):\n )\n assert resp.status_code == 400\n assert \"prompt_token_ids\" in resp.json()[\"error\"][\"message\"]\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\n+ (\"endpoint\", \"server\", \"server_flag\"),\n+ [\n+ (endpoint, args, flag)\n+ for endpoint in (\"chat\", \"parsed\", \"completion\")\n+ for flag in (False, True)\n+ for args in [\n+ ([\"--return-tokens-as-token-ids\"] if flag else [])\n+ + (\n+ [\"--tool-call-parser\", \"hermes\", \"--enable-auto-tool-choice\"]\n+ if endpoint == \"parsed\"\n+ else []\n+ )\n+ ]\n+ ],\n+ indirect=[\"server\"],\n+ scope=\"module\",\n+)\n+@pytest.mark.parametrize(\"override\", [None, False, True])\n+async def test_streaming_derender_logprob_override(\n+ client, tokenizer, server_flag, endpoint, override\n+):\n+ \"\"\"Plain/parsed chat and completion chunks honor the request override.\"\"\"\n+ token_id = tokenizer.convert_tokens_to_ids(\"▁true\")\n+ logprobs = _generate_logprobs([token_id])\n+ logprobs[\"content\"][0][\"top_logprobs\"] = [{\"token_id\": token_id, \"logprob\": -0.5}]\n+ chunk = _make_stream_chunk(\n+ [token_id], finish_reason=\"length\", logprobs=logprobs\n+ ).model_dump(mode=\"json\")\n+ chat = endpoint != \"completion\"\n+ original = (\n+ {\"messages\": [], \"logprobs\": True, \"top_logprobs\": 1}\n+ if chat\n+ else {\"prompt\": \"Hi\", \"logprobs\": 1}\n+ )\n+ if override is not None:\n+ original[\"return_tokens_as_token_ids\"] = override\n+ response = await client.post(\n+ f\"/v1/{'chat/completions' if chat else 'completions'}/derender\",\n+ json={\n+ \"stream\": True,\n+ \"prompt_token_ids\": tokenizer.encode(\"Hi\"),\n+ \"generate_chunk\": chunk,\n+ \"chat_request\" if chat else \"completion_request\": original,\n+ },\n+ )\n+ response.raise_for_status()\n+ placeholders = server_flag if override is None else override\n+ expected = f\"token_id:{token_id}\" if placeholders else \" true\"\n+ choice = response.json()[\"chunk\"][\"choices\"][0]\n+ if chat:\n+ entry = choice[\"logprobs\"][\"content\"][0]\n+ assert (entry[\"token\"], entry[\"bytes\"]) == (\n+ expected,\n+ None if placeholders else list(b\" true\"),\n+ )\n+ assert entry[\"top_logprobs\"][0][\"token\"] == expected\n+ else:\n+ assert choice[\"logprobs\"][\"tokens\"] == [expected]\n+ assert choice[\"logprobs\"][\"top_logprobs\"] == [{expected: -0.5}]\ndiff --git a/tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py b/tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py\nindex 47153f4099ad..a889adccffcf 100644\n--- a/tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py\n+++ b/tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py\n@@ -170,3 +170,25 @@ def test_unknown_top_id_does_not_shift_the_other_candidates():\n (\"\", None),\n (\"ok\", list(b\"ok\")),\n ]\n+\n+\n+def test_token_id_placeholders_preserve_sampled_and_top_logprobs():\n+ logprobs = GenerateLogProbs(\n+ content=[\n+ GenerateLogProbsContent(\n+ token_id=SECOND_BYTE,\n+ logprob=-0.5,\n+ top_logprobs=[\n+ GenerateLogProb(token_id=FIRST_BYTE, logprob=-1.5),\n+ ],\n+ )\n+ ]\n+ )\n+ resolved = _resolve_logprobs(\n+ logprobs, _StubTokenizer(), return_tokens_as_token_ids=True\n+ )\n+ entry = resolved.content[0]\n+ assert (entry.token, entry.bytes, entry.logprob) == (\"token_id:11\", None, -0.5)\n+ assert [(top.token, top.bytes, top.logprob) for top in entry.top_logprobs] == [\n+ (\"token_id:10\", None, -1.5)\n+ ]\ndiff --git a/tests/entrypoints/scale_out/render/test_render.py b/tests/entrypoints/scale_out/render/test_render.py\nindex b3be5fa8dc76..1807b0ae73d6 100644\n--- a/tests/entrypoints/scale_out/render/test_render.py\n+++ b/tests/entrypoints/scale_out/render/test_render.py\n@@ -1184,3 +1184,19 @@ async def test_messages_render_tool_search_result_for_deepseek_v41(\n \"<|User|>get_weather\\n\\n\"\n \"notes<|Assistant|>\"\n ) in detokenize.json()[\"prompt\"]\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\"override\", [\"omitted\", None, False, True])\n+async def test_render_omits_null_token_id_override(client, override):\n+ \"\"\"Default requests must not send a new field to older generate nodes.\"\"\"\n+ body = {\"model\": MODEL_NAME, \"messages\": [{\"role\": \"user\", \"content\": \"Hi\"}]}\n+ if override != \"omitted\":\n+ body[\"return_tokens_as_token_ids\"] = override\n+ response = await client.post(\"/v1/chat/completions/render\", json=body)\n+ response.raise_for_status()\n+ context = response.json()[\"parse_context\"]\n+ if override is None or override == \"omitted\":\n+ assert \"return_tokens_as_token_ids\" not in context\n+ else:\n+ assert context[\"return_tokens_as_token_ids\"] is override\ndiff --git a/tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py b/tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py\nindex 4ac47ef11125..98bea6880abd 100644\n--- a/tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py\n+++ b/tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py\n@@ -1590,10 +1590,10 @@ def set_history_tool_call_count(self, count):\n self.history_tool_call_cnt = count\n \n \n-def _derender_serving(engine, parser_cls=_StubParser):\n+def _derender_serving(engine, parser_cls=_StubParser, **kwargs):\n \"\"\"Serving whose derenderer builds real stream processors around\n `parser_cls`, or plain ones when it is None.\"\"\"\n- serving = _build_serving_tokens(engine)\n+ serving = _build_serving_tokens(engine, **kwargs)\n derenderer = serving.online_derenderer\n derenderer.parser = parser_cls\n derenderer.enable_auto_tools = False\n@@ -1878,3 +1878,46 @@ async def mock_generate(*args, **kwargs):\n .delta.content\n == \"a\"\n )\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\"server_flag\", [False, True])\n+@pytest.mark.parametrize(\"override\", [None, False, True])\n+async def test_stream_derender_logprob_request_override(server_flag, override):\n+ engine = _mock_engine()\n+\n+ async def mock_generate(*args, **kwargs):\n+ yield _make_request_output(\n+ \"req-1\",\n+ token_ids=[10],\n+ text=\"é\",\n+ finish_reason=\"length\",\n+ finished=True,\n+ logprobs=[\n+ {\n+ 10: Logprob(logprob=-0.5, decoded_token=\"é\"),\n+ 11: Logprob(logprob=-1.5, decoded_token=\"e\"),\n+ }\n+ ],\n+ )\n+\n+ engine.generate = MagicMock(side_effect=mock_generate)\n+ serving = _derender_serving(engine, return_tokens_as_token_ids=server_flag)\n+ request = _derender_request(ParseContext(return_tokens_as_token_ids=override))\n+ request.sampling_params.logprobs = 2\n+ parsed = await _collect_sse(await serving.serve_tokens(request))\n+\n+ chunk = parsed[0]\n+ assert chunk[\"output_mode\"] == \"derender\"\n+ choice = chunk[\"choices\"][0]\n+ assert choice[\"delta\"][\"content\"] == \"é\"\n+ entry = choice[\"logprobs\"][\"content\"][0]\n+ placeholders = server_flag if override is None else override\n+ assert (entry[\"token\"], entry[\"bytes\"]) == (\n+ (\"token_id:10\", None) if placeholders else (\"é\", [195, 169])\n+ )\n+ assert [(top[\"token\"], top[\"bytes\"]) for top in entry[\"top_logprobs\"]] == (\n+ [(\"token_id:10\", None), (\"token_id:11\", None)]\n+ if placeholders\n+ else [(\"é\", [195, 169]), (\"e\", [101])]\n+ )\ndiff --git a/tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py b/tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py\nindex c236f5f31eff..f4eb15912194 100644\n--- a/tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py\n+++ b/tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py\n@@ -923,3 +923,73 @@ async def test_abort_requests_is_served_without_tokens_only(client):\n \"/abort_requests\", json={\"request_ids\": [\"generate-tokens-unknown\"]}\n )\n assert resp.status_code == 404\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.skipif(\n+ envs.VLLM_USE_RUST_FRONTEND,\n+ reason=\"The Rust frontend does not support /render\",\n+)\n+@pytest.mark.parametrize(\n+ (\"server\", \"server_flag\"),\n+ [\n+ ([\"--gpu-memory-utilization\", \"0.3\"], False),\n+ ([\"--gpu-memory-utilization\", \"0.3\", \"--return-tokens-as-token-ids\"], True),\n+ ],\n+ indirect=[\"server\"],\n+ scope=\"module\",\n+)\n+async def test_derender_logprob_request_override(client, server_flag):\n+ \"\"\"Both derender routes must use the same tri-state override as coupled chat.\"\"\"\n+ for override in (None, False, True):\n+ request = {\n+ \"model\": MODEL_NAME,\n+ \"messages\": [{\"role\": \"user\", \"content\": \"Hi\"}],\n+ \"max_completion_tokens\": 2,\n+ \"temperature\": 0,\n+ \"logprobs\": True,\n+ \"top_logprobs\": 2,\n+ }\n+ if override is not None:\n+ request[\"return_tokens_as_token_ids\"] = override\n+ coupled = await client.post(\"/v1/chat/completions\", json=request)\n+ assert coupled.status_code == 200, coupled.text\n+ expected = coupled.json()[\"choices\"][0][\"logprobs\"]\n+ assert expected and expected[\"content\"]\n+ placeholders = server_flag if override is None else override\n+ if placeholders:\n+ # Both derender paths keep generate text mode's null bytes\n+ # for placeholders; coupled chat currently includes bytes.\n+ # Normalize only that existing representation difference.\n+ for entry in expected[\"content\"]:\n+ entry[\"bytes\"] = None\n+ for top in entry[\"top_logprobs\"]:\n+ top[\"bytes\"] = None\n+ # Separate requests can differ slightly in floating-point logprobs.\n+ # Keep token strings, bytes and the remaining structure exact.\n+ for entry in expected[\"content\"]:\n+ entry[\"logprob\"] = pytest.approx(entry[\"logprob\"], abs=1e-3)\n+ for top in entry[\"top_logprobs\"]:\n+ top[\"logprob\"] = pytest.approx(top[\"logprob\"], abs=1e-3)\n+ rendered = await client.post(\"/v1/chat/completions/render\", json=request)\n+ assert rendered.status_code == 200, rendered.text\n+ payload = rendered.json()\n+ for mode in (\"derender\", \"tokens\"):\n+ generated = await client.post(\n+ \"/inference/v1/generate\", json={**payload, \"output_mode\": mode}\n+ )\n+ assert generated.status_code == 200, generated.text\n+ result = generated.json()\n+ if mode == \"tokens\":\n+ derendered = await client.post(\n+ \"/v1/chat/completions/derender\",\n+ json={\n+ \"model\": MODEL_NAME,\n+ \"chat_request\": request,\n+ \"prompt_token_ids\": payload[\"token_ids\"],\n+ \"generate_response\": result,\n+ },\n+ )\n+ assert derendered.status_code == 200, derendered.text\n+ result = derendered.json()\n+ assert result[\"choices\"][0][\"logprobs\"] == expected\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Kernel] hadacore: fix skipped wait_group on partial-chunk warp for odd row counts (#63514)\nLabels: bug, ready, nvidia\nFiles changed (2): csrc/quantization/hadamard/hadacore/hadamard_transform_cuda.cu, tests/kernels/quantization/test_hadacore.py\n\n## Description (results removed)\n\nFixes #63514\n\n### Problem\nWhen using INT4 per-token-head KV cache (`--kv-cache-dtype int4_per_token_head`), `reshape_and_cache_int4` rotates Key and Value tensors via `hadacore_transform`. \n\nFor `head_dim = 256`, `num_chunks` is 2. When the row count (`num_tokens * num_kv_heads_per_rank`) is odd, the last warp receives only 1 chunk (`real_num_chunks = 1`).\n\n`diff_num_chunks` was calculated as:\n```cpp\nint64_t diff_num_chunks = real_num_chunks - num_chunks; // 1 - 2 = -1\n```\nBecause `diff_num_chunks` was negative, `switch(k + diff_num_chunks)` evaluated to `-1`. Since the switch statement only contains `case 0..31` and had no `default:` fallback, it silently skipped `cp.async.wait_group` completely. \n\nThe warp proceeded to read shared memory before the asynchronous DMA copy completed, causing:\n1. Silent data corruption (relative errors up to 10^36).\n2. Intermittent `CUDA illegal memory access` crashes during prefill.\n\n### Fix\n1. Correct the difference to `num_chunks - real_num_chunks` so `k + diff_num_chunks` maps to the intended wait barrier count (`wait_group 0` for the single tail chunk).\n2. Add `default: asm volatile(\"cp.async.wait_group 0;\\n\"); break;` so an unhandled case can never silently skip synchronization.\n3. Add parameterized unit test in `tests/kernels/quantization/test_hadacore.py` covering odd and large row counts (`num_rows in [1, 17, 53, 65, 165, 173, 257, 513, 1025, 4097, 8193]`).\n\n### Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/csrc/quantization/hadamard/hadacore/hadamard_transform_cuda.cu b/csrc/quantization/hadamard/hadacore/hadamard_transform_cuda.cu\nindex e86c5182048c..fba25ea5631e 100644\n--- a/csrc/quantization/hadamard/hadacore/hadamard_transform_cuda.cu\n+++ b/csrc/quantization/hadamard/hadacore/hadamard_transform_cuda.cu\n@@ -118,7 +118,7 @@ hadamard_transform_kernel(b16* a, b16* out, int total_num_chunks) {\n int64_t threadid = threadIdx.x % 32;\n extern __shared__ b32 bfrag_arr[]; // num_chunks * warps_per_block * 128\n int64_t real_num_chunks = ((blockid + 1) * num_chunks) > total_num_chunks ? (total_num_chunks - (blockid * num_chunks)) : num_chunks;\n- int64_t diff_num_chunks = real_num_chunks - num_chunks;\n+ int64_t diff_num_chunks = num_chunks - real_num_chunks;\n \n b32* a_start_ptr = (b32*) (a + blockid * num_chunks * 256); // offset a to where this warp starts\n b32* out_start_ptr = (b32*) (out + blockid * num_chunks * 256);\n@@ -389,6 +389,9 @@ hadamard_transform_kernel(b16* a, b16* out, int total_num_chunks) {\n SWITCH_WAIT_ASYNC_LOAD_GROUP(29)\n SWITCH_WAIT_ASYNC_LOAD_GROUP(30)\n SWITCH_WAIT_ASYNC_LOAD_GROUP(31)\n+ default:\n+ asm volatile(\"cp.async.wait_group 0;\\n\");\n+ break;\n }\n } else {\n switch(k) {\n@@ -424,6 +427,9 @@ hadamard_transform_kernel(b16* a, b16* out, int total_num_chunks) {\n SWITCH_WAIT_ASYNC_LOAD_GROUP(29)\n SWITCH_WAIT_ASYNC_LOAD_GROUP(30)\n SWITCH_WAIT_ASYNC_LOAD_GROUP(31)\n+ default:\n+ asm volatile(\"cp.async.wait_group 0;\\n\");\n+ break;\n }\n }\n }\ndiff --git a/tests/kernels/quantization/test_hadacore.py b/tests/kernels/quantization/test_hadacore.py\nindex 7a5c7fbd55f7..b995ecffb0a3 100644\n--- a/tests/kernels/quantization/test_hadacore.py\n+++ b/tests/kernels/quantization/test_hadacore.py\n@@ -31,3 +31,23 @@ def test_hadacore(batch_size, hidden_dim, dtype=torch.bfloat16, device=\"cuda\"):\n \n y = ops.hadacore_transform(y)\n assert torch.allclose(y, x)\n+\n+\n+@pytest.mark.parametrize(\n+ \"num_rows\",\n+ [1, 17, 53, 65, 165, 173, 257, 513, 1025, 1041, 1537, 2049, 4097, 8193],\n+)\n+@pytest.mark.parametrize(\"hidden_dim\", [64, 128, 256])\n+def test_hadacore_odd_row_counts(\n+ num_rows, hidden_dim, dtype=torch.bfloat16, device=\"cuda\"\n+):\n+ \"\"\"Verify hadacore_transform handles odd row counts without corruption (#63514).\"\"\"\n+ torch.manual_seed(num_rows)\n+ x = torch.randn(num_rows, hidden_dim, dtype=dtype, device=device)\n+ hadamard = deterministic_hadamard_matrix(\n+ hidden_dim, dtype=torch.float64, device=device\n+ ) / math.sqrt(hidden_dim)\n+\n+ y = ops.hadacore_transform(x.clone(), inplace=True)\n+ y_true = (x.to(hadamard.dtype) @ hadamard.T).to(y.dtype)\n+ torch.testing.assert_close(y, y_true, atol=0.05, rtol=0.02)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Tool Parser] Parse bare FunctionGemma arguments and stream them as valid JSON\nLabels: bug, ready, tool-calling, verified\nFiles changed (3): tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py, tests/tool_parsers/test_functiongemma_tool_parser.py, vllm/tool_parsers/functiongemma_tool_parser.py\n\n## Description (results removed)\n\n## Overview\n\nFix the `functiongemma` tool parser dropping every non-string argument, and make its streamed arguments reassemble into valid JSON. Fixes #63983.\n\n## Claims\n\n- Bare booleans, numbers, `null`, arrays and objects are parsed in streaming and non-streaming, nested containers included.\n- Streamed deltas of a multi-argument call concatenate to one JSON object.\n- A streamed call still gets closed when its end tag shares a delta with the next call's start tag.\n- A streamed call with no arguments sends `{}` instead of an empty string.\n\n## Validation\n[results removed]\n## Details\n\nThe template's `format_argument` macro wraps only strings in ``, e.g. `enabled:true,hour:7,days:[mon],snooze:{minutes:5}`. The old `arg_regex` only matched `key:...`, so bare values were dropped. A small recursive parser for that grammar replaces it. With `partial=True` (streaming) it stops at the first incomplete value, so each value is streamed once in its final form. A bare word that is not a JSON literal stays a string.\n\nStreaming diffs are computed by length against `json.dumps(args)`, so the closing brace is held back until the call ends. That left two gaps, both fixed here. When an end tag and the next start tag arrive together, the start branch returned before closing the earlier call, so it never got its brace, or any arguments if they were still unsent. A call with no arguments streamed nothing because the end branch skipped empty arguments. Both paths now go through `_close_tool_call`. Deltas can merge when the client falls behind the engine or `stream_interval` is above 1.\n\nKnown limitation: from `stream_interval=10` in these runs, a call's name can share a delta with its end tag, and the name is lost. At 64 the second call is lost too. main behaves the same or worse here, so this is left for a follow-up.\n\nRelated PRs:\n\n- #63947 fixes #63906, a separate bug. `` values keep their current decoding here, so `123` is still the integer 123.\n- #48705 fixes the brace issue the same way. It is included here because the streaming tests cannot reassemble a multi-argument call without it. Happy to rebase if #48705 lands first.\n- #64360 targets the same issue and was opened a day after this PR.\n\nAI assistance was used for this change.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/tool_parsers/functiongemma_tool_parser.py b/vllm/tool_parsers/functiongemma_tool_parser.py\nindex 6fcae6e55220..4d809bb42029 100644\n--- a/vllm/tool_parsers/functiongemma_tool_parser.py\n+++ b/vllm/tool_parsers/functiongemma_tool_parser.py\n@@ -25,6 +25,109 @@\n \n logger = init_logger(__name__)\n \n+_ESCAPE = \"\"\n+_BARE_LITERALS = {\"true\": True, \"false\": False, \"null\": None, \"None\": None}\n+\n+\n+class _IncompleteValue(Exception):\n+ \"\"\"The argument text ends before the value does.\"\"\"\n+\n+\n+class _MalformedValue(Exception):\n+ \"\"\"A delimiter appears where a value or key should start.\"\"\"\n+\n+\n+def _skip_whitespace(text: str, pos: int) -> int:\n+ while pos < len(text) and text[pos] in \" \\n\":\n+ pos += 1\n+ return pos\n+\n+\n+def _decode_escaped(raw: str):\n+ try:\n+ return json.loads(raw)\n+ except json.JSONDecodeError:\n+ return raw\n+\n+\n+def _decode_bare(raw: str):\n+ raw = raw.strip()\n+ if raw in _BARE_LITERALS:\n+ return _BARE_LITERALS[raw]\n+ try:\n+ return json.loads(raw)\n+ except json.JSONDecodeError:\n+ return raw\n+\n+\n+def _parse_value(text: str, pos: int, partial: bool) -> tuple[object, int]:\n+ \"\"\"Parse one value at ``pos`` and return it with the position after it.\n+\n+ Raises:\n+ _IncompleteValue: ``text`` ends inside the value. A bare scalar at the\n+ end of a ``partial`` string counts as incomplete, since more digits\n+ or letters may still follow.\n+ _MalformedValue: a delimiter stands where the value should start.\n+\n+ \"\"\"\n+ pos = _skip_whitespace(text, pos)\n+ if text.startswith(_ESCAPE, pos):\n+ start = pos + len(_ESCAPE)\n+ end = text.find(_ESCAPE, start)\n+ if end < 0:\n+ raise _IncompleteValue\n+ return _decode_escaped(text[start:end]), end + len(_ESCAPE)\n+ if text.startswith(\"{\", pos):\n+ return _parse_object(text, pos + 1, partial)\n+ if text.startswith(\"[\", pos):\n+ return _parse_array(text, pos + 1, partial)\n+ end = pos\n+ while end < len(text) and text[end] not in \",}]\":\n+ end += 1\n+ if end == pos:\n+ raise _MalformedValue\n+ if end == len(text) and partial:\n+ raise _IncompleteValue\n+ return _decode_bare(text[pos:end]), end\n+\n+\n+def _parse_object(text: str, pos: int, partial: bool) -> tuple[dict, int]:\n+ obj: dict = {}\n+ while True:\n+ pos = _skip_whitespace(text, pos)\n+ if pos >= len(text):\n+ raise _IncompleteValue\n+ if text[pos] == \"}\":\n+ return obj, pos + 1\n+ if text[pos] == \"]\":\n+ raise _MalformedValue\n+ if text[pos] == \",\":\n+ pos += 1\n+ continue\n+ colon = text.find(\":\", pos)\n+ if colon < 0:\n+ raise _IncompleteValue\n+ key = text[pos:colon].strip()\n+ value, pos = _parse_value(text, colon + 1, partial)\n+ obj[key] = value\n+\n+\n+def _parse_array(text: str, pos: int, partial: bool) -> tuple[list, int]:\n+ items: list = []\n+ while True:\n+ pos = _skip_whitespace(text, pos)\n+ if pos >= len(text):\n+ raise _IncompleteValue\n+ if text[pos] == \"]\":\n+ return items, pos + 1\n+ if text[pos] == \"}\":\n+ raise _MalformedValue\n+ if text[pos] == \",\":\n+ pos += 1\n+ continue\n+ value, pos = _parse_value(text, pos, partial)\n+ items.append(value)\n+\n \n class FunctionGemmaToolParser(ToolParser):\n \"\"\"Tool parser for Google's FunctionGemma model (google/functiongemma-270m-it).\n@@ -43,10 +146,6 @@ class FunctionGemmaToolParser(ToolParser):\n r\"|call:(\\w+)\\{(.*)\",\n re.DOTALL,\n )\n- arg_regex: re.Pattern = re.compile(\n- r\"(\\w+):(.*?)\",\n- re.DOTALL,\n- )\n \n def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n super().__init__(tokenizer, tools)\n@@ -58,20 +157,32 @@ def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n self.streamed_args_for_tool: list[str] = []\n self.buffered_delta_text = \"\"\n \n- def _parse_arguments(self, args_str: str) -> dict:\n- \"\"\"Parse FunctionGemma argument string into a dictionary.\"\"\"\n- arguments: dict = {}\n- if not args_str:\n- return arguments\n+ def _parse_arguments(self, args_str: str, partial: bool = False) -> dict:\n+ \"\"\"Parse a FunctionGemma argument string into a dictionary.\n \n- matches = self.arg_regex.findall(args_str)\n- for key, value in matches:\n+ The chat template writes strings as ``text`` and\n+ everything else bare: ``true``/``false``, numbers, ``[item,...]`` and\n+ ``{key:value,...}`` with bare keys. With ``partial`` the string is a\n+ streaming prefix: parsing stops at the first incomplete value and the\n+ complete arguments before it are returned.\n+ \"\"\"\n+ arguments: dict = {}\n+ pos = 0\n+ while pos < len(args_str):\n+ if args_str[pos] in \", \\n\":\n+ pos += 1\n+ continue\n+ colon = args_str.find(\":\", pos)\n+ if colon < 0:\n+ break\n+ key = args_str[pos:colon].strip()\n+ if not key:\n+ break\n try:\n- parsed_value = json.loads(value)\n- arguments[key] = parsed_value\n- except json.JSONDecodeError:\n- arguments[key] = value\n-\n+ value, pos = _parse_value(args_str, colon + 1, partial)\n+ except (_IncompleteValue, _MalformedValue):\n+ break\n+ arguments[key] = value\n return arguments\n \n def adjust_request(\n@@ -143,6 +254,46 @@ def extract_tool_calls(\n tools_called=False, tool_calls=[], content=model_output\n )\n \n+ def _stream_arguments(self, args: dict, final: bool) -> DeltaMessage | None:\n+ \"\"\"Stream the part of the arguments JSON not sent yet.\n+\n+ Arguments only grow by appended keys, so their JSON is prefix-stable\n+ except for the closing brace, which is held back until ``final``.\n+ \"\"\"\n+ self.prev_tool_call_arr[self.current_tool_id][\"arguments\"] = args\n+ args_json = json.dumps(args, ensure_ascii=False)\n+ if not final:\n+ args_json = args_json[:-1]\n+ prev_streamed = self.streamed_args_for_tool[self.current_tool_id]\n+ if len(args_json) <= len(prev_streamed):\n+ return None\n+ diff = args_json[len(prev_streamed) :]\n+ self.streamed_args_for_tool[self.current_tool_id] = args_json\n+ return DeltaMessage(\n+ tool_calls=[\n+ DeltaToolCall(\n+ index=self.current_tool_id,\n+ function=DeltaFunctionCall(arguments=diff).model_dump(\n+ exclude_none=True\n+ ),\n+ )\n+ ]\n+ )\n+\n+ def _close_tool_call(self, current_text: str) -> DeltaMessage | None:\n+ \"\"\"Stream what is left of the current call, including its closing brace.\"\"\"\n+ if not 0 <= self.current_tool_id < len(self.prev_tool_call_arr):\n+ return None\n+ all_calls = self.tool_call_regex.findall(current_text)\n+ args = {}\n+ if self.current_tool_id < len(all_calls):\n+ match = all_calls[self.current_tool_id]\n+ if match[0]:\n+ args = self._parse_arguments(match[1])\n+ if args or self.current_tool_name_sent:\n+ return self._stream_arguments(args, final=True)\n+ return None\n+\n def _buffer_delta_text(self, delta_text: str) -> str:\n \"\"\"Buffer incoming delta text to handle multi-token special sequences.\"\"\"\n potential_start = \"\"\n@@ -192,12 +343,17 @@ def extract_tool_calls_streaming(\n \n # Starting a new function call\n if start_count > prev_start_count and start_count > end_count:\n+ closing = (\n+ self._close_tool_call(current_text)\n+ if end_count > prev_end_count\n+ else None\n+ )\n self.current_tool_id += 1\n self.current_tool_name_sent = False\n self.streamed_args_for_tool.append(\"\")\n self.prev_tool_call_arr.append({})\n logger.debug(\"Starting new tool call %d\", self.current_tool_id)\n- return None\n+ return closing\n \n # In the middle of a function call\n if start_count > end_count:\n@@ -235,74 +391,17 @@ def extract_tool_calls_streaming(\n )\n \n if self.current_tool_name_sent and args_part:\n- current_args = self._parse_arguments(args_part)\n+ current_args = self._parse_arguments(\n+ args_part, partial=True\n+ )\n if current_args:\n- current_args_json = json.dumps(\n- current_args, ensure_ascii=False\n- )\n- prev_streamed = self.streamed_args_for_tool[\n- self.current_tool_id\n- ]\n-\n- if len(current_args_json) > len(prev_streamed):\n- diff = current_args_json[len(prev_streamed) :]\n- self.streamed_args_for_tool[\n- self.current_tool_id\n- ] = current_args_json\n- self.prev_tool_call_arr[self.current_tool_id][\n- \"arguments\"\n- ] = current_args\n-\n- return DeltaMessage(\n- tool_calls=[\n- DeltaToolCall(\n- index=self.current_tool_id,\n- function=DeltaFunctionCall(\n- arguments=diff\n- ).model_dump(exclude_none=True),\n- )\n- ]\n- )\n+ return self._stream_arguments(current_args, final=False)\n \n return None\n \n # Function call just ended\n if end_count > prev_end_count:\n- if self.current_tool_id >= 0 and self.current_tool_id < len(\n- self.prev_tool_call_arr\n- ):\n- all_calls = self.tool_call_regex.findall(current_text)\n- args = {}\n- if self.current_tool_id < len(all_calls):\n- match = all_calls[self.current_tool_id]\n- if match[0]:\n- args_str = match[1]\n- args = self._parse_arguments(args_str)\n- self.prev_tool_call_arr[self.current_tool_id][\n- \"arguments\"\n- ] = args\n-\n- if args:\n- args_json = json.dumps(args, ensure_ascii=False)\n- prev_streamed = self.streamed_args_for_tool[\n- self.current_tool_id\n- ]\n- if len(args_json) > len(prev_streamed):\n- diff = args_json[len(prev_streamed) :]\n- self.streamed_args_for_tool[self.current_tool_id] = (\n- args_json\n- )\n- return DeltaMessage(\n- tool_calls=[\n- DeltaToolCall(\n- index=self.current_tool_id,\n- function=DeltaFunctionCall(\n- arguments=diff\n- ).model_dump(exclude_none=True),\n- )\n- ]\n- )\n- return None\n+ return self._close_tool_call(current_text)\n \n if delta_text:\n return DeltaMessage(content=delta_text)\n\ndiff --git a/tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py b/tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py\nnew file mode 100644\nindex 000000000000..048ddbbaaea5\n--- /dev/null\n+++ b/tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py\n@@ -0,0 +1,101 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+import json\n+\n+import pytest\n+import regex as re\n+\n+from tests.utils import RemoteOpenAIServer\n+\n+MODEL = \"unsloth/functiongemma-270m-it\"\n+START = \"\"\n+END = \"\"\n+TOOLS = [\n+ {\n+ \"type\": \"function\",\n+ \"function\": {\n+ \"name\": name,\n+ \"description\": name,\n+ \"parameters\": {\"type\": \"object\", \"properties\": {}},\n+ },\n+ }\n+ for name in (\"set_alarm\", \"get_weather\", \"get_time\")\n+]\n+\n+\n+@pytest.fixture(scope=\"module\")\n+def server():\n+ args = [\n+ \"--enforce-eager\",\n+ \"--enable-auto-tool-choice\",\n+ \"--tool-call-parser\",\n+ \"functiongemma\",\n+ \"--max-model-len\",\n+ \"2048\",\n+ \"--max-num-seqs\",\n+ \"2\",\n+ \"--gpu-memory-utilization\",\n+ \"0.05\",\n+ ]\n+ with RemoteOpenAIServer(MODEL, args, max_wait_seconds=480) as server:\n+ yield server\n+\n+\n+def _tool_calls(server, output, stream, stream_interval=None):\n+ \"\"\"Pin the model output with a regex, so only serving and parsing are tested.\"\"\"\n+ extra_body = {\"structured_outputs\": {\"regex\": re.escape(output)}}\n+ if stream_interval is not None:\n+ extra_body[\"stream_interval\"] = stream_interval\n+ with server.get_client() as client:\n+ response = client.chat.completions.create(\n+ model=MODEL,\n+ messages=[{\"role\": \"user\", \"content\": \"Call the tools.\"}],\n+ tools=TOOLS,\n+ tool_choice=\"auto\",\n+ temperature=0,\n+ max_tokens=128,\n+ stream=stream,\n+ extra_body=extra_body,\n+ )\n+ if not stream:\n+ calls = response.choices[0].message.tool_calls or []\n+ return [(c.function.name, json.loads(c.function.arguments)) for c in calls]\n+ streamed: dict[int, dict] = {}\n+ for chunk in response:\n+ for call in chunk.choices[0].delta.tool_calls or []:\n+ entry = streamed.setdefault(call.index, {\"name\": None, \"args\": \"\"})\n+ entry[\"name\"] = entry[\"name\"] or call.function.name\n+ entry[\"args\"] += call.function.arguments or \"\"\n+ return [(e[\"name\"], json.loads(e[\"args\"])) for _, e in sorted(streamed.items())]\n+\n+\n+@pytest.mark.parametrize(\"stream\", [False, True])\n+@pytest.mark.parametrize(\n+ (\"args\", \"expected\"),\n+ [\n+ (\n+ \"days:[mon],enabled:true,hour:7\",\n+ {\"days\": [\"mon\"], \"enabled\": True, \"hour\": 7},\n+ ),\n+ (\"\", {}),\n+ ],\n+ ids=[\"non_string_arguments\", \"no_arguments\"],\n+)\n+def test_arguments_reach_the_client(server, stream, args, expected):\n+ output = f\"{START}call:set_alarm{{{args}}}{END}\"\n+ assert _tool_calls(server, output, stream) == [(\"set_alarm\", expected)]\n+\n+\n+@pytest.mark.parametrize(\"stream_interval\", [2, 3, 4])\n+def test_streamed_call_closes_when_next_call_starts_in_same_delta(\n+ server, stream_interval\n+):\n+ \"\"\"These intervals merge the first call's end tag and the second's start tag.\"\"\"\n+ output = (\n+ f\"{START}call:get_weather{{city:Paris}}{END}\"\n+ f\"{START}call:get_time{{tz:UTC}}{END}\"\n+ )\n+ assert _tool_calls(server, output, True, stream_interval) == [\n+ (\"get_weather\", {\"city\": \"Paris\"}),\n+ (\"get_time\", {\"tz\": \"UTC\"}),\n+ ]\ndiff --git a/tests/tool_parsers/test_functiongemma_tool_parser.py b/tests/tool_parsers/test_functiongemma_tool_parser.py\nindex 10792c16607e..92c6dba9ff86 100644\n--- a/tests/tool_parsers/test_functiongemma_tool_parser.py\n+++ b/tests/tool_parsers/test_functiongemma_tool_parser.py\n@@ -1,9 +1,11 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import json\n from unittest.mock import MagicMock\n \n import pytest\n+import regex as re\n \n from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest\n from vllm.tool_parsers.functiongemma_tool_parser import FunctionGemmaToolParser\n@@ -121,6 +123,171 @@ def test_argument_with_spaces(self, parser):\n assert result == {\"message\": \"Hello World\"}\n \n \n+# Rendered by the model's chat template (``format_argument``): only strings are\n+# ````-delimited; booleans, numbers, arrays and objects are bare.\n+TEMPLATE_CALL = (\n+ \"call:set_alarm{\"\n+ \"days:[mon,tue],enabled:true,hour:7,\"\n+ \"label:Wake up,snooze:{minutes:5}}\"\n+ \"\"\n+)\n+TEMPLATE_ARGS = {\n+ \"days\": [\"mon\", \"tue\"],\n+ \"enabled\": True,\n+ \"hour\": 7,\n+ \"label\": \"Wake up\",\n+ \"snooze\": {\"minutes\": 5},\n+}\n+\n+_START = \"\"\n+_END = \"\"\n+_TAG_RE = re.compile(f\"({_START}|{_END})\")\n+\n+\n+def _chunks(text: str, size: int) -> list[str]:\n+ \"\"\"Split ``text`` into ``size``-character chunks, keeping the tags whole.\n+\n+ The tags are single special tokens, so a delta never splits them.\n+ \"\"\"\n+ chunks = []\n+ for part in _TAG_RE.split(text):\n+ if _TAG_RE.fullmatch(part):\n+ chunks.append(part)\n+ else:\n+ chunks.extend(part[i : i + size] for i in range(0, len(part), size))\n+ return [chunk for chunk in chunks if chunk]\n+\n+\n+def _stream(parser, request, text: str, size: int) -> list[tuple[str, dict]]:\n+ return _stream_deltas(parser, request, _chunks(text, size))\n+\n+\n+def _stream_deltas(parser, request, deltas: list[str]) -> list[tuple[str, dict]]:\n+ \"\"\"Reassemble streamed tool calls as a client would: by index.\"\"\"\n+ previous = \"\"\n+ calls: dict[int, dict] = {}\n+ for i, chunk in enumerate(deltas, start=1):\n+ current = previous + chunk\n+ delta = parser.extract_tool_calls_streaming(\n+ previous, current, chunk, [], [i], [i], request\n+ )\n+ previous = current\n+ for call in (delta.tool_calls if delta else None) or []:\n+ entry = calls.setdefault(call.index, {\"name\": None, \"arguments\": \"\"})\n+ if call.function.name:\n+ entry[\"name\"] = call.function.name\n+ entry[\"arguments\"] += call.function.arguments or \"\"\n+ return [\n+ (entry[\"name\"], json.loads(entry[\"arguments\"]))\n+ for _, entry in sorted(calls.items())\n+ ]\n+\n+\n+class TestTemplateArgumentTypes:\n+ \"\"\"Regression tests for #63983: bare (non-string) arguments were dropped.\"\"\"\n+\n+ def test_non_streaming_keeps_every_argument(self, parser, mock_request):\n+ result = parser.extract_tool_calls(TEMPLATE_CALL, mock_request)\n+\n+ assert result.tools_called is True\n+ assert json.loads(result.tool_calls[0].function.arguments) == TEMPLATE_ARGS\n+\n+ @pytest.mark.parametrize(\"size\", [1, 3, 1000])\n+ def test_streaming_keeps_every_argument(self, parser, mock_request, size):\n+ assert _stream(parser, mock_request, TEMPLATE_CALL, size) == [\n+ (\"set_alarm\", TEMPLATE_ARGS)\n+ ]\n+\n+ @pytest.mark.parametrize(\"size\", [1, 1000])\n+ def test_streaming_multiple_arguments_reassemble_to_json(\n+ self, parser, mock_request, size\n+ ):\n+ \"\"\"The closing brace is held back until the call ends, so the\n+ concatenated deltas of a multi-argument call form one JSON object.\"\"\"\n+ text = (\n+ \"call:get_weather{\"\n+ \"location:San Francisco,unit:celsius}\"\n+ \"\"\n+ \"call:set_alarm{hour:7,snooze:{minutes:5}}\"\n+ \"\"\n+ )\n+ assert _stream(parser, mock_request, text, size) == [\n+ (\"get_weather\", {\"location\": \"San Francisco\", \"unit\": \"celsius\"}),\n+ (\"set_alarm\", {\"hour\": 7, \"snooze\": {\"minutes\": 5}}),\n+ ]\n+\n+ @pytest.mark.parametrize(\n+ \"first_call_deltas\",\n+ [\n+ [\"city:Paris\", \"}\", _END + _START],\n+ [\"city:Paris\", \"}\" + _END + _START],\n+ [\"city:Paris}\" + _END + _START],\n+ ],\n+ )\n+ def test_streaming_closes_call_when_next_starts_in_same_delta(\n+ self, parser, mock_request, first_call_deltas\n+ ):\n+ \"\"\"Deltas merge when the client falls behind the engine, so one call's\n+ end tag can share a delta with the next call's start tag.\"\"\"\n+ deltas = [\n+ _START,\n+ \"call:get_weather{\",\n+ *first_call_deltas,\n+ \"call:get_time{\",\n+ \"tz:UTC\",\n+ \"}\",\n+ _END,\n+ ]\n+ assert _stream_deltas(parser, mock_request, deltas) == [\n+ (\"get_weather\", {\"city\": \"Paris\"}),\n+ (\"get_time\", {\"tz\": \"UTC\"}),\n+ ]\n+\n+ @pytest.mark.parametrize(\"size\", [1, 1000])\n+ def test_streaming_call_without_arguments_sends_empty_object(\n+ self, parser, mock_request, size\n+ ):\n+ text = f\"{_START}call:get_time{{}}{_END}\"\n+ assert _stream(parser, mock_request, text, size) == [(\"get_time\", {})]\n+\n+ def test_escaped_strings_keep_delimiters(self, parser):\n+ args = \"note:a, b: {c} [d],count:2\"\n+ assert parser._parse_arguments(args) == {\"note\": \"a, b: {c} [d]\", \"count\": 2}\n+\n+ def test_nested_containers_and_literals(self, parser):\n+ args = \"cfg:{on:false,ids:[1,[2,3],{k:v}],none:None},f:1.5\"\n+ assert parser._parse_arguments(args) == {\n+ \"cfg\": {\"on\": False, \"ids\": [1, [2, 3], {\"k\": \"v\"}], \"none\": None},\n+ \"f\": 1.5,\n+ }\n+\n+ @pytest.mark.parametrize(\n+ (\"prefix\", \"expected\"),\n+ [\n+ (\"hour:7\", {}),\n+ (\"hour:7,\", {\"hour\": 7}),\n+ (\"hour:7,label:Wake\", {\"hour\": 7}),\n+ (\"hour:7,days:[mon\", {\"hour\": 7}),\n+ (\"hour:7,snooze:{minutes:5\", {\"hour\": 7}),\n+ (\"hour:7,snooze:{minutes:5}\", {\"hour\": 7, \"snooze\": {\"minutes\": 5}}),\n+ ],\n+ )\n+ def test_partial_parsing_holds_back_incomplete_values(\n+ self, parser, prefix, expected\n+ ):\n+ assert parser._parse_arguments(prefix, partial=True) == expected\n+\n+ @pytest.mark.parametrize(\n+ \"args\",\n+ [\"a:1,items:[1}\", \"a:1,cfg:{x:1]\", \"a:1,b:,c:2\", \"a:1,b:}\"],\n+ )\n+ @pytest.mark.parametrize(\"partial\", [False, True])\n+ def test_mismatched_delimiters_stop_parsing(self, parser, args, partial):\n+ \"\"\"A stray closing brace must not spin the parser; the arguments\n+ parsed before it are kept and the rest is dropped.\"\"\"\n+ assert parser._parse_arguments(args, partial=partial) == {\"a\": 1}\n+\n+\n class TestAdjustRequest:\n def test_skip_special_tokens_disabled(self, parser, mock_request):\n mock_request.tools = [{\"type\": \"function\", \"function\": {\"name\": \"test\"}}]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Frontend] fix Anthropic inline-system probe crashing startup\nLabels: bug, frontend, ready, verified\nFiles changed (2): tests/entrypoints/anthropic/test_anthropic_messages_conversion.py, vllm/entrypoints/anthropic/serving.py\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n\n- `vllm serve allenai/Olmo-3-7B-Instruct` now starts. Before this change, it stopped with `TypeError: Object of type Undefined is not JSON serializable`.\n- OLMo 3 is correctly detected as accepting non-leading system messages, so inline system messages are **not** merged into the leading system prompt, and the prefix cache keeps working.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause:** `AnthropicServingMessages.__init__` calls `_should_merge_inline_system`, which calls `_detect_merge_inline_system`. That function renders the chat template with a `[system, user, system, user]` conversation to find out whether the template accepts non-leading system messages. Since #58727, this check renders the model's own template.\n\n**Fix:**\n\n**Tradeoff:** catching `Exception` alone would also stop the crash. But for OLMo 3 it would wrongly decide that merging is needed, which moves inline system messages into the leading system prompt and breaks prefix caching. That's why (1) is included and not only (2).\n\n**Not a duplicate:** I searched open PRs for `61919` and for `merge_inline_system`. None address this crash. The related open PRs #63368 (fold inline system messages in place) and #53501 (preserve prefix cache for inline system turns) change different behavior.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/anthropic/serving.py b/vllm/entrypoints/anthropic/serving.py\nindex e1b362ab4136..6d653616b148 100644\n--- a/vllm/entrypoints/anthropic/serving.py\n+++ b/vllm/entrypoints/anthropic/serving.py\n@@ -324,7 +324,9 @@ def _detect_merge_inline_system(chat_template: str | None) -> bool:\n add_generation_prompt=False,\n )\n return False\n- except jinja2.TemplateError:\n+ except Exception:\n+ # Non-TemplateError failures (e.g. TypeError from filters on\n+ # undefined variables) must not abort server startup.\n return True\n \n @staticmethod\n\ndiff --git a/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py b/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py\nindex aa50a16b2365..0525272576dc 100644\n--- a/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py\n+++ b/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py\n@@ -1454,6 +1454,27 @@ def test_no_template_defaults_merge(self):\n \"\"\"No chat_template → conservative default: merge.\"\"\"\n assert AnthropicServingMessages._detect_merge_inline_system(None) is True\n \n+ def test_tools_none_check_template_merges(self):\n+ \"\"\"OLMo 3-style ``tools | tojson`` on undefined tools falls back to merge.\"\"\"\n+ template = (\n+ \"{% if tools is none %}{% else %}{{ tools | tojson }}{% endif %}\"\n+ \"{% for m in messages %}{{ m.content }}{% endfor %}\"\n+ )\n+ assert AnthropicServingMessages._detect_merge_inline_system(template) is True\n+\n+ def test_tools_loop_template_no_merge(self):\n+ \"\"\"Hermes-style ``for tool in tools`` must not raise in the probe.\"\"\"\n+ template = (\n+ \"{% for tool in tools %}{{ tool | tojson }}{% endfor %}\"\n+ \"{% for m in messages %}{{ m.content }}{% endfor %}\"\n+ )\n+ assert AnthropicServingMessages._detect_merge_inline_system(template) is False\n+\n+ def test_non_template_error_defaults_merge(self):\n+ \"\"\"A non-TemplateError render failure must not abort startup.\"\"\"\n+ template = \"{{ undefined_var | tojson }}\"\n+ assert AnthropicServingMessages._detect_merge_inline_system(template) is True\n+\n @pytest.mark.parametrize(\n (\"resolved\", \"expected\"),\n [(PERMISSIVE_TEMPLATE, False), (Q35_TEMPLATE, True)],\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fix DFlash draft acceptance of 0 with FULL CUDA graphs\nLabels: bug, speculative-decoding, ready, nvidia, mrv2, dflash\nFiles changed (4): tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py, vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py, vllm/v1/worker/gpu/spec_decode/dflash/speculator.py, vllm/v1/worker/gpu/spec_decode/speculator.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #63587. With the default `FULL_AND_PIECEWISE` CUDA graphs, the DFlash draft reads a stale kernel block table, so none of its tokens are accepted. This PR maps the draft kernel block tables before the FULL graph replay, the same way `TargetDependentARSpeculator` already does (#57169).\n\n## Claims\n\n- DFlash-family drafts work again under FULL draft CUDA graphs when the KV cache block is split into smaller kernel blocks. Tested with hybrid `Qwen/Qwen3.5-4B` and a DFlash2 draft on B200: acceptance goes from 0.0000 to about 0.185, the same as the PIECEWISE control (0.1863).\n- The code change is 8 lines in `vllm/v1/worker/gpu/spec_decode/dflash/speculator.py`.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause.** Qwen3.5 is a hybrid model (attention plus GDN layers). To make the attention page match the mamba page, the KV cache manager uses 640-token blocks. The draft's FlashAttention 4 backend uses 128-token kernel blocks. So the draft attention group reads its block table from the persistent `AttentionGroup.kernel_block_table` buffer (`vllm/v1/worker/utils.py`), and the captured FULL graph reads that buffer. Only `map_to_kernel_block_table` fills it, and only the eager metadata build calls that (`_with_kernel_block_table`).\n\nSince #60692, `DFlashSpeculator.propose` skips `_build_uniform_attn_metadata` when it replays a FULL graph and every draft backend supports `update_draft_decode_metadata`. The in-graph `_update_draft_decode_metadata` only asks each builder to refresh its own data. It does not map the block table. So after capture, the buffer keeps the rows from the dummy all-zero block table: kernel pages 0..4, which belong to the null block. On every replay the draft reads the null block's K/V instead of the request's. The drafts are unrelated to the context, and the target rejects all of them. The output stays correct because the target checks every token.\n\nA debug print before `run_fullgraph` (not part of this PR) confirmed this. Request 0 owned manager block 83, so its kernel row should be `[415, 416, 417, 418, 419]`, but the buffer held `[0, 1, 2, 3, 4]`. With the fix, it held `[415, 416, 417, 418, 419]`.\n\n**Other FULL draft replays checked.** `TargetDependentARSpeculator` (MTP, EAGLE, Gemma4) already maps the table before its fused FULL replay. `MultiModuleMTPSpeculator` builds the metadata before `run_fullgraph`. `StandaloneARSpeculator` does not use FULL replay.\n\n**Not chosen.** Mapping inside `_update_draft_decode_metadata` would also map again on every `TargetDependentAR` step, which already maps. Reporting `supports_decode_metadata_update = False` for split groups would turn #60692 off for these models.\n\n**Limitations and notes for reviewers.**\n\n- The issue does not name its checkpoints (a 9B FP8 target and an NVFP4 target, served through Dynamo). I validated with the 4B BF16 pair above and plain `vllm serve`. The issue saw acceptance of 0.004 and 0.0005; here it was exactly 0. The issue's `no KV cache group could be identified as the draft model's` warning did not appear here, and I did not look into it.\n- The test row uses a community draft checkpoint, `nchapman/Qwen3.5-4B-DFlash2`, the one used in the issue thread. If CI should use only official checkpoints, the row can point at another hybrid target/draft pair with the same block split.\n- CI: the row id contains `dflash2`, so the nightly `spec-decode-dflash2-nightly-b200` step (`-k \"dflash2\"`) selects it. `-k dflash2` also selects it in non-B200 steps (H100, MI355), and the thresholds were measured only on B200.\n\n---\n\n
\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py b/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py\nindex 9875d90120db..24df7aac111d 100644\n--- a/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py\n+++ b/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py\n@@ -273,11 +273,7 @@ def _fused_multi_step_decode(\n num_speculative_steps: int,\n ) -> None:\n if batch_desc.cg_mode == CUDAGraphMode.FULL:\n- for groups in self.attn_groups:\n- for group in groups:\n- group.map_to_kernel_block_table(\n- self.block_tables.input_block_tables[group.kv_cache_group_id]\n- )\n+ self._map_kernel_block_tables()\n assert self.decode_cudagraph_manager is not None\n self.decode_cudagraph_manager.run_fullgraph(batch_desc)\n return\ndiff --git a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py\nindex 8b369280abfb..87e88ed49e4d 100644\n--- a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py\n+++ b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py\n@@ -614,6 +614,8 @@ def propose(\n step=self.num_query_per_req,\n causal=self._group_causal,\n )\n+ else:\n+ self._map_kernel_block_tables()\n \n # DFlash processes all speculative tokens in one forward pass,\n # so the real token count is num_query_tokens.\ndiff --git a/vllm/v1/worker/gpu/spec_decode/speculator.py b/vllm/v1/worker/gpu/spec_decode/speculator.py\nindex ca1fe53ca494..3040e3306def 100644\n--- a/vllm/v1/worker/gpu/spec_decode/speculator.py\n+++ b/vllm/v1/worker/gpu/spec_decode/speculator.py\n@@ -749,3 +749,11 @@ def _update_draft_decode_metadata(\n for groups in self.attn_groups:\n for group in groups:\n group.update_draft_decode_metadata(attn_metadata)\n+\n+ def _map_kernel_block_tables(self) -> None:\n+ \"\"\"Refresh the persistent kernel block tables a FULL graph reads.\"\"\"\n+ for groups in self.attn_groups:\n+ for group in groups:\n+ group.map_to_kernel_block_table(\n+ self.block_tables.input_block_tables[group.kv_cache_group_id]\n+ )\n\ndiff --git a/tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py b/tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py\nindex 0dff04333602..38642a4fdba5 100644\n--- a/tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py\n+++ b/tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py\n@@ -49,6 +49,18 @@ class DFlashCorrectnessConfig:\n chat_template_kwargs={\"enable_thinking\": False},\n )\n \n+QWEN3_5_4B_DFLASH2 = DFlashCorrectnessConfig(\n+ model=\"Qwen/Qwen3.5-4B\",\n+ draft_model=\"nchapman/Qwen3.5-4B-DFlash2\",\n+ expected_accuracy=0.8,\n+ expected_acceptance_len=4.55 * 0.9,\n+ num_speculative_tokens=15,\n+ max_num_seqs=32,\n+ use_chat_completions=True,\n+ language_model_only=True,\n+ chat_template_kwargs={\"enable_thinking\": False},\n+)\n+\n LAGUNA_DFLASH_NVFP4 = DFlashCorrectnessConfig(\n model=\"poolside/Laguna-XS-2.1-NVFP4\",\n draft_model=\"poolside/Laguna-XS-2.1-DFlash-NVFP4\",\n@@ -123,6 +135,11 @@ def test_dflash_reference_acceptance_lengths(\n True,\n id=\"qwen3.8-dflash2-nvfp4-mrv2\",\n ),\n+ pytest.param(\n+ QWEN3_5_4B_DFLASH2,\n+ True,\n+ id=\"qwen3.5-4b-dflash2-mrv2\",\n+ ),\n ],\n )\n def test_dflash_correctness(\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fix DFlash draft acceptance of 0 with FULL CUDA graphs\nLabels: bug, speculative-decoding, ready, nvidia, mrv2, dflash\nFiles changed (4): tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py, vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py, vllm/v1/worker/gpu/spec_decode/dflash/speculator.py, vllm/v1/worker/gpu/spec_decode/speculator.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #63587. With the default `FULL_AND_PIECEWISE` CUDA graphs, the DFlash draft reads a stale kernel block table, so none of its tokens are accepted. This PR maps the draft kernel block tables before the FULL graph replay, the same way `TargetDependentARSpeculator` already does (#57169).\n\n## Claims\n\n- DFlash-family drafts work again under FULL draft CUDA graphs when the KV cache block is split into smaller kernel blocks. Tested with hybrid `Qwen/Qwen3.5-4B` and a DFlash2 draft on B200: acceptance goes from 0.0000 to about 0.185, the same as the PIECEWISE control (0.1863).\n- The code change is 8 lines in `vllm/v1/worker/gpu/spec_decode/dflash/speculator.py`.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause.** Qwen3.5 is a hybrid model (attention plus GDN layers). To make the attention page match the mamba page, the KV cache manager uses 640-token blocks. The draft's FlashAttention 4 backend uses 128-token kernel blocks. So the draft attention group reads its block table from the persistent `AttentionGroup.kernel_block_table` buffer (`vllm/v1/worker/utils.py`), and the captured FULL graph reads that buffer. Only `map_to_kernel_block_table` fills it, and only the eager metadata build calls that (`_with_kernel_block_table`).\n\nSince #60692, `DFlashSpeculator.propose` skips `_build_uniform_attn_metadata` when it replays a FULL graph and every draft backend supports `update_draft_decode_metadata`. The in-graph `_update_draft_decode_metadata` only asks each builder to refresh its own data. It does not map the block table. So after capture, the buffer keeps the rows from the dummy all-zero block table: kernel pages 0..4, which belong to the null block. On every replay the draft reads the null block's K/V instead of the request's. The drafts are unrelated to the context, and the target rejects all of them. The output stays correct because the target checks every token.\n\nA debug print before `run_fullgraph` (not part of this PR) confirmed this. Request 0 owned manager block 83, so its kernel row should be `[415, 416, 417, 418, 419]`, but the buffer held `[0, 1, 2, 3, 4]`. With the fix, it held `[415, 416, 417, 418, 419]`.\n\n**Other FULL draft replays checked.** `TargetDependentARSpeculator` (MTP, EAGLE, Gemma4) already maps the table before its fused FULL replay. `MultiModuleMTPSpeculator` builds the metadata before `run_fullgraph`. `StandaloneARSpeculator` does not use FULL replay.\n\n**Not chosen.** Mapping inside `_update_draft_decode_metadata` would also map again on every `TargetDependentAR` step, which already maps. Reporting `supports_decode_metadata_update = False` for split groups would turn #60692 off for these models.\n\n**Limitations and notes for reviewers.**\n\n- The issue does not name its checkpoints (a 9B FP8 target and an NVFP4 target, served through Dynamo). I validated with the 4B BF16 pair above and plain `vllm serve`. The issue saw acceptance of 0.004 and 0.0005; here it was exactly 0. The issue's `no KV cache group could be identified as the draft model's` warning did not appear here, and I did not look into it.\n- The test row uses a community draft checkpoint, `nchapman/Qwen3.5-4B-DFlash2`, the one used in the issue thread. If CI should use only official checkpoints, the row can point at another hybrid target/draft pair with the same block split.\n- CI: the row id contains `dflash2`, so the nightly `spec-decode-dflash2-nightly-b200` step (`-k \"dflash2\"`) selects it. `-k dflash2` also selects it in non-B200 steps (H100, MI355), and the thresholds were measured only on B200.\n\n---\n\n
\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py\nindex 8b369280abfb..87e88ed49e4d 100644\n--- a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py\n+++ b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py\n@@ -614,6 +614,8 @@ def propose(\n step=self.num_query_per_req,\n causal=self._group_causal,\n )\n+ else:\n+ self._map_kernel_block_tables()\n \n # DFlash processes all speculative tokens in one forward pass,\n # so the real token count is num_query_tokens.\ndiff --git a/vllm/v1/worker/gpu/spec_decode/speculator.py b/vllm/v1/worker/gpu/spec_decode/speculator.py\nindex bc907d59fe2f..8dc35bf1e9f2 100644\n--- a/vllm/v1/worker/gpu/spec_decode/speculator.py\n+++ b/vllm/v1/worker/gpu/spec_decode/speculator.py\n@@ -751,3 +751,11 @@ def _update_draft_decode_metadata(\n for groups in self.attn_groups:\n for group in groups:\n group.update_draft_decode_metadata(attn_metadata)\n+\n+ def _map_kernel_block_tables(self) -> None:\n+ \"\"\"Refresh the persistent kernel block tables a FULL graph reads.\"\"\"\n+ for groups in self.attn_groups:\n+ for group in groups:\n+ group.map_to_kernel_block_table(\n+ self.block_tables.input_block_tables[group.kv_cache_group_id]\n+ )\ndiff --git a/vllm/v1/worker/gpu/spec_decode/target_dependent_ar/speculator.py b/vllm/v1/worker/gpu/spec_decode/target_dependent_ar/speculator.py\nindex 8b4ca9fc9e59..75b7062e0310 100644\n--- a/vllm/v1/worker/gpu/spec_decode/target_dependent_ar/speculator.py\n+++ b/vllm/v1/worker/gpu/spec_decode/target_dependent_ar/speculator.py\n@@ -578,11 +578,7 @@ def _fused_multi_step_decode(\n idx_mapping = self.idx_mapping[:num_reqs]\n \n if batch_desc.cg_mode == CUDAGraphMode.FULL:\n- for groups in self.attn_groups:\n- for group in groups:\n- group.map_to_kernel_block_table(\n- self.block_tables.input_block_tables[group.kv_cache_group_id]\n- )\n+ self._map_kernel_block_tables()\n assert self.decode_cudagraph_manager is not None\n self.decode_cudagraph_manager.run_fullgraph(batch_desc)\n return\n\ndiff --git a/tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py b/tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py\nindex 0dff04333602..38642a4fdba5 100644\n--- a/tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py\n+++ b/tests/v1/e2e/spec_decode/acceptance_rates/dflash/test_dflash.py\n@@ -49,6 +49,18 @@ class DFlashCorrectnessConfig:\n chat_template_kwargs={\"enable_thinking\": False},\n )\n \n+QWEN3_5_4B_DFLASH2 = DFlashCorrectnessConfig(\n+ model=\"Qwen/Qwen3.5-4B\",\n+ draft_model=\"nchapman/Qwen3.5-4B-DFlash2\",\n+ expected_accuracy=0.8,\n+ expected_acceptance_len=4.55 * 0.9,\n+ num_speculative_tokens=15,\n+ max_num_seqs=32,\n+ use_chat_completions=True,\n+ language_model_only=True,\n+ chat_template_kwargs={\"enable_thinking\": False},\n+)\n+\n LAGUNA_DFLASH_NVFP4 = DFlashCorrectnessConfig(\n model=\"poolside/Laguna-XS-2.1-NVFP4\",\n draft_model=\"poolside/Laguna-XS-2.1-DFlash-NVFP4\",\n@@ -123,6 +135,11 @@ def test_dflash_reference_acceptance_lengths(\n True,\n id=\"qwen3.8-dflash2-nvfp4-mrv2\",\n ),\n+ pytest.param(\n+ QWEN3_5_4B_DFLASH2,\n+ True,\n+ id=\"qwen3.5-4b-dflash2-mrv2\",\n+ ),\n ],\n )\n def test_dflash_correctness(\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Multimodal] Fix DeepSeek-OCR zero-sum patch guard in _encode…\nLabels: bug, ready, multi-modality, deepseek\nFiles changed (3): tests/models/multimodal/generation/test_deepseek_ocr.py, vllm/model_executor/models/deepseek_ocr.py, vllm/model_executor/models/deepseek_ocr2.py\n\n## Description (results removed)\n\nFixes #64075.\n\n_encode_local_features in deepseek_ocr.py and deepseek_ocr2.py used torch.sum(patches).item() == 0 to detect \"no crop patches\", so a tiled image whose normalized pixels cancel to zero (e.g. half-white/half-black 1536x768) wrongly returned None, dropped local features, and crashed EngineCore with a placeholder/embedding shape mismatch. Replace the guard with patches.numel() == 0; #59417 fixed the equivalent check in _parse_and_validate_image_input but left this one as \"not engine-fatal\", which #64075 disproves.\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/deepseek_ocr.py b/vllm/model_executor/models/deepseek_ocr.py\nindex 3aef695d0608..d137030a337a 100644\n--- a/vllm/model_executor/models/deepseek_ocr.py\n+++ b/vllm/model_executor/models/deepseek_ocr.py\n@@ -499,7 +499,7 @@ def _encode_global_features(self, image_tensor: torch.Tensor) -> torch.Tensor:\n def _encode_local_features(\n self, patches: torch.Tensor, crop_shape: torch.Tensor\n ) -> torch.Tensor | None:\n- if torch.sum(patches).item() == 0:\n+ if patches.numel() == 0:\n return None\n \n local_features_1 = self.sam_model(patches)\ndiff --git a/vllm/model_executor/models/deepseek_ocr2.py b/vllm/model_executor/models/deepseek_ocr2.py\nindex 18de7503c721..9139259909e6 100644\n--- a/vllm/model_executor/models/deepseek_ocr2.py\n+++ b/vllm/model_executor/models/deepseek_ocr2.py\n@@ -343,7 +343,7 @@ def _encode_global_features(self, image_tensor: torch.Tensor) -> torch.Tensor:\n return features.view(-1, dim)\n \n def _encode_local_features(self, patches: torch.Tensor) -> torch.Tensor | None:\n- if torch.sum(patches).item() == 0:\n+ if patches.numel() == 0:\n return None\n \n local_features = self.sam_model(patches)\n\ndiff --git a/tests/models/multimodal/generation/test_deepseek_ocr.py b/tests/models/multimodal/generation/test_deepseek_ocr.py\nnew file mode 100644\nindex 000000000000..6dc9ea52434f\n--- /dev/null\n+++ b/tests/models/multimodal/generation/test_deepseek_ocr.py\n@@ -0,0 +1,58 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+\"\"\"Guard tests for DeepSeek-OCR _encode_local_features.\n+\n+_encode_local_features must skip processing only for an empty-element\n+patches tensor, not for a zero-sum one.\n+\n+Regression for #64075: the old guard ``torch.sum(patches).item() == 0``\n+returned None for a 1536x768 half-white/half-black image whose two\n+normalised crop patches cancel to sum==0, causing a shape mismatch in\n+_merge_multimodal_embeddings and a fatal EngineCore crash.\n+\n+The correct guard is ``patches.numel() == 0``.\n+\"\"\"\n+\n+import pytest\n+import torch\n+\n+from vllm.model_executor.models.deepseek_ocr import DeepseekOCRForCausalLM\n+from vllm.model_executor.models.deepseek_ocr2 import DeepseekOCR2ForCausalLM\n+\n+\n+class TestDeepseekOCREncodeLocalFeaturesGuard:\n+ def test_ocr2_empty_patches_returns_none(self):\n+ \"\"\"Zero-element tensor → skip local encoding (non-tiled image).\"\"\"\n+ empty = torch.empty(0, 3, 224, 224)\n+ assert DeepseekOCR2ForCausalLM._encode_local_features(None, empty) is None\n+\n+ def test_ocr2_zero_sum_patches_enters_model_body(self):\n+ \"\"\"Non-empty patches that happen to sum to zero must NOT return None.\n+\n+ The method will raise AttributeError when it tries to call\n+ self.sam_model on a None self – that is the expected outcome here\n+ because it proves the guard was passed, not that encoding succeeded.\n+ The real crash was a shape-mismatch ValueError that killed EngineCore.\n+ \"\"\"\n+ # Two patches that cancel: white (1.0) + black (-1.0) after Normalize.\n+ wb = torch.cat([torch.ones(1, 3, 4, 4), -torch.ones(1, 3, 4, 4)])\n+ assert wb.numel() > 0\n+ assert wb.sum().item() == 0.0\n+ with pytest.raises(AttributeError):\n+ DeepseekOCR2ForCausalLM._encode_local_features(None, wb)\n+\n+ def test_ocr1_empty_patches_returns_none(self):\n+ \"\"\"OCR-1: zero-element tensor → skip local encoding.\"\"\"\n+ empty = torch.empty(0, 3, 224, 224)\n+ crop_shape = torch.tensor([0, 0])\n+ assert (\n+ DeepseekOCRForCausalLM._encode_local_features(None, empty, crop_shape)\n+ is None\n+ )\n+\n+ def test_ocr1_zero_sum_patches_enters_model_body(self):\n+ \"\"\"OCR-1: non-empty zero-sum patches must pass the guard.\"\"\"\n+ wb = torch.cat([torch.ones(1, 3, 4, 4), -torch.ones(1, 3, 4, 4)])\n+ crop_shape = torch.tensor([1, 2])\n+ with pytest.raises(AttributeError):\n+ DeepseekOCRForCausalLM._encode_local_features(None, wb, crop_shape)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fix Gemma 4 vision crash with online FP8 quantization\nLabels: bug, ready, ci/build, multi-modality, nvidia, quantization\nFiles changed (2): tests/models/multimodal/processing/test_gemma4.py, vllm/model_executor/models/gemma4_mm.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #63732. With `--quantization fp8`, an image request to Gemma 4 returns HTTP 500 and kills the engine core. The transformers patch embedder casts the pixel values to `input_proj.weight.dtype`. Once vLLM quantizes that layer, this dtype is `float8_e4m3fn`, so the FP8 linear gets an FP8 input. This PR runs the patch embedder steps in `gemma4_mm.py` with the pixel values cast to `self.model_dtype`. It makes the same change for the pooled states before `embedding_projection` in the encoder CUDA graph path.\n\nCompared with #63911, this fix:\n\n- Also fixes `DiffusionGemmaForConditionalGeneration` and `EmbeddingGemma2Model`. They borrow Gemma 4's `_process_image_input` and `_process_video_input` and build their own FP8-quantized tower. [#63911](https://github.com/vllm-project/vllm/pull/63911) swaps the embedder only in `Gemma4ForConditionalGeneration.__init__`, so their image and video paths still crash with the reported error (checked with a probe that loads E4B with FP8 and builds each model's own tower, since no checkpoint of either model was at hand).\n\n## Claims\n\n- The same fix covers video inputs. On the old code, `--quantization fp8 --enforce-eager` with video enabled crashed at engine start, because the encoder profile run sends dummy video through the same patch embedder.\n- The same fix covers the encoder CUDA graph path (the patch embedder call and the `embedding_projection` cast).\n- Online `fp8_per_block`, `fp8_per_channel` and `mxfp8` (eager, custom ops off) crashed at engine start on the old code. With this fix, all three answer `The sign in the image is a **STOP** sign.`\n- `DiffusionGemmaForConditionalGeneration` and `EmbeddingGemma2Model` get the same fix through the borrowed methods.\n\n## Validation\n[results removed]\n## Details\n\nRoot cause: vLLM builds the Gemma 4 vision tower with `AutoModel.from_config`. It then replaces each `nn.Linear` with a `ReplicatedLinear` that carries the tower quant config. With online FP8, `input_proj.weight` becomes `float8_e4m3fn` after loading. The transformers `Gemma4VisionPatchEmbedder.forward` does:\n\n```python\npixel_values = 2 * (pixel_values - 0.5)\nif (target_dtype := self.input_proj.weight.dtype).is_floating_point:\n pixel_values = pixel_values.to(target_dtype)\nhidden_states = self.input_proj(pixel_values)\n```\n\nThis is right for a plain `nn.Linear`. For a quantized layer, though, the weight dtype is the storage dtype. FP8 is a floating type, so the guard lets the cast through. The bf16 pixel values are rounded to FP8 without a scale, and the FP8 linear's activation quant gets an FP8 input. `dynamic_per_token_scaled_fp8_quant` only accepts fp16, bf16 or fp32. A debug run confirmed the chain: the pixel values enter the patch embedder as bf16, and only `vision_tower.patch_embedder.input_proj` receives an FP8 input. `encoder_cudagraph_forward` had the same mistake in vLLM code: it cast the pooled states to `embedding_projection.weight.dtype`, which is also FP8 under the tower quant config.\n\nFix: a module-level `_embed_patches(patch_embedder, pixel_values, pixel_position_ids, padding_positions, dtype)` repeats the steps of the transformers forward (`2 * (x - 0.5)`, `input_proj`, `_position_embeddings`, sum), but casts to the given dtype. The image, video and encoder CUDA graph paths call it with `self.model_dtype`. The CUDA graph path also casts the pooled states to `self.model_dtype`, as the eager paths already do before `embed_vision`. The quant config is not touched, so the layers stay FP8. For an unquantized layer nothing changes, because then the weight dtype is the model dtype. The helper is a module-level function, not a method, because the two borrowing models copy `_process_image_input` and `_process_video_input` without inheriting from Gemma 4. A method would be missing on those classes.\n\nAlternatives not taken:\n\n- Building `input_proj` without quantization: this changes which layers the user's quantization covers. It can also break loading of pre-quantized checkpoints that quantize this layer, and it leaves the `embedding_projection` cast as it is.\n- Making the FP8 linear accept an FP8 input: this treats the crash site, and by then the input has already been rounded to FP8.\n\nTradeoffs and limitations:\n\n- `_embed_patches` uses the private `_position_embeddings` of the transformers embedder. This file already splits `Gemma4VisionModel.forward` into its parts, so this goes one level deeper in the same style.\n- The tests use `google/gemma-4-E4B-it`, which CI already uses. E2B has the same vision tower and would be cheaper, but I could not confirm the answer checks (`stop`, `book`) on E2B.\n- Not run on AMD.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/gemma4_mm.py b/vllm/model_executor/models/gemma4_mm.py\nindex a3c5aca78729..cd9417ec1fd8 100644\n--- a/vllm/model_executor/models/gemma4_mm.py\n+++ b/vllm/model_executor/models/gemma4_mm.py\n@@ -1315,9 +1315,16 @@ def _embed_patches(\n pixel_values = self.vision_input_norm(\n pixel_values.reshape(-1, num_channels), self.model_dtype\n ).view(pixel_values.shape)\n- return self.vision_tower.patch_embedder(\n- pixel_values, pixel_position_ids, padding_positions\n- ).to(self.model_dtype)\n+ # Inline `Gemma4VisionPatchEmbedder.forward` with the pixel values in\n+ # the model dtype. Transformers casts them to `input_proj.weight.dtype`,\n+ # which is the storage dtype (e.g. FP8) once `input_proj` is quantized.\n+ embedder = self.vision_tower.patch_embedder\n+ pixel_values = (2 * (pixel_values - 0.5)).to(self.model_dtype)\n+ hidden_states = embedder.input_proj(pixel_values)\n+ position_embeddings = embedder._position_embeddings(\n+ pixel_position_ids, padding_positions\n+ )\n+ return (hidden_states + position_embeddings).to(self.model_dtype)\n \n # ------------------------------------------------------------------ #\n # Image processing\n@@ -2073,11 +2080,7 @@ def encoder_cudagraph_forward(\n pooled_states = (pooled_states - vt.std_bias) * vt.std_scale\n \n flat_pooled = pooled_states.reshape(-1, pooled_states.shape[-1])\n- gathered_states = flat_pooled[gather_indices]\n-\n- # Cast to the projection layer's dtype to resolve mixed-precision crash\n- target_dtype = self.embed_vision.embedding_projection.weight.dtype\n- gathered_states = gathered_states.to(target_dtype)\n+ gathered_states = flat_pooled[gather_indices].to(self.model_dtype)\n \n flat_proj_embs = self.embed_vision(\n inputs_embeds=gathered_states.unsqueeze(0)\n\ndiff --git a/tests/models/multimodal/processing/test_gemma4.py b/tests/models/multimodal/processing/test_gemma4.py\nindex 12790def3eb9..1c29deba3d3a 100644\n--- a/tests/models/multimodal/processing/test_gemma4.py\n+++ b/tests/models/multimodal/processing/test_gemma4.py\n@@ -371,16 +371,21 @@ def test_embed_patches_normalizes_channel_last_patches():\n )\n model.vision_tower = SimpleNamespace(\n config=SimpleNamespace(num_channels=3),\n- patch_embedder=lambda pixel_values, *_: pixel_values,\n+ patch_embedder=SimpleNamespace(\n+ input_proj=lambda pixel_values: pixel_values,\n+ _position_embeddings=lambda *_: 0.0,\n+ ),\n )\n model.model_dtype = torch.float32\n \n pixel_values = torch.randint(0, 256, (2, 6, 16 * 16 * 3), dtype=torch.uint8)\n output = model._embed_patches(pixel_values, None, None)\n \n+ # `_embed_patches` also applies the embedder's [0, 1] -> [-1, 1] rescale.\n expected = (\n pixel_values.view(2, 6, -1, 3) / 255 - torch.tensor(mean)\n ) / torch.tensor(std)\n+ expected = 2 * (expected - 0.5)\n torch.testing.assert_close(output, expected.view(pixel_values.shape))\n \n \n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fix Gemma 4 vision crash with online FP8 quantization\nLabels: bug, ready, ci/build, multi-modality, nvidia, quantization\nFiles changed (2): tests/models/multimodal/processing/test_gemma4.py, vllm/model_executor/models/gemma4_mm.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #63732. With `--quantization fp8`, an image request to Gemma 4 returns HTTP 500 and kills the engine core. The transformers patch embedder casts the pixel values to `input_proj.weight.dtype`. Once vLLM quantizes that layer, this dtype is `float8_e4m3fn`, so the FP8 linear gets an FP8 input. This PR runs the patch embedder steps in `gemma4_mm.py` with the pixel values cast to `self.model_dtype`. It makes the same change for the pooled states before `embedding_projection` in the encoder CUDA graph path.\n\nCompared with #63911, this fix:\n\n- Also fixes `DiffusionGemmaForConditionalGeneration` and `EmbeddingGemma2Model`. They borrow Gemma 4's `_process_image_input` and `_process_video_input` and build their own FP8-quantized tower. [#63911](https://github.com/vllm-project/vllm/pull/63911) swaps the embedder only in `Gemma4ForConditionalGeneration.__init__`, so their image and video paths still crash with the reported error (checked with a probe that loads E4B with FP8 and builds each model's own tower, since no checkpoint of either model was at hand).\n\n## Claims\n\n- The same fix covers video inputs. On the old code, `--quantization fp8 --enforce-eager` with video enabled crashed at engine start, because the encoder profile run sends dummy video through the same patch embedder.\n- The same fix covers the encoder CUDA graph path (the patch embedder call and the `embedding_projection` cast).\n- Online `fp8_per_block`, `fp8_per_channel` and `mxfp8` (eager, custom ops off) crashed at engine start on the old code. With this fix, all three answer `The sign in the image is a **STOP** sign.`\n- `DiffusionGemmaForConditionalGeneration` and `EmbeddingGemma2Model` get the same fix through the borrowed methods.\n\n## Validation\n[results removed]\n## Details\n\nRoot cause: vLLM builds the Gemma 4 vision tower with `AutoModel.from_config`. It then replaces each `nn.Linear` with a `ReplicatedLinear` that carries the tower quant config. With online FP8, `input_proj.weight` becomes `float8_e4m3fn` after loading. The transformers `Gemma4VisionPatchEmbedder.forward` does:\n\n```python\npixel_values = 2 * (pixel_values - 0.5)\nif (target_dtype := self.input_proj.weight.dtype).is_floating_point:\n pixel_values = pixel_values.to(target_dtype)\nhidden_states = self.input_proj(pixel_values)\n```\n\nThis is right for a plain `nn.Linear`. For a quantized layer, though, the weight dtype is the storage dtype. FP8 is a floating type, so the guard lets the cast through. The bf16 pixel values are rounded to FP8 without a scale, and the FP8 linear's activation quant gets an FP8 input. `dynamic_per_token_scaled_fp8_quant` only accepts fp16, bf16 or fp32. A debug run confirmed the chain: the pixel values enter the patch embedder as bf16, and only `vision_tower.patch_embedder.input_proj` receives an FP8 input. `encoder_cudagraph_forward` had the same mistake in vLLM code: it cast the pooled states to `embedding_projection.weight.dtype`, which is also FP8 under the tower quant config.\n\nFix: a module-level `_embed_patches(patch_embedder, pixel_values, pixel_position_ids, padding_positions, dtype)` repeats the steps of the transformers forward (`2 * (x - 0.5)`, `input_proj`, `_position_embeddings`, sum), but casts to the given dtype. The image, video and encoder CUDA graph paths call it with `self.model_dtype`. The CUDA graph path also casts the pooled states to `self.model_dtype`, as the eager paths already do before `embed_vision`. The quant config is not touched, so the layers stay FP8. For an unquantized layer nothing changes, because then the weight dtype is the model dtype. The helper is a module-level function, not a method, because the two borrowing models copy `_process_image_input` and `_process_video_input` without inheriting from Gemma 4. A method would be missing on those classes.\n\nAlternatives not taken:\n\n- Building `input_proj` without quantization: this changes which layers the user's quantization covers. It can also break loading of pre-quantized checkpoints that quantize this layer, and it leaves the `embedding_projection` cast as it is.\n- Making the FP8 linear accept an FP8 input: this treats the crash site, and by then the input has already been rounded to FP8.\n\nTradeoffs and limitations:\n\n- `_embed_patches` uses the private `_position_embeddings` of the transformers embedder. This file already splits `Gemma4VisionModel.forward` into its parts, so this goes one level deeper in the same style.\n- The tests use `google/gemma-4-E4B-it`, which CI already uses. E2B has the same vision tower and would be cheaper, but I could not confirm the answer checks (`stop`, `book`) on E2B.\n- Not run on AMD.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/gemma4_mm.py b/vllm/model_executor/models/gemma4_mm.py\nindex a3c5aca78729..069c1b8a8b94 100644\n--- a/vllm/model_executor/models/gemma4_mm.py\n+++ b/vllm/model_executor/models/gemma4_mm.py\n@@ -1315,9 +1315,16 @@ def _embed_patches(\n pixel_values = self.vision_input_norm(\n pixel_values.reshape(-1, num_channels), self.model_dtype\n ).view(pixel_values.shape)\n- return self.vision_tower.patch_embedder(\n- pixel_values, pixel_position_ids, padding_positions\n- ).to(self.model_dtype)\n+ # Inline `Gemma4VisionPatchEmbedder.forward` with the pixel values in\n+ # the model dtype. Transformers casts them to `input_proj.weight.dtype`,\n+ # which is the storage dtype (e.g. FP8) once `input_proj` is quantized.\n+ embedder = self.vision_tower.patch_embedder\n+ pixel_values = (2 * (pixel_values - 0.5)).to(self.model_dtype)\n+ hidden_states = embedder.input_proj(pixel_values)\n+ position_embeddings = embedder._position_embeddings(\n+ pixel_position_ids, padding_positions\n+ )\n+ return hidden_states + position_embeddings\n \n # ------------------------------------------------------------------ #\n # Image processing\n@@ -2073,11 +2080,7 @@ def encoder_cudagraph_forward(\n pooled_states = (pooled_states - vt.std_bias) * vt.std_scale\n \n flat_pooled = pooled_states.reshape(-1, pooled_states.shape[-1])\n- gathered_states = flat_pooled[gather_indices]\n-\n- # Cast to the projection layer's dtype to resolve mixed-precision crash\n- target_dtype = self.embed_vision.embedding_projection.weight.dtype\n- gathered_states = gathered_states.to(target_dtype)\n+ gathered_states = flat_pooled[gather_indices].to(self.model_dtype)\n \n flat_proj_embs = self.embed_vision(\n inputs_embeds=gathered_states.unsqueeze(0)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Benchmark] Restore --input-len/--output-len/--prefix-len in vllm bench throughput\nLabels: bug, performance, ready\nFiles changed (2): tests/benchmarks/test_throughput_cli.py, vllm/benchmarks/throughput.py\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n\n- `--input-len/--output-len/--prefix-len` take effect again; an explicit `--random-*` flag still wins, and with neither the defaults stay 1024 / 128 / 0.\n- The help of all six flags, and so the CLI reference, states the precedence and the effective defaults.\n\n## Validation\n[results removed]\n## Details\n\n- **No duplicate.** No open issue or PR reports or fixes this; searched open PRs and issues for `bench throughput` with `--input-len` / `--random-input-len`.\n- **Docs.** With the `--random-*` lengths unset in the parser, the CLI reference would no longer show their defaults, so all six flags' help now states: explicit `--random-*` > legacy flag > `RandomDataset` default (1024 / 128 / 0).\n- **Impact in tree.** The documented example in `docs/cli/README.md` (`--input-len 32 --output-len 1`) has been running 1024 / 128 since #29105, and `benchmarks/benchmark_pin_memory.py` works around the bug by setting the `--random-*` lengths to `None` by hand.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/benchmarks/throughput.py b/vllm/benchmarks/throughput.py\nindex 76f6a72fd98a..b48e5da6895c 100644\n--- a/vllm/benchmarks/throughput.py\n+++ b/vllm/benchmarks/throughput.py\n@@ -17,6 +17,7 @@\n \n from vllm.benchmarks.datasets import (\n BenchmarkDataset,\n+ RandomDataset,\n SampleRequest,\n add_random_dataset_base_args,\n add_random_multimodal_dataset_args,\n@@ -523,6 +524,14 @@ def save_to_pytorch_benchmark_format(\n write_to_json(pt_file, pt_records)\n \n \n+# --random-* length -> (legacy option it overrides, value when neither is set).\n+_RANDOM_LEN_FALLBACKS = {\n+ \"random_input_len\": (\"input_len\", RandomDataset.DEFAULT_INPUT_LEN),\n+ \"random_output_len\": (\"output_len\", RandomDataset.DEFAULT_OUTPUT_LEN),\n+ \"random_prefix_len\": (\"prefix_len\", RandomDataset.DEFAULT_PREFIX_LEN),\n+}\n+\n+\n def _to_serve_args(args: argparse.Namespace) -> argparse.Namespace:\n \"\"\"Translate throughput args into a namespace the shared get_samples reads.\n \n@@ -539,16 +548,16 @@ def _to_serve_args(args: argparse.Namespace) -> argparse.Namespace:\n \n \"\"\"\n d = vars(args).copy()\n- # random_*: prefer --random-* over legacy --input/output/prefix-len.\n- # Callers without the legacy flags (e.g. bench mm-processor) omit them, so\n- # read them optionally. Identity checks, not truthiness: an explicit 0\n- # (the default of --random-prefix-len) must not fall through to them.\n- input_len = getattr(args, \"input_len\", None)\n+ # random_*: prefer --random-* over legacy --input/output/prefix-len, then\n+ # the RandomDataset defaults. Callers without the legacy flags (e.g. bench\n+ # mm-processor) omit them, so read them optionally. Identity checks, not\n+ # truthiness: an explicit 0 must not fall through to them.\n+ for name, (legacy, default) in _RANDOM_LEN_FALLBACKS.items():\n+ value = getattr(args, name, None)\n+ if value is None:\n+ value = getattr(args, legacy, None)\n+ d[name] = default if value is None else value\n output_len = getattr(args, \"output_len\", None)\n- prefix_len = getattr(args, \"prefix_len\", None)\n- d[\"random_input_len\"] = getattr(args, \"random_input_len\", input_len)\n- d[\"random_output_len\"] = getattr(args, \"random_output_len\", output_len)\n- d[\"random_prefix_len\"] = getattr(args, \"random_prefix_len\", prefix_len)\n # --output-len maps to the per-dataset output-len entry points get_samples\n # reads. None passes through (each dataset applies its own default),\n # matching prior throughput behaviour of omitting output_len when unset.\n@@ -642,12 +651,6 @@ def validate_args(args):\n if not args.dataset_path and args.dataset_name != \"prefix_repetition\":\n print(\"When dataset path is not set, it will default to random dataset\")\n args.dataset_name = \"random\"\n- random_input_len = getattr(args, \"random_input_len\", None)\n- if args.input_len is None and random_input_len is None:\n- raise ValueError(\n- \"Either --input-len or --random-input-len must be provided \"\n- \"for a random dataset\"\n- )\n \n # === Dataset Name Specific Checks ===\n # --hf-subset and --hf-split: only used\n@@ -820,14 +823,18 @@ def add_cli_args(parser: FlexibleArgumentParser):\n \"--input-len\",\n type=int,\n default=None,\n- help=\"Input prompt length for each request\",\n+ help=\"Input prompt length for each request. For random datasets, \"\n+ \"--random-input-len takes precedence; if neither is set, \"\n+ f\"{RandomDataset.DEFAULT_INPUT_LEN}.\",\n )\n parser.add_argument(\n \"--output-len\",\n type=int,\n default=None,\n help=\"Output length for each request. Overrides the \"\n- \"output length from the dataset.\",\n+ \"output length from the dataset. For random datasets, \"\n+ \"--random-output-len takes precedence; if neither is set, \"\n+ f\"{RandomDataset.DEFAULT_OUTPUT_LEN}.\",\n )\n parser.add_argument(\n \"--n\", type=int, default=1, help=\"Number of generated sequences per prompt.\"\n@@ -907,9 +914,10 @@ def add_cli_args(parser: FlexibleArgumentParser):\n parser.add_argument(\n \"--prefix-len\",\n type=int,\n- default=0,\n+ default=None,\n help=\"Number of fixed prefix tokens before the random \"\n- \"context in a request (default: 0).\",\n+ \"context in a request. --random-prefix-len takes precedence; if \"\n+ f\"neither is set, {RandomDataset.DEFAULT_PREFIX_LEN}.\",\n )\n \n # hf dataset\n@@ -975,6 +983,16 @@ def add_cli_args(parser: FlexibleArgumentParser):\n \n # (random, random-mm, random-rerank)\n add_random_dataset_base_args(parser)\n+ # Unset unless passed, so the legacy --input-len/--output-len/--prefix-len\n+ # apply when given; _to_serve_args falls back to the RandomDataset defaults.\n+ for action in parser._actions:\n+ if action.dest in _RANDOM_LEN_FALLBACKS:\n+ legacy, default = _RANDOM_LEN_FALLBACKS[action.dest]\n+ action.default = None\n+ action.help = (\n+ f\"{action.help} Takes precedence over \"\n+ f\"--{legacy.replace('_', '-')}; if neither is set, {default}.\"\n+ )\n add_random_multimodal_dataset_args(parser)\n \n # ASR dataset\n\ndiff --git a/tests/benchmarks/test_throughput_cli.py b/tests/benchmarks/test_throughput_cli.py\nindex 37ced49838c3..c994d9ed0bf7 100644\n--- a/tests/benchmarks/test_throughput_cli.py\n+++ b/tests/benchmarks/test_throughput_cli.py\n@@ -9,6 +9,7 @@\n \"\"\"\n \n import subprocess\n+import warnings\n from argparse import Namespace\n from types import SimpleNamespace\n \n@@ -22,6 +23,7 @@\n add_cli_args,\n assign_loras,\n get_requests,\n+ validate_args,\n )\n from vllm.utils.argparse_utils import FlexibleArgumentParser\n \n@@ -322,6 +324,68 @@ def test_to_serve_args_keeps_legacy_flag_fallback() -> None:\n assert not serve_args.enable_multimodal_chat\n \n \n+def _parse_throughput_args(*argv: str) -> Namespace:\n+ parser = FlexibleArgumentParser()\n+ add_cli_args(parser)\n+ return parser.parse_args([\"--model\", MODEL_NAME, *argv])\n+\n+\n+@pytest.mark.parametrize(\n+ (\"argv\", \"expected\"),\n+ [\n+ # Neither flag: the RandomDataset defaults.\n+ ([], (1024, 128, 0)),\n+ # Legacy flags alone are honored.\n+ (\n+ [\"--input-len\", \"2048\", \"--output-len\", \"512\", \"--prefix-len\", \"64\"],\n+ (2048, 512, 64),\n+ ),\n+ # Explicit --random-* wins, including an explicit 0.\n+ (\n+ [\n+ \"--input-len\",\n+ \"2048\",\n+ \"--random-input-len\",\n+ \"300\",\n+ \"--prefix-len\",\n+ \"64\",\n+ \"--random-prefix-len\",\n+ \"0\",\n+ ],\n+ (300, 128, 0),\n+ ),\n+ ],\n+)\n+def test_parsed_lengths_follow_flag_precedence(argv, expected) -> None:\n+ \"\"\"Lengths from the real parser: --random-* > legacy flags > defaults.\"\"\"\n+ serve_args = _to_serve_args(_parse_throughput_args(*argv))\n+\n+ assert (\n+ serve_args.random_input_len,\n+ serve_args.random_output_len,\n+ serve_args.random_prefix_len,\n+ ) == expected\n+\n+\n+@pytest.mark.parametrize(\n+ \"argv\",\n+ [\n+ [\"--input-len\", \"32\", \"--output-len\", \"1\", \"--prefix-len\", \"8\"],\n+ [\"--random-input-len\", \"32\", \"--random-output-len\", \"1\"],\n+ [\"--random-prefix-len\", \"64\"],\n+ [\"--random-prefix-len\", \"0\"],\n+ ],\n+)\n+def test_one_flag_per_length_does_not_warn(argv) -> None:\n+ \"\"\"Only the legacy or only the --random-* flag: no \"Both ... are specified\".\"\"\"\n+ args = _parse_throughput_args(*argv)\n+ with warnings.catch_warnings(record=True) as caught:\n+ warnings.simplefilter(\"always\")\n+ validate_args(args)\n+\n+ assert not [str(w.message) for w in caught if \"are specified\" in str(w.message)]\n+\n+\n @pytest.mark.benchmark\n def test_get_requests_random_mm_with_mm_processor_args(\n hf_tokenizer: PreTrainedTokenizerBase,\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][KV Offload] Publish successful stores to lookup state\nLabels: bug, ready, nixl\nFiles changed (6): tests/v1/kv_offload/tiering/test_async_lookup.py, tests/v1/kv_offload/tiering/test_fs_tier.py, tests/v1/kv_offload/tiering/test_obj_tier.py, vllm/v1/kv_offload/tiering/async_lookup.py, vllm/v1/kv_offload/tiering/fs/manager.py, vllm/v1/kv_offload/tiering/obj/manager.py\n\n## Description (results removed)\n\n## Summary\n\nBuilds on the invalidation approach in #61187. When this instance successfully stores keys to a filesystem or object-store tier, it publishes them as present in the tier's lookup state. This updates cached misses and prevents older pending or in-flight probes from overwriting the store result.\n\nUnlike #61717, this preserves cross-request miss reuse instead of probing again for every request. It handles successful stores by this instance only; writes from other instances to shared storage remain out of scope, so this does not close #61658.\n\n## Validation\n[results removed]\n## Related work\n\n#61187 is closed and unmerged; this PR continues its invalidation direction. #61717 addresses the related stale-miss behavior by re-probing on new requests, while this change preserves cached-miss reuse.\n\nAI assistance was used; the submitter reviewed the change.\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/kv_offload/tiering/async_lookup.py b/vllm/v1/kv_offload/tiering/async_lookup.py\nindex 69a513f55de8..080c9139433e 100644\n--- a/vllm/v1/kv_offload/tiering/async_lookup.py\n+++ b/vllm/v1/kv_offload/tiering/async_lookup.py\n@@ -33,7 +33,8 @@\n Results are drained on the first lookup after each flush, at flush(), and\n after worker shutdown. In-flight lookups with no remaining request references\n are retained until their results are drained, allowing new requests to share\n-the same probe.\n+the same probe; a successful store drops such an orphan instead (see\n+mark_present()).\n \"\"\"\n \n import queue\n@@ -61,8 +62,9 @@ class LookupPhase(Enum):\n class LookupState:\n generation: int\n phase: LookupPhase = LookupPhase.PENDING\n- # None while pending/in flight; True if the key exists; False if absent or\n- # explicitly marked missing after a failed load.\n+ # None while pending/in flight; True if the key is known to exist (a probe\n+ # found it, or this instance stored it); False if absent or explicitly\n+ # marked missing after a failed load.\n result: bool | None = None\n request_ids: set[str] = field(default_factory=set) # requests asking for the lookup\n \n@@ -229,6 +231,34 @@ def mark_miss(self, keys: Collection[OffloadKey]) -> None:\n if state is not None and state.phase is LookupPhase.RESOLVED:\n state.result = False\n \n+ def mark_present(self, keys: Collection[OffloadKey]) -> None:\n+ \"\"\"Record that keys were successfully stored to this tier.\n+\n+ Unlike mark_miss(), which leaves a newer probe alone (#59096), a store\n+ completion is newer information than any probe started before it, so\n+ this supersedes them: advancing the generation makes a stale pending\n+ batch entry fail flush()'s generation check and a stale in-flight\n+ result fail drain_results()'s, before either phase assert is reached.\n+\n+ Keys with no cached entry are skipped, since a verdict with no owning\n+ request could never be reclaimed. An in-flight entry whose requests all\n+ finished is dropped; cleanup() already removed the reverse-index\n+ entries, so its late result is simply ignored.\n+ \"\"\"\n+ for key in keys:\n+ state = self._lookup_state.get(key)\n+ if state is None or state.result is True:\n+ continue\n+ if not state.request_ids:\n+ del self._lookup_state[key]\n+ continue\n+ # Generations are opaque identity tokens compared for equality\n+ # only, so bumping one key cannot affect another key's results.\n+ state.generation = self._next_generation\n+ self._next_generation += 1\n+ state.result = True\n+ state.phase = LookupPhase.RESOLVED\n+\n def cleanup(self, req_id: str) -> None:\n \"\"\"Release request references, retaining in-flight lookups.\n \ndiff --git a/vllm/v1/kv_offload/tiering/fs/manager.py b/vllm/v1/kv_offload/tiering/fs/manager.py\nindex 594e18b9f549..91a1dd755138 100644\n--- a/vllm/v1/kv_offload/tiering/fs/manager.py\n+++ b/vllm/v1/kv_offload/tiering/fs/manager.py\n@@ -150,6 +150,7 @@ def __init__(\n \"emit events.\",\n tier_type,\n )\n+ # Track in-flight store jobs for lookup invalidation and KV events.\n self._store_jobs: dict[JobId, TransferJob] = {}\n # Keys of in-flight load (promotion) jobs, so a failed load can mark\n # its own cached lookup verdicts False (see get_finished_jobs).\n@@ -221,8 +222,7 @@ def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:\n @override\n def submit_store(self, job_metadata: TransferJob) -> None:\n keys = list(job_metadata.keys)\n- if self.events is not None:\n- self._store_jobs[job_metadata.job_id] = job_metadata\n+ self._store_jobs[job_metadata.job_id] = job_metadata\n task = functools.partial(\n batch_store_block,\n [self.file_mapper.get_file_name(key) for key in keys],\n@@ -282,9 +282,11 @@ def get_finished_jobs(self) -> Iterable[JobResult]:\n for job_id, success, transfer_time in self._pool.get_finished():\n block_count = self._job_block_counts.pop(job_id, 0)\n transfer_bytes = block_count * self._block_size if block_count else None\n- if self.events is not None:\n- job = self._store_jobs.pop(job_id, None)\n- if success and job is not None and job.keys:\n+ job = self._store_jobs.pop(job_id, None)\n+ if job is not None and success:\n+ # Successful store makes previously absent keys known-present.\n+ self._lookup_manager.mark_present(job.keys)\n+ if self.events is not None and job.keys:\n self.events.append(\n OffloadingEvent(\n keys=list(job.keys),\ndiff --git a/vllm/v1/kv_offload/tiering/obj/manager.py b/vllm/v1/kv_offload/tiering/obj/manager.py\nindex 3a6f8328dfa5..fb18502332d9 100644\n--- a/vllm/v1/kv_offload/tiering/obj/manager.py\n+++ b/vllm/v1/kv_offload/tiering/obj/manager.py\n@@ -149,6 +149,7 @@ def __init__(\n \"emit events.\",\n tier_type,\n )\n+ # Track in-flight store jobs for lookup invalidation and KV events.\n self._store_jobs: dict[JobId, TransferJob] = {}\n # Keys of in-flight load (promotion) jobs, so a failed download can\n # mark its own cached lookup verdicts False (see get_finished_jobs).\n@@ -293,8 +294,7 @@ def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:\n return LookupResult.HIT if result else LookupResult.MISS\n \n def submit_store(self, job_metadata: TransferJob) -> None:\n- if self.events is not None:\n- self._store_jobs[job_metadata.job_id] = job_metadata\n+ self._store_jobs[job_metadata.job_id] = job_metadata\n obj_keys = (self._file_mapper.get_file_name(k) for k in job_metadata.keys)\n self._submit_transfer(\n job_metadata.job_id, job_metadata.chunk_ids, obj_keys, NIXL_WRITE\n@@ -388,9 +388,10 @@ def get_finished_jobs(self) -> Iterable[JobResult]:\n results = self._pending_results\n self._pending_results = []\n for result in results:\n- if self.events is not None:\n- job = self._store_jobs.pop(result.job_id, None)\n- if result.success and job is not None and job.keys:\n+ job = self._store_jobs.pop(result.job_id, None)\n+ if result.success and job is not None:\n+ self._lookup_manager.mark_present(job.keys)\n+ if self.events is not None and job.keys:\n self.events.append(\n OffloadingEvent(\n keys=list(job.keys),\n\ndiff --git a/tests/v1/kv_offload/tiering/test_async_lookup.py b/tests/v1/kv_offload/tiering/test_async_lookup.py\nindex d23d837371bd..543257dc9b35 100644\n--- a/tests/v1/kv_offload/tiering/test_async_lookup.py\n+++ b/tests/v1/kv_offload/tiering/test_async_lookup.py\n@@ -403,3 +403,105 @@ def test_enqueue_once_invariant_enforced(self):\n with pytest.raises(AssertionError):\n mgr.drain_results()\n mgr.shutdown()\n+\n+ def test_store_drops_orphaned_in_flight_state(\n+ self, monkeypatch: pytest.MonkeyPatch\n+ ):\n+ \"\"\"A store must not retain an in-flight state after its request ended.\"\"\"\n+ key = _key(1)\n+ mgr = InMemoryLookupManager()\n+ probe_started = threading.Event()\n+ release_probe = threading.Event()\n+ batch_lookup = mgr.batch_lookup\n+\n+ def blocking_lookup(keys, req_context):\n+ results = list(batch_lookup(keys, req_context))\n+ probe_started.set()\n+ if not release_probe.wait(timeout=5):\n+ raise TimeoutError(\"Test did not release the backend probe\")\n+ return results\n+\n+ monkeypatch.setattr(mgr, \"batch_lookup\", blocking_lookup)\n+ try:\n+ assert mgr.lookup(key, _ctx(\"req_a\")) is None\n+ mgr.flush()\n+ assert probe_started.wait(timeout=5)\n+ mgr.cleanup(\"req_a\")\n+ assert key in mgr._lookup_state\n+ assert not mgr._lookup_state[key].request_ids\n+\n+ mgr._existing.add(key)\n+ mgr.mark_present([key])\n+ assert key not in mgr._lookup_state\n+ release_probe.set()\n+ finally:\n+ release_probe.set()\n+ mgr.shutdown()\n+\n+ assert key not in mgr._lookup_state\n+\n+ def test_mark_present_handles_mixed_phases(self, monkeypatch: pytest.MonkeyPatch):\n+ \"\"\"One call updates pending, in-flight and resolved keys independently.\"\"\"\n+ pending_key, in_flight_key, resolved_key, unknown_key = (\n+ _key(1),\n+ _key(2),\n+ _key(3),\n+ _key(99),\n+ )\n+ mgr = InMemoryLookupManager()\n+ probe_started = threading.Event()\n+ release_probe = threading.Event()\n+ batch_lookup = mgr.batch_lookup\n+ calls = 0\n+\n+ def blocking_lookup(keys, req_context):\n+ nonlocal calls\n+ calls += 1\n+ results = list(batch_lookup(keys, req_context))\n+ if calls == 2:\n+ probe_started.set()\n+ if not release_probe.wait(timeout=5):\n+ raise TimeoutError(\"Test did not release the backend probe\")\n+ return results\n+\n+ monkeypatch.setattr(mgr, \"batch_lookup\", blocking_lookup)\n+ try:\n+ # Resolved: a probe delivered a miss.\n+ assert mgr.lookup(resolved_key, _ctx(\"req_c\")) is None\n+ mgr.flush()\n+ assert mgr._results_ready.wait(timeout=5)\n+ mgr._results_ready.clear()\n+ assert mgr.lookup(resolved_key, _ctx(\"req_c\")) is False\n+\n+ # In flight: the worker is still inside this probe.\n+ assert mgr.lookup(in_flight_key, _ctx(\"req_b\")) is None\n+ mgr.flush()\n+ assert probe_started.wait(timeout=5)\n+\n+ # Pending: accumulated this step, not flushed yet.\n+ assert mgr.lookup(pending_key, _ctx(\"req_a\")) is None\n+\n+ mgr.mark_present([pending_key, in_flight_key, resolved_key, unknown_key])\n+\n+ for key in (pending_key, in_flight_key, resolved_key):\n+ state = mgr._lookup_state[key]\n+ assert state.result is True\n+ assert state.phase is LookupPhase.RESOLVED\n+ assert unknown_key not in mgr._lookup_state\n+\n+ # A stale pending entry is skipped when its batch is flushed.\n+ mgr.flush()\n+\n+ assert mgr.lookup(pending_key, _ctx(\"req_a\")) is True\n+ assert mgr.lookup(in_flight_key, _ctx(\"req_b\")) is True\n+ assert mgr.lookup(resolved_key, _ctx(\"req_c\")) is True\n+ assert mgr.lookup(unknown_key, _ctx(\"req_d\")) is None\n+\n+ release_probe.set()\n+ finally:\n+ release_probe.set()\n+ mgr.shutdown()\n+\n+ # Only the two flushed probes ran: the pending batch was dropped, the\n+ # in-flight result was ignored, and unknown_key was never probed.\n+ assert calls == 2\ndiff --git a/tests/v1/kv_offload/tiering/test_fs_tier.py b/tests/v1/kv_offload/tiering/test_fs_tier.py\nindex 0d04cfad2b94..8c8ebf01ff6b 100644\n--- a/tests/v1/kv_offload/tiering/test_fs_tier.py\n+++ b/tests/v1/kv_offload/tiering/test_fs_tier.py\n@@ -231,6 +231,18 @@ def test_store_creates_file_and_lookup_succeeds(fs_tier):\n assert os.path.exists(dest), f\"Expected file at {dest}\"\n \n \n+def test_store_marks_a_cached_miss_present(fs_tier):\n+ tier, _ = fs_tier\n+ block_key = key(1)\n+ assert lookup_and_wait(tier, [block_key]) == [LookupResult.MISS]\n+\n+ tier.submit_store(make_job(1, [block_key], [0]))\n+ results = drain(tier)\n+ assert len(results) == 1\n+ assert results[0].success\n+ assert lookup_and_wait(tier, [block_key]) == [LookupResult.HIT]\n+\n+\n def test_store_accepts_block_published_by_another_writer(fs_tier, monkeypatch):\n \"\"\"Losing the race to publish a block must not fail the store job.\n \ndiff --git a/tests/v1/kv_offload/tiering/test_obj_tier.py b/tests/v1/kv_offload/tiering/test_obj_tier.py\nindex 1a4b5410faea..f69755ed2286 100644\n--- a/tests/v1/kv_offload/tiering/test_obj_tier.py\n+++ b/tests/v1/kv_offload/tiering/test_obj_tier.py\n@@ -321,6 +321,28 @@ def test_store_and_lookup(self):\n assert results[0].success\n assert lookup_and_wait(self.tier, [key(1)]) == [LookupResult.HIT]\n \n+ def test_store_marks_a_cached_miss_present(self):\n+ block_key = key(1)\n+ assert lookup_and_wait(self.tier, [block_key]) == [LookupResult.MISS]\n+\n+ self.tier.submit_store(make_job(1, [block_key], [0]))\n+ results = drain(self.tier)\n+ assert len(results) == 1\n+ assert results[0].success\n+ assert lookup_and_wait(self.tier, [block_key]) == [LookupResult.HIT]\n+\n+ def test_failed_store_does_not_mark_cached_miss_present(self):\n+ block_key = key(1)\n+ assert lookup_and_wait(self.tier, [block_key]) == [LookupResult.MISS]\n+\n+ self.agent.check_xfer_state = lambda h: \"ERR\"\n+ self.tier.submit_store(make_job(1, [block_key], [0]))\n+ results = drain(self.tier)\n+\n+ assert len(results) == 1\n+ assert not results[0].success\n+ assert lookup_and_wait(self.tier, [block_key]) == [LookupResult.MISS]\n+\n def test_lookup_unrelated_key_returns_false(self):\n self.tier.submit_store(make_job(1, [key(1)], [0]))\n drain(self.tier)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Tool Parser] Keep raw text for string parameters with union/enum/$ref schemas (Muse, MiniCPM5, Poolside)\nLabels: bug, documentation, ready, tool-calling, rust\nFiles changed (10): rust/src/parser/src/schema.rs, rust/src/parser/src/unified/muse.rs, tests/tool_parsers/test_minicpm5xml_tool_parser.py, tests/tool_parsers/test_poolside_v1_tool_parser.py, tests/tool_parsers/test_schema_types.py, tests/tool_use/test_muse.py, vllm/tool_parsers/minicpm5xml_tool_parser.py, vllm/tool_parsers/muse_tool_parser.py, vllm/tool_parsers/poolside_v1_tool_parser.py, vllm/tool_parsers/schema_types.py\n\n## Description (results removed)\n\n## Overview\n\nThe `muse`, `minicpm5` and `poolside_v1` tool parsers keep a parameter's raw text only when its schema is exactly `{\"type\": \"string\"}`, so `Optional[str]` values such as `\"1.10\"` or `\"1984\"` come back as `1.1` or `1984`. This makes them keep the raw text whenever the schema allows a string. The Rust frontend's Muse parser gets the same fix.\n\nFIX #64517\n\n## Claims\n\n- String parameters keep their raw text when the schema allows a string through `anyOf`/`oneOf`, a `type` list, `enum`/`const`, a local `$ref`, `allOf`, or `additionalProperties`. Streaming and non-streaming both get the fix.\n- Values that fit another type the schema allows still decode to it: `null` -> `None` for `Optional[str]`, `\"25\"` -> `25` under `anyOf [integer, string]`.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause.** Each parser compared the schema to `\"type\": \"string\"` (Muse `_string_parameters`, MiniCPM5 `_get_argument_type`, Poolside `_is_string_type`, Rust `MuseUnifiedParser::new`) and decoded everything else.\n\n**Change.** `parameter_types` in the new `vllm/tool_parsers/schema_types.py` computes the JSON types each top-level parameter allows (`type`, `const`, `enum`, local `$ref`, `anyOf`/`oneOf` as union, `allOf` as intersection). `convert_value` keeps the raw text unless the parser's own decoder returns another allowed type. Each parser keeps its decoder. In Rust, Muse derives the types from the existing `SchemaRoot::options` walk, which already resolves `$ref` for coercion and the output grammars, and intersects multi-branch `allOf`, where a `number` branch also admits integers.\n\n**Scope.** `extract_types_from_schema` and `ParserEngine` coercion are not touched; consolidating them is #63385. Structured-output schema analysis (RFC #58697) checks grammar-backend features, not value types.\n\n**Limitations.**\n- Only top-level parameters are checked; nested values are decoded as a whole.\n- A union with an untyped branch (`anyOf [string, {}]`) is unconstrained, so it decodes, as on main.\n- `anyOf [string, object]` decodes a JSON body to an object; the schema allows both.\n- Poolside V1 streams `Optional[str]` arguments in one delta at ``, as on main.\n- The Rust frontend uses one parser for Spark and Glimmer, so Rust Glimmer gets the new rules while Python Glimmer always decodes. This split predates this PR.\n\n**Rust differs from Python** on a few schemas that admit a string:\n- `allOf` nested inside `anyOf`;\n- an untyped `anyOf` beside a `type` list;\n- `$ref` chains deeper than 32, which decode as on main;\n- the OpenAPI `nullable` null option.\n\nThe decoders also differ. serde_json rejects `NaN`/`Infinity` and reads integers beyond 64 bits as floats, so Rust keeps the raw text in cases where Python's `json.loads` decodes.\n\n---\n\n_This PR was prepared with Claude Code and reviewed by a human (@simon-veitner-redhat)._\n\n## Diff\n\n```diff\ndiff --git a/rust/src/parser/src/schema.rs b/rust/src/parser/src/schema.rs\nindex c27427de2e2c..27cf0f2077f1 100644\n--- a/rust/src/parser/src/schema.rs\n+++ b/rust/src/parser/src/schema.rs\n@@ -319,7 +319,7 @@ impl JsonType {\n })\n }\n \n- fn of_value(value: &Value) -> Self {\n+ pub(crate) fn of_value(value: &Value) -> Self {\n match value {\n Value::String(_) => Self::String,\n Value::Number(number) if number.is_f64() => Self::Number,\ndiff --git a/rust/src/parser/src/unified/muse.rs b/rust/src/parser/src/unified/muse.rs\nindex c04d519b2552..6eb24e98bc6c 100644\n--- a/rust/src/parser/src/unified/muse.rs\n+++ b/rust/src/parser/src/unified/muse.rs\n@@ -20,7 +20,7 @@\n //!\n //! `self` bodies are reasoning, `commentary`/`user` bodies are visible text,\n //! and any other recipient names a tool whose body is one ATEM block with one\n-//! or more `` calls. Parameters declared as strings retain their\n+//! or more `` calls. Parameters admitting strings retain their\n //! raw text; other values are JSON-decoded when possible and kept as raw\n //! strings otherwise. Each invoke's arguments are reassembled as a compact\n //! JSON object preserving parameter order.\n@@ -43,6 +43,7 @@ use winnow::stream::Partial;\n use winnow::token::{literal, rest, take_till, take_until, take_while};\n \n use super::{Result, UnifiedParser, UnifiedParserOutput, token_id};\n+use crate::schema::{JsonType, OptionSource, SchemaRoot};\n use crate::tool::{Tool, ToolCallDelta};\n use crate::unified::parsing_failed;\n use crate::utils::{MarkerScanState, parse_buffered_event, safe_text_len_mul, take_until_marker};\n@@ -131,7 +132,7 @@ pub struct MuseUnifiedParser {\n mode: MuseMode,\n /// Names of the tools registered on the request.\n tool_names: HashSet,\n- string_parameters: HashMap>,\n+ parameters: HashMap,\n /// Number of calls emitted in the current response.\n emitted_call_count: usize,\n }\n@@ -148,22 +149,9 @@ impl MuseUnifiedParser {\n buffer: DecodedText::default(),\n mode: MuseMode::default(),\n tool_names: tools.iter().map(|tool| tool.name.clone()).collect(),\n- string_parameters: tools\n+ parameters: tools\n .iter()\n- .map(|tool| {\n- let strings = tool\n- .parameters\n- .get(\"properties\")\n- .and_then(Value::as_object)\n- .into_iter()\n- .flatten()\n- .filter(|(_, schema)| {\n- schema.get(\"type\").and_then(Value::as_str) == Some(\"string\")\n- })\n- .map(|(name, _)| name.clone())\n- .collect();\n- (tool.name.clone(), strings)\n- })\n+ .map(|tool| (tool.name.clone(), tool.parameters.clone()))\n .collect(),\n emitted_call_count: 0,\n })\n@@ -198,16 +186,12 @@ impl MuseUnifiedParser {\n MuseEvent::ToolCalls { calls } => {\n for call in calls {\n let name = normalize_tool_name(call.name, &self.tool_names);\n- let strings = self.string_parameters.get(&name);\n+ let parameters = self.parameters.get(&name).unwrap_or(&Value::Null);\n let arguments: Map = call\n .parameters\n .into_iter()\n .map(|(key, raw)| {\n- let value = if strings.is_some_and(|strings| strings.contains(&key)) {\n- Value::String(raw)\n- } else {\n- decode_parameter_value(&raw)\n- };\n+ let value = convert_parameter_value(parameters, &key, raw);\n (key, value)\n })\n .collect();\n@@ -491,6 +475,61 @@ fn decode_parameter_value(raw: &str) -> Value {\n serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.to_string()))\n }\n \n+/// Decode a parameter value, keeping the raw text when its schema admits a\n+/// string unless the value decodes to another admitted type (`null` for\n+/// `Optional[str]`, `3` for `anyOf: [integer, string]`).\n+fn convert_parameter_value(parameters: &Value, key: &str, raw: String) -> Value {\n+ let decoded = decode_parameter_value(&raw);\n+ let root = SchemaRoot::new(parameters);\n+ let types = root\n+ .resolved()\n+ .get(\"properties\")\n+ .and_then(|properties| properties.get(key))\n+ .or_else(|| root.resolved().get(\"additionalProperties\"))\n+ .and_then(|schema| schema_types(root, schema))\n+ .unwrap_or_default();\n+ match JsonType::of_value(&decoded) {\n+ _ if !types.contains(&JsonType::String) => decoded,\n+ JsonType::Integer if types.contains(&JsonType::Number) => decoded,\n+ ty if ty != JsonType::String && types.contains(&ty) => decoded,\n+ _ => Value::String(raw),\n+ }\n+}\n+\n+/// Types `schema` admits (none for a non-`string` type name), or `None` if unconstrained.\n+fn schema_types<'a>(root: SchemaRoot<'a>, schema: &'a Value) -> Option> {\n+ // Only the exact type name `string` keeps the raw text, as before.\n+ if let Some(name) = schema.get(\"type\").and_then(Value::as_str) {\n+ let string = (name == \"string\").then_some(JsonType::String);\n+ return Some(string.into_iter().collect());\n+ }\n+ // `options` admits any value under a multi-schema `allOf`; intersect the\n+ // constrained branches so `[{$ref}, {description}]` keeps the referenced type.\n+ if let Some(schemas @ [_, _, ..]) =\n+ schema.get(\"allOf\").and_then(Value::as_array).map(Vec::as_slice)\n+ {\n+ return schemas\n+ .iter()\n+ .filter_map(|schema| schema_types(root, schema))\n+ .map(|mut types| {\n+ // A `number` branch also admits integers.\n+ if types.contains(&JsonType::Number) {\n+ types.push(JsonType::Integer);\n+ }\n+ types\n+ })\n+ .reduce(|both, types| both.into_iter().filter(|ty| types.contains(ty)).collect());\n+ }\n+ // An untyped option leaves the value unconstrained; `nullable` adds a null one.\n+ root.options(schema)\n+ .into_iter()\n+ .map(|option| match option.source {\n+ OptionSource::Any if option.ty != JsonType::Null => None,\n+ _ => Some(option.ty),\n+ })\n+ .collect()\n+}\n+\n /// Build a cut error for determinably malformed Muse structure.\n fn muse_error(label: &'static str) -> ErrMode {\n let mut error = ContextError::new();\n@@ -506,7 +545,7 @@ mod tests {\n use thiserror_ext::AsReport;\n use vllm_tokenizer::{DecodedText, test_utils::TestTokenizer};\n \n- use super::{EOM, EOT, MESSAGE, MuseUnifiedParser, START};\n+ use super::{EOM, EOT, MESSAGE, MuseUnifiedParser, START, convert_parameter_value};\n use crate::tool::{Tool, ToolCallDelta};\n use crate::unified::{\n UnifiedParser, UnifiedParserError, UnifiedParserEvent, UnifiedParserOutput,\n@@ -744,9 +783,11 @@ mod tests {\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\"type\": \"string\"},\n+ \"note\": {\"$ref\": \"#/$defs/Note\"},\n \"count\": {\"type\": \"integer\"},\n \"items\": {\"type\": \"array\", \"items\": {\"type\": \"integer\"}}\n- }\n+ },\n+ \"$defs\": {\"Note\": {\"type\": \"string\"}}\n }),\n strict: None,\n defer_loading: None,\n@@ -765,7 +806,12 @@ mod tests {\n \" to=echo.echo{MESSAGE}{}{EOT}\",\n atem(&[(\n \"echo.echo\",\n- &[(\"text\", value), (\"count\", \"25\"), (\"items\", \"[1,2]\")]\n+ &[\n+ (\"text\", value),\n+ (\"note\", value),\n+ (\"count\", \"25\"),\n+ (\"items\", \"[1,2]\")\n+ ]\n )])\n );\n let mut parser = MuseUnifiedParser::new(&tools, Arc::new(tokenizer())).unwrap();\n@@ -775,7 +821,7 @@ mod tests {\n assert_eq!(calls[0].name.as_deref(), Some(\"echo\"));\n assert_eq!(\n serde_json::from_str::(&calls[0].arguments).unwrap(),\n- json!({\"text\": value, \"count\": 25, \"items\": [1, 2]})\n+ json!({\"text\": value, \"note\": value, \"count\": 25, \"items\": [1, 2]})\n );\n for size in [1, 17, text.len()] {\n parser.reset();\n@@ -1163,4 +1209,50 @@ mod tests {\n ]\n );\n }\n+\n+ #[test]\n+ fn muse_parameter_schema_types() {\n+ let nullable = json!({\"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}]});\n+ let body = \"{\\n \\\"v\\\": \\\"1.4.0\\\"\\n}\";\n+ let cases = json!([\n+ // schemas admitting a string keep the raw text...\n+ [{\"type\": \"string\"}, \"1.10\", \"1.10\"],\n+ [nullable, \"1984\", \"1984\"],\n+ [nullable, body, body],\n+ [nullable, r#\"\"q\"\"#, r#\"\"q\"\"#],\n+ [{\"oneOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}]}, \"true\", \"true\"],\n+ [{\"type\": [\"string\", \"null\"]}, \"1984\", \"1984\"],\n+ [{\"enum\": [\"1.10\", \"2.0\"]}, \"1.10\", \"1.10\"],\n+ [{\"const\": \"1.10\"}, \"1.10\", \"1.10\"],\n+ [{\"$ref\": \"#/$defs/S\"}, \"1984\", \"1984\"],\n+ [{\"allOf\": [{\"$ref\": \"#/$defs/S\"}]}, \"1.10\", \"1.10\"],\n+ [{\"allOf\": [{\"$ref\": \"#/$defs/S\"}, {\"description\": \"d\"}]}, \"1.10\", \"1.10\"],\n+ [{\"allOf\": [nullable, {\"type\": \"string\"}]}, \"null\", \"null\"],\n+ [{\"anyOf\": [{\"type\": \"integer\"}, {\"type\": \"string\"}]}, \"1.10\", \"1.10\"],\n+ [{\"type\": [\"number\", \"string\"]}, \"true\", \"true\"],\n+ // ...unless the value decodes to another admitted type\n+ [nullable, \"null\", null],\n+ [{\"anyOf\": [{\"type\": \"integer\"}, {\"type\": \"string\"}]}, \"25\", 25],\n+ [{\"type\": [\"number\", \"string\"]}, \"25\", 25],\n+ [{\"enum\": [1, \"a\"]}, \"1\", 1],\n+ [{\"type\": [\"number\", \"string\"], \"enum\": [1, \"x\"]}, \"1\", 1],\n+ [{\"allOf\": [{\"type\": [\"number\", \"string\"]}, {\"enum\": [1, \"x\"]}]}, \"1\", 1],\n+ [{\"allOf\": [{\"type\": [\"integer\", \"string\"]}, {\"type\": [\"number\", \"string\"]}]}, \"5\", 5],\n+ // no string admitted, or no type information: decode as before\n+ [{\"type\": \"integer\"}, \"1.10\", 1.1],\n+ [{\"description\": \"untyped\"}, \"25\", 25],\n+ [{\"anyOf\": [{\"type\": \"string\"}, {}]}, r#\"\"q\"\"#, \"q\"],\n+ [{\"type\": \"integer\", \"enum\": [\"1\"]}, \"1\", 1],\n+ ]);\n+ let defs = json!({\"S\": {\"type\": \"string\"}});\n+ for case in cases.as_array().unwrap() {\n+ let (schema, raw) = (&case[0], case[1].as_str().unwrap());\n+ let parameters =\n+ json!({\"properties\": {\"v\": schema}, \"additionalProperties\": schema, \"$defs\": defs});\n+ for key in [\"v\", \"other\"] {\n+ let value = convert_parameter_value(¶meters, key, raw.to_string());\n+ assert_eq!(value, case[2], \"{schema} {key} {raw:?}\");\n+ }\n+ }\n+ }\n }\ndiff --git a/vllm/tool_parsers/minicpm5xml_tool_parser.py b/vllm/tool_parsers/minicpm5xml_tool_parser.py\nindex 818b51c47f4f..08c93874fe10 100644\n--- a/vllm/tool_parsers/minicpm5xml_tool_parser.py\n+++ b/vllm/tool_parsers/minicpm5xml_tool_parser.py\n@@ -27,6 +27,11 @@\n Tool,\n ToolParser,\n )\n+from vllm.tool_parsers.schema_types import (\n+ ParameterTypes,\n+ ParameterTypesCache,\n+ convert_value,\n+)\n from vllm.tool_parsers.utils import partial_tag_overlap, safe_literal_eval\n from vllm.utils import random_uuid\n \n@@ -121,35 +126,19 @@ def _parse_arguments(json_value: str) -> tuple[Any, bool]:\n return json_value, False\n \n \n-def _get_argument_type(\n- func_name: str,\n- arg_key: str,\n- name_to_tool: dict[str, ChatCompletionToolsParam],\n-) -> str | None:\n- tool = name_to_tool.get(func_name)\n- if tool is None or tool.function.parameters is None:\n- return None\n- props = tool.function.parameters.get(\"properties\", {})\n- if arg_key not in props:\n- return None\n- return props[arg_key].get(\"type\")\n-\n-\n def _coerce_argument_value(\n func_name: str,\n arg_key: str,\n value: Any,\n- name_to_tool: dict[str, ChatCompletionToolsParam],\n+ param_types: dict[str, ParameterTypes],\n ) -> Any:\n- arg_type = _get_argument_type(func_name, arg_key, name_to_tool)\n- if arg_type == \"string\":\n- return (\n- value if isinstance(value, str) else json.dumps(value, ensure_ascii=False)\n- )\n+ props, extra = param_types.get(func_name, ({}, None))\n+ allowed = props.get(arg_key, extra)\n if isinstance(value, str):\n- parsed_val, _ = _parse_arguments(value)\n- return parsed_val\n- return value\n+ return convert_value(value, allowed, lambda v: _parse_arguments(v)[0])\n+ # Already decoded (wrapped arguments): serialize it where a string is meant.\n+ text = json.dumps(value, ensure_ascii=False)\n+ return convert_value(text, allowed, lambda _: value)\n \n \n def _add_argument(\n@@ -159,7 +148,7 @@ def _add_argument(\n arguments: dict[str, Any],\n seen_keys: set[str],\n allowed_props: set[str],\n- name_to_tool: dict[str, ChatCompletionToolsParam],\n+ param_types: dict[str, ParameterTypes],\n ) -> bool:\n \"\"\"Add one argument; return False if it violates the tool schema.\"\"\"\n # MiniCPM5 can emit OpenAI-style wrappers, e.g.\n@@ -181,7 +170,7 @@ def _add_argument(\n return False\n seen_keys.add(wrapped_key)\n arguments[wrapped_key] = _coerce_argument_value(\n- func_name, wrapped_key, wrapped_value, name_to_tool\n+ func_name, wrapped_key, wrapped_value, param_types\n )\n added = True\n return added\n@@ -191,7 +180,7 @@ def _add_argument(\n if key in seen_keys:\n return False\n seen_keys.add(key)\n- arguments[key] = _coerce_argument_value(func_name, key, val_text, name_to_tool)\n+ arguments[key] = _coerce_argument_value(func_name, key, val_text, param_types)\n return True\n \n \n@@ -275,13 +264,7 @@ def _normalize_alias_tool_call(\n \n def _build_tool_maps(\n tools: list[ChatCompletionToolsParam] | None,\n-) -> tuple[\n- set[str],\n- dict[str, set[str]],\n- dict[str, set[str]],\n- dict[str, ChatCompletionToolsParam],\n-]:\n- name_to_tool: dict[str, ChatCompletionToolsParam] = {}\n+) -> tuple[set[str], dict[str, set[str]], dict[str, set[str]]]:\n name_to_allowed_props: dict[str, set[str]] = {}\n name_to_required: dict[str, set[str]] = {}\n \n@@ -289,7 +272,6 @@ def _build_tool_maps(\n name = tool.function.name\n if not name:\n continue\n- name_to_tool[name] = tool\n params = tool.function.parameters or {}\n props = params.get(\"properties\", {}) if isinstance(params, dict) else {}\n name_to_allowed_props[name] = set(props.keys())\n@@ -305,12 +287,7 @@ def _build_tool_maps(\n )\n name_to_required[name] = set()\n \n- return (\n- set(name_to_tool.keys()),\n- name_to_allowed_props,\n- name_to_required,\n- name_to_tool,\n- )\n+ return set(name_to_allowed_props), name_to_allowed_props, name_to_required\n \n \n def _parse_function_block(\n@@ -318,7 +295,7 @@ def _parse_function_block(\n tool_names: set[str],\n name_to_allowed_props: dict[str, set[str]],\n name_to_required: dict[str, set[str]],\n- name_to_tool: dict[str, ChatCompletionToolsParam],\n+ param_types: dict[str, ParameterTypes],\n ) -> dict[str, Any] | None:\n \"\"\"Return {name, parameters} if block is valid, else None.\"\"\"\n func_name: str | None = None\n@@ -368,7 +345,7 @@ def _parse_function_block(\n arguments,\n seen_keys,\n allowed_props,\n- name_to_tool,\n+ param_types,\n ):\n has_invalid_param = True\n break\n@@ -401,7 +378,7 @@ def _parse_function_block(\n arguments,\n seen_keys,\n allowed_props,\n- name_to_tool,\n+ param_types,\n ):\n has_invalid_param = True\n break\n@@ -434,7 +411,7 @@ def _parse_partial_params(\n block: str,\n func_name: str,\n name_to_allowed_props: dict[str, set[str]],\n- name_to_tool: dict[str, ChatCompletionToolsParam],\n+ param_types: dict[str, ParameterTypes],\n ) -> dict[str, Any]:\n arguments: dict[str, Any] = {}\n seen_keys: set[str] = set()\n@@ -455,7 +432,7 @@ def _parse_partial_params(\n arguments,\n seen_keys,\n allowed_props,\n- name_to_tool,\n+ param_types,\n )\n return arguments\n \n@@ -472,6 +449,7 @@ def __init__(\n self.tool_call_start_token = \"\"\n self._processed_len = 0\n+ self._parameter_types_cache = ParameterTypesCache()\n \n def _reset_stream_state(self) -> None:\n self._processed_len = 0\n@@ -504,8 +482,8 @@ def extract_tool_calls(\n content=_strip_thinking_content(model_output),\n )\n \n- tool_names, name_to_allowed_props, name_to_required, name_to_tool = (\n- _build_tool_maps(request.tools)\n+ tool_names, name_to_allowed_props, name_to_required = _build_tool_maps(\n+ request.tools\n )\n \n tool_calls: list[ToolCall] = []\n@@ -523,7 +501,7 @@ def extract_tool_calls(\n tool_names,\n name_to_allowed_props,\n name_to_required,\n- name_to_tool,\n+ self._parameter_types_cache.for_tools(request.tools),\n )\n if parsed is not None:\n tool_calls.append(\n@@ -627,15 +605,15 @@ def _process_complete_block_streaming(\n block: str,\n request: ChatCompletionRequest,\n ) -> DeltaMessage | None:\n- tool_names, name_to_allowed_props, name_to_required, name_to_tool = (\n- _build_tool_maps(request.tools)\n+ tool_names, name_to_allowed_props, name_to_required = _build_tool_maps(\n+ request.tools\n )\n parsed = _parse_function_block(\n block,\n tool_names,\n name_to_allowed_props,\n name_to_required,\n- name_to_tool,\n+ self._parameter_types_cache.for_tools(request.tools),\n )\n if parsed is None:\n return DeltaMessage(content=block)\n@@ -690,9 +668,7 @@ def _process_partial_block_streaming(\n block: str,\n request: ChatCompletionRequest,\n ) -> DeltaMessage | None:\n- tool_names, name_to_allowed_props, _, name_to_tool = _build_tool_maps(\n- request.tools\n- )\n+ tool_names, name_to_allowed_props, _ = _build_tool_maps(request.tools)\n if _PARAM_MISSING_NAME_REGEX.search(block):\n return None\n \n@@ -710,7 +686,7 @@ def _process_partial_block_streaming(\n block,\n func_name,\n name_to_allowed_props,\n- name_to_tool,\n+ self._parameter_types_cache.for_tools(request.tools),\n )\n if not arguments:\n return None\ndiff --git a/vllm/tool_parsers/muse_tool_parser.py b/vllm/tool_parsers/muse_tool_parser.py\nindex 8b684889f94b..7f46c954c8cf 100644\n--- a/vllm/tool_parsers/muse_tool_parser.py\n+++ b/vllm/tool_parsers/muse_tool_parser.py\n@@ -62,6 +62,11 @@\n Tool,\n ToolParser,\n )\n+from vllm.tool_parsers.schema_types import (\n+ ParameterTypes,\n+ ParameterTypesCache,\n+ convert_value,\n+)\n \n logger = init_logger(__name__)\n \n@@ -198,6 +203,7 @@ def __init__(\n tools: list[Tool] | None = None,\n ) -> None:\n super().__init__(tokenizer, tools)\n+ self._parameter_types_cache = ParameterTypesCache()\n # Streaming cursors. vLLM constructs one ToolParser per request, so\n # instance state is per-stream.\n self._streamed_content_len: int = 0\n@@ -314,28 +320,12 @@ def _registered_names(request: ChatCompletionRequest | None) -> set[str]:\n names.add(name)\n return names\n \n- @classmethod\n- def _string_parameters(\n- cls, request: ChatCompletionRequest | ResponsesRequest | None\n- ) -> dict[str, set[str]]:\n- if not cls._preserve_string_parameters:\n- return {}\n- strings: dict[str, set[str]] = {}\n- for tool in getattr(request, \"tools\", None) or []:\n- function = getattr(tool, \"function\", None) or tool\n- if isinstance(function, dict):\n- name = function.get(\"name\")\n- parameters = function.get(\"parameters\")\n- else:\n- name = getattr(function, \"name\", None)\n- parameters = getattr(function, \"parameters\", None)\n- if name and isinstance(parameters, dict):\n- strings[name] = {\n- key\n- for key, schema in parameters.get(\"properties\", {}).items()\n- if isinstance(schema, dict) and schema.get(\"type\") == \"string\"\n- }\n- return strings\n+ def _parameter_types(\n+ self, request: ChatCompletionRequest | ResponsesRequest | None\n+ ) -> dict[str, ParameterTypes]:\n+ if not self._preserve_string_parameters:\n+ return {} # MuseGlimmer keeps legacy decoding, so it never walks.\n+ return self._parameter_types_cache.for_tools(getattr(request, \"tools\", None))\n \n @staticmethod\n def _normalize_name(emitted: str, registered: set[str]) -> str:\n@@ -369,7 +359,7 @@ def _parse_tool_calls(\n cls,\n text: str,\n registered: set[str] | None = None,\n- strings: dict[str, set[str]] | None = None,\n+ types: dict[str, ParameterTypes] | None = None,\n ) -> list[ToolCall]:\n registered = registered or set()\n scoped = cls._tool_channel_text(text)\n@@ -379,11 +369,11 @@ def _parse_tool_calls(\n if not name_m:\n continue\n name = cls._normalize_name(name_m.group(1), registered)\n- string_parameters = (strings or {}).get(name, set())\n+ props, extra = (types or {}).get(name, ({}, None))\n args: dict = {}\n for pm in _PARAM_RE.finditer(invoke):\n key, raw = pm.group(\"key\"), pm.group(\"value\")\n- args[key] = raw if key in string_parameters else _decode_value(raw)\n+ args[key] = convert_value(raw, props.get(key, extra), _decode_value)\n tool_calls.append(\n ToolCall(\n function=FunctionCall(\n@@ -422,7 +412,7 @@ def extract_tool_calls(\n try:\n registered = self._registered_names(request)\n tool_calls = self._parse_tool_calls(\n- model_output, registered, self._string_parameters(request)\n+ model_output, registered, self._parameter_types(request)\n )\n if not tool_calls:\n # A tool block was opened but no COMPLETE\n@@ -488,7 +478,7 @@ def extract_tool_calls_streaming(\n try:\n registered = self._registered_names(request)\n calls = self._parse_tool_calls(\n- current_text, registered, self._string_parameters(request)\n+ current_text, registered, self._parameter_types(request)\n )\n content, reasoning, content_open, reasoning_open = self._visible_channels(\n current_text\ndiff --git a/vllm/tool_parsers/poolside_v1_tool_parser.py b/vllm/tool_parsers/poolside_v1_tool_parser.py\nindex 998927264757..c8db45574d2f 100644\n--- a/vllm/tool_parsers/poolside_v1_tool_parser.py\n+++ b/vllm/tool_parsers/poolside_v1_tool_parser.py\n@@ -41,6 +41,7 @@\n Tool,\n ToolParser,\n )\n+from vllm.tool_parsers.schema_types import ParameterTypesCache, convert_value\n from vllm.tool_parsers.utils import safe_literal_eval\n \n logger = init_logger(__name__)\n@@ -91,6 +92,8 @@ def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n self.tool_call_end_token_id = self.vocab.get(self.tool_call_end_token)\n self._buffer: str = \"\"\n \n+ self._parameter_types_cache = ParameterTypesCache()\n+\n # Streaming state for incremental tool-call streaming\n self._in_tool_call: bool = False\n self._current_tool_name: str | None = None\n@@ -103,6 +106,7 @@ def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n \n @staticmethod\n def _deserialize(value: str) -> Any:\n+ value = value.strip()\n try:\n return json.loads(value)\n except json.JSONDecodeError:\n@@ -126,27 +130,13 @@ def _json_escape_string_content(s: str) -> str:\n return \"\"\n return json.dumps(s, ensure_ascii=False)[1:-1]\n \n- @staticmethod\n- def _is_string_type(\n- tool_name: str,\n- arg_name: str,\n- tools: list[Tool] | None,\n- ) -> bool:\n- if tools is None:\n- return False\n- for tool in tools:\n- # ChatCompletion tools nest under .function; Responses\n- [comment with results removed]\n- fn = getattr(tool, \"function\", tool)\n- if getattr(fn, \"name\", None) != tool_name:\n- continue\n- params = getattr(fn, \"parameters\", None)\n- if params is None:\n- return False\n- arg_type = params.get(\"properties\", {}).get(arg_name, {}).get(\"type\", None)\n- return arg_type == \"string\"\n- logger.debug(\"No tool named '%s'.\", tool_name)\n- return False\n+ def _allowed_types(\n+ self, tool_name: str, arg_name: str, tools: list[Tool] | None\n+ ) -> set[str] | None:\n+ \"\"\"JSON types the argument's schema admits; ``None`` if unconstrained.\"\"\"\n+ tool_types = self._parameter_types_cache.for_tools(tools)\n+ props, extra = tool_types.get(tool_name, ({}, None))\n+ return props.get(arg_name, extra)\n \n @staticmethod\n def _tools_enabled(request: ChatCompletionRequest) -> bool:\n@@ -214,10 +204,11 @@ def extract_tool_calls(\n arg_key = key.strip()\n # Keep string values verbatim; whitespace is significant\n # (e.g. code/file content). Only strip non-string types.\n- if self._is_string_type(tc_name, arg_key, request.tools):\n- arg_val = value\n- else:\n- arg_val = self._deserialize(value.strip())\n+ arg_val = convert_value(\n+ value,\n+ self._allowed_types(tc_name, arg_key, request.tools),\n+ self._deserialize,\n+ )\n logger.debug(\"arg_key = %s, arg_val = %s\", arg_key, arg_val)\n arg_dct[arg_key] = arg_val\n tool_calls.append(\n@@ -365,12 +356,12 @@ def extract_tool_calls_streaming(\n \n key = (self._pending_key or \"\").strip()\n \n- is_string = self._is_string_type(\n+ allowed = self._allowed_types(\n self._current_tool_name, key, request.tools\n )\n \n- if is_string:\n- # String type: stream incrementally\n+ if allowed == {\"string\"}:\n+ # String-only type: stream incrementally\n self._buffer = self._buffer[len(self.arg_val_start) :]\n \n if key in self._seen_keys[self.current_tool_id]:\n@@ -391,16 +382,19 @@ def extract_tool_calls_streaming(\n self._update_tool_args(pending_deltas, frag)\n continue\n \n- # Non-string type: wait for complete value\n+ # Other types, including nullable strings: wait for the\n+ # complete value, since e.g. \"null\" is not a string prefix.\n val_end = self._buffer.find(self.arg_val_end)\n if val_end == -1:\n break\n \n- raw_val = self._buffer[len(self.arg_val_start) : val_end].strip()\n+ raw_val = self._buffer[len(self.arg_val_start) : val_end]\n self._buffer = self._buffer[val_end + len(self.arg_val_end) :]\n self._pending_key = None\n \n- frag_or_none = self._append_arg_fragment(key=key, raw_val=raw_val)\n+ frag_or_none = self._append_arg_fragment(\n+ key=key, raw_val=raw_val, allowed=allowed\n+ )\n if frag_or_none:\n self._update_tool_args(pending_deltas, frag_or_none)\n continue\n@@ -573,6 +567,7 @@ def _append_arg_fragment(\n *,\n key: str,\n raw_val: str,\n+ allowed: set[str] | None,\n ) -> str | None:\n key = key.strip()\n if not key:\n@@ -580,9 +575,7 @@ def _append_arg_fragment(\n if key in self._seen_keys[self.current_tool_id]:\n return None\n \n- # This function is only called for non-string types (already checked\n- # by _is_string_type in the caller), so we always deserialize.\n- val_obj: Any = self._deserialize(raw_val)\n+ val_obj: Any = convert_value(raw_val, allowed, self._deserialize)\n \n key_json = json.dumps(key, ensure_ascii=False)\n val_json = json.dumps(val_obj, ensure_ascii=False)\ndiff --git a/vllm/tool_parsers/schema_types.py b/vllm/tool_parsers/schema_types.py\nnew file mode 100644\nindex 000000000000..06beea0dd0f5\n--- /dev/null\n+++ b/vllm/tool_parsers/schema_types.py\n@@ -0,0 +1,128 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+\"\"\"JSON types admitted by tool parameter schemas.\n+\n+XML-style tool parsers receive every argument as raw text. These helpers use\n+the parameter's schema to decide whether to keep that text or decode it.\n+\"\"\"\n+\n+from collections.abc import Callable, Iterable\n+from typing import Any\n+\n+# Types admitted by each listed parameter of one tool, and by any other\n+# parameter (additionalProperties). None means unconstrained.\n+ParameterTypes = tuple[dict[str, set[str] | None], set[str] | None]\n+\n+\n+def _json_type(value: Any) -> str:\n+ \"\"\"JSON Schema type name of a decoded JSON value.\"\"\"\n+ if value is None:\n+ return \"null\"\n+ if isinstance(value, bool):\n+ return \"boolean\"\n+ if isinstance(value, int):\n+ return \"integer\"\n+ if isinstance(value, float):\n+ return \"number\"\n+ if isinstance(value, list):\n+ return \"array\"\n+ if isinstance(value, dict):\n+ return \"object\"\n+ return \"string\"\n+\n+\n+def _schema_types(\n+ schema: Any, root: dict, refs: dict[str, set[str] | None]\n+) -> set[str] | None:\n+ \"\"\"JSON types a parameter schema admits, or ``None`` if it admits any.\n+\n+ Covers ``type``, ``const``, ``enum``, local ``$ref``, ``anyOf``/``oneOf``\n+ (union) and ``allOf`` (intersection), so that e.g. pydantic's\n+ ``Optional[str]`` counts as a string. *refs* memoizes each ``$ref``, which\n+ keeps the walk linear and ends cycles.\n+ \"\"\"\n+ if not isinstance(schema, dict):\n+ return None\n+ constraints: list[set[str] | None] = []\n+ declared = schema.get(\"type\")\n+ if isinstance(declared, str):\n+ constraints.append({declared})\n+ elif isinstance(declared, list):\n+ constraints.append({t for t in declared if isinstance(t, str)})\n+ if \"const\" in schema:\n+ constraints.append({_json_type(schema[\"const\"])})\n+ if isinstance(schema.get(\"enum\"), list):\n+ constraints.append({_json_type(v) for v in schema[\"enum\"]})\n+ ref = schema.get(\"$ref\")\n+ if isinstance(ref, str):\n+ if ref not in refs:\n+ refs[ref] = None # a ref still being resolved is unconstrained\n+ node = root if ref.startswith(\"#/\") else None # e.g. #/$defs/Name\n+ for part in ref[2:].split(\"/\"):\n+ if isinstance(node, dict):\n+ node = node.get(part.replace(\"~1\", \"/\").replace(\"~0\", \"~\"))\n+ refs[ref] = _schema_types(node, root, refs)\n+ constraints.append(refs[ref])\n+ for key in (\"anyOf\", \"oneOf\"):\n+ if isinstance(schema.get(key), list) and schema[key]:\n+ union: set[str] = set()\n+ for branch in schema[key]:\n+ if (types := _schema_types(branch, root, refs)) is None:\n+ break # an unconstrained branch admits anything\n+ union |= types\n+ else:\n+ constraints.append(union)\n+ if isinstance(schema.get(\"allOf\"), list):\n+ constraints.extend(_schema_types(s, root, refs) for s in schema[\"allOf\"])\n+ known = [ # an integer is also a number\n+ t | {\"integer\"} if \"number\" in t else t for t in constraints if t is not None\n+ ]\n+ return set.intersection(*known) if known else None\n+\n+\n+def parameter_types(tools: Iterable[Any] | None) -> dict[str, ParameterTypes]:\n+ \"\"\"Map tool name to :data:`ParameterTypes`, for Chat or flat Responses tools.\"\"\"\n+ types: dict[str, ParameterTypes] = {}\n+ for tool in tools or []:\n+ function = getattr(tool, \"function\", None) or tool\n+ if isinstance(function, dict):\n+ name, parameters = function.get(\"name\"), function.get(\"parameters\")\n+ else:\n+ name = getattr(function, \"name\", None)\n+ parameters = getattr(function, \"parameters\", None)\n+ if not name or not isinstance(parameters, dict):\n+ continue\n+ properties = parameters.get(\"properties\")\n+ if not isinstance(properties, dict):\n+ properties = {}\n+ refs: dict[str, set[str] | None] = {}\n+ types[name] = (\n+ {k: _schema_types(s, parameters, refs) for k, s in properties.items()},\n+ _schema_types(parameters.get(\"additionalProperties\"), parameters, refs),\n+ )\n+ return types\n+\n+\n+class ParameterTypesCache:\n+ \"\"\"Parameter types of the last tools list seen, built on first use.\"\"\"\n+\n+ _last: tuple[Any, dict[str, ParameterTypes]] = (None, {})\n+\n+ def for_tools(self, tools: Iterable[Any] | None) -> dict[str, ParameterTypes]:\n+ if tools is not self._last[0]:\n+ self._last = tools, parameter_types(tools)\n+ return self._last[1]\n+\n+\n+def convert_value(\n+ raw: str, allowed: set[str] | None, decode: Callable[[str], Any]\n+) -> Any:\n+ \"\"\"Decode *raw*, but keep the text if the schema admits a string, unless it\n+ decodes to another admitted type (``null`` for ``Optional[str]``).\n+ \"\"\"\n+ if allowed == {\"string\"}:\n+ return raw\n+ decoded = decode(raw)\n+ if allowed is None or \"string\" not in allowed:\n+ return decoded\n+ return decoded if _json_type(decoded) in allowed - {\"string\"} else raw\n\ndiff --git a/tests/tool_parsers/test_minicpm5xml_tool_parser.py b/tests/tool_parsers/test_minicpm5xml_tool_parser.py\nindex d60a6f46d946..e67a4cbb3427 100644\n--- a/tests/tool_parsers/test_minicpm5xml_tool_parser.py\n+++ b/tests/tool_parsers/test_minicpm5xml_tool_parser.py\n@@ -792,3 +792,27 @@ def test_cdata_whitespace_preserved_streaming(self, parser: ToolParser) -> None:\n assert json.loads(reconstructor.tool_calls[0].function.arguments) == {\n \"content\": \" def foo():\\n pass\\n\"\n }\n+\n+\n+@pytest.mark.parametrize(\"stream\", [False, True])\n+@pytest.mark.parametrize(\n+ (\"param\", \"expected\"),\n+ [\n+ ('1.10', \"1.10\"),\n+ ('null', None),\n+ ('{\"v\": 1984}', \"1984\"),\n+ ],\n+)\n+def test_nullable_string_keeps_raw_text(\n+ parser: ToolParser, param: str, expected, stream: bool\n+) -> None:\n+ schema = {\"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}]}\n+ request = make_request([_tool(\"f\", {\"properties\": {\"v\": schema}})])\n+ text = f'{param}'\n+ if stream:\n+ calls = run_tool_extraction_streaming(\n+ parser, list(text), request, assert_one_tool_per_delta=False\n+ ).tool_calls\n+ else:\n+ calls = parser.extract_tool_calls(text, request).tool_calls\n+ assert [json.loads(call.function.arguments) for call in calls] == [{\"v\": expected}]\ndiff --git a/tests/tool_parsers/test_poolside_v1_tool_parser.py b/tests/tool_parsers/test_poolside_v1_tool_parser.py\nindex 635081b43b37..6a763a5c9106 100644\n--- a/tests/tool_parsers/test_poolside_v1_tool_parser.py\n+++ b/tests/tool_parsers/test_poolside_v1_tool_parser.py\n@@ -23,15 +23,17 @@\n import json\n from typing import Any\n \n+import pytest\n from openai.types.responses.tool_param import FunctionToolParam\n \n+from tests.tool_parsers.utils import run_tool_extraction_streaming\n from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest\n from vllm.entrypoints.openai.responses.protocol import ResponsesRequest\n from vllm.tool_parsers.poolside_v1_tool_parser import PoolsideV1ToolParser\n \n \n def _write_file_tool() -> dict[str, Any]:\n- \"\"\"Tool with a string arg (``content``) and a non-string arg (``mode``).\"\"\"\n+ \"\"\"Tool with string (``content``), integer and nullable string args.\"\"\"\n return {\n \"type\": \"function\",\n \"function\": {\n@@ -42,6 +44,7 @@ def _write_file_tool() -> dict[str, Any]:\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"mode\": {\"type\": \"integer\"},\n+ \"note\": {\"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}]},\n },\n \"required\": [\"content\"],\n },\n@@ -100,6 +103,9 @@ class _StubTokenizer:\n def get_vocab(self) -> dict[str, int]:\n return {\"\": 151_657, \"\": 151_658}\n \n+ def tokenize(self, text: str) -> list[str]:\n+ return []\n+\n \n def _make_parser(request: ChatCompletionRequest) -> PoolsideV1ToolParser:\n return PoolsideV1ToolParser(_StubTokenizer(), tools=request.tools)\n@@ -217,7 +223,7 @@ def test_non_string_arg_still_deserialized() -> None:\n \n def test_responses_extract_tool_calls_with_flat_tools() -> None:\n # required/named Responses calls route into extract_tool_calls with flat\n- # FunctionTool (.name); _is_string_type must not raise.\n+ # FunctionTool (.name); _allowed_types must not raise.\n request = _build_responses_request(tool_choice=\"required\")\n parser = PoolsideV1ToolParser(_StubTokenizer(), tools=request.tools)\n \n@@ -364,3 +370,21 @@ def test_streaming_responses_request_with_logprobs_emits_empty_delta() -> None:\n result = _stream_partial_start_token(request)\n assert result is not None\n assert result.content == \"\"\n+\n+\n+@pytest.mark.parametrize(\"stream\", [False, True])\n+@pytest.mark.parametrize(\n+ (\"raw\", \"expected\"), [(\" 1.10\\n\", \" 1.10\\n\"), (\" null \", None)]\n+)\n+def test_nullable_string_keeps_raw_text(raw: str, expected: Any, stream: bool) -> None:\n+ request = _build_chat_request(tool_choice=\"auto\")\n+ parser = _make_parser(request)\n+ output = (\n+ \"write_file\\nnote\"\n+ f\"{raw}\"\n+ )\n+ if stream:\n+ calls = run_tool_extraction_streaming(parser, list(output), request).tool_calls\n+ else:\n+ calls = parser.extract_tool_calls(output, request).tool_calls\n+ assert [json.loads(c.function.arguments) for c in calls] == [{\"note\": expected}]\ndiff --git a/tests/tool_parsers/test_schema_types.py b/tests/tool_parsers/test_schema_types.py\nnew file mode 100644\nindex 000000000000..e1d3c8ee2c2e\n--- /dev/null\n+++ b/tests/tool_parsers/test_schema_types.py\n@@ -0,0 +1,65 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+import json\n+\n+import pytest\n+\n+from vllm.tool_parsers.schema_types import convert_value, parameter_types\n+\n+_NULLABLE_STR = {\"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}]}\n+_INT_OR_STR = {\"anyOf\": [{\"type\": \"integer\"}, {\"type\": \"string\"}]}\n+_BODY = '{\\n \"version\": \"1.4.0\",\\n \"build\": 7\\n}'\n+_DEFS = {\n+ \"S\": {\"type\": \"string\"},\n+ \"C\": {\"allOf\": [{\"$ref\": \"#/$defs/C\"}, {\"type\": \"string\"}]},\n+ # Each def references the next one twice: 2**60 paths without memoization.\n+ **{f\"D{i}\": {\"anyOf\": [{\"$ref\": f\"#/$defs/D{i + 1}\"}] * 2} for i in range(60)},\n+ \"D60\": {\"type\": \"string\"},\n+}\n+\n+\n+@pytest.mark.parametrize(\n+ (\"schema\", \"raw\", \"expected\"),\n+ [\n+ # plain string and non-string types: unchanged\n+ ({\"type\": \"string\"}, \"1.10\", \"1.10\"),\n+ ({\"type\": \"integer\"}, \"1.10\", 1.1),\n+ # schemas that admit a string keep the raw text...\n+ (_NULLABLE_STR, \"1.10\", \"1.10\"),\n+ (_NULLABLE_STR, \"1984\", \"1984\"),\n+ (_NULLABLE_STR, _BODY, _BODY),\n+ (_NULLABLE_STR, '\"q\"', '\"q\"'),\n+ ({\"oneOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}]}, \"true\", \"true\"),\n+ ({\"type\": [\"string\", \"null\"]}, \"1984\", \"1984\"),\n+ ({\"enum\": [\"1.10\", \"2.0\"]}, \"1.10\", \"1.10\"),\n+ ({\"const\": \"1.10\"}, \"1.10\", \"1.10\"),\n+ ({\"$ref\": \"#/$defs/S\"}, \"1984\", \"1984\"),\n+ ({\"allOf\": [{\"$ref\": \"#/$defs/S\"}, {\"description\": \"d\"}]}, \"1.10\", \"1.10\"),\n+ ({\"$ref\": \"#/$defs/C\"}, \"1.10\", \"1.10\"),\n+ ({\"allOf\": [_NULLABLE_STR, {\"type\": \"string\"}]}, \"null\", \"null\"),\n+ ({\"$ref\": \"#/$defs/D0\"}, \"1.10\", \"1.10\"),\n+ (_INT_OR_STR, \"1.10\", \"1.10\"),\n[... diff truncated: 1 more file(s) not shown]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][LoRA] Fix KeyError crash when a LoRA name is reloaded with requests in flight\nLabels: bug, verified\nFiles changed (2): tests/lora/test_lora_functions.py, vllm/lora/request.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #64570. This change compares both `lora_name` and `lora_int_id` in `LoRARequest`, so reloading an adapter under the same name while old requests are still running no longer kills the engine.\n\n## Claims\n\n- Fixes the `KeyError` in `convert_mapping` → `EngineDeadError` reported in #64570.\n- In-flight requests keep using the old adapter, while new requests use the reloaded one.\n\n## Validation\n[results removed]\n## Details\n\n`LoRARequest` currently compares only adapter names. If an adapter is unloaded and reloaded under the same name while old requests are still running, the worker can treat the old and new IDs as one adapter. The missing ID then causes `convert_mapping` to raise `KeyError`, killing the engine.\n\nThis does not change when unload takes effect or whether it waits for in-flight requests.\n\nNot a duplicate: no open PR references #64570 or changes `LoRARequest` equality. I searched open PRs by the issue number and by `convert_mapping`, `LoRARequest`, `unload_lora_adapter` and `make_lora_inputs`.\n\nAI assistance: Claude Code helped prepare this PR. I reviewed the changes and ran the tests above.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/lora/request.py b/vllm/lora/request.py\nindex 36c6881270cc..ee5288833421 100644\n--- a/vllm/lora/request.py\n+++ b/vllm/lora/request.py\n@@ -54,16 +54,15 @@ def path(self):\n return self.lora_path\n \n def __eq__(self, value: object) -> bool:\n- \"\"\"Overrides the equality method to compare LoRARequest\n- instances based on lora_name. This allows for identification\n- and comparison lora adapter across engines.\n+ \"\"\"Compares lora_name and lora_int_id. A name loaded again at runtime\n+ gets a new lora_int_id while requests for the old one may still be\n+ running, and the engine needs both adapters active.\n \"\"\"\n- return isinstance(value, self.__class__) and self.lora_name == value.lora_name\n+ return (\n+ isinstance(value, self.__class__)\n+ and self.lora_name == value.lora_name\n+ and self.lora_int_id == value.lora_int_id\n+ )\n \n def __hash__(self) -> int:\n- \"\"\"Overrides the hash method to hash LoRARequest instances\n- based on lora_name. This ensures that LoRARequest instances\n- can be used in hash-based collections such as sets and dictionaries,\n- identified by their names across engines.\n- \"\"\"\n- return hash(self.lora_name)\n+ return hash((self.lora_name, self.lora_int_id))\n\ndiff --git a/tests/lora/test_lora_functions.py b/tests/lora/test_lora_functions.py\nindex 5bd3ed6b045b..c959e0d21d33 100644\n--- a/tests/lora/test_lora_functions.py\n+++ b/tests/lora/test_lora_functions.py\n@@ -4,6 +4,7 @@\n \n import pytest\n \n+from vllm import LLM, SamplingParams\n from vllm.engine.arg_utils import AsyncEngineArgs, EngineArgs\n from vllm.entrypoints.launchers.api_server.entry import (\n build_async_engine_client_from_engine_args,\n@@ -116,3 +117,35 @@ async def run_check(fn, args, expected: list):\n await run_check(llm.remove_lora, 12, [10, 11])\n await run_check(llm.remove_lora, 11, [10])\n await run_check(llm.remove_lora, 10, [])\n+\n+\n+def test_same_lora_name_with_different_ids(\n+ qwen3_meowing_lora_files, qwen3_woofing_lora_files\n+):\n+ \"\"\"An adapter unloaded and loaded again under the same name gets a new id\n+ while requests for the old id may still be running; each request in the\n+ shared batch must use its own adapter.\"\"\"\n+ llm = LLM(\n+ model=MODEL_PATH,\n+ enable_lora=True,\n+ max_loras=2,\n+ max_lora_rank=LORA_RANK,\n+ max_model_len=128,\n+ gpu_memory_utilization=0.8,\n+ enforce_eager=True,\n+ )\n+ messages = [\n+ {\"role\": \"system\", \"content\": \"Follow the instructions to make animal noises\"},\n+ {\"role\": \"user\", \"content\": \"Make your favorite animal noise.\"},\n+ ]\n+ outputs = llm.chat(\n+ [messages, messages],\n+ SamplingParams(temperature=0, max_tokens=10),\n+ chat_template_kwargs={\"enable_thinking\": False},\n+ lora_request=[\n+ LoRARequest(\"pet\", 1, qwen3_meowing_lora_files),\n+ LoRARequest(\"pet\", 2, qwen3_woofing_lora_files),\n+ ],\n+ )\n+ assert \"Meow Meow Meow\" in outputs[0].outputs[0].text\n+ assert \"Woof Woof Woof\" in outputs[1].outputs[0].text\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][UMBP] Copy every KV cache layout's per-head runs\nLabels: bug, rocm, ready, ci/build, kv-connector\nFiles changed (3): tests/v1/kv_connector/unit/test_umbp_embedded.py, vllm/distributed/kv_transfer/kv_connector/v1/umbp/data.py, vllm/distributed/kv_transfer/kv_connector/v1/umbp/runtime/embedded.py\n\n## Description (results removed)\n\n- Split each layer's page into per-head runs in `data.py`, using the allocator's `compute_layout_strides`.\n- Register the same runs in the `embedded.py` bulk path, falling back to per-range copies for a group whose stride doesn't match.\n- Round-trip all 6 layouts through the bulk and range paths in `test_umbp_embedded.py`.\n\n## Diff\n\n```diff\ndiff --git a/vllm/distributed/kv_transfer/kv_connector/v1/umbp/data.py b/vllm/distributed/kv_transfer/kv_connector/v1/umbp/data.py\nindex 3535facf0416..07383763b3b3 100644\n--- a/vllm/distributed/kv_transfer/kv_connector/v1/umbp/data.py\n+++ b/vllm/distributed/kv_transfer/kv_connector/v1/umbp/data.py\n@@ -10,6 +10,7 @@\n from __future__ import annotations\n \n import hashlib\n+import itertools\n import json\n from collections.abc import Sequence\n from dataclasses import dataclass, field, replace\n@@ -28,8 +29,12 @@\n KVCacheConfig,\n KVCacheGroupSpec,\n KVCacheSpec,\n+ KVCacheTensor,\n UniformTypeKVCacheSpecs,\n+ compute_layer_kv_cache_shape_bytes,\n+ compute_layout_strides,\n )\n+from vllm.v1.kv_cache_layout import KVCacheLayout\n \n \n def _layer_specs(group: KVCacheGroupSpec) -> dict[str, KVCacheSpec]:\n@@ -40,6 +45,43 @@ def _layer_specs(group: KVCacheGroupSpec) -> dict[str, KVCacheSpec]:\n return dict.fromkeys(group.layer_names, spec)\n \n \n+def _page_segments(\n+ spec: KVCacheSpec,\n+ tensor: KVCacheTensor,\n+ num_blocks: int,\n+ layout: KVCacheLayout,\n+) -> tuple[tuple[int, int], ...]:\n+ \"\"\"Byte ``(offset, length)`` runs of a layer's page from its block start.\n+\n+ Empty when the page is one contiguous run. LHBNC and BHLNC store each\n+ head's tokens as a separate run.\n+ \"\"\"\n+ if not spec.has_layer_views:\n+ return ()\n+ _, heads, states, content = compute_layer_kv_cache_shape_bytes(spec, num_blocks)\n+ _, _, head_stride, state_stride, _ = compute_layout_strides(\n+ spec,\n+ num_blocks,\n+ len(tensor.layers),\n+ layout,\n+ fixed_strides=(tensor.layer_stride, tensor.block_stride, None, None, None),\n+ )\n+ dims = sorted(\n+ (stride, size)\n+ for stride, size in ((head_stride, heads), (state_stride, states))\n+ if size > 1\n+ )\n+ run = content\n+ while dims and dims[0][0] == run:\n+ run *= dims.pop(0)[1]\n+ if not dims:\n+ return ()\n+ return tuple(\n+ (sum(i * stride for i, (stride, _) in zip(index, dims)), run)\n+ for index in itertools.product(*(range(size) for _, size in dims))\n+ )\n+\n+\n def _spec_fingerprint(spec: KVCacheSpec) -> dict[str, str]:\n \"\"\"Every field that shapes a layer's stored bytes, in a stable form.\"\"\"\n return {\n@@ -266,13 +308,20 @@ class KVRegion:\n block_bytes: int\n object_offset: int\n block_size: int = 1\n+ segments: tuple[tuple[int, int], ...] = ()\n \n def __post_init__(self) -> None:\n if self.block_stride <= 0 or self.block_bytes <= 0:\n raise ValueError(\"KV region sizes must be positive\")\n if self.block_size <= 0:\n raise ValueError(\"KV region block_size must be positive\")\n- if self.block_bytes > self.block_stride:\n+ if self.segments:\n+ if sum(length for _, length in self.segments) != self.block_bytes:\n+ raise ValueError(\n+ f\"KV region segments of {self.layer_name!r} do not cover \"\n+ f\"its {self.block_bytes} bytes\"\n+ )\n+ elif self.block_bytes > self.block_stride:\n raise ValueError(\n f\"KV region bytes ({self.block_bytes}) exceed its stride \"\n f\"({self.block_stride}) for {self.layer_name!r}\"\n@@ -319,6 +368,7 @@ def from_kv_cache_config(cls, config: KVCacheConfig) -> KVLayoutPlanner:\n if group.enable_kv_transfer\n for layer, spec in _layer_specs(group).items()\n }\n+ layout = config.kv_cache_layout\n regions: list[KVRegion] = []\n offset = 0\n for tensor in config.kv_cache_tensors:\n@@ -327,6 +377,21 @@ def from_kv_cache_config(cls, config: KVCacheConfig) -> KVLayoutPlanner:\n continue\n group_id, spec = layer_specs[layer_name]\n block_bytes = spec.page_size_bytes\n+ segments = (\n+ ()\n+ if layout is None\n+ else _page_segments(\n+ spec, tensor, config.num_blocks, KVCacheLayout[layout]\n+ )\n+ )\n+ if not segments and (\n+ block_bytes > tensor.block_stride\n+ or (len(tensor.layers) > 1 and tensor.layer_stride < block_bytes)\n+ ):\n+ raise ValueError(\n+ f\"UMBP cannot copy {layer_name!r}: its KV block is split \"\n+ \"into strided runs and KVCacheConfig.kv_cache_layout is unset\"\n+ )\n regions.append(\n KVRegion(\n layer_name=layer_name,\n@@ -335,6 +400,7 @@ def from_kv_cache_config(cls, config: KVCacheConfig) -> KVLayoutPlanner:\n block_bytes=block_bytes,\n object_offset=offset,\n block_size=spec.block_size,\n+ segments=segments,\n )\n )\n offset += block_bytes\n@@ -371,6 +437,11 @@ def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]) -> None:\n for region in self.regions:\n if region.layer_name != layer_name:\n continue\n+ if region.segments and block_stride != region.block_stride:\n+ raise ValueError(\n+ f\"KV block stride mismatch for {layer_name!r}: \"\n+ f\"config={region.block_stride}, tensor={block_stride}\"\n+ )\n if (\n block_stride > region.block_stride\n or region.block_stride % block_stride != 0\n@@ -458,6 +529,25 @@ def _ranges_for_block(\n physical_stride = self._physical_strides.get(\n region.layer_name, region.block_stride\n )\n+ if region.segments:\n+ start = object_offset if group_id is not None else region.object_offset\n+ for segment_offset, length in region.segments:\n+ ranges.append(\n+ KVRange(\n+ layer_name=region.layer_name,\n+ group_id=region.group_id,\n+ block_id=block_id,\n+ base_address=base_address\n+ + block_id * region.block_stride\n+ + segment_offset,\n+ stride=region.block_stride,\n+ length=length,\n+ object_offset=start,\n+ )\n+ )\n+ start += length\n+ object_offset += region.block_bytes\n+ continue\n if region.block_bytes <= physical_stride:\n ranges.append(\n KVRange(\ndiff --git a/vllm/distributed/kv_transfer/kv_connector/v1/umbp/runtime/embedded.py b/vllm/distributed/kv_transfer/kv_connector/v1/umbp/runtime/embedded.py\nindex 818e9ab37cef..be0d9ed69939 100644\n--- a/vllm/distributed/kv_transfer/kv_connector/v1/umbp/runtime/embedded.py\n+++ b/vllm/distributed/kv_transfer/kv_connector/v1/umbp/runtime/embedded.py\n@@ -398,6 +398,16 @@ def _register_load_layouts(self, kv_caches: dict[str, torch.Tensor]) -> None:\n if cache is None or cache.ndim == 0:\n break\n stride = cache.stride(0) * cache.element_size()\n+ if region.segments:\n+ if stride != region.block_stride:\n+ break\n+ for segment_offset, length in region.segments:\n+ bases.append(cache.data_ptr() + segment_offset)\n+ strides.append(stride)\n+ offsets.append(sum(sizes))\n+ sizes.append(length)\n+ counts.append(cache.shape[0])\n+ continue\n if (\n stride <= 0\n or stride > region.block_stride\n\ndiff --git a/tests/v1/kv_connector/unit/test_umbp_embedded.py b/tests/v1/kv_connector/unit/test_umbp_embedded.py\nindex 5054b2582936..9a66b79bbeb5 100644\n--- a/tests/v1/kv_connector/unit/test_umbp_embedded.py\n+++ b/tests/v1/kv_connector/unit/test_umbp_embedded.py\n@@ -1,6 +1,7 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import ctypes\n import importlib.util\n import sys\n import threading\n@@ -55,6 +56,8 @@\n UMBPStoreConnectorWorker,\n )\n from vllm.platforms import current_platform\n+from vllm.utils.torch_utils import set_random_seed\n+from vllm.v1.core.kv_cache_planning import get_kv_cache_config_from_groups\n from vllm.v1.kv_cache_interface import (\n FullAttentionSpec,\n KVCacheConfig,\n@@ -62,7 +65,9 @@\n KVCacheTensor,\n SlidingWindowSpec,\n )\n+from vllm.v1.kv_cache_layout import KVCacheLayout\n from vllm.v1.request import RequestStatus\n+from vllm.v1.worker.utils import allocate_kv_cache\n \n mori_available = importlib.util.find_spec(\"mori\") is not None\n \n@@ -147,6 +152,99 @@ def put(keys, object_sizes, pointers, sizes, offsets):\n handle.close()\n \n \n+@pytest.mark.parametrize(\"bulk\", [True, False], ids=[\"bulk\", \"ranges\"])\n+@pytest.mark.parametrize(\"layout\", list(KVCacheLayout), ids=lambda x: x.name)\n+def test_every_kv_cache_layout_restores_blocks_exactly(\n+ monkeypatch, socket_dir, layout, bulk\n+):\n+ \"\"\"Restoring a stored block equals copying each layer's block, whatever the\n+ layout interleaves with it (LHBNC and BHLNC split pages per head).\"\"\"\n+ shape = dict(block_size=16, num_kv_heads=2, head_size=16, dtype=torch.float16)\n+ groups = [\n+ KVCacheGroupSpec([\"a0\", \"a1\"], FullAttentionSpec(**shape)),\n+ KVCacheGroupSpec([\"s0\", \"s1\"], SlidingWindowSpec(**shape, sliding_window=32)),\n+ ]\n+ planner_config = SimpleNamespace(\n+ cache_config=SimpleNamespace(\n+ get_resolved_kv_cache_layout=lambda: layout,\n+ num_gpu_blocks_override=4,\n+ prefix_cache_retention_interval=None,\n+ ),\n+ attention_config=SimpleNamespace(hisparse_config=None),\n+ )\n+ config = get_kv_cache_config_from_groups(planner_config, groups, 1 << 30)\n+ config.kv_cache_layout = layout.name\n+ kv_caches = allocate_kv_cache(config, torch.device(\"cpu\"), layout)\n+\n+ objects: dict[str, bytes] = {}\n+\n+ def put(keys, object_sizes, pointers, sizes, offsets):\n+ for key, size, *ranges in zip(keys, object_sizes, pointers, sizes, offsets):\n+ value = bytearray(size)\n+ for pointer, length, offset in zip(*ranges):\n+ value[offset : offset + length] = ctypes.string_at(pointer, length)\n+ objects[key] = bytes(value)\n+ return [True] * len(keys)\n+\n+ def get(keys, pointers, sizes, offsets):\n+ for key, *ranges in zip(keys, pointers, sizes, offsets):\n+ for pointer, length, offset in zip(*ranges):\n+ ctypes.memmove(pointer, objects[key][offset : offset + length], length)\n+ return [True] * len(keys)\n+\n+ monkeypatch.setitem(\n+ sys.modules,\n+ \"mori.cpp\",\n+ SimpleNamespace(MemoryLocationType=SimpleNamespace(CPU=0, GPU=1)),\n+ )\n+ client = SimpleNamespace(\n+ register_memory=lambda *a: True,\n+ deregister_memory=lambda *a: True,\n+ batch_get_ranges_into_ptr=get,\n+ batch_put_ranges_from_ptr=put,\n+ flush=lambda: True,\n+ close=lambda: None,\n+ )\n+ planner = KVLayoutPlanner.from_kv_cache_config(config)\n+ handle = _MoriWorkerHandle(\n+ client,\n+ \"layouts\",\n+ RankTopology(),\n+ socket_dir,\n+ 1,\n+ 5,\n+ planner.describe(RankTopology()),\n+ )\n+ try:\n+ UMBPStoreConnectorWorker(handle, planner).register_kv_caches(kv_caches)\n+ raw = torch.empty(0, dtype=torch.int8).set_(\n+ next(iter(kv_caches.values())).untyped_storage()\n+ )\n+ set_random_seed(0)\n+ raw.copy_(torch.randint(-128, 128, raw.shape, dtype=torch.int8))\n+ before = raw.clone()\n+ for cache in kv_caches.values():\n+ cache[3].copy_(cache[1])\n+ expected = raw.clone()\n+ raw.copy_(before)\n+\n+ def transfer(store, block_id):\n+ plans = [BlockTransferPlan(f\"g{g}\", block_id, group_id=g) for g in (0, 1)]\n+ if bulk:\n+ job = (handle.store_blocks if store else handle.load_blocks)(plans)\n+ assert job is not None\n+ else:\n+ plans = [planner.materialize(plan) for plan in plans]\n+ job = (handle.store if store else handle.load)(plans)\n+ assert handle.wait(job).status is TransferJobStatus.COMPLETED\n+\n+ transfer(True, 1)\n+ transfer(False, 3)\n+ assert torch.equal(raw, expected)\n+ finally:\n+ handle.close()\n+\n+\n @pytest.mark.parametrize(\"batched\", [False, True])\n def test_bulk_load_preserves_group_order_failures_and_new_buffers(\n bulk_worker, batched, monkeypatch\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][UMBP] Copy every KV cache layout's per-head runs\nLabels: bug, rocm, ready, ci/build, kv-connector\nFiles changed (3): tests/v1/kv_connector/unit/test_umbp_embedded.py, vllm/distributed/kv_transfer/kv_connector/v1/umbp/data.py, vllm/distributed/kv_transfer/kv_connector/v1/umbp/runtime/embedded.py\n\n## Description (results removed)\n\n- Split each layer's page into per-head runs in `data.py`, using the allocator's `compute_layout_strides`.\n- Register the same runs in the `embedded.py` bulk path, falling back to per-range copies for a group whose stride doesn't match.\n- Round-trip all 6 layouts through the bulk and range paths in `test_umbp_embedded.py`.\n\n## Diff\n\n```diff\ndiff --git a/.buildkite/test-amd.yaml b/.buildkite/test-amd.yaml\nindex 89f0a9c14960..a3297e4b1ecd 100644\n--- a/.buildkite/test-amd.yaml\n+++ b/.buildkite/test-amd.yaml\n@@ -4160,6 +4160,8 @@ steps:\n - vllm/v1/kv_offload/\n - vllm/v1/simple_kv_offload/\n - tests/evals/gsm8k/test_gsm8k_offloading.py\n+ - vllm/distributed/kv_transfer/kv_connector/v1/umbp/\n+ - tests/v1/kv_connector/umbp_test_utils.py\n - vllm/platforms/rocm.py\n commands:\n - pytest -s -v evals/gsm8k/test_gsm8k_offloading.py -k \"nemotron-h-8b or gemma-4-e4b-it\"\n@@ -5600,6 +5602,9 @@ steps:\n - vllm/v1/kv_cache_interface.py\n - tests/v1/kv_connector/unit/test_umbp_\n - tests/v1/kv_connector/umbp_test_utils.py\n+ - tests/v1/kv_connector/unit/utils.py\n+ - tests/v1/kv_connector/conftest.py\n+ - docker/Dockerfile.rocm_base\n commands:\n - export VLLM_WORKER_MULTIPROC_METHOD=spawn\n # Fail loudly instead of skipping every test if the image lacks mori.\n@@ -5800,6 +5805,26 @@ steps:\n - export VLLM_WORKER_MULTIPROC_METHOD=spawn\n - pytest -v -s -m 'not distributed' tests/v1/kv_connector/extract_hidden_states_integration\n \n+- label: \":amd: (MI355 DPX) UMBP Connector Integration\"\n+ timeout_in_minutes: 30\n+ mirror_hardwares: [amdexperimental, amdproduction, amdgfx950nightly, amdmi355]\n+ dind: false\n+ agent_pool: mi355_dpx\n+ num_gpus: 1\n+ optional: true\n+ working_dir: \"/vllm-workspace/tests\"\n+ source_file_dependencies:\n+ - vllm/distributed/kv_transfer/kv_connector/v1/umbp/\n+ - vllm/distributed/kv_transfer/kv_connector/v1/base.py\n+ - tests/v1/kv_connector/umbp_integration/\n+ - tests/v1/kv_connector/umbp_test_utils.py\n+ - tests/v1/kv_connector/conftest.py\n+ - tests/v1/kv_connector/rocm_pd_accuracy_utils.py\n+ - docker/Dockerfile.rocm_base\n+ commands:\n+ - export VLLM_WORKER_MULTIPROC_METHOD=spawn\n+ - pytest -v -s -rs v1/kv_connector/umbp_integration\n+\n - label: \":amd: (MI355 DPX) V1 Attention Shard %N\" # TBD\n timeout_in_minutes: 125\n mirror_hardwares: [amdexperimental, amdproduction, amdgfx950nightly, amdmi355]\ndiff --git a/.buildkite/test_areas/lm_eval.yaml b/.buildkite/test_areas/lm_eval.yaml\nindex 6bbe79232c0d..63d0240dad61 100644\n--- a/.buildkite/test_areas/lm_eval.yaml\n+++ b/.buildkite/test_areas/lm_eval.yaml\n@@ -1341,6 +1341,8 @@ steps:\n - vllm/v1/kv_offload/\n - vllm/v1/simple_kv_offload/\n - tests/evals/gsm8k/test_gsm8k_offloading.py\n+ - vllm/distributed/kv_transfer/kv_connector/v1/umbp/\n+ - tests/v1/kv_connector/umbp_test_utils.py\n - vllm/platforms/rocm.py\n \n - label: \":nvidia: (H100) LM Eval KV-Offload Medium\"\ndiff --git a/.buildkite/test_areas/misc.yaml b/.buildkite/test_areas/misc.yaml\nindex 47aa69b98461..c011d8ba8fc8 100644\n--- a/.buildkite/test_areas/misc.yaml\n+++ b/.buildkite/test_areas/misc.yaml\n@@ -210,10 +210,34 @@ steps:\n - vllm/v1/kv_cache_interface.py\n - tests/v1/kv_connector/unit/test_umbp_\n - tests/v1/kv_connector/umbp_test_utils.py\n+ - tests/v1/kv_connector/unit/utils.py\n+ - tests/v1/kv_connector/conftest.py\n+ - docker/Dockerfile.rocm_base\n commands:\n - export VLLM_WORKER_MULTIPROC_METHOD=spawn\n - pytest -v -s -rs v1/kv_connector/unit/test_umbp_*.py\n \n+- label: \":amd: (MI355 DPX) UMBP Connector Integration\"\n+ key: amd-umbp-connector-integration-mi355\n+ dind: false\n+ device: mi355_dpx\n+ num_devices: 1\n+ timeout_in_minutes: 30\n+ working_dir: /vllm-workspace/tests\n+ depends_on:\n+ - image-build-amd\n+ source_file_dependencies:\n+ - vllm/distributed/kv_transfer/kv_connector/v1/umbp/\n+ - vllm/distributed/kv_transfer/kv_connector/v1/base.py\n+ - tests/v1/kv_connector/umbp_integration/\n+ - tests/v1/kv_connector/umbp_test_utils.py\n+ - tests/v1/kv_connector/conftest.py\n+ - tests/v1/kv_connector/rocm_pd_accuracy_utils.py\n+ - docker/Dockerfile.rocm_base\n+ commands:\n+ - export VLLM_WORKER_MULTIPROC_METHOD=spawn\n+ - pytest -v -s -rs v1/kv_connector/umbp_integration\n+\n # Single-node MoRIIO P/D on dummy weights, WRITE and READ mode: prefill and\n # decode on separate GPUs over xGMI, compared exactly against a direct serve.\n # Disabled until the KV connectors installation is locked.\ndiff --git a/docker/Dockerfile.rocm_base b/docker/Dockerfile.rocm_base\nindex b4f9703a2536..5b67c81b64d1 100644\n--- a/docker/Dockerfile.rocm_base\n+++ b/docker/Dockerfile.rocm_base\n@@ -165,6 +165,11 @@ RUN if [ -f \"${SITE_PACKAGES}/rocm_sdk/__init__.py\" ]; then \\\n ### MORI Build\n ###\n FROM base AS build_mori\n+# mori silently builds without UMBP when gRPC or Protobuf is missing.\n+RUN apt-get update \\\n+ && apt-get install -y --no-install-recommends libgrpc++-dev libprotobuf-dev \\\n+ protobuf-compiler protobuf-compiler-grpc \\\n+ && rm -rf /var/lib/apt/lists/*\n ARG MORI_BRANCH\n ARG MORI_REPO\n RUN git clone ${MORI_REPO}\n@@ -174,7 +179,9 @@ RUN --mount=type=cache,target=/root/.cache/pip cd mori \\\n && ln -sfn ${ROCM_PATH} /opt/rocm \\\n && pip install \"setuptools_scm>=6.2\" \\\n && CMAKE_PREFIX_PATH=\"${ROCM_PATH}:${ROCM_PATH}/lib/rocm_sysdeps\" \\\n- python3 setup.py bdist_wheel --dist-dir=dist && ls /app/mori/dist/*.whl\n+ python3 setup.py bdist_wheel --dist-dir=dist \\\n+ && grep -qx 'BUILD_UMBP:BOOL=ON' build/CMakeCache.txt \\\n+ && ls /app/mori/dist/*.whl\n RUN mkdir -p /app/install && cp /app/mori/dist/*.whl /app/install\n \n ###\n@@ -357,6 +364,11 @@ RUN TORCH_DIST_INFO=$(ls -d ${SITE_PACKAGES}/torch-*.dist-info) \\\n && sed -i '/^Requires-Dist: triton/d' \"$TORCH_DIST_INFO/METADATA\" \\\n && sed -i \"s|^\\(${TORCH_DIST_INFO##*/}/METADATA\\),.*|\\1,,|\" \"$TORCH_DIST_INFO/RECORD\"\n \n+# Runtime libraries of mori's UMBP extension.\n+RUN apt-get update \\\n+ && apt-get install -y --no-install-recommends libgrpc++1 libprotobuf23 \\\n+ && rm -rf /var/lib/apt/lists/*\n+\n RUN --mount=type=bind,from=build_triton,src=/app/install,target=/i/triton \\\n --mount=type=bind,from=build_fa,src=/app/install,target=/i/fa \\\n --mount=type=bind,from=build_aiter,src=/app/install,target=/i/aiter \\\n@@ -374,6 +386,7 @@ RUN --mount=type=bind,from=build_triton,src=/app/install,target=/i/triton \\\n && grep -q '^pybind11==3\\.0\\.' /etc/rocm-constraints.txt \\\n && python3 -c \"import torch; assert torch.version.hip, f'non-ROCm torch: {torch.__version__}'; print(f'torch={torch.__version__}')\" \\\n && python3 -c \"import triton; print(f'triton={triton.__version__}')\" \\\n+ && python3 -c \"from mori.cpp import UMBPClient\" \\\n && pip list 2>/dev/null | grep -iE '^(torch|triton) '\n \n # Fail if a pip call above ran without the cache mount and left its downloads in the image.\ndiff --git a/tests/evals/gsm8k/test_gsm8k_offloading.py b/tests/evals/gsm8k/test_gsm8k_offloading.py\nindex 9df8498d45a1..d1fa93484251 100644\n--- a/tests/evals/gsm8k/test_gsm8k_offloading.py\n+++ b/tests/evals/gsm8k/test_gsm8k_offloading.py\n@@ -11,11 +11,13 @@\n it until success also waits for offloading to complete.\n \n Correctness is enforced via GSM8K accuracy on both runs: corrupt reloaded\n-KV drops accuracy below threshold. The reload itself is not asserted, so\n-a silently skipped reload (e.g. offloading disabled) would not be flagged.\n+KV drops accuracy below threshold. The reload itself is only asserted for\n+configs with ``assert_reload``, so elsewhere a silently skipped reload\n+(e.g. offloading disabled) would not be flagged.\n \n Covers both KV offloading connectors (OffloadingConnector and\n-SimpleCPUOffloadConnector) across five architecture families:\n+SimpleCPUOffloadConnector) across five architecture families, plus\n+UMBPStoreConnector on ROCm for Gemma 4:\n - Hybrid Mamba (NemotronH: attention + Mamba)\n - Heterogeneous head dim (Gemma 4)\n - Hybrid GDN (Qwen 3.5: attention + GatedDeltaNet)\n@@ -35,6 +37,7 @@\n import requests\n \n from tests.utils import RemoteOpenAIServer\n+from tests.v1.kv_connector.umbp_test_utils import mori_has_umbp\n from vllm.platforms import current_platform\n \n from .gsm8k_eval import evaluate_gsm8k\n@@ -63,6 +66,17 @@ def _kv_transfer_config(\n },\n }\n )\n+ elif connector == \"UMBPStoreConnector\":\n+ return json.dumps(\n+ {\n+ \"kv_connector\": \"UMBPStoreConnector\",\n+ \"kv_role\": \"kv_both\",\n+ \"kv_connector_extra_config\": {\n+ \"mode\": \"embedded\",\n+ \"capacity_bytes\": cpu_gib << 30,\n+ },\n+ }\n+ )\n elif connector == \"SimpleCPUOffloadConnector\":\n return json.dumps(\n {\n@@ -110,6 +124,17 @@ def _reset_gpu_prefix_cache(base_url: str) -> None:\n _force_engine_step(base_url)\n \n \n+def _external_kv_tokens(base_url: str) -> float:\n+ metrics = requests.get(f\"{base_url}/metrics\", timeout=30)\n+ metrics.raise_for_status()\n+ return sum(\n+ float(line.rsplit(\" \", 1)[1])\n+ for line in metrics.text.splitlines()\n+ if line.startswith(\"vllm:prompt_tokens_by_source_total{\")\n+ and 'source=\"external_kv_transfer\"' in line\n+ )\n+\n+\n @dataclass\n class OffloadingModelConfig:\n id: str\n@@ -122,6 +147,7 @@ class OffloadingModelConfig:\n cpu_offload_gib: int = 4\n startup_timeout: int = 600\n spec_name: str = \"CPUOffloadingSpec\"\n+ assert_reload: bool = False\n \n \n MODELS = [\n@@ -228,6 +254,21 @@ class OffloadingModelConfig:\n cpu_offload_gib=16,\n startup_timeout=1200,\n ),\n+ # ── UMBPStoreConnector (embedded MORI DRAM store) ────────────────\n+ pytest.param(\n+ OffloadingModelConfig(\n+ id=\"umbp-gemma-4-e4b-it\",\n+ model=\"google/gemma-4-E4B-it\",\n+ connector=\"UMBPStoreConnector\",\n+ accuracy_threshold=0.55,\n+ assert_reload=True,\n+ ),\n+ id=\"umbp-gemma-4-e4b-it\",\n+ marks=pytest.mark.skipif(\n+ not (current_platform.is_rocm() and mori_has_umbp()),\n+ reason=\"requires ROCm and MORI built with UMBP\",\n+ ),\n+ ),\n ]\n \n \n@@ -288,3 +329,8 @@ def test_gsm8k_offloading_correctness(cfg: OffloadingModelConfig):\n \n if run_idx == 1:\n _reset_gpu_prefix_cache(base_url)\n+ reloaded_before = _external_kv_tokens(base_url)\n+ elif cfg.assert_reload:\n+ assert _external_kv_tokens(base_url) > reloaded_before, (\n+ f\"GSM8K run 2/2 did not reload KV through {cfg.connector}\"\n+ )\ndiff --git a/tests/v1/kv_connector/conftest.py b/tests/v1/kv_connector/conftest.py\nnew file mode 100644\nindex 000000000000..1938f63c3993\n--- /dev/null\n+++ b/tests/v1/kv_connector/conftest.py\n@@ -0,0 +1,13 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+\n+import tempfile\n+\n+import pytest\n+\n+\n+@pytest.fixture\n+def socket_dir():\n+ \"\"\"Keep AF_UNIX paths short regardless of CI's TMPDIR.\"\"\"\n+ with tempfile.TemporaryDirectory(prefix=\"umbp-\", dir=\"/tmp\") as directory:\n+ yield directory\ndiff --git a/tests/v1/kv_connector/umbp_integration/__init__.py b/tests/v1/kv_connector/umbp_integration/__init__.py\nnew file mode 100644\nindex 000000000000..e69de29bb2d1\ndiff --git a/tests/v1/kv_connector/umbp_integration/test_mori_embedded_gpu.py b/tests/v1/kv_connector/umbp_integration/test_mori_embedded_gpu.py\nnew file mode 100644\nindex 000000000000..857a2a013836\n--- /dev/null\n+++ b/tests/v1/kv_connector/umbp_integration/test_mori_embedded_gpu.py\n@@ -0,0 +1,115 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+\"\"\"MORI-backed EmbeddedRuntime GPU integration tests.\"\"\"\n+\n+import pytest\n+import torch\n+\n+from tests.v1.kv_connector.umbp_test_utils import mori_has_umbp\n+from vllm.distributed.kv_transfer.kv_connector.v1.umbp.data import (\n+ BlockTransferPlan,\n+ KVLayoutDescriptor,\n+ KVRange,\n+ KVRegion,\n+ RankTopology,\n+ TransferJobStatus,\n+)\n+from vllm.distributed.kv_transfer.kv_connector.v1.umbp.runtime import (\n+ EmbeddedRuntime,\n+ UMBPRuntimeConfig,\n+)\n+from vllm.platforms import current_platform\n+\n+pytestmark = pytest.mark.skipif(\n+ not (current_platform.is_rocm() and mori_has_umbp()),\n+ reason=\"requires ROCm and MORI built with UMBP\",\n+)\n+\n+\n+@pytest.mark.parametrize(\"bulk_load\", [False, True])\n+def test_mori_embedded_dram_eviction_and_restore(socket_dir, bulk_load):\n+ \"\"\"Overflowing DRAM evicts old objects, and the newest one still restores.\"\"\"\n+ object_size = 1 << 20\n+ num_objects = 16\n+ runtime = EmbeddedRuntime.from_config(\n+ UMBPRuntimeConfig(\n+ \"embedded\",\n+ {\n+ \"capacity_bytes\": 8 * object_size,\n+ \"dram_high_watermark\": 0.75,\n+ \"dram_low_watermark\": 0.5,\n+ \"lookup_dir\": socket_dir,\n+ \"timeout_ms\": 60000,\n+ },\n+ )\n+ )\n+ worker = runtime.create_worker_handle(\n+ \"mori-eviction\",\n+ RankTopology(),\n+ KVLayoutDescriptor(\n+ regions=(KVRegion(\"layer0\", 0, object_size, object_size, 0),),\n+ topology=RankTopology(),\n+ ),\n+ )\n+ try:\n+ source = torch.empty((1, object_size), dtype=torch.uint8, device=\"cuda\")\n+ destination = torch.zeros_like(source)\n+ worker.register_buffers({\"layer0\": source, \"destination\": destination})\n+\n+ keys = [f\"eviction-{index}\" for index in range(num_objects)]\n+ for index, key in enumerate(keys):\n+ source.fill_(index)\n+ plan = BlockTransferPlan(\n+ key,\n+ index,\n+ ranges=(\n+ KVRange(\n+ \"layer0\",\n+ 0,\n+ index,\n+ source.data_ptr(),\n+ object_size,\n+ object_size,\n+ 0,\n+ ),\n+ ),\n+ )\n+ stored = worker.wait(worker.store([plan]))\n+ if stored.status is TransferJobStatus.COMPLETED:\n+ worker.publish(stored)\n+\n+ hits = list(worker.batch_exists(keys))\n+ assert not all(hits), \"the stores never exceeded DRAM capacity\"\n+ latest = max(index for index, hit in enumerate(hits) if hit)\n+\n+ if bulk_load:\n+ worker.register_buffers({\"layer0\": destination})\n+ job = worker.load_blocks([BlockTransferPlan(keys[latest], 0, group_id=0)])\n+ assert job is not None\n+ else:\n+ job = worker.load(\n+ [\n+ BlockTransferPlan(\n+ keys[latest],\n+ 0,\n+ ranges=(\n+ KVRange(\n+ \"layer0\",\n+ 0,\n+ 0,\n+ destination.data_ptr(),\n+ object_size,\n+ object_size,\n+ 0,\n+ ),\n+ ),\n+ )\n+ ]\n+ )\n+ loaded = worker.wait(job)\n+ assert loaded.status is TransferJobStatus.COMPLETED\n+ assert loaded.completed_bytes == object_size\n+ torch.accelerator.synchronize()\n+ assert torch.all(destination == latest)\n+ finally:\n+ worker.close()\ndiff --git a/tests/v1/kv_connector/umbp_integration/test_mori_token_e2e.py b/tests/v1/kv_connector/umbp_integration/test_mori_token_e2e.py\nnew file mode 100644\nindex 000000000000..b14467c44f16\n--- /dev/null\n+++ b/tests/v1/kv_connector/umbp_integration/test_mori_token_e2e.py\n@@ -0,0 +1,128 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+\"\"\"End-to-end restore through the MORI-backed UMBP runtime.\n+\n+Batch-invariant kernels make a restore bitwise comparable with recomputing the\n+prompt, so restored KV must reproduce the cold run's tokens and logprobs.\n+\"\"\"\n+\n+import time\n+\n+import pytest\n+\n+import vllm.envs as envs\n+from tests.v1.kv_connector.rocm_pd_accuracy_utils import _REVISIONS, QWEN_MODEL\n+from tests.v1.kv_connector.umbp_test_utils import mori_has_umbp\n+from vllm import SamplingParams, TokensPrompt\n+from vllm.config import KVTransferConfig\n+from vllm.platforms import current_platform\n+\n+pytestmark = pytest.mark.skipif(\n+ not (current_platform.is_rocm() and mori_has_umbp()),\n+ reason=\"requires ROCm and MORI built with UMBP\",\n+)\n+\n+BLOCK_SIZE = 16\n+PARAMS = SamplingParams(temperature=0, max_tokens=16, logprobs=5, ignore_eos=True)\n+\n+\n+@pytest.fixture\n+def umbp_llm(vllm_runner, socket_dir, monkeypatch):\n+ monkeypatch.setattr(envs, \"VLLM_BATCH_INVARIANT\", True)\n+ monkeypatch.setenv(\"VLLM_BATCH_INVARIANT\", \"1\")\n+ with vllm_runner(\n+ QWEN_MODEL,\n+ revision=_REVISIONS[QWEN_MODEL],\n+ enforce_eager=True,\n+ block_size=BLOCK_SIZE,\n+ enable_prefix_caching=True,\n+ disable_log_stats=False,\n+ kv_transfer_config=KVTransferConfig(\n+ kv_connector=\"UMBPStoreConnector\",\n+ kv_role=\"kv_both\",\n+ kv_connector_extra_config={\n+ \"mode\": \"embedded\",\n+ \"capacity_bytes\": 1 << 30,\n+ \"lookup_dir\": socket_dir,\n+ },\n+ ),\n+ ) as runner:\n+ yield runner.llm\n+\n+\n+def _prompt(seed: int, num_tokens: int) -> TokensPrompt:\n+ return TokensPrompt(\n+ prompt_token_ids=[\n+ 100 + (seed * 1009 + i * 37) % 5000 for i in range(num_tokens)\n+ ]\n+ )\n+\n+\n+def _external_tokens(llm) -> int:\n+ return sum(\n+ metric.value\n+ for metric in llm.get_metrics()\n+ if metric.name == \"vllm:prompt_tokens_by_source\"\n+ and metric.labels.get(\"source\") == \"external_kv_transfer\"\n+ )\n+\n+\n+def _reset_gpu_prefix_cache(llm) -> None:\n+ \"\"\"Drop the GPU prefix cache once UMBP has released the stored blocks.\"\"\"\n+ deadline = time.monotonic() + 60\n+ while not llm.reset_prefix_cache():\n+ assert time.monotonic() < deadline, \"UMBP stores never released GPU blocks\"\n+ llm.generate(\n+ TokensPrompt(prompt_token_ids=[0]),\n+ SamplingParams(max_tokens=1),\n+ use_tqdm=False,\n+ )\n+\n+\n+def _assert_same_outputs(expected, actual) -> None:\n+ for want, got in zip(expected, actual, strict=True):\n+ want_out, got_out = want.outputs[0], got.outputs[0]\n+ assert got_out.token_ids == want_out.token_ids\n+ assert [\n+ {token: entry.logprob for token, entry in step.items()}\n+ for step in got_out.logprobs\n+ ] == [\n+ {token: entry.logprob for token, entry in step.items()}\n+ for step in want_out.logprobs\n+ ]\n+\n+\n+def test_restore_matches_recompute(umbp_llm):\n+ \"\"\"A batch of prompts ending mid-block restores every full block exactly.\"\"\"\n+ prompts = [\n+ _prompt(seed, 4 * BLOCK_SIZE + tail)\n+ for seed, tail in enumerate((1, 7, BLOCK_SIZE - 1))\n+ ]\n+ computed = umbp_llm.generate(prompts, PARAMS, use_tqdm=False)\n+ _reset_gpu_prefix_cache(umbp_llm)\n+\n+ before = _external_tokens(umbp_llm)\n+ restored = umbp_llm.generate(prompts, PARAMS, use_tqdm=False)\n+\n+ assert _external_tokens(umbp_llm) - before == 3 * 4 * BLOCK_SIZE\n+ _assert_same_outputs(computed, restored)\n+\n+\n+def test_restore_extends_a_local_prefix_hit(umbp_llm):\n+ \"\"\"UMBP fills in only the blocks after a shorter GPU prefix-cache hit.\"\"\"\n+ prompt = _prompt(0, 8 * BLOCK_SIZE + 7)\n+ computed = umbp_llm.generate(prompt, PARAMS, use_tqdm=False)\n+ _reset_gpu_prefix_cache(umbp_llm)\n+ short = PARAMS.clone()\n+ short.skip_reading_prefix_cache = True\n+ local_prefix = TokensPrompt(\n+ prompt_token_ids=prompt[\"prompt_token_ids\"][: 2 * BLOCK_SIZE + 1]\n+ )\n+ umbp_llm.generate(local_prefix, short, use_tqdm=False)\n+\n+ before = _external_tokens(umbp_llm)\n+ mixed = umbp_llm.generate(prompt, PARAMS, use_tqdm=False)\n+\n+ assert mixed[0].num_cached_tokens == 8 * BLOCK_SIZE\n+ assert _external_tokens(umbp_llm) - before == 6 * BLOCK_SIZE\n+ _assert_same_outputs(computed, mixed)\ndiff --git a/tests/v1/kv_connector/umbp_test_utils.py b/tests/v1/kv_connector/umbp_test_utils.py\nindex 4f7ca892e68f..0c79f6d63045 100644\n--- a/tests/v1/kv_connector/umbp_test_utils.py\n+++ b/tests/v1/kv_connector/umbp_test_utils.py\n@@ -225,6 +225,17 @@ def create_worker_handle(\n del namespace\n return _MemoryWorkerHandle(self._store, topology, layout)\n \n+ def evict_all(self) -> None:\n+ self._store.clear()\n+\n+\n+def mori_has_umbp() -> bool:\n+ try:\n+ from mori.cpp import UMBPClient # noqa: F401\n+ except ImportError:\n+ return False\n+ return True\n+\n \n def install_memory_runtime(monkeypatch):\n \"\"\"Share one isolated store across the connectors created by a test.\"\"\"\ndiff --git a/tests/v1/kv_connector/unit/test_umbp_embedded.py b/tests/v1/kv_connector/unit/test_umbp_embedded.py\nindex 3d79e6c9463f..5054b2582936 100644\n--- a/tests/v1/kv_connector/unit/test_umbp_embedded.py\n+++ b/tests/v1/kv_connector/unit/test_umbp_embedded.py\n@@ -1,95 +1,339 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n-import tempfile\n+import importlib.util\n+import sys\n import threading\n+from dataclasses import replace\n from types import SimpleNamespace\n \n import pytest\n+import torch\n \n+from tests.v1.kv_connector.umbp_test_utils import (\n+ _kv_cache_config,\n+ _vllm_config,\n+ handshake,\n+ install_memory_runtime,\n+ make_kv_caches,\n+)\n+from tests.v1.kv_connector.unit.utils import (\n+ create_model_runner_output,\n+ create_request,\n+ create_scheduler,\n+ create_vllm_config,\n+)\n+from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorRole\n+from vllm.distributed.kv_transfer.kv_connector.v1.umbp.connector import (\n+ UMBPStoreConnector,\n+)\n from vllm.distributed.kv_transfer.kv_connector.v1.umbp.data import (\n+ BlockIdentityCodec,\n+ BlockLoadBatch,\n BlockTransferPlan,\n+ KVLayoutPlanner,\n+ KVRange,\n+ KVRegion,\n RankTopology,\n TransferJobStatus,\n+ UMBPConnectorMetadata,\n+ UMBPNamespace,\n+)\n+from vllm.distributed.kv_transfer.kv_connector.v1.umbp.runtime import (\n+ EmbeddedRuntime,\n+ UMBPRuntimeConfig,\n+ UMBPRuntimeFactory,\n+ embedded,\n )\n-from vllm.distributed.kv_transfer.kv_connector.v1.umbp.runtime import embedded\n from vllm.distributed.kv_transfer.kv_connector.v1.umbp.runtime.embedded import (\n _lookup_socket_path,\n _MoriLookupServer,\n _MoriSchedulerHandle,\n _MoriWorkerHandle,\n )\n+from vllm.distributed.kv_transfer.kv_connector.v1.umbp.worker import (\n+ UMBPStoreConnectorWorker,\n+)\n+from vllm.platforms import current_platform\n+from vllm.v1.kv_cache_interface import (\n+ FullAttentionSpec,\n+ KVCacheConfig,\n+ KVCacheGroupSpec,\n+ KVCacheTensor,\n+ SlidingWindowSpec,\n+)\n+from vllm.v1.request import RequestStatus\n+\n+mori_available = importlib.util.find_spec(\"mori\") is not None\n+\n+pytestmark = pytest.mark.skipif(\n+ not (current_platform.is_rocm() and mori_available),\n+ reason=\"UMBP is only available on ROCm with the mori package installed\",\n+)\n+\n+\n+@pytest.mark.parametrize(\"for_store\", [False, True])\n+def test_mori_range_arguments_preserve_sparse_offsets_and_empty_objects(for_store):\n+ plans = [\n+ BlockTransferPlan(\"empty\", 0),\n+ BlockTransferPlan(\n+ \"scatter\",\n+ 1,\n+ ranges=(\n+ KVRange(\"layer0\", 0, 1, 1000, 64, 16, 48),\n+ KVRange(\"layer1\", 0, 1, 2000, 64, 8, 0),\n+ ),\n+ ),\n+ ]\n+ assert _MoriWorkerHandle._range_args(plans, for_store=for_store) == (\n+ [\"empty\", \"scatter\"],\n+ [0, 64] if for_store else [],\n+ [[], [1000, 2000]],\n+ [[], [16, 8]],\n+ [[], [48, 0]],\n+ )\n \n \n @pytest.fixture\n-def blocked_native_load(monkeypatch, tmp_path):\n- started = threading.Event()\n- release = threading.Event()\n- finished = threading.Event()\n- clock = SimpleNamespace(now=100.0)\n- monkeypatch.setattr(embedded.time, \"monotonic\", lambda: clock.now)\n+def bulk_worker(monkeypatch, socket_dir):\n+ calls: list[\n+ tuple[list[str], list[int], list[list[int]], list[list[int]], list[list[int]]]\n+ ] = []\n \n- def get(keys, *args):\n- started.set()\n- assert release.wait(5)\n+ def get(keys, pointers, sizes, offsets):\n+ calls.append((keys, [], pointers, sizes, offsets))\n+ return [key != \"missing\" for key in keys]\n+\n+ def put(keys, object_sizes, pointers, sizes, offsets):\n+ calls.append((keys, object_sizes, pointers, sizes, offsets))\n return [True] * len(keys)\n \n+ monkeypatch.setitem(\n+ sys.modules,\n+ \"mori.cpp\",\n+ SimpleNamespace(MemoryLocationType=SimpleNamespace(CPU=0, GPU=1)),\n+ )\n+ client = SimpleNamespace(\n+ register_memory=lambda *a: True,\n+ deregister_memory=lambda *a: True,\n+ batch_get_ranges_into_ptr=get,\n+ batch_put_ranges_from_ptr=put,\n+ flush=lambda: True,\n+ close=lambda: None,\n+ )\n+ planner = KVLayoutPlanner(\n+ [\n+ KVRegion(\"a\", 0, 64, 32, 0, 16),\n+ KVRegion(\"b\", 1, 32, 16, 32, 16),\n+ KVRegion(\"c\", 0, 128, 64, 48, 16),\n+ ]\n+ )\n handle = _MoriWorkerHandle(\n- SimpleNamespace(batch_get_ranges_into_ptr=get, close=lambda: None),\n- \"blocked-load\",\n+ client,\n+ \"bulk\",\n RankTopology(),\n- str(tmp_path),\n- 1,\n+ socket_dir,\n 1,\n+ 5,\n+ planner.describe(RankTopology()),\n+ )\n+ worker = UMBPStoreConnectorWorker(handle, planner)\n+ buffers = {\n+ r.layer_name: torch.empty((8, r.block_stride), dtype=torch.uint8)\n+ for r in planner.regions\n+ }\n+ worker.register_kv_caches(buffers)\n+ yield worker, buffers, calls\n+ handle.close()\n+\n+\n+@pytest.mark.parametrize(\"batched\", [False, True])\n+def test_bulk_load_preserves_group_order_failures_and_new_buffers(\n+ bulk_worker, batched, monkeypatch\n+):\n+ worker, buffers, calls = bulk_worker\n+ plans = [\n+ BlockTransferPlan(\"group1\", 3, group_id=1, request_id=\"r\"),\n+ BlockTransferPlan(\"missing\", 4, group_id=0, request_id=\"r\"),\n+ BlockTransferPlan(\"group0\", 6, group_id=0, request_id=\"r\"),\n+ ]\n+ for caches in (buffers, {name: torch.empty_like(t) for name, t in buffers.items()}):\n+ worker.register_kv_caches(caches)\n+ expected = _MoriWorkerHandle._range_args(\n+ [worker.layout.materialize(p) for p in plans], for_store=False\n+ )\n+ supplied = plans\n+ if batched:\n+ supplied = BlockLoadBatch(\n+ [p.key for p in plans],\n+ [p.block_id for p in plans],\n+ [p.group_id for p in plans],\n+ \"r\",\n+ )\n+ monkeypatch.setattr(\n+ BlockLoadBatch,\n+ \"__getitem__\",\n+ lambda *a: pytest.fail(\n+ \"bulk loading must not materialize per-block plans\"\n+ ),\n+ )\n+ job = worker.runtime.load_blocks(supplied)\n+ assert job is not None\n+ result = worker.runtime.wait(job)\n+ assert calls[-1] == expected\n+ assert result.plans is supplied if batched else result.plans == tuple(plans)\n+ assert result.failed_block_ids == {4}\n+ assert result.completed_keys == {\"group0\", \"group1\"}\n+ assert result.completed_bytes == 112\n+ assert len(calls) == 2\n+ assert calls[0][2] != calls[1][2]\n+\n+\n+def test_bulk_store_matches_materialized_ranges(bulk_worker, monkeypatch):\n+ worker, _, calls = bulk_worker\n+ plans = [\n+ BlockTransferPlan(\"group1\", 3, group_id=1, request_id=\"r\"),\n+ BlockTransferPlan(\"group0\", 6, group_id=0, request_id=\"r\"),\n+ ]\n+ expected = _MoriWorkerHandle._range_args(\n+ [worker.layout.materialize(p) for p in plans]\n+ )\n+ monkeypatch.setattr(\n+ worker.layout,\n+ \"materialize\",\n+ lambda *a: pytest.fail(\"bulk stores must not materialize per-block plans\"),\n+ )\n+\n+ worker.enqueue_stores(UMBPConnectorMetadata(store_requests={\"r\": plans}))\n+ (job,) = worker._store_jobs.values()\n+ result = worker.runtime.wait(job)\n+\n+ assert calls == [expected]\n+ assert result.plans == tuple(plans)\n+ assert result.completed_keys == {\"group0\", \"group1\"}\n+ assert result.completed_bytes == 112\n+\n+\n+@pytest.mark.parametrize(\"special\", [\"subblocks\", \"materialized\", \"batch-subblocks\"])\n+def test_bulk_load_falls_back_for_entire_mixed_batch(bulk_worker, special):\n+ worker, buffers, calls = bulk_worker\n+ plans = [\n+ BlockTransferPlan(\"a\", 1, group_id=1),\n+ BlockTransferPlan(\"c\", 2, group_id=0),\n+ ]\n+ if special in (\"subblocks\", \"batch-subblocks\"):\n+ buffers[\"c\"] = torch.empty((16, 32), dtype=torch.uint8)\n+ worker.register_kv_caches(buffers)\n+ if special == \"batch-subblocks\":\n+ plans = BlockLoadBatch(\n+ [p.key for p in plans],\n+ [p.block_id for p in plans],\n+ [p.group_id for p in plans],\n+ \"r\",\n+ )\n+ else:\n+ plans[1] = worker.layout.materialize(plans[1])\n+ assert worker.runtime.load_blocks(plans) is None\n+ assert not calls\n+ expected = _MoriWorkerHandle._range_args(\n+ [p if p.ranges else worker.layout.materialize(p) for p in plans],\n+ for_store=False,\n+ )\n+ worker.start_load_kv(None, UMBPConnectorMetadata(load_requests={\"r\": plans}))\n+ worker.wait_for_layer_load(\"\")\n+ assert calls == [expected]\n+\n+\n+@pytest.mark.parametrize(\n+ (\"options\", \"error\"),\n+ [\n+ ({\"dram_low_watermark\": 0.9, \"dram_high_watermark\": 0.7}, \"must not\"),\n+ ({\"dram_use_hugepages\": 1}, \"boolean\"),\n+ ({\"dram_numa_node\": -2}, \">= -1\"),\n+ ({\"dram_hugepage_size\": 0}, \"positive integer\"),\n+ ({\"capacity_bytes\": 1024, \"total_capacity_bytes\": 4096}, \"mutually exclusive\"),\n+ ],\n+)\n+def test_runtime_config_rejects_invalid_embedded_dram_options(options, error):\n+ with pytest.raises(ValueError, match=error):\n+ UMBPRuntimeFactory.build(\n+ UMBPRuntimeConfig.from_vllm(_vllm_config({\"mode\": \"embedded\", **options}))\n+ )\n+\n+\n+def test_mori_client_is_created_only_for_worker(monkeypatch, socket_dir):\n+ \"\"\"Scheduler lookup must not allocate a second, unused DRAM store.\"\"\"\n+ monkeypatch.setitem(sys.modules, \"mori.cpp\", None)\n+ runtime = EmbeddedRuntime.from_config(\n+ UMBPRuntimeConfig(\n+ \"embedded\", {\"capacity_bytes\": 1024, \"lookup_dir\": socket_dir}\n+ )\n+ )\n+ topology = RankTopology()\n+ layout = KVLayoutPlanner.from_kv_cache_config(_kv_cache_config()).describe(topology)\n+ scheduler = runtime.create_scheduler_handle(\"worker-only\", topology, layout)\n+ scheduler.close()\n+ with pytest.raises(RuntimeError, match=\"requires MORI\"):\n+ runtime.create_worker_handle(\"worker-only\", topology, layout)\n+\n+ configs = []\n+\n+ def create_client(config):\n+ configs.append(config)\n+ return SimpleNamespace(close=lambda: None)\n+\n+ monkeypatch.setitem(\n+ sys.modules,\n+ \"mori.cpp\",\n+ SimpleNamespace(\n+ UMBPClient=create_client,\n+ UMBPConfig=lambda: SimpleNamespace(dram=SimpleNamespace()),\n+ ),\n )\n+ worker = runtime.create_worker_handle(\"worker-only\", topology, layout)\n try:\n- job = handle.load([BlockTransferPlan(\"running\", 0)])\n- future = handle._futures[id(job)]\n- future.add_done_callback(lambda _: finished.set())\n- assert started.wait(5)\n- yield handle, job, future, release, finished, clock\n+ assert len(configs) == 1\n+ assert configs[0].dram.capacity_bytes == 1024\n finally:\n- release.set()\n- handle.close()\n+ worker.close()\n \n \n-def test_async_load_poll_timeout_keeps_buffers_owned(blocked_native_load):\n- handle, job, future, release, finished, clock = blocked_native_load\n- assert handle.poll(job) is None\n- clock.now += 2\n- with pytest.raises(TimeoutError, match=\"buffers still in use\"):\n- handle.poll(job)\n- assert job.status is TransferJobStatus.RUNNING\n- assert handle._futures[id(job)] is future\n- assert not future.done()\n+def test_runtime_config_resolves_total_embedded_capacity_per_rank():\n+ config = UMBPRuntimeConfig.from_vllm(\n+ _vllm_config({\"mode\": \"embedded\", \"total_capacity_bytes\": 4096})\n+ ).resolve_for_rank_count(4)\n \n- release.set()\n- assert finished.wait(5)\n- assert handle.poll(job) is job\n- assert job.status is TransferJobStatus.COMPLETED\n- assert id(job) not in handle._futures\n+ runtime = EmbeddedRuntime.from_config(config)\n+ assert runtime.options[\"capacity_bytes\"] == 1024\n+ assert config.options[\"total_capacity_bytes\"] == 4096\n+ assert \"capacity_bytes\" not in config.options\n \n \n-def test_load_timeout_does_not_count_time_waiting_for_a_worker(blocked_native_load):\n- handle, _, _, release, _, clock = blocked_native_load\n- queued = handle.load([BlockTransferPlan(\"queued\", 1)])\n- finished = threading.Event()\n- handle._futures[id(queued)].add_done_callback(lambda _: finished.set())\n- clock.now += 2\n- assert handle.poll(queued) is None\n- assert queued.status is TransferJobStatus.RUNNING\n+def test_embedded_connector_rejects_pipeline_parallelism():\n+ with pytest.raises(NotImplementedError, match=\"pipeline parallelism\"):\n+ UMBPStoreConnector(\n+ _vllm_config(\n+ {\"mode\": \"embedded\"},\n+ pipeline_parallel_size=2,\n+ ),\n+ KVConnectorRole.SCHEDULER,\n+ _kv_cache_config(),\n+ )\n \n- release.set()\n- assert finished.wait(5)\n- assert handle.poll(queued) is queued\n- assert queued.status is TransferJobStatus.COMPLETED\n \n+def test_lookup_sockets_separate_engines_and_data_parallel_ranks(socket_dir):\n+ def path(options, dp_index=0):\n+ config = UMBPRuntimeConfig(\"embedded\", {\"lookup_dir\": socket_dir, **options})\n+ handle = EmbeddedRuntime.from_config(\n+ replace(config, dp_index=dp_index)\n+ ).create_scheduler_handle(\"same-model\", RankTopology(), None)\n+ return handle._paths[RankTopology().local_namespace]\n \n-@pytest.fixture\n-def socket_dir():\n- \"\"\"Keep AF_UNIX paths short regardless of CI's TMPDIR.\"\"\"\n- with tempfile.TemporaryDirectory(prefix=\"umbp-\", dir=\"/tmp\") as directory:\n- yield directory\n+ assert path({}) == path({})\n+ assert path({}, dp_index=0) != path({}, dp_index=1)\n+ assert path({\"lookup_instance\": \"a\"}) != path({\"lookup_instance\": \"b\"})\n+ with pytest.raises(ValueError, match=\"lookup_instance\"):\n+ path({\"lookup_instance\": 1})\n \n \n def test_lookup_server_refuses_a_socket_another_engine_serves(socket_dir):\n@@ -109,6 +353,233 @@ def test_lookup_server_refuses_a_socket_another_engine_serves(socket_dir):\n first.close()\n \n \n+def test_lookup_server_replaces_a_stale_socket_file(socket_dir):\n+ import socket\n+\n+ path = _lookup_socket_path(\"stale\", (0, 0, 0, 0), socket_dir, \"dp0\")\n+ dead = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n+ dead.bind(path)\n+ dead.close()\n+ server = _MoriLookupServer(\n+ path, SimpleNamespace(batch_exists=lambda keys: [True] * len(keys))\n+ )\n+ server.start()\n+ try:\n+ scheduler = _MoriSchedulerHandle(\"stale\", RankTopology(), socket_dir, \"dp0\")\n+ assert scheduler.lookup([\"k\"]) == [True]\n+ finally:\n+ server.close()\n+\n+\n+@pytest.mark.parametrize(\"close_rank\", [None, 0, 1])\n+def test_mori_scheduler_routes_lookup_and_clear_to_all_ranks(socket_dir, close_rank):\n+ class _Client:\n+ def __init__(self, keys):\n+ self.keys = set(keys)\n+\n+ def batch_exists(self, keys):\n+ return [key in self.keys for key in keys]\n+\n+ def clear(self):\n+ self.keys.clear()\n+ return True\n+\n+ namespace = \"routed-lookup\"\n+ topology = RankTopology(tp_size=2)\n+ codec0 = BlockIdentityCodec(UMBPNamespace(namespace), tp_rank=0)\n+ codec1 = BlockIdentityCodec(UMBPNamespace(namespace), tp_rank=1)\n+ keys = [codec0.key(b\"a\"), codec1.key(b\"a\")]\n+ servers = []\n+ clients = [_Client([key, \"legacy-key\"]) for key in keys]\n+ for rank, client in zip(topology.all_namespaces(), clients, strict=True):\n+ server = _MoriLookupServer(\n+ _lookup_socket_path(namespace, rank, socket_dir),\n+ client,\n+ )\n+ server.start()\n+ servers.append(server)\n+ scheduler = _MoriSchedulerHandle(namespace, topology, socket_dir)\n+ try:\n+ assert scheduler.lookup(keys) == [True, True]\n+ assert scheduler.last_lookup_diagnostics == {\n+ \"unavailable_ranks\": (),\n+ \"missing_keys\": (),\n+ }\n+ new_keys = [codec0.key(b\"new\"), codec1.key(b\"new\")]\n+ assert scheduler.lookup(new_keys) == [False, False]\n+ for client, key in zip(clients, new_keys, strict=True):\n+ client.keys.add(key)\n+ assert scheduler.lookup(new_keys) == [True, True]\n+ assert scheduler.lookup([keys[1], \"legacy-key\", keys[0]]) == [True] * 3\n+ if close_rank is not None:\n+ servers[close_rank].close()\n+ assert scheduler.lookup(keys) == [rank != close_rank for rank in range(2)]\n+ assert scheduler.last_lookup_diagnostics[\"unavailable_ranks\"] == (\n+ topology.all_namespaces()[close_rank],\n+ )\n+ assert scheduler.last_lookup_diagnostics[\"missing_keys\"] == (\n+ keys[close_rank],\n+ )\n+ assert scheduler.clear() is (close_rank is None)\n+ for rank, client in enumerate(clients):\n+ if rank != close_rank:\n+ assert not client.keys\n+ assert scheduler.lookup(keys + [\"legacy-key\"]) == [False] * 3\n+ finally:\n+ for server in servers:\n+ server.close()\n+\n+\n+def test_single_rank_lookup_returns_fresh_results(socket_dir):\n+ \"\"\"The only rank also answers legacy keys, and hits are never cached.\"\"\"\n+ namespace = \"single-route\"\n+ codec = BlockIdentityCodec(UMBPNamespace(namespace))\n+ topology = RankTopology()\n+ keys = [codec.key(b\"known\"), \"legacy\", codec.key(b\"new\")]\n+ resident = set(keys[:2])\n+ server = _MoriLookupServer(\n+ _lookup_socket_path(namespace, topology.local_namespace, socket_dir),\n+ SimpleNamespace(batch_exists=lambda keys: [key in resident for key in keys]),\n+ )\n+ scheduler = _MoriSchedulerHandle(namespace, topology, socket_dir)\n+ server.start()\n+ try:\n+ assert scheduler.lookup(keys) == [True, True, False]\n+ resident.clear()\n+ resident.add(keys[-1])\n+ assert scheduler.lookup(keys) == [False, False, True]\n+ server.close()\n+ assert scheduler.lookup(keys) == [False] * len(keys)\n+ assert scheduler.last_lookup_diagnostics[\"unavailable_ranks\"] == (\n+ topology.local_namespace,\n+ )\n+ finally:\n+ scheduler.close()\n+ server.close()\n+\n+\n+@pytest.mark.parametrize(\"flush_succeeds\", [False, True])\n+def test_mori_publication_does_not_flush_on_the_worker_thread(\n+ socket_dir, flush_succeeds\n+):\n+ flush_threads = []\n+\n+ def flush():\n+ flush_threads.append(threading.get_ident())\n+ return flush_succeeds\n+\n+ client = SimpleNamespace(\n+ batch_put_ranges_from_ptr=lambda keys, *args: [True] * len(keys),\n+ batch_exists=lambda keys: [True] * len(keys),\n+ flush=flush,\n+ close=lambda: None,\n+ )\n[... diff truncated: 1 more file(s) not shown]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Pooling] Enable Matryoshka dimensions for EmbeddingGemma 2\nLabels: bug, ready, ci/build, multi-modality, verified, pooling\nFiles changed (2): tests/models/multimodal/pooling/test_embedding_gemma2.py, vllm/model_executor/models/config.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #64845. EmbeddingGemma 2 is trained with Matryoshka Representation Learning, and its model card lists 128, 256, 512 and 768 as supported dimensions. None of its published configs (`config.json`, `config_sentence_transformers.json`, `sentence_bert_config.json`) declares this, so vLLM treats the model as non-Matryoshka and rejects every request that sets `dimensions`. Today users need `--hf-overrides '{\"matryoshka_dimensions\": [...]}'` to get the documented behavior.\n\nThis PR sets `matryoshka_dimensions = [128, 256, 512, 768]` in `EmbeddingGemma2ModelConfig.verify_and_update_model_config`, the same hook `JinaForRankingConfig` uses to set `embedding_size`.\n\n## Claims\n\n- Without overrides, `dimensions` of 128, 256 and 512 are accepted, and other values are rejected with the existing \"only supports Matryoshka dimensions\" error.\n- No change for requests without `dimensions`, or for other models.\n- The pooler truncates before it normalizes (`seqwise/heads.py`), which matches the model card's \"re-normalize after truncating\".\n\n## Validation\n[results removed]\n## Question\n\nNo other model in vLLM sets `matryoshka_dimensions` from its config hook; it normally comes from the checkpoint's `config.json`. Is setting it here OK, or would you rather it come from the model's config on the Hub?\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/config.py b/vllm/model_executor/models/config.py\nindex dc7b5fabcf83..e435e1b58b60 100644\n--- a/vllm/model_executor/models/config.py\n+++ b/vllm/model_executor/models/config.py\n@@ -529,6 +529,17 @@ def verify_and_update_config(vllm_config: \"VllmConfig\") -> None:\n \n \n class EmbeddingGemma2ModelConfig(Gemma4Config):\n+ @staticmethod\n+ def verify_and_update_model_config(model_config: \"ModelConfig\") -> None:\n+ # Trained with Matryoshka Representation Learning (see the model card),\n+ # but the published configs don't declare the supported dimensions.\n+ # Only fill in the default; keep explicit settings such as overrides.\n+ hf_config = model_config.hf_config\n+ if not hasattr(hf_config, \"matryoshka_dimensions\") and not hasattr(\n+ hf_config, \"is_matryoshka\"\n+ ):\n+ hf_config.matryoshka_dimensions = [128, 256, 512, 768]\n+\n @staticmethod\n def verify_and_update_config(vllm_config: \"VllmConfig\") -> None:\n Gemma4Config.verify_and_update_config(vllm_config)\n\ndiff --git a/tests/models/multimodal/pooling/test_embedding_gemma2.py b/tests/models/multimodal/pooling/test_embedding_gemma2.py\nindex ff4f7e9fb167..3e88eca4bbfc 100644\n--- a/tests/models/multimodal/pooling/test_embedding_gemma2.py\n+++ b/tests/models/multimodal/pooling/test_embedding_gemma2.py\n@@ -91,6 +91,25 @@ def test_text_parity(vllm_runner, st_model, prompt):\n )\n \n \n+@needs_model\n+def test_matryoshka_parity(vllm_runner, st_model):\n+ from vllm import PoolingParams\n+\n+ prompt = \"task: search result | query: what is vllm\"\n+ # 768 also needs embedding_size to report the 768-d output (#60978).\n+ dims = [128, 256, 512]\n+ with vllm_runner(MODEL, runner=\"pooling\", max_model_len=8192) as vm:\n+ outs = vm.embed(\n+ [prompt] * len(dims),\n+ pooling_params=[PoolingParams(dimensions=d) for d in dims],\n+ )\n+ for d, out in zip(dims, outs):\n+ ref = st_model.encode([prompt], truncate_dim=d, normalize_embeddings=True)\n+ assert len(out) == d\n+ sim = _cos([out], ref).min().item()\n+ assert sim >= TEXT_COS, f\"Matryoshka {d}d cosine {sim} < {TEXT_COS}\"\n+\n+\n @needs_model\n def test_mm_recipe(vllm_runner, st_model):\n from PIL import Image\n@@ -648,6 +667,38 @@ def test_config_capping_and_explicit_limits():\n assert cfg_explicit_16k.model_config.max_model_len == 16384\n \n \n+def _update_matryoshka_config(**hf_config_fields):\n+ from types import SimpleNamespace\n+\n+ from vllm.model_executor.models.config import EmbeddingGemma2ModelConfig\n+\n+ hf_config = SimpleNamespace(**hf_config_fields)\n+ EmbeddingGemma2ModelConfig.verify_and_update_model_config(\n+ SimpleNamespace(hf_config=hf_config)\n+ )\n+ return hf_config\n+\n+\n+def test_sets_matryoshka_dimensions_from_model_card():\n+ assert _update_matryoshka_config().matryoshka_dimensions == [128, 256, 512, 768]\n+\n+\n+@pytest.mark.parametrize(\n+ \"fields\",\n+ [\n+ {\"matryoshka_dimensions\": [768, 256]},\n+ {\"matryoshka_dimensions\": None},\n+ {\"is_matryoshka\": True},\n+ {\"is_matryoshka\": False},\n+ ],\n+)\n+def test_keeps_declared_matryoshka_config(fields):\n+ hf_config = _update_matryoshka_config(**fields)\n+ assert getattr(hf_config, \"matryoshka_dimensions\", None) == fields.get(\n+ \"matryoshka_dimensions\"\n+ )\n+\n+\n def test_sentence_transformer_tokenizer_config_max_seq_length(tmp_path):\n \"\"\"Verify get_sentence_transformer_tokenizer_config accepts config\n with only max_seq_length.\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Kernel] Only set PDL launch attr for MoE top-k gating on SM90+\nLabels: bug, ready\nFiles changed (1): csrc/moe/topk_softmax_kernels.cu\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n\n## Validation\n[results removed]\n## Details\n\n- #59737 first had this host check (uncached); review asked to drop it for consistency with `topk_softplus_sqrt` / `per_token_group_quant` and to avoid `cudaGetDevice` + `call_once` per eager launch. The measurements above are the reason to bring it back. It is cached in a function-local static as in `fused_deepseek_v4_qnorm_rope_kv_insert_kernel.cu` (`numAttrs = (sm_version >= 90) ? 1 : 0`), so eager launches pay nothing per call. This also matches the scope in #59737's own description (\"Enable PDL for the consumer on SM90+\"). Python launch sites already gate PDL on `current_platform.is_arch_support_pdl()`.\n- The static is initialized once per template instantiation, on the device the caller's `DeviceGuard` selects. It assumes all GPUs in a process share the major arch, which holds for vLLM workers (one GPU each); a mismatch would only affect speed, not results.\n- Other C++ launchers still set the attribute on all archs, for example `topk_softplus_sqrt_kernels.cu` and `per_token_group_quant.cu` (the latter can run on sm89 for FP8). They are left out to keep this fix small enough to cherry-pick; a shared helper can follow if maintainers prefer.\n- Not a duplicate: no open issue or PR changes this launch attribute (searched `topkGating PDL`, `topk_softmax PDL`, `59737`). #62912 (open) changes top-k selection in the same file and keeps `config.numAttrs = 1` as context next to this change, so whichever lands second needs a small rebase; it does not touch the attribute.\n- I used AI assistance (Claude) for the investigation, the code and the tests. I reviewed every changed line and ran the tests and GPU checks above.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/csrc/moe/topk_softmax_kernels.cu b/csrc/moe/topk_softmax_kernels.cu\nindex abacf6502b1c..b687e95f75e8 100644\n--- a/csrc/moe/topk_softmax_kernels.cu\n+++ b/csrc/moe/topk_softmax_kernels.cu\n@@ -627,6 +627,8 @@ void topkGatingLauncherHelper(const InputType* input, const bool* finished, floa\n \n dim3 block_dim(WARP_SIZE_PARAM, WARPS_PER_TB);\n #ifndef USE_ROCM\n+ // Pre-SM90 cannot use PDL, but the attribute still adds a programmatic edge to captured CUDA graphs.\n+ static const bool use_pdl = get_device_prop()->major >= 9;\n cudaLaunchConfig_t config{};\n config.gridDim = dim3(num_blocks);\n config.blockDim = block_dim;\n@@ -635,7 +637,7 @@ void topkGatingLauncherHelper(const InputType* input, const bool* finished, floa\n attr.id = cudaLaunchAttributeProgrammaticStreamSerialization;\n attr.val.programmaticStreamSerializationAllowed = 1;\n config.attrs = &attr;\n- config.numAttrs = 1;\n+ config.numAttrs = use_pdl ? 1 : 0;\n auto err = cudaLaunchKernelEx(\n &config,\n topkGating,\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Benchmark] Keep numeric-string prompts as strings in CustomDataset\nLabels: bug, performance, ready\nFiles changed (2): tests/benchmarks/test_custom_dataset_seed.py, vllm/benchmarks/datasets/datasets.py\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n\n- JSON string prompts are kept exactly as written, regardless of what other rows contain.\n- `output_tokens` and other columns are unaffected.\n\n## Validation\n[results removed]\n## Details\n\nThe other two `pd.read_json` callers in `datasets.py` read list-valued columns (`turns` / `messages`), which pandas does not coerce, so they are left alone.\n\nNot a duplicate: no open PR references #65071. #60506 and #61776 also touch `CustomDataset` but address output lengths / audio without a tokenizer in `sample()`, not the `read_json` dtype.\n\n---\n\nAI assistance (Claude) was used to locate the root cause, write the fix and test, and run the validation above; I reviewed every changed line and ran the tests locally.\n\n## Diff\n\n```diff\ndiff --git a/vllm/benchmarks/datasets/datasets.py b/vllm/benchmarks/datasets/datasets.py\nindex 3746ac727e0f..322e409aac4f 100644\n--- a/vllm/benchmarks/datasets/datasets.py\n+++ b/vllm/benchmarks/datasets/datasets.py\n@@ -2451,7 +2451,10 @@ def load_data(self) -> None:\n \n # Load the JSONL file\n if self.dataset_path.endswith(\".jsonl\"):\n- jsonl_data = pd.read_json(path_or_buf=self.dataset_path, lines=True)\n+ # Keep prompts like \"00123\" as strings instead of inferring numbers.\n+ jsonl_data = pd.read_json(\n+ path_or_buf=self.dataset_path, lines=True, dtype={\"prompt\": str}\n+ )\n \n # check if the JSONL file has a 'prompt' column\n if \"prompt\" not in jsonl_data.columns:\n\ndiff --git a/tests/benchmarks/test_custom_dataset_seed.py b/tests/benchmarks/test_custom_dataset_seed.py\nindex d23ce40b53e7..e38b1451655c 100644\n--- a/tests/benchmarks/test_custom_dataset_seed.py\n+++ b/tests/benchmarks/test_custom_dataset_seed.py\n@@ -5,9 +5,11 @@\n from pathlib import Path\n \n import pytest\n-from transformers import AutoTokenizer, PreTrainedTokenizerBase\n+from tokenizers import Tokenizer\n+from tokenizers.models import WordLevel\n+from transformers import AutoTokenizer, PreTrainedTokenizerBase, TokenizersBackend\n \n-from vllm.benchmarks.datasets import get_samples\n+from vllm.benchmarks.datasets import CustomDataset, get_samples\n \n \n @pytest.fixture(scope=\"session\")\n@@ -75,3 +77,22 @@ def test_custom_dataset_same_seed_is_deterministic(\n prompts_b = [s.prompt for s in samples_b]\n \n assert prompts_a == prompts_b\n+\n+\n+@pytest.mark.benchmark\n+def test_custom_dataset_keeps_numeric_string_prompts(tmp_path: Path) -> None:\n+ \"\"\"All-numeric string prompts must not be inferred as numbers by pandas.\"\"\"\n+ prompts = [\"00123\", \"00456\"]\n+ jsonl = tmp_path / \"data.jsonl\"\n+ jsonl.write_text(\n+ \"\".join(json.dumps({\"prompt\": p, \"output_tokens\": 4}) + \"\\n\" for p in prompts)\n+ )\n+ tokenizer = TokenizersBackend(\n+ tokenizer_object=Tokenizer(WordLevel({\"[UNK]\": 0}, unk_token=\"[UNK]\")),\n+ unk_token=\"[UNK]\",\n+ )\n+\n+ dataset = CustomDataset(dataset_path=str(jsonl), disable_shuffle=True)\n+ requests = dataset.sample(tokenizer, num_requests=2, skip_chat_template=True)\n+\n+ assert [r.prompt for r in requests] == prompts\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Pooling] Fix scoring token limits with MistralTokenizer\nLabels: bug, frontend, ready, mistral, pooling\nFiles changed (3): tests/entrypoints/pooling/scoring/test_bi_encoder_offline.py, tests/entrypoints/pooling/scoring/test_utils.py, vllm/entrypoints/pooling/scoring/utils.py\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n\n- HF tokenizers are unaffected: they keep the existing `offset_mapping` code.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause.** `truncate_text_to_tokens`, added in #38827, calls `tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)` before checking the length. vLLM's `MistralTokenizer.__call__` has a fixed signature without that argument, so every positive limit raised, even for text already within it. Forwarding the argument would not help, because transformers' `MistralCommonBackend` raises a `ValueError` for `return_offsets_mapping=True`. This went unnoticed because `test_max_tokens_per_doc.py` only covers HF tokenizers.\n\n**Who is affected.** Pooling models that end up with `MistralTokenizer`: either `--tokenizer-mode mistral`, or the default `auto` on official Mistral repos, such as `--convert embed` on `mistralai/Mistral-7B-Instruct-v0.3`. Bi-encoder, late-interaction and Jina-ranking scoring all go through `_truncate_scoring_data`, so they share the fix. Cross-encoder scoring already rejects `MistralTokenizer`. Popular Mistral-based embedding models (e5-mistral, SFR-Embedding-Mistral, Linq-Embed-Mistral) ship HF tokenizers and were never affected.\n\n**Fix.** For `MistralTokenizer`, the helper encodes the text, decodes the first `max_tokens` ids, and cuts the original text at the length of that decoded prefix. The existing loop then re-encodes and repeats until the text fits, as on the offsets path. The result is therefore always a prefix of the original text and never exceeds the limit. `skip_special_tokens=True` is required: without it, `MistralTokenizer.decode` returns raw SentencePiece pieces (`'▁line▁one<0x0A>line'`), whose length doesn't match the original text.\n\n**Why `is_mistral_tokenizer`.** `MistralTokenizer.is_fast` is `True`, so an `is_fast` check (what `HfRenderer._can_produce_offsets` uses) would still send it down the offsets path. The renderer's private method also isn't reachable from this helper. The cross-encoder processor uses the same `is_mistral_tokenizer` check to reject Mistral.\n\n**Not a duplicate.** No open PR references #65075. Two open PRs touch `return_offsets_mapping`, #61363 and #62691, but both change only renderer and tokenizer code, not the scoring helper. #62691 adds `return_special_tokens_mask`, not offsets, to `MistralTokenizer.__call__`.\n\nNo docs change: this adds no options, and the docs don't say Mistral tokenizers are unsupported.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/pooling/scoring/utils.py b/vllm/entrypoints/pooling/scoring/utils.py\nindex dd879778aef5..2edc0ef3345e 100644\n--- a/vllm/entrypoints/pooling/scoring/utils.py\n+++ b/vllm/entrypoints/pooling/scoring/utils.py\n@@ -17,6 +17,7 @@\n MultiModalItemTracker,\n parse_chat_message_content_parts,\n )\n+from vllm.utils.mistral import is_mistral_tokenizer\n \n from .typing import (\n ScoreContentPartParam,\n@@ -48,22 +49,35 @@ def truncate_text_to_tokens(\n \n Uses offset_mapping to slice the original text at the exact character\n boundary, avoiding lossy encode→decode round-trips that can shift\n- the token count due to BPE merge boundary changes.\n+ the token count due to BPE merge boundary changes. MistralTokenizer has\n+ no offset_mapping, so its boundary comes from the decoded token prefix;\n+ the token count of the sliced text is re-checked either way.\n \"\"\"\n if max_tokens <= 0:\n return \"\"\n \n while text:\n- encoding = tokenizer(\n- text,\n- add_special_tokens=False,\n- return_offsets_mapping=True,\n- )\n- offsets = encoding[\"offset_mapping\"]\n- if len(encoding[\"input_ids\"]) <= max_tokens:\n- break\n-\n- char_end = min(offsets[max_tokens - 1][1], offsets[max_tokens][0])\n+ if is_mistral_tokenizer(tokenizer):\n+ token_ids = tokenizer.encode(text, add_special_tokens=False)\n+ if len(token_ids) <= max_tokens:\n+ break\n+\n+ # Unless special tokens are skipped, SentencePiece pieces such as\n+ # \"▁\" and \"<0x0A>\" are decoded verbatim.\n+ prefix = tokenizer.decode(token_ids[:max_tokens], skip_special_tokens=True)\n+ char_end = len(prefix)\n+ else:\n+ encoding = tokenizer(\n+ text,\n+ add_special_tokens=False,\n+ return_offsets_mapping=True,\n+ )\n+ offsets = encoding[\"offset_mapping\"]\n+ if len(encoding[\"input_ids\"]) <= max_tokens:\n+ break\n+\n+ char_end = min(offsets[max_tokens - 1][1], offsets[max_tokens][0])\n+\n if char_end >= len(text):\n char_end = len(text) - 1\n text = text[:char_end]\n\ndiff --git a/tests/entrypoints/pooling/scoring/test_bi_encoder_offline.py b/tests/entrypoints/pooling/scoring/test_bi_encoder_offline.py\nindex 5f0ba9c60e1c..1baee1b4ae5c 100644\n--- a/tests/entrypoints/pooling/scoring/test_bi_encoder_offline.py\n+++ b/tests/entrypoints/pooling/scoring/test_bi_encoder_offline.py\n@@ -6,6 +6,8 @@\n import pytest\n \n from tests.entrypoints.pooling.scoring.util import EncoderScoringHfRunner\n+from vllm import PoolingParams\n+from vllm.utils.mistral import is_mistral_tokenizer\n \n MODEL_NAME = \"intfloat/multilingual-e5-small\"\n PROMPT = \"The chef prepared a delicious meal.\"\n@@ -99,3 +101,32 @@ def test_embed(llm):\n outputs = llm.encode(PROMPT, pooling_task=\"embed\", use_tqdm=False)\n assert len(outputs) == 1\n assert len(outputs[0].outputs.data) == EMBEDDING_SIZE\n+\n+\n+def test_token_limits_with_mistral_tokenizer(vllm_runner):\n+ \"\"\"MistralTokenizer cannot return offset_mapping, but scoring token limits\n+ must still truncate the query and leave a short document unchanged.\n+\n+ Only tokenization matters, so the model has dummy weights and one layer.\n+ \"\"\"\n+ with vllm_runner(\n+ \"mistralai/Mistral-7B-Instruct-v0.3\",\n+ runner=\"pooling\",\n+ convert=\"embed\",\n+ load_format=\"dummy\",\n+ hf_overrides={\"num_hidden_layers\": 1},\n+ gpu_memory_utilization=0.3,\n+ enforce_eager=True,\n+ ) as runner:\n+ llm = runner.llm\n+ assert is_mistral_tokenizer(llm.get_tokenizer())\n+\n+ params = PoolingParams(\n+ extra_kwargs={\"max_tokens_per_query\": 3, \"max_tokens_per_doc\": 100}\n+ )\n+ (limited,) = llm.score(\n+ TEXTS_1[0], TEXTS_2[0], pooling_params=params, use_tqdm=False\n+ )\n+ (expected,) = llm.score(\"What is the\", TEXTS_2[0], use_tqdm=False)\n+\n+ assert limited.prompt_token_ids == expected.prompt_token_ids\ndiff --git a/tests/entrypoints/pooling/scoring/test_utils.py b/tests/entrypoints/pooling/scoring/test_utils.py\nindex ddd3c082be1c..98525ce23b8d 100644\n--- a/tests/entrypoints/pooling/scoring/test_utils.py\n+++ b/tests/entrypoints/pooling/scoring/test_utils.py\n@@ -11,6 +11,7 @@\n validate_score_input,\n )\n from vllm.exceptions import VLLMValidationError\n+from vllm.tokenizers.mistral import MistralTokenizer\n \n \n @pytest.mark.parametrize(\n@@ -82,3 +83,16 @@ def test_truncate_text_to_tokens_handles_shared_character_offsets():\n \n assert truncated == \"a\"\n assert len(tokenizer(truncated, add_special_tokens=False)[\"input_ids\"]) == 1\n+\n+\n+@pytest.mark.parametrize(\n+ \"model_name\",\n+ [\"mistralai/Mistral-7B-Instruct-v0.3\", \"mistralai/Magistral-Small-2509\"],\n+)\n+def test_truncate_text_to_tokens_with_mistral_tokenizer(model_name: str):\n+ \"\"\"MistralTokenizer cannot return offset_mapping, but limits still apply.\"\"\"\n+ tokenizer = MistralTokenizer.from_pretrained(model_name)\n+ text = \"The quick brown fox jumps over the lazy dog\"\n+\n+ assert truncate_text_to_tokens(text, tokenizer, max_tokens=3) == \"The quick brown\"\n+ assert truncate_text_to_tokens(text, tokenizer, max_tokens=100) == text\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Validate global model seed range\nLabels: bug, ready\nFiles changed (2): tests/entrypoints/llm/test_prompt_validation.py, vllm/config/model.py\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n- Constrain `ModelConfig.seed` to NumPy's supported range `[0, 2**32 - 1]`, and document the range.\n\n## Validation\n[results removed]\n## Details\n`ModelConfig.seed` was previously unbounded. Invalid values would propagate into `np.random.seed()` during worker initialization and crash the engine.\nThe config field now validates against NumPy's supported range before worker startup.\n\nDuplicate-work check: Coordinated with @ntu-b12505041; they are okay with me taking this fix. No existing open PR referenced #64953.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/config/model.py b/vllm/config/model.py\nindex 382a41486f32..0434f1291306 100644\n--- a/vllm/config/model.py\n+++ b/vllm/config/model.py\n@@ -212,9 +212,11 @@ class ModelConfig:\n - \"bfloat16\" for a balance between precision and range.\n - \"float\" is shorthand for FP32 precision.\n - \"float32\" for FP32 precision.\"\"\"\n- seed: int = 0\n+ seed: int = Field(default=0, ge=0, le=2**32 - 1)\n \"\"\"Random seed for reproducibility.\n \n+ The seed must be in the range [0, 2**32 - 1].\n+\n We must set the global seed because otherwise,\n different tensor parallel workers would sample different tokens,\n leading to inconsistent results.\"\"\"\n\ndiff --git a/tests/entrypoints/llm/test_prompt_validation.py b/tests/entrypoints/llm/test_prompt_validation.py\nindex 40e5e7b14bdd..94e3bf7883e3 100644\n--- a/tests/entrypoints/llm/test_prompt_validation.py\n+++ b/tests/entrypoints/llm/test_prompt_validation.py\n@@ -3,7 +3,9 @@\n \n import pytest\n import torch\n+from transformers import GPT2Config\n \n+from vllm import LLM\n from vllm.exceptions import VLLMValidationError\n \n \n@@ -52,3 +54,25 @@ def test_require_mm_embeds(vllm_runner):\n \"multi_modal_data\": {\"image\": torch.empty(1, 1, 1)},\n }\n )\n+\n+\n+@pytest.mark.parametrize(\"seed\", [-1, 2**32])\n+def test_model_seed_out_of_numpy_range_fails_during_initialization(tmp_path, seed):\n+ GPT2Config(\n+ n_layer=1,\n+ n_head=1,\n+ n_embd=8,\n+ vocab_size=16,\n+ bos_token_id=1,\n+ eos_token_id=2,\n+ ).save_pretrained(tmp_path)\n+\n+ with pytest.raises(ValueError, match=\"seed\"):\n+ LLM(\n+ model=str(tmp_path),\n+ seed=seed,\n+ skip_tokenizer_init=True,\n+ load_format=\"dummy\",\n+ max_model_len=16,\n+ enforce_eager=True,\n+ )\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fix startup illegal memory access from unaligned extensible KV cache segments\nLabels: bug, ready\nFiles changed (5): tests/kernels/attention/test_flashmla_sparse.py, tests/v1/worker/test_extensible_kv_cache.py, tests/v1/worker/test_gpu_worker.py, vllm/v1/worker/extensible_kv_cache.py, vllm/v1/worker/gpu_worker.py\n\n## Description (results removed)\n\n## Overview\n\nFix a startup illegal memory access in FlashMLA sparse prefill with the extensible KV cache (#56492), reproduced with DeepSeek-V3.2 on B300.\n\nFlashInfer autotuning runs FlashMLA before warmup expands the cache. When a sparse gather includes an invalid (padding) index, FlashMLA reads past the selected rows. With only the null block committed, those reads can reach unmapped memory inside the layer's reserved KV view.\n\nThis PR extends the segment alignment introduced in #65225 to caches without an RDMA connector, and commits a second block at allocation for block-outermost layouts (follow-up commit by Nick Hill).\n\n[image]\n\n## Claims\n\n- Prevents the reproduced startup crash by keeping memory mapped beyond each layer's initial KV rows.\n- Covers block-compact, layer-outermost layouts and block-outermost layouts.\n- Preserves logical KV capacity and block strides.\n\n## Validation\n[results removed]\n## Details\n\nThe fix handles the two layouts differently:\n\n- **Block-compact, layer-outermost:** align each layer's segment to a memory granule, so committing the null block maps the full first granule. This reuses the existing RDMA padding path. Padding increases reserved address space without adding physical memory, since each segment's commits already map whole granules.\n\nLayouts that are neither, such as `LHBNC`, keep the current allocation; forcing `LHBNC` with sparse MLA can still fault.\n\nThis keeps the allocation policy independent of a hard-coded FlashMLA access size.\n\nAI assistance (Claude Code) was used to investigate the crash, write the change and tests, and draft this description. The submitter reviewed every changed line and ran the tests and evaluations listed above.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/worker/extensible_kv_cache.py b/vllm/v1/worker/extensible_kv_cache.py\nindex 94df470045df..5b42b3c0e49e 100644\n--- a/vllm/v1/worker/extensible_kv_cache.py\n+++ b/vllm/v1/worker/extensible_kv_cache.py\n@@ -98,6 +98,7 @@ def __init__(\n self.capacity_blocks = kv_cache_config.num_blocks\n if self.capacity_blocks <= 0:\n raise ValueError(f\"Invalid KV cache capacity {self.capacity_blocks}.\")\n+ self._is_block_outermost = layout.is_block_outermost\n self.segment_offsets, self.segment_strides = self._segments(tensors, layout)\n self.bytes_per_block = sum(self.segment_strides)\n self.num_committed_blocks = 0\n@@ -169,9 +170,14 @@ def _segments(\n return offsets, strides\n \n def allocate(self, size: int) -> torch.Tensor:\n- \"\"\"Allocator hook for allocate_kv_cache; commits only the null block.\"\"\"\n+ \"\"\"Allocator hook for allocate_kv_cache; commits the null block.\n+\n+ Under block-outermost layouts layers' views start inside block 0, so a\n+ second block keeps at least half a granule mapped past each view's start\n+ (see `pad_kv_cache_segments` for what reads it).\n+ \"\"\"\n assert size == self.size, f\"Expected {self.size} bytes, got {size}.\"\n- self.commit(1)\n+ self.commit(2 if self._is_block_outermost else 1)\n return self.buffer.full_view()\n \n def commit(\n@@ -373,18 +379,29 @@ def registers_kv_cache_memory(vllm_config: \"VllmConfig\") -> bool:\n \n \n def pad_kv_cache_segments(\n- kv_cache_config: KVCacheConfig, layout: KVCacheLayout, granule: int\n+ kv_cache_config: KVCacheConfig,\n+ layout: KVCacheLayout,\n+ granule: int,\n+ *,\n+ registers_memory: bool = False,\n ) -> KVCacheConfig:\n- \"\"\"Start every layer's region on a granule, so that a defragmenting commit\n- of any block count can back each segment with one physical chunk.\n+ \"\"\"Start every layer's region on a granule.\n+\n+ Committing the null block then backs each layer's first granule, which\n+ TMA gathers with out-of-bounds indices touch beyond the rows they address.\n+ It also lets a defragmenting commit of any block count back each segment\n+ with one physical chunk, as RDMA registration (registers_memory) requires.\n \n Only address space grows: commits already map whole granules per segment.\n- Block-outermost layouts have a single segment at offset 0 and are returned\n- as is.\n+ Block-outermost layouts (one segment at offset 0, see `allocate`) are\n+ returned as is, and so are other layouts that are not block-compact, unless\n+ registers_memory.\n \"\"\"\n if layout.is_block_outermost:\n return kv_cache_config\n- assert layout.is_block_compact, f\"{layout.name} has no per-layer segments.\"\n+ if not layout.is_block_compact:\n+ assert not registers_memory, f\"{layout.name} has no per-layer segments.\"\n+ return kv_cache_config\n num_blocks = kv_cache_config.num_blocks\n tensors = kv_cache_config.kv_cache_tensors\n assert all(t.layer_stride == num_blocks * t.block_stride for t in tensors)\ndiff --git a/vllm/v1/worker/gpu_worker.py b/vllm/v1/worker/gpu_worker.py\nindex 0b7b40ad92cf..7a3706d46df3 100644\n--- a/vllm/v1/worker/gpu_worker.py\n+++ b/vllm/v1/worker/gpu_worker.py\n@@ -969,12 +969,12 @@ def initialize_from_config(self, kv_cache_config: KVCacheConfig) -> None:\n # related to kv cache connector (e.g. kv cache sharing layers).\n allocation_context = self._maybe_get_memory_pool_context(tag=\"kv_cache\")\n if self.cache_config.enable_extensible_kv_cache:\n- if registers_kv_cache_memory(self.vllm_config):\n- kv_cache_config = pad_kv_cache_segments(\n- kv_cache_config,\n- self.cache_config.get_resolved_kv_cache_layout(),\n- granule_size(torch.accelerator.current_device_index()),\n- )\n+ kv_cache_config = pad_kv_cache_segments(\n+ kv_cache_config,\n+ self.cache_config.get_resolved_kv_cache_layout(),\n+ granule_size(torch.accelerator.current_device_index()),\n+ registers_memory=registers_kv_cache_memory(self.vllm_config),\n+ )\n # The connector is created in `extend_kv_cache`, once the\n # memory it registers is final.\n self._kv_cache_config = kv_cache_config\n\ndiff --git a/tests/kernels/attention/test_flashmla_sparse.py b/tests/kernels/attention/test_flashmla_sparse.py\nindex 8fcf3f6a5870..1e9abef5a5e6 100644\n--- a/tests/kernels/attention/test_flashmla_sparse.py\n+++ b/tests/kernels/attention/test_flashmla_sparse.py\n@@ -225,6 +225,79 @@ def test_sparse_flashmla_prefill_smoke(h_q: int):\n assert actual[0].shape == (s_q, h_q, d_v)\n \n \n+@pytest.mark.parametrize(\n+ (\"layout_name\", \"num_layers\", \"num_blocks\"),\n+ [\n+ # Unpadded, layer 1 would start 104 KiB below a granule boundary.\n+ (\"LBNHC\", 2, 27),\n+ # Block 0 alone would leave the last layer's view 104 KiB or 96 KiB.\n+ (\"BLNHC\", 28, 8),\n+ (\"BLNHC\", 85, 8),\n+ ],\n+)\n+def test_sparse_flashmla_prefill_on_the_kv_cache_at_allocation(\n+ layout_name: str, num_layers: int, num_blocks: int\n+):\n+ \"\"\"On SM100, a TMA gather with an out-of-bounds index reads up to 128 KiB past\n+ the start of the KV view. Autotuning runs this before warmup commits more than\n+ the extensible cache's first blocks, which an illegal access would crash.\"\"\"\n+ import vllm.v1.attention.ops.flashmla as fm\n+ from vllm.config import ModelConfig, VllmConfig\n+ from vllm.utils.extensible_tensor import granule_size\n+ from vllm.utils.vmm_driver import vmm_unavailable_reason\n+ from vllm.v1.attention.backends.mla.sparse_utils import flat_kv_row_view\n+ from vllm.v1.core.kv_cache_planning import get_kv_cache_config_from_groups\n+ from vllm.v1.kv_cache_interface import KVCacheGroupSpec, MLAAttentionSpec\n+ from vllm.v1.kv_cache_layout import KVCacheLayout\n+ from vllm.v1.worker.extensible_kv_cache import (\n+ ExtensibleKVCache,\n+ pad_kv_cache_segments,\n+ )\n+ from vllm.v1.worker.utils import allocate_kv_cache\n+\n+ ok, reason = fm.is_flashmla_sparse_supported()\n+ if not ok:\n+ pytest.skip(reason)\n+ if (reason := vmm_unavailable_reason()) is not None:\n+ pytest.skip(f\"VMM unavailable: {reason}\")\n+\n+ device = torch.device(\"cuda\")\n+ block_size, d_qk, h_q, s_q, topk = 64, 576, 64, 128, 2048\n+ layout = KVCacheLayout[layout_name]\n+ spec = MLAAttentionSpec(\n+ block_size=block_size, num_kv_heads=1, head_size=d_qk, dtype=torch.bfloat16\n+ )\n+ vllm_config = VllmConfig(model_config=ModelConfig(max_model_len=16))\n+ vllm_config.cache_config.kv_cache_layout = layout.name\n+ layers = [f\"layer.{i}\" for i in range(num_layers)]\n+ config = get_kv_cache_config_from_groups(\n+ vllm_config,\n+ [KVCacheGroupSpec(layers, spec)],\n+ available_memory=num_layers * spec.page_size_bytes * num_blocks,\n+ )\n+ assert config.num_blocks == num_blocks\n+ config = pad_kv_cache_segments(\n+ config, layout, granule_size(torch.accelerator.current_device_index())\n+ )\n+ kv_cache = ExtensibleKVCache(config, device, layout)\n+ try:\n+ views = allocate_kv_cache(config, device, layout, allocate=kv_cache.allocate)\n+ q = torch.randn((s_q, h_q, d_qk), dtype=torch.bfloat16, device=device)\n+ # The farthest reach: one valid slot in an int4 group of invalid ones, on\n+ # the last row of a 64-row page.\n+ indices = torch.full((s_q, 1, topk), -1, dtype=torch.int32, device=device)\n+ indices[..., 0] = block_size - 1\n+ topk_length = torch.ones(s_q, dtype=torch.int32, device=device)\n+ for layer in layers:\n+ rows, _ = flat_kv_row_view(views[layer].squeeze(1), block_size)\n+ fm.flash_mla_sparse_fwd(\n+ q, rows.unsqueeze(1), indices, d_qk**-0.5, topk_length=topk_length\n+ )\n+ torch.accelerator.synchronize()\n+ finally:\n+ kv_cache.free()\n+\n+\n def test_deepseek_v4_prefill_chunk_planning_expands_for_short_sequences():\n from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata\n \ndiff --git a/tests/v1/worker/test_extensible_kv_cache.py b/tests/v1/worker/test_extensible_kv_cache.py\nindex 275005647dd9..8a7c6513edc8 100644\n--- a/tests/v1/worker/test_extensible_kv_cache.py\n+++ b/tests/v1/worker/test_extensible_kv_cache.py\n@@ -15,6 +15,7 @@\n FullAttentionSpec,\n KVCacheGroupSpec,\n KVCacheTensor,\n+ MLAAttentionSpec,\n UniformTypeKVCacheSpecs,\n )\n from vllm.v1.kv_cache_layout import KVCacheLayout\n@@ -368,6 +369,67 @@ def test_pad_kv_cache_segments():\n config, _ = _make_config(KVCacheLayout.BLNHC)\n assert pad_kv_cache_segments(config, KVCacheLayout.BLNHC, granule) is config\n \n+ # LHBNC has no per-layer segments: left alone, unless a connector needs them.\n+ config, _ = _make_config(KVCacheLayout.LHBNC)\n+ assert pad_kv_cache_segments(config, KVCacheLayout.LHBNC, granule) is config\n+ with pytest.raises(AssertionError, match=\"LHBNC\"):\n+ pad_kv_cache_segments(\n+ config, KVCacheLayout.LHBNC, granule, registers_memory=True\n+ )\n+\n+\n+def _layout_of_segments(worker):\n+ kv_cache = worker.model_runner.extensible_kv_cache\n+ granule = kv_cache.buffer.granularity\n+ return kv_cache.segment_offsets, granule\n+\n+\n+@requires_cuda\n+def test_engine_pads_segments_without_a_connector(\n+ vmm, vllm_runner, enable_pickle, monkeypatch\n+):\n+ \"\"\"A plain engine, with no KV connector, starts each layer on a granule.\"\"\"\n+ # Pinned: some ROCm backends default to LHBNC, which has no per-layer segments.\n+ monkeypatch.setenv(\"VLLM_KV_CACHE_LAYOUT\", KVCacheLayout.LBHNC.name)\n+ with vllm_runner(\n+ \"Qwen/Qwen3-0.6B\",\n+ enforce_eager=True,\n+ max_model_len=256,\n+ ) as runner:\n+ ((offsets, granule),) = runner.llm.collective_rpc(_layout_of_segments)\n+ assert len(offsets) > 1\n+ assert all(offset % granule == 0 for offset in offsets)\n+\n+\n+@requires_cuda\n+@pytest.mark.parametrize(\"num_layers\", [28, 85])\n+def test_block_outermost_views_have_mapped_memory_past_their_start(vmm, num_layers):\n+ \"\"\"Only the null block's bytes would leave the last layer's view under 128 KiB\n+ from unmapped memory: 72 KiB pages put block 0's end just below a granule.\"\"\"\n+ layout = KVCacheLayout.BLNHC\n+ spec = MLAAttentionSpec(\n+ block_size=64, num_kv_heads=1, head_size=576, dtype=torch.bfloat16\n+ )\n+ assert spec.page_size_bytes == 72 << 10\n+ vllm_config = VllmConfig(model_config=ModelConfig(max_model_len=16))\n+ vllm_config.cache_config.kv_cache_layout = layout.name\n+ layers = [f\"layer.{i}\" for i in range(num_layers)]\n+ config = get_kv_cache_config_from_groups(\n+ vllm_config,\n+ [KVCacheGroupSpec(layers, spec)],\n+ available_memory=num_layers * spec.page_size_bytes * NUM_BLOCKS,\n+ )\n+ kv_cache = ExtensibleKVCache(config, torch.device(\"cuda\"), layout)\n+ try:\n+ views = allocate_kv_cache(\n+ config, torch.device(\"cuda\"), layout, allocate=kv_cache.allocate\n+ )\n+ last_view_start = views[layers[-1]].data_ptr() - kv_cache.buffer.base_ptr\n+ granule = kv_cache.buffer.granularity\n+ assert kv_cache.physical_bytes - last_view_start >= granule // 2\n+ finally:\n+ kv_cache.free()\n+\n \n @requires_cuda\n def test_mixed_block_strides_commit_per_layer(vmm):\ndiff --git a/tests/v1/worker/test_gpu_worker.py b/tests/v1/worker/test_gpu_worker.py\nindex 5fd40496ed94..255efd530c69 100644\n--- a/tests/v1/worker/test_gpu_worker.py\n+++ b/tests/v1/worker/test_gpu_worker.py\n@@ -537,6 +537,7 @@ def worker(enable_jit_warmup):\n def test_extensible_init_defers_the_connector(monkeypatch: pytest.MonkeyPatch):\n \"\"\"Under the extensible cache the connector is created at the final extend,\n not at init, and the config is kept for it.\"\"\"\n+ from vllm.v1.kv_cache_layout import KVCacheLayout\n from vllm.v1.worker import gpu_worker\n from vllm.v1.worker.gpu_worker import Worker\n \n@@ -544,6 +545,7 @@ def fail(*args, **kwargs):\n raise AssertionError(\"connector created at init\")\n \n monkeypatch.setattr(gpu_worker, \"ensure_kv_transfer_initialized\", fail)\n+ monkeypatch.setattr(gpu_worker, \"granule_size\", lambda device: 2 << 20)\n log: list[str] = []\n runner = SimpleNamespace(\n initialize_kv_cache=lambda *args, **kwargs: log.append(\"initialize_kv_cache\"),\n@@ -559,7 +561,11 @@ def fail(*args, **kwargs):\n cache_hit_alignment_tokens=16,\n )\n worker = SimpleNamespace(\n- cache_config=SimpleNamespace(enable_extensible_kv_cache=True),\n+ cache_config=SimpleNamespace(\n+ enable_extensible_kv_cache=True,\n+ # Block-outermost layouts are not padded, so the config is kept as is.\n+ get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLNHC,\n+ ),\n model_config=SimpleNamespace(enable_return_routed_experts=False),\n vllm_config=SimpleNamespace(kv_transfer_config=None),\n model_runner=runner,\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: InternLM/lmdeploy\nPull request: fix(disagg): await Mooncake async migration executor future (#4971)\nFiles changed (2): lmdeploy/pytorch/disagg/backend/mooncake.py, tests/pytorch/disagg/test_mooncake_async_migration.py\n\n## Description (results removed)\n\n## Summary\n\n- Fixes [#4971](https://github.com/InternLM/lmdeploy/issues/4971): with `LMDEPLOY_USE_ASYNC_MIGRATION`, Decode hung forever after Prefill finished.\n\n## Test plan\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/lmdeploy/pytorch/disagg/backend/mooncake.py b/lmdeploy/pytorch/disagg/backend/mooncake.py\nindex e33056b717..dc1f13a261 100644\n--- a/lmdeploy/pytorch/disagg/backend/mooncake.py\n+++ b/lmdeploy/pytorch/disagg/backend/mooncake.py\n@@ -146,7 +146,6 @@ def register_memory_region(self, register_mr_request: DistServeRegisterMRMessage\n @property\n def endpoint_info(self) -> dict:\n \"\"\"Get endpoint information for this connection.\"\"\"\n-\n mr_info = {}\n for mr_key, buffer_info in self.local_kv_table.items():\n mr_info[mr_key] = {\n@@ -182,17 +181,14 @@ async def p2p_migrate(self, assignment: MigrationAssignment, async_op: bool = Fa\n if not LMDEPLOY_USE_ASYNC_MIGRATION:\n # For synchronous migration, call the method directly\n self._migrate(assignment)\n- else:\n- # For asynchronous migration, use an async method\n- import asyncio\n- loop = asyncio.get_event_loop()\n- future = loop.create_future()\n-\n- await loop.run_in_executor(None, self._migrate, assignment)\n-\n- result = await future\n- if result != 0:\n- raise RuntimeError(f'Failed to perform async transfer: {result}')\n+ return\n+\n+ # Offload the blocking RDMA transfer so the event loop can keep running.\n+ # Await the executor future itself; `_migrate` already raises on failure.\n+ # Do not create a separate unresolved asyncio.Future (hangs Decode forever).\n+ import asyncio\n+ loop = asyncio.get_running_loop()\n+ await loop.run_in_executor(None, self._migrate, assignment)\n \n def _migrate(self, assignment: MigrationAssignment):\n \"\"\"Migrate data to the remote engine synchronously.\"\"\"\ndiff --git a/tests/pytorch/disagg/test_mooncake_async_migration.py b/tests/pytorch/disagg/test_mooncake_async_migration.py\nnew file mode 100644\nindex 0000000000..90137f7e07\n--- /dev/null\n+++ b/tests/pytorch/disagg/test_mooncake_async_migration.py\n@@ -0,0 +1,53 @@\n+\"\"\"Regression: Mooncake async migration must not hang on an unused Future\n+(#4971).\"\"\"\n+\n+from __future__ import annotations\n+\n+import asyncio\n+from types import SimpleNamespace\n+from unittest.mock import MagicMock\n+\n+from lmdeploy.pytorch.disagg.backend.mooncake import MooncakeMigrationManagement\n+\n+\n+def test_p2p_migrate_async_awaits_executor_not_orphan_future(monkeypatch):\n+ \"\"\"With LMDEPLOY_USE_ASYNC_MIGRATION, p2p_migrate must complete when\n+ _migrate returns.\n+\n+ Previously an unresolved asyncio.Future was awaited after run_in_executor, so Decode hung forever even though the\n+ RDMA transfer finished.\n+ \"\"\"\n+ monkeypatch.setattr(\n+ 'lmdeploy.pytorch.disagg.backend.mooncake.LMDEPLOY_USE_ASYNC_MIGRATION',\n+ True,\n+ )\n+\n+ backend = object.__new__(MooncakeMigrationManagement)\n+ called = {'n': 0}\n+\n+ def fake_migrate(_assignment):\n+ called['n'] += 1\n+\n+ backend._migrate = fake_migrate # type: ignore[method-assign]\n+ assignment = SimpleNamespace(batch=[])\n+\n+ async def _run():\n+ await asyncio.wait_for(backend.p2p_migrate(assignment), timeout=2.0)\n+\n+ asyncio.run(_run())\n+ assert called['n'] == 1\n+\n+\n+def test_p2p_migrate_sync_path_calls_migrate_directly(monkeypatch):\n+ \"\"\"Sync path should call _migrate directly without an orphan Future.\"\"\"\n+ monkeypatch.setattr(\n+ 'lmdeploy.pytorch.disagg.backend.mooncake.LMDEPLOY_USE_ASYNC_MIGRATION',\n+ False,\n+ )\n+\n+ backend = object.__new__(MooncakeMigrationManagement)\n+ backend._migrate = MagicMock()\n+ assignment = SimpleNamespace(batch=[])\n+\n+ asyncio.run(backend.p2p_migrate(assignment))\n+ backend._migrate.assert_called_once_with(assignment)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(profiler): size Hub checkpoints from file metadata\nLabels: external-contribution, size/L, fix, planner\nFiles changed (2): components/src/dynamo/profiler/tests/unit/test_model_info.py, components/src/dynamo/profiler/utils/model_info.py\n\n## Description (results removed)\n\n### Overview\n\n### Key Changes\n\nAbout 50 lines in [`profiler/utils/model_info.py`](https://github.com/Alex-Wengg/dynamo/blob/fix/16140-profiler-hub-file-sizes/components/src/dynamo/profiler/utils/model_info.py): request `files_metadata=True` and pick the weight files the way vLLM's default loader does. That means repo-root files of the first format present, minus PEFT adapters and training state, and only the files in `model.safetensors.index.json` when the repo has one (a small JSON download). If any selected file lacks a size, or the index can't be read (a gated repo without access, or a network error), the existing estimate is kept.\n\n### Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/profiler/utils/model_info.py b/components/src/dynamo/profiler/utils/model_info.py\nindex 18aac4e09775..c9983e0722da 100644\n--- a/components/src/dynamo/profiler/utils/model_info.py\n+++ b/components/src/dynamo/profiler/utils/model_info.py\n@@ -1,6 +1,7 @@\n # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n # SPDX-License-Identifier: Apache-2.0\n \n+import importlib\n import json\n import logging\n from pathlib import Path\n@@ -22,6 +23,15 @@ class HuggingFaceDownloadError(Exception):\n pass\n \n _load_model_config_from_model_path = None\n+\n+# huggingface_hub raises its HTTP client's network errors, which are not\n+# OSError: httpx in 1.x, httpx2 in 2.x. Older versions use requests (OSError).\n+HUB_NETWORK_ERRORS: tuple[type[Exception], ...] = ()\n+for _client in (\"httpx\", \"httpx2\"):\n+ try:\n+ HUB_NETWORK_ERRORS += (importlib.import_module(_client).HTTPError,)\n+ except ImportError:\n+ pass\n logger = logging.getLogger(__name__)\n \n DTYPE_BYTES_MAP = {\n@@ -85,24 +95,85 @@ def get_local_model_weight_size(\n return total_size_bytes / (1024**2)\n \n \n+# Checkpoint formats in the order vLLM's default loader prefers them.\n+HUB_WEIGHT_EXTENSIONS = (\".safetensors\", \".bin\", \".pt\", \".pth\")\n+SAFETENSORS_INDEX_NAME = \"model.safetensors.index.json\"\n+# Root files that are not model weights: PEFT adapters and training state,\n+# as in vLLM's filter_files_not_needed_for_inference.\n+NON_WEIGHT_FILENAMES = {\n+ \"adapter_model.safetensors\",\n+ \"adapter_model.bin\",\n+ \"training_args.bin\",\n+ \"optimizer.bin\",\n+ \"optimizer.pt\",\n+ \"scheduler.bin\",\n+ \"scheduler.pt\",\n+ \"scaler.pt\",\n+}\n+\n+\n+def _select_hub_checkpoint_files(model_name: str, info, token: Optional[str]) -> list:\n+ \"\"\"Return the Hub repo files that vLLM would load as the model weights.\n+\n+ Like vLLM's default loader, this takes the repo-root files of the first\n+ format present, skips non-weight files, and keeps only the files listed in\n+ ``model.safetensors.index.json`` when the repo has one. That counts one\n+ copy when a repo ships the weights twice (gpt2 in two formats, Mistral's\n+ consolidated file, Llama's ``original/`` folder).\n+ \"\"\"\n+ siblings = info.siblings or []\n+ root_files = [\n+ sibling\n+ for sibling in siblings\n+ if \"/\" not in sibling.rfilename\n+ and sibling.rfilename not in NON_WEIGHT_FILENAMES\n+ ]\n+ for ext in HUB_WEIGHT_EXTENSIONS:\n+ files = [sibling for sibling in root_files if sibling.rfilename.endswith(ext)]\n+ if not files:\n+ continue\n+ if ext == \".safetensors\" and any(\n+ sibling.rfilename == SAFETENSORS_INDEX_NAME for sibling in siblings\n+ ):\n+ try:\n+ index_path = hf_hub_download(\n+ repo_id=model_name,\n+ filename=SAFETENSORS_INDEX_NAME,\n+ revision=info.sha,\n+ token=token,\n+ )\n+ with open(index_path) as f:\n+ indexed = set(json.load(f)[\"weight_map\"].values())\n+ except (OSError, ValueError, KeyError, *HUB_NETWORK_ERRORS) as e:\n+ # Gated repos refuse the download; the network can fail.\n+ logger.warning(\n+ \"Cannot read %s for %s: %s\", SAFETENSORS_INDEX_NAME, model_name, e\n+ )\n+ return []\n+ files = [sibling for sibling in files if sibling.rfilename in indexed]\n+ # An indexed file missing from the repo would make the sum too small.\n+ if len(files) != len(indexed):\n+ return []\n+ return files\n+ return []\n+\n+\n def get_model_weight_size_from_hub(\n model_name: str,\n token: Optional[str] = None,\n ) -> float:\n \"\"\"Return model size in MB by querying Hugging Face Hub API.\"\"\"\n try:\n- info = model_info(model_name, token=token)\n+ # Sibling file sizes are only populated when file metadata is requested.\n+ info = model_info(model_name, token=token, files_metadata=True)\n \n- # Filter for model weight files (safetensors or pytorch bin files)\n- # Also filter out files with None size\n- weight_extensions = [\".safetensors\", \".bin\", \".pt\", \".pth\"]\n total_size_bytes = 0\n-\n- if info.siblings is not None:\n- for sibling in info.siblings:\n- if any(sibling.rfilename.endswith(ext) for ext in weight_extensions):\n- if sibling.size is not None:\n- total_size_bytes += sibling.size\n+ checkpoint_files = _select_hub_checkpoint_files(model_name, info, token)\n+ # A partial sum would undercount, so fall back to the estimate instead.\n+ if checkpoint_files and all(\n+ sibling.size is not None for sibling in checkpoint_files\n+ ):\n+ total_size_bytes = sum(sibling.size for sibling in checkpoint_files)\n \n # If no file sizes were available, try to estimate from safetensors metadata\n if total_size_bytes == 0 and info.safetensors is not None:\n\ndiff --git a/components/src/dynamo/profiler/tests/unit/test_model_info.py b/components/src/dynamo/profiler/tests/unit/test_model_info.py\nindex 1a85e74f4b01..8f219abec718 100644\n--- a/components/src/dynamo/profiler/tests/unit/test_model_info.py\n+++ b/components/src/dynamo/profiler/tests/unit/test_model_info.py\n@@ -19,6 +19,7 @@\n from dynamo.profiler.utils.model_info import (\n get_mamba_cache_align_block_size,\n get_model_context_length,\n+ get_model_weight_size_from_hub,\n )\n except ImportError as e:\n pytest.skip(f\"Skip (missing dependency): {e}\", allow_module_level=True)\n@@ -157,3 +158,187 @@ class DownloadError(Exception):\n )\n \n assert get_model_context_length(\"test/model\") == 4096\n+\n+\n+MIB = 1024**2\n+\n+\n+def _patch_hub(monkeypatch, tmp_path, files, index=None, parameters=None) -> list:\n+ \"\"\"Serve `files` from a fake Hub repo, with an optional safetensors index.\n+\n+ An exception as `index` lists the index but makes downloading it fail.\n+ \"\"\"\n+ siblings = list(files)\n+ index_path = tmp_path / \"model.safetensors.index.json\"\n+ if isinstance(index, Exception):\n+ siblings.append((index_path.name, 1))\n+ elif index is not None:\n+ weight_map = {f\"weight{i}\": name for i, name in enumerate(index)}\n+ index_path.write_text(json.dumps({\"weight_map\": weight_map}))\n+ siblings.append((index_path.name, index_path.stat().st_size))\n+ info = SimpleNamespace(\n+ sha=\"abc123\",\n+ siblings=[\n+ SimpleNamespace(rfilename=name, size=size) for name, size in siblings\n+ ],\n+ safetensors=(\n+ SimpleNamespace(parameters=parameters) if parameters is not None else None\n+ ),\n+ )\n+ calls = []\n+\n+ def fake_model_info(*args, **kwargs):\n+ calls.append(kwargs)\n+ return info\n+\n+ def fake_hf_hub_download(**kwargs):\n+ assert index is not None, \"downloaded an index the repo does not have\"\n+ assert kwargs[\"revision\"] == info.sha\n+ if isinstance(index, Exception):\n+ raise index\n+ return str(index_path)\n+\n+ monkeypatch.setattr(\"dynamo.profiler.utils.model_info.model_info\", fake_model_info)\n+ monkeypatch.setattr(\n+ \"dynamo.profiler.utils.model_info.hf_hub_download\", fake_hf_hub_download\n+ )\n+ return calls\n+\n+\n+def test_model_weight_size_from_hub_uses_checkpoint_file_sizes(\n+ monkeypatch, tmp_path\n+) -> None:\n+ \"\"\"Packed GPTQ weights are sized from the file, not two bytes per param.\"\"\"\n+ calls = _patch_hub(\n+ monkeypatch,\n+ tmp_path,\n+ [(\"config.json\", 1024), (\"model.safetensors\", 768_148_704)],\n+ parameters={\"I32\": 968_884_224, \"BF16\": 131_164_160, \"F16\": 394_240},\n+ )\n+\n+ assert get_model_weight_size_from_hub(\"test/gptq\") == 768_148_704 / MIB\n+ assert calls[0][\"files_metadata\"] is True\n+\n+\n+@pytest.mark.parametrize(\n+ \"files, index, expected_mib\",\n+ [\n+ # gpt2: the same weights in two formats.\n+ (\n+ [(\"model.safetensors\", 548 * MIB), (\"pytorch_model.bin\", 548 * MIB)],\n+ None,\n+ 548,\n+ ),\n+ # Mistral: a consolidated file next to the indexed shards.\n+ (\n+ [\n+ (\"consolidated.safetensors\", 14 * MIB),\n+ (\"model-00001-of-00002.safetensors\", 8 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 6 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 14,\n+ ),\n+ # Devstral: two shard sets; the model index picks one.\n+ (\n+ [\n+ (\"consolidated-00001-of-00002.safetensors\", 7 * MIB),\n+ (\"consolidated-00002-of-00002.safetensors\", 3 * MIB),\n+ (\"consolidated.safetensors.index.json\", 1),\n+ (\"model-00001-of-00002.safetensors\", 6 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 4 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 10,\n+ ),\n+ # A single file left next to the indexed shards of the same name.\n+ (\n+ [\n+ (\"model-00001-of-00002.safetensors\", 5 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 4 * MIB),\n+ (\"model.safetensors\", 9 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 9,\n+ ),\n+ # An Accelerate checkpoint: optimizer state is larger than the model.\n+ (\n+ [\n+ (\"optimizer.bin\", 4 * MIB),\n+ (\"pytorch_model.bin\", 2 * MIB),\n+ (\"scheduler.bin\", 1),\n+ ],\n+ None,\n+ 2,\n+ ),\n+ # A PEFT adapter next to full PyTorch shards.\n+ (\n+ [\n+ (\"adapter_model.safetensors\", 1 * MIB),\n+ (\"pytorch_model-00001-of-00002.bin\", 9 * MIB),\n+ (\"pytorch_model-00002-of-00002.bin\", 3 * MIB),\n+ (\"training_args.bin\", 1),\n+ ],\n+ None,\n+ 12,\n+ ),\n+ ],\n+)\n+def test_model_weight_size_from_hub_counts_one_checkpoint_copy(\n+ monkeypatch, tmp_path, files, index, expected_mib\n+) -> None:\n+ _patch_hub(monkeypatch, tmp_path, files, index=index)\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == expected_mib\n+\n+\n+@pytest.mark.parametrize(\n+ \"files, index\",\n+ [\n+ # Sizes missing for part of the checkpoint.\n+ (\n+ [\n+ (\"model-00001-of-00002.safetensors\", 4 * MIB),\n+ (\"model-00002-of-00002.safetensors\", None),\n+ ],\n+ None,\n+ ),\n+ # The index lists a shard the repo does not have.\n+ (\n+ [(\"model-00001-of-00002.safetensors\", 4 * MIB)],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ ),\n+ # A gated repo lists its index but refuses the download.\n+ (\n+ [(\"model-00001-of-00001.safetensors\", 4 * MIB)],\n+ OSError(\"403 Client Error\"),\n+ ),\n+ # No weights at the repo root.\n+ ([(\"checkpoints/model.safetensors\", 4 * MIB)], None),\n+ ],\n+)\n+def test_model_weight_size_from_hub_estimates_without_checkpoint_sizes(\n+ monkeypatch, tmp_path, files, index\n+) -> None:\n+ _patch_hub(monkeypatch, tmp_path, files, index=index, parameters={\"BF16\": 3 * MIB})\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == 6\n+\n+\n+@pytest.mark.parametrize(\"client\", [\"httpx\", \"httpx2\"])\n+@pytest.mark.parametrize(\"error_name\", [\"ConnectError\", \"ReadTimeout\"])\n+def test_model_weight_size_from_hub_estimates_on_index_transport_error(\n+ monkeypatch, tmp_path, client, error_name\n+) -> None:\n+ \"\"\"huggingface_hub raises httpx (1.x) or httpx2 (2.x) errors, not OSError.\"\"\"\n+ module = pytest.importorskip(client)\n+ error = getattr(module, error_name)(\"index download failed\")\n+ _patch_hub(\n+ monkeypatch,\n+ tmp_path,\n+ [(\"model-00001-of-00001.safetensors\", 4 * MIB)],\n+ index=error,\n+ parameters={\"BF16\": 3 * MIB},\n+ )\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == 6\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(profiler): size Hub checkpoints from file metadata\nLabels: external-contribution, size/L, fix, planner\nFiles changed (2): components/src/dynamo/profiler/tests/unit/test_model_info.py, components/src/dynamo/profiler/utils/model_info.py\n\n## Description (results removed)\n\n### Overview\n\n### Key Changes\n\nAbout 50 lines in [`profiler/utils/model_info.py`](https://github.com/Alex-Wengg/dynamo/blob/fix/16140-profiler-hub-file-sizes/components/src/dynamo/profiler/utils/model_info.py): request `files_metadata=True` and pick the weight files the way vLLM's default loader does. That means repo-root files of the first format present, minus PEFT adapters and training state, and only the files in `model.safetensors.index.json` when the repo has one (a small JSON download). If any selected file lacks a size, or the index can't be read (a gated repo without access, or a network error), the existing estimate is kept.\n\n### Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/profiler/utils/model_info.py b/components/src/dynamo/profiler/utils/model_info.py\nindex 18aac4e097..b97006012f 100644\n--- a/components/src/dynamo/profiler/utils/model_info.py\n+++ b/components/src/dynamo/profiler/utils/model_info.py\n@@ -22,6 +22,12 @@ except ImportError:\n pass\n \n _load_model_config_from_model_path = None\n+\n+try:\n+ # huggingface_hub 1.x raises httpx network errors, which are not OSError.\n+ from httpx import HTTPError as HTTPXError\n+except ImportError: # Older huggingface_hub raises requests errors (OSError).\n+ HTTPXError = OSError\n logger = logging.getLogger(__name__)\n \n DTYPE_BYTES_MAP = {\n@@ -85,24 +91,85 @@ def get_local_model_weight_size(\n return total_size_bytes / (1024**2)\n \n \n+# Checkpoint formats in the order vLLM's default loader prefers them.\n+HUB_WEIGHT_EXTENSIONS = (\".safetensors\", \".bin\", \".pt\", \".pth\")\n+SAFETENSORS_INDEX_NAME = \"model.safetensors.index.json\"\n+# Root files that are not model weights: PEFT adapters and training state,\n+# as in vLLM's filter_files_not_needed_for_inference.\n+NON_WEIGHT_FILENAMES = {\n+ \"adapter_model.safetensors\",\n+ \"adapter_model.bin\",\n+ \"training_args.bin\",\n+ \"optimizer.bin\",\n+ \"optimizer.pt\",\n+ \"scheduler.bin\",\n+ \"scheduler.pt\",\n+ \"scaler.pt\",\n+}\n+\n+\n+def _select_hub_checkpoint_files(model_name: str, info, token: Optional[str]) -> list:\n+ \"\"\"Return the Hub repo files that vLLM would load as the model weights.\n+\n+ Like vLLM's default loader, this takes the repo-root files of the first\n+ format present, skips non-weight files, and keeps only the files listed in\n+ ``model.safetensors.index.json`` when the repo has one. That counts one\n+ copy when a repo ships the weights twice (gpt2 in two formats, Mistral's\n+ consolidated file, Llama's ``original/`` folder).\n+ \"\"\"\n+ siblings = info.siblings or []\n+ root_files = [\n+ sibling\n+ for sibling in siblings\n+ if \"/\" not in sibling.rfilename\n+ and sibling.rfilename not in NON_WEIGHT_FILENAMES\n+ ]\n+ for ext in HUB_WEIGHT_EXTENSIONS:\n+ files = [sibling for sibling in root_files if sibling.rfilename.endswith(ext)]\n+ if not files:\n+ continue\n+ if ext == \".safetensors\" and any(\n+ sibling.rfilename == SAFETENSORS_INDEX_NAME for sibling in siblings\n+ ):\n+ try:\n+ index_path = hf_hub_download(\n+ repo_id=model_name,\n+ filename=SAFETENSORS_INDEX_NAME,\n+ revision=info.sha,\n+ token=token,\n+ )\n+ with open(index_path) as f:\n+ indexed = set(json.load(f)[\"weight_map\"].values())\n+ except (OSError, ValueError, KeyError, HTTPXError) as e:\n+ # Gated repos refuse the download; the network can fail.\n+ logger.warning(\n+ \"Cannot read %s for %s: %s\", SAFETENSORS_INDEX_NAME, model_name, e\n+ )\n+ return []\n+ files = [sibling for sibling in files if sibling.rfilename in indexed]\n+ # An indexed file missing from the repo would make the sum too small.\n+ if len(files) != len(indexed):\n+ return []\n+ return files\n+ return []\n+\n+\n def get_model_weight_size_from_hub(\n model_name: str,\n token: Optional[str] = None,\n ) -> float:\n \"\"\"Return model size in MB by querying Hugging Face Hub API.\"\"\"\n try:\n- info = model_info(model_name, token=token)\n+ # Sibling file sizes are only populated when file metadata is requested.\n+ info = model_info(model_name, token=token, files_metadata=True)\n \n- # Filter for model weight files (safetensors or pytorch bin files)\n- # Also filter out files with None size\n- weight_extensions = [\".safetensors\", \".bin\", \".pt\", \".pth\"]\n total_size_bytes = 0\n-\n- if info.siblings is not None:\n- for sibling in info.siblings:\n- if any(sibling.rfilename.endswith(ext) for ext in weight_extensions):\n- if sibling.size is not None:\n- total_size_bytes += sibling.size\n+ checkpoint_files = _select_hub_checkpoint_files(model_name, info, token)\n+ # A partial sum would undercount, so fall back to the estimate instead.\n+ if checkpoint_files and all(\n+ sibling.size is not None for sibling in checkpoint_files\n+ ):\n+ total_size_bytes = sum(sibling.size for sibling in checkpoint_files)\n \n # If no file sizes were available, try to estimate from safetensors metadata\n if total_size_bytes == 0 and info.safetensors is not None:\n\ndiff --git a/components/src/dynamo/profiler/tests/unit/test_model_info.py b/components/src/dynamo/profiler/tests/unit/test_model_info.py\nindex 1a85e74f4b..506ccfd67f 100644\n--- a/components/src/dynamo/profiler/tests/unit/test_model_info.py\n+++ b/components/src/dynamo/profiler/tests/unit/test_model_info.py\n@@ -19,6 +19,7 @@ try:\n from dynamo.profiler.utils.model_info import (\n get_mamba_cache_align_block_size,\n get_model_context_length,\n+ get_model_weight_size_from_hub,\n )\n except ImportError as e:\n pytest.skip(f\"Skip (missing dependency): {e}\", allow_module_level=True)\n@@ -157,3 +158,186 @@ def test_model_config_falls_back_when_aic_download_fails(monkeypatch) -> None:\n )\n \n assert get_model_context_length(\"test/model\") == 4096\n+\n+\n+MIB = 1024**2\n+\n+\n+def _patch_hub(monkeypatch, tmp_path, files, index=None, parameters=None) -> list:\n+ \"\"\"Serve `files` from a fake Hub repo, with an optional safetensors index.\n+\n+ An exception as `index` lists the index but makes downloading it fail.\n+ \"\"\"\n+ siblings = list(files)\n+ index_path = tmp_path / \"model.safetensors.index.json\"\n+ if isinstance(index, Exception):\n+ siblings.append((index_path.name, 1))\n+ elif index is not None:\n+ weight_map = {f\"weight{i}\": name for i, name in enumerate(index)}\n+ index_path.write_text(json.dumps({\"weight_map\": weight_map}))\n+ siblings.append((index_path.name, index_path.stat().st_size))\n+ info = SimpleNamespace(\n+ sha=\"abc123\",\n+ siblings=[\n+ SimpleNamespace(rfilename=name, size=size) for name, size in siblings\n+ ],\n+ safetensors=(\n+ SimpleNamespace(parameters=parameters) if parameters is not None else None\n+ ),\n+ )\n+ calls = []\n+\n+ def fake_model_info(*args, **kwargs):\n+ calls.append(kwargs)\n+ return info\n+\n+ def fake_hf_hub_download(**kwargs):\n+ assert index is not None, \"downloaded an index the repo does not have\"\n+ assert kwargs[\"revision\"] == info.sha\n+ if isinstance(index, Exception):\n+ raise index\n+ return str(index_path)\n+\n+ monkeypatch.setattr(\"dynamo.profiler.utils.model_info.model_info\", fake_model_info)\n+ monkeypatch.setattr(\n+ \"dynamo.profiler.utils.model_info.hf_hub_download\", fake_hf_hub_download\n+ )\n+ return calls\n+\n+\n+def test_model_weight_size_from_hub_uses_checkpoint_file_sizes(\n+ monkeypatch, tmp_path\n+) -> None:\n+ \"\"\"Packed GPTQ weights are sized from the file, not two bytes per param.\"\"\"\n+ calls = _patch_hub(\n+ monkeypatch,\n+ tmp_path,\n+ [(\"config.json\", 1024), (\"model.safetensors\", 768_148_704)],\n+ parameters={\"I32\": 968_884_224, \"BF16\": 131_164_160, \"F16\": 394_240},\n+ )\n+\n+ assert get_model_weight_size_from_hub(\"test/gptq\") == 768_148_704 / MIB\n+ assert calls[0][\"files_metadata\"] is True\n+\n+\n+@pytest.mark.parametrize(\n+ \"files, index, expected_mib\",\n+ [\n+ # gpt2: the same weights in two formats.\n+ (\n+ [(\"model.safetensors\", 548 * MIB), (\"pytorch_model.bin\", 548 * MIB)],\n+ None,\n+ 548,\n+ ),\n+ # Mistral: a consolidated file next to the indexed shards.\n+ (\n+ [\n+ (\"consolidated.safetensors\", 14 * MIB),\n+ (\"model-00001-of-00002.safetensors\", 8 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 6 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 14,\n+ ),\n+ # Devstral: two shard sets; the model index picks one.\n+ (\n+ [\n+ (\"consolidated-00001-of-00002.safetensors\", 7 * MIB),\n+ (\"consolidated-00002-of-00002.safetensors\", 3 * MIB),\n+ (\"consolidated.safetensors.index.json\", 1),\n+ (\"model-00001-of-00002.safetensors\", 6 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 4 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 10,\n+ ),\n+ # A single file left next to the indexed shards of the same name.\n+ (\n+ [\n+ (\"model-00001-of-00002.safetensors\", 5 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 4 * MIB),\n+ (\"model.safetensors\", 9 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 9,\n+ ),\n+ # An Accelerate checkpoint: optimizer state is larger than the model.\n+ (\n+ [\n+ (\"optimizer.bin\", 4 * MIB),\n+ (\"pytorch_model.bin\", 2 * MIB),\n+ (\"scheduler.bin\", 1),\n+ ],\n+ None,\n+ 2,\n+ ),\n+ # A PEFT adapter next to full PyTorch shards.\n+ (\n+ [\n+ (\"adapter_model.safetensors\", 1 * MIB),\n+ (\"pytorch_model-00001-of-00002.bin\", 9 * MIB),\n+ (\"pytorch_model-00002-of-00002.bin\", 3 * MIB),\n+ (\"training_args.bin\", 1),\n+ ],\n+ None,\n+ 12,\n+ ),\n+ ],\n+)\n+def test_model_weight_size_from_hub_counts_one_checkpoint_copy(\n+ monkeypatch, tmp_path, files, index, expected_mib\n+) -> None:\n+ _patch_hub(monkeypatch, tmp_path, files, index=index)\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == expected_mib\n+\n+\n+@pytest.mark.parametrize(\n+ \"files, index\",\n+ [\n+ # Sizes missing for part of the checkpoint.\n+ (\n+ [\n+ (\"model-00001-of-00002.safetensors\", 4 * MIB),\n+ (\"model-00002-of-00002.safetensors\", None),\n+ ],\n+ None,\n+ ),\n+ # The index lists a shard the repo does not have.\n+ (\n+ [(\"model-00001-of-00002.safetensors\", 4 * MIB)],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ ),\n+ # A gated repo lists its index but refuses the download.\n+ (\n+ [(\"model-00001-of-00001.safetensors\", 4 * MIB)],\n+ OSError(\"403 Client Error\"),\n+ ),\n+ # No weights at the repo root.\n+ ([(\"checkpoints/model.safetensors\", 4 * MIB)], None),\n+ ],\n+)\n+def test_model_weight_size_from_hub_estimates_without_checkpoint_sizes(\n+ monkeypatch, tmp_path, files, index\n+) -> None:\n+ _patch_hub(monkeypatch, tmp_path, files, index=index, parameters={\"BF16\": 3 * MIB})\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == 6\n+\n+\n+@pytest.mark.parametrize(\"error_name\", [\"ConnectError\", \"ReadTimeout\"])\n+def test_model_weight_size_from_hub_estimates_on_index_transport_error(\n+ monkeypatch, tmp_path, error_name\n+) -> None:\n+ \"\"\"huggingface_hub 1.x raises httpx transport errors, which are not OSError.\"\"\"\n+ httpx = pytest.importorskip(\"httpx\")\n+ error = getattr(httpx, error_name)(\"index download failed\")\n+ _patch_hub(\n+ monkeypatch,\n+ tmp_path,\n+ [(\"model-00001-of-00001.safetensors\", 4 * MIB)],\n+ index=error,\n+ parameters={\"BF16\": 3 * MIB},\n+ )\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == 6\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: server : fix usage.completion_tokens undercount with n > 1\nLabels: server\nFiles changed (2): tools/server/server-context.cpp, tools/server/tests/unit/test_chat_completion.py\n\n## Description (results removed)\n\n## Overview\n\nFix incorrect usage reporting for OpenAI requests with `n > 1`.\n\nFixes #29451.\n\nWhen multiple choices are requested, the server only keeps the usage from the first result. This causes `completion_tokens` and `total_tokens` to be undercounted.\n\nSum `completion_tokens` across all choices and recalculate `total_tokens`, while counting `prompt_tokens` once.\n\nThe issue can be reproduced with the script provided in #29451. With `n=4`, for example, four completions are returned but `completion_tokens` only reports the tokens from one choice.\n\n## Requirements\n\n* I have read and agree with the [[contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md)](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md)\n\n* AI usage disclosure: YES — AI was used to help review the code and run the test.\n\n## Diff\n\n```diff\ndiff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp\nindex e95fb63ab3cc..b4f1c7e57642 100644\n--- a/tools/server/server-context.cpp\n+++ b/tools/server/server-context.cpp\n@@ -4367,10 +4367,20 @@ std::unique_ptr server_routes::handle_completions_impl(\n res->ok(arr[0]);\n } else if (res_type == TASK_RESPONSE_TYPE_OAI_CHAT || res_type == TASK_RESPONSE_TYPE_OAI_CMPL) {\n // if multiple results in OAI format, we need to re-format them\n+ json & usage = arr[0][\"usage\"];\n json & choices = arr[0][\"choices\"];\n for (size_t i = 1; i < arr.size(); i++) {\n choices.push_back(std::move(arr[i][\"choices\"][0]));\n }\n+\n+ // OAI counts generated tokens across all choices\n+ int64_t n_completion_tokens = 0;\n+ for (auto & item : arr) {\n+ n_completion_tokens += item[\"usage\"][\"completion_tokens\"].get();\n+ }\n+ usage[\"completion_tokens\"] = n_completion_tokens;\n+ usage[\"total_tokens\"] = usage[\"prompt_tokens\"].get() + n_completion_tokens;\n+\n res->ok(arr[0]);\n } else {\n // multi-results, non-OAI compat\ndiff --git a/tools/server/tests/unit/test_chat_completion.py b/tools/server/tests/unit/test_chat_completion.py\nindex 0258b539ed87..afbcef030664 100644\n--- a/tools/server/tests/unit/test_chat_completion.py\n+++ b/tools/server/tests/unit/test_chat_completion.py\n@@ -587,6 +587,10 @@ def test_chat_completions_multiple_choices():\n for choice in res.body[\"choices\"]:\n assert \"assistant\" == choice[\"message\"][\"role\"]\n assert choice[\"finish_reason\"] == \"length\"\n+ # each choice generates max_tokens tokens, usage counts them all\n+ # ref: https://github.com/ggml-org/llama.cpp/issues/29451\n+ assert res.body[\"usage\"][\"completion_tokens\"] == 16\n+ assert res.body[\"usage\"][\"total_tokens\"] == res.body[\"usage\"][\"prompt_tokens\"] + 16\n \n \n def test_chat_completions_token_count():\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: llama-quant : fix 4D tensor quantization using ggml_nrows() and name-based expert detection\nLabels: testing, merge ready\nFiles changed (2): src/llama-quant.cpp, tests/snapshots/deepseek-v3.1.schema\n\n## Description (results removed)\n\n## Overview\n\nFix quantization of 4D tensors by using `ggml_nrows()` to count rows, and detect expert tensors by name instead of by shape.\n\nFixes #29916 in https://github.com/ggml-org/llama.cpp/commit/64d1bbb254298a6714c3302b54526082c71c04f7. The row count was computed from `ne[1]` and `ne[2]` only, ignoring `ne[3]`. For tensors like `a.conv1d.0.weight [3, 3, 1, 128]` this produces the wrong size and trips the `gguf_get_tensor_size(...) == new_size` assert. `ggml_nrows()` is now used instead. Other places in `src/llama-quant.cpp` that ignored `ne[3]` are fixed as well.\n\n[details with results removed]\n\n[details with results removed]\n\nOn top of that, we previously used `tensor->ne[2] > 1` to detect expert tensors, but that did not cover all cases and required some hard-coded exclusions for the bailingmoe3 model. Expert tensors are now identified by `_exps.` or `_chexps.` in their name. This new implementation does not break existing models, and it even caught an edge case where the attention weights for deepseek-v3.1 were wrongly treated as expert tensors when they should be quantized as `Q8_0` instead. The test schema has also been updated.\n\n## Requirements\n\n- AI usage disclosure: YES. AI was used for solution exploration and code generation. Every line of generated code has been reviewed by me.\n\n## Log files\n- [reproduced.log](https://github.com/user-attachments/files/33674908/reproduced.log)\n- [after-fix.log](https://github.com/user-attachments/files/33674906/after-fix.log)\n\n## Diff\n\n```diff\ndiff --git a/src/llama-quant.cpp b/src/llama-quant.cpp\nindex b8f96bcef30f..a879701d4e97 100644\n--- a/src/llama-quant.cpp\n+++ b/src/llama-quant.cpp\n@@ -161,6 +161,12 @@ static tensor_category tensor_get_category(const std::string & tensor_name) {\n return tensor_category::OTHER;\n }\n \n+// check if tensor is a MoE expert tensor (used by GGML_OP_MUL_MAT_ID)\n+static bool tensor_is_expert(const std::string & tensor_name) {\n+ return tensor_name.find(\"_exps.\") != std::string::npos ||\n+ tensor_name.find(\"_chexps.\") != std::string::npos;\n+}\n+\n // check if category is for attention-v-like tensors (more sensitive to quantization)\n static bool category_is_attn_v(tensor_category cat) {\n return cat == tensor_category::ATTENTION_V ||\n@@ -296,7 +302,7 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param\n // trivial checks first -- no string ops needed\n if (params->only_copy) return false;\n \n- // quantize only 2D and 3D tensors (experts)\n+ // quantize only 2D+ tensors (matrices, experts, conv kernels)\n if (ggml_n_dims(tensor) < 2) return false;\n \n const std::string name = ggml_get_name(tensor);\n@@ -538,12 +544,7 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type\n } else if (ftype == LLAMA_FTYPE_MOSTLY_MXFP4_MOE) {\n // MoE tensors -> MXFP4\n // other tensors -> Q8_0\n- // MLA projection tensors are also 3D, so match expert tensor roles explicitly.\n- const bool is_bailingmoe3_expert = arch == LLM_ARCH_BAILINGMOE3 &&\n- (category == tensor_category::FFN_UP ||\n- category == tensor_category::FFN_GATE ||\n- category == tensor_category::FFN_DOWN);\n- if (tensor->ne[2] > 1 && (arch != LLM_ARCH_BAILINGMOE3 || is_bailingmoe3_expert)) {\n+ if (tensor_is_expert(name)) {\n new_type = GGML_TYPE_MXFP4;\n } else {\n new_type = GGML_TYPE_Q8_0;\n@@ -1304,11 +1305,11 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::\n if (it == imatrix_data->end()) {\n LLAMA_LOG_INFO(\"\\n====== %s: did not find weights for %s\\n\", __func__, tensor->name);\n } else {\n- if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {\n+ if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]*tensor->ne[3]) {\n imatrix = it->second.data();\n } else {\n LLAMA_LOG_INFO(\"\\n====== %s: imatrix size %d is different from tensor size %d for %s\\n\", __func__,\n- int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);\n+ int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name);\n \n // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix\n // this is a significant error and it may be good idea to abort the process if this happens,\n@@ -1316,7 +1317,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::\n // tok_embd should be ignored in this case, since it always causes this warning\n if (!tensor_name_match_token_embd(tensor->name)) {\n throw std::runtime_error(format(\"imatrix size %d is different from tensor size %d for %s\",\n- int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));\n+ int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name));\n }\n }\n }\n@@ -1338,7 +1339,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::\n \n const int64_t n_per_row = tensor->ne[0];\n const int64_t nrows_per_expert = tensor->ne[1];\n- const int64_t nrows_total = tensor->ne[1] * tensor->ne[2];\n+ const int64_t nrows_total = ggml_nrows(tensor);\n \n const size_t row_size_src = ggml_row_size(tensor->type, n_per_row);\n const size_t row_size_dst = ggml_row_size(new_type, n_per_row);\ndiff --git a/tests/snapshots/deepseek-v3.1.schema b/tests/snapshots/deepseek-v3.1.schema\nindex 0e9dfd6ed4a7..117a76833f4f 100644\n--- a/tests/snapshots/deepseek-v3.1.schema\n+++ b/tests/snapshots/deepseek-v3.1.schema\n@@ -2927,430 +2927,552 @@ blk.60.attn_k_b.weight q4_0\n [MXFP4_MOE] mxfp4\n output.weight q8_0\n token_embd.weight q8_0\n+blk.0.attn_k_b.weight q8_0\n blk.0.attn_kv_a_mqa.weight q8_0\n blk.0.attn_output.weight q8_0\n blk.0.attn_q_a.weight q8_0\n blk.0.attn_q_b.weight q8_0\n+blk.0.attn_v_b.weight q8_0\n blk.0.ffn_down.weight q8_0\n blk.0.ffn_gate.weight q8_0\n blk.0.ffn_up.weight q8_0\n+blk.1.attn_k_b.weight q8_0\n blk.1.attn_kv_a_mqa.weight q8_0\n blk.1.attn_output.weight q8_0\n blk.1.attn_q_a.weight q8_0\n blk.1.attn_q_b.weight q8_0\n+blk.1.attn_v_b.weight q8_0\n blk.1.ffn_down.weight q8_0\n blk.1.ffn_gate.weight q8_0\n blk.1.ffn_up.weight q8_0\n+blk.2.attn_k_b.weight q8_0\n blk.2.attn_kv_a_mqa.weight q8_0\n blk.2.attn_output.weight q8_0\n blk.2.attn_q_a.weight q8_0\n blk.2.attn_q_b.weight q8_0\n+blk.2.attn_v_b.weight q8_0\n blk.2.ffn_down.weight q8_0\n blk.2.ffn_gate.weight q8_0\n blk.2.ffn_up.weight q8_0\n+blk.3.attn_k_b.weight q8_0\n blk.3.attn_kv_a_mqa.weight q8_0\n blk.3.attn_output.weight q8_0\n blk.3.attn_q_a.weight q8_0\n blk.3.attn_q_b.weight q8_0\n+blk.3.attn_v_b.weight q8_0\n blk.3.ffn_down_shexp.weight q8_0\n blk.3.ffn_gate_shexp.weight q8_0\n blk.3.ffn_up_shexp.weight q8_0\n+blk.4.attn_k_b.weight q8_0\n blk.4.attn_kv_a_mqa.weight q8_0\n blk.4.attn_output.weight q8_0\n blk.4.attn_q_a.weight q8_0\n blk.4.attn_q_b.weight q8_0\n+blk.4.attn_v_b.weight q8_0\n blk.4.ffn_down_shexp.weight q8_0\n blk.4.ffn_gate_shexp.weight q8_0\n blk.4.ffn_up_shexp.weight q8_0\n+blk.5.attn_k_b.weight q8_0\n blk.5.attn_kv_a_mqa.weight q8_0\n blk.5.attn_output.weight q8_0\n blk.5.attn_q_a.weight q8_0\n blk.5.attn_q_b.weight q8_0\n+blk.5.attn_v_b.weight q8_0\n blk.5.ffn_down_shexp.weight q8_0\n blk.5.ffn_gate_shexp.weight q8_0\n blk.5.ffn_up_shexp.weight q8_0\n+blk.6.attn_k_b.weight q8_0\n blk.6.attn_kv_a_mqa.weight q8_0\n blk.6.attn_output.weight q8_0\n blk.6.attn_q_a.weight q8_0\n blk.6.attn_q_b.weight q8_0\n+blk.6.attn_v_b.weight q8_0\n blk.6.ffn_down_shexp.weight q8_0\n blk.6.ffn_gate_shexp.weight q8_0\n blk.6.ffn_up_shexp.weight q8_0\n+blk.7.attn_k_b.weight q8_0\n blk.7.attn_kv_a_mqa.weight q8_0\n blk.7.attn_output.weight q8_0\n blk.7.attn_q_a.weight q8_0\n blk.7.attn_q_b.weight q8_0\n+blk.7.attn_v_b.weight q8_0\n blk.7.ffn_down_shexp.weight q8_0\n blk.7.ffn_gate_shexp.weight q8_0\n blk.7.ffn_up_shexp.weight q8_0\n+blk.8.attn_k_b.weight q8_0\n blk.8.attn_kv_a_mqa.weight q8_0\n blk.8.attn_output.weight q8_0\n blk.8.attn_q_a.weight q8_0\n blk.8.attn_q_b.weight q8_0\n+blk.8.attn_v_b.weight q8_0\n blk.8.ffn_down_shexp.weight q8_0\n blk.8.ffn_gate_shexp.weight q8_0\n blk.8.ffn_up_shexp.weight q8_0\n+blk.9.attn_k_b.weight q8_0\n blk.9.attn_kv_a_mqa.weight q8_0\n blk.9.attn_output.weight q8_0\n blk.9.attn_q_a.weight q8_0\n blk.9.attn_q_b.weight q8_0\n+blk.9.attn_v_b.weight q8_0\n blk.9.ffn_down_shexp.weight q8_0\n blk.9.ffn_gate_shexp.weight q8_0\n blk.9.ffn_up_shexp.weight q8_0\n+blk.10.attn_k_b.weight q8_0\n blk.10.attn_kv_a_mqa.weight q8_0\n blk.10.attn_output.weight q8_0\n blk.10.attn_q_a.weight q8_0\n blk.10.attn_q_b.weight q8_0\n+blk.10.attn_v_b.weight q8_0\n blk.10.ffn_down_shexp.weight q8_0\n blk.10.ffn_gate_shexp.weight q8_0\n blk.10.ffn_up_shexp.weight q8_0\n+blk.11.attn_k_b.weight q8_0\n blk.11.attn_kv_a_mqa.weight q8_0\n blk.11.attn_output.weight q8_0\n blk.11.attn_q_a.weight q8_0\n blk.11.attn_q_b.weight q8_0\n+blk.11.attn_v_b.weight q8_0\n blk.11.ffn_down_shexp.weight q8_0\n blk.11.ffn_gate_shexp.weight q8_0\n blk.11.ffn_up_shexp.weight q8_0\n+blk.12.attn_k_b.weight q8_0\n blk.12.attn_kv_a_mqa.weight q8_0\n blk.12.attn_output.weight q8_0\n blk.12.attn_q_a.weight q8_0\n blk.12.attn_q_b.weight q8_0\n+blk.12.attn_v_b.weight q8_0\n blk.12.ffn_down_shexp.weight q8_0\n blk.12.ffn_gate_shexp.weight q8_0\n blk.12.ffn_up_shexp.weight q8_0\n+blk.13.attn_k_b.weight q8_0\n blk.13.attn_kv_a_mqa.weight q8_0\n blk.13.attn_output.weight q8_0\n blk.13.attn_q_a.weight q8_0\n blk.13.attn_q_b.weight q8_0\n+blk.13.attn_v_b.weight q8_0\n blk.13.ffn_down_shexp.weight q8_0\n blk.13.ffn_gate_shexp.weight q8_0\n blk.13.ffn_up_shexp.weight q8_0\n+blk.14.attn_k_b.weight q8_0\n blk.14.attn_kv_a_mqa.weight q8_0\n blk.14.attn_output.weight q8_0\n blk.14.attn_q_a.weight q8_0\n blk.14.attn_q_b.weight q8_0\n+blk.14.attn_v_b.weight q8_0\n blk.14.ffn_down_shexp.weight q8_0\n blk.14.ffn_gate_shexp.weight q8_0\n blk.14.ffn_up_shexp.weight q8_0\n+blk.15.attn_k_b.weight q8_0\n blk.15.attn_kv_a_mqa.weight q8_0\n blk.15.attn_output.weight q8_0\n blk.15.attn_q_a.weight q8_0\n blk.15.attn_q_b.weight q8_0\n+blk.15.attn_v_b.weight q8_0\n blk.15.ffn_down_shexp.weight q8_0\n blk.15.ffn_gate_shexp.weight q8_0\n blk.15.ffn_up_shexp.weight q8_0\n+blk.16.attn_k_b.weight q8_0\n blk.16.attn_kv_a_mqa.weight q8_0\n blk.16.attn_output.weight q8_0\n blk.16.attn_q_a.weight q8_0\n blk.16.attn_q_b.weight q8_0\n+blk.16.attn_v_b.weight q8_0\n blk.16.ffn_down_shexp.weight q8_0\n blk.16.ffn_gate_shexp.weight q8_0\n blk.16.ffn_up_shexp.weight q8_0\n+blk.17.attn_k_b.weight q8_0\n blk.17.attn_kv_a_mqa.weight q8_0\n blk.17.attn_output.weight q8_0\n blk.17.attn_q_a.weight q8_0\n blk.17.attn_q_b.weight q8_0\n+blk.17.attn_v_b.weight q8_0\n blk.17.ffn_down_shexp.weight q8_0\n blk.17.ffn_gate_shexp.weight q8_0\n blk.17.ffn_up_shexp.weight q8_0\n+blk.18.attn_k_b.weight q8_0\n blk.18.attn_kv_a_mqa.weight q8_0\n blk.18.attn_output.weight q8_0\n blk.18.attn_q_a.weight q8_0\n blk.18.attn_q_b.weight q8_0\n+blk.18.attn_v_b.weight q8_0\n blk.18.ffn_down_shexp.weight q8_0\n blk.18.ffn_gate_shexp.weight q8_0\n blk.18.ffn_up_shexp.weight q8_0\n+blk.19.attn_k_b.weight q8_0\n blk.19.attn_kv_a_mqa.weight q8_0\n blk.19.attn_output.weight q8_0\n blk.19.attn_q_a.weight q8_0\n blk.19.attn_q_b.weight q8_0\n+blk.19.attn_v_b.weight q8_0\n blk.19.ffn_down_shexp.weight q8_0\n blk.19.ffn_gate_shexp.weight q8_0\n blk.19.ffn_up_shexp.weight q8_0\n+blk.20.attn_k_b.weight q8_0\n blk.20.attn_kv_a_mqa.weight q8_0\n blk.20.attn_output.weight q8_0\n blk.20.attn_q_a.weight q8_0\n blk.20.attn_q_b.weight q8_0\n+blk.20.attn_v_b.weight q8_0\n blk.20.ffn_down_shexp.weight q8_0\n blk.20.ffn_gate_shexp.weight q8_0\n blk.20.ffn_up_shexp.weight q8_0\n+blk.21.attn_k_b.weight q8_0\n blk.21.attn_kv_a_mqa.weight q8_0\n blk.21.attn_output.weight q8_0\n blk.21.attn_q_a.weight q8_0\n blk.21.attn_q_b.weight q8_0\n+blk.21.attn_v_b.weight q8_0\n blk.21.ffn_down_shexp.weight q8_0\n blk.21.ffn_gate_shexp.weight q8_0\n blk.21.ffn_up_shexp.weight q8_0\n+blk.22.attn_k_b.weight q8_0\n blk.22.attn_kv_a_mqa.weight q8_0\n blk.22.attn_output.weight q8_0\n blk.22.attn_q_a.weight q8_0\n blk.22.attn_q_b.weight q8_0\n+blk.22.attn_v_b.weight q8_0\n blk.22.ffn_down_shexp.weight q8_0\n blk.22.ffn_gate_shexp.weight q8_0\n blk.22.ffn_up_shexp.weight q8_0\n+blk.23.attn_k_b.weight q8_0\n blk.23.attn_kv_a_mqa.weight q8_0\n blk.23.attn_output.weight q8_0\n blk.23.attn_q_a.weight q8_0\n blk.23.attn_q_b.weight q8_0\n+blk.23.attn_v_b.weight q8_0\n blk.23.ffn_down_shexp.weight q8_0\n blk.23.ffn_gate_shexp.weight q8_0\n blk.23.ffn_up_shexp.weight q8_0\n+blk.24.attn_k_b.weight q8_0\n blk.24.attn_kv_a_mqa.weight q8_0\n blk.24.attn_output.weight q8_0\n blk.24.attn_q_a.weight q8_0\n blk.24.attn_q_b.weight q8_0\n+blk.24.attn_v_b.weight q8_0\n blk.24.ffn_down_shexp.weight q8_0\n blk.24.ffn_gate_shexp.weight q8_0\n blk.24.ffn_up_shexp.weight q8_0\n+blk.25.attn_k_b.weight q8_0\n blk.25.attn_kv_a_mqa.weight q8_0\n blk.25.attn_output.weight q8_0\n blk.25.attn_q_a.weight q8_0\n blk.25.attn_q_b.weight q8_0\n+blk.25.attn_v_b.weight q8_0\n blk.25.ffn_down_shexp.weight q8_0\n blk.25.ffn_gate_shexp.weight q8_0\n blk.25.ffn_up_shexp.weight q8_0\n+blk.26.attn_k_b.weight q8_0\n blk.26.attn_kv_a_mqa.weight q8_0\n blk.26.attn_output.weight q8_0\n blk.26.attn_q_a.weight q8_0\n blk.26.attn_q_b.weight q8_0\n+blk.26.attn_v_b.weight q8_0\n blk.26.ffn_down_shexp.weight q8_0\n blk.26.ffn_gate_shexp.weight q8_0\n blk.26.ffn_up_shexp.weight q8_0\n+blk.27.attn_k_b.weight q8_0\n blk.27.attn_kv_a_mqa.weight q8_0\n blk.27.attn_output.weight q8_0\n blk.27.attn_q_a.weight q8_0\n blk.27.attn_q_b.weight q8_0\n+blk.27.attn_v_b.weight q8_0\n blk.27.ffn_down_shexp.weight q8_0\n blk.27.ffn_gate_shexp.weight q8_0\n blk.27.ffn_up_shexp.weight q8_0\n+blk.28.attn_k_b.weight q8_0\n blk.28.attn_kv_a_mqa.weight q8_0\n blk.28.attn_output.weight q8_0\n blk.28.attn_q_a.weight q8_0\n blk.28.attn_q_b.weight q8_0\n+blk.28.attn_v_b.weight q8_0\n blk.28.ffn_down_shexp.weight q8_0\n blk.28.ffn_gate_shexp.weight q8_0\n blk.28.ffn_up_shexp.weight q8_0\n+blk.29.attn_k_b.weight q8_0\n blk.29.attn_kv_a_mqa.weight q8_0\n blk.29.attn_output.weight q8_0\n blk.29.attn_q_a.weight q8_0\n blk.29.attn_q_b.weight q8_0\n+blk.29.attn_v_b.weight q8_0\n blk.29.ffn_down_shexp.weight q8_0\n blk.29.ffn_gate_shexp.weight q8_0\n blk.29.ffn_up_shexp.weight q8_0\n+blk.30.attn_k_b.weight q8_0\n blk.30.attn_kv_a_mqa.weight q8_0\n blk.30.attn_output.weight q8_0\n blk.30.attn_q_a.weight q8_0\n blk.30.attn_q_b.weight q8_0\n+blk.30.attn_v_b.weight q8_0\n blk.30.ffn_down_shexp.weight q8_0\n blk.30.ffn_gate_shexp.weight q8_0\n blk.30.ffn_up_shexp.weight q8_0\n+blk.31.attn_k_b.weight q8_0\n blk.31.attn_kv_a_mqa.weight q8_0\n blk.31.attn_output.weight q8_0\n blk.31.attn_q_a.weight q8_0\n blk.31.attn_q_b.weight q8_0\n+blk.31.attn_v_b.weight q8_0\n blk.31.ffn_down_shexp.weight q8_0\n blk.31.ffn_gate_shexp.weight q8_0\n blk.31.ffn_up_shexp.weight q8_0\n+blk.32.attn_k_b.weight q8_0\n blk.32.attn_kv_a_mqa.weight q8_0\n blk.32.attn_output.weight q8_0\n blk.32.attn_q_a.weight q8_0\n blk.32.attn_q_b.weight q8_0\n+blk.32.attn_v_b.weight q8_0\n blk.32.ffn_down_shexp.weight q8_0\n blk.32.ffn_gate_shexp.weight q8_0\n blk.32.ffn_up_shexp.weight q8_0\n+blk.33.attn_k_b.weight q8_0\n blk.33.attn_kv_a_mqa.weight q8_0\n blk.33.attn_output.weight q8_0\n blk.33.attn_q_a.weight q8_0\n blk.33.attn_q_b.weight q8_0\n+blk.33.attn_v_b.weight q8_0\n blk.33.ffn_down_shexp.weight q8_0\n blk.33.ffn_gate_shexp.weight q8_0\n blk.33.ffn_up_shexp.weight q8_0\n+blk.34.attn_k_b.weight q8_0\n blk.34.attn_kv_a_mqa.weight q8_0\n blk.34.attn_output.weight q8_0\n blk.34.attn_q_a.weight q8_0\n blk.34.attn_q_b.weight q8_0\n+blk.34.attn_v_b.weight q8_0\n blk.34.ffn_down_shexp.weight q8_0\n blk.34.ffn_gate_shexp.weight q8_0\n blk.34.ffn_up_shexp.weight q8_0\n+blk.35.attn_k_b.weight q8_0\n blk.35.attn_kv_a_mqa.weight q8_0\n blk.35.attn_output.weight q8_0\n blk.35.attn_q_a.weight q8_0\n blk.35.attn_q_b.weight q8_0\n+blk.35.attn_v_b.weight q8_0\n blk.35.ffn_down_shexp.weight q8_0\n blk.35.ffn_gate_shexp.weight q8_0\n blk.35.ffn_up_shexp.weight q8_0\n+blk.36.attn_k_b.weight q8_0\n blk.36.attn_kv_a_mqa.weight q8_0\n blk.36.attn_output.weight q8_0\n blk.36.attn_q_a.weight q8_0\n blk.36.attn_q_b.weight q8_0\n+blk.36.attn_v_b.weight q8_0\n blk.36.ffn_down_shexp.weight q8_0\n blk.36.ffn_gate_shexp.weight q8_0\n blk.36.ffn_up_shexp.weight q8_0\n+blk.37.attn_k_b.weight q8_0\n blk.37.attn_kv_a_mqa.weight q8_0\n blk.37.attn_output.weight q8_0\n blk.37.attn_q_a.weight q8_0\n blk.37.attn_q_b.weight q8_0\n+blk.37.attn_v_b.weight q8_0\n blk.37.ffn_down_shexp.weight q8_0\n blk.37.ffn_gate_shexp.weight q8_0\n blk.37.ffn_up_shexp.weight q8_0\n+blk.38.attn_k_b.weight q8_0\n blk.38.attn_kv_a_mqa.weight q8_0\n blk.38.attn_output.weight q8_0\n blk.38.attn_q_a.weight q8_0\n blk.38.attn_q_b.weight q8_0\n+blk.38.attn_v_b.weight q8_0\n blk.38.ffn_down_shexp.weight q8_0\n blk.38.ffn_gate_shexp.weight q8_0\n blk.38.ffn_up_shexp.weight q8_0\n+blk.39.attn_k_b.weight q8_0\n blk.39.attn_kv_a_mqa.weight q8_0\n blk.39.attn_output.weight q8_0\n blk.39.attn_q_a.weight q8_0\n blk.39.attn_q_b.weight q8_0\n+blk.39.attn_v_b.weight q8_0\n blk.39.ffn_down_shexp.weight q8_0\n blk.39.ffn_gate_shexp.weight q8_0\n blk.39.ffn_up_shexp.weight q8_0\n+blk.40.attn_k_b.weight q8_0\n blk.40.attn_kv_a_mqa.weight q8_0\n blk.40.attn_output.weight q8_0\n blk.40.attn_q_a.weight q8_0\n blk.40.attn_q_b.weight q8_0\n+blk.40.attn_v_b.weight q8_0\n blk.40.ffn_down_shexp.weight q8_0\n blk.40.ffn_gate_shexp.weight q8_0\n blk.40.ffn_up_shexp.weight q8_0\n+blk.41.attn_k_b.weight q8_0\n blk.41.attn_kv_a_mqa.weight q8_0\n blk.41.attn_output.weight q8_0\n blk.41.attn_q_a.weight q8_0\n blk.41.attn_q_b.weight q8_0\n+blk.41.attn_v_b.weight q8_0\n blk.41.ffn_down_shexp.weight q8_0\n blk.41.ffn_gate_shexp.weight q8_0\n blk.41.ffn_up_shexp.weight q8_0\n+blk.42.attn_k_b.weight q8_0\n blk.42.attn_kv_a_mqa.weight q8_0\n blk.42.attn_output.weight q8_0\n blk.42.attn_q_a.weight q8_0\n blk.42.attn_q_b.weight q8_0\n+blk.42.attn_v_b.weight q8_0\n blk.42.ffn_down_shexp.weight q8_0\n blk.42.ffn_gate_shexp.weight q8_0\n blk.42.ffn_up_shexp.weight q8_0\n+blk.43.attn_k_b.weight q8_0\n blk.43.attn_kv_a_mqa.weight q8_0\n blk.43.attn_output.weight q8_0\n blk.43.attn_q_a.weight q8_0\n blk.43.attn_q_b.weight q8_0\n+blk.43.attn_v_b.weight q8_0\n blk.43.ffn_down_shexp.weight q8_0\n blk.43.ffn_gate_shexp.weight q8_0\n blk.43.ffn_up_shexp.weight q8_0\n+blk.44.attn_k_b.weight q8_0\n blk.44.attn_kv_a_mqa.weight q8_0\n blk.44.attn_output.weight q8_0\n blk.44.attn_q_a.weight q8_0\n blk.44.attn_q_b.weight q8_0\n+blk.44.attn_v_b.weight q8_0\n blk.44.ffn_down_shexp.weight q8_0\n blk.44.ffn_gate_shexp.weight q8_0\n blk.44.ffn_up_shexp.weight q8_0\n+blk.45.attn_k_b.weight q8_0\n blk.45.attn_kv_a_mqa.weight q8_0\n blk.45.attn_output.weight q8_0\n blk.45.attn_q_a.weight q8_0\n blk.45.attn_q_b.weight q8_0\n+blk.45.attn_v_b.weight q8_0\n blk.45.ffn_down_shexp.weight q8_0\n blk.45.ffn_gate_shexp.weight q8_0\n blk.45.ffn_up_shexp.weight q8_0\n+blk.46.attn_k_b.weight q8_0\n blk.46.attn_kv_a_mqa.weight q8_0\n blk.46.attn_output.weight q8_0\n blk.46.attn_q_a.weight q8_0\n blk.46.attn_q_b.weight q8_0\n+blk.46.attn_v_b.weight q8_0\n blk.46.ffn_down_shexp.weight q8_0\n blk.46.ffn_gate_shexp.weight q8_0\n blk.46.ffn_up_shexp.weight q8_0\n+blk.47.attn_k_b.weight q8_0\n blk.47.attn_kv_a_mqa.weight q8_0\n blk.47.attn_output.weight q8_0\n blk.47.attn_q_a.weight q8_0\n blk.47.attn_q_b.weight q8_0\n+blk.47.attn_v_b.weight q8_0\n blk.47.ffn_down_shexp.weight q8_0\n blk.47.ffn_gate_shexp.weight q8_0\n blk.47.ffn_up_shexp.weight q8_0\n+blk.48.attn_k_b.weight q8_0\n blk.48.attn_kv_a_mqa.weight q8_0\n blk.48.attn_output.weight q8_0\n blk.48.attn_q_a.weight q8_0\n blk.48.attn_q_b.weight q8_0\n+blk.48.attn_v_b.weight q8_0\n blk.48.ffn_down_shexp.weight q8_0\n blk.48.ffn_gate_shexp.weight q8_0\n blk.48.ffn_up_shexp.weight q8_0\n+blk.49.attn_k_b.weight q8_0\n blk.49.attn_kv_a_mqa.weight q8_0\n blk.49.attn_output.weight q8_0\n blk.49.attn_q_a.weight q8_0\n blk.49.attn_q_b.weight q8_0\n+blk.49.attn_v_b.weight q8_0\n blk.49.ffn_down_shexp.weight q8_0\n blk.49.ffn_gate_shexp.weight q8_0\n blk.49.ffn_up_shexp.weight q8_0\n+blk.50.attn_k_b.weight q8_0\n blk.50.attn_kv_a_mqa.weight q8_0\n blk.50.attn_output.weight q8_0\n blk.50.attn_q_a.weight q8_0\n blk.50.attn_q_b.weight q8_0\n+blk.50.attn_v_b.weight q8_0\n blk.50.ffn_down_shexp.weight q8_0\n blk.50.ffn_gate_shexp.weight q8_0\n blk.50.ffn_up_shexp.weight q8_0\n+blk.51.attn_k_b.weight q8_0\n blk.51.attn_kv_a_mqa.weight q8_0\n blk.51.attn_output.weight q8_0\n blk.51.attn_q_a.weight q8_0\n blk.51.attn_q_b.weight q8_0\n+blk.51.attn_v_b.weight q8_0\n blk.51.ffn_down_shexp.weight q8_0\n blk.51.ffn_gate_shexp.weight q8_0\n blk.51.ffn_up_shexp.weight q8_0\n+blk.52.attn_k_b.weight q8_0\n blk.52.attn_kv_a_mqa.weight q8_0\n blk.52.attn_output.weight q8_0\n blk.52.attn_q_a.weight q8_0\n blk.52.attn_q_b.weight q8_0\n+blk.52.attn_v_b.weight q8_0\n blk.52.ffn_down_shexp.weight q8_0\n blk.52.ffn_gate_shexp.weight q8_0\n blk.52.ffn_up_shexp.weight q8_0\n+blk.53.attn_k_b.weight q8_0\n blk.53.attn_kv_a_mqa.weight q8_0\n blk.53.attn_output.weight q8_0\n blk.53.attn_q_a.weight q8_0\n blk.53.attn_q_b.weight q8_0\n+blk.53.attn_v_b.weight q8_0\n blk.53.ffn_down_shexp.weight q8_0\n blk.53.ffn_gate_shexp.weight q8_0\n blk.53.ffn_up_shexp.weight q8_0\n+blk.54.attn_k_b.weight q8_0\n blk.54.attn_kv_a_mqa.weight q8_0\n blk.54.attn_output.weight q8_0\n blk.54.attn_q_a.weight q8_0\n blk.54.attn_q_b.weight q8_0\n+blk.54.attn_v_b.weight q8_0\n blk.54.ffn_down_shexp.weight q8_0\n blk.54.ffn_gate_shexp.weight q8_0\n blk.54.ffn_up_shexp.weight q8_0\n+blk.55.attn_k_b.weight q8_0\n blk.55.attn_kv_a_mqa.weight q8_0\n blk.55.attn_output.weight q8_0\n blk.55.attn_q_a.weight q8_0\n blk.55.attn_q_b.weight q8_0\n+blk.55.attn_v_b.weight q8_0\n blk.55.ffn_down_shexp.weight q8_0\n blk.55.ffn_gate_shexp.weight q8_0\n blk.55.ffn_up_shexp.weight q8_0\n+blk.56.attn_k_b.weight q8_0\n blk.56.attn_kv_a_mqa.weight q8_0\n blk.56.attn_output.weight q8_0\n blk.56.attn_q_a.weight q8_0\n blk.56.attn_q_b.weight q8_0\n+blk.56.attn_v_b.weight q8_0\n blk.56.ffn_down_shexp.weight q8_0\n blk.56.ffn_gate_shexp.weight q8_0\n blk.56.ffn_up_shexp.weight q8_0\n+blk.57.attn_k_b.weight q8_0\n blk.57.attn_kv_a_mqa.weight q8_0\n blk.57.attn_output.weight q8_0\n blk.57.attn_q_a.weight q8_0\n blk.57.attn_q_b.weight q8_0\n+blk.57.attn_v_b.weight q8_0\n blk.57.ffn_down_shexp.weight q8_0\n blk.57.ffn_gate_shexp.weight q8_0\n blk.57.ffn_up_shexp.weight q8_0\n+blk.58.attn_k_b.weight q8_0\n blk.58.attn_kv_a_mqa.weight q8_0\n blk.58.attn_output.weight q8_0\n blk.58.attn_q_a.weight q8_0\n blk.58.attn_q_b.weight q8_0\n+blk.58.attn_v_b.weight q8_0\n blk.58.ffn_down_shexp.weight q8_0\n blk.58.ffn_gate_shexp.weight q8_0\n blk.58.ffn_up_shexp.weight q8_0\n+blk.59.attn_k_b.weight q8_0\n blk.59.attn_kv_a_mqa.weight q8_0\n blk.59.attn_output.weight q8_0\n blk.59.attn_q_a.weight q8_0\n blk.59.attn_q_b.weight q8_0\n+blk.59.attn_v_b.weight q8_0\n blk.59.ffn_down_shexp.weight q8_0\n blk.59.ffn_gate_shexp.weight q8_0\n blk.59.ffn_up_shexp.weight q8_0\n+blk.60.attn_k_b.weight q8_0\n blk.60.attn_kv_a_mqa.weight q8_0\n blk.60.attn_output.weight q8_0\n blk.60.attn_q_a.weight q8_0\n blk.60.attn_q_b.weight q8_0\n+blk.60.attn_v_b.weight q8_0\n blk.60.ffn_down_shexp.weight q8_0\n blk.60.ffn_gate_shexp.weight q8_0\n blk.60.ffn_up_shexp.weight q8_0\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ggml-org/llama.cpp\nPull request: llama-quant : fix 4D tensor quantization using ggml_nrows() and name-based expert detection\nLabels: testing, merge ready\nFiles changed (2): src/llama-quant.cpp, tests/snapshots/deepseek-v3.1.schema\n\n## Description (results removed)\n\n## Overview\n\nFix quantization of 4D tensors by using `ggml_nrows()` to count rows, and detect expert tensors by name instead of by shape.\n\nFixes #29916 in https://github.com/ggml-org/llama.cpp/commit/64d1bbb254298a6714c3302b54526082c71c04f7. The row count was computed from `ne[1]` and `ne[2]` only, ignoring `ne[3]`. For tensors like `a.conv1d.0.weight [3, 3, 1, 128]` this produces the wrong size and trips the `gguf_get_tensor_size(...) == new_size` assert. `ggml_nrows()` is now used instead. Other places in `src/llama-quant.cpp` that ignored `ne[3]` are fixed as well.\n\n[details with results removed]\n\n[details with results removed]\n\nOn top of that, we previously used `tensor->ne[2] > 1` to detect expert tensors, but that did not cover all cases and required some hard-coded exclusions for the bailingmoe3 model. Expert tensors are now identified by `_exps.` or `_chexps.` in their name. This new implementation does not break existing models, and it even caught an edge case where the attention weights for deepseek-v3.1 were wrongly treated as expert tensors when they should be quantized as `Q8_0` instead. The test schema has also been updated.\n\n## Requirements\n\n- AI usage disclosure: YES. AI was used for solution exploration and code generation. Every line of generated code has been reviewed by me.\n\n## Log files\n- [reproduced.log](https://github.com/user-attachments/files/33674908/reproduced.log)\n- [after-fix.log](https://github.com/user-attachments/files/33674906/after-fix.log)\n\n## Diff\n\n```diff\ndiff --git a/src/llama-quant.cpp b/src/llama-quant.cpp\nindex b8f96bcef..fb7acd4d5 100644\n--- a/src/llama-quant.cpp\n+++ b/src/llama-quant.cpp\n@@ -296,7 +296,7 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param\n // trivial checks first -- no string ops needed\n if (params->only_copy) return false;\n \n- // quantize only 2D and 3D tensors (experts)\n+ // quantize only 2D+ tensors (matrices, experts, conv kernels)\n if (ggml_n_dims(tensor) < 2) return false;\n \n const std::string name = ggml_get_name(tensor);\n@@ -1338,7 +1338,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::\n \n const int64_t n_per_row = tensor->ne[0];\n const int64_t nrows_per_expert = tensor->ne[1];\n- const int64_t nrows_total = tensor->ne[1] * tensor->ne[2];\n+ const int64_t nrows_total = ggml_nrows(tensor);\n \n const size_t row_size_src = ggml_row_size(tensor->type, n_per_row);\n const size_t row_size_dst = ggml_row_size(new_type, n_per_row);\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: huggingface/transformers\nPull request: Fix model_input_names singleton issue causing shared state\nFiles changed (2): src/transformers/tokenization_utils_base.py, tests/tokenization/test_tokenization_utils.py\n\n## Description (results removed)\n\n# What does this PR do?\n\nFixes #42024\n\nI found this while testing tokenizers - when you modify `model_input_names` on one tokenizer instance, it was affecting all other instances of the same tokenizer class.\n\nThe problem is that `model_input_names` is defined as a class-level list, and in the `__init__` method (line 1417), when no custom `model_input_names` is provided, it was just referencing the class attribute directly instead of making a copy.\n\nSo all instances were sharing the same list object. This is a classic Python gotcha with mutable class attributes.\n\nThe fix is simple - wrap it in `list()` to create a new list for each instance:\n\n**Before:**\n```python\nself.model_input_names = kwargs.pop(\"model_input_names\", self.model_input_names)\n```\n\n**After:**\n```python\nself.model_input_names = list(kwargs.pop(\"model_input_names\", self.model_input_names))\n```\n\nThis ensures each tokenizer instance gets its own independent copy of the list. Now modifications to one instance won't affect others.\n\nThe reproduction from the issue shows the problem clearly - with the fix, the second tokenizer instance will have the original list values instead of inheriting the modifications from the first instance.\n\n## Diff\n\n```diff\ndiff --git a/src/transformers/tokenization_utils_base.py b/src/transformers/tokenization_utils_base.py\nindex 10feaff36b1c..48bc88e78289 100644\n--- a/src/transformers/tokenization_utils_base.py\n+++ b/src/transformers/tokenization_utils_base.py\n@@ -1068,7 +1068,7 @@ def __init__(self, **kwargs):\n f\"Truncation side should be selected between 'right' and 'left', current value: {self.truncation_side}\"\n )\n \n- self.model_input_names = kwargs.pop(\"model_input_names\", self.model_input_names)\n+ self.model_input_names = list(kwargs.pop(\"model_input_names\", self.model_input_names))\n \n # By default, do not clean up tokenization spaces for both fast and slow tokenizers\n self.clean_up_tokenization_spaces = kwargs.pop(\"clean_up_tokenization_spaces\", False)\ndiff --git a/tests/tokenization/test_tokenization_utils.py b/tests/tokenization/test_tokenization_utils.py\nindex c144622dbb75..02eb8460c982 100644\n--- a/tests/tokenization/test_tokenization_utils.py\n+++ b/tests/tokenization/test_tokenization_utils.py\n@@ -32,6 +32,7 @@\n ProphetNetTokenizer,\n PythonBackend,\n TensorType,\n+ TokenizersBackend,\n TokenSpan,\n is_tokenizers_available,\n )\n@@ -294,6 +295,16 @@ def test_instantiation_from_tokenizers_json_file(self):\n bert_tokenizer.save(os.path.join(tmpdirname, \"tokenizer.json\"))\n PreTrainedTokenizerFast(tokenizer_file=os.path.join(tmpdirname, \"tokenizer.json\"))\n \n+ @require_tokenizers\n+ def test_model_input_names_not_shared_between_instances(self):\n+ tokenizer_1 = TokenizersBackend(tokenizer_object=Tokenizer(WordPiece(unk_token=\"[UNK]\")))\n+ tokenizer_2 = TokenizersBackend(tokenizer_object=Tokenizer(WordPiece(unk_token=\"[UNK]\")))\n+\n+ tokenizer_1.model_input_names.append(\"pixel_values\")\n+ self.assertIn(\"pixel_values\", tokenizer_1.model_input_names)\n+ self.assertNotIn(\"pixel_values\", tokenizer_2.model_input_names)\n+ self.assertNotIn(\"pixel_values\", TokenizersBackend.model_input_names)\n+\n def test_vocab_file_in_config_does_not_escape_repo(self):\n # Regression test for path traversal (CWE-22): a vocab-file argument injected into\n # `tokenizer_config.json` must not override the repository-resolved path nor be opened\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: huggingface/transformers\nPull request: Fix boolean padding in ClapFeatureExtractor (#23648)\nFiles changed (2): src/transformers/models/clap/feature_extraction_clap.py, tests/models/clap/test_feature_extraction_clap.py\n\n## Description (results removed)\n\n[[image]](https://transformers-ci.huggingface.cool/d/pytest-observability-by-pr/pytest-observability-branch?var-pr=49960)\n\nFixes #23648\n\n### Description\n\nIn `ClapFeatureExtractor.__call__`, `padding = padding if padding else self.padding` leaves `padding=True` as a boolean. In `_get_input_mel`, `padding == \"repeat\"` and `padding == \"repeatpad\"` both evaluate to `False`, causing `padding=True` to fall through to constant zero padding instead of using the configured `self.padding` strategy (`repeatpad`).\n\nFollowing @ArthurZucker's recommendation in #23648, this PR:\n- Maps boolean `padding=True` to `self.padding` in `ClapFeatureExtractor.__call__`.\n- Updates the method type annotation and docstring to reflect `bool` support.\n\n## Diff\n\n```diff\ndiff --git a/src/transformers/models/clap/feature_extraction_clap.py b/src/transformers/models/clap/feature_extraction_clap.py\nindex 0a271e94b8c4..31e929771285 100644\n--- a/src/transformers/models/clap/feature_extraction_clap.py\n+++ b/src/transformers/models/clap/feature_extraction_clap.py\n@@ -263,7 +263,7 @@ def __call__(\n self,\n raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],\n truncation: str | None = None,\n- padding: str | None = None,\n+ padding: bool | str | None = None,\n max_length: int | None = None,\n sampling_rate: int | None = None,\n return_tensors: str | TensorType | None = None,\n@@ -284,8 +284,9 @@ def __call__(\n If `config.fusion` is set to True, shorter audios also need to return 4 mels, which will just be a\n copy of the original mel obtained from the padded audio.\n - `rand_trunc` will select a random crop of the mel spectrogram.\n- padding (`str`, *optional*):\n- Padding pattern for shorter audio inputs. Three patterns were originally implemented:\n+ padding (`bool`, `str`, *optional*):\n+ Padding pattern for shorter audio inputs. If `True`, defaults to `self.padding`.\n+ Available patterns:\n - `repeatpad`: the audio is repeated, and then padded to fit the `max_length`.\n - `repeat`: the audio is repeated and then cut to fit the `max_length`\n - `pad`: the audio is padded.\n@@ -299,7 +300,8 @@ def __call__(\n pipeline.\n \"\"\"\n truncation = truncation if truncation is not None else self.truncation\n- padding = padding if padding else self.padding\n+ if padding is True or padding is None:\n+ padding = self.padding\n \n if sampling_rate is not None:\n if sampling_rate != self.sampling_rate:\ndiff --git a/tests/models/clap/test_feature_extraction_clap.py b/tests/models/clap/test_feature_extraction_clap.py\nindex 4cd73372dd87..92204f2ad4d4 100644\n--- a/tests/models/clap/test_feature_extraction_clap.py\n+++ b/tests/models/clap/test_feature_extraction_clap.py\n@@ -144,6 +144,20 @@ def test_double_precision_pad(self):\n pt_processed = feature_extractor.pad([{\"input_features\": inputs}], return_tensors=\"pt\")\n self.assertTrue(pt_processed.input_features.dtype == torch.float32)\n \n+ def test_padding_boolean(self):\n+ feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())\n+ speech_inputs = floats_list((1, 800))[0]\n+\n+ np.random.seed(0)\n+ out_default = feature_extractor(speech_inputs, return_tensors=\"np\").input_features\n+ np.random.seed(0)\n+ out_bool = feature_extractor(speech_inputs, padding=True, return_tensors=\"np\").input_features\n+ np.random.seed(0)\n+ out_repeatpad = feature_extractor(speech_inputs, padding=\"repeatpad\", return_tensors=\"np\").input_features\n+\n+ self.assertTrue(np.allclose(out_bool, out_default, atol=1e-3))\n+ self.assertTrue(np.allclose(out_bool, out_repeatpad, atol=1e-3))\n+\n # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest._load_datasamples\n def _load_datasamples(self, num_samples):\n ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: sgl-project/sglang\nPull request: [Fix] compressed-tensors: Honor .linear-wrapped ignore entries on fused shards\nLabels: run-ci\nFiles changed (2): python/sglang/srt/layers/quantization/compressed_tensors/utils.py, test/registered/unit/layers/quantization/test_compressed_tensors_mixed_precision.py\n\n## Description (results removed)\n\nFixes #28018.\n\nThe reported llm-compressor checkpoint spells its vision-tower `ignore` entries against the `CompressedLinear` wrapper (`...q_proj.linear`). For fused `qkv_proj` / `gate_up_proj`, SGLang expands the layer into shard names without that suffix, so `should_ignore_layer` misses those wrapped entries and quantizes the corresponding fused projections. That is 135 of its 189 wrapped entries; the other 54 name `o_proj` / `down_proj`, which `ClippableRowParallelLinear` already nests at `.linear`, so those already match.\n\nThe change is therefore on the fused path only: retry the wrapper spelling once per expanded shard, after the existing comparator misses. Four lines, no new matching primitive; #32736's no-prefix invariant is untouched.\n\nVerified on one H200 with `google/gemma-4-31B-it-qat-w4a16-ct`:\n\n- **before** — the load reaches `compressed_tensors_wNa16` → `gptq_marlin_repack` and aborts with `size_n = 8608 is not divisible by tile_n_size = 64`, the message in #28018;\n- **after** — the model loads, all 108 vision-tower projections come up `UnquantizedLinearMethod`/bf16, and `language_model.layers.0` stays `CompressedTensorsLinearMethod`;\n\nTwo behavior changes, your call:\n\n- naming **only some** fused shards in the wrapped spelling previously loaded silently quantized, and now raises the existing inconsistent-scheme `ValueError` (whose message does not mention `.linear`);\n- **mixing** plain and wrapped spellings previously raised, and now resolves to ignored.\n\nTests are CPU-only and matcher-level: 10 cases, 5 red on main; the largest drives the checkpoint's 189-entry list at the tower's real runtime names. One checkpoint on one GPU, and no accuracy or throughput measurement.\n\n#24929 identified this mechanism first; its hunk sits in `check_contains`, which the ignore path no longer reaches since #32736.\n\n---\n### CI States\n\nLatest PR Test (Base): :white_check_mark: [Run #41643349182](https://github.com/sgl-project/sglang/actions/runs/41643349182)\nLatest PR Test (Extra): :x: [Run #41643348757](https://github.com/sgl-project/sglang/actions/runs/41643348757)\nLatest PR Test (AMD ROCm 10): :x: [Run #41643349042](https://github.com/sgl-project/sglang/actions/runs/41643349042)\n\n> [!TIP]\n>\n> ```text\n> ```\n\n## Diff\n\n```diff\ndiff --git a/python/sglang/srt/layers/quantization/compressed_tensors/utils.py b/python/sglang/srt/layers/quantization/compressed_tensors/utils.py\nindex 4913f6ad4ff6..7c7fb30ff0d6 100644\n--- a/python/sglang/srt/layers/quantization/compressed_tensors/utils.py\n+++ b/python/sglang/srt/layers/quantization/compressed_tensors/utils.py\n@@ -53,6 +53,10 @@ def should_ignore_layer(\n should_ignore_shard = check_equal_or_regex_match(\n layer_name=shard_name, targets=ignore\n )\n+ if not should_ignore_shard:\n+ should_ignore_shard = check_equal_or_regex_match(\n+ layer_name=f\"{shard_name}.linear\", targets=ignore\n+ )\n \n # If shard_idx=0, set layer ignore to match shard.\n if should_ignore_layer is None:\ndiff --git a/test/registered/unit/layers/quantization/test_compressed_tensors_mixed_precision.py b/test/registered/unit/layers/quantization/test_compressed_tensors_mixed_precision.py\nindex b40ad11c4937..7e3ad418234b 100644\n--- a/test/registered/unit/layers/quantization/test_compressed_tensors_mixed_precision.py\n+++ b/test/registered/unit/layers/quantization/test_compressed_tensors_mixed_precision.py\n@@ -32,6 +32,39 @@\n GATE_PROJ = f\"{EXPERTS_LAYER}.0.gate_proj\"\n MLP_LAYER = \"model.language_model.layers.0.mlp.gate_proj\"\n \n+# A vision tower whose ignore list is spelled against the CompressedLinear\n+# wrapper. The names below are the prefixes the matcher actually receives:\n+# ClippableQKVParallelLinear and ClippableGateUpParallelLinear hand their own\n+# prefix to the inner fused linear, while ClippableRowParallelLinear nests its\n+# inner linear at \".linear\".\n+VISION_PREFIX = \"model.vision_tower.encoder.layers\"\n+VISION_QKV_LAYER = f\"{VISION_PREFIX}.0.self_attn.qkv_proj\"\n+VISION_GATE_UP_LAYER = f\"{VISION_PREFIX}.0.mlp.gate_up_proj\"\n+VISION_O_PROJ_LAYER = f\"{VISION_PREFIX}.0.self_attn.o_proj.linear\"\n+VISION_DOWN_PROJ_LAYER = f\"{VISION_PREFIX}.0.mlp.down_proj.linear\"\n+VISION_FUSED_MAPPING = {\n+ \"qkv_proj\": [\"q_proj\", \"k_proj\", \"v_proj\"],\n+ \"gate_up_proj\": [\"gate_proj\", \"up_proj\"],\n+}\n+VISION_NUM_LAYERS = 27\n+TEXT_PREFIX = \"model.language_model.layers.0\"\n+\n+\n+def _wrapped_tower_ignore_list():\n+ \"\"\"27 layers x 7 projections, every entry spelled ``.linear``.\n+\n+ 135 name fused shards (q/k/v, gate/up) and 54 name unfused layers\n+ (o_proj, down_proj).\n+ \"\"\"\n+ entries = []\n+ for idx in range(VISION_NUM_LAYERS):\n+ for proj in (\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\"):\n+ entries.append(f\"{VISION_PREFIX}.{idx}.self_attn.{proj}.linear\")\n+ for proj in (\"gate_proj\", \"up_proj\", \"down_proj\"):\n+ entries.append(f\"{VISION_PREFIX}.{idx}.mlp.{proj}.linear\")\n+ return entries\n+\n+\n FP8_TARGET = \"re:.*self_attn\\\\.(q|k|v|o)_proj$\"\n NVFP4_TARGET = \"re:.*mlp\\\\.experts\\\\.\\\\d+\\\\.(gate|up|down)_proj$\"\n WNA16_TARGET = \"re:.*mlp\\\\.(gate|up|down)_proj$\"\n@@ -150,6 +183,189 @@ def test_exact_and_regex_targets_unchanged(self):\n self.assertFalse(check_equal_or_regex_match(GATE_PROJ, [\"re:.*down_proj$\"]))\n \n \n+class TestFusedIgnoreLinearWrapper(CustomTestCase):\n+ \"\"\"Fused shard names must honor ignores written for the CT wrapper.\"\"\"\n+\n+ def test_all_wrapped_shards_are_ignored(self):\n+ ignore = [\n+ f\"{VISION_PREFIX}.0.self_attn.{proj}.linear\"\n+ for proj in (\"q_proj\", \"k_proj\", \"v_proj\")\n+ ]\n+\n+ self.assertTrue(\n+ should_ignore_layer(\n+ VISION_QKV_LAYER,\n+ ignore=ignore,\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ )\n+ )\n+\n+ def test_partial_wrapped_shards_extend_inconsistent_scheme_error(self):\n+ \"\"\"Wrapped shards join the consistency check, so a partial list now raises.\n+\n+ Before this change the wrapped entry matched nothing, every shard agreed\n+ on \"not ignored\", and the layer loaded quantized. The error boundary is\n+ extended to the wrapper spelling, not preserved unchanged.\n+ \"\"\"\n+ ignore = [f\"{VISION_PREFIX}.0.mlp.gate_proj.linear\"]\n+\n+ with self.assertRaisesRegex(ValueError, \"different quantization schemes\"):\n+ should_ignore_layer(\n+ VISION_GATE_UP_LAYER,\n+ ignore=ignore,\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ )\n+\n+ def test_mixed_spelling_shards_resolve_to_ignored(self):\n+ \"\"\"A list mixing plain and wrapped shard spellings is now consistent.\n+\n+ Before this change the plain entry matched and the wrapped ones did not,\n+ which raised the inconsistent-scheme error. Both spellings now match, so\n+ the layer is ignored instead of aborting the load.\n+ \"\"\"\n+ ignore = [f\"{VISION_PREFIX}.0.self_attn.q_proj\"] + [\n+ f\"{VISION_PREFIX}.0.self_attn.{proj}.linear\"\n+ for proj in (\"k_proj\", \"v_proj\")\n+ ]\n+\n+ self.assertTrue(\n+ should_ignore_layer(\n+ VISION_QKV_LAYER,\n+ ignore=ignore,\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ )\n+ )\n+\n+ def test_wrapped_tower_list_is_honored_at_runtime_names(self):\n+ \"\"\"The whole wrapped list, queried at the names the tower really has.\n+\n+ The two fused names need the retry; the two unfused ones are already\n+ nested at \".linear\" by ClippableRowParallelLinear and match directly.\n+ \"\"\"\n+ ignore = _wrapped_tower_ignore_list()\n+ self.assertEqual(len(ignore), VISION_NUM_LAYERS * 7)\n+\n+ for idx in range(VISION_NUM_LAYERS):\n+ for layer_name in (\n+ f\"{VISION_PREFIX}.{idx}.self_attn.qkv_proj\",\n+ f\"{VISION_PREFIX}.{idx}.mlp.gate_up_proj\",\n+ f\"{VISION_PREFIX}.{idx}.self_attn.o_proj.linear\",\n+ f\"{VISION_PREFIX}.{idx}.mlp.down_proj.linear\",\n+ ):\n+ self.assertTrue(\n+ should_ignore_layer(\n+ layer_name,\n+ ignore=ignore,\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ ),\n+ layer_name,\n+ )\n+\n+ def test_wrapped_tower_list_leaves_the_text_model_quantized(self):\n+ \"\"\"A tower-only ignore list must not reach the language model.\"\"\"\n+ ignore = _wrapped_tower_ignore_list()\n+\n+ for layer_name in (\n+ f\"{TEXT_PREFIX}.self_attn.qkv_proj\",\n+ f\"{TEXT_PREFIX}.mlp.gate_up_proj\",\n+ f\"{TEXT_PREFIX}.self_attn.o_proj.linear\",\n+ f\"{TEXT_PREFIX}.mlp.down_proj.linear\",\n+ \"lm_head\",\n+ ):\n+ self.assertFalse(\n+ should_ignore_layer(\n+ layer_name,\n+ ignore=ignore,\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ ),\n+ layer_name,\n+ )\n+\n+ def test_intentionally_quantized_tower_keeps_its_scheme(self):\n+ config = CompressedTensorsConfig.from_config(\n+ {\n+ \"quant_method\": \"compressed-tensors\",\n+ \"format\": \"pack-quantized\",\n+ \"config_groups\": {\"group_0\": WNA16_GROUP},\n+ \"ignore\": [],\n+ }\n+ )\n+ config.update_packed_modules_mapping(VISION_FUSED_MAPPING)\n+\n+ scheme = config.get_scheme_dict(torch.nn.Linear(1, 1), VISION_GATE_UP_LAYER)\n+\n+ self.assertIsNotNone(\n+ scheme, \"an empty ignore list must not force the tower to bf16\"\n+ )\n+\n+ def test_parent_ignore_does_not_swallow_fused_children(self):\n+ \"\"\"The no-prefix invariant, in both spellings of the parent entry.\"\"\"\n+ for entry in (f\"{VISION_PREFIX}.0.mlp\", f\"{VISION_PREFIX}.0.mlp.linear\"):\n+ self.assertFalse(\n+ should_ignore_layer(\n+ VISION_GATE_UP_LAYER,\n+ ignore=[entry],\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ ),\n+ entry,\n+ )\n+\n+ def test_retry_stays_keyed_on_the_ignore_list(self):\n+ \"\"\"Only the wrapper suffix, only one level, only listed modules.\"\"\"\n+ for entry in (\n+ \"some.other.module.linear\",\n+ f\"{VISION_PREFIX}.0.self_attn.q_proj.linear.linear\",\n+ f\"{VISION_PREFIX}.0.self_attn.q_proj.weight\",\n+ ):\n+ self.assertFalse(\n+ should_ignore_layer(\n+ VISION_QKV_LAYER,\n+ ignore=[entry],\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ ),\n+ entry,\n+ )\n+\n+ def test_class_name_target_spelling_stays_inert(self):\n+ \"\"\"Configs name the class as \"Linear\", and matching is case-sensitive.\"\"\"\n+ for layer_name in (\n+ VISION_QKV_LAYER,\n+ VISION_O_PROJ_LAYER,\n+ VISION_DOWN_PROJ_LAYER,\n+ ):\n+ self.assertFalse(\n+ should_ignore_layer(\n+ layer_name,\n+ ignore=[\"Linear\"],\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ ),\n+ layer_name,\n+ )\n+\n+ def test_bare_linear_token_reaches_fused_names_only(self):\n+ \"\"\"A bare \"linear\" entry is a suffix target, so it now reaches fused names.\n+\n+ It cannot reach further than that: unfused names that are not already\n+ nested at \".linear\" are matched exactly as before.\n+ \"\"\"\n+ self.assertTrue(\n+ should_ignore_layer(\n+ VISION_QKV_LAYER,\n+ ignore=[\"linear\"],\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ )\n+ )\n+ for layer_name in (f\"{VISION_PREFIX}.0.self_attn.o_proj\", \"lm_head\"):\n+ self.assertFalse(\n+ should_ignore_layer(\n+ layer_name,\n+ ignore=[\"linear\"],\n+ fused_mapping=VISION_FUSED_MAPPING,\n+ ),\n+ layer_name,\n+ )\n+\n+\n class TestMixedPrecisionFormat(CustomTestCase):\n \"\"\"The per-group `format` must win over a top-level \"mixed-precision\".\"\"\"\n \n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: sgl-project/sglang\nPull request: [Fix] [SM120] quantization: Requantize block-FP8 MoE weights to UE8M0 for DeepGEMM\nLabels: quant\nFiles changed (4): python/sglang/srt/layers/quantization/fp8.py, python/sglang/srt/layers/quantization/fp8_utils.py, python/sglang/srt/model_loader/utils.py, test/registered/unit/layers/quantization/test_deepgemm_ue8m0_requant.py\n\n## Description (results removed)\n\n## Motivation\n\nOn SM120, `should_deepgemm_weight_requant_ue8m0` returns False for every caller, so block-FP8 MoE experts served by the DeepGEMM runner keep their FP32 checkpoint scales. SM120's grouped GEMM converts FP32 scales to UE8M0 itself, and it faults (CUDA error 719) on scales that are not powers of two.\n\nWith `nvidia/Qwen3.8-Flash-Next-NVFP4` and `--speculative-moe-runner-backend deep_gemm`, the block-FP8 MTP draft experts crash at the first prefill graph capture, at every token count. The same weights with power-of-two scales run.\n\n#39065 (open, fixing #39063) makes the same guard change by inferring a grouped layer from `weight.ndim == 3`, without tests. This PR differs in two ways:\n\nSplit out of #42566 at a maintainer's request. #42566 now carries only the TP block-scale refinement, which depends on this change for its DeepGEMM path on SM120.\n\nFixes #39063\n\n## Modifications\n\n- Keep the SM120 exemption for dense block-FP8 GEMMs, which run on CUTLASS or Triton with FP32 scales there.\n- Requantize grouped MoE weights to UE8M0 as on SM90 and SM100.\n- `should_deepgemm_weight_requant_ue8m0` and `requant_block_scale_ue8m0_for_deepgemm` take a keyword-only `grouped_moe` flag, which `Fp8MoEMethod` sets for its expert weights.\n\n## Accuracy Tests\n[results removed]\n## Checklist\n\nThis PR was written with AI assistance (Claude); I reviewed every line.\n\n---\n### CI States\n\nLatest PR Test (Base): :x: [Run #39355945695](https://github.com/sgl-project/sglang/actions/runs/39355945695)\nLatest PR Test (Extra): :x: [Run #39355945781](https://github.com/sgl-project/sglang/actions/runs/39355945781)\nLatest PR Test (AMD ROCm 10): :x: [Run #39355945903](https://github.com/sgl-project/sglang/actions/runs/39355945903)\n\n## Diff\n\n```diff\ndiff --git a/python/sglang/srt/layers/quantization/fp8.py b/python/sglang/srt/layers/quantization/fp8.py\nindex 9d0c3e0116fa..360e62e3b614 100644\n--- a/python/sglang/srt/layers/quantization/fp8.py\n+++ b/python/sglang/srt/layers/quantization/fp8.py\n@@ -2205,6 +2205,7 @@ def process_weights_after_loading_block_quant(self, layer: Module) -> None:\n use_deepgemm_runner=will_use_deepgemm,\n output_dtype=torch.bfloat16,\n weight_shape=weight.shape[-2:],\n+ grouped_moe=True,\n )\n \n def _convert_mxfp8_moe_to_block_fp8(self, layer: Module) -> None:\ndiff --git a/python/sglang/srt/layers/quantization/fp8_utils.py b/python/sglang/srt/layers/quantization/fp8_utils.py\nindex 231b243ed939..097a75066f0c 100755\n--- a/python/sglang/srt/layers/quantization/fp8_utils.py\n+++ b/python/sglang/srt/layers/quantization/fp8_utils.py\n@@ -2023,6 +2023,8 @@ def requant_block_scale_ue8m0_for_deepgemm(\n use_deepgemm_runner: bool,\n output_dtype: Optional[torch.dtype] = None,\n weight_shape=None,\n+ *,\n+ grouped_moe: bool = False,\n ) -> bool:\n \"\"\"Requantize block-FP8 weight scales to UE8M0 in place for DeepGEMM.\n \n@@ -2041,6 +2043,7 @@ def requant_block_scale_ue8m0_for_deepgemm(\n weight_block_size=weight_block_size,\n output_dtype=output_dtype,\n weight_shape=weight_shape,\n+ grouped_moe=grouped_moe,\n )\n ):\n return False\ndiff --git a/python/sglang/srt/model_loader/utils.py b/python/sglang/srt/model_loader/utils.py\nindex 55496273bda3..c3bdbafa59ac 100644\n--- a/python/sglang/srt/model_loader/utils.py\n+++ b/python/sglang/srt/model_loader/utils.py\n@@ -264,7 +264,7 @@ def get_architecture_class_name(model_config: ModelConfig) -> str:\n \n \n def should_deepgemm_weight_requant_ue8m0(\n- weight_block_size, output_dtype=None, weight_shape=None\n+ weight_block_size, output_dtype=None, weight_shape=None, *, grouped_moe=False\n ):\n \"\"\"Should we requant fp8 weights into UE8M0 format when loading the model.\n \n@@ -281,7 +281,7 @@ def should_deepgemm_weight_requant_ue8m0(\n return False\n # SM120 routes dense block-FP8 GEMMs to CUTLASS/Triton (fp32 scales);\n # only the grouped MoE GEMM consumes DeepGEMM layouts there.\n- if get_device_sm() == 120:\n+ if get_device_sm() == 120 and not grouped_moe:\n return False\n if output_dtype is not None and output_dtype != torch.bfloat16:\n return False\ndiff --git a/test/registered/unit/layers/quantization/test_deepgemm_ue8m0_requant.py b/test/registered/unit/layers/quantization/test_deepgemm_ue8m0_requant.py\nindex ddc039fcd450..c6db7e15c614 100644\n--- a/test/registered/unit/layers/quantization/test_deepgemm_ue8m0_requant.py\n+++ b/test/registered/unit/layers/quantization/test_deepgemm_ue8m0_requant.py\n@@ -11,6 +11,7 @@\n from compressed_tensors.quantization import QuantizationStrategy\n \n import sglang.srt.layers.quantization.fp8_utils as fp8_utils\n+import sglang.srt.model_loader.utils as model_loader_utils\n from sglang.srt.layers import deep_gemm_wrapper\n from sglang.srt.layers.quantization import fp8 as fp8_quant\n from sglang.srt.layers.quantization.compressed_tensors.schemes.compressed_tensors_w8a8_fp8 import (\n@@ -65,6 +66,37 @@ def test_helper_requants_supported_deepgemm_bf16_once(self):\n self.assertTrue(weight_scale.format_ue8m0)\n requant.assert_called_once_with(weight, weight_scale, BLOCK_SIZE)\n \n+ def test_sm120_requants_grouped_moe_but_not_dense_weights(self):\n+ \"\"\"SM120's DeepGEMM grouped MoE GEMM faults on FP32 block scales that are\n+ not powers of two; dense block-FP8 GEMMs there keep FP32 scales.\"\"\"\n+ dense = _make_params()\n+ experts = _make_params()\n+\n+ with (\n+ self._enabled_deepgemm_ue8m0(),\n+ patch.object(model_loader_utils, \"get_device_sm\", return_value=120),\n+ patch.object(fp8_utils, \"requant_weight_ue8m0_inplace\") as requant,\n+ ):\n+ dense_fired = fp8_utils.requant_block_scale_ue8m0_for_deepgemm(\n+ *dense,\n+ BLOCK_SIZE,\n+ use_deepgemm_runner=True,\n+ output_dtype=torch.bfloat16,\n+ weight_shape=dense[0].shape,\n+ )\n+ experts_fired = fp8_utils.requant_block_scale_ue8m0_for_deepgemm(\n+ *experts,\n+ BLOCK_SIZE,\n+ use_deepgemm_runner=True,\n+ output_dtype=torch.bfloat16,\n+ weight_shape=experts[0].shape,\n+ grouped_moe=True,\n+ )\n+\n+ self.assertFalse(dense_fired)\n+ self.assertTrue(experts_fired)\n+ requant.assert_called_once_with(*experts, BLOCK_SIZE)\n+\n def test_helper_skips_non_bf16_output(self):\n weight, weight_scale = _make_params()\n \n@@ -213,6 +245,7 @@ def _mark_ue8m0(weight, weight_scale, *args, **kwargs):\n use_deepgemm_runner=True,\n output_dtype=torch.bfloat16,\n weight_shape=layer.w13_weight.shape[-2:],\n+ grouped_moe=True,\n ),\n call(\n layer.w2_weight,\n@@ -221,6 +254,7 @@ def _mark_ue8m0(weight, weight_scale, *args, **kwargs):\n use_deepgemm_runner=True,\n output_dtype=torch.bfloat16,\n weight_shape=layer.w2_weight.shape[-2:],\n+ grouped_moe=True,\n ),\n ],\n )\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: sgl-project/sglang\nPull request: [Fix] disaggregation: Reuse startup decode graphs across PD role switches\nLabels: run-ci\nFiles changed (2): python/sglang/srt/model_executor/model_runner.py, test/registered/unit/disaggregation/test_pd_role_switch.py\n\n## Description (results removed)\n\n## Motivation\n\nFixes https://github.com/sgl-project/sglang/issues/43557.\n\nAn engine launched in decode mode captures its decode CUDA graphs during `ModelRunner.init_cuda_graphs()`, but that path leaves `decode_cuda_graph_captured` false and `decode_cuda_graph_capture_bs` empty. After a decode → prefill → decode round trip, `ensure_decode_cuda_graphs()` therefore captures another runner instead of reusing the startup graphs. The original v0.5.21 source reproduced CUDA illegal memory access on the first returned-decode workload in two independent concurrent runs.\n\n## Modifications\n\n- Record the captured flag and batch sizes when assigning the startup decode graph runner, matching the bookkeeping already performed by `init_decode_cuda_graph()`.\n- Reuse startup graphs on later role switches while retaining deferred capture when startup produced no decode graph.\n\n## Checklist\n\n---\n### CI States\n\nLatest PR Test (Base): :white_check_mark: [Run #39051538377](https://github.com/sgl-project/sglang/actions/runs/39051538377)\nLatest PR Test (Extra): :x: [Run #39051538330](https://github.com/sgl-project/sglang/actions/runs/39051538330)\nLatest PR Test (AMD ROCm 10): :x: [Run #39051538395](https://github.com/sgl-project/sglang/actions/runs/39051538395)\n\n## Diff\n\n```diff\ndiff --git a/python/sglang/srt/model_executor/model_runner.py b/python/sglang/srt/model_executor/model_runner.py\nindex 6818ad777830..59b6eaf29adb 100644\n--- a/python/sglang/srt/model_executor/model_runner.py\n+++ b/python/sglang/srt/model_executor/model_runner.py\n@@ -1189,6 +1189,11 @@ def init_cuda_graphs(self, capture_decode_cuda_graph: bool = True):\n self.eager_runner = capture.eager_runner\n self.prefill_cuda_graph_runner = capture.prefill.runner\n self.decode_cuda_graph_runner = capture.decode.runner\n+ # Reuse startup decode graphs on a subsequent PD role switch.\n+ self.decode_cuda_graph_captured = self.decode_cuda_graph_runner is not None\n+ self.decode_cuda_graph_capture_bs = list(\n+ getattr(self.decode_cuda_graph_runner, \"capture_bs\", []) or []\n+ )\n self.graph_memory_usage = capture.memory_usage\n self.graph_time_usage = capture.time_usage\n \ndiff --git a/test/registered/unit/disaggregation/test_pd_role_switch.py b/test/registered/unit/disaggregation/test_pd_role_switch.py\nindex 493c2e5bd8bd..b5b700e9399e 100644\n--- a/test/registered/unit/disaggregation/test_pd_role_switch.py\n+++ b/test/registered/unit/disaggregation/test_pd_role_switch.py\n@@ -597,5 +597,47 @@ def test_teardown_invokes_release(self):\n s.tree_cache.reset.assert_called_once_with()\n \n \n+class TestStartupDecodeGraphReuse(unittest.TestCase):\n+ def test_switch_reuses_startup_graph_or_captures_when_missing(self):\n+ from sglang.srt.managers.tp_worker import TpModelWorker\n+ from sglang.srt.model_executor import model_runner as mr\n+\n+ for graph in (SimpleNamespace(capture_bs=[1, 2, 4]), None):\n+ with self.subTest(captured_at_startup=graph is not None):\n+ rc.reset_context()\n+ try:\n+ rc.get_context().set_server_args(ServerArgs(model_path=\"dummy\"))\n+ runner = mr.ModelRunner.__new__(mr.ModelRunner)\n+ runner.model = MagicMock()\n+ runner.decode_cuda_graph_captured = False\n+ runner.decode_cuda_graph_capture_bs = []\n+ runner.init_decode_cuda_graph = MagicMock()\n+ capture = SimpleNamespace(\n+ eager_runner=MagicMock(),\n+ prefill=SimpleNamespace(runner=None),\n+ decode=SimpleNamespace(runner=graph),\n+ memory_usage=None,\n+ time_usage=None,\n+ )\n+ with (\n+ patch.object(mr, \"capture_cuda_graphs\", return_value=capture),\n+ patch.object(mr, \"prebuild_deepep_v2_buffer\"),\n+ ):\n+ runner.init_cuda_graphs()\n+ worker = SimpleNamespace(model_runner=runner)\n+ self.assertEqual(\n+ TpModelWorker.get_decode_cuda_graph_bs(worker),\n+ [1, 2, 4] if graph is not None else [],\n+ )\n+ runner.ensure_decode_cuda_graphs()\n+ if graph is not None:\n+ runner.init_decode_cuda_graph.assert_not_called()\n+ self.assertIs(runner.decode_cuda_graph_runner, graph)\n+ else:\n+ runner.init_decode_cuda_graph.assert_called_once_with()\n+ finally:\n+ rc.reset_context()\n+\n+\n if __name__ == \"__main__\":\n unittest.main()\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: sgl-project/sglang\nPull request: [Fix] DSA: skip-topk pipeline handoff for owed outputs\nLabels: deepseek, run-ci\nFiles changed (2): python/sglang/srt/models/deepseek_v2.py, test/registered/unit/models/test_deepseek_pp_mtp_embedding.py\n\n## Description (results removed)\n\nFixes #43580\n\n## Motivation\n\n`DeepseekV2Model.forward` exports the stage output through `residual_batch.to_pp()` before checking whether a non-idle batch has rows that require DSA top-k indices. A residual-stream output may still be represented locally by an opaque `OwedOutput`, so reading `hidden_states.shape` after export raises `AttributeError` during the PP handoff.\n\n## Modifications\n\n- Read the row count from the exported `proxy_tensors[\"hidden_states\"]` tensor.\n- Use the same exported tensor when allocating empty top-k indices for the zero-row case, preserving its device and the existing `torch.int32` shape contract.\n\n## Tests\n[results removed]\n## Accuracy Tests\n[results removed]\n## Checklist\n\n- [x] Format/lint checks for changed files.\n- [ ] Full repository CI and GPU/model validation.\n- [ ] Codeowner and Merge Oncall review.\n\n---\n### CI States\n\nLatest PR Test (Base): :hourglass_flowing_sand: [Run #38968488327](https://github.com/sgl-project/sglang/actions/runs/38968488327)\nLatest PR Test (Extra): :x: [Run #38968488473](https://github.com/sgl-project/sglang/actions/runs/38968488473)\nLatest PR Test (AMD ROCm 10): :hourglass_flowing_sand: [Run #38968488805](https://github.com/sgl-project/sglang/actions/runs/38968488805)\n\n## Diff\n\n```diff\ndiff --git a/python/sglang/srt/models/deepseek_v2.py b/python/sglang/srt/models/deepseek_v2.py\nindex 9b1b597ec8bc..4c9ec84f6062 100644\n--- a/python/sglang/srt/models/deepseek_v2.py\n+++ b/python/sglang/srt/models/deepseek_v2.py\n@@ -3194,7 +3194,7 @@ def forward(\n topk_indices = index_topk_share.topk_indices\n if (\n not forward_batch.forward_mode.is_idle()\n- and hidden_states.shape[0] != 0\n+ and proxy_tensors[\"hidden_states\"].shape[0] != 0\n ):\n assert topk_indices is not None, (\n f\"PP stage ending at layer {self.end_layer} must forward \"\n@@ -3202,7 +3202,7 @@ def forward(\n \"skip-topk layer.\"\n )\n if topk_indices is None:\n- topk_indices = hidden_states.new_empty(\n+ topk_indices = proxy_tensors[\"hidden_states\"].new_empty(\n (0, get_dsa_index_topk(self.config)), dtype=torch.int32\n )\n proxy_tensors.tensors[\"topk_indices\"] = topk_indices\ndiff --git a/test/registered/unit/models/test_deepseek_pp_mtp_embedding.py b/test/registered/unit/models/test_deepseek_pp_mtp_embedding.py\nindex 2a3334852e09..0a8ce56da4f9 100644\n--- a/test/registered/unit/models/test_deepseek_pp_mtp_embedding.py\n+++ b/test/registered/unit/models/test_deepseek_pp_mtp_embedding.py\n@@ -2,8 +2,17 @@\n \n import unittest\n from types import SimpleNamespace\n+from unittest.mock import Mock, patch\n \n-from sglang.srt.models.deepseek_v2 import pp_stage_needs_embedding\n+import torch\n+\n+from sglang.srt.layers.layer_boundary import PLAIN_ADD, SumGroup\n+from sglang.srt.layers.layer_boundary.output import DeferredFinalize\n+from sglang.srt.layers.layer_boundary.residual import stream as residual_stream\n+from sglang.srt.layers.layer_boundary.residual.stream import OwedOutput\n+from sglang.srt.model_executor.forward_batch_info import ForwardMode\n+from sglang.srt.models import deepseek_v2\n+from sglang.srt.models.deepseek_v2 import DeepseekV2Model, pp_stage_needs_embedding\n from sglang.test.ci.ci_register import register_cpu_ci\n from sglang.test.test_utils import CustomTestCase\n \n@@ -41,5 +50,101 @@ def test_without_pipeline_parallelism_the_single_stage_embeds_either_way(self):\n )\n \n \n+class TestDeepseekDSAPPHandoff(CustomTestCase):\n+ def test_skip_topk_pp_handoff_uses_exported_hidden_states(self):\n+ for rows in (2, 0):\n+ for deferred_finalize in (False, True):\n+ with self.subTest(rows=rows, deferred_finalize=deferred_finalize):\n+ self._run_forward(rows, deferred_finalize)\n+\n+ def _run_forward(self, rows, deferred_finalize):\n+ class Group:\n+ def __init__(self):\n+ self.all_reduce_calls = 0\n+\n+ def all_reduce(self, value):\n+ self.all_reduce_calls += 1\n+ return value\n+\n+ forward_batch = SimpleNamespace(\n+ can_run_tbo=False,\n+ forward_mode=ForwardMode.DECODE,\n+ residual_stream=None,\n+ reuse_dsa_topk_indices=False,\n+ spec_info=None,\n+ )\n+ expected_hidden = torch.ones(rows, 4)\n+ expected_topk = torch.ones(rows, 3, dtype=torch.int32) if rows else None\n+ group = Group()\n+ finalize = Mock(return_value=expected_hidden)\n+\n+ class Layer:\n+ def __call__(self, *args, **kwargs):\n+ stream = deepseek_v2.residual_batch.stream_of(forward_batch)\n+ if deferred_finalize:\n+ hidden = stream.record(DeferredFinalize(), PLAIN_ADD)\n+ else:\n+ hidden = stream.record(\n+ expected_hidden,\n+ PLAIN_ADD,\n+ declared_sum=SumGroup.TP,\n+ )\n+ assert isinstance(hidden, OwedOutput)\n+ assert group.all_reduce_calls == 0\n+ return hidden, expected_topk\n+\n+ model = DeepseekV2Model.__new__(DeepseekV2Model)\n+ torch.nn.Module.__init__(model)\n+ model.use_dsa = True\n+ model.pp_group = SimpleNamespace(is_first_rank=True, is_last_rank=False)\n+ model.config = SimpleNamespace(num_hidden_layers=2)\n+ model.start_layer = 0\n+ model.end_layer = 1\n+ model.layers = [Layer()]\n+ model.embed_tokens = torch.nn.Identity()\n+ model.layers_to_capture = []\n+ model.next_full_attention_layer_id = {}\n+ model.llama_4_scaling_config = None\n+\n+ finalizer_patch = (\n+ patch.object(DeferredFinalize, \"complete\", finalize)\n+ if deferred_finalize\n+ else patch.object(DeferredFinalize, \"complete\")\n+ )\n+ with (\n+ patch.object(model, \"_dsa_forward_uses_topk\", return_value=True),\n+ patch.object(deepseek_v2, \"dsa_layer_skips_topk\", return_value=True),\n+ patch.object(deepseek_v2, \"get_dsa_index_topk\", return_value=3),\n+ patch.object(deepseek_v2, \"BumpAllocator\", return_value=None),\n+ patch.object(deepseek_v2, \"check_cuda_graph_backend\", return_value=True),\n+ patch.object(residual_stream, \"_sum_group\", return_value=group),\n+ finalizer_patch,\n+ ):\n+ proxy = model.forward(\n+ input_ids=torch.zeros(rows, dtype=torch.long),\n+ positions=torch.zeros(rows, dtype=torch.long),\n+ forward_batch=forward_batch,\n+ )\n+\n+ if deferred_finalize:\n+ finalize.assert_called_once_with()\n+ self.assertEqual(group.all_reduce_calls, 0)\n+ else:\n+ finalize.assert_not_called()\n+ self.assertEqual(group.all_reduce_calls, 1)\n+ self.assertIsNone(forward_batch.residual_stream)\n+ self.assertEqual(proxy[\"hidden_states\"].shape, (rows, 4))\n+ torch.testing.assert_close(proxy[\"hidden_states\"], expected_hidden)\n+ if rows:\n+ self.assertIs(proxy[\"topk_indices\"], expected_topk)\n+ torch.testing.assert_close(proxy[\"topk_indices\"], expected_topk)\n+ else:\n+ self.assertEqual(proxy[\"topk_indices\"].shape, (0, 3))\n+ self.assertEqual(proxy[\"topk_indices\"].dtype, torch.int32)\n+ self.assertEqual(\n+ proxy[\"topk_indices\"].device, proxy[\"hidden_states\"].device\n+ )\n+\n+\n if __name__ == \"__main__\":\n unittest.main()\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: sgl-project/sglang\nPull request: [Fix] glm4v: Clamp request video budgets to the deployment limit\nLabels: documentation, Multi-modal, run-ci\nFiles changed (5): docs/docs/supported-models/multimodal_language_models.mdx, python/sglang/srt/disaggregation/encoder/preprocessor.py, python/sglang/srt/entrypoints/openai/protocol.py, python/sglang/srt/multimodal/processors/glm4v.py, test/registered/unit/multimodal/test_glm4v_mixed_offsets.py\n\n## Description (results removed)\n\n## Motivation\n\nFixes #43705.\n\nGLM-V video requests could raise `fps`, `max_frames`, `max_tokens_per_frame`, and `max_image_tokens` above the deployment budget before frames were decoded. A large request could then make the worker decode far more frames, at higher resolution, than the default config allows.\n\n## Modifications\n\n- Clamp each request knob to the deployment limit, so a request can only tighten the budget. Omitted knobs stay unset, so an `fps`-only request does not inject `max_frames` and bypass the HF sampler.\n- The `max_frames` limit comes from the processor's `max_frames`, or from `--mm-process-config`. GLM-4.1V/4.5V/4.6V processors have no `max_frames`; their HF sampler stops at `max_duration * fps` (600 by default), so that value is the limit there. It follows a server `fps` override.\n - Note: GLM-4.6V's own HF sampler allows up to 640 frames, so a request asking for 601-640 frames now gets 600. This is deliberate: the limit stays at or below what the default config samples.\n- At decode time, drop a request `max_tokens_per_frame` when its total pixels (`cap * 28^2 * frame_count`) exceed the shared presize budget. The frames then go through the shared presize path. A server-configured per-frame cap keeps per-frame mode.\n- On the DP encoder path, make that decision with the full clip length, so every shard picks the same resizer.\n- Reject non-positive, non-numeric, and non-finite values. `ChatCompletionMessageContentVideoURL` now declares `gt=0` (and `allow_inf_nan=False` for `fps`), so OpenAI-path requests get a 400 before batching. The processor keeps the same check for the native `/generate` path.\n- Log a one-time warning when a request value is clamped.\n- Docs: `multimodal_language_models.mdx` now says GLM-V request knobs can only tighten the budget, and operators raise the limits with `--mm-process-config`.\n\n## Accuracy Tests\n[results removed]\n## Checklist\n\nAccuracy and speed benchmarks do not apply because this does not change model outputs or kernels.\n\n---\n### CI States\n\nLatest PR Test (Base): :white_check_mark: [Run #39040010390](https://github.com/sgl-project/sglang/actions/runs/39040010390)\nLatest PR Test (Extra): :x: [Run #39040010177](https://github.com/sgl-project/sglang/actions/runs/39040010177)\nLatest PR Test (AMD ROCm 10): :x: [Run #39040010354](https://github.com/sgl-project/sglang/actions/runs/39040010354)\n\n## Diff\n\n```diff\ndiff --git a/python/sglang/srt/disaggregation/encoder/preprocessor.py b/python/sglang/srt/disaggregation/encoder/preprocessor.py\nindex c0344903b582..b38b88633079 100644\n--- a/python/sglang/srt/disaggregation/encoder/preprocessor.py\n+++ b/python/sglang/srt/disaggregation/encoder/preprocessor.py\n@@ -29,6 +29,7 @@\n )\n from sglang.srt.multimodal.processors.glm4v import (\n _glm_effective_presize_budget,\n+ _merge_glm_video_configs,\n glm_budget_kwargs,\n glm_decode_frames_at,\n glm_max_image_tokens_from_configs,\n@@ -465,7 +466,11 @@ async def _dp_sharded_decode_single_video(\n try:\n frames = await asyncio.get_running_loop().run_in_executor(\n self.io_executor,\n- glm_decode_frames_at,\n+ functools.partial(\n+ glm_decode_frames_at,\n+ # Full-clip count. local_indices is this rank's shard.\n+ budget_frame_count=len(global_indices),\n+ ),\n vr,\n local_indices,\n video_config,\n@@ -523,9 +528,7 @@ async def _flatten_and_load_videos(self, mm_items):\n mm_items, video_configs = split_glm_video_items(mm_items)\n defaults = glm_processor_video_config(self.video_processor)\n defaults.update(self.vision_config.get(\"video\", {}))\n- video_configs = [\n- {**defaults, **dict(config or {})} for config in video_configs\n- ]\n+ video_configs = _merge_glm_video_configs(defaults, video_configs)\n \n futures, _ = self._submit_data_loading_tasks(\n mm_items, [Modality.VIDEO] * len(mm_items)\ndiff --git a/python/sglang/srt/entrypoints/openai/protocol.py b/python/sglang/srt/entrypoints/openai/protocol.py\nindex 36c1a41f6731..641ccde47665 100644\n--- a/python/sglang/srt/entrypoints/openai/protocol.py\n+++ b/python/sglang/srt/entrypoints/openai/protocol.py\n@@ -606,10 +606,10 @@ class ChatCompletionMessageContentVideoURL(BaseModel):\n url: str\n max_dynamic_patch: Optional[int] = None\n min_dynamic_patch: Optional[int] = None\n- fps: Optional[float] = None\n- max_frames: Optional[int] = None\n- max_tokens_per_frame: Optional[int] = None\n- max_image_tokens: Optional[int] = None\n+ fps: Optional[float] = Field(default=None, gt=0, allow_inf_nan=False)\n+ max_frames: Optional[int] = Field(default=None, gt=0)\n+ max_tokens_per_frame: Optional[int] = Field(default=None, gt=0)\n+ max_image_tokens: Optional[int] = Field(default=None, gt=0)\n \n \n class ChatCompletionMessageContentAudioURL(BaseModel):\ndiff --git a/python/sglang/srt/multimodal/processors/glm4v.py b/python/sglang/srt/multimodal/processors/glm4v.py\nindex 105814e25a58..aee01de5db8c 100644\n--- a/python/sglang/srt/multimodal/processors/glm4v.py\n+++ b/python/sglang/srt/multimodal/processors/glm4v.py\n@@ -16,7 +16,7 @@\n from sglang.srt.multimodal.processors.base_processor import (\n MultimodalSpecialTokens,\n )\n-from sglang.srt.utils import GLM_MEDIA_CONFIG_KEYS\n+from sglang.srt.utils import GLM_MEDIA_CONFIG_KEYS, print_warning_once\n from sglang.srt.utils.video_decoder import VideoDecoderWrapper\n \n try:\n@@ -34,6 +34,7 @@\n GLM_VIDEO_PATCH_SIZE = 14\n GLM_VIDEO_MERGE_SIZE = 2\n GLM_VIDEO_PATCH_EXPAND_FACTOR = 4\n+GLM_VIDEO_FRAME_PIXELS_PER_TOKEN = (GLM_VIDEO_PATCH_SIZE * GLM_VIDEO_MERGE_SIZE) ** 2\n \n \n def _glm_video_metadata(total_num_frames, fps, duration, frames_indices):\n@@ -116,6 +117,8 @@ def glm_processor_video_config(processor):\n for key in GLM_MEDIA_CONFIG_KEYS\n if (value := getattr(processor, key, None)) is not None\n }\n+ if (max_duration := getattr(processor, \"max_duration\", None) or 0) > 0:\n+ config[\"_max_duration\"] = max_duration\n budget = _glm_processor_resize_budget(processor)\n if budget is not None:\n config[\"_presize_budget\"] = budget\n@@ -155,9 +158,72 @@ def _glm_effective_presize_budget(video_config, effective_max_image_tokens):\n return config\n \n \n+def _glm_video_budget_ceiling(defaults, key):\n+ if defaults.get(key) is not None:\n+ return defaults[key]\n+ if key == \"fps\":\n+ return GLM_VIDEO_DEFAULT_FPS\n+ if key == \"max_frames\":\n+ # HF samplers without max_frames (GLM-4.1V/4.6V) stop at max_duration * fps.\n+ if max_duration := defaults.get(\"_max_duration\"):\n+ return int(max_duration * defaults.get(\"fps\", GLM_VIDEO_DEFAULT_FPS))\n+ return GLM_VIDEO_DEFAULT_MAX_FRAMES\n+ return None\n+\n+\n+def _clamp_glm_video_request_config(defaults, request):\n+ \"\"\"Let request knobs lower the deployment budget, never raise it.\n+\n+ Omitted keys stay unset so an injected max_frames does not bypass the HF sampler.\n+ \"\"\"\n+ merged = {**defaults, **request}\n+ if defaults.get(\"max_tokens_per_frame\") is not None:\n+ merged[\"_server_max_tokens_per_frame\"] = True\n+ for key in GLM_MEDIA_CONFIG_KEYS:\n+ if key not in request:\n+ continue\n+ number = float if key == \"fps\" else int\n+ try:\n+ value = number(request[key])\n+ valid = value > 0 and (number is int or math.isfinite(value))\n+ except (TypeError, ValueError, OverflowError):\n+ valid = False\n+ if not valid:\n+ raise ValueError(f\"GLM video {key} must be a positive finite number\")\n+ ceiling = _glm_video_budget_ceiling(defaults, key)\n+ if ceiling is not None and value > number(ceiling):\n+ print_warning_once(\n+ f\"GLM video request {key} is clamped to the deployment limit \"\n+ f\"{ceiling}; raise it with --mm-process-config.\"\n+ )\n+ value = number(ceiling)\n+ merged[key] = value\n+ return merged\n+\n+\n+def _glm_video_config_for_decode(video_config, frame_count):\n+ \"\"\"Drop a request per-frame cap whose total pixels exceed the shared presize budget.\n+\n+ ``frame_count`` is the full clip, not a DP shard. A server-configured cap stays.\n+ \"\"\"\n+ config = dict(video_config or {})\n+ cap = config.get(\"max_tokens_per_frame\")\n+ budget = config.get(\"_presize_budget\")\n+ if cap is None or not budget or config.get(\"_server_max_tokens_per_frame\"):\n+ return config\n+ # Per-frame resize counts 28x28 px per token; presize max_pixels spans all frames.\n+ frame_pixels = int(cap) * GLM_VIDEO_FRAME_PIXELS_PER_TOKEN\n+ if frame_pixels * int(frame_count) > budget[\"max_pixels\"]:\n+ config.pop(\"max_tokens_per_frame\", None)\n+ return config\n+\n+\n def _merge_glm_video_configs(default_config, item_configs):\n defaults = dict(default_config or {})\n- return [{**defaults, **dict(config or {})} for config in item_configs]\n+ return [\n+ _clamp_glm_video_request_config(defaults, dict(config or {}))\n+ for config in item_configs\n+ ]\n \n \n def _hf_sample_frame_indices(\n@@ -250,7 +316,7 @@ def _resize_frames_to_max_tokens(frames, max_tokens_per_frame):\n frames = torch.from_numpy(np.asarray(frames))\n nchw = frames.permute(0, 3, 1, 2)\n _, _, height, width = nchw.shape\n- pixels_per_token = (GLM_VIDEO_PATCH_SIZE * GLM_VIDEO_MERGE_SIZE) ** 2\n+ pixels_per_token = GLM_VIDEO_FRAME_PIXELS_PER_TOKEN\n factor = GLM_VIDEO_PATCH_SIZE * GLM_VIDEO_MERGE_SIZE * GLM_VIDEO_PATCH_EXPAND_FACTOR\n max_pixels = max(\n int(max_tokens_per_frame) * pixels_per_token,\n@@ -388,11 +454,14 @@ def _pre_resize_frames_for_processor(\n return nchw.permute(0, 2, 3, 1).contiguous()\n \n \n-def glm_decode_frames_at(vr, indices, video_config=None):\n+def glm_decode_frames_at(vr, indices, video_config=None, budget_frame_count=None):\n+ \"\"\"Decode ``indices`` and resize under the shared token budget.\"\"\"\n indices = list(indices)\n if not indices:\n return None\n- video_config = video_config or {}\n+ if budget_frame_count is None:\n+ budget_frame_count = len(indices)\n+ video_config = _glm_video_config_for_decode(video_config, budget_frame_count)\n if hasattr(vr, \"get_frames_as_tensor\"):\n frames = vr.get_frames_as_tensor(indices)\n else:\ndiff --git a/test/registered/unit/multimodal/test_glm4v_mixed_offsets.py b/test/registered/unit/multimodal/test_glm4v_mixed_offsets.py\nindex 1384c12c168f..54a0b8a9150c 100644\n--- a/test/registered/unit/multimodal/test_glm4v_mixed_offsets.py\n+++ b/test/registered/unit/multimodal/test_glm4v_mixed_offsets.py\n@@ -1,9 +1,19 @@\n+import numpy as np\n import pytest\n import torch\n+from pydantic import ValidationError\n \n+from sglang.srt.entrypoints.openai.protocol import ChatCompletionMessageContentVideoURL\n from sglang.srt.managers.schedule_batch import Modality\n+from sglang.srt.multimodal.processors import glm4v as glm4v_module\n from sglang.srt.multimodal.processors.base_processor import MultimodalSpecialTokens\n-from sglang.srt.multimodal.processors.glm4v import Glm4vImageProcessor\n+from sglang.srt.multimodal.processors.glm4v import (\n+ Glm4vImageProcessor,\n+ _merge_glm_video_configs,\n+ glm_decode_frames_at,\n+ glm_processor_video_config,\n+ glm_sample_and_decode_sync,\n+)\n from sglang.test.ci.ci_register import register_cpu_ci\n \n register_cpu_ci(est_time=9, suite=\"base-a-test-cpu\")\n@@ -97,5 +107,173 @@ def test_glm4v_uses_default_offsets_when_token_ids_are_distinct():\n ]\n \n \n+class _Glm5NextLikeVideoProcessor:\n+ fps = 2\n+ max_frames = 2048\n+ max_duration = 0\n+ max_image_tokens = 16384\n+ patch_size = 14\n+ merge_size = 2\n+ temporal_patch_size = 2\n+\n+\n+class _Glm4vLikeVideoProcessor:\n+ \"\"\"GLM-4.1V/4.6V shape: no max_frames, HF sampler stops at max_duration * fps.\"\"\"\n+\n+ fps = 2\n+ max_duration = 300\n+\n+ def sample_frames(self, metadata, fps=None):\n+ duration = min(metadata.duration, self.max_duration)\n+ count = int(duration * (fps or self.fps))\n+ return np.linspace(0, metadata.total_num_frames - 1, count, dtype=int)\n+\n+\n+class _FakeVideoReader:\n+ avg_fps = 30.0\n+\n+ def __init__(self, seconds):\n+ self._num_frames = int(seconds * self.avg_fps)\n+\n+ def __len__(self):\n+ return self._num_frames\n+\n+ def get_frames_at(self, indices):\n+ return np.zeros((len(indices), 2, 2, 3), dtype=np.uint8)\n+\n+\n+def _video_defaults(processor, **server_video_config):\n+ return {**glm_processor_video_config(processor), **server_video_config}\n+\n+\n+def _merge_one(defaults, request):\n+ return _merge_glm_video_configs(defaults, [request])[0]\n+\n+\n+def test_glm_video_merge_does_not_inject_omitted_max_frames():\n+ \"\"\"Any max_frames bypasses the HF sampler, so an fps-only request must not gain one.\"\"\"\n+ defaults = _video_defaults(_Glm4vLikeVideoProcessor())\n+ assert _merge_one(defaults, {}) == defaults\n+ assert \"max_frames\" not in _merge_one(defaults, {\"fps\": 1})\n+\n+\n+@pytest.mark.parametrize(\n+ \"server, request_config, key, expected\",\n+ [\n+ ({}, {\"fps\": 60}, \"fps\", 2.0),\n+ ({}, {\"max_frames\": 1_000_000}, \"max_frames\", 2048),\n+ ({}, {\"max_frames\": 10**400}, \"max_frames\", 2048),\n+ ({}, {\"max_image_tokens\": 10**9}, \"max_image_tokens\", 16384),\n+ ({\"max_frames\": 4096}, {\"max_frames\": 10**6}, \"max_frames\", 4096),\n+ (\n+ {\"max_tokens_per_frame\": 512},\n+ {\"max_tokens_per_frame\": 10**6},\n+ \"max_tokens_per_frame\",\n+ 512,\n+ ),\n+ ],\n+)\n+def test_glm_video_merge_clamps_request_to_deployment_limit(\n+ server, request_config, key, expected\n+):\n+ defaults = _video_defaults(_Glm5NextLikeVideoProcessor(), **server)\n+ assert _merge_one(defaults, request_config)[key] == expected\n+\n+\n+def test_glm_video_merge_keeps_tighter_request():\n+ defaults = _video_defaults(_Glm5NextLikeVideoProcessor())\n+ request = {\n+ \"fps\": 1,\n+ \"max_frames\": 8,\n+ \"max_image_tokens\": 1000,\n+ \"max_tokens_per_frame\": 100,\n+ }\n+ merged = _merge_one(defaults, request)\n+ assert {key: merged[key] for key in request} == request\n+\n+\n+@pytest.mark.parametrize(\"server\", [{}, {\"fps\": 3}])\n+def test_glm4v_request_cannot_sample_more_frames_than_default(server):\n+ \"\"\"A request max_frames switches to the fallback sampler; it must not exceed the HF default count.\"\"\"\n+ processor = _Glm4vLikeVideoProcessor()\n+ defaults = _video_defaults(processor, **server)\n+ video = _FakeVideoReader(seconds=3600)\n+\n+ def frame_count(request):\n+ frames, _ = glm_sample_and_decode_sync(\n+ video, _merge_one(defaults, request), processor\n+ )\n+ return len(frames)\n+\n+ default_count = frame_count({})\n+ assert frame_count({\"fps\": 60, \"max_frames\": 1_000_000}) <= default_count\n+\n+\n+def _patch_glm_resizers(monkeypatch):\n+ monkeypatch.setattr(\n+ glm4v_module,\n+ \"_resize_frames_to_max_tokens\",\n+ lambda frames, max_tokens_per_frame: (\"per_frame\", max_tokens_per_frame),\n+ )\n+ monkeypatch.setattr(\n+ glm4v_module,\n+ \"_pre_resize_frames_for_processor\",\n+ lambda frames, **budget: (\"presize\",),\n+ )\n+\n+\n+def test_glm_decode_drops_request_per_frame_cap_over_pixel_budget(monkeypatch):\n+ \"\"\"A request per-frame cap is kept only while its total pixels fit the shared budget.\n+\n+ Per-frame resize counts 784 px per token and presize counts 1568, so 16384 tokens\n+ x 2 frames fits a 16384-token video budget exactly.\n+ \"\"\"\n+ _patch_glm_resizers(monkeypatch)\n+ defaults = _video_defaults(_Glm5NextLikeVideoProcessor())\n+ config = _merge_one(defaults, {\"max_tokens_per_frame\": 16384})\n+ video = _FakeVideoReader(seconds=1)\n+\n+ assert glm_decode_frames_at(video, [0, 1], config) == (\"per_frame\", 16384)\n+ assert glm_decode_frames_at(video, [0, 1, 2], config) == (\"presize\",)\n+ # A DP shard decides on the full clip length, not its own slice.\n+ assert glm_decode_frames_at(video, [0], config, budget_frame_count=3) == (\n+ \"presize\",\n+ )\n+\n+\n+def test_glm_decode_keeps_server_per_frame_mode(monkeypatch):\n+ _patch_glm_resizers(monkeypatch)\n+ defaults = _video_defaults(_Glm5NextLikeVideoProcessor(), max_tokens_per_frame=512)\n+ config = _merge_one(defaults, {\"max_tokens_per_frame\": 100})\n+ frames = glm_decode_frames_at(_FakeVideoReader(seconds=1), range(200), config)\n+ assert frames == (\"per_frame\", 100)\n+\n+\n+@pytest.mark.parametrize(\n+ \"request_config\",\n+ [\n+ {\"fps\": 0},\n+ {\"fps\": \"fast\"},\n+ {\"fps\": float(\"inf\")},\n+ {\"fps\": float(\"nan\")},\n+ {\"max_frames\": -1},\n+ {\"max_frames\": float(\"inf\")},\n+ ],\n+)\n+def test_glm_video_merge_rejects_invalid_knobs(request_config):\n+ (key,) = request_config\n+ with pytest.raises(ValueError, match=key):\n+ _merge_glm_video_configs({}, [request_config])\n+\n+\n+@pytest.mark.parametrize(\n+ \"field, value\",\n+ [(\"fps\", 0), (\"fps\", float(\"inf\")), (\"max_frames\", 0), (\"max_image_tokens\", -1)],\n+)\n+def test_video_url_rejects_non_positive_knobs(field, value):\n+ with pytest.raises(ValidationError):\n+ ChatCompletionMessageContentVideoURL(url=\"video.mp4\", **{field: value})\n+\n+\n if __name__ == \"__main__\":\n raise SystemExit(pytest.main([__file__, \"-v\"]))\n\n[1 documentation file diff(s) omitted]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: sgl-project/sglang\nPull request: [Fix] compressed-tensors: Serve NVFP4 W4A4 linears via FP4 Marlin when --fp4-gemm-backend marlin is set on SM100\nLabels: run-ci\nFiles changed (2): python/sglang/srt/layers/quantization/compressed_tensors/compressed_tensors.py, test/registered/unit/layers/quantization/test_compressed_tensors_fp4_schemes.py\n\n## Description (results removed)\n\n## Motivation\n\nFixes #43988.\n\nWith a compressed-tensors NVFP4 W4A4 checkpoint on SM100, `--fp4-gemm-backend marlin` crashes during CUDA-graph capture:\n\n```\nflashinfer.utils.BackendSupportedError: mm_fp4 does not support backend 'marlin' with capability 100\n```\n\n## Modifications\n\n- `compressed_tensors.py`: when `--fp4-gemm-backend marlin` is set, W4A4 NVFP4 dense linears take the existing weight-only Marlin path on SM100 too, the same way ModelOpt NVFP4 honors the flag. Without the flag, SM100 still uses the native W4A4 scheme.\n- The warning now names the reason for each case. For an explicit marlin request it also says that NVFP4 MoE layers follow `--moe-runner-backend` and stay W4A4.\n\n## Accuracy Tests\n[results removed]\n## Checklist\n\n---\n### CI States\n\nLatest PR Test (Base): :no_entry_sign: [Run #38746283111](https://github.com/sgl-project/sglang/actions/runs/38746283111)\nLatest PR Test (Extra): :x: [Run #38746283325](https://github.com/sgl-project/sglang/actions/runs/38746283325)\nLatest PR Test (AMD ROCm 10): :hourglass_flowing_sand: [Run #38746283033](https://github.com/sgl-project/sglang/actions/runs/38746283033)\n\n## Diff\n\n```diff\ndiff --git a/python/sglang/srt/layers/quantization/compressed_tensors/compressed_tensors.py b/python/sglang/srt/layers/quantization/compressed_tensors/compressed_tensors.py\nindex 9950075c4bc8..fbb155ec91e0 100644\n--- a/python/sglang/srt/layers/quantization/compressed_tensors/compressed_tensors.py\n+++ b/python/sglang/srt/layers/quantization/compressed_tensors/compressed_tensors.py\n@@ -67,6 +67,7 @@\n is_activation_quantization_format,\n should_ignore_layer,\n )\n+from sglang.srt.layers.quantization.fp4_utils import get_fp4_gemm_runner_backend\n from sglang.srt.layers.quantization.fp8 import Fp8LinearMethod\n from sglang.srt.layers.quantization.kv_cache import BaseKVCacheMethod\n from sglang.srt.layers.quantization.unquant import (\n@@ -757,15 +758,28 @@ def _get_scheme_from_parts(\n is_fp4a4_nvfp4_supported = self._check_scheme_supported(\n CompressedTensorsW4A4Fp4.get_min_capability(), error=False\n )\n- if is_fp4a4_nvfp4_supported:\n+ # FP4 Marlin is weight-only and FlashInfer mm_fp4 has no marlin\n+ # backend, so a marlin request takes the weight-only path on SM100 too.\n+ if (\n+ is_fp4a4_nvfp4_supported\n+ and not get_fp4_gemm_runner_backend().is_marlin()\n+ ):\n return CompressedTensorsW4A4Fp4()\n # note: input_global_scale will be present for w4a4 checkpoints;\n # it is dropped post loading and activations stay unquantized.\n- logger.warning_once(\n- \"NVFP4 w4a4 requires compute capability >= 10.0; serving \"\n- \"this checkpoint weight-only via FP4 Marlin instead. \"\n- \"Activation quantization is ignored.\"\n- )\n+ if is_fp4a4_nvfp4_supported:\n+ logger.warning_once(\n+ \"--fp4-gemm-backend marlin is weight-only; serving NVFP4 \"\n+ \"w4a4 dense linears weight-only via FP4 Marlin, so their \"\n+ \"activation quantization is ignored. MoE layers follow \"\n+ \"--moe-runner-backend and stay w4a4.\"\n+ )\n+ else:\n+ logger.warning_once(\n+ \"NVFP4 w4a4 requires compute capability >= 10.0; serving \"\n+ \"this checkpoint weight-only via FP4 Marlin instead. \"\n+ \"Activation quantization is ignored.\"\n+ )\n return CompressedTensorsW4A16Fp4(has_input_global_scale=True)\n \n # Activation-quantized float4 that is not the nvfp4 layout: the\ndiff --git a/test/registered/unit/layers/quantization/test_compressed_tensors_fp4_schemes.py b/test/registered/unit/layers/quantization/test_compressed_tensors_fp4_schemes.py\nindex e88102d52cbe..9417db3db52f 100644\n--- a/test/registered/unit/layers/quantization/test_compressed_tensors_fp4_schemes.py\n+++ b/test/registered/unit/layers/quantization/test_compressed_tensors_fp4_schemes.py\n@@ -158,6 +158,29 @@ def test_weight_only_downgrade_warns_and_a16_does_not(self):\n _get_scheme(\"linear\", _make_config(a16), SM90)\n warn.assert_not_called()\n \n+ def test_marlin_backend_serves_w4a4_weight_only_on_blackwell(self):\n+ \"\"\"FlashInfer mm_fp4 has no marlin backend, so --fp4-gemm-backend marlin\n+ must not select the native w4a4 linear on SM100. The MoE follows\n+ --moe-runner-backend instead, which the warning has to say.\"\"\"\n+ from sglang.srt.layers.quantization import fp4_utils\n+\n+ logging.Logger.warning_once.cache_clear()\n+ self.addCleanup(logging.Logger.warning_once.cache_clear)\n+ with (\n+ mock.patch.object(\n+ fp4_utils, \"FP4_GEMM_RUNNER_BACKEND\", Fp4GemmRunnerBackend.MARLIN\n+ ),\n+ self.assertLogs(SCHEME_LOGGER, level=\"WARNING\") as captured,\n+ ):\n+ linear = _get_scheme(\"linear\", _make_config(\"nvfp4\"), SM100)\n+ moe = _get_scheme(\"moe\", _make_config(\"nvfp4\"), SM100)\n+ self.assertIsInstance(linear, CompressedTensorsW4A16Fp4)\n+ self.assertTrue(linear.has_input_global_scale)\n+ self.assertIsInstance(moe, CompressedTensorsW4A4Nvfp4MoE)\n+ output = \"\\n\".join(captured.output)\n+ self.assertIn(\"marlin is weight-only\", output)\n+ self.assertIn(\"MoE layers follow --moe-runner-backend\", output)\n+\n def test_fp4_weights_with_non_nvfp4_activations_raise(self):\n \"\"\"Mismatched activation quantization must not be served weight-only.\"\"\"\n config = _make_config(\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: sgl-project/sglang\nPull request: [Fix] function_call: Normalize GLM non-streaming tool names\nLabels: run-ci\nFiles changed (4): python/sglang/srt/function_call/glm47_moe_detector.py, python/sglang/srt/function_call/glm4_moe_detector.py, test/registered/unit/function_call/test_function_call_parser.py, test/registered/unit/function_call/test_glm47_schema_types.py\n\n## Description (results removed)\n\n## Motivation\n\nFixes #45953.\n\nGLM non-streaming tool-call parsing can silently drop a defined tool when the captured function name contains surrounding whitespace. A GLM-4.7/5 response such as `get_weather` followed by a newline and its argument tags is rejected as an unknown function; both `tool_calls` and visible content can be empty. GLM-4.5/4.6 has the same inconsistency for names with leading/trailing spaces, tabs, or CRLF headers. Both streaming paths already normalize function names.\n\nThis PR consolidates the GLM-4.7/5 fix from #45962 with the independently reproduced GLM-4.5/4.6 fix.\n\n## Modifications\n\n- Strip surrounding whitespace from function names in both `Glm4MoeDetector` and `Glm47MoeDetector` before argument-schema lookup and tool validation.\n\n## Attribution\n\n## Accuracy Tests\n[results removed]\n## Checklist\n\n- [x] Check formatting and relevant static checks on the changed files.\n- [x] Preserve authorship and credit the source contribution.\n- Documentation: no public API or documented format changes.\n- End-to-end accuracy/performance benchmarks: not run; this PR is limited to the demonstrated parser defects.\n\n---\n### CI States\n\nLatest PR Test (Base): :white_check_mark: [Run #42144417064](https://github.com/sgl-project/sglang/actions/runs/42144417064)\nLatest PR Test (Extra): :x: [Run #42144417407](https://github.com/sgl-project/sglang/actions/runs/42144417407)\nLatest PR Test (AMD ROCm 10): :hourglass_flowing_sand: [Run #42144417225](https://github.com/sgl-project/sglang/actions/runs/42144417225)\n\n> [!TIP]\n>\n> ```text\n> ```\n\n## Diff\n\n```diff\ndiff --git a/python/sglang/srt/function_call/glm47_moe_detector.py b/python/sglang/srt/function_call/glm47_moe_detector.py\nindex d928c8423c10..fdabb24a92e6 100644\n--- a/python/sglang/srt/function_call/glm47_moe_detector.py\n+++ b/python/sglang/srt/function_call/glm47_moe_detector.py\n@@ -392,7 +392,7 @@ def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult\n func_detail = self.func_detail_regex.search(match_result)\n if func_detail is None:\n continue\n- func_name = func_detail.group(1) if func_detail.group(1) else \"\"\n+ func_name = func_detail.group(1).strip() if func_detail.group(1) else \"\"\n func_args = func_detail.group(2) if func_detail.group(2) else \"\"\n arguments = {}\n if func_args:\ndiff --git a/python/sglang/srt/function_call/glm4_moe_detector.py b/python/sglang/srt/function_call/glm4_moe_detector.py\nindex ee2efd4aae66..b4eaa3ddc971 100644\n--- a/python/sglang/srt/function_call/glm4_moe_detector.py\n+++ b/python/sglang/srt/function_call/glm4_moe_detector.py\n@@ -247,7 +247,7 @@ def detect_and_parse(self, text: str, tools: List[Tool]) -> StreamingParseResult\n func_detail = self.func_detail_regex.search(match_result)\n if func_detail is None:\n continue\n- func_name = func_detail.group(1) if func_detail.group(1) else \"\"\n+ func_name = (func_detail.group(1) or \"\").strip()\n func_args = func_detail.group(2) if func_detail.group(2) else \"\"\n pairs = self.func_arg_regex.findall(func_args)\n \ndiff --git a/test/registered/unit/function_call/test_function_call_parser.py b/test/registered/unit/function_call/test_function_call_parser.py\nindex 7501ad3ac4af..015e827cdc0b 100644\n--- a/test/registered/unit/function_call/test_function_call_parser.py\n+++ b/test/registered/unit/function_call/test_function_call_parser.py\n@@ -2911,7 +2911,7 @@ def test_get_model_structural_tag(self):\n self.assertIsInstance(grammar, xgr.Grammar)\n \n \n-class TestGlm4MoeDetector(unittest.TestCase):\n+class TestGlm4MoeDetector(CustomTestCase):\n def setUp(self):\n self.tools = [\n Tool(\n@@ -2932,6 +2932,34 @@ def setUp(self):\n ]\n self.detector = Glm4MoeDetector()\n \n+ def test_nonstreaming_function_name_whitespace(self):\n+ \"\"\"Whitespace around a defined name must not silently drop the call.\"\"\"\n+ for name in (\n+ \"get_weather\",\n+ \" get_weather\",\n+ \"get_weather \",\n+ \"get_weather\\t\",\n+ \"get_weather\\r\",\n+ \"\\tget_weather \\t\",\n+ ):\n+ for separator in (\"\\n\", r\"\\n\"):\n+ with self.subTest(name=name, separator=separator):\n+ text = (\n+ f\"{name}{separator}\"\n+ \"city\\n Beijing \\n\"\n+ \"date\\n2024-06-27\\n\"\n+ \"\"\n+ )\n+ result = self.detector.detect_and_parse(text, self.tools)\n+ self.assertEqual(result.normal_text, \"\")\n+ self.assertEqual(len(result.calls), 1)\n+ self.assertEqual(result.calls[0].tool_index, 0)\n+ self.assertEqual(result.calls[0].name, \"get_weather\")\n+ self.assertEqual(\n+ json.loads(result.calls[0].parameters),\n+ {\"city\": \" Beijing \", \"date\": \"2024-06-27\"},\n+ )\n+\n def test_multiple_tool_calls(self):\n text = (\n \"get_weather\\n\"\ndiff --git a/test/registered/unit/function_call/test_glm47_schema_types.py b/test/registered/unit/function_call/test_glm47_schema_types.py\nindex 264b9f1b00d5..365e3ed7586f 100644\n--- a/test/registered/unit/function_call/test_glm47_schema_types.py\n+++ b/test/registered/unit/function_call/test_glm47_schema_types.py\n@@ -4,12 +4,13 @@\n from sglang.srt.entrypoints.openai.protocol import Function, Tool\n from sglang.srt.function_call.glm47_moe_detector import Glm47MoeDetector\n from sglang.test.ci.ci_register import register_cpu_ci\n+from sglang.test.test_utils import CustomTestCase\n \n register_cpu_ci(est_time=6, suite=\"base-a-test-cpu\")\n \n \n-class TestGlm47SchemaTypes(unittest.TestCase):\n- def check_arguments(self, schema, expected, raw_values=None):\n+class TestGlm47SchemaTypes(CustomTestCase):\n+ def check_arguments(self, schema, expected, raw_values=None, name=\"inspect\"):\n tools = [\n Tool(type=\"function\", function=Function(name=\"inspect\", parameters=schema))\n ]\n@@ -19,7 +20,12 @@ def check_arguments(self, schema, expected, raw_values=None):\n key, value if isinstance(value, str) else json.dumps(value)\n )\n pairs.append(f\"{key}{raw}\")\n- text = \"inspect\" + \"\".join(pairs) + \"\"\n+ text = (\n+ Glm47MoeDetector().bot_token\n+ + name\n+ + \"\".join(pairs)\n+ + Glm47MoeDetector().eot_token\n+ )\n for size in (0, 1, 7, len(text)):\n with self.subTest(schema=schema, expected=expected, chunk_size=size):\n detector = Glm47MoeDetector()\n@@ -38,6 +44,20 @@ def check_arguments(self, schema, expected, raw_values=None):\n for key in expected:\n self.assertIs(type(actual[key]), type(expected[key]))\n \n+ def test_function_name_followed_by_newline(self):\n+ \"\"\"The non-streaming path strips the function name like streaming.\n+\n+ Regression for issue #45953: with the name left unstripped, a model\n+ writing a newline after the name made parse_base_json reject the call\n+ as an undefined tool and silently drop it (no tool_calls, empty\n+ content), while the streaming path accepted the same output.\n+ \"\"\"\n+ self.check_arguments(\n+ {\"properties\": {\"value\": {\"type\": \"string\"}}},\n+ {\"value\": \"Paris\"},\n+ name=\"inspect\\n\",\n+ )\n+\n def test_field_types(self):\n cases = [\n ({\"type\": [\"integer\", \"string\"]}, \"auto\"),\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/speculators\nPull request: Add unit tests, type annotations, and docstrings for train utilities (fixes #1092)\nLabels: ready\nFiles changed (2): src/speculators/train/vocab_mapping.py, tests/unit/train/test_vocab_mapping.py\n\n## Description (results removed)\n\n## Purpose\nFixes #1092 (vocab_mapping part). Adds missing unit tests, type annotations, and docstrings for `speculators.train.vocab_mapping`, plus small discrepancies found along the way:\n- `save_token_frequency_distribution()` now returns the saved `Path`, matching its docstring (previously returned `None`).\n- `__all__` in `vocab_mapping.py` now exports all four public functions.\n- `combine_token_frequency_distributions()`: fixed `Counter[str]` → `Counter[int]` typing.\n- `get_target_vocab_size()` gains type hints and a docstring; Optional args are narrowed directly so mypy can verify them.\nNote: `__all__` entries are sorted to satisfy the repo's RUF022 lint rule (slightly different order than suggested in the issue).\nNote: the `noise_transforms.py` part of the original scope was dropped on rebase — upstream #1211 removed noise transforms entirely (\"seen to not have an impact on training quality, while significantly slowing down data loading\").\n\n## Tests\n[results removed]\n## Checklist\n- [x] (Optional) The necessary documentation update. — docstrings added/updated in the touched module; no separate docs pages needed.\n\n## Diff\n\n```diff\ndiff --git a/src/speculators/train/vocab_mapping.py b/src/speculators/train/vocab_mapping.py\nindex ac1e5a302..11c82cc8c 100644\n--- a/src/speculators/train/vocab_mapping.py\n+++ b/src/speculators/train/vocab_mapping.py\n@@ -13,6 +13,8 @@\n \n __all__ = [\n \"build_vocab_mappings_from_distribution\",\n+ \"combine_token_frequency_distributions\",\n+ \"get_target_vocab_size\",\n \"save_token_frequency_distribution\",\n ]\n \n@@ -20,7 +22,7 @@\n def save_token_frequency_distribution(\n dataset: HFDataset,\n output_path: Path | str = \"./token_freq.pt\",\n-):\n+) -> Path:\n \"\"\"Save token frequency distribution from the dataset.\n \n Args:\n@@ -39,7 +41,7 @@ def save_token_frequency_distribution(\n \"it (or pass a different output path) when the dataset or target \"\n \"model changed.\"\n )\n- return\n+ return path\n \n token_freq: Counter[int] = Counter()\n for item in tqdm(dataset, desc=\"Counting token frequencies\"):\n@@ -54,6 +56,7 @@ def save_token_frequency_distribution(\n token_freq_dict = dict(token_freq)\n Path(path).parent.mkdir(parents=True, exist_ok=True)\n torch.save(token_freq_dict, path)\n+ return path\n \n \n def combine_token_frequency_distributions(\n@@ -64,7 +67,7 @@ def combine_token_frequency_distributions(\n token_freq_dicts = [\n torch.load(path, weights_only=True) for path in token_freq_paths\n ]\n- combined_token_freq: Counter[str] = Counter()\n+ combined_token_freq: Counter[int] = Counter()\n for token_freq_dict in token_freq_dicts:\n combined_token_freq.update(token_freq_dict)\n combined_token_freq_dict = dict(combined_token_freq)\n@@ -107,10 +110,26 @@ def build_vocab_mappings_from_distribution(\n \n \n def get_target_vocab_size(\n- target_vocab_size,\n- target_model_path,\n+ target_vocab_size: int | None,\n+ target_model_path: str | Path | None,\n trust_remote_code: bool = False,\n-):\n+) -> int:\n+ \"\"\"Resolve the target vocabulary size.\n+\n+ Args:\n+ target_vocab_size: Explicitly configured target vocabulary size, if any.\n+ target_model_path: HuggingFace model path to read the vocabulary size\n+ from when ``target_vocab_size`` is not given.\n+ trust_remote_code: Whether to trust remote code when loading the model\n+ config.\n+\n+ Returns:\n+ The resolved target vocabulary size.\n+\n+ Raises:\n+ ValueError: If both or neither of ``target_vocab_size`` and\n+ ``target_model_path`` are provided.\n+ \"\"\"\n has_vocab = target_vocab_size is not None\n has_model = target_model_path is not None\n \n@@ -120,9 +139,14 @@ def get_target_vocab_size(\n if not has_vocab and not has_model:\n raise ValueError(\"Must specify either target-vocab-size or target-model-path\")\n \n- if has_vocab:\n+ if target_vocab_size is not None:\n return target_vocab_size\n \n+ if target_model_path is None:\n+ # Unreachable: validated above, but needed for mypy narrowing since\n+ # it cannot narrow through the has_model boolean.\n+ raise ValueError(\"Must specify either target-vocab-size or target-model-path\")\n+\n config = AutoConfig.from_pretrained(\n target_model_path,\n trust_remote_code=trust_remote_code,\ndiff --git a/tests/unit/train/test_vocab_mapping.py b/tests/unit/train/test_vocab_mapping.py\nnew file mode 100644\nindex 000000000..56e5737eb\n--- /dev/null\n+++ b/tests/unit/train/test_vocab_mapping.py\n@@ -0,0 +1,103 @@\n+\"\"\"Tests for speculators.train.vocab_mapping.\"\"\"\n+\n+import torch\n+\n+from speculators.train.vocab_mapping import (\n+ build_vocab_mappings_from_distribution,\n+ combine_token_frequency_distributions,\n+ save_token_frequency_distribution,\n+)\n+\n+\n+class _FakeDataset:\n+ \"\"\"Minimal iterable stub exposing input_ids/loss_mask items.\"\"\"\n+\n+ def __init__(self, items):\n+ self._items = items\n+\n+ def __iter__(self):\n+ return iter(self._items)\n+\n+\n+def test_build_vocab_mappings_ranks_by_frequency():\n+ token_freq = {5: 10, 3: 20, 7: 5}\n+\n+ draft_to_target, target_to_draft = build_vocab_mappings_from_distribution(\n+ token_freq, draft_vocab_size=2, target_vocab_size=10\n+ )\n+\n+ # top-2 by frequency are tokens 3 and 5; offsets encode\n+ # target_id = draft_idx + draft_to_target[draft_idx]\n+ assert draft_to_target.tolist() == [3, 4]\n+ for draft_idx, offset in enumerate(draft_to_target.tolist()):\n+ assert draft_idx + offset in (3, 5)\n+ assert target_to_draft.dtype == torch.bool\n+ assert target_to_draft.tolist() == [\n+ False,\n+ False,\n+ False,\n+ True,\n+ False,\n+ True,\n+ False,\n+ False,\n+ False,\n+ False,\n+ ]\n+\n+\n+def test_build_vocab_mappings_pads_with_smallest_missing_ids():\n+ token_freq = {2: 5}\n+\n+ draft_to_target, target_to_draft = build_vocab_mappings_from_distribution(\n+ token_freq, draft_vocab_size=4, target_vocab_size=8\n+ )\n+\n+ # only token 2 observed: pad with 0, 1, 3 -> sorted [0, 1, 2, 3]\n+ assert draft_to_target.tolist() == [0, 0, 0, 0]\n+ for draft_idx, offset in enumerate(draft_to_target.tolist()):\n+ assert draft_idx + offset in (0, 1, 2, 3)\n+ assert target_to_draft.sum().item() == 4\n+\n+\n+def test_combine_token_frequency_distributions(tmp_path):\n+ first = tmp_path / \"freq1.pt\"\n+ second = tmp_path / \"freq2.pt\"\n+ out = tmp_path / \"combined.pt\"\n+ torch.save({1: 2, 2: 3}, first)\n+ torch.save({2: 4, 3: 5}, second)\n+\n+ combine_token_frequency_distributions([first, second], out)\n+\n+ assert torch.load(out, weights_only=True) == {1: 2, 2: 7, 3: 5}\n+\n+\n+def test_save_token_frequency_distribution_returns_path(tmp_path):\n+ dataset = _FakeDataset(\n+ [\n+ {\n+ \"input_ids\": torch.tensor([1, 2, 2, 3]),\n+ \"loss_mask\": torch.tensor([1, 1, 0, 1]),\n+ },\n+ {\n+ \"input_ids\": torch.tensor([2, 3, 3]),\n+ \"loss_mask\": torch.tensor([0, 1, 1]),\n+ },\n+ ]\n+ )\n+ out = tmp_path / \"freq.pt\"\n+\n+ result = save_token_frequency_distribution(dataset, out)\n+\n+ assert result == out\n+ assert torch.load(out, weights_only=True) == {1: 1, 2: 1, 3: 3}\n+\n+\n+def test_save_token_frequency_distribution_reuses_existing_file(tmp_path):\n+ out = tmp_path / \"freq.pt\"\n+ torch.save({9: 9}, out)\n+\n+ result = save_token_frequency_distribution(_FakeDataset([]), out)\n+\n+ assert result == out\n+ assert torch.load(out, weights_only=True) == {9: 9}\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/speculators\nPull request: fix(data): don't store the messages column for text-only prepare-data\nLabels: ready\nFiles changed (4): src/speculators/data_generation/preprocessing.py, src/speculators/data_generation/vllm_client.py, src/speculators/train/data.py, tests/integration/datagen/test_render_boundary.py\n\n## Description (results removed)\n\n## Purpose\n\nPreprocessing now records per row whether the conversation is multimodal, and after `map` drops `messages` when no row is. Multimodal datasets keep the column as before. When several sources are combined, the decision is made per source; `build_client_item` treats the resulting `None` messages as text-only. `has_multimodal_content` now counts only non-text parts, so text-only part lists (`[{\"type\": \"text\", ...}]`) also drop the column.\n\n## Tests\n[results removed]\n## Checklist\n\nI have filled in:\n\n---\n[image] [image]\nNeed help on this PR? Tag @codesmith-bot with what you need.\n\n## Diff\n\n```diff\ndiff --git a/src/speculators/data_generation/preprocessing.py b/src/speculators/data_generation/preprocessing.py\nindex 677868d02..868f8cef2 100644\n--- a/src/speculators/data_generation/preprocessing.py\n+++ b/src/speculators/data_generation/preprocessing.py\n@@ -17,6 +17,7 @@\n from speculators.data_generation.logging_utils import PipelineLogger\n from speculators.data_generation.render_client import render_conversation\n from speculators.data_generation.torch_utils import set_default_torch_num_threads\n+from speculators.data_generation.vllm_client import has_multimodal_content\n from speculators.train.vocab_mapping import save_token_frequency_distribution\n \n __all__ = [\n@@ -430,7 +431,9 @@ def _append_boundary_rows(\n if status == \"kept\":\n num_kept += 1\n if \"messages\" in results:\n- results[\"messages\"].append(_adapt_conv_for_vllm(row[\"conv\"]))\n+ messages = _adapt_conv_for_vllm(row[\"conv\"])\n+ results[\"messages\"].append(messages)\n+ results[\"is_multimodal\"].append(has_multimodal_content(messages))\n \n return num_kept, num_unsupervised, num_maybe_truncated\n \n@@ -510,6 +513,7 @@ def _preprocess_batch(\n # original messages -- token ids alone cannot carry the images.\n if is_multimodal:\n results[\"messages\"] = []\n+ results[\"is_multimodal\"] = []\n \n if not conversations:\n log.warning(f\"No conversations key found. Keys: {list(examples.keys())}\")\n@@ -637,10 +641,28 @@ def build_speculator_training_dataset(\n keep_in_memory=True, # skip caching\n )\n \n+ dataset = _drop_unused_messages(dataset)\n dataset.set_format(type=\"torch\")\n return dataset\n \n \n+def _drop_unused_messages(dataset: HFDataset) -> HFDataset:\n+ \"\"\"Drop the ``messages`` column when no row is multimodal.\n+\n+ Processor-based models write ``messages`` for every row, but the trainer\n+ only forwards it for multimodal rows, so a text-only dataset would store\n+ the full conversation text unused. Decided after ``map`` rather than per\n+ batch so every map shard keeps the same schema.\n+ \"\"\"\n+ if \"is_multimodal\" not in dataset.column_names:\n+ return dataset\n+ drop = [\"is_multimodal\"]\n+ if not any(dataset[\"is_multimodal\"]):\n+ log.info(\"No multimodal rows: not storing the messages column\")\n+ drop.append(\"messages\")\n+ return dataset.remove_columns(drop)\n+\n+\n def _load_hf_dataset(spec: str) -> tuple[HFDataset, None]:\n \"\"\"Load an arbitrary HuggingFace dataset from an ``hf:`` spec.\n \ndiff --git a/src/speculators/data_generation/vllm_client.py b/src/speculators/data_generation/vllm_client.py\nindex 12dc98c9d..5deb66cb0 100644\n--- a/src/speculators/data_generation/vllm_client.py\n+++ b/src/speculators/data_generation/vllm_client.py\n@@ -130,6 +130,20 @@ class ClientItem(TypedDict):\n instead of passing `token_ids` to Completions API.\"\"\"\n \n \n+def has_multimodal_content(messages: list[dict]) -> bool:\n+ \"\"\"True when any turn carries non-text content (images, video, audio).\n+\n+ Turns store ``content`` as a plain string or, after ``_adapt_conv_for_vllm``,\n+ as a list of typed parts, e.g. ``[{\"type\": \"text\", ...}, {\"type\": \"image_url\",\n+ ...}]``. Only a part whose type is not ``text`` makes the turn multimodal.\n+ \"\"\"\n+ return any(\n+ isinstance(m.get(\"content\"), list)\n+ and any(part.get(\"type\") != \"text\" for part in m[\"content\"])\n+ for m in messages\n+ )\n+\n+\n async def _poll_lock_async(fd, poll_interval):\n while True:\n try:\ndiff --git a/src/speculators/train/data.py b/src/speculators/train/data.py\nindex 241e4d6a1..474537359 100644\n--- a/src/speculators/train/data.py\n+++ b/src/speculators/train/data.py\n@@ -17,6 +17,7 @@\n DEFAULT_REQUEST_TIMEOUT,\n ClientItem,\n generate_hidden_states,\n+ has_multimodal_content,\n )\n from speculators.train.recovery import (\n RECOVERY_METADATA_KEY,\n@@ -55,16 +56,6 @@ def create_empty_sample(\n }\n \n \n-def _has_multimodal_content(messages: list[dict]) -> bool:\n- \"\"\"True when any turn carries non-text content (images, video, audio).\n-\n- Text-only turns store ``content`` as a plain string. Multimodal turns\n- (produced by ``_adapt_conv_for_vllm``) store it as a list of typed parts,\n- e.g. ``[{\"type\": \"text\", ...}, {\"type\": \"image_url\", ...}]``.\n- \"\"\"\n- return any(isinstance(m.get(\"content\"), list) for m in messages)\n-\n-\n def build_client_item(dataset_item: dict) -> ClientItem:\n \"\"\"Build a request payload for vLLM hidden-state extraction.\n \n@@ -89,8 +80,10 @@ def build_client_item(dataset_item: dict) -> ClientItem:\n \"\"\"\n out_dict: dict = {\"input_ids\": dataset_item[\"input_ids\"].tolist()}\n \n- if \"messages\" in dataset_item and _has_multimodal_content(dataset_item[\"messages\"]):\n- out_dict[\"messages\"] = dataset_item[\"messages\"]\n+ # A text-only source concatenated with a multimodal one has None messages.\n+ messages = dataset_item.get(\"messages\")\n+ if messages is not None and has_multimodal_content(messages):\n+ out_dict[\"messages\"] = messages\n \n return cast(\"ClientItem\", out_dict)\n \ndiff --git a/tests/integration/datagen/test_render_boundary.py b/tests/integration/datagen/test_render_boundary.py\nindex e4b2b3d15..ab210c8cb 100644\n--- a/tests/integration/datagen/test_render_boundary.py\n+++ b/tests/integration/datagen/test_render_boundary.py\n@@ -13,7 +13,8 @@\n import pytest\n import torch\n from datasets import Dataset as HFDataset\n-from datasets import load_from_disk\n+from datasets import concatenate_datasets, load_from_disk\n+from transformers import ProcessorMixin\n \n from speculators.data_generation import preprocessing, render_client\n from speculators.data_generation.preprocessing import (\n@@ -21,7 +22,7 @@\n build_speculator_training_dataset,\n )\n from speculators.data_generation.vllm_client import InvalidResponseError\n-from speculators.train.data import CollateFn\n+from speculators.train.data import CollateFn, build_client_item\n \n # Neither build path below reads the processor: the missing-endpoint guard\n # raises before it is used, and speculator-format rows skip rendering entirely.\n@@ -337,3 +338,81 @@ def test_loss_mask_stays_boolean_after_save_load_and_collation(tmp_path, mask):\n )\n assert batch[\"loss_mask\"].dtype == torch.bool\n assert batch[\"loss_mask\"].tolist() == [[False, False, True, True, False, False]]\n+\n+\n+class _ProcessorMixinStub(ProcessorMixin):\n+ \"\"\"Routes preprocessing down the multimodal path; never called.\"\"\"\n+\n+ def __init__(self):\n+ pass\n+\n+\n+def _build_with_processor(monkeypatch, conversations: list[list[dict]]) -> HFDataset:\n+ # One row per conversation; the conv itself is what `messages` would store.\n+ monkeypatch.setattr(\n+ preprocessing,\n+ \"_render_conversation_rows\",\n+ lambda conv, *a, **k: [\n+ {\"input_ids\": [1, 2, 3], \"loss_mask\": [0, 1, 1], \"conv\": conv}\n+ ],\n+ )\n+ return build_speculator_training_dataset(\n+ HFDataset.from_dict({\"conversations\": conversations}),\n+ cast(\"ProcessorLike\", _ProcessorMixinStub()),\n+ num_proc=1,\n+ render_endpoint=\"http://x\",\n+ )\n+\n+\n+def test_processor_text_only_rows_do_not_store_messages(monkeypatch):\n+ # The trainer only forwards `messages` for multimodal rows, so a text-only\n+ # prep through a processor-based model should not keep the column.\n+ dataset = _build_with_processor(monkeypatch, [_conv(2), _conv(2)])\n+ assert len(dataset) == 2\n+ assert \"messages\" not in dataset.column_names\n+ assert \"is_multimodal\" not in dataset.column_names\n+\n+\n+def test_processor_multimodal_rows_keep_messages(monkeypatch):\n+ image = {\"type\": \"image\", \"url\": \"http://x/a.png\", \"text\": None}\n+ text = {\"type\": \"text\", \"url\": None, \"text\": \"what is this?\"}\n+ conv = [\n+ {\"role\": \"user\", \"content\": [image, text]},\n+ {\"role\": \"assistant\", \"content\": [{**text, \"text\": \"a cat\"}]},\n+ ]\n+ dataset = _build_with_processor(monkeypatch, [conv])\n+ assert \"is_multimodal\" not in dataset.column_names\n+ user_parts = dataset[0][\"messages\"][0][\"content\"]\n+ assert user_parts[0][\"image_url\"] == {\"url\": \"http://x/a.png\"}\n+ assert build_client_item(dataset[0])[\"messages\"] == dataset[0][\"messages\"]\n+\n+\n+def test_processor_text_part_lists_do_not_store_messages(monkeypatch):\n+ # Content given as a list of text parts carries no media either.\n+ conv = [\n+ {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"hi\"}]},\n+ {\"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"hello\"}]},\n+ ]\n+ dataset = _build_with_processor(monkeypatch, [conv])\n+ assert \"messages\" not in dataset.column_names\n+\n+\n+def test_mixed_text_and_multimodal_sources_build_client_items(monkeypatch):\n+ # Concatenating a text-only source with a multimodal one fills the\n+ # text-only rows' `messages` with None; those rows must still send ids.\n+ image = {\"type\": \"image\", \"url\": \"http://x/a.png\", \"text\": None}\n+ text = {\"type\": \"text\", \"url\": None, \"text\": \"what is this?\"}\n+ conv = [\n+ {\"role\": \"user\", \"content\": [image, text]},\n+ {\"role\": \"assistant\", \"content\": [{**text, \"text\": \"a cat\"}]},\n+ ]\n+ dataset = concatenate_datasets(\n+ [\n+ _build_with_processor(monkeypatch, [_conv(2)]),\n+ _build_with_processor(monkeypatch, [conv]),\n+ ]\n+ )\n+ dataset.set_format(type=\"torch\")\n+ text_item, mm_item = (build_client_item(dataset[i]) for i in range(2))\n+ assert \"messages\" not in text_item\n+ assert mm_item[\"messages\"] == dataset[1][\"messages\"]\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/speculators\nPull request: fix(data): don't store the messages column for text-only prepare-data\nLabels: ready\nFiles changed (4): src/speculators/data_generation/preprocessing.py, src/speculators/data_generation/vllm_client.py, src/speculators/train/data.py, tests/integration/datagen/test_render_boundary.py\n\n## Description (results removed)\n\n## Purpose\n\nPreprocessing now records per row whether the conversation is multimodal, and after `map` drops `messages` when no row is. Multimodal datasets keep the column as before. When several sources are combined, the decision is made per source; `build_client_item` treats the resulting `None` messages as text-only. `has_multimodal_content` now counts only non-text parts, so text-only part lists (`[{\"type\": \"text\", ...}]`) also drop the column.\n\n## Tests\n[results removed]\n## Checklist\n\nI have filled in:\n\n---\n[image] [image]\nNeed help on this PR? Tag @codesmith-bot with what you need.\n\n## Diff\n\n```diff\ndiff --git a/src/speculators/data_generation/preprocessing.py b/src/speculators/data_generation/preprocessing.py\nindex 677868d..868f8ce 100644\n--- a/src/speculators/data_generation/preprocessing.py\n+++ b/src/speculators/data_generation/preprocessing.py\n@@ -17,6 +17,7 @@ from transformers import (\n from speculators.data_generation.logging_utils import PipelineLogger\n from speculators.data_generation.render_client import render_conversation\n from speculators.data_generation.torch_utils import set_default_torch_num_threads\n+from speculators.data_generation.vllm_client import has_multimodal_content\n from speculators.train.vocab_mapping import save_token_frequency_distribution\n \n __all__ = [\n@@ -430,7 +431,9 @@ def _append_boundary_rows(\n if status == \"kept\":\n num_kept += 1\n if \"messages\" in results:\n- results[\"messages\"].append(_adapt_conv_for_vllm(row[\"conv\"]))\n+ messages = _adapt_conv_for_vllm(row[\"conv\"])\n+ results[\"messages\"].append(messages)\n+ results[\"is_multimodal\"].append(has_multimodal_content(messages))\n \n return num_kept, num_unsupervised, num_maybe_truncated\n \n@@ -510,6 +513,7 @@ def _preprocess_batch(\n # original messages -- token ids alone cannot carry the images.\n if is_multimodal:\n results[\"messages\"] = []\n+ results[\"is_multimodal\"] = []\n \n if not conversations:\n log.warning(f\"No conversations key found. Keys: {list(examples.keys())}\")\n@@ -637,10 +641,28 @@ def build_speculator_training_dataset(\n keep_in_memory=True, # skip caching\n )\n \n+ dataset = _drop_unused_messages(dataset)\n dataset.set_format(type=\"torch\")\n return dataset\n \n \n+def _drop_unused_messages(dataset: HFDataset) -> HFDataset:\n+ \"\"\"Drop the ``messages`` column when no row is multimodal.\n+\n+ Processor-based models write ``messages`` for every row, but the trainer\n+ only forwards it for multimodal rows, so a text-only dataset would store\n+ the full conversation text unused. Decided after ``map`` rather than per\n+ batch so every map shard keeps the same schema.\n+ \"\"\"\n+ if \"is_multimodal\" not in dataset.column_names:\n+ return dataset\n+ drop = [\"is_multimodal\"]\n+ if not any(dataset[\"is_multimodal\"]):\n+ log.info(\"No multimodal rows: not storing the messages column\")\n+ drop.append(\"messages\")\n+ return dataset.remove_columns(drop)\n+\n+\n def _load_hf_dataset(spec: str) -> tuple[HFDataset, None]:\n \"\"\"Load an arbitrary HuggingFace dataset from an ``hf:`` spec.\n \ndiff --git a/src/speculators/data_generation/vllm_client.py b/src/speculators/data_generation/vllm_client.py\nindex 12dc98c..bcb418c 100644\n--- a/src/speculators/data_generation/vllm_client.py\n+++ b/src/speculators/data_generation/vllm_client.py\n@@ -130,6 +130,16 @@ class ClientItem(TypedDict):\n instead of passing `token_ids` to Completions API.\"\"\"\n \n \n+def has_multimodal_content(messages: list[dict]) -> bool:\n+ \"\"\"True when any turn carries non-text content (images, video, audio).\n+\n+ Text-only turns store ``content`` as a plain string. Multimodal turns\n+ (produced by ``_adapt_conv_for_vllm``) store it as a list of typed parts,\n+ e.g. ``[{\"type\": \"text\", ...}, {\"type\": \"image_url\", ...}]``.\n+ \"\"\"\n+ return any(isinstance(m.get(\"content\"), list) for m in messages)\n+\n+\n async def _poll_lock_async(fd, poll_interval):\n while True:\n try:\ndiff --git a/src/speculators/train/data.py b/src/speculators/train/data.py\nindex 241e4d6..379764b 100644\n--- a/src/speculators/train/data.py\n+++ b/src/speculators/train/data.py\n@@ -17,6 +17,7 @@ from speculators.data_generation.vllm_client import (\n DEFAULT_REQUEST_TIMEOUT,\n ClientItem,\n generate_hidden_states,\n+ has_multimodal_content,\n )\n from speculators.train.recovery import (\n RECOVERY_METADATA_KEY,\n@@ -55,16 +56,6 @@ def create_empty_sample(\n }\n \n \n-def _has_multimodal_content(messages: list[dict]) -> bool:\n- \"\"\"True when any turn carries non-text content (images, video, audio).\n-\n- Text-only turns store ``content`` as a plain string. Multimodal turns\n- (produced by ``_adapt_conv_for_vllm``) store it as a list of typed parts,\n- e.g. ``[{\"type\": \"text\", ...}, {\"type\": \"image_url\", ...}]``.\n- \"\"\"\n- return any(isinstance(m.get(\"content\"), list) for m in messages)\n-\n-\n def build_client_item(dataset_item: dict) -> ClientItem:\n \"\"\"Build a request payload for vLLM hidden-state extraction.\n \n@@ -89,7 +80,7 @@ def build_client_item(dataset_item: dict) -> ClientItem:\n \"\"\"\n out_dict: dict = {\"input_ids\": dataset_item[\"input_ids\"].tolist()}\n \n- if \"messages\" in dataset_item and _has_multimodal_content(dataset_item[\"messages\"]):\n+ if \"messages\" in dataset_item and has_multimodal_content(dataset_item[\"messages\"]):\n out_dict[\"messages\"] = dataset_item[\"messages\"]\n \n return cast(\"ClientItem\", out_dict)\ndiff --git a/tests/integration/datagen/test_render_boundary.py b/tests/integration/datagen/test_render_boundary.py\nindex e4b2b3d..673c232 100644\n--- a/tests/integration/datagen/test_render_boundary.py\n+++ b/tests/integration/datagen/test_render_boundary.py\n@@ -14,6 +14,7 @@ import pytest\n import torch\n from datasets import Dataset as HFDataset\n from datasets import load_from_disk\n+from transformers import ProcessorMixin\n \n from speculators.data_generation import preprocessing, render_client\n from speculators.data_generation.preprocessing import (\n@@ -21,7 +22,7 @@ from speculators.data_generation.preprocessing import (\n build_speculator_training_dataset,\n )\n from speculators.data_generation.vllm_client import InvalidResponseError\n-from speculators.train.data import CollateFn\n+from speculators.train.data import CollateFn, build_client_item\n \n # Neither build path below reads the processor: the missing-endpoint guard\n # raises before it is used, and speculator-format rows skip rendering entirely.\n@@ -337,3 +338,50 @@ def test_loss_mask_stays_boolean_after_save_load_and_collation(tmp_path, mask):\n )\n assert batch[\"loss_mask\"].dtype == torch.bool\n assert batch[\"loss_mask\"].tolist() == [[False, False, True, True, False, False]]\n+\n+\n+class _ProcessorMixinStub(ProcessorMixin):\n+ \"\"\"Routes preprocessing down the multimodal path; never called.\"\"\"\n+\n+ def __init__(self):\n+ pass\n+\n+\n+def _build_with_processor(monkeypatch, conversations: list[list[dict]]) -> HFDataset:\n+ # One row per conversation; the conv itself is what `messages` would store.\n+ monkeypatch.setattr(\n+ preprocessing,\n+ \"_render_conversation_rows\",\n+ lambda conv, *a, **k: [\n+ {\"input_ids\": [1, 2, 3], \"loss_mask\": [0, 1, 1], \"conv\": conv}\n+ ],\n+ )\n+ return build_speculator_training_dataset(\n+ HFDataset.from_dict({\"conversations\": conversations}),\n+ cast(\"ProcessorLike\", _ProcessorMixinStub()),\n+ num_proc=1,\n+ render_endpoint=\"http://x\",\n+ )\n+\n+\n+def test_processor_text_only_rows_do_not_store_messages(monkeypatch):\n+ # The trainer only forwards `messages` for multimodal rows, so a text-only\n+ # prep through a processor-based model should not keep the column.\n+ dataset = _build_with_processor(monkeypatch, [_conv(2), _conv(2)])\n+ assert len(dataset) == 2\n+ assert \"messages\" not in dataset.column_names\n+ assert \"is_multimodal\" not in dataset.column_names\n+\n+\n+def test_processor_multimodal_rows_keep_messages(monkeypatch):\n+ image = {\"type\": \"image\", \"url\": \"http://x/a.png\", \"text\": None}\n+ text = {\"type\": \"text\", \"url\": None, \"text\": \"what is this?\"}\n+ conv = [\n+ {\"role\": \"user\", \"content\": [image, text]},\n+ {\"role\": \"assistant\", \"content\": [{**text, \"text\": \"a cat\"}]},\n+ ]\n+ dataset = _build_with_processor(monkeypatch, [conv])\n+ assert \"is_multimodal\" not in dataset.column_names\n+ user_parts = dataset[0][\"messages\"][0][\"content\"]\n+ assert user_parts[0][\"image_url\"] == {\"url\": \"http://x/a.png\"}\n+ assert build_client_item(dataset[0])[\"messages\"] == dataset[0][\"messages\"]\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Spec Decode] DFlash/DSpark no longer drop the last prefix-cache block (mamba align context recompute)\nLabels: bug, ready, dflash, scheduler\nFiles changed (4): tests/test_config.py, tests/v1/core/test_scheduler.py, vllm/config/speculative.py, vllm/v1/core/sched/scheduler.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #53477. DFlash and DSpark preserve the target KV cache and do not require the EAGLE-style trailing prefix-cache block drop. Scoping that drop correctly restores reusable Mamba checkpoints in `--mamba-cache-mode align` and prevents full-context recomputation on subsequent replies.\n\n## Claims\n\n- DFlash/DSpark no longer drop the last prefix-cache block solely because `SpeculativeConfig.use_eagle()` also matches those methods.\n\n## Validation\n[results removed]\n## Details\n\n### Root cause\n\n`SpeculativeConfig.use_eagle()` is a broad predicate for speculative decoding that reads target hidden states, and it intentionally matches `eagle`, `eagle3`, `mtp`, `dflash`, and `dspark`. #53388 derived `use_eagle_block_drop()` from that broad predicate.\n\nEAGLE-style drafters construct a position's draft KV from the target hidden state **and the next token**. DFlash/DSpark construct it from the target hidden state alone. Therefore only EAGLE/EAGLE3/MTP need the trailing EAGLE block drop; both DFlash and DSpark preserve the target KV cache.\n\nFor a prompt shorter than two Mamba blocks, the spurious back-off produced this sequence:\n\n1. `last_cache_position == 0`, so the prompt was a single chunk ending off the Mamba block grid.\n2. Mamba align mode only materializes a reusable recurrent state at a block-aligned chunk end.\n3. `HybridKVCacheCoordinator.find_longest_cache_hit()` converged the next turn's hit to zero, causing full-context recomputation.\n\n### Implementation\n\n- `vllm/config/speculative.py`: add `needs_eagle_block_drop()` for the precise EAGLE/EAGLE3/MTP capability, and compose `use_eagle_block_drop()` from it plus `disable_eagle_block_drop`.\n- `vllm/v1/core/sched/scheduler.py`: reuse `needs_eagle_block_drop()` in the warning condition. The existing split back-off, `KVCacheManager(use_eagle=...)`, offloading, and Mooncake paths now receive `False` for DFlash/DSpark without changing `use_eagle()`.\n- `tests/test_config.py`: parameterize the existing config test over EAGLE3/MTP (drop) and DFlash/DSpark (no drop), both with the opt-out enabled and disabled.\n- `tests/v1/core/test_scheduler.py`: set the now-separate `use_eagle_block_drop` scheduler value in the Mamba-align EAGLE fixture.\n\nThe change is limited to the prefix-cache trailing-block policy. EAGLE/EAGLE3/MTP retain the previous default behavior, and the existing explicit opt-out remains available.\n\n### Related work and duplication\n\nNo open PR addresses #53477. Related work includes #53388 (merged opt-out for EAGLE trailing-block dropping), #30877 (Mamba align prefix caching), #42971, and #44082. None previously corrected the DFlash/DSpark classification.\n\n## Diff\n\n```diff\ndiff --git a/vllm/config/speculative.py b/vllm/config/speculative.py\nindex 630a8705cbf5..1f4a04ef0c12 100644\n--- a/vllm/config/speculative.py\n+++ b/vllm/config/speculative.py\n@@ -2052,6 +2052,15 @@ def use_eagle(self) -> bool:\n # TODO(ben): Refactor this so the naming is clearer\n return self.method in (\"eagle\", \"eagle3\", \"mtp\", \"dflash\", \"dspark\")\n \n+ def needs_eagle_block_drop(self) -> bool:\n+ \"\"\"Whether draft KV at a position depends on the next token.\n+\n+ EAGLE-style drafters build a position's draft KV from its hidden state\n+ and the next token. DFlash/DSpark build it from the target hidden state\n+ alone, so only EAGLE/EAGLE3/MTP require the trailing-block drop.\n+ \"\"\"\n+ return self.use_eagle() and not (self.use_dflash() or self.use_dspark())\n+\n def is_xpress(self) -> bool:\n \"\"\"Whether the dflash draft carries an XPress refiner.\n \n@@ -2069,8 +2078,8 @@ def is_xpress(self) -> bool:\n )\n \n def use_eagle_block_drop(self) -> bool:\n- \"\"\"Whether volatile trailing cache blocks should be discarded.\"\"\"\n- return self.use_eagle() and not self.disable_eagle_block_drop\n+ \"\"\"Whether the volatile trailing prefix-cache block should be dropped.\"\"\"\n+ return self.needs_eagle_block_drop() and not self.disable_eagle_block_drop\n \n def use_dflash(self) -> bool:\n return self.method == \"dflash\"\ndiff --git a/vllm/v1/core/sched/scheduler.py b/vllm/v1/core/sched/scheduler.py\nindex e277df75c8f4..844f29e01343 100644\n--- a/vllm/v1/core/sched/scheduler.py\n+++ b/vllm/v1/core/sched/scheduler.py\n@@ -321,7 +321,10 @@ def __init__(\n )\n self.use_eagle = speculative_config.use_eagle()\n self.use_eagle_block_drop = speculative_config.use_eagle_block_drop()\n- if self.use_eagle and not self.use_eagle_block_drop:\n+ if (\n+ speculative_config.needs_eagle_block_drop()\n+ and speculative_config.disable_eagle_block_drop\n+ ):\n logger.warning(\n \"EAGLE trailing prefix-cache block dropping is disabled. \"\n \"This is experimental and may affect speculative-token \"\n\ndiff --git a/tests/test_config.py b/tests/test_config.py\nindex 985af6284561..5334cbd2081f 100644\n--- a/tests/test_config.py\n+++ b/tests/test_config.py\n@@ -3587,8 +3587,14 @@ def test_draft_sample_method_probabilistic_is_accepted():\n assert speculative_config.draft_sample_method == \"probabilistic\"\n \n \n+@pytest.mark.parametrize(\n+ (\"method\", \"drops_block\"),\n+ [(\"eagle3\", True), (\"mtp\", True), (\"dflash\", False), (\"dspark\", False)],\n+)\n @pytest.mark.parametrize(\"disable_eagle_block_drop\", [False, True])\n def test_eagle_block_drop_can_be_disabled_without_disabling_eagle(\n+ method: str,\n+ drops_block: bool,\n disable_eagle_block_drop: bool,\n ):\n # Start from an ngram config to avoid loading model metadata: these predicates\n@@ -3598,10 +3604,12 @@ def test_eagle_block_drop_can_be_disabled_without_disabling_eagle(\n num_speculative_tokens=3,\n disable_eagle_block_drop=disable_eagle_block_drop,\n )\n- speculative_config.method = \"eagle3\"\n+ speculative_config.method = method\n \n assert speculative_config.use_eagle()\n- assert speculative_config.use_eagle_block_drop() is not disable_eagle_block_drop\n+ assert speculative_config.use_eagle_block_drop() is (\n+ drops_block and not disable_eagle_block_drop\n+ )\n \n \n def test_draft_sample_method_gumbel_is_rejected():\ndiff --git a/tests/v1/core/test_scheduler.py b/tests/v1/core/test_scheduler.py\nindex ef5f9c232e28..fe199d809ee5 100644\n--- a/tests/v1/core/test_scheduler.py\n+++ b/tests/v1/core/test_scheduler.py\n@@ -5075,6 +5075,7 @@ def test_mamba_align_eagle_schedules_encoder_at_boundary():\n )\n scheduler.need_mamba_block_aligned_split = True\n scheduler.use_eagle = True\n+ scheduler.use_eagle_block_drop = True\n scheduler.num_prefill_lookahead = 1\n scheduler.max_num_encoder_input_tokens = 2048\n scheduler.encoder_cache_manager = EncoderCacheManager(cache_size=2048)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Tool Calling] Tool parser non-streaming parse drops post-tool-call text that streaming returns\nLabels: bug, ready, tool-calling, deepseek\nFiles changed (2): tests/tool_parsers/test_deepseekv3_tool_parser.py, vllm/tool_parsers/deepseekv3_tool_parser.py\n\n## Description (results removed)\n\n## Purpose\n\nFixes https://github.com/vllm-project/vllm/issues/56263\n\nFor a model output that contains text before AND after a tool call, the two delivery modes disagree: streaming returns the post-tool text, non-streaming drops it. The tool parser is inconsistent with its own streaming mode.\n\n## Changes made\n\n## Test Plan\n[results removed]\n## Test Result\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/tool_parsers/deepseekv3_tool_parser.py b/vllm/tool_parsers/deepseekv3_tool_parser.py\nindex 649eded2878f..9e18bdcd899a 100644\n--- a/vllm/tool_parsers/deepseekv3_tool_parser.py\n+++ b/vllm/tool_parsers/deepseekv3_tool_parser.py\n@@ -109,7 +109,13 @@ def extract_tool_calls(\n )\n )\n \n- content = model_output[: model_output.find(self.tool_calls_start_token)]\n+ tool_calls_start = model_output.find(self.tool_calls_start_token)\n+ tool_calls_end = model_output.rfind(self.tool_calls_end_token)\n+ content = model_output[:tool_calls_start]\n+ if tool_calls_end != -1:\n+ content += model_output[\n+ tool_calls_end + len(self.tool_calls_end_token) :\n+ ]\n return ExtractedToolCallInformation(\n tools_called=True,\n tool_calls=tool_calls,\n\ndiff --git a/tests/tool_parsers/test_deepseekv3_tool_parser.py b/tests/tool_parsers/test_deepseekv3_tool_parser.py\nindex 27fbae0920bb..e0d2897e917e 100644\n--- a/tests/tool_parsers/test_deepseekv3_tool_parser.py\n+++ b/tests/tool_parsers/test_deepseekv3_tool_parser.py\n@@ -8,6 +8,7 @@\n ToolParserTestConfig,\n ToolParserTests,\n )\n+from tests.tool_parsers.utils import run_tool_extraction\n from vllm.tokenizers import TokenizerLike, get_tokenizer\n \n \n@@ -90,3 +91,31 @@ def test_config(self) -> ToolParserTestConfig:\n ),\n },\n )\n+\n+ @pytest.mark.parametrize(\"streaming\", [False, True])\n+ def test_preserves_text_after_tool_call(\n+ self,\n+ tool_parser,\n+ streaming: bool,\n+ ) -> None:\n+ model_output = (\n+ \"let me check the weather.\"\n+ \"<|tool▁calls▁begin|>\"\n+ \"<|tool▁call▁begin|>function<|tool▁sep|>get_weather\\n\"\n+ \"```json\\n\"\n+ '{\"city\": \"Paris\"}\\n'\n+ \"```<|tool▁call▁end|>\"\n+ \"<|tool▁calls▁end|>\"\n+ \"It is 30 degrees.\"\n+ )\n+\n+ content, tool_calls = run_tool_extraction(\n+ tool_parser,\n+ model_output,\n+ streaming=streaming,\n+ )\n+\n+ assert content == \"let me check the weather.It is 30 degrees.\"\n+ assert len(tool_calls) == 1\n+ assert tool_calls[0].function.name == \"get_weather\"\n+ assert tool_calls[0].function.arguments == '{\"city\": \"Paris\"}'\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] [Frontend] Preserve prompt_logprobs in /v1/completions/derender\nLabels: bug, frontend, ready\nFiles changed (4): tests/entrypoints/scale_out/derender/test_derender.py, tests/entrypoints/scale_out/derender/test_derender_stream.py, vllm/entrypoints/scale_out/derender/serving.py, vllm/renderers/online_derenderer.py\n\n## Description (results removed)\n\nFixes #57929\n\n**Updated:** Chat fills `prompt_logprobs` inside `_derender_chat`, in the same background call that decodes the text \n\n**AI Assistance** \nCo-Authored-By: ZCode GLM 5.3 / Claude\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/scale_out/derender/serving.py b/vllm/entrypoints/scale_out/derender/serving.py\nindex 28468becd19e..d338d679c754 100644\n--- a/vllm/entrypoints/scale_out/derender/serving.py\n+++ b/vllm/entrypoints/scale_out/derender/serving.py\n@@ -172,7 +172,7 @@ async def derender_chat_response(\n )\n \n try:\n- choices = await self.online_derenderer.derender_chat(\n+ choices, prompt_logprobs = await self.online_derenderer.derender_chat(\n request.generate_response,\n request.chat_request,\n request.prompt_token_ids,\n@@ -205,7 +205,7 @@ async def derender_chat_response(\n created=int(time.time()),\n choices=choices,\n usage=usage,\n- prompt_logprobs=gen.prompt_logprobs,\n+ prompt_logprobs=prompt_logprobs,\n prompt_token_ids=(\n gen.prompt_token_ids\n if request.chat_request is not None\ndiff --git a/vllm/renderers/online_derenderer.py b/vllm/renderers/online_derenderer.py\nindex cad4877ec2e2..5c1b632f7bc0 100644\n--- a/vllm/renderers/online_derenderer.py\n+++ b/vllm/renderers/online_derenderer.py\n@@ -47,6 +47,7 @@\n resolve_finish_reason,\n )\n from vllm.logger import init_logger\n+from vllm.logprobs import Logprob, PromptLogprobs\n from vllm.outputs import CompletionOutput\n from vllm.parser import Parser, ParserManager\n from vllm.renderers import BaseRenderer\n@@ -147,7 +148,7 @@ async def derender_chat(\n generate_response: GenerateTokensResponse,\n chat_request: ChatCompletionRequest | None = None,\n prompt_token_ids: list[int] | None = None,\n- ) -> list[ChatCompletionResponseChoice]:\n+ ) -> tuple[list[ChatCompletionResponseChoice], PromptLogprobs | None]:\n return await self._derender_chat_async(\n generate_response, chat_request, prompt_token_ids\n )\n@@ -258,7 +259,7 @@ def _derender_chat(\n generate_response: GenerateTokensResponse,\n chat_request: ChatCompletionRequest | None = None,\n prompt_token_ids: list[int] | None = None,\n- ) -> list[ChatCompletionResponseChoice]:\n+ ) -> tuple[list[ChatCompletionResponseChoice], PromptLogprobs | None]:\n tokenizer = self.renderer.get_tokenizer()\n choices: list[ChatCompletionResponseChoice] = []\n \n@@ -353,7 +354,10 @@ def _derender_chat(\n )\n )\n \n- return choices\n+ prompt_logprobs = _resolve_prompt_logprobs(\n+ generate_response.prompt_logprobs, tokenizer\n+ )\n+ return choices, prompt_logprobs\n \n async def derender_text_choices(\n self,\n@@ -951,6 +955,7 @@ def _derender_completion(\n seed_state = _seed_stream_state(\n tokenizer, seed_ids, skip_special_tokens=skip_special\n )\n+ prompt_logprobs = _resolve_prompt_logprobs(gen.prompt_logprobs, tokenizer)\n for choice in gen.choices:\n if not choice.token_ids:\n raise ValueError(\n@@ -989,6 +994,7 @@ def _derender_completion(\n gen.prompt_token_ids if return_token_ids else None\n ),\n token_ids=choice.token_ids if return_token_ids else None,\n+ prompt_logprobs=prompt_logprobs,\n )\n )\n total_completion_tokens += len(choice.token_ids)\n@@ -1279,6 +1285,56 @@ def _completion_top_logprobs_limit(\n )\n \n \n+def _resolve_prompt_logprobs(\n+ prompt_logprobs: PromptLogprobs | None, tokenizer: TokenizerLike\n+) -> PromptLogprobs | None:\n+ \"\"\"Fill missing ``decoded_token`` values in prompt logprobs.\n+\n+ A ``--tokens-only`` generate server has no tokenizer, so it returns\n+ ``decoded_token=None``. Mirrors LogprobsProcessor._update_prompt_logprobs\n+ in v1/engine/logprobs.py: decode each token id, then fix U+FFFD using the\n+ preceding prompt tokens (the first entry of each earlier position).\n+ \"\"\"\n+ if prompt_logprobs is None:\n+ return None\n+\n+ missing = list(\n+ dict.fromkeys(\n+ tid\n+ for entry in prompt_logprobs\n+ if entry is not None\n+ for tid, lp in entry.items()\n+ if lp.decoded_token is None\n+ )\n+ )\n+ if not missing:\n+ return prompt_logprobs\n+ # Ids with no vocab entry decode to \"\", as for output logprobs.\n+ decoded = {\n+ tid: text\n+ for tid, (text, _) in zip(missing, decode_token_ids(missing, tokenizer))\n+ }\n+\n+ resolved: PromptLogprobs = []\n+ context_token_ids: list[int] = []\n+ for entry in prompt_logprobs:\n+ if not entry:\n+ resolved.append(entry)\n+ continue\n+ new_entry: dict[int, Logprob] = {}\n+ for tid, lp in entry.items():\n+ if lp.decoded_token is None:\n+ text = decoded[tid]\n+ if text.endswith(\"\\ufffd\"):\n+ text = _correct_decoded_token(tid, context_token_ids, tokenizer)\n+ lp = Logprob(lp.logprob, lp.rank, text)\n+ new_entry[tid] = lp\n+ resolved.append(new_entry)\n+ # The prompt token is always inserted first by the engine.\n+ context_token_ids.append(next(iter(entry)))\n+ return resolved\n+\n+\n def _resolve_logprobs(\n logprobs: GenerateLogProbs,\n tokenizer: TokenizerLike,\n\ndiff --git a/tests/entrypoints/scale_out/derender/test_derender.py b/tests/entrypoints/scale_out/derender/test_derender.py\nindex 667635eb9fc7..93ba9bf70581 100644\n--- a/tests/entrypoints/scale_out/derender/test_derender.py\n+++ b/tests/entrypoints/scale_out/derender/test_derender.py\n@@ -19,6 +19,7 @@\n )\n from vllm.renderers.online_derenderer import OnlineDerenderer\n from vllm.tokenizers import get_tokenizer\n+from vllm.tokenizers.detokenizer_utils import convert_ids_list_to_tokens\n \n MODEL_NAME = \"hmellor/tiny-random-LlamaForCausalLM\"\n \n@@ -522,6 +523,7 @@ def _make_completion_generate_response(\n request_id: str,\n kv_transfer_params: dict | None = None,\n logprobs: dict | None = None,\n+ prompt_logprobs: list | None = None,\n ) -> dict:\n return {\n \"request_id\": request_id,\n@@ -533,7 +535,7 @@ def _make_completion_generate_response(\n \"logprobs\": logprobs,\n }\n ],\n- \"prompt_logprobs\": None,\n+ \"prompt_logprobs\": prompt_logprobs,\n \"kv_transfer_params\": kv_transfer_params,\n }\n \n@@ -737,6 +739,81 @@ async def test_derender_completion_logprobs(client):\n assert logprobs[\"text_offset\"][0] == 0\n \n \n+@pytest.mark.asyncio\n+async def test_derender_completion_prompt_logprobs_passthrough(client):\n+ \"\"\"Each GenerateResponse's prompt_logprobs reaches that prompt's choices.\n+\n+ Regression test: /v1/completions/derender used to drop the prompt\n+ logprobs the engine had already computed and returned, while the direct\n+ /v1/completions endpoint attaches them to every choice of the prompt.\n+ \"\"\"\n+ gr1 = await _render_completion(client, \"Hello\")\n+ gr2 = await _render_completion(client, \"World\")\n+ tok = get_tokenizer(MODEL_NAME)\n+ # A --tokens-only generate server has no tokenizer: decoded_token is null.\n+ plp1 = [None, {str(gr1[\"token_ids\"][0]): {\"logprob\": -0.5, \"rank\": 1}}]\n+ plp2 = [None, {str(gr2[\"token_ids\"][0]): {\"logprob\": -0.25, \"rank\": 2}}]\n+\n+ response = await client.post(\n+ \"/v1/completions/derender\",\n+ json={\n+ \"model\": MODEL_NAME,\n+ \"generate_responses\": [\n+ _make_completion_generate_response(\n+ gr1[\"token_ids\"][:3], gr1[\"request_id\"], prompt_logprobs=plp1\n+ ),\n+ _make_completion_generate_response(\n+ gr2[\"token_ids\"][:3], gr2[\"request_id\"], prompt_logprobs=plp2\n+ ),\n+ ],\n+ },\n+ )\n+ assert response.status_code == 200\n+ choices = response.json()[\"choices\"]\n+ assert len(choices) == 2\n+ for choice, gr, plp in zip(choices, (gr1, gr2), (plp1, plp2)):\n+ tid = gr[\"token_ids\"][0]\n+ (text,) = convert_ids_list_to_tokens(tok, [tid])\n+ entry = choice[\"prompt_logprobs\"][1][str(tid)]\n+ assert plp[1] is not None\n+ assert choice[\"prompt_logprobs\"][0] is None\n+ assert entry[\"decoded_token\"] == text\n+ assert entry[\"logprob\"] == plp[1][str(tid)][\"logprob\"]\n+ assert entry[\"rank\"] == plp[1][str(tid)][\"rank\"]\n+\n+\n+@pytest.mark.asyncio\n+async def test_derender_chat_prompt_logprobs_decoded_token(client):\n+ \"\"\"Null decoded_token is filled (unknown ids as \"\"); given ones and empty\n+ entries are kept.\"\"\"\n+ gen_req = await _render_chat(client)\n+ ids = gen_req[\"token_ids\"][:3]\n+ tok = get_tokenizer(MODEL_NAME)\n+ plp = [\n+ None,\n+ {str(ids[0]): {\"logprob\": -0.5, \"rank\": 1}},\n+ {str(ids[1]): {\"logprob\": -0.1, \"rank\": 1, \"decoded_token\": \"kept\"}},\n+ {},\n+ {str(len(tok) + 1000): {\"logprob\": -1.0, \"rank\": 1}},\n+ ]\n+ response = await client.post(\n+ \"/v1/chat/completions/derender\",\n+ json={\n+ \"model\": MODEL_NAME,\n+ \"generate_response\": _make_generate_response(ids, prompt_logprobs=plp),\n+ },\n+ )\n+ assert response.status_code == 200\n+ out = response.json()[\"prompt_logprobs\"]\n+ assert (\n+ out[1][str(ids[0])][\"decoded_token\"]\n+ == (convert_ids_list_to_tokens(tok, [ids[0]])[0])\n+ )\n+ assert out[2][str(ids[1])][\"decoded_token\"] == \"kept\"\n+ assert out[3] == {}\n+ assert out[4][str(len(tok) + 1000)][\"decoded_token\"] == \"\"\n+\n+\n @pytest.mark.asyncio\n async def test_derender_completion_kv_transfer_params_passthrough(client):\n \"\"\"kv_transfer_params passes through to CompletionResponse.\"\"\"\n@@ -1608,7 +1685,7 @@ def _derender_hermes_chat(\n )\n )\n \n- (choice,) = derenderer._derender_chat(response, request)\n+ (choice,), _ = derenderer._derender_chat(response, request)\n return choice\n \n \n@@ -1767,7 +1844,7 @@ def test_derender_batch_trims_stop_like_engine(\n messages=[{\"role\": \"user\", \"content\": \"Count\"}],\n **request_kwargs,\n )\n- (choice,) = derenderer._derender_chat(response, request)\n+ (choice,), _ = derenderer._derender_chat(response, request)\n output_text = choice.message.content\n else:\n request = CompletionRequest(model=MODEL_NAME, prompt=\"Count\", **request_kwargs)\ndiff --git a/tests/entrypoints/scale_out/derender/test_derender_stream.py b/tests/entrypoints/scale_out/derender/test_derender_stream.py\nindex c58f9cf0034f..ca25c90b27c2 100644\n--- a/tests/entrypoints/scale_out/derender/test_derender_stream.py\n+++ b/tests/entrypoints/scale_out/derender/test_derender_stream.py\n@@ -345,7 +345,7 @@ def test_non_streaming_derender_initializes_parser_prefix(\n tools=_WEATHER_TOOLS,\n )\n \n- choices = derenderer._derender_chat(response, request)\n+ choices, _ = derenderer._derender_chat(response, request)\n \n parser.set_prompt_token_ids.assert_called_once_with([11, 12])\n assert choices[0].message.tool_calls[0].function.name == \"tool\"\n@@ -409,7 +409,7 @@ def batch_content(token_ids: list[int], finish_reason: str) -> str:\n response = GenerateTokensResponse(\n request_id=\"test\", prompt_token_ids=[11, 12], choices=[choice]\n )\n- return derenderer._derender_chat(response, request)[0].message.content\n+ return derenderer._derender_chat(response, request)[0][0].message.content\n \n # Same decode window and seeding; \"length\" never drops a token.\n expected = batch_content(\n@@ -743,7 +743,7 @@ async def test_chat_batch_seeded_via_explicit_prompt_token_ids(\n self, derenderer, leading_space_ids\n ):\n prompt_ids, output_ids, expected = leading_space_ids\n- choices = await derenderer.derender_chat(\n+ choices, _ = await derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"t\",\n choices=[\n@@ -761,7 +761,7 @@ async def test_chat_batch_seeded_via_generate_response_fallback(\n self, derenderer, leading_space_ids\n ):\n prompt_ids, output_ids, expected = leading_space_ids\n- choices = await derenderer.derender_chat(\n+ choices, _ = await derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"t\",\n choices=[\n@@ -780,7 +780,7 @@ async def test_chat_batch_explicit_takes_precedence_over_fallback(\n ):\n prompt_ids, output_ids, expected = leading_space_ids\n wrong_ids = tokenizer.encode(\"a different prompt\", add_special_tokens=False)\n- choices = await derenderer.derender_chat(\n+ choices, _ = await derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"t\",\n choices=[\n@@ -799,7 +799,7 @@ async def test_chat_batch_without_prompt_context_stays_unseeded(\n self, derenderer, leading_space_ids\n ):\n _, output_ids, _ = leading_space_ids\n- choices = await derenderer.derender_chat(\n+ choices, _ = await derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"t\",\n choices=[\n@@ -1887,7 +1887,7 @@ async def test_stream_matches_batch(self, harmony_derenderer, harmony_encode):\n reasoning = \"\".join(d.reasoning or \"\" for d in deltas)\n content = \"\".join(d.content or \"\" for d in deltas)\n \n- batch_choices = await harmony_derenderer.derender_chat(\n+ batch_choices, _ = await harmony_derenderer.derender_chat(\n GenerateTokensResponse(\n request_id=\"test-harmony-batch\",\n choices=[\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Tool Parser] Parse multi-line JSON arguments in the DeepSeek V3 and V3.1 parsers\nLabels: bug, ready, tool-calling, deepseek\nFiles changed (4): tests/tool_parsers/test_deepseekv31_tool_parser.py, tests/tool_parsers/test_deepseekv3_tool_parser.py, vllm/tool_parsers/deepseekv31_tool_parser.py, vllm/tool_parsers/deepseekv3_tool_parser.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #60342. The `deepseek_v3` and `deepseek_v31` tool parsers lose tool calls whose JSON arguments the model pretty-prints over several lines: their regexes match the arguments with `.`, which stops at a newline.\n\n## Claims\n\n- Tool calls with multi-line JSON arguments are now parsed by `deepseek_v3` and `deepseek_v31`, in both streaming and non-streaming mode.\n\n## Validation\n[results removed]\n## Details\n\n- Root cause: `DeepSeekV3ToolParser` matches `function_arguments` with `.*` (`` .*[^\\n`] `` when streaming), and `DeepSeekV31ToolParser` with `.*?` / `.*`. Without `re.DOTALL`, `.` doesn't match `\\n`, so the non-streaming regex finds nothing and the streaming regex captures only the first line of the arguments.\n- Fix: only the arguments group uses `[\\s\\S]`. It stays non-greedy in the regexes used with `findall`, so parallel calls still split at the first closing tag. The type and function-name groups keep `.`, so a name can't span lines and the whole pattern doesn't need `re.DOTALL`.\n- The Rust frontend's parsers (`rust/src/parser/src/tool/deepseek_json`) don't use a regex here; `take_json_object` scans the object by brace depth, so from reading the code they already handle pretty-printed arguments. Only the Python parsers change.\n- Related PRs: #60361 (opened a few minutes before this one, still a draft) makes the same change to the V3 regexes and leaves V3.1 for later; this PR covers both parsers. #47503 edits the same DeepSeek-V3 regexes to accept an optional newline before the JSON fence, which is a different case, so whichever merges second needs a small rebase. #55473 wraps these regexes with timeouts and is independent.\n\nAI assistance was used for this change (tracking down the cause, writing the tests and this description). I reviewed every changed line and ran the tests above.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/tool_parsers/deepseekv31_tool_parser.py b/vllm/tool_parsers/deepseekv31_tool_parser.py\nindex ff5f605f511f..9bf6675a2d08 100644\n--- a/vllm/tool_parsers/deepseekv31_tool_parser.py\n+++ b/vllm/tool_parsers/deepseekv31_tool_parser.py\n@@ -43,12 +43,13 @@ def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n self.tool_call_start_token: str = \"<|tool▁call▁begin|>\"\n self.tool_call_end_token: str = \"<|tool▁call▁end|>\"\n \n+ # The arguments may be pretty-printed over several lines.\n self.tool_call_regex = re.compile(\n- r\"<|tool▁call▁begin|>(?P.*?)<|tool▁sep|>(?P.*?)<|tool▁call▁end|>\"\n+ r\"<|tool▁call▁begin|>(?P.*?)<|tool▁sep|>(?P[\\s\\S]*?)<|tool▁call▁end|>\"\n )\n \n self.stream_tool_call_portion_regex = re.compile(\n- r\"(?P.*)<|tool▁sep|>(?P.*)\"\n+ r\"(?P.*)<|tool▁sep|>(?P[\\s\\S]*)\"\n )\n \n self.stream_tool_call_name_regex = re.compile(\ndiff --git a/vllm/tool_parsers/deepseekv3_tool_parser.py b/vllm/tool_parsers/deepseekv3_tool_parser.py\nindex 9e18bdcd899a..ec6a8ba907f1 100644\n--- a/vllm/tool_parsers/deepseekv3_tool_parser.py\n+++ b/vllm/tool_parsers/deepseekv3_tool_parser.py\n@@ -46,12 +46,13 @@ def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n self.tool_call_start_token: str = \"<|tool▁call▁begin|>\"\n self.tool_call_end_token: str = \"<|tool▁call▁end|>\"\n \n+ # The arguments may be pretty-printed over several lines.\n self.tool_call_regex = re.compile(\n- r\"<|tool▁call▁begin|>(?P.*)<|tool▁sep|>(?P.*)\\n```json\\n(?P.*)\\n```<|tool▁call▁end|>\"\n+ r\"<|tool▁call▁begin|>(?P.*)<|tool▁sep|>(?P.*)\\n```json\\n(?P[\\s\\S]*?)\\n```<|tool▁call▁end|>\"\n )\n \n self.stream_tool_call_portion_regex = re.compile(\n- r\"(?P.*)<|tool▁sep|>(?P.*)\\n```json\\n(?P.*[^\\n`])\"\n+ r\"(?P.*)<|tool▁sep|>(?P.*)\\n```json\\n(?P[\\s\\S]*[^\\n`])\"\n )\n \n self.stream_tool_call_name_regex = re.compile(\n\ndiff --git a/tests/tool_parsers/test_deepseekv31_tool_parser.py b/tests/tool_parsers/test_deepseekv31_tool_parser.py\nindex 43597b1d1844..f90d471fab20 100644\n--- a/tests/tool_parsers/test_deepseekv31_tool_parser.py\n+++ b/tests/tool_parsers/test_deepseekv31_tool_parser.py\n@@ -1,8 +1,11 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import json\n+\n import pytest\n \n+from tests.tool_parsers.utils import run_tool_extraction\n from vllm.tokenizers import get_tokenizer\n from vllm.tool_parsers.deepseekv31_tool_parser import (\n DeepSeekV31ToolParser,\n@@ -59,3 +62,22 @@ def test_extract_tool_calls_with_multiple_tools(parser):\n \n # prefix is content\n assert result.content == \"some prefix text\"\n+\n+\n+@pytest.mark.parametrize(\"streaming\", [True, False])\n+def test_extract_tool_calls_with_multiline_arguments(parser, streaming):\n+ # The model may pretty-print the JSON arguments over several lines.\n+ args = {\"x\": 1, \"y\": [1, 2]}\n+ model_output = (\n+ \"<|tool▁calls▁begin|>\"\n+ f\"<|tool▁call▁begin|>foo<|tool▁sep|>{json.dumps(args, indent=2)}\"\n+ \"<|tool▁call▁end|>\"\n+ '<|tool▁call▁begin|>bar<|tool▁sep|>{\"y\":2}<|tool▁call▁end|>'\n+ \"<|tool▁calls▁end|>\"\n+ )\n+\n+ _, tool_calls = run_tool_extraction(parser, model_output, streaming=streaming)\n+\n+ assert [call.function.name for call in tool_calls] == [\"foo\", \"bar\"]\n+ assert json.loads(tool_calls[0].function.arguments) == args\n+ assert json.loads(tool_calls[1].function.arguments) == {\"y\": 2}\ndiff --git a/tests/tool_parsers/test_deepseekv3_tool_parser.py b/tests/tool_parsers/test_deepseekv3_tool_parser.py\nindex e0d2897e917e..ff64661000cb 100644\n--- a/tests/tool_parsers/test_deepseekv3_tool_parser.py\n+++ b/tests/tool_parsers/test_deepseekv3_tool_parser.py\n@@ -1,6 +1,7 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import json\n \n import pytest\n \n@@ -92,6 +93,32 @@ def test_config(self) -> ToolParserTestConfig:\n },\n )\n \n+ def test_multiline_json_arguments(self, tool_parser, streaming: bool):\n+ # The model may pretty-print the JSON arguments over several lines.\n+ weather = {\"city\": \"Tokyo\", \"unit\": \"celsius\"}\n+ hotels = {\"location\": \"Tokyo\", \"check_in\": \"2025-01-15\"}\n+ model_output = (\n+ \"<|tool▁calls▁begin|>\"\n+ \"<|tool▁call▁begin|>function<|tool▁sep|>get_weather\\n\"\n+ f\"```json\\n{json.dumps(weather, indent=2)}\\n```<|tool▁call▁end|>\"\n+ \"<|tool▁call▁begin|>function<|tool▁sep|>search_hotels\\n\"\n+ f\"```json\\n{json.dumps(hotels, indent=2)}\\n```<|tool▁call▁end|>\"\n+ \"<|tool▁calls▁end|>\"\n+ )\n+\n+ _, tool_calls = run_tool_extraction(\n+ tool_parser, model_output, streaming=streaming\n+ )\n+\n+ assert [call.function.name for call in tool_calls] == [\n+ \"get_weather\",\n+ \"search_hotels\",\n+ ]\n+ assert [json.loads(call.function.arguments) for call in tool_calls] == [\n+ weather,\n+ hotels,\n+ ]\n+\n @pytest.mark.parametrize(\"streaming\", [False, True])\n def test_preserves_text_after_tool_call(\n self,\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Benchmark] Support boolean sweep plot filters\nLabels: bug, performance, ready\nFiles changed (2): tests/benchmarks/test_plot_filters.py, vllm/benchmarks/sweep/plot.py\n\n## Description (results removed)\n\nFixes #60629.\n\nPlotEqualTo and PlotNotEqualTo now parse `true`/`false` as booleans when filtering boolean columns, while preserving existing string and numeric filtering behavior.\n\n### Tests\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/benchmarks/sweep/plot.py b/vllm/benchmarks/sweep/plot.py\nindex 6b36a7acc601..d5d702a9dab3 100644\n--- a/vllm/benchmarks/sweep/plot.py\n+++ b/vllm/benchmarks/sweep/plot.py\n@@ -31,10 +31,10 @@ class PlotFilterBase(ABC):\n def parse_str(cls, s: str):\n for op_key in PLOT_FILTERS:\n if op_key in s:\n- key, value = s.split(op_key)\n+ key, _, value = s.partition(op_key)\n return PLOT_FILTERS[op_key](\n- key,\n- value.removeprefix(op_key).strip(\"'\").strip('\"'),\n+ key.strip(),\n+ value.removeprefix(op_key).strip().strip(\"'\").strip('\"'),\n )\n else:\n raise ValueError(\n@@ -48,16 +48,29 @@ def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n raise NotImplementedError\n \n \n+def _parse_filter_target(series, target: str) -> float | bool | str:\n+ \"\"\"Parse a filter target using the column's value type when needed.\"\"\"\n+ if target.casefold() in (\"true\", \"false\"):\n+ dtype_kind = getattr(series.dtype, \"kind\", None)\n+ non_null_values = series.dropna()\n+ is_boolean = dtype_kind == \"b\" or (\n+ len(non_null_values) > 0\n+ and all(isinstance(value, bool) for value in non_null_values)\n+ )\n+ if is_boolean:\n+ return target.casefold() == \"true\"\n+\n+ try:\n+ return float(target)\n+ except ValueError:\n+ return target\n+\n+\n @dataclass\n class PlotEqualTo(PlotFilterBase):\n @override\n def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n- target: float | str\n- try:\n- target = float(self.target)\n- except ValueError:\n- target = self.target\n-\n+ target = _parse_filter_target(df[self.var], self.target)\n return df[df[self.var] == target]\n \n \n@@ -65,12 +78,7 @@ def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n class PlotNotEqualTo(PlotFilterBase):\n @override\n def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n- target: float | str\n- try:\n- target = float(self.target)\n- except ValueError:\n- target = self.target\n-\n+ target = _parse_filter_target(df[self.var], self.target)\n return df[df[self.var] != target]\n \n \n@@ -137,8 +145,10 @@ class PlotBinner:\n def parse_str(cls, s: str):\n for op_key in PLOT_BINNERS:\n if op_key in s:\n- key, value = s.split(op_key)\n- return PLOT_BINNERS[op_key](key, float(value.removeprefix(op_key)))\n+ key, _, value = s.partition(op_key)\n+ return PLOT_BINNERS[op_key](\n+ key.strip(), float(value.removeprefix(op_key).strip())\n+ )\n else:\n raise ValueError(\n f\"Invalid operator for plot binner '{s}'. \"\n\ndiff --git a/tests/benchmarks/test_plot_filters.py b/tests/benchmarks/test_plot_filters.py\nindex 2b58a99125e6..b6b13f55861d 100644\n--- a/tests/benchmarks/test_plot_filters.py\n+++ b/tests/benchmarks/test_plot_filters.py\n@@ -4,6 +4,7 @@\n import pytest\n \n from vllm.benchmarks.sweep.plot import (\n+ PlotBinner,\n PlotEqualTo,\n PlotFilterBase,\n PlotFilters,\n@@ -37,6 +38,13 @@ def setup_method(self):\n }\n )\n \n+ self.df_boolean = pd.DataFrame(\n+ {\n+ \"enable_prefix_caching\": [True, False],\n+ \"request_rate\": [10, 20],\n+ }\n+ )\n+\n @pytest.mark.parametrize(\n \"target,expected_count\",\n [\n@@ -78,6 +86,45 @@ def test_not_equal_to_inf_float(self):\n # Should exclude float('inf') entries\n assert len(result) == 3\n \n+ def test_equal_to_boolean(self):\n+ \"\"\"Boolean filter targets should match JSON boolean columns.\"\"\"\n+ filter_obj = PlotFilters.parse_str(\"enable_prefix_caching==true\")\n+\n+ result = filter_obj.apply(self.df_boolean)\n+\n+ assert result[\"request_rate\"].tolist() == [10]\n+\n+ def test_not_equal_to_boolean(self):\n+ \"\"\"Boolean inequality should exclude only the matching rows.\"\"\"\n+ filter_obj = PlotFilters.parse_str(\"enable_prefix_caching!=true\")\n+\n+ result = filter_obj.apply(self.df_boolean)\n+\n+ assert result[\"request_rate\"].tolist() == [20]\n+\n+ def test_boolean_target_is_literal_for_string_column(self):\n+ \"\"\"String labels named true/false must keep string comparisons.\"\"\"\n+ df = pd.DataFrame({\"label\": [\"true\", \"false\"]})\n+\n+ result = PlotFilters.parse_str(\"label==true\").apply(df)\n+\n+ assert result[\"label\"].tolist() == [\"true\"]\n+\n+ def test_boolean_filter_with_missing_values(self):\n+ \"\"\"Nullable boolean columns keep missing rows out of either match.\"\"\"\n+ df = pd.DataFrame(\n+ {\n+ \"enabled\": pd.Series([True, False, None], dtype=\"boolean\"),\n+ \"request_rate\": [10, 20, 30],\n+ }\n+ )\n+\n+ equal = PlotFilters.parse_str(\"enabled==false\").apply(df)\n+ not_equal = PlotFilters.parse_str(\"enabled!=false\").apply(df)\n+\n+ assert equal[\"request_rate\"].tolist() == [20]\n+ assert not_equal[\"request_rate\"].tolist() == [10]\n+\n @pytest.mark.parametrize(\n \"target,expected_count\",\n [\n@@ -158,6 +205,20 @@ def test_parse_str_inf_edge_case(self):\n assert filter_obj.var == \"request_rate\"\n assert filter_obj.target == \"inf\"\n \n+ def test_parse_str_preserves_operator_in_quoted_target(self):\n+ \"\"\"Only the first operator separates a filter's variable and target.\"\"\"\n+ filter_obj = PlotFilterBase.parse_str('model==\"foo==bar\"')\n+\n+ assert filter_obj.var == \"model\"\n+ assert filter_obj.target == \"foo==bar\"\n+\n+ def test_parse_str_strips_variable_whitespace(self):\n+ \"\"\"Whitespace around a filter expression should not alter its column.\"\"\"\n+ filter_obj = PlotFilterBase.parse_str(\" request_rate >= 10.0 \")\n+\n+ assert filter_obj.var == \"request_rate\"\n+ assert filter_obj.target == \"10.0\"\n+\n def test_parse_multiple_filters(self):\n \"\"\"Test parsing multiple filters.\"\"\"\n filters = PlotFilters.parse_str(\"request_rate>5.0,value<=40\")\n@@ -169,3 +230,10 @@ def test_parse_empty_filter(self):\n \"\"\"Test parsing empty filter string.\"\"\"\n filters = PlotFilters.parse_str(\"\")\n assert len(filters) == 0\n+\n+ def test_parse_binner_strips_whitespace(self):\n+ \"\"\"Whitespace around a bin expression should not break parsing.\"\"\"\n+ binner = PlotBinner.parse_str(\" request_rate % 5 \")\n+\n+ assert binner.var == \"request_rate\"\n+ assert binner.bin_size == 5\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Benchmark] Support boolean sweep plot filters\nLabels: bug, performance, ready\nFiles changed (2): tests/benchmarks/test_plot_filters.py, vllm/benchmarks/sweep/plot.py\n\n## Description (results removed)\n\nFixes #60629.\n\nPlotEqualTo and PlotNotEqualTo now parse `true`/`false` as booleans when filtering boolean columns, while preserving existing string and numeric filtering behavior.\n\n### Tests\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/benchmarks/sweep/plot.py b/vllm/benchmarks/sweep/plot.py\nindex 6b36a7acc..cfb11f903 100644\n--- a/vllm/benchmarks/sweep/plot.py\n+++ b/vllm/benchmarks/sweep/plot.py\n@@ -48,16 +48,29 @@ class PlotFilterBase(ABC):\n raise NotImplementedError\n \n \n+def _parse_filter_target(series, target: str) -> float | bool | str:\n+ \"\"\"Parse a filter target using the column's value type when needed.\"\"\"\n+ if target.casefold() in (\"true\", \"false\"):\n+ dtype_kind = getattr(series.dtype, \"kind\", None)\n+ non_null_values = series.dropna()\n+ is_boolean = dtype_kind == \"b\" or (\n+ len(non_null_values) > 0\n+ and all(isinstance(value, bool) for value in non_null_values)\n+ )\n+ if is_boolean:\n+ return target.casefold() == \"true\"\n+\n+ try:\n+ return float(target)\n+ except ValueError:\n+ return target\n+\n+\n @dataclass\n class PlotEqualTo(PlotFilterBase):\n @override\n def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n- target: float | str\n- try:\n- target = float(self.target)\n- except ValueError:\n- target = self.target\n-\n+ target = _parse_filter_target(df[self.var], self.target)\n return df[df[self.var] == target]\n \n \n@@ -65,12 +78,7 @@ class PlotEqualTo(PlotFilterBase):\n class PlotNotEqualTo(PlotFilterBase):\n @override\n def apply(self, df: \"pd.DataFrame\") -> \"pd.DataFrame\":\n- target: float | str\n- try:\n- target = float(self.target)\n- except ValueError:\n- target = self.target\n-\n+ target = _parse_filter_target(df[self.var], self.target)\n return df[df[self.var] != target]\n \n \n\ndiff --git a/tests/benchmarks/test_plot_filters.py b/tests/benchmarks/test_plot_filters.py\nindex 2b58a9912..a271da2b5 100644\n--- a/tests/benchmarks/test_plot_filters.py\n+++ b/tests/benchmarks/test_plot_filters.py\n@@ -37,6 +37,13 @@ class TestPlotFilters:\n }\n )\n \n+ self.df_boolean = pd.DataFrame(\n+ {\n+ \"enable_prefix_caching\": [True, False],\n+ \"request_rate\": [10, 20],\n+ }\n+ )\n+\n @pytest.mark.parametrize(\n \"target,expected_count\",\n [\n@@ -78,6 +85,45 @@ class TestPlotFilters:\n # Should exclude float('inf') entries\n assert len(result) == 3\n \n+ def test_equal_to_boolean(self):\n+ \"\"\"Boolean filter targets should match JSON boolean columns.\"\"\"\n+ filter_obj = PlotFilters.parse_str(\"enable_prefix_caching==true\")\n+\n+ result = filter_obj.apply(self.df_boolean)\n+\n+ assert result[\"request_rate\"].tolist() == [10]\n+\n+ def test_not_equal_to_boolean(self):\n+ \"\"\"Boolean inequality should exclude only the matching rows.\"\"\"\n+ filter_obj = PlotFilters.parse_str(\"enable_prefix_caching!=true\")\n+\n+ result = filter_obj.apply(self.df_boolean)\n+\n+ assert result[\"request_rate\"].tolist() == [20]\n+\n+ def test_boolean_target_is_literal_for_string_column(self):\n+ \"\"\"String labels named true/false must keep string comparisons.\"\"\"\n+ df = pd.DataFrame({\"label\": [\"true\", \"false\"]})\n+\n+ result = PlotFilters.parse_str(\"label==true\").apply(df)\n+\n+ assert result[\"label\"].tolist() == [\"true\"]\n+\n+ def test_boolean_filter_with_missing_values(self):\n+ \"\"\"Nullable boolean columns keep missing rows out of either match.\"\"\"\n+ df = pd.DataFrame(\n+ {\n+ \"enabled\": pd.Series([True, False, None], dtype=\"boolean\"),\n+ \"request_rate\": [10, 20, 30],\n+ }\n+ )\n+\n+ equal = PlotFilters.parse_str(\"enabled==false\").apply(df)\n+ not_equal = PlotFilters.parse_str(\"enabled!=false\").apply(df)\n+\n+ assert equal[\"request_rate\"].tolist() == [20]\n+ assert not_equal[\"request_rate\"].tolist() == [10]\n+\n @pytest.mark.parametrize(\n \"target,expected_count\",\n [\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Fix Opencv video backend frames count missing for WebM video inputs\nLabels: bug, ready, multi-modality\nFiles changed (3): tests/multimodal/test_video.py, tests/multimodal/utils.py, vllm/multimodal/video_decoders/opencv.py\n\n## Description (results removed)\n\n## Overview\n- Fix #60518 with a method to avoid decoding/unpacking all frames duplicately\n\n## Claims\n**Metadata recovery time (best of 4 runs)**\n\n[table with results removed]\n\n## Details\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/multimodal/video_decoders/opencv.py b/vllm/multimodal/video_decoders/opencv.py\nindex 3ca141c738c4..88d7fb837551 100644\n--- a/vllm/multimodal/video_decoders/opencv.py\n+++ b/vllm/multimodal/video_decoders/opencv.py\n@@ -38,7 +38,9 @@ def decode_opencv(\n int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),\n )\n- source = loader_cls._prepare_source(OpenCVVideoBackendMixin.get_video_metadata(cap))\n+ source = loader_cls._prepare_source(\n+ OpenCVVideoBackendMixin.get_video_metadata(data)\n+ )\n frame_idx = loader_cls.compute_frames_index_to_sample(\n source=source, target=target, **sampling_kwargs\n )\n@@ -74,10 +76,34 @@ def open_video_capture(cls, data: bytes) -> \"cv2.VideoCapture\":\n raise ValueError(\"Could not open video stream\")\n return cap\n \n+ @classmethod\n+ def demux_count_frames(cls, data: bytes) -> int:\n+ \"\"\"Count frames with OpenCV's demuxer-only mode.\"\"\"\n+ # NOTE: buf must stay referenced until after release().\n+ # OpenCV's Python stream binding does not safely own the stream object\n+ buf = BytesIO(data)\n+ demux_cap = cv2.VideoCapture(\n+ buf, cls.get_cv2_video_api(), [cv2.CAP_PROP_FORMAT, -1]\n+ )\n+ count = 0\n+ while demux_cap.grab():\n+ count += 1\n+ demux_cap.release()\n+ if count == 0:\n+ raise ValueError(\"Could not determine the number of video frames\")\n+ return count\n+\n @staticmethod\n- def get_video_metadata(cap: \"cv2.VideoCapture\") -> VideoSourceMetadata:\n+ def get_video_metadata(data: bytes) -> VideoSourceMetadata:\n+ cap = OpenCVVideoBackendMixin.open_video_capture(data)\n total_frames_num = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n original_fps = cap.get(cv2.CAP_PROP_FPS)\n+ if total_frames_num <= 0:\n+ # Streamed WebM/MKV and raw H.264 miss frame count in headers;\n+ # We need to use demux frames count for retrieval\n+ total_frames_num = OpenCVVideoBackendMixin.demux_count_frames(data)\n+ duration = total_frames_num / original_fps if original_fps > 0 else 0\n+ return VideoSourceMetadata(total_frames_num, original_fps, duration)\n # CAP_PROP_FRAME_COUNT counts every physical sample in the container,\n # overstating the presentable frames when an mp4 edit list hides the\n # decode lead-in (e.g. a lossless `ffmpeg -ss ... -c copy` trim).\n@@ -87,7 +113,7 @@ def get_video_metadata(cap: \"cv2.VideoCapture\") -> VideoSourceMetadata:\n # may land mid-stream on corrupt files, so only trust it when the\n # stream really ends there. A one-frame tolerance keeps mere header\n # miscounts from being \"corrected\".\n- if total_frames_num > 0 and cap.set(cv2.CAP_PROP_POS_AVI_RATIO, 1.0):\n+ if cap.set(cv2.CAP_PROP_POS_AVI_RATIO, 1.0):\n visible_frames = int(cap.get(cv2.CAP_PROP_POS_FRAMES))\n at_stream_end = not cap.grab()\n cap.set(cv2.CAP_PROP_POS_FRAMES, 0)\n\ndiff --git a/tests/multimodal/test_video.py b/tests/multimodal/test_video.py\nindex 1c7730a37ef8..16334fdb0dc7 100644\n--- a/tests/multimodal/test_video.py\n+++ b/tests/multimodal/test_video.py\n@@ -49,7 +49,9 @@\n \n from .utils import (\n create_edit_list_trimmed_video,\n+ create_live_webm_video,\n create_long_gop_video,\n+ create_raw_h264_video,\n create_video_from_image,\n )\n \n@@ -1261,8 +1263,8 @@ def test_qwen3_vl_unknown_source_fps_matches_hf(\n the metadata carries the fps HF assumes, which the frame timestamps use.\"\"\"\n get_video_metadata = OpenCVVideoBackendMixin.get_video_metadata\n \n- def unknown_fps(cap) -> VideoSourceMetadata:\n- return get_video_metadata(cap)._replace(original_fps=0.0, duration=0.0)\n+ def unknown_fps(data) -> VideoSourceMetadata:\n+ return get_video_metadata(data)._replace(original_fps=0.0, duration=0.0)\n \n monkeypatch.setattr(\n OpenCVVideoBackendMixin, \"get_video_metadata\", staticmethod(unknown_fps)\n@@ -1476,6 +1478,36 @@ def test_video_backend_handles_edit_list_trimmed_video(\n assert qwen_frames.shape[0] >= 4\n \n \n+def test_opencv_demux_counts_frames_when_video_header_lacks_metadata(\n+ monkeypatch: pytest.MonkeyPatch,\n+):\n+ \"\"\"Streamed WebM and raw H.264 carry no frame count/duration in their\n+ headers, so OpenCV reports a bogus negative ``CAP_PROP_FRAME_COUNT``.\n+ The loader must count the frames via a demux-only pass, without\n+ decoding.\n+ \"\"\"\n+ with monkeypatch.context() as m:\n+ m.setenv(\"VLLM_VIDEO_LOADER_BACKEND\", \"opencv\")\n+ loader = VIDEO_LOADER_REGISTRY.load(\"opencv\")\n+\n+ webm_data = create_live_webm_video(num_frames=20, fps=10)\n+ frames, metadata = loader.load_bytes(webm_data, backend=\"opencv\")\n+ assert frames.shape[0] == 20\n+ assert metadata[\"total_num_frames\"] == 20\n+ assert metadata[\"duration\"] == pytest.approx(2.0)\n+\n+ h264_data = create_raw_h264_video(num_frames=20, fps=25)\n+ frames, metadata = loader.load_bytes(h264_data, backend=\"opencv\")\n+ assert frames.shape[0] == 20\n+ assert metadata[\"total_num_frames\"] == 20\n+ assert metadata[\"duration\"] == pytest.approx(0.8)\n+\n+ # The Qwen samplers used to raise on the bogus negative frame count.\n+ qwen_frames, qwen_metadata = Qwen2VLVideoBackend.load_bytes(webm_data)\n+ assert qwen_metadata[\"total_num_frames\"] == 20\n+ assert qwen_frames.shape[0] >= 4\n+\n+\n # ============================================================================\n # Frame Recovery Tests\n # ============================================================================\ndiff --git a/tests/multimodal/utils.py b/tests/multimodal/utils.py\nindex 23a05a094422..d74f68453146 100644\n--- a/tests/multimodal/utils.py\n+++ b/tests/multimodal/utils.py\n@@ -1,6 +1,8 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import io\n+\n import cv2\n import numpy as np\n import numpy.typing as npt\n@@ -77,8 +79,6 @@ def create_long_gop_video(\n The marker lets a test recover which frame the decoder actually returned,\n independent of any metadata label.\n \"\"\"\n- import io\n-\n import av\n \n buf = io.BytesIO()\n@@ -103,6 +103,63 @@ def create_long_gop_video(\n return buf.getvalue()\n \n \n+def create_live_webm_video(\n+ num_frames: int = 20,\n+ fps: int = 10,\n+ width: int = 64,\n+ height: int = 64,\n+) -> bytes:\n+ \"\"\"Encode a WebM stream without container duration or frame-count metadata.\n+\n+ The ``live`` muxing option mimics writing to a pipe: the Segment size is\n+ unknown and no Duration or Cues elements are written, so decoder backends\n+ cannot learn the frame count from the header.\n+ \"\"\"\n+ import av\n+\n+ buf = io.BytesIO()\n+ with av.open(buf, mode=\"w\", format=\"webm\", options={\"live\": \"1\"}) as container:\n+ stream = container.add_stream(\"libvpx\", rate=fps)\n+ stream.width = width\n+ stream.height = height\n+ stream.pix_fmt = \"yuv420p\"\n+ for i in range(num_frames):\n+ img = np.zeros((height, width, 3), dtype=np.uint8)\n+ img[:, :, 1] = i % 256\n+ frame = av.VideoFrame.from_ndarray(img, format=\"rgb24\")\n+ for packet in stream.encode(frame):\n+ container.mux(packet)\n+ for packet in stream.encode():\n+ container.mux(packet)\n+ return buf.getvalue()\n+\n+\n+def create_raw_h264_video(\n+ num_frames: int = 20,\n+ fps: int = 25,\n+ width: int = 64,\n+ height: int = 64,\n+) -> bytes:\n+ \"\"\"Encode a raw H.264 Annex B elementary stream (no container metadata).\"\"\"\n+ import av\n+\n+ buf = io.BytesIO()\n+ with av.open(buf, mode=\"w\", format=\"h264\") as container:\n+ stream = container.add_stream(\"h264\", rate=fps)\n+ stream.width = width\n+ stream.height = height\n+ stream.pix_fmt = \"yuv420p\"\n+ for i in range(num_frames):\n+ img = np.zeros((height, width, 3), dtype=np.uint8)\n+ img[:, :, 1] = i % 256\n+ frame = av.VideoFrame.from_ndarray(img, format=\"rgb24\")\n+ for packet in stream.encode(frame):\n+ container.mux(packet)\n+ for packet in stream.encode():\n+ container.mux(packet)\n+ return buf.getvalue()\n+\n+\n def create_edit_list_trimmed_video(\n num_frames: int = 90,\n trim_start_frame: int = 60,\n@@ -117,8 +174,6 @@ def create_edit_list_trimmed_video(\n trailing frames are presentable — the shape produced by lossless trims\n (e.g. ``ffmpeg -ss ... -c copy``). Returns (video_bytes, visible_frames).\n \"\"\"\n- import io\n-\n import av\n \n src = create_long_gop_video(num_frames=num_frames, fps=fps)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][EPLB] Move 1-byte expert tensors as uint8 views\nLabels: bug, ready, verified\nFiles changed (2): tests/distributed/test_eplb_execute.py, vllm/model_executor/models/interfaces.py\n\n## Description (results removed)\n\n## Purpose\n\nFixes #51567.\n\nWith `communicator=torch_nccl`:\n\n```text\nFile \"vllm/v1/worker/gpu_worker.py\", line 572, in determine_available_memory\nFile \"vllm/v1/worker/gpu/eplb_utils.py\", line 126, in step\nFile \"vllm/distributed/eplb/eplb_state.py\", line 580, in step\n...\nFile \"torch/distributed/distributed_c10d.py\", line 4280, in all_gather\n work = group.allgather([tensor_list], [tensor], opts)\nTypeError: Input tensor data type is not supported for NCCL process group: Float8_e8m0fnu\n```\n\nWith `communicator=pynccl`:\n\n```text\nFile \"vllm/distributed/eplb/eplb_communicator.py\", line 756, in create_eplb_communicator\n return _create_pynccl()\nFile \"vllm/distributed/eplb/eplb_communicator.py\", line 693, in _create_pynccl\n raise RuntimeError(\nRuntimeError: EPLB communicator 'pynccl' requested but expert weights contain unsupported dtypes: (torch.float8_e8m0fnu).\n```\n\n## When this triggers\n\n1. EPLB is enabled (`--enable-eplb`, with EP).\n2. The experts use MX quantization (MXFP4/MXFP8 with E8M0 block scales).\n3. After post-processing, the backend stores an expert tensor in a 1-byte dtype that NCCL/RCCL does not support. For example:\n - Marlin MXFP4 MoE: `mxfp4_marlin_process_scales()` returns scales as `float8_e8m0fnu`.\n - ROCm AITER MXFP4: expert weights are viewed as `float4_e2m1fn_x2` (`oracle/mxfp4.py`).\n - Humming MXFP4 (my repro): scales are stored as `float8_e8m0fnu`.\n\n Backends that keep these tensors as `uint8` are not affected.\n4. The tensor is returned by `get_expert_weights()`, so it is registered for EPLB transport.\n\nConverting at load time is not enough. DeepSeek-V4/V4.1 loaders already view checkpoint E8M0 scales as `uint8`, but the backend's kernel-format conversion writes `float8_e8m0fnu` back into the parameter. The fix therefore belongs where the tensors are registered for EPLB, not in individual loaders or backends.\n\n## Root cause\n\n- `torch_nccl` raises `TypeError` inside `all_gather`.\n- `pynccl` rejects the dtype earlier, when the communicator is created.\n\n## Fix\n\nEPLB only copies expert bytes between ranks. It never reduces them, so the numeric dtype does not matter to the transport. In `MixtureOfExperts.set_eplb_state()`, every 1-byte expert tensor is now registered as `w.view(torch.uint8)`:\n\n- The view keeps the shape, stride, and storage, so a rearrange writes directly into the parameter that the kernels read in the original dtype.\n- Applying the view at this registration point covers `FusedMoE` layers, models with their own `get_expert_weights()` (for example DeepSeek-V4 MegaMoE), and elastic EP re-registration.\n- 1-byte dtypes that NCCL already supports (`int8`, `uint8`, `float8_e4m3fn`) move the same bytes as before.\n\n## Test Plan\n[results removed]\n## Test Result\n[results removed]\n## AI assistance\n\nThis PR was prepared with AI assistance (Claude). I reviewed every changed line and ran the tests above.\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/interfaces.py b/vllm/model_executor/models/interfaces.py\nindex 818c1610500e..bd0a6881c7a9 100644\n--- a/vllm/model_executor/models/interfaces.py\n+++ b/vllm/model_executor/models/interfaces.py\n@@ -1109,8 +1109,14 @@ def set_eplb_state(\n \"\"\"\n self.expert_weights = []\n for layer_idx, layer in enumerate(self.moe_layers):\n- # Register the expert weights.\n- self.expert_weights.append(list(layer.get_expert_weights()))\n+ # Register the expert weights. EPLB only moves bytes, so 1-byte\n+ # dtypes NCCL lacks (e.g. E8M0, FP4x2) go as uint8 views.\n+ self.expert_weights.append(\n+ [\n+ w.view(torch.uint8) if w.element_size() == 1 else w\n+ for w in layer.get_expert_weights()\n+ ]\n+ )\n layer.set_eplb_state(\n moe_layer_idx=layer_idx,\n expert_load_view=expert_load_view,\n\ndiff --git a/tests/distributed/test_eplb_execute.py b/tests/distributed/test_eplb_execute.py\nindex acdb9f39fcac..6d0f89248d47 100644\n--- a/tests/distributed/test_eplb_execute.py\n+++ b/tests/distributed/test_eplb_execute.py\n@@ -2,6 +2,7 @@\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n import random\n+from types import SimpleNamespace\n \n import pytest\n import torch\n@@ -23,11 +24,33 @@\n ensure_model_parallel_initialized,\n get_tp_group,\n )\n+from vllm.model_executor.models.interfaces import MixtureOfExperts\n from vllm.platforms import current_platform\n \n from .eplb_utils import distributed_run, set_env_vars_and_device\n \n \n+@pytest.mark.parametrize(\"dtype\", [torch.float8_e8m0fnu, torch.float4_e2m1fn_x2])\n+def test_set_eplb_state_registers_byte_dtypes_as_uint8_views(dtype):\n+ \"\"\"NCCL lacks these dtypes, so EPLB must see their bytes as uint8 views\n+ sharing storage with the parameter the kernel reads.\"\"\"\n+ weight = torch.zeros(2, 8, dtype=torch.int32)\n+ scale = torch.zeros(2, 4, dtype=torch.uint8).view(dtype)\n+ layer = SimpleNamespace(\n+ get_expert_weights=lambda: [weight, scale],\n+ set_eplb_state=lambda **_: None,\n+ )\n+ model = SimpleNamespace(moe_layers=[layer])\n+ empty = torch.empty(0)\n+ MixtureOfExperts.set_eplb_state(model, empty, empty, empty)\n+\n+ registered_weight, registered_scale = model.expert_weights[0]\n+ assert registered_weight is weight\n+ assert registered_scale.dtype == torch.uint8\n+ registered_scale.fill_(127)\n+ assert torch.equal(scale.view(torch.uint8), registered_scale)\n+\n+\n @pytest.mark.skipif(not torch.cuda.is_available(), reason=\"requires CUDA\")\n def test_gloo_receive_staging_does_not_force_gpu_sync(monkeypatch):\n \"\"\"Gloo receives must reach the GPU without an implicit pageable copy.\"\"\"\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Reject LoRA at config time for models without SupportsLoRA\nLabels: bug, ready, verified\nFiles changed (6): tests/test_config.py, vllm/config/lora.py, vllm/config/model.py, vllm/model_executor/models/mamba2.py, vllm/model_executor/models/registry.py, vllm/model_executor/models/zamba2.py\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n\n- The check applies to every registered model without `SupportsLoRA` (125 architectures today), not only Zamba2 and Mamba2.\n- No behavior change for models that support LoRA, or for any model run without `enable_lora`.\n\n## Validation\n[results removed]\n## Details\n\n**Fix:** follows the existing pattern used for pipeline parallelism (`supports_pp` → `ModelConfig.is_pp_supported` → checked in `ModelConfig.verify_with_parallel_config`):\n\n- `registry.py`: record `supports_lora` in `_ModelInfo`, computed with the existing `supports_lora()` helper.\n- `config/model.py`: expose it as `ModelConfig.is_lora_supported`.\n- `config/lora.py`: raise in `LoRAConfig.verify_with_model_config`, which already runs during `VllmConfig` validation.\n- `zamba2.py`, `mamba2.py`: drop the now-unreachable asserts.\n\n**Notes for reviewers:**\n\n- No configuration that worked before is newly rejected: the runtime check calls the same `supports_lora()` on an instance of the same class, and no model sets `supports_lora` dynamically. Across all 390 loadable architectures, the class-level check also logs none of `supports_lora()`'s attribute-mismatch warnings.\n- Cached model info from older versions lacks the new field; `_ModelInfo(**cached)` then raises, which `_load_modelinfo_from_cache` already catches, so the model is re-inspected.\n- The runtime check in `LoRAModelRunnerMixin` is left in place.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/config/lora.py b/vllm/config/lora.py\nindex a77660f3b130..5eaca2b4930b 100644\n--- a/vllm/config/lora.py\n+++ b/vllm/config/lora.py\n@@ -135,6 +135,14 @@ def _validate_lora_config(self) -> Self:\n return self\n \n def verify_with_model_config(self, model_config: ModelConfig):\n+ if not model_config.is_lora_supported:\n+ raise ValueError(\n+ f\"LoRA is not supported for {model_config.architecture} \"\n+ f\"({model_config.model}). Supported models implement the \"\n+ \"`SupportsLoRA` interface. Run this model without \"\n+ \"`enable_lora`.\"\n+ )\n+\n if self.lora_dtype in (None, \"auto\"):\n self.lora_dtype = model_config.dtype\n elif isinstance(self.lora_dtype, str):\ndiff --git a/vllm/config/model.py b/vllm/config/model.py\nindex 6dc2d16d529e..4620213e529c 100644\n--- a/vllm/config/model.py\n+++ b/vllm/config/model.py\n@@ -2015,6 +2015,10 @@ def score_type(self) -> ScoreType:\n def is_pp_supported(self) -> bool:\n return self._model_info.supports_pp\n \n+ @property\n+ def is_lora_supported(self) -> bool:\n+ return self._model_info.supports_lora\n+\n @property\n def is_attention_free(self) -> bool:\n return self._model_info.is_attention_free\ndiff --git a/vllm/model_executor/models/mamba2.py b/vllm/model_executor/models/mamba2.py\nindex cb8b2b481631..7788fe22c3b2 100644\n--- a/vllm/model_executor/models/mamba2.py\n+++ b/vllm/model_executor/models/mamba2.py\n@@ -101,9 +101,6 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = \"\"):\n model_config = vllm_config.model_config\n cache_config = vllm_config.cache_config\n quant_config = vllm_config.quant_config\n- lora_config = vllm_config.lora_config\n- is_lora_enabled = bool(lora_config)\n- assert not is_lora_enabled\n \n self.config = config\n \ndiff --git a/vllm/model_executor/models/registry.py b/vllm/model_executor/models/registry.py\nindex 50280061e257..e3f1396c4d57 100644\n--- a/vllm/model_executor/models/registry.py\n+++ b/vllm/model_executor/models/registry.py\n@@ -51,6 +51,7 @@\n requires_raw_input_tokens,\n supports_hc_sp,\n supports_kv_cache_grouping,\n+ supports_lora,\n supports_multimodal,\n supports_multimodal_encoder_tp_data,\n supports_multimodal_raw_input_only,\n@@ -875,6 +876,7 @@ class _ModelInfo:\n requires_raw_input_tokens: bool\n supports_multimodal_encoder_tp_data: bool\n supports_pp: bool\n+ supports_lora: bool\n supports_hc_sp: bool\n has_inner_state: bool\n is_attention_free: bool\n@@ -906,6 +908,7 @@ def from_model_cls(model: type[nn.Module]) -> \"_ModelInfo\":\n model\n ),\n supports_pp=supports_pp(model),\n+ supports_lora=supports_lora(model),\n supports_hc_sp=supports_hc_sp(model),\n has_inner_state=has_inner_state(model),\n is_attention_free=is_attention_free(model),\ndiff --git a/vllm/model_executor/models/zamba2.py b/vllm/model_executor/models/zamba2.py\nindex 35e972818726..1a173a326334 100644\n--- a/vllm/model_executor/models/zamba2.py\n+++ b/vllm/model_executor/models/zamba2.py\n@@ -714,9 +714,6 @@ def __init__(self, *, vllm_config: VllmConfig, prefix: str = \"\") -> None:\n model_config = vllm_config.model_config\n cache_config = vllm_config.cache_config\n quant_config = vllm_config.quant_config\n- lora_config = vllm_config.lora_config\n- is_lora_enabled = bool(lora_config)\n- assert not is_lora_enabled\n \n self.config = config\n \n\ndiff --git a/tests/test_config.py b/tests/test_config.py\nindex c68ecca605ac..56f0a6763c0a 100644\n--- a/tests/test_config.py\n+++ b/tests/test_config.py\n@@ -29,6 +29,7 @@\n HiSparseConfig,\n KernelConfig,\n KVTransferConfig,\n+ LoRAConfig,\n ModelConfig,\n ObservabilityConfig,\n ParallelConfig,\n@@ -284,6 +285,27 @@ def test_kda_recoverssm_derivation_is_revalidated():\n VllmConfig.validate_mamba_cached_kernel(config)\n \n \n+@pytest.mark.parametrize(\"supported\", [True, False])\n+def test_lora_rejected_at_config_time_for_unsupported_model(supported):\n+ \"\"\"Models without SupportsLoRA must fail during config validation with a\n+ clear message, not with a bare assert inside the model constructor.\"\"\"\n+ model_config = SimpleNamespace(\n+ is_lora_supported=supported,\n+ architecture=\"Zamba2ForCausalLM\",\n+ architectures=[\"Zamba2ForCausalLM\"],\n+ model=\"Zyphra/Zamba2-1.2B-instruct\",\n+ dtype=torch.bfloat16,\n+ )\n+ lora_config = LoRAConfig()\n+ if supported:\n+ lora_config.verify_with_model_config(model_config)\n+ else:\n+ with pytest.raises(\n+ ValueError, match=\"LoRA is not supported for Zamba2ForCausalLM\"\n+ ):\n+ lora_config.verify_with_model_config(model_config)\n+\n+\n def test_mamba_cache_mode_all_is_rejected():\n \"\"\"The removed 'all' mode must fail validation instead of being ignored.\"\"\"\n with pytest.raises(ValidationError, match=\"mamba_cache_mode\"):\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][LoRA] Apply text-only LoRAs to the LM of multimodal wrappers\nLabels: bug, ready, verified\nFiles changed (2): tests/lora/test_lora_manager.py, vllm/lora/model_manager.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #48019. A LoRA trained on the text-only `*ForCausalLM` of a multimodal model silently does nothing when served on the multimodal wrapper. This resolves such adapters on the model side, in `LoRAModelManager._get_lora_layer_weights`, so it works for every multimodal wrapper without per-model mapper rules.\n\nThis builds on #49525 by @fooSynaptic (co-author), which fixes the same bug through a `WeightsMapper` fallback and only covers wrappers whose mapper has a `model.language_model.` rule. This PR covers those wrappers too, plus the ones without such a rule.\n\n## Claims\n\n- Text-named adapters (`model.layers.*` / `lm_head`) now apply to the language model of multimodal wrappers, including wrappers with no `model.language_model.` mapper rule or a different LM prefix (`llm.`, `model.text_model.`), e.g. Llama4, DeepSeek-V4, MiniCPM-V, Idefics3/SmolVLM.\n\n## Validation\n[results removed]\n## Details\n\n**Fix.** When a LoRA module has no exact match and lives under `get_mm_mapping().language_model`, look it up by its text-only name: the remainder after the prefix, or the remainder under `model.` when the prefix holds a bare decoder. All lookups, including packed (`qkv_proj`, `gate_up_proj`) and MoE packing, go through this function; text-named entries consumed by packing are dropped like the other sub-module entries.\n\n- The lookup is driven by the model's real modules, so there is no double-mapping risk (e.g. `model.language_model. -> model.` mappers) and no effect on layers owned by other PP ranks.\n- No change to base-weight loading or to any model's `hf_to_vllm_mapper`.\n- No new validation or error path, and no separate name-matching logic: the fallback lives inside the existing lookup, so any future \"adapter matches nothing\" check can reuse `_get_lora_layer_weights` and stay consistent with what is actually applied.\n\n---\n\nAI assistance (Claude Code) was used to write the patch and tests. I reviewed every changed line and ran the tests above.\n\n## Diff\n\n```diff\ndiff --git a/vllm/lora/model_manager.py b/vllm/lora/model_manager.py\nindex a7f9f02e77af..9eac678fb95b 100644\n--- a/vllm/lora/model_manager.py\n+++ b/vllm/lora/model_manager.py\n@@ -871,8 +871,7 @@ def _create_merged_loras_inplace(self, lora_model: LoRAModel) -> None:\n module_name,\n )\n )\n- for module in packed_module_names:\n- lora_model.loras.pop(module, None)\n+ self._pop_lora_weights(lora_model, packed_module_names)\n continue\n if self._is_non_gated_moe and len(replacement_loras) > 0:\n replacement_loras = self._pad_lora_pairs_to_triplets(\n@@ -891,8 +890,7 @@ def _create_merged_loras_inplace(self, lora_model: LoRAModel) -> None:\n # entries that were loaded but did not contribute to the\n # packed result. Without this they would keep extra CPU\n # memory alive after pack_moe.\n- for module in packed_module_names:\n- lora_model.loras.pop(module, None)\n+ self._pop_lora_weights(lora_model, packed_module_names)\n \n for lora in lora_model.loras.values():\n lora.optimize()\n@@ -1128,7 +1126,7 @@ def _convert_3d_to_2d_moe_lora(\n down_proj_lora.lora_b = [w1_b, down_b, w3_b]\n # Drop the redundant base_layer entry to avoid double pin_memory\n # and to keep the activation path looking up only the wrapper key.\n- lora_model.loras.pop(module_name + \".base_layer\", None)\n+ self._pop_lora_weights(lora_model, [module_name + \".base_layer\"])\n \n def _slice_moe_lora_ep(\n self,\n@@ -1224,15 +1222,57 @@ def _get_lora_layer_weights(\n if self.is_pooling_model and not lora_model.check_lora_name(module_name):\n # If it's a pool model, and the layer name is not found,\n # remove the prefix 'model.' and search again.\n- module_name = module_name.removeprefix(\"model.\")\n- if lora_model.check_lora_name(module_name):\n- org_module_name = module_name\n+ stripped_name = module_name.removeprefix(\"model.\")\n+ if lora_model.check_lora_name(stripped_name):\n+ org_module_name = stripped_name\n logger.info_once(\n \"For the pool model, successfully loaded the LoRA weights \"\n \"after removing the prefix 'model.'.\"\n )\n+ if not lora_model.check_lora_name(org_module_name):\n+ text_name = self._get_text_lora_name(lora_model, module_name)\n+ if text_name is not None:\n+ org_module_name = text_name\n return lora_model.get_lora(org_module_name)\n \n+ def _pop_lora_weights(self, lora_model: LoRAModel, module_names: list[str]) -> None:\n+ for module in module_names:\n+ lora_model.loras.pop(module, None)\n+ if text_name := self._get_text_lora_name(lora_model, module):\n+ lora_model.loras.pop(text_name)\n+\n+ def _get_text_lora_name(\n+ self, lora_model: LoRAModel, module_name: str\n+ ) -> str | None:\n+ for name in self._get_text_lora_names(module_name):\n+ if lora_model.check_lora_name(name):\n+ logger.info_once(\n+ \"Loaded text-only LoRA weights for the language model of a \"\n+ \"multimodal model.\"\n+ )\n+ return name\n+ return None\n+\n+ def _get_text_lora_names(self, module_name: str) -> list[str]:\n+ \"\"\"Names a text-only adapter uses for a language-model module.\n+\n+ Adapters trained on the text-only `*ForCausalLM` (e.g. PEFT on\n+ `Qwen3_5ForCausalLM`) name modules `model.layers.*` / `lm_head`, while\n+ multimodal wrappers mount the language model under a prefix such as\n+ `language_model.` or `llm.`. If the prefix holds a `*ForCausalLM`, the\n+ text name is the remainder; if it holds a bare decoder, it is the\n+ remainder under `model.`.\n+ \"\"\"\n+ if not getattr(self, \"supports_mm\", False):\n+ return []\n+ lm_prefix = self.mm_mapping.language_model[0].rstrip(\".\") + \".\"\n+ if not module_name.startswith(lm_prefix):\n+ return []\n+ name = module_name.removeprefix(lm_prefix)\n+ if name.startswith((\"model.\", \"lm_head\")):\n+ return [name]\n+ return [f\"model.{name}\", name]\n+\n def _get_module_to_save_weights(\n self, lora_model: LoRAModel, module_name: str\n ) -> LoRAFullModuleWeights | None:\n\ndiff --git a/tests/lora/test_lora_manager.py b/tests/lora/test_lora_manager.py\nindex ffb064ebfbdc..0d1ffdd61f51 100644\n--- a/tests/lora/test_lora_manager.py\n+++ b/tests/lora/test_lora_manager.py\n@@ -30,6 +30,7 @@\n from vllm.lora.request import LoRARequest\n from vllm.lora.worker_manager import LRUCacheWorkerLoRAManager, WorkerLoRAManager\n from vllm.model_executor.layers.fused_moe import GateLinear\n+from vllm.model_executor.models.module_mapping import MultiModelKeys\n from vllm.platforms import current_platform\n \n from .utils import create_peft_lora\n@@ -138,6 +139,46 @@ def test_from_lora_tensors(qwen3_lora_files, device):\n assert lora.lora_a.shape[0] == 8\n \n \n+@pytest.mark.parametrize(\"is_pooling_model\", [False, True])\n+@pytest.mark.parametrize(\n+ \"lm_prefix,module_name,text_name\",\n+ [\n+ (\n+ \"language_model\",\n+ \"language_model.model.layers.0.self_attn.o_proj\",\n+ \"model.layers.0.self_attn.o_proj\",\n+ ),\n+ (\"language_model\", \"language_model.lm_head\", \"lm_head\"),\n+ (\n+ \"model.text_model\",\n+ \"model.text_model.layers.0.self_attn.o_proj\",\n+ \"model.layers.0.self_attn.o_proj\",\n+ ),\n+ ],\n+)\n+def test_text_only_lora_binds_to_multimodal_language_model(\n+ lm_prefix, module_name, text_name, is_pooling_model\n+):\n+ \"\"\"An adapter trained on the text-only *ForCausalLM must apply to the\n+ language model of a multimodal wrapper instead of silently doing nothing.\"\"\"\n+ manager = LoRAModelManager.__new__(LoRAModelManager)\n+ manager.is_pooling_model = is_pooling_model\n+ manager.supports_mm = True\n+ manager.mm_mapping = MultiModelKeys.from_string_field(language_model=lm_prefix)\n+\n+ def weights(name):\n+ return LoRALayerWeights(name, 8, 16, torch.zeros(8, 4), torch.zeros(4, 8))\n+\n+ text_lora = weights(text_name)\n+ adapter = LoRAModel(1, 8, {text_name: text_lora})\n+ assert manager._get_lora_layer_weights(adapter, module_name) is text_lora\n+ assert manager._get_lora_layer_weights(adapter, \"visual.blocks.0.proj\") is None\n+\n+ exact_lora = weights(module_name)\n+ adapter = LoRAModel(1, 8, {text_name: text_lora, module_name: exact_lora})\n+ assert manager._get_lora_layer_weights(adapter, module_name) is exact_lora\n+\n+\n def create_lora(\n lora_id: int, model: nn.Module, sub_modules: list[str], device: torch.device\n ) -> LoRAModel:\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix] Honor add_generation_prompt and continue_final_message in the DeepSeek V4.1 tokenizer\nLabels: bug, ready, tool-calling, deepseek, verified, DSv4.1\nFiles changed (5): tests/parser/engine/test_deepseek_v41.py, tests/tokenizers_/test_deepseek_v41.py, vllm/parser/deepseek_v41.py, vllm/tokenizers/deepseek_v41.py, vllm/tokenizers/deepseek_v41_encoding.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #64431. Python-frontend part of #46256 on DeepSeek V4.1 (`vllm/tokenizers/deepseek_v41_encoding.py`).\n\nThe V4.1 encoder ignores `add_generation_prompt` and `continue_final_message`. When the last message is an assistant message, the prompt always ends at `<|end▁of▁sentence|>` without an `<|Assistant|>` turn prefix, so the model returns empty or garbled text with HTTP 200. With `continue_final_message=true`, the final message is still closed with EOS, so the reply cannot continue it.\n\nThis PR makes the V4.1 encoder honor both controls, and declares turn boundaries for the V4.1 parser so that the prompt-aware reasoning start from #61857 also applies to V4.1. It is the Python counterpart of the Rust-frontend fix in #62189 and uses the same semantics. The encoder change is a port of #57882 by @xijiaat (closed without review; credited as co-author of the commit) onto current `main` (after #60792, image order, and #62199, the 1017 reference encoding).\n\n**Related, not duplicates:** #62199 (merged) and #62196 (open) sync turn handling with the 1017 reference encoder (tool-result turns) and do not touch the generation controls. #62459 (open) fixes a conversation whose final message is `system`; this PR leaves that case to it and only changes conversations that end with an assistant message. #62887 (open) fixes `continue_final_message` only, by setting `wo_eos` on the final assistant message; this PR also covers `add_generation_prompt`. #64493 (draft) makes the same change for V3.2.\n\n## Claims\n\n- `add_generation_prompt=true` (the default): when the final message is an assistant message, the prompt now equals the DeepSeek reference encoding of the conversation followed by the reference assistant turn prefix, `<|Assistant|>` in thinking mode and `<|Assistant|>` in chat mode. The comparison is token-for-token. Earlier assistant messages keep their EOS.\n- `continue_final_message=true`: the final assistant message is left open (no EOS). If it ends inside its reasoning, the reasoning is left open as well. A request without a final assistant message is rejected with HTTP 400 (before, the flag was ignored and the request returned 200).\n- A final assistant message that is already left open with `wo_eos` (only possible when calling `encode_messages` directly; requests cannot set it) gets no new assistant turn, so it renders exactly as before.\n- With `turn_boundary_tokens` declared, the V4.1 parser starts in content when the current turn's prompt already closed reasoning (for example a continued answer after ``). A `` in an earlier turn does not count.\n- Fixes empty and garbled replies on DeepSeek-V4.1-Flash with the Python frontend: 210/280 empty replies before this change, 2/280 after (both remaining ones hit `max_tokens` while still reasoning).\n\n## Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/vllm/parser/deepseek_v41.py b/vllm/parser/deepseek_v41.py\nindex 76c7ad19bfd3..fb98861c4268 100644\n--- a/vllm/parser/deepseek_v41.py\n+++ b/vllm/parser/deepseek_v41.py\n@@ -20,6 +20,9 @@\n DSML_INVOKE_END = \"\"\n DSML_PARAM_START = \"<|DSML| parameter\"\n DSML_PARAM_CLOSE = \"\"\n+# Turn markers, so a prompt-closed reasoning block is only honored in the\n+# current turn (continue_final_message, or a template that skips thinking).\n+DEEPSEEK_TURN_BOUNDARY_TOKENS = frozenset({\"<|User|>\", \"<|Assistant|>\"})\n \n _PARAM_RE, _PARTIAL_PARAM_RE = _param_patterns(DSML_PARAM_START, DSML_PARAM_CLOSE)\n \n@@ -38,6 +41,7 @@ def deepseek_v41_config(thinking: bool = False) -> ParserEngineConfig:\n return replace(\n config,\n name=\"deepseek_v41\",\n+ turn_boundary_tokens=DEEPSEEK_TURN_BOUNDARY_TOKENS,\n terminals={**config.terminals, **terminal_overrides},\n token_id_terminals={\n key: terminal_overrides.get(key, value)\ndiff --git a/vllm/tokenizers/deepseek_v41.py b/vllm/tokenizers/deepseek_v41.py\nindex b628a34a8532..fecbae5e34df 100644\n--- a/vllm/tokenizers/deepseek_v41.py\n+++ b/vllm/tokenizers/deepseek_v41.py\n@@ -127,6 +127,8 @@ def apply_chat_template(\n drop_thinking=kwargs.get(\"drop_thinking\", True),\n reasoning_effort=effort,\n image_order=image_order,\n+ add_generation_prompt=kwargs.get(\"add_generation_prompt\", True),\n+ continue_final_message=kwargs.get(\"continue_final_message\", False),\n )\n if kwargs.get(\"tokenize\", True):\n tokenizer_kwargs = {\ndiff --git a/vllm/tokenizers/deepseek_v41_encoding.py b/vllm/tokenizers/deepseek_v41_encoding.py\nindex b25fe57c2b61..e6befedc9751 100644\n--- a/vllm/tokenizers/deepseek_v41_encoding.py\n+++ b/vllm/tokenizers/deepseek_v41_encoding.py\n@@ -332,6 +332,8 @@ def render_message(\n drop_thinking: bool = True,\n reasoning_effort: Union[str, int, None] = None,\n image_order: Optional[List[int]] = None,\n+ add_generation_prompt: bool = True,\n+ continue_final_message: bool = False,\n ) -> str:\n \"\"\"\n Render a single message at the given index into its V4.1 encoded string form.\n@@ -350,7 +352,8 @@ def render_message(\n response_format = msg.get(\"response_format\")\n tool_calls = msg.get(\"tool_calls\")\n reasoning_content = msg.get(\"reasoning_content\")\n- wo_eos = msg.get(\"wo_eos\", False)\n+ is_last = index == len(messages) - 1\n+ wo_eos = msg.get(\"wo_eos\", False) or (is_last and continue_final_message)\n \n # Collect source indices only from content that survives preprocessing.\n if image_order is not None:\n@@ -475,6 +478,14 @@ def render_message(\n thinking_part = (\n thinking_template.format(reasoning_content=rc) + thinking_end_token\n )\n+ if (\n+ is_last\n+ and continue_final_message\n+ and rc\n+ and not summary_content\n+ and not tc_content\n+ ):\n+ thinking_part = rc\n else:\n thinking_part = \"\"\n \n@@ -493,6 +504,10 @@ def render_message(\n else:\n raise NotImplementedError(f\"Unknown role: {role}\")\n \n+ # Historical assistant separators are needed even without a generation prompt.\n+ if is_last and not add_generation_prompt:\n+ return prompt\n+\n # Append transition tokens based on what follows\n if index + 1 < len(messages) and messages[index + 1].get(\"role\") not in [\n \"assistant\",\n@@ -521,8 +536,11 @@ def render_message(\n )\n prompt += task_sp_token\n \n- elif messages[index].get(\"role\") in [\"user\", \"developer\"] or (\n- messages[index].get(\"role\") == \"system\" and index > 0\n+ elif (\n+ messages[index].get(\"role\") in [\"user\", \"developer\"]\n+ or (messages[index].get(\"role\") == \"system\" and index > 0)\n+ # A final assistant message left open by wo_eos is not followed by a turn.\n+ or (is_last and role == \"assistant\" and not wo_eos)\n ):\n # Normal generation: append Assistant + thinking token\n # (mid-conversation system messages also trigger the assistant header)\n@@ -567,8 +585,17 @@ def encode_messages(\n add_default_bos_token: bool = True,\n reasoning_effort: Union[str, int, None] = None,\n image_order: Optional[List[int]] = None,\n+ add_generation_prompt: bool = True,\n+ continue_final_message: bool = False,\n ) -> str:\n \"\"\"Encode preprocessed (text-only) messages into the V4.1 prompt format.\"\"\"\n+ if continue_final_message:\n+ if not messages or messages[-1].get(\"role\") != \"assistant\":\n+ raise ValueError(\n+ \"continue_final_message requires a final assistant message\"\n+ )\n+ add_generation_prompt = False\n+\n context = context if context else []\n \n # Preprocess: merge tool messages and sort tool results\n@@ -603,6 +630,8 @@ def encode_messages(\n drop_thinking=effective_drop_thinking,\n reasoning_effort=reasoning_effort,\n image_order=image_order,\n+ add_generation_prompt=add_generation_prompt,\n+ continue_final_message=continue_final_message,\n )\n \n return prompt\n\ndiff --git a/tests/parser/engine/test_deepseek_v41.py b/tests/parser/engine/test_deepseek_v41.py\nindex 75ef0bf044c9..430aafb76351 100644\n--- a/tests/parser/engine/test_deepseek_v41.py\n+++ b/tests/parser/engine/test_deepseek_v41.py\n@@ -27,7 +27,7 @@\n \n \n def tokenizer_for(text, special_calls):\n- vocab = {\"\": 50, \"\": 51}\n+ vocab = {\"\": 50, \"\": 51, \"<|User|>\": 54, \"<|Assistant|>\": 55}\n if special_calls:\n vocab |= {\"<|DSML| calls>\": 52, \"\": 53}\n tokens: list[tuple[int, str]] = []\n@@ -132,6 +132,54 @@ def test_reasoning_adapter_controls_and_usage(\n assert not parser.is_reasoning_end([51, 100, 50])\n \n \n+@pytest.mark.parametrize(\"streaming\", [False, True])\n+@pytest.mark.parametrize(\n+ (\"prompt_token_ids\", \"text\", \"expected_reasoning\", \"expected_content\"),\n+ [\n+ # continue_final_message: the current turn already closed reasoning.\n+ ([54, 100, 55, 50, 101, 51, 102], \"12\", \"\", \"12\"),\n+ # A closed block in an earlier turn does not end this turn's reasoning.\n+ (\n+ [54, 100, 55, 50, 101, 51, 102, 54, 103, 55, 50],\n+ \"Plan.12\",\n+ \"Plan.\",\n+ \"12\",\n+ ),\n+ ],\n+)\n+def test_prompt_closed_reasoning_is_scoped_to_current_turn(\n+ streaming,\n+ prompt_token_ids,\n+ text,\n+ expected_reasoning,\n+ expected_content,\n+):\n+ tokenizer, tokens = tokenizer_for(text, False)\n+ parser = parser_for(tokenizer, {\"thinking\": True})\n+ output_ids = [tid for tid, _ in tokens]\n+ if streaming:\n+ output = collect_output(\n+ replay_streaming(\n+ parser,\n+ tokens,\n+ chunk_size=1,\n+ finished_on_last=True,\n+ prompt_token_ids=prompt_token_ids,\n+ )\n+ )\n+ reasoning, content = output.reasoning, output.content\n+ else:\n+ parser.set_prompt_token_ids(prompt_token_ids)\n+ reasoning, content, _ = parser.parse(\n+ text, _test_request(), model_output_token_ids=output_ids\n+ )\n+ assert (reasoning or \"\") == expected_reasoning\n+ assert content == expected_content\n+ assert (parser.reasoning_parser.count_reasoning_tokens(output_ids) == 0) == (\n+ not expected_reasoning\n+ )\n+\n+\n def test_python_argument_conversion_and_partial_values():\n converter = deepseek_v41_config().arg_converter\n assert converter is not None\ndiff --git a/tests/tokenizers_/test_deepseek_v41.py b/tests/tokenizers_/test_deepseek_v41.py\nindex 664c1c07cc52..e85a362b591d 100644\n--- a/tests/tokenizers_/test_deepseek_v41.py\n+++ b/tests/tokenizers_/test_deepseek_v41.py\n@@ -48,6 +48,9 @@ def test_reference_encoder_fixtures(case_id):\n thinking_mode = case.get(\"thinking_mode\") or \"chat\"\n expected = (FIXTURES / \"deepseek_v41\" / f\"test_output_{case_id}.txt\").read_text()\n \n+ # The reference encodes a conversation that ends with an assistant message as\n+ # closed history, which is add_generation_prompt=False here.\n+ final_assistant = messages[-1][\"role\"] == \"assistant\"\n if any(m[\"role\"] == \"latest_reminder\" for m in messages):\n # latest_reminder is not an API role.\n assert case.get(\"tools\") is None\n@@ -55,14 +58,21 @@ def test_reference_encoder_fixtures(case_id):\n messages,\n thinking_mode=thinking_mode,\n reasoning_effort=case.get(\"reasoning_effort\"),\n+ add_generation_prompt=not final_assistant,\n )\n else:\n- prompt = render(\n- messages,\n+ kwargs = dict(\n tools=case.get(\"tools\"),\n thinking=thinking_mode == \"thinking\",\n reasoning_effort=case.get(\"reasoning_effort\"),\n )\n+ prompt = render(messages, add_generation_prompt=not final_assistant, **kwargs)\n+ if final_assistant:\n+ # By default a new assistant turn follows the final assistant message.\n+ opener = \"<|Assistant|>\" + (\n+ \"\" if thinking_mode == \"thinking\" else \"\"\n+ )\n+ assert render(messages, **kwargs) == expected + opener\n assert prompt == expected\n \n \n@@ -403,3 +413,101 @@ def test_dropped_developer_only_image_leaves_text_prompt(render_with_media):\n assert \"<|deepseek_image|>\" not in prompt[\"prompt\"]\n assert \"multi_modal_data\" not in prompt\n assert \"multi_modal_uuids\" not in prompt\n+\n+\n+@pytest.mark.parametrize(\"thinking\", [False, True])\n+@pytest.mark.parametrize(\"final_role\", [\"user\", \"developer\", \"system\", \"assistant\"])\n+def test_generation_prompt_only_controls_final_turn(thinking, final_role):\n+ messages = [\n+ {\"role\": \"user\", \"content\": \"first question\"},\n+ {\"role\": \"assistant\", \"content\": \"first answer\"},\n+ {\"role\": \"user\", \"content\": \"second question\"},\n+ {\"role\": final_role, \"content\": \"final message\"},\n+ ]\n+ original = copy.deepcopy(messages)\n+ closed = render(messages, thinking=thinking, add_generation_prompt=False)\n+ opened = render(messages, thinking=thinking, add_generation_prompt=True)\n+ cue = \"<|Assistant|>\" + (\"\" if thinking else \"\")\n+\n+ assert opened == closed + cue\n+ assert \"first answer<|end▁of▁sentence|>\" in closed\n+ assert \"<|User|>first question<|Assistant|>\" in closed\n+ assert messages == original\n+\n+\n+@pytest.mark.parametrize(\"thinking\", [False, True])\n+def test_continue_final_message_preserves_historical_eos(thinking):\n+ messages = [\n+ {\"role\": \"user\", \"content\": \"first question\"},\n+ {\"role\": \"assistant\", \"content\": \"first answer\"},\n+ {\"role\": \"user\", \"content\": \"second question\"},\n+ {\"role\": \"assistant\", \"content\": \"The answer is \"},\n+ ]\n+ original = copy.deepcopy(messages)\n+ closed = render(messages, thinking=thinking, add_generation_prompt=False)\n+ continued = render(\n+ messages,\n+ thinking=thinking,\n+ add_generation_prompt=False,\n+ continue_final_message=True,\n+ )\n+ assert closed == continued + \"<|end▁of▁sentence|>\"\n+ assert continued.endswith(\"The answer is \")\n+ assert \"first answer<|end▁of▁sentence|>\" in continued\n+ assert messages == original\n+\n+\n+def test_continue_final_message_through_chat_request():\n+ request = ChatCompletionRequest(\n+ model=\"deepseek-ai/DeepSeek-V4.1-Flash\",\n+ messages=[\n+ {\"role\": \"user\", \"content\": \"Finish this sentence.\"},\n+ {\"role\": \"assistant\", \"content\": \"The answer is \"},\n+ ],\n+ continue_final_message=True,\n+ )\n+ kwargs = request.build_chat_params(None, \"auto\").get_apply_chat_template_kwargs()\n+ assert render(request.messages, **kwargs).endswith(\"The answer is \")\n+\n+\n+def test_continue_final_reasoning_keeps_thinking_open():\n+ messages = [\n+ {\"role\": \"user\", \"content\": \"Explain your answer.\"},\n+ {\"role\": \"assistant\", \"content\": None, \"reasoning\": \"Let me consider \"},\n+ ]\n+ assert render(messages, continue_final_message=True).endswith(\n+ \"<|Assistant|>Let me consider \"\n+ )\n+\n+\n+@pytest.mark.parametrize(\"thinking_mode\", [\"chat\", \"thinking\"])\n+@pytest.mark.parametrize(\n+ \"final\",\n+ [\n+ {\"content\": \"The answer is \"},\n+ {\"content\": \"\", \"reasoning_content\": \"Let me consider \"},\n+ {\"content\": \"\", \"tool_calls\": [tool_call(\"search\")]},\n+ ],\n+)\n+def test_open_final_message_gets_no_generation_prompt(thinking_mode, final):\n+ # A final assistant message left open with wo_eos is never followed by a\n+ # new assistant turn, whatever add_generation_prompt says.\n+ messages = [\n+ {\"role\": \"user\", \"content\": \"question\"},\n+ {\"role\": \"assistant\", \"wo_eos\": True, **final},\n+ ]\n+\n+ def encode(**kwargs):\n+ return encode_messages(\n+ copy.deepcopy(messages), thinking_mode=thinking_mode, **kwargs\n+ )\n+\n+ closed = encode(add_generation_prompt=False)\n+ assert not closed.endswith(\"<|end▁of▁sentence|>\")\n+ assert encode() == closed\n+\n+\n+@pytest.mark.parametrize(\"messages\", [[], [{\"role\": \"user\", \"content\": \"hello\"}]])\n+def test_continue_final_message_requires_assistant(messages):\n+ with pytest.raises(ValueError, match=\"final assistant\"):\n+ render(messages, continue_final_message=True)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Frontend] Normalize beam search scores by generated length\nLabels: bug, frontend, ready\nFiles changed (5): tests/samplers/test_beam_search_online.py, vllm/entrypoints/generate/beam_search/offline.py, vllm/entrypoints/generate/beam_search/online.py, vllm/entrypoints/generate/beam_search/utils.py, vllm/sampling_params.py\n\n## Description (results removed)\n\n## Overview\n\nBeam search divides each beam's cumulative log-prob (a sum over the *generated* tokens) by `(prompt + generated length) ** length_penalty`. It should divide by the generated length only, as Transformers does. With any non-trivial prompt, the prompt length dominates the denominator, so `length_penalty` stops having an effect and beams that hit EOS early win, often with an empty completion. This affects `LLM.beam_search` and `use_beam_search` on `/v1/completions`, `/v1/chat/completions` and speech-to-text, which all share `create_sort_beams_key_function`.\n\nFixes #2606, which was auto-closed as stale. The earlier fix in #7007 targeted the old V0 `sequence.py` and was never merged, and the bug carried over into the current frontend implementation.\n\n## Claims\n\n- Beams are ranked by `cum_logprob / num_generated_tokens ** length_penalty`, counting a terminating EOS token, as in Transformers' [`_update_finished_beams`](https://github.com/huggingface/transformers/blob/09a71e5b32a747dbc7805599457e67c956ef212f/src/transformers/generation/utils.py#L3531): `topk_log_probs / ((cur_len + 1 - decoder_prompt_len) ** length_penalty)`. Transformers fixed the same bug in huggingface/transformers#27351.\n- Beam search no longer prefers empty completions. On `tests/prompts/example.txt` without trailing newlines, the top beam on `main` is EOS-only for 8 of 8 prompts (HF: 1 of 8). With this PR it is 1 of 8.\n- HF parity improves. On the exact prompts `tests/samplers/test_beam_search.py` uses, the top beam matches HF on 8/8 prompts instead of 6/8.\n- `length_penalty` changes the result again for long prompts. On `main`, the same beam wins for every value from 0 to 2.\n- `BeamSearchParams.length_penalty` now has a docstring describing these semantics.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause.** `get_beam_search_score` divided by `len(tokens)`. `tokens` starts as the prompt (`BeamSearchInstance` and the online path's `tokens=prompt_token_ids`), but `cum_logprob` only sums generated tokens. The helper was adapted from an old Transformers `BeamHypotheses.add` that had the same bug. huggingface/transformers#27351 (v4.36) fixed it there, noting it \"would cause an unexpected bias towards generating shorter sequences\".\n\n**Why `len(x.logprobs)`.** Every path that extends or completes a beam appends exactly one logprobs entry and adds that token's log-prob to `cum_logprob`. That covers offline steps, online running beams, EOS beams and aborted beams. `tokens` can't be used, because the online path drops the EOS from `tokens` unless `include_stop_str_in_output` is set. The `max(..., 1)` guard still covers a beam aborted before generating anything.\n\n**Not changed.** Two differences from Transformers remain:\n- vLLM finalizes every EOS candidate among each beam's top `2 * beam_width` logprobs; Transformers only finalizes those in the global top `num_beams`.\n- vLLM has no early-stopping heuristic.\n\n**Related.**\n- #59506 adds overflow handling to the same function. It is orthogonal, but it needs a rebase onto the new `(num_generated_tokens, cumulative_logprob, length_penalty)` signature.\n- The Rust-frontend beam search in #47705 ports the old formula, including unit tests that encode it. The same `logprobs.len()` change applies there.\n- RFC #61880 plans to reuse `get_beam_search_score` for HF-parity scoring.\n\n**Not a duplicate.** I searched open and closed issues and PRs for `beam search length penalty`, `length_penalty`, `get_beam_search_score`, `beam search normalization` and `beam search shorter`. The only related hits are #2606, the stale V0 PR #7007, and #59506 (overflow only). I also checked every open PR touching `vllm/entrypoints/generate/beam_search/` (#59506, #60327, #60550, #52621, #36285, #60787, #49541, #47705): none changes the normalization.\n\n**AI assistance.** This PR was prepared with AI assistance (Claude Code). It helped locate the bug, write the change and test, and run the validation above. I reviewed every changed line and the results.\n\ncc @DarkLight1337\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/generate/beam_search/offline.py b/vllm/entrypoints/generate/beam_search/offline.py\nindex c109fc75c8e5..e458ba99282f 100644\n--- a/vllm/entrypoints/generate/beam_search/offline.py\n+++ b/vllm/entrypoints/generate/beam_search/offline.py\n@@ -136,7 +136,7 @@ def beam_search(\n self.llm_engine.input_processor.generation_config_fields,\n tokenizer.eos_token_id,\n )\n- sort_beams_key = create_sort_beams_key_function(eos_token_ids, length_penalty)\n+ sort_beams_key = create_sort_beams_key_function(length_penalty)\n instances: list[BeamSearchInstance] = []\n \n for lora_req, prompt, prompt_priority in zip(\ndiff --git a/vllm/entrypoints/generate/beam_search/online.py b/vllm/entrypoints/generate/beam_search/online.py\nindex 45949dd6b5f8..f353c90c8e43 100644\n--- a/vllm/entrypoints/generate/beam_search/online.py\n+++ b/vllm/entrypoints/generate/beam_search/online.py\n@@ -78,7 +78,7 @@ async def beam_search(\n self.engine_client.input_processor.generation_config_fields,\n tokenizer.eos_token_id,\n )\n- sort_beams_key = create_sort_beams_key_function(eos_token_ids, length_penalty)\n+ sort_beams_key = create_sort_beams_key_function(length_penalty)\n all_beams = [\n BeamSearchSequence(\n orig_prompt=prompt,\ndiff --git a/vllm/entrypoints/generate/beam_search/utils.py b/vllm/entrypoints/generate/beam_search/utils.py\nindex d0480420de7c..d009008cb5a0 100644\n--- a/vllm/entrypoints/generate/beam_search/utils.py\n+++ b/vllm/entrypoints/generate/beam_search/utils.py\n@@ -139,30 +139,26 @@ def __init__(\n \n \n def get_beam_search_score(\n- tokens: list[int],\n+ num_generated_tokens: int,\n cumulative_logprob: float,\n- eos_token_ids: set[int],\n length_penalty: float = 1.0,\n ) -> float:\n \"\"\"Calculate the beam search score with length penalty.\n \n- Adapted from\n+ Like Transformers, the length counts the generated tokens, including a\n+ terminating EOS token. Adapted from\n \n- https://github.com/huggingface/transformers/blob/ccb92be23def445f2afdea94c31286f84b89eb5b/src/transformers/generation/beam_search.py#L938\n+ https://github.com/huggingface/transformers/blob/09a71e5b32a747dbc7805599457e67c956ef212f/src/transformers/generation/utils.py#L3531\n \"\"\"\n- seq_len = len(tokens)\n- if tokens[-1] in eos_token_ids:\n- seq_len -= 1\n+ # An aborted beam may not have generated any tokens.\n+ return cumulative_logprob / (max(num_generated_tokens, 1) ** length_penalty)\n \n- # An aborted beam may contain only an EOS prompt token.\n- return cumulative_logprob / (max(seq_len, 1) ** length_penalty)\n \n-\n-def create_sort_beams_key_function(eos_token_ids: set[int], length_penalty: float):\n+def create_sort_beams_key_function(length_penalty: float):\n def sort_beams_key(x: BeamSearchSequence) -> float:\n- return get_beam_search_score(\n- x.tokens, x.cum_logprob, eos_token_ids, length_penalty\n- )\n+ # `logprobs` has one entry per generated token, including an EOS token\n+ # that `tokens` omits unless include_stop_str_in_output is set.\n+ return get_beam_search_score(len(x.logprobs), x.cum_logprob, length_penalty)\n \n return sort_beams_key\n \ndiff --git a/vllm/sampling_params.py b/vllm/sampling_params.py\nindex a0ff63615566..466c19e6bb74 100644\n--- a/vllm/sampling_params.py\n+++ b/vllm/sampling_params.py\n@@ -1506,6 +1506,9 @@ class BeamSearchParams(\n ignore_eos: bool = False\n temperature: float = 0.0\n length_penalty: float = 1.0\n+ \"\"\"Exponent on the number of generated tokens (including a final EOS) that\n+ normalizes a beam's cumulative log-probability when ranking beams, as in\n+ Transformers. Values above 0 favor longer beams, below 0 shorter ones.\"\"\"\n include_stop_str_in_output: bool = False\n structured_outputs: StructuredOutputsParams | None = None\n skip_special_tokens: bool = True\n\ndiff --git a/tests/samplers/test_beam_search_online.py b/tests/samplers/test_beam_search_online.py\nindex 9afda98eff3b..2381f6b8da57 100644\n--- a/tests/samplers/test_beam_search_online.py\n+++ b/tests/samplers/test_beam_search_online.py\n@@ -211,6 +211,63 @@ async def generate(engine_prompt, sampling_params, *args, **kwargs):\n assert all(not p.stop_token_ids for p in engine_params)\n \n \n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\"offline\", [False, True])\n+async def test_beam_search_score_ignores_prompt_length(\n+ monkeypatch, offline: bool\n+) -> None:\n+ \"\"\"Beams are ranked by generated length only, as in Transformers.\"\"\"\n+ [comment with results removed]\n+ prompt_len = 50\n+ prompt: TokensInput = {\"type\": \"token\", \"prompt_token_ids\": [1] * prompt_len}\n+ params = BeamSearchParams(\n+ beam_width=1, max_tokens=2, length_penalty=1.0, watermarking=False\n+ )\n+ eos = _Tokenizer.eos_token_id\n+ # Mean logprobs: [eos] -1.0, [11, eos] -0.85, [11, 11] -0.8.\n+ results = []\n+ for logprobs in (\n+ {eos: Logprob(-1.0), 11: Logprob(-1.5)},\n+ {11: Logprob(-0.1), eos: Logprob(-0.2)},\n+ ):\n+ result = await anext(\n+ _EngineClient().generate(prompt, SamplingParams(watermarking=False))\n+ )\n+ result.outputs[0].logprobs = [logprobs]\n+ results.append(result)\n+\n+ def step_result(engine_prompt) -> RequestOutput:\n+ return results[len(engine_prompt[\"prompt_token_ids\"]) - prompt_len]\n+\n+ if offline:\n+ offline_serving = _OfflineServing()\n+ monkeypatch.setattr(\n+ _OfflineServing,\n+ \"_beam_search_step\",\n+ BeamSearchOfflineMixin._beam_search_step,\n+ )\n+\n+ def render_and_run_requests(*, prompts, **kwargs):\n+ return [step_result(p) for p in prompts]\n+\n+ monkeypatch.setattr(\n+ offline_serving, \"_render_and_run_requests\", render_and_run_requests\n+ )\n+ beam = offline_serving.beam_search(cast(list, [prompt]), params)[0].sequences[0]\n+ assert beam.tokens[prompt_len:] == [11, 11]\n+ else:\n+\n+ async def generate(engine_prompt, *args, **kwargs):\n+ yield step_result(engine_prompt)\n+\n+ online_serving = _AsyncServing()\n+ monkeypatch.setattr(online_serving.engine_client, \"generate\", generate)\n+ output = (\n+ await anext(online_serving.beam_search(prompt, \"request\", params))\n+ ).outputs[0]\n+ assert output.token_ids == [11, 11]\n+\n+\n @pytest.mark.asyncio\n @pytest.mark.parametrize(\"priority\", [None, -9, 12])\n async def test_beam_search_preserves_priority_for_every_step(monkeypatch, priority):\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Frontend] Honor token ID logprob overrides on derender paths\nLabels: bug, documentation, frontend, ready\nFiles changed (14): docs/serving/online_serving/derenderer.md, docs/serving/online_serving/token_in_token_out.md, tests/entrypoints/scale_out/derender/test_derender.py, tests/entrypoints/scale_out/derender/test_derender_stream.py, tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py, tests/entrypoints/scale_out/render/test_render.py, tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py, tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py, vllm/entrypoints/launchers/api_server/app_state.py, vllm/entrypoints/launchers/render/app_state.py, vllm/entrypoints/scale_out/render/serving.py, vllm/entrypoints/scale_out/token_in_token_out/protocol.py, vllm/entrypoints/scale_out/token_in_token_out/serving.py, vllm/renderers/online_derenderer.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #63162: honor the tri-state `return_tokens_as_token_ids` override on both disaggregated derender paths, including generate streaming after merged #63103.\n\n## Claims\n\n- Explicit request true/false overrides the answering server's flag; omitted/null falls back to that server's setting.\n- `/render` omits the new context key when null, preserving legacy generate compatibility for default requests. Explicit overrides require an upgraded generate node.\n\n## Validation\n[results removed]\n## Details\n\nThe request override was dropped at render serialization, generate used only its server flag, and separate derender always decoded. A nullable `ParseContext` field preserves explicit false; field-level null omission prevents adding an unknown key for older generate nodes. Each answering path resolves the override against its own server default. Placeholder formatting reuses the existing helper; decoded logprobs retain the existing decoder and UTF-8 fallback repair.\n\nDuplicate searches found only this PR and merged #60082/#63103; neither merged feature includes this request-override fix. The affected logprobs docs explain precedence and rolling upgrade behavior. AI assistance was used for implementation, tests, documentation and review preparation.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/launchers/api_server/app_state.py b/vllm/entrypoints/launchers/api_server/app_state.py\nindex 682e5882204e..949a0b0977a2 100644\n--- a/vllm/entrypoints/launchers/api_server/app_state.py\n+++ b/vllm/entrypoints/launchers/api_server/app_state.py\n@@ -119,6 +119,7 @@ async def init_app_state(\n default_chat_template_kwargs=default_chat_template_kwargs,\n reasoning_effort_map=args.reasoning_effort_map,\n log_error_stack=args.log_error_stack,\n+ return_tokens_as_token_ids=args.return_tokens_as_token_ids,\n )\n \n state.serving_tokenization = ServingTokenization(\ndiff --git a/vllm/entrypoints/launchers/render/app_state.py b/vllm/entrypoints/launchers/render/app_state.py\nindex 3152d354e363..4a4e13d0497b 100644\n--- a/vllm/entrypoints/launchers/render/app_state.py\n+++ b/vllm/entrypoints/launchers/render/app_state.py\n@@ -94,6 +94,7 @@ async def init_render_app_state(\n default_chat_template_kwargs=default_chat_template_kwargs,\n reasoning_effort_map=args.reasoning_effort_map,\n log_error_stack=args.log_error_stack,\n+ return_tokens_as_token_ids=args.return_tokens_as_token_ids,\n )\n \n state.openai_serving_models = model_registry\ndiff --git a/vllm/entrypoints/scale_out/render/serving.py b/vllm/entrypoints/scale_out/render/serving.py\nindex f64562538bb8..d72cc05ae7ad 100644\n--- a/vllm/entrypoints/scale_out/render/serving.py\n+++ b/vllm/entrypoints/scale_out/render/serving.py\n@@ -233,6 +233,7 @@ def _build_parse_context(\n tool_choice=request.tool_choice,\n parallel_tool_calls=request.parallel_tool_calls,\n include_reasoning=request.include_reasoning,\n+ return_tokens_as_token_ids=request.return_tokens_as_token_ids,\n # Like the derenderer, Harmony output is parsed without template\n # kwargs.\n chat_template_kwargs=(\ndiff --git a/vllm/entrypoints/scale_out/token_in_token_out/protocol.py b/vllm/entrypoints/scale_out/token_in_token_out/protocol.py\nindex e0c30ddce01b..83fceac173b4 100644\n--- a/vllm/entrypoints/scale_out/token_in_token_out/protocol.py\n+++ b/vllm/entrypoints/scale_out/token_in_token_out/protocol.py\n@@ -68,6 +68,9 @@ class ParseContext(BaseModel):\n ) = \"none\"\n parallel_tool_calls: bool | None = True\n include_reasoning: bool = True\n+ return_tokens_as_token_ids: bool | None = Field(\n+ default=None, exclude_if=lambda value: value is None\n+ )\n chat_template_kwargs: dict[str, JsonValue] = Field(default_factory=dict)\n \"\"\"Template kwargs with the render server's defaults already applied,\n without the API server only entries a handler keeps out of the engine.\"\"\"\ndiff --git a/vllm/entrypoints/scale_out/token_in_token_out/serving.py b/vllm/entrypoints/scale_out/token_in_token_out/serving.py\nindex 1f4af4ad9b83..8a733e069ea6 100644\n--- a/vllm/entrypoints/scale_out/token_in_token_out/serving.py\n+++ b/vllm/entrypoints/scale_out/token_in_token_out/serving.py\n@@ -471,7 +471,7 @@ async def serve_tokens_full_generator(\n sampling_params: SamplingParams = request.sampling_params\n derender_mode = request.output_mode == \"derender\"\n text_mode = request.output_mode == \"text\" or derender_mode\n- tokenizer = self._logprobs_tokenizer(text_mode)\n+ tokenizer = self._logprobs_tokenizer(request, text_mode)\n num_logprobs, top_limit = self._logprob_settings(sampling_params, derender_mode)\n \n try:\n@@ -693,7 +693,7 @@ async def serve_tokens_stream_generator(\n derender_mode = request.output_mode == \"derender\"\n assert derender_mode == (processors is not None)\n text_mode = request.output_mode == \"text\" or derender_mode\n- tokenizer = self._logprobs_tokenizer(text_mode)\n+ tokenizer = self._logprobs_tokenizer(request, text_mode)\n num_logprobs, top_limit = self._logprob_settings(sampling_params, derender_mode)\n response_cls = _STREAM_RESPONSE_CLS[request.output_mode]\n role_sent = [False] * sampling_params.n\n@@ -902,13 +902,16 @@ def _logprob_settings(\n )\n return sampling_params.logprobs, None\n \n- def _logprobs_tokenizer(self, text_mode: bool) -> TokenizerLike | None:\n- \"\"\"Tokenizer that resolves logprob tokens, or None for placeholders.\n-\n- ``--return-tokens-as-token-ids`` keeps placeholders at every level, as\n- it does on ``/v1/completions``.\n- \"\"\"\n- if not text_mode or self.return_tokens_as_token_ids:\n+ def _logprobs_tokenizer(\n+ self, request: GenerateRequest, text_mode: bool\n+ ) -> TokenizerLike | None:\n+ \"\"\"Tokenizer that resolves logprob tokens, or None for placeholders.\"\"\"\n+ return_tokens_as_token_ids = self.return_tokens_as_token_ids\n+ if request.output_mode == \"derender\" and request.parse_context is not None:\n+ override = request.parse_context.return_tokens_as_token_ids\n+ if override is not None:\n+ return_tokens_as_token_ids = override\n+ if not text_mode or return_tokens_as_token_ids:\n return None\n return self.renderer.tokenizer\n \ndiff --git a/vllm/renderers/online_derenderer.py b/vllm/renderers/online_derenderer.py\nindex 2816ffc22db9..e57f432e4212 100644\n--- a/vllm/renderers/online_derenderer.py\n+++ b/vllm/renderers/online_derenderer.py\n@@ -11,6 +11,7 @@\n chat_top_logprobs_limit,\n completion_top_logprobs_limit,\n decode_token_ids,\n+ format_token_id_placeholder,\n )\n from vllm.entrypoints.openai.chat_completion.message_assembly import (\n assemble_chat_message_fields,\n@@ -85,10 +86,12 @@ def __init__(\n default_chat_template_kwargs: dict[str, Any] | None = None,\n reasoning_effort_map: dict[str, str] | None = None,\n log_error_stack: bool = False,\n+ return_tokens_as_token_ids: bool = False,\n ) -> None:\n self.model_config = model_config\n self.renderer = renderer\n self.request_logger = request_logger\n+ self.return_tokens_as_token_ids = return_tokens_as_token_ids\n \n # EOS ids the engine stops on, loaded once like InputProcessor does.\n self._eos_token_id = renderer.get_eos_token_id()\n@@ -200,6 +203,13 @@ def _drop_stop_token(\n return token_ids, stop_reason\n return token_ids[:-1], stop_reason\n \n+ def _return_tokens_as_token_ids(\n+ self, request: ChatCompletionRequest | CompletionRequest | None\n+ ) -> bool:\n+ if request is not None and request.return_tokens_as_token_ids is not None:\n+ return request.return_tokens_as_token_ids\n+ return self.return_tokens_as_token_ids\n+\n def _decode_output(\n self,\n tokenizer: TokenizerLike,\n@@ -303,6 +313,7 @@ def _derender_chat(\n and not hide_metadata\n )\n top_limit = _chat_top_logprobs_limit(chat_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(chat_request)\n \n for choice in generate_response.choices:\n if not choice.token_ids:\n@@ -313,6 +324,7 @@ def _derender_chat(\n choice.logprobs,\n tokenizer,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n if choice.logprobs is not None and not hide_metadata\n else None\n@@ -701,6 +713,7 @@ async def derender_chat_stream(\n \n return_token_ids = chat_request is not None and chat_request.return_token_ids\n top_limit = _chat_top_logprobs_limit(chat_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(chat_request)\n for choice in generate_chunk.choices:\n delta_tids = choice.token_ids or []\n text_tids, stop_reason = self._drop_stop_token(\n@@ -721,6 +734,7 @@ async def derender_chat_stream(\n tokenizer,\n initial_context_token_ids=state.logprob_context_token_ids,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n \n include_role = not updated_state.role_sent\n@@ -804,6 +818,7 @@ def _derender_chat_stream_parsed(\n \"\"\"\n tokenizer = self.renderer.get_tokenizer()\n top_limit = _chat_top_logprobs_limit(chat_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(chat_request)\n \n processor = ChatStreamProcessor(\n chat_request,\n@@ -908,6 +923,7 @@ def _replay(token_ids: list[int], chunk_lens: list[int]) -> None:\n tokenizer,\n initial_context_token_ids=state.logprob_context_token_ids,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n logprob_context = _logprob_context_tail(\n state.logprob_context_token_ids, delta_tids\n@@ -1006,6 +1022,9 @@ def _derender_completion(\n total_completion_tokens = 0\n index = 0\n top_limit = _completion_top_logprobs_limit(completion_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(\n+ completion_request\n+ )\n return_token_ids = (\n completion_request is not None and completion_request.return_token_ids\n )\n@@ -1045,6 +1064,7 @@ def _derender_completion(\n choice.logprobs,\n tokenizer,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n completion_logprobs = _convert_chat_logprobs_to_completion_logprobs(\n resolved, choice.logprobs\n@@ -1126,6 +1146,9 @@ async def derender_completion_stream(\n updated_state = state\n \n top_limit = _completion_top_logprobs_limit(completion_request)\n+ return_tokens_as_token_ids = self._return_tokens_as_token_ids(\n+ completion_request\n+ )\n return_token_ids = (\n completion_request is not None and completion_request.return_token_ids\n )\n@@ -1149,6 +1172,7 @@ async def derender_completion_stream(\n tokenizer,\n initial_context_token_ids=state.logprob_context_token_ids,\n top_limit=top_limit,\n+ return_tokens_as_token_ids=return_tokens_as_token_ids,\n )\n completion_logprobs = _convert_chat_logprobs_to_completion_logprobs(\n resolved,\n@@ -1414,6 +1438,7 @@ def _resolve_logprobs(\n tokenizer: TokenizerLike,\n initial_context_token_ids: Sequence[int] = (),\n top_limit: int | None = None,\n+ return_tokens_as_token_ids: bool = False,\n ) -> ChatCompletionLogProbs:\n \"\"\"Convert generate's integer-id logprobs to the OpenAI chat shape.\n \n@@ -1440,10 +1465,13 @@ def _resolve_logprobs(\n entry.top_logprobs if top_limit is None else entry.top_logprobs[:top_limit]\n )\n # One batch per position: the sampled id and its kept top-k ids.\n- (token_str, token_bytes), *top_decoded = decode_token_ids(\n- [entry.token_id, *(top.token_id for top in top_entries)],\n- tokenizer,\n+ token_ids = [entry.token_id, *(top.token_id for top in top_entries)]\n+ decoded = (\n+ [(format_token_id_placeholder(tid), None) for tid in token_ids]\n+ if return_tokens_as_token_ids\n+ else decode_token_ids(token_ids, tokenizer)\n )\n+ (token_str, token_bytes), *top_decoded = decoded\n \n if token_str.endswith(\"\\ufffd\"):\n token_str = _correct_decoded_token(\n\n[2 documentation file diff(s) omitted]\ndiff --git a/tests/entrypoints/scale_out/derender/test_derender.py b/tests/entrypoints/scale_out/derender/test_derender.py\nindex c457245d3df4..64bf9c216747 100644\n--- a/tests/entrypoints/scale_out/derender/test_derender.py\n+++ b/tests/entrypoints/scale_out/derender/test_derender.py\n@@ -25,8 +25,9 @@\n \n \n @pytest.fixture(scope=\"module\")\n-def server():\n- with RemoteLaunchRenderServer(MODEL_NAME, []) as remote_server:\n+def server(request):\n+ args = getattr(request, \"param\", [])\n+ with RemoteLaunchRenderServer(MODEL_NAME, args) as remote_server:\n yield remote_server\n \n \n@@ -1970,3 +1971,54 @@ async def test_derender_completion_preserves_requested_token_ids(\n )\n assert choices[0].token_ids == (token_ids if return_token_ids else None)\n assert choices[0].prompt_token_ids == (prompt_ids if return_token_ids else None)\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\n+ (\"server\", \"server_flag\"),\n+ [([], False), ([\"--return-tokens-as-token-ids\"], True)],\n+ indirect=[\"server\"],\n+ scope=\"module\",\n+)\n+@pytest.mark.parametrize(\"endpoint\", [\"chat\", \"completion\"])\n+@pytest.mark.parametrize(\"override\", [None, False, True])\n+async def test_derender_logprob_override(\n+ client, tokenizer, server_flag, endpoint, override\n+):\n+ \"\"\"An explicit false must override a true render-server default.\"\"\"\n+ token_id = tokenizer.convert_tokens_to_ids(\"▁true\")\n+ logprobs = _make_generate_logprobs(token_id)\n+ logprobs[\"content\"][0][\"top_logprobs\"][0][\"token_id\"] = token_id\n+ generated = _make_generate_response(\n+ [token_id], finish_reason=\"length\", logprobs=logprobs\n+ )\n+ original = (\n+ {\"messages\": [], \"logprobs\": True, \"top_logprobs\": 1}\n+ if endpoint == \"chat\"\n+ else {\"prompt\": \"Hi\", \"logprobs\": 1}\n+ )\n+ if override is not None:\n+ original[\"return_tokens_as_token_ids\"] = override\n+ payload = (\n+ {\"chat_request\": original, \"generate_response\": generated}\n+ if endpoint == \"chat\"\n+ else {\"completion_request\": original, \"generate_responses\": [generated]}\n+ )\n+ response = await client.post(\n+ f\"/v1/{'chat/completions' if endpoint == 'chat' else 'completions'}/derender\",\n+ json=payload,\n+ )\n+ response.raise_for_status()\n+ placeholders = server_flag if override is None else override\n+ expected = f\"token_id:{token_id}\" if placeholders else \" true\"\n+ choice = response.json()[\"choices\"][0]\n+ if endpoint == \"chat\":\n+ entry = choice[\"logprobs\"][\"content\"][0]\n+ assert (entry[\"token\"], entry[\"bytes\"]) == (\n+ expected,\n+ None if placeholders else list(b\" true\"),\n+ )\n+ assert entry[\"top_logprobs\"][0][\"token\"] == expected\n+ else:\n+ assert choice[\"logprobs\"][\"tokens\"] == [expected]\n+ assert choice[\"logprobs\"][\"top_logprobs\"] == [{expected: -2.0}]\ndiff --git a/tests/entrypoints/scale_out/derender/test_derender_stream.py b/tests/entrypoints/scale_out/derender/test_derender_stream.py\nindex a002279a9826..893aaa17365e 100644\n--- a/tests/entrypoints/scale_out/derender/test_derender_stream.py\n+++ b/tests/entrypoints/scale_out/derender/test_derender_stream.py\n@@ -2263,8 +2263,9 @@ async def test_too_many_choices_rejected(self):\n \n \n @pytest.fixture(scope=\"module\")\n-def server():\n- with RemoteLaunchRenderServer(MODEL_NAME, []) as remote_server:\n+def server(request):\n+ args = getattr(request, \"param\", [])\n+ with RemoteLaunchRenderServer(MODEL_NAME, args) as remote_server:\n yield remote_server\n \n \n@@ -2833,3 +2834,66 @@ async def test_stream_parsed_missing_prompt_token_ids_rejected(parser_client):\n )\n assert resp.status_code == 400\n assert \"prompt_token_ids\" in resp.json()[\"error\"][\"message\"]\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\n+ (\"endpoint\", \"server\", \"server_flag\"),\n+ [\n+ (endpoint, args, flag)\n+ for endpoint in (\"chat\", \"parsed\", \"completion\")\n+ for flag in (False, True)\n+ for args in [\n+ ([\"--return-tokens-as-token-ids\"] if flag else [])\n+ + (\n+ [\"--tool-call-parser\", \"hermes\", \"--enable-auto-tool-choice\"]\n+ if endpoint == \"parsed\"\n+ else []\n+ )\n+ ]\n+ ],\n+ indirect=[\"server\"],\n+ scope=\"module\",\n+)\n+@pytest.mark.parametrize(\"override\", [None, False, True])\n+async def test_streaming_derender_logprob_override(\n+ client, tokenizer, server_flag, endpoint, override\n+):\n+ \"\"\"Plain/parsed chat and completion chunks honor the request override.\"\"\"\n+ token_id = tokenizer.convert_tokens_to_ids(\"▁true\")\n+ logprobs = _generate_logprobs([token_id])\n+ logprobs[\"content\"][0][\"top_logprobs\"] = [{\"token_id\": token_id, \"logprob\": -0.5}]\n+ chunk = _make_stream_chunk(\n+ [token_id], finish_reason=\"length\", logprobs=logprobs\n+ ).model_dump(mode=\"json\")\n+ chat = endpoint != \"completion\"\n+ original = (\n+ {\"messages\": [], \"logprobs\": True, \"top_logprobs\": 1}\n+ if chat\n+ else {\"prompt\": \"Hi\", \"logprobs\": 1}\n+ )\n+ if override is not None:\n+ original[\"return_tokens_as_token_ids\"] = override\n+ response = await client.post(\n+ f\"/v1/{'chat/completions' if chat else 'completions'}/derender\",\n+ json={\n+ \"stream\": True,\n+ \"prompt_token_ids\": tokenizer.encode(\"Hi\"),\n+ \"generate_chunk\": chunk,\n+ \"chat_request\" if chat else \"completion_request\": original,\n+ },\n+ )\n+ response.raise_for_status()\n+ placeholders = server_flag if override is None else override\n+ expected = f\"token_id:{token_id}\" if placeholders else \" true\"\n+ choice = response.json()[\"chunk\"][\"choices\"][0]\n+ if chat:\n+ entry = choice[\"logprobs\"][\"content\"][0]\n+ assert (entry[\"token\"], entry[\"bytes\"]) == (\n+ expected,\n+ None if placeholders else list(b\" true\"),\n+ )\n+ assert entry[\"top_logprobs\"][0][\"token\"] == expected\n+ else:\n+ assert choice[\"logprobs\"][\"tokens\"] == [expected]\n+ assert choice[\"logprobs\"][\"top_logprobs\"] == [{expected: -0.5}]\ndiff --git a/tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py b/tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py\nindex 47153f4099ad..a889adccffcf 100644\n--- a/tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py\n+++ b/tests/entrypoints/scale_out/derender/test_generate_logprobs_conversion.py\n@@ -170,3 +170,25 @@ def test_unknown_top_id_does_not_shift_the_other_candidates():\n (\"\", None),\n (\"ok\", list(b\"ok\")),\n ]\n+\n+\n+def test_token_id_placeholders_preserve_sampled_and_top_logprobs():\n+ logprobs = GenerateLogProbs(\n+ content=[\n+ GenerateLogProbsContent(\n+ token_id=SECOND_BYTE,\n+ logprob=-0.5,\n+ top_logprobs=[\n+ GenerateLogProb(token_id=FIRST_BYTE, logprob=-1.5),\n+ ],\n+ )\n+ ]\n+ )\n+ resolved = _resolve_logprobs(\n+ logprobs, _StubTokenizer(), return_tokens_as_token_ids=True\n+ )\n+ entry = resolved.content[0]\n+ assert (entry.token, entry.bytes, entry.logprob) == (\"token_id:11\", None, -0.5)\n+ assert [(top.token, top.bytes, top.logprob) for top in entry.top_logprobs] == [\n+ (\"token_id:10\", None, -1.5)\n+ ]\ndiff --git a/tests/entrypoints/scale_out/render/test_render.py b/tests/entrypoints/scale_out/render/test_render.py\nindex b3be5fa8dc76..1807b0ae73d6 100644\n--- a/tests/entrypoints/scale_out/render/test_render.py\n+++ b/tests/entrypoints/scale_out/render/test_render.py\n@@ -1184,3 +1184,19 @@ async def test_messages_render_tool_search_result_for_deepseek_v41(\n \"<|User|>get_weather\\n\\n\"\n \"notes<|Assistant|>\"\n ) in detokenize.json()[\"prompt\"]\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\"override\", [\"omitted\", None, False, True])\n+async def test_render_omits_null_token_id_override(client, override):\n+ \"\"\"Default requests must not send a new field to older generate nodes.\"\"\"\n+ body = {\"model\": MODEL_NAME, \"messages\": [{\"role\": \"user\", \"content\": \"Hi\"}]}\n+ if override != \"omitted\":\n+ body[\"return_tokens_as_token_ids\"] = override\n+ response = await client.post(\"/v1/chat/completions/render\", json=body)\n+ response.raise_for_status()\n+ context = response.json()[\"parse_context\"]\n+ if override is None or override == \"omitted\":\n+ assert \"return_tokens_as_token_ids\" not in context\n+ else:\n+ assert context[\"return_tokens_as_token_ids\"] is override\ndiff --git a/tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py b/tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py\nindex 4ac47ef11125..98bea6880abd 100644\n--- a/tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py\n+++ b/tests/entrypoints/scale_out/token_in_token_out/test_generate_stream.py\n@@ -1590,10 +1590,10 @@ def set_history_tool_call_count(self, count):\n self.history_tool_call_cnt = count\n \n \n-def _derender_serving(engine, parser_cls=_StubParser):\n+def _derender_serving(engine, parser_cls=_StubParser, **kwargs):\n \"\"\"Serving whose derenderer builds real stream processors around\n `parser_cls`, or plain ones when it is None.\"\"\"\n- serving = _build_serving_tokens(engine)\n+ serving = _build_serving_tokens(engine, **kwargs)\n derenderer = serving.online_derenderer\n derenderer.parser = parser_cls\n derenderer.enable_auto_tools = False\n@@ -1878,3 +1878,46 @@ async def mock_generate(*args, **kwargs):\n .delta.content\n == \"a\"\n )\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\"server_flag\", [False, True])\n+@pytest.mark.parametrize(\"override\", [None, False, True])\n+async def test_stream_derender_logprob_request_override(server_flag, override):\n+ engine = _mock_engine()\n+\n+ async def mock_generate(*args, **kwargs):\n+ yield _make_request_output(\n+ \"req-1\",\n+ token_ids=[10],\n+ text=\"é\",\n+ finish_reason=\"length\",\n+ finished=True,\n+ logprobs=[\n+ {\n+ 10: Logprob(logprob=-0.5, decoded_token=\"é\"),\n+ 11: Logprob(logprob=-1.5, decoded_token=\"e\"),\n+ }\n+ ],\n+ )\n+\n+ engine.generate = MagicMock(side_effect=mock_generate)\n+ serving = _derender_serving(engine, return_tokens_as_token_ids=server_flag)\n+ request = _derender_request(ParseContext(return_tokens_as_token_ids=override))\n+ request.sampling_params.logprobs = 2\n+ parsed = await _collect_sse(await serving.serve_tokens(request))\n+\n+ chunk = parsed[0]\n+ assert chunk[\"output_mode\"] == \"derender\"\n+ choice = chunk[\"choices\"][0]\n+ assert choice[\"delta\"][\"content\"] == \"é\"\n+ entry = choice[\"logprobs\"][\"content\"][0]\n+ placeholders = server_flag if override is None else override\n+ assert (entry[\"token\"], entry[\"bytes\"]) == (\n+ (\"token_id:10\", None) if placeholders else (\"é\", [195, 169])\n+ )\n+ assert [(top[\"token\"], top[\"bytes\"]) for top in entry[\"top_logprobs\"]] == (\n+ [(\"token_id:10\", None), (\"token_id:11\", None)]\n+ if placeholders\n+ else [(\"é\", [195, 169]), (\"e\", [101])]\n+ )\ndiff --git a/tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py b/tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py\nindex c236f5f31eff..f4eb15912194 100644\n--- a/tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py\n+++ b/tests/entrypoints/scale_out/token_in_token_out/test_serving_tokens.py\n@@ -923,3 +923,73 @@ async def test_abort_requests_is_served_without_tokens_only(client):\n \"/abort_requests\", json={\"request_ids\": [\"generate-tokens-unknown\"]}\n )\n assert resp.status_code == 404\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.skipif(\n+ envs.VLLM_USE_RUST_FRONTEND,\n+ reason=\"The Rust frontend does not support /render\",\n+)\n+@pytest.mark.parametrize(\n+ (\"server\", \"server_flag\"),\n+ [\n+ ([\"--gpu-memory-utilization\", \"0.3\"], False),\n+ ([\"--gpu-memory-utilization\", \"0.3\", \"--return-tokens-as-token-ids\"], True),\n+ ],\n+ indirect=[\"server\"],\n+ scope=\"module\",\n+)\n+async def test_derender_logprob_request_override(client, server_flag):\n+ \"\"\"Both derender routes must use the same tri-state override as coupled chat.\"\"\"\n+ for override in (None, False, True):\n+ request = {\n+ \"model\": MODEL_NAME,\n+ \"messages\": [{\"role\": \"user\", \"content\": \"Hi\"}],\n+ \"max_completion_tokens\": 2,\n+ \"temperature\": 0,\n+ \"logprobs\": True,\n+ \"top_logprobs\": 2,\n+ }\n+ if override is not None:\n+ request[\"return_tokens_as_token_ids\"] = override\n+ coupled = await client.post(\"/v1/chat/completions\", json=request)\n+ assert coupled.status_code == 200, coupled.text\n+ expected = coupled.json()[\"choices\"][0][\"logprobs\"]\n+ assert expected and expected[\"content\"]\n+ placeholders = server_flag if override is None else override\n+ if placeholders:\n+ # Both derender paths keep generate text mode's null bytes\n+ # for placeholders; coupled chat currently includes bytes.\n+ # Normalize only that existing representation difference.\n+ for entry in expected[\"content\"]:\n+ entry[\"bytes\"] = None\n+ for top in entry[\"top_logprobs\"]:\n+ top[\"bytes\"] = None\n+ # Separate requests can differ slightly in floating-point logprobs.\n+ # Keep token strings, bytes and the remaining structure exact.\n+ for entry in expected[\"content\"]:\n+ entry[\"logprob\"] = pytest.approx(entry[\"logprob\"], abs=1e-3)\n+ for top in entry[\"top_logprobs\"]:\n+ top[\"logprob\"] = pytest.approx(top[\"logprob\"], abs=1e-3)\n+ rendered = await client.post(\"/v1/chat/completions/render\", json=request)\n+ assert rendered.status_code == 200, rendered.text\n+ payload = rendered.json()\n+ for mode in (\"derender\", \"tokens\"):\n+ generated = await client.post(\n+ \"/inference/v1/generate\", json={**payload, \"output_mode\": mode}\n+ )\n+ assert generated.status_code == 200, generated.text\n+ result = generated.json()\n+ if mode == \"tokens\":\n+ derendered = await client.post(\n+ \"/v1/chat/completions/derender\",\n+ json={\n+ \"model\": MODEL_NAME,\n+ \"chat_request\": request,\n+ \"prompt_token_ids\": payload[\"token_ids\"],\n+ \"generate_response\": result,\n+ },\n+ )\n+ assert derendered.status_code == 200, derendered.text\n+ result = derendered.json()\n+ assert result[\"choices\"][0][\"logprobs\"] == expected\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Tool Parser] Parse bare FunctionGemma arguments and stream them as valid JSON\nLabels: bug, ready, tool-calling, verified\nFiles changed (3): tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py, tests/tool_parsers/test_functiongemma_tool_parser.py, vllm/tool_parsers/functiongemma_tool_parser.py\n\n## Description (results removed)\n\n## Overview\n\nFix the `functiongemma` tool parser dropping every non-string argument, and make its streamed arguments reassemble into valid JSON. Fixes #63983.\n\n## Claims\n\n- Bare booleans, numbers, `null`, arrays and objects are parsed in streaming and non-streaming, nested containers included.\n- Streamed deltas of a multi-argument call concatenate to one JSON object.\n- A streamed call still gets closed when its end tag shares a delta with the next call's start tag.\n- A streamed call with no arguments sends `{}` instead of an empty string.\n\n## Validation\n[results removed]\n## Details\n\nThe template's `format_argument` macro wraps only strings in ``, e.g. `enabled:true,hour:7,days:[mon],snooze:{minutes:5}`. The old `arg_regex` only matched `key:...`, so bare values were dropped. A small recursive parser for that grammar replaces it. With `partial=True` (streaming) it stops at the first incomplete value, so each value is streamed once in its final form. A bare word that is not a JSON literal stays a string.\n\nStreaming diffs are computed by length against `json.dumps(args)`, so the closing brace is held back until the call ends. That left two gaps, both fixed here. When an end tag and the next start tag arrive together, the start branch returned before closing the earlier call, so it never got its brace, or any arguments if they were still unsent. A call with no arguments streamed nothing because the end branch skipped empty arguments. Both paths now go through `_close_tool_call`. Deltas can merge when the client falls behind the engine or `stream_interval` is above 1.\n\nKnown limitation: from `stream_interval=10` in these runs, a call's name can share a delta with its end tag, and the name is lost. At 64 the second call is lost too. main behaves the same or worse here, so this is left for a follow-up.\n\nRelated PRs:\n\n- #63947 fixes #63906, a separate bug. `` values keep their current decoding here, so `123` is still the integer 123.\n- #48705 fixes the brace issue the same way. It is included here because the streaming tests cannot reassemble a multi-argument call without it. Happy to rebase if #48705 lands first.\n- #64360 targets the same issue and was opened a day after this PR.\n\nAI assistance was used for this change.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/tool_parsers/functiongemma_tool_parser.py b/vllm/tool_parsers/functiongemma_tool_parser.py\nindex 6fcae6e55220..4d809bb42029 100644\n--- a/vllm/tool_parsers/functiongemma_tool_parser.py\n+++ b/vllm/tool_parsers/functiongemma_tool_parser.py\n@@ -25,6 +25,109 @@\n \n logger = init_logger(__name__)\n \n+_ESCAPE = \"\"\n+_BARE_LITERALS = {\"true\": True, \"false\": False, \"null\": None, \"None\": None}\n+\n+\n+class _IncompleteValue(Exception):\n+ \"\"\"The argument text ends before the value does.\"\"\"\n+\n+\n+class _MalformedValue(Exception):\n+ \"\"\"A delimiter appears where a value or key should start.\"\"\"\n+\n+\n+def _skip_whitespace(text: str, pos: int) -> int:\n+ while pos < len(text) and text[pos] in \" \\n\":\n+ pos += 1\n+ return pos\n+\n+\n+def _decode_escaped(raw: str):\n+ try:\n+ return json.loads(raw)\n+ except json.JSONDecodeError:\n+ return raw\n+\n+\n+def _decode_bare(raw: str):\n+ raw = raw.strip()\n+ if raw in _BARE_LITERALS:\n+ return _BARE_LITERALS[raw]\n+ try:\n+ return json.loads(raw)\n+ except json.JSONDecodeError:\n+ return raw\n+\n+\n+def _parse_value(text: str, pos: int, partial: bool) -> tuple[object, int]:\n+ \"\"\"Parse one value at ``pos`` and return it with the position after it.\n+\n+ Raises:\n+ _IncompleteValue: ``text`` ends inside the value. A bare scalar at the\n+ end of a ``partial`` string counts as incomplete, since more digits\n+ or letters may still follow.\n+ _MalformedValue: a delimiter stands where the value should start.\n+\n+ \"\"\"\n+ pos = _skip_whitespace(text, pos)\n+ if text.startswith(_ESCAPE, pos):\n+ start = pos + len(_ESCAPE)\n+ end = text.find(_ESCAPE, start)\n+ if end < 0:\n+ raise _IncompleteValue\n+ return _decode_escaped(text[start:end]), end + len(_ESCAPE)\n+ if text.startswith(\"{\", pos):\n+ return _parse_object(text, pos + 1, partial)\n+ if text.startswith(\"[\", pos):\n+ return _parse_array(text, pos + 1, partial)\n+ end = pos\n+ while end < len(text) and text[end] not in \",}]\":\n+ end += 1\n+ if end == pos:\n+ raise _MalformedValue\n+ if end == len(text) and partial:\n+ raise _IncompleteValue\n+ return _decode_bare(text[pos:end]), end\n+\n+\n+def _parse_object(text: str, pos: int, partial: bool) -> tuple[dict, int]:\n+ obj: dict = {}\n+ while True:\n+ pos = _skip_whitespace(text, pos)\n+ if pos >= len(text):\n+ raise _IncompleteValue\n+ if text[pos] == \"}\":\n+ return obj, pos + 1\n+ if text[pos] == \"]\":\n+ raise _MalformedValue\n+ if text[pos] == \",\":\n+ pos += 1\n+ continue\n+ colon = text.find(\":\", pos)\n+ if colon < 0:\n+ raise _IncompleteValue\n+ key = text[pos:colon].strip()\n+ value, pos = _parse_value(text, colon + 1, partial)\n+ obj[key] = value\n+\n+\n+def _parse_array(text: str, pos: int, partial: bool) -> tuple[list, int]:\n+ items: list = []\n+ while True:\n+ pos = _skip_whitespace(text, pos)\n+ if pos >= len(text):\n+ raise _IncompleteValue\n+ if text[pos] == \"]\":\n+ return items, pos + 1\n+ if text[pos] == \"}\":\n+ raise _MalformedValue\n+ if text[pos] == \",\":\n+ pos += 1\n+ continue\n+ value, pos = _parse_value(text, pos, partial)\n+ items.append(value)\n+\n \n class FunctionGemmaToolParser(ToolParser):\n \"\"\"Tool parser for Google's FunctionGemma model (google/functiongemma-270m-it).\n@@ -43,10 +146,6 @@ class FunctionGemmaToolParser(ToolParser):\n r\"|call:(\\w+)\\{(.*)\",\n re.DOTALL,\n )\n- arg_regex: re.Pattern = re.compile(\n- r\"(\\w+):(.*?)\",\n- re.DOTALL,\n- )\n \n def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n super().__init__(tokenizer, tools)\n@@ -58,20 +157,32 @@ def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):\n self.streamed_args_for_tool: list[str] = []\n self.buffered_delta_text = \"\"\n \n- def _parse_arguments(self, args_str: str) -> dict:\n- \"\"\"Parse FunctionGemma argument string into a dictionary.\"\"\"\n- arguments: dict = {}\n- if not args_str:\n- return arguments\n+ def _parse_arguments(self, args_str: str, partial: bool = False) -> dict:\n+ \"\"\"Parse a FunctionGemma argument string into a dictionary.\n \n- matches = self.arg_regex.findall(args_str)\n- for key, value in matches:\n+ The chat template writes strings as ``text`` and\n+ everything else bare: ``true``/``false``, numbers, ``[item,...]`` and\n+ ``{key:value,...}`` with bare keys. With ``partial`` the string is a\n+ streaming prefix: parsing stops at the first incomplete value and the\n+ complete arguments before it are returned.\n+ \"\"\"\n+ arguments: dict = {}\n+ pos = 0\n+ while pos < len(args_str):\n+ if args_str[pos] in \", \\n\":\n+ pos += 1\n+ continue\n+ colon = args_str.find(\":\", pos)\n+ if colon < 0:\n+ break\n+ key = args_str[pos:colon].strip()\n+ if not key:\n+ break\n try:\n- parsed_value = json.loads(value)\n- arguments[key] = parsed_value\n- except json.JSONDecodeError:\n- arguments[key] = value\n-\n+ value, pos = _parse_value(args_str, colon + 1, partial)\n+ except (_IncompleteValue, _MalformedValue):\n+ break\n+ arguments[key] = value\n return arguments\n \n def adjust_request(\n@@ -143,6 +254,46 @@ def extract_tool_calls(\n tools_called=False, tool_calls=[], content=model_output\n )\n \n+ def _stream_arguments(self, args: dict, final: bool) -> DeltaMessage | None:\n+ \"\"\"Stream the part of the arguments JSON not sent yet.\n+\n+ Arguments only grow by appended keys, so their JSON is prefix-stable\n+ except for the closing brace, which is held back until ``final``.\n+ \"\"\"\n+ self.prev_tool_call_arr[self.current_tool_id][\"arguments\"] = args\n+ args_json = json.dumps(args, ensure_ascii=False)\n+ if not final:\n+ args_json = args_json[:-1]\n+ prev_streamed = self.streamed_args_for_tool[self.current_tool_id]\n+ if len(args_json) <= len(prev_streamed):\n+ return None\n+ diff = args_json[len(prev_streamed) :]\n+ self.streamed_args_for_tool[self.current_tool_id] = args_json\n+ return DeltaMessage(\n+ tool_calls=[\n+ DeltaToolCall(\n+ index=self.current_tool_id,\n+ function=DeltaFunctionCall(arguments=diff).model_dump(\n+ exclude_none=True\n+ ),\n+ )\n+ ]\n+ )\n+\n+ def _close_tool_call(self, current_text: str) -> DeltaMessage | None:\n+ \"\"\"Stream what is left of the current call, including its closing brace.\"\"\"\n+ if not 0 <= self.current_tool_id < len(self.prev_tool_call_arr):\n+ return None\n+ all_calls = self.tool_call_regex.findall(current_text)\n+ args = {}\n+ if self.current_tool_id < len(all_calls):\n+ match = all_calls[self.current_tool_id]\n+ if match[0]:\n+ args = self._parse_arguments(match[1])\n+ if args or self.current_tool_name_sent:\n+ return self._stream_arguments(args, final=True)\n+ return None\n+\n def _buffer_delta_text(self, delta_text: str) -> str:\n \"\"\"Buffer incoming delta text to handle multi-token special sequences.\"\"\"\n potential_start = \"\"\n@@ -192,12 +343,17 @@ def extract_tool_calls_streaming(\n \n # Starting a new function call\n if start_count > prev_start_count and start_count > end_count:\n+ closing = (\n+ self._close_tool_call(current_text)\n+ if end_count > prev_end_count\n+ else None\n+ )\n self.current_tool_id += 1\n self.current_tool_name_sent = False\n self.streamed_args_for_tool.append(\"\")\n self.prev_tool_call_arr.append({})\n logger.debug(\"Starting new tool call %d\", self.current_tool_id)\n- return None\n+ return closing\n \n # In the middle of a function call\n if start_count > end_count:\n@@ -235,74 +391,17 @@ def extract_tool_calls_streaming(\n )\n \n if self.current_tool_name_sent and args_part:\n- current_args = self._parse_arguments(args_part)\n+ current_args = self._parse_arguments(\n+ args_part, partial=True\n+ )\n if current_args:\n- current_args_json = json.dumps(\n- current_args, ensure_ascii=False\n- )\n- prev_streamed = self.streamed_args_for_tool[\n- self.current_tool_id\n- ]\n-\n- if len(current_args_json) > len(prev_streamed):\n- diff = current_args_json[len(prev_streamed) :]\n- self.streamed_args_for_tool[\n- self.current_tool_id\n- ] = current_args_json\n- self.prev_tool_call_arr[self.current_tool_id][\n- \"arguments\"\n- ] = current_args\n-\n- return DeltaMessage(\n- tool_calls=[\n- DeltaToolCall(\n- index=self.current_tool_id,\n- function=DeltaFunctionCall(\n- arguments=diff\n- ).model_dump(exclude_none=True),\n- )\n- ]\n- )\n+ return self._stream_arguments(current_args, final=False)\n \n return None\n \n # Function call just ended\n if end_count > prev_end_count:\n- if self.current_tool_id >= 0 and self.current_tool_id < len(\n- self.prev_tool_call_arr\n- ):\n- all_calls = self.tool_call_regex.findall(current_text)\n- args = {}\n- if self.current_tool_id < len(all_calls):\n- match = all_calls[self.current_tool_id]\n- if match[0]:\n- args_str = match[1]\n- args = self._parse_arguments(args_str)\n- self.prev_tool_call_arr[self.current_tool_id][\n- \"arguments\"\n- ] = args\n-\n- if args:\n- args_json = json.dumps(args, ensure_ascii=False)\n- prev_streamed = self.streamed_args_for_tool[\n- self.current_tool_id\n- ]\n- if len(args_json) > len(prev_streamed):\n- diff = args_json[len(prev_streamed) :]\n- self.streamed_args_for_tool[self.current_tool_id] = (\n- args_json\n- )\n- return DeltaMessage(\n- tool_calls=[\n- DeltaToolCall(\n- index=self.current_tool_id,\n- function=DeltaFunctionCall(\n- arguments=diff\n- ).model_dump(exclude_none=True),\n- )\n- ]\n- )\n- return None\n+ return self._close_tool_call(current_text)\n \n if delta_text:\n return DeltaMessage(content=delta_text)\n\ndiff --git a/tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py b/tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py\nnew file mode 100644\nindex 000000000000..048ddbbaaea5\n--- /dev/null\n+++ b/tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py\n@@ -0,0 +1,101 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+import json\n+\n+import pytest\n+import regex as re\n+\n+from tests.utils import RemoteOpenAIServer\n+\n+MODEL = \"unsloth/functiongemma-270m-it\"\n+START = \"\"\n+END = \"\"\n+TOOLS = [\n+ {\n+ \"type\": \"function\",\n+ \"function\": {\n+ \"name\": name,\n+ \"description\": name,\n+ \"parameters\": {\"type\": \"object\", \"properties\": {}},\n+ },\n+ }\n+ for name in (\"set_alarm\", \"get_weather\", \"get_time\")\n+]\n+\n+\n+@pytest.fixture(scope=\"module\")\n+def server():\n+ args = [\n+ \"--enforce-eager\",\n+ \"--enable-auto-tool-choice\",\n+ \"--tool-call-parser\",\n+ \"functiongemma\",\n+ \"--max-model-len\",\n+ \"2048\",\n+ \"--max-num-seqs\",\n+ \"2\",\n+ \"--gpu-memory-utilization\",\n+ \"0.05\",\n+ ]\n+ with RemoteOpenAIServer(MODEL, args, max_wait_seconds=480) as server:\n+ yield server\n+\n+\n+def _tool_calls(server, output, stream, stream_interval=None):\n+ \"\"\"Pin the model output with a regex, so only serving and parsing are tested.\"\"\"\n+ extra_body = {\"structured_outputs\": {\"regex\": re.escape(output)}}\n+ if stream_interval is not None:\n+ extra_body[\"stream_interval\"] = stream_interval\n+ with server.get_client() as client:\n+ response = client.chat.completions.create(\n+ model=MODEL,\n+ messages=[{\"role\": \"user\", \"content\": \"Call the tools.\"}],\n+ tools=TOOLS,\n+ tool_choice=\"auto\",\n+ temperature=0,\n+ max_tokens=128,\n+ stream=stream,\n+ extra_body=extra_body,\n+ )\n+ if not stream:\n+ calls = response.choices[0].message.tool_calls or []\n+ return [(c.function.name, json.loads(c.function.arguments)) for c in calls]\n+ streamed: dict[int, dict] = {}\n+ for chunk in response:\n+ for call in chunk.choices[0].delta.tool_calls or []:\n+ entry = streamed.setdefault(call.index, {\"name\": None, \"args\": \"\"})\n+ entry[\"name\"] = entry[\"name\"] or call.function.name\n+ entry[\"args\"] += call.function.arguments or \"\"\n+ return [(e[\"name\"], json.loads(e[\"args\"])) for _, e in sorted(streamed.items())]\n+\n+\n+@pytest.mark.parametrize(\"stream\", [False, True])\n+@pytest.mark.parametrize(\n+ (\"args\", \"expected\"),\n+ [\n+ (\n+ \"days:[mon],enabled:true,hour:7\",\n+ {\"days\": [\"mon\"], \"enabled\": True, \"hour\": 7},\n+ ),\n+ (\"\", {}),\n+ ],\n+ ids=[\"non_string_arguments\", \"no_arguments\"],\n+)\n+def test_arguments_reach_the_client(server, stream, args, expected):\n+ output = f\"{START}call:set_alarm{{{args}}}{END}\"\n+ assert _tool_calls(server, output, stream) == [(\"set_alarm\", expected)]\n+\n+\n+@pytest.mark.parametrize(\"stream_interval\", [2, 3, 4])\n+def test_streamed_call_closes_when_next_call_starts_in_same_delta(\n+ server, stream_interval\n+):\n+ \"\"\"These intervals merge the first call's end tag and the second's start tag.\"\"\"\n+ output = (\n+ f\"{START}call:get_weather{{city:Paris}}{END}\"\n+ f\"{START}call:get_time{{tz:UTC}}{END}\"\n+ )\n+ assert _tool_calls(server, output, True, stream_interval) == [\n+ (\"get_weather\", {\"city\": \"Paris\"}),\n+ (\"get_time\", {\"tz\": \"UTC\"}),\n+ ]\ndiff --git a/tests/tool_parsers/test_functiongemma_tool_parser.py b/tests/tool_parsers/test_functiongemma_tool_parser.py\nindex 10792c16607e..92c6dba9ff86 100644\n--- a/tests/tool_parsers/test_functiongemma_tool_parser.py\n+++ b/tests/tool_parsers/test_functiongemma_tool_parser.py\n@@ -1,9 +1,11 @@\n # SPDX-License-Identifier: Apache-2.0\n # SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n \n+import json\n from unittest.mock import MagicMock\n \n import pytest\n+import regex as re\n \n from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest\n from vllm.tool_parsers.functiongemma_tool_parser import FunctionGemmaToolParser\n@@ -121,6 +123,171 @@ def test_argument_with_spaces(self, parser):\n assert result == {\"message\": \"Hello World\"}\n \n \n+# Rendered by the model's chat template (``format_argument``): only strings are\n+# ````-delimited; booleans, numbers, arrays and objects are bare.\n+TEMPLATE_CALL = (\n+ \"call:set_alarm{\"\n+ \"days:[mon,tue],enabled:true,hour:7,\"\n+ \"label:Wake up,snooze:{minutes:5}}\"\n+ \"\"\n+)\n+TEMPLATE_ARGS = {\n+ \"days\": [\"mon\", \"tue\"],\n+ \"enabled\": True,\n+ \"hour\": 7,\n+ \"label\": \"Wake up\",\n+ \"snooze\": {\"minutes\": 5},\n+}\n+\n+_START = \"\"\n+_END = \"\"\n+_TAG_RE = re.compile(f\"({_START}|{_END})\")\n+\n+\n+def _chunks(text: str, size: int) -> list[str]:\n+ \"\"\"Split ``text`` into ``size``-character chunks, keeping the tags whole.\n+\n+ The tags are single special tokens, so a delta never splits them.\n+ \"\"\"\n+ chunks = []\n+ for part in _TAG_RE.split(text):\n+ if _TAG_RE.fullmatch(part):\n+ chunks.append(part)\n+ else:\n+ chunks.extend(part[i : i + size] for i in range(0, len(part), size))\n+ return [chunk for chunk in chunks if chunk]\n+\n+\n+def _stream(parser, request, text: str, size: int) -> list[tuple[str, dict]]:\n+ return _stream_deltas(parser, request, _chunks(text, size))\n+\n+\n+def _stream_deltas(parser, request, deltas: list[str]) -> list[tuple[str, dict]]:\n+ \"\"\"Reassemble streamed tool calls as a client would: by index.\"\"\"\n+ previous = \"\"\n+ calls: dict[int, dict] = {}\n+ for i, chunk in enumerate(deltas, start=1):\n+ current = previous + chunk\n+ delta = parser.extract_tool_calls_streaming(\n+ previous, current, chunk, [], [i], [i], request\n+ )\n+ previous = current\n+ for call in (delta.tool_calls if delta else None) or []:\n+ entry = calls.setdefault(call.index, {\"name\": None, \"arguments\": \"\"})\n+ if call.function.name:\n+ entry[\"name\"] = call.function.name\n+ entry[\"arguments\"] += call.function.arguments or \"\"\n+ return [\n+ (entry[\"name\"], json.loads(entry[\"arguments\"]))\n+ for _, entry in sorted(calls.items())\n+ ]\n+\n+\n+class TestTemplateArgumentTypes:\n+ \"\"\"Regression tests for #63983: bare (non-string) arguments were dropped.\"\"\"\n+\n+ def test_non_streaming_keeps_every_argument(self, parser, mock_request):\n+ result = parser.extract_tool_calls(TEMPLATE_CALL, mock_request)\n+\n+ assert result.tools_called is True\n+ assert json.loads(result.tool_calls[0].function.arguments) == TEMPLATE_ARGS\n+\n+ @pytest.mark.parametrize(\"size\", [1, 3, 1000])\n+ def test_streaming_keeps_every_argument(self, parser, mock_request, size):\n+ assert _stream(parser, mock_request, TEMPLATE_CALL, size) == [\n+ (\"set_alarm\", TEMPLATE_ARGS)\n+ ]\n+\n+ @pytest.mark.parametrize(\"size\", [1, 1000])\n+ def test_streaming_multiple_arguments_reassemble_to_json(\n+ self, parser, mock_request, size\n+ ):\n+ \"\"\"The closing brace is held back until the call ends, so the\n+ concatenated deltas of a multi-argument call form one JSON object.\"\"\"\n+ text = (\n+ \"call:get_weather{\"\n+ \"location:San Francisco,unit:celsius}\"\n+ \"\"\n+ \"call:set_alarm{hour:7,snooze:{minutes:5}}\"\n+ \"\"\n+ )\n+ assert _stream(parser, mock_request, text, size) == [\n+ (\"get_weather\", {\"location\": \"San Francisco\", \"unit\": \"celsius\"}),\n+ (\"set_alarm\", {\"hour\": 7, \"snooze\": {\"minutes\": 5}}),\n+ ]\n+\n+ @pytest.mark.parametrize(\n+ \"first_call_deltas\",\n+ [\n+ [\"city:Paris\", \"}\", _END + _START],\n+ [\"city:Paris\", \"}\" + _END + _START],\n+ [\"city:Paris}\" + _END + _START],\n+ ],\n+ )\n+ def test_streaming_closes_call_when_next_starts_in_same_delta(\n+ self, parser, mock_request, first_call_deltas\n+ ):\n+ \"\"\"Deltas merge when the client falls behind the engine, so one call's\n+ end tag can share a delta with the next call's start tag.\"\"\"\n+ deltas = [\n+ _START,\n+ \"call:get_weather{\",\n+ *first_call_deltas,\n+ \"call:get_time{\",\n+ \"tz:UTC\",\n+ \"}\",\n+ _END,\n+ ]\n+ assert _stream_deltas(parser, mock_request, deltas) == [\n+ (\"get_weather\", {\"city\": \"Paris\"}),\n+ (\"get_time\", {\"tz\": \"UTC\"}),\n+ ]\n+\n+ @pytest.mark.parametrize(\"size\", [1, 1000])\n+ def test_streaming_call_without_arguments_sends_empty_object(\n+ self, parser, mock_request, size\n+ ):\n+ text = f\"{_START}call:get_time{{}}{_END}\"\n+ assert _stream(parser, mock_request, text, size) == [(\"get_time\", {})]\n+\n+ def test_escaped_strings_keep_delimiters(self, parser):\n+ args = \"note:a, b: {c} [d],count:2\"\n+ assert parser._parse_arguments(args) == {\"note\": \"a, b: {c} [d]\", \"count\": 2}\n+\n+ def test_nested_containers_and_literals(self, parser):\n+ args = \"cfg:{on:false,ids:[1,[2,3],{k:v}],none:None},f:1.5\"\n+ assert parser._parse_arguments(args) == {\n+ \"cfg\": {\"on\": False, \"ids\": [1, [2, 3], {\"k\": \"v\"}], \"none\": None},\n+ \"f\": 1.5,\n+ }\n+\n+ @pytest.mark.parametrize(\n+ (\"prefix\", \"expected\"),\n+ [\n+ (\"hour:7\", {}),\n+ (\"hour:7,\", {\"hour\": 7}),\n+ (\"hour:7,label:Wake\", {\"hour\": 7}),\n+ (\"hour:7,days:[mon\", {\"hour\": 7}),\n+ (\"hour:7,snooze:{minutes:5\", {\"hour\": 7}),\n+ (\"hour:7,snooze:{minutes:5}\", {\"hour\": 7, \"snooze\": {\"minutes\": 5}}),\n+ ],\n+ )\n+ def test_partial_parsing_holds_back_incomplete_values(\n+ self, parser, prefix, expected\n+ ):\n+ assert parser._parse_arguments(prefix, partial=True) == expected\n+\n+ @pytest.mark.parametrize(\n+ \"args\",\n+ [\"a:1,items:[1}\", \"a:1,cfg:{x:1]\", \"a:1,b:,c:2\", \"a:1,b:}\"],\n+ )\n+ @pytest.mark.parametrize(\"partial\", [False, True])\n+ def test_mismatched_delimiters_stop_parsing(self, parser, args, partial):\n+ \"\"\"A stray closing brace must not spin the parser; the arguments\n+ parsed before it are kept and the rest is dropped.\"\"\"\n+ assert parser._parse_arguments(args, partial=partial) == {\"a\": 1}\n+\n+\n class TestAdjustRequest:\n def test_skip_special_tokens_disabled(self, parser, mock_request):\n mock_request.tools = [{\"type\": \"function\", \"function\": {\"name\": \"test\"}}]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Frontend] fix Anthropic inline-system probe crashing startup\nLabels: bug, frontend, ready, verified\nFiles changed (2): tests/entrypoints/anthropic/test_anthropic_messages_conversion.py, vllm/entrypoints/anthropic/serving.py\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n\n- `vllm serve allenai/Olmo-3-7B-Instruct` now starts. Before this change, it stopped with `TypeError: Object of type Undefined is not JSON serializable`.\n- OLMo 3 is correctly detected as accepting non-leading system messages, so inline system messages are **not** merged into the leading system prompt, and the prefix cache keeps working.\n\n## Validation\n[results removed]\n## Details\n\n**Root cause:** `AnthropicServingMessages.__init__` calls `_should_merge_inline_system`, which calls `_detect_merge_inline_system`. That function renders the chat template with a `[system, user, system, user]` conversation to find out whether the template accepts non-leading system messages. Since #58727, this check renders the model's own template.\n\n**Fix:**\n\n**Tradeoff:** catching `Exception` alone would also stop the crash. But for OLMo 3 it would wrongly decide that merging is needed, which moves inline system messages into the leading system prompt and breaks prefix caching. That's why (1) is included and not only (2).\n\n**Not a duplicate:** I searched open PRs for `61919` and for `merge_inline_system`. None address this crash. The related open PRs #63368 (fold inline system messages in place) and #53501 (preserve prefix cache for inline system turns) change different behavior.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/vllm/entrypoints/anthropic/serving.py b/vllm/entrypoints/anthropic/serving.py\nindex e1b362ab4136..6d653616b148 100644\n--- a/vllm/entrypoints/anthropic/serving.py\n+++ b/vllm/entrypoints/anthropic/serving.py\n@@ -324,7 +324,9 @@ def _detect_merge_inline_system(chat_template: str | None) -> bool:\n add_generation_prompt=False,\n )\n return False\n- except jinja2.TemplateError:\n+ except Exception:\n+ # Non-TemplateError failures (e.g. TypeError from filters on\n+ # undefined variables) must not abort server startup.\n return True\n \n @staticmethod\n\ndiff --git a/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py b/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py\nindex aa50a16b2365..0525272576dc 100644\n--- a/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py\n+++ b/tests/entrypoints/anthropic/test_anthropic_messages_conversion.py\n@@ -1454,6 +1454,27 @@ def test_no_template_defaults_merge(self):\n \"\"\"No chat_template → conservative default: merge.\"\"\"\n assert AnthropicServingMessages._detect_merge_inline_system(None) is True\n \n+ def test_tools_none_check_template_merges(self):\n+ \"\"\"OLMo 3-style ``tools | tojson`` on undefined tools falls back to merge.\"\"\"\n+ template = (\n+ \"{% if tools is none %}{% else %}{{ tools | tojson }}{% endif %}\"\n+ \"{% for m in messages %}{{ m.content }}{% endfor %}\"\n+ )\n+ assert AnthropicServingMessages._detect_merge_inline_system(template) is True\n+\n+ def test_tools_loop_template_no_merge(self):\n+ \"\"\"Hermes-style ``for tool in tools`` must not raise in the probe.\"\"\"\n+ template = (\n+ \"{% for tool in tools %}{{ tool | tojson }}{% endfor %}\"\n+ \"{% for m in messages %}{{ m.content }}{% endfor %}\"\n+ )\n+ assert AnthropicServingMessages._detect_merge_inline_system(template) is False\n+\n+ def test_non_template_error_defaults_merge(self):\n+ \"\"\"A non-TemplateError render failure must not abort startup.\"\"\"\n+ template = \"{{ undefined_var | tojson }}\"\n+ assert AnthropicServingMessages._detect_merge_inline_system(template) is True\n+\n @pytest.mark.parametrize(\n (\"resolved\", \"expected\"),\n [(PERMISSIVE_TEMPLATE, False), (Q35_TEMPLATE, True)],\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Multimodal] Fix DeepSeek-OCR zero-sum patch guard in _encode…\nLabels: bug, ready, multi-modality, deepseek\nFiles changed (3): tests/models/multimodal/generation/test_deepseek_ocr.py, vllm/model_executor/models/deepseek_ocr.py, vllm/model_executor/models/deepseek_ocr2.py\n\n## Description (results removed)\n\nFixes #64075.\n\n_encode_local_features in deepseek_ocr.py and deepseek_ocr2.py used torch.sum(patches).item() == 0 to detect \"no crop patches\", so a tiled image whose normalized pixels cancel to zero (e.g. half-white/half-black 1536x768) wrongly returned None, dropped local features, and crashed EngineCore with a placeholder/embedding shape mismatch. Replace the guard with patches.numel() == 0; #59417 fixed the equivalent check in _parse_and_validate_image_input but left this one as \"not engine-fatal\", which #64075 disproves.\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/deepseek_ocr.py b/vllm/model_executor/models/deepseek_ocr.py\nindex 3aef695d0608..d137030a337a 100644\n--- a/vllm/model_executor/models/deepseek_ocr.py\n+++ b/vllm/model_executor/models/deepseek_ocr.py\n@@ -499,7 +499,7 @@ def _encode_global_features(self, image_tensor: torch.Tensor) -> torch.Tensor:\n def _encode_local_features(\n self, patches: torch.Tensor, crop_shape: torch.Tensor\n ) -> torch.Tensor | None:\n- if torch.sum(patches).item() == 0:\n+ if patches.numel() == 0:\n return None\n \n local_features_1 = self.sam_model(patches)\ndiff --git a/vllm/model_executor/models/deepseek_ocr2.py b/vllm/model_executor/models/deepseek_ocr2.py\nindex 18de7503c721..9139259909e6 100644\n--- a/vllm/model_executor/models/deepseek_ocr2.py\n+++ b/vllm/model_executor/models/deepseek_ocr2.py\n@@ -343,7 +343,7 @@ def _encode_global_features(self, image_tensor: torch.Tensor) -> torch.Tensor:\n return features.view(-1, dim)\n \n def _encode_local_features(self, patches: torch.Tensor) -> torch.Tensor | None:\n- if torch.sum(patches).item() == 0:\n+ if patches.numel() == 0:\n return None\n \n local_features = self.sam_model(patches)\n\ndiff --git a/tests/models/multimodal/generation/test_deepseek_ocr.py b/tests/models/multimodal/generation/test_deepseek_ocr.py\nnew file mode 100644\nindex 000000000000..6dc9ea52434f\n--- /dev/null\n+++ b/tests/models/multimodal/generation/test_deepseek_ocr.py\n@@ -0,0 +1,58 @@\n+# SPDX-License-Identifier: Apache-2.0\n+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project\n+\"\"\"Guard tests for DeepSeek-OCR _encode_local_features.\n+\n+_encode_local_features must skip processing only for an empty-element\n+patches tensor, not for a zero-sum one.\n+\n+Regression for #64075: the old guard ``torch.sum(patches).item() == 0``\n+returned None for a 1536x768 half-white/half-black image whose two\n+normalised crop patches cancel to sum==0, causing a shape mismatch in\n+_merge_multimodal_embeddings and a fatal EngineCore crash.\n+\n+The correct guard is ``patches.numel() == 0``.\n+\"\"\"\n+\n+import pytest\n+import torch\n+\n+from vllm.model_executor.models.deepseek_ocr import DeepseekOCRForCausalLM\n+from vllm.model_executor.models.deepseek_ocr2 import DeepseekOCR2ForCausalLM\n+\n+\n+class TestDeepseekOCREncodeLocalFeaturesGuard:\n+ def test_ocr2_empty_patches_returns_none(self):\n+ \"\"\"Zero-element tensor → skip local encoding (non-tiled image).\"\"\"\n+ empty = torch.empty(0, 3, 224, 224)\n+ assert DeepseekOCR2ForCausalLM._encode_local_features(None, empty) is None\n+\n+ def test_ocr2_zero_sum_patches_enters_model_body(self):\n+ \"\"\"Non-empty patches that happen to sum to zero must NOT return None.\n+\n+ The method will raise AttributeError when it tries to call\n+ self.sam_model on a None self – that is the expected outcome here\n+ because it proves the guard was passed, not that encoding succeeded.\n+ The real crash was a shape-mismatch ValueError that killed EngineCore.\n+ \"\"\"\n+ # Two patches that cancel: white (1.0) + black (-1.0) after Normalize.\n+ wb = torch.cat([torch.ones(1, 3, 4, 4), -torch.ones(1, 3, 4, 4)])\n+ assert wb.numel() > 0\n+ assert wb.sum().item() == 0.0\n+ with pytest.raises(AttributeError):\n+ DeepseekOCR2ForCausalLM._encode_local_features(None, wb)\n+\n+ def test_ocr1_empty_patches_returns_none(self):\n+ \"\"\"OCR-1: zero-element tensor → skip local encoding.\"\"\"\n+ empty = torch.empty(0, 3, 224, 224)\n+ crop_shape = torch.tensor([0, 0])\n+ assert (\n+ DeepseekOCRForCausalLM._encode_local_features(None, empty, crop_shape)\n+ is None\n+ )\n+\n+ def test_ocr1_zero_sum_patches_enters_model_body(self):\n+ \"\"\"OCR-1: non-empty zero-sum patches must pass the guard.\"\"\"\n+ wb = torch.cat([torch.ones(1, 3, 4, 4), -torch.ones(1, 3, 4, 4)])\n+ crop_shape = torch.tensor([1, 2])\n+ with pytest.raises(AttributeError):\n+ DeepseekOCRForCausalLM._encode_local_features(None, wb, crop_shape)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][KV Offload] Publish successful stores to lookup state\nLabels: bug, ready, nixl\nFiles changed (6): tests/v1/kv_offload/tiering/test_async_lookup.py, tests/v1/kv_offload/tiering/test_fs_tier.py, tests/v1/kv_offload/tiering/test_obj_tier.py, vllm/v1/kv_offload/tiering/async_lookup.py, vllm/v1/kv_offload/tiering/fs/manager.py, vllm/v1/kv_offload/tiering/obj/manager.py\n\n## Description (results removed)\n\n## Summary\n\nBuilds on the invalidation approach in #61187. When this instance successfully stores keys to a filesystem or object-store tier, it publishes them as present in the tier's lookup state. This updates cached misses and prevents older pending or in-flight probes from overwriting the store result.\n\nUnlike #61717, this preserves cross-request miss reuse instead of probing again for every request. It handles successful stores by this instance only; writes from other instances to shared storage remain out of scope, so this does not close #61658.\n\n## Validation\n[results removed]\n## Related work\n\n#61187 is closed and unmerged; this PR continues its invalidation direction. #61717 addresses the related stale-miss behavior by re-probing on new requests, while this change preserves cached-miss reuse.\n\nAI assistance was used; the submitter reviewed the change.\n\n## Diff\n\n```diff\ndiff --git a/vllm/v1/kv_offload/tiering/async_lookup.py b/vllm/v1/kv_offload/tiering/async_lookup.py\nindex 69a513f55de8..080c9139433e 100644\n--- a/vllm/v1/kv_offload/tiering/async_lookup.py\n+++ b/vllm/v1/kv_offload/tiering/async_lookup.py\n@@ -33,7 +33,8 @@\n Results are drained on the first lookup after each flush, at flush(), and\n after worker shutdown. In-flight lookups with no remaining request references\n are retained until their results are drained, allowing new requests to share\n-the same probe.\n+the same probe; a successful store drops such an orphan instead (see\n+mark_present()).\n \"\"\"\n \n import queue\n@@ -61,8 +62,9 @@ class LookupPhase(Enum):\n class LookupState:\n generation: int\n phase: LookupPhase = LookupPhase.PENDING\n- # None while pending/in flight; True if the key exists; False if absent or\n- # explicitly marked missing after a failed load.\n+ # None while pending/in flight; True if the key is known to exist (a probe\n+ # found it, or this instance stored it); False if absent or explicitly\n+ # marked missing after a failed load.\n result: bool | None = None\n request_ids: set[str] = field(default_factory=set) # requests asking for the lookup\n \n@@ -229,6 +231,34 @@ def mark_miss(self, keys: Collection[OffloadKey]) -> None:\n if state is not None and state.phase is LookupPhase.RESOLVED:\n state.result = False\n \n+ def mark_present(self, keys: Collection[OffloadKey]) -> None:\n+ \"\"\"Record that keys were successfully stored to this tier.\n+\n+ Unlike mark_miss(), which leaves a newer probe alone (#59096), a store\n+ completion is newer information than any probe started before it, so\n+ this supersedes them: advancing the generation makes a stale pending\n+ batch entry fail flush()'s generation check and a stale in-flight\n+ result fail drain_results()'s, before either phase assert is reached.\n+\n+ Keys with no cached entry are skipped, since a verdict with no owning\n+ request could never be reclaimed. An in-flight entry whose requests all\n+ finished is dropped; cleanup() already removed the reverse-index\n+ entries, so its late result is simply ignored.\n+ \"\"\"\n+ for key in keys:\n+ state = self._lookup_state.get(key)\n+ if state is None or state.result is True:\n+ continue\n+ if not state.request_ids:\n+ del self._lookup_state[key]\n+ continue\n+ # Generations are opaque identity tokens compared for equality\n+ # only, so bumping one key cannot affect another key's results.\n+ state.generation = self._next_generation\n+ self._next_generation += 1\n+ state.result = True\n+ state.phase = LookupPhase.RESOLVED\n+\n def cleanup(self, req_id: str) -> None:\n \"\"\"Release request references, retaining in-flight lookups.\n \ndiff --git a/vllm/v1/kv_offload/tiering/fs/manager.py b/vllm/v1/kv_offload/tiering/fs/manager.py\nindex 594e18b9f549..91a1dd755138 100644\n--- a/vllm/v1/kv_offload/tiering/fs/manager.py\n+++ b/vllm/v1/kv_offload/tiering/fs/manager.py\n@@ -150,6 +150,7 @@ def __init__(\n \"emit events.\",\n tier_type,\n )\n+ # Track in-flight store jobs for lookup invalidation and KV events.\n self._store_jobs: dict[JobId, TransferJob] = {}\n # Keys of in-flight load (promotion) jobs, so a failed load can mark\n # its own cached lookup verdicts False (see get_finished_jobs).\n@@ -221,8 +222,7 @@ def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:\n @override\n def submit_store(self, job_metadata: TransferJob) -> None:\n keys = list(job_metadata.keys)\n- if self.events is not None:\n- self._store_jobs[job_metadata.job_id] = job_metadata\n+ self._store_jobs[job_metadata.job_id] = job_metadata\n task = functools.partial(\n batch_store_block,\n [self.file_mapper.get_file_name(key) for key in keys],\n@@ -282,9 +282,11 @@ def get_finished_jobs(self) -> Iterable[JobResult]:\n for job_id, success, transfer_time in self._pool.get_finished():\n block_count = self._job_block_counts.pop(job_id, 0)\n transfer_bytes = block_count * self._block_size if block_count else None\n- if self.events is not None:\n- job = self._store_jobs.pop(job_id, None)\n- if success and job is not None and job.keys:\n+ job = self._store_jobs.pop(job_id, None)\n+ if job is not None and success:\n+ # Successful store makes previously absent keys known-present.\n+ self._lookup_manager.mark_present(job.keys)\n+ if self.events is not None and job.keys:\n self.events.append(\n OffloadingEvent(\n keys=list(job.keys),\ndiff --git a/vllm/v1/kv_offload/tiering/obj/manager.py b/vllm/v1/kv_offload/tiering/obj/manager.py\nindex 3a6f8328dfa5..fb18502332d9 100644\n--- a/vllm/v1/kv_offload/tiering/obj/manager.py\n+++ b/vllm/v1/kv_offload/tiering/obj/manager.py\n@@ -149,6 +149,7 @@ def __init__(\n \"emit events.\",\n tier_type,\n )\n+ # Track in-flight store jobs for lookup invalidation and KV events.\n self._store_jobs: dict[JobId, TransferJob] = {}\n # Keys of in-flight load (promotion) jobs, so a failed download can\n # mark its own cached lookup verdicts False (see get_finished_jobs).\n@@ -293,8 +294,7 @@ def lookup(self, key: OffloadKey, req_context: ReqContext) -> LookupResult:\n return LookupResult.HIT if result else LookupResult.MISS\n \n def submit_store(self, job_metadata: TransferJob) -> None:\n- if self.events is not None:\n- self._store_jobs[job_metadata.job_id] = job_metadata\n+ self._store_jobs[job_metadata.job_id] = job_metadata\n obj_keys = (self._file_mapper.get_file_name(k) for k in job_metadata.keys)\n self._submit_transfer(\n job_metadata.job_id, job_metadata.chunk_ids, obj_keys, NIXL_WRITE\n@@ -388,9 +388,10 @@ def get_finished_jobs(self) -> Iterable[JobResult]:\n results = self._pending_results\n self._pending_results = []\n for result in results:\n- if self.events is not None:\n- job = self._store_jobs.pop(result.job_id, None)\n- if result.success and job is not None and job.keys:\n+ job = self._store_jobs.pop(result.job_id, None)\n+ if result.success and job is not None:\n+ self._lookup_manager.mark_present(job.keys)\n+ if self.events is not None and job.keys:\n self.events.append(\n OffloadingEvent(\n keys=list(job.keys),\n\ndiff --git a/tests/v1/kv_offload/tiering/test_async_lookup.py b/tests/v1/kv_offload/tiering/test_async_lookup.py\nindex d23d837371bd..543257dc9b35 100644\n--- a/tests/v1/kv_offload/tiering/test_async_lookup.py\n+++ b/tests/v1/kv_offload/tiering/test_async_lookup.py\n@@ -403,3 +403,105 @@ def test_enqueue_once_invariant_enforced(self):\n with pytest.raises(AssertionError):\n mgr.drain_results()\n mgr.shutdown()\n+\n+ def test_store_drops_orphaned_in_flight_state(\n+ self, monkeypatch: pytest.MonkeyPatch\n+ ):\n+ \"\"\"A store must not retain an in-flight state after its request ended.\"\"\"\n+ key = _key(1)\n+ mgr = InMemoryLookupManager()\n+ probe_started = threading.Event()\n+ release_probe = threading.Event()\n+ batch_lookup = mgr.batch_lookup\n+\n+ def blocking_lookup(keys, req_context):\n+ results = list(batch_lookup(keys, req_context))\n+ probe_started.set()\n+ if not release_probe.wait(timeout=5):\n+ raise TimeoutError(\"Test did not release the backend probe\")\n+ return results\n+\n+ monkeypatch.setattr(mgr, \"batch_lookup\", blocking_lookup)\n+ try:\n+ assert mgr.lookup(key, _ctx(\"req_a\")) is None\n+ mgr.flush()\n+ assert probe_started.wait(timeout=5)\n+ mgr.cleanup(\"req_a\")\n+ assert key in mgr._lookup_state\n+ assert not mgr._lookup_state[key].request_ids\n+\n+ mgr._existing.add(key)\n+ mgr.mark_present([key])\n+ assert key not in mgr._lookup_state\n+ release_probe.set()\n+ finally:\n+ release_probe.set()\n+ mgr.shutdown()\n+\n+ assert key not in mgr._lookup_state\n+\n+ def test_mark_present_handles_mixed_phases(self, monkeypatch: pytest.MonkeyPatch):\n+ \"\"\"One call updates pending, in-flight and resolved keys independently.\"\"\"\n+ pending_key, in_flight_key, resolved_key, unknown_key = (\n+ _key(1),\n+ _key(2),\n+ _key(3),\n+ _key(99),\n+ )\n+ mgr = InMemoryLookupManager()\n+ probe_started = threading.Event()\n+ release_probe = threading.Event()\n+ batch_lookup = mgr.batch_lookup\n+ calls = 0\n+\n+ def blocking_lookup(keys, req_context):\n+ nonlocal calls\n+ calls += 1\n+ results = list(batch_lookup(keys, req_context))\n+ if calls == 2:\n+ probe_started.set()\n+ if not release_probe.wait(timeout=5):\n+ raise TimeoutError(\"Test did not release the backend probe\")\n+ return results\n+\n+ monkeypatch.setattr(mgr, \"batch_lookup\", blocking_lookup)\n+ try:\n+ # Resolved: a probe delivered a miss.\n+ assert mgr.lookup(resolved_key, _ctx(\"req_c\")) is None\n+ mgr.flush()\n+ assert mgr._results_ready.wait(timeout=5)\n+ mgr._results_ready.clear()\n+ assert mgr.lookup(resolved_key, _ctx(\"req_c\")) is False\n+\n+ # In flight: the worker is still inside this probe.\n+ assert mgr.lookup(in_flight_key, _ctx(\"req_b\")) is None\n+ mgr.flush()\n+ assert probe_started.wait(timeout=5)\n+\n+ # Pending: accumulated this step, not flushed yet.\n+ assert mgr.lookup(pending_key, _ctx(\"req_a\")) is None\n+\n+ mgr.mark_present([pending_key, in_flight_key, resolved_key, unknown_key])\n+\n+ for key in (pending_key, in_flight_key, resolved_key):\n+ state = mgr._lookup_state[key]\n+ assert state.result is True\n+ assert state.phase is LookupPhase.RESOLVED\n+ assert unknown_key not in mgr._lookup_state\n+\n+ # A stale pending entry is skipped when its batch is flushed.\n+ mgr.flush()\n+\n+ assert mgr.lookup(pending_key, _ctx(\"req_a\")) is True\n+ assert mgr.lookup(in_flight_key, _ctx(\"req_b\")) is True\n+ assert mgr.lookup(resolved_key, _ctx(\"req_c\")) is True\n+ assert mgr.lookup(unknown_key, _ctx(\"req_d\")) is None\n+\n+ release_probe.set()\n+ finally:\n+ release_probe.set()\n+ mgr.shutdown()\n+\n+ # Only the two flushed probes ran: the pending batch was dropped, the\n+ # in-flight result was ignored, and unknown_key was never probed.\n+ assert calls == 2\ndiff --git a/tests/v1/kv_offload/tiering/test_fs_tier.py b/tests/v1/kv_offload/tiering/test_fs_tier.py\nindex 0d04cfad2b94..8c8ebf01ff6b 100644\n--- a/tests/v1/kv_offload/tiering/test_fs_tier.py\n+++ b/tests/v1/kv_offload/tiering/test_fs_tier.py\n@@ -231,6 +231,18 @@ def test_store_creates_file_and_lookup_succeeds(fs_tier):\n assert os.path.exists(dest), f\"Expected file at {dest}\"\n \n \n+def test_store_marks_a_cached_miss_present(fs_tier):\n+ tier, _ = fs_tier\n+ block_key = key(1)\n+ assert lookup_and_wait(tier, [block_key]) == [LookupResult.MISS]\n+\n+ tier.submit_store(make_job(1, [block_key], [0]))\n+ results = drain(tier)\n+ assert len(results) == 1\n+ assert results[0].success\n+ assert lookup_and_wait(tier, [block_key]) == [LookupResult.HIT]\n+\n+\n def test_store_accepts_block_published_by_another_writer(fs_tier, monkeypatch):\n \"\"\"Losing the race to publish a block must not fail the store job.\n \ndiff --git a/tests/v1/kv_offload/tiering/test_obj_tier.py b/tests/v1/kv_offload/tiering/test_obj_tier.py\nindex 1a4b5410faea..f69755ed2286 100644\n--- a/tests/v1/kv_offload/tiering/test_obj_tier.py\n+++ b/tests/v1/kv_offload/tiering/test_obj_tier.py\n@@ -321,6 +321,28 @@ def test_store_and_lookup(self):\n assert results[0].success\n assert lookup_and_wait(self.tier, [key(1)]) == [LookupResult.HIT]\n \n+ def test_store_marks_a_cached_miss_present(self):\n+ block_key = key(1)\n+ assert lookup_and_wait(self.tier, [block_key]) == [LookupResult.MISS]\n+\n+ self.tier.submit_store(make_job(1, [block_key], [0]))\n+ results = drain(self.tier)\n+ assert len(results) == 1\n+ assert results[0].success\n+ assert lookup_and_wait(self.tier, [block_key]) == [LookupResult.HIT]\n+\n+ def test_failed_store_does_not_mark_cached_miss_present(self):\n+ block_key = key(1)\n+ assert lookup_and_wait(self.tier, [block_key]) == [LookupResult.MISS]\n+\n+ self.agent.check_xfer_state = lambda h: \"ERR\"\n+ self.tier.submit_store(make_job(1, [block_key], [0]))\n+ results = drain(self.tier)\n+\n+ assert len(results) == 1\n+ assert not results[0].success\n+ assert lookup_and_wait(self.tier, [block_key]) == [LookupResult.MISS]\n+\n def test_lookup_unrelated_key_returns_false(self):\n self.tier.submit_store(make_job(1, [key(1)], [0]))\n drain(self.tier)\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Pooling] Enable Matryoshka dimensions for EmbeddingGemma 2\nLabels: bug, ready, ci/build, multi-modality, verified, pooling\nFiles changed (2): tests/models/multimodal/pooling/test_embedding_gemma2.py, vllm/model_executor/models/config.py\n\n## Description (results removed)\n\n## Overview\n\nFixes #64845. EmbeddingGemma 2 is trained with Matryoshka Representation Learning, and its model card lists 128, 256, 512 and 768 as supported dimensions. None of its published configs (`config.json`, `config_sentence_transformers.json`, `sentence_bert_config.json`) declares this, so vLLM treats the model as non-Matryoshka and rejects every request that sets `dimensions`. Today users need `--hf-overrides '{\"matryoshka_dimensions\": [...]}'` to get the documented behavior.\n\nThis PR sets `matryoshka_dimensions = [128, 256, 512, 768]` in `EmbeddingGemma2ModelConfig.verify_and_update_model_config`, the same hook `JinaForRankingConfig` uses to set `embedding_size`.\n\n## Claims\n\n- Without overrides, `dimensions` of 128, 256 and 512 are accepted, and other values are rejected with the existing \"only supports Matryoshka dimensions\" error.\n- No change for requests without `dimensions`, or for other models.\n- The pooler truncates before it normalizes (`seqwise/heads.py`), which matches the model card's \"re-normalize after truncating\".\n\n## Validation\n[results removed]\n## Question\n\nNo other model in vLLM sets `matryoshka_dimensions` from its config hook; it normally comes from the checkpoint's `config.json`. Is setting it here OK, or would you rather it come from the model's config on the Hub?\n\n## Diff\n\n```diff\ndiff --git a/vllm/model_executor/models/config.py b/vllm/model_executor/models/config.py\nindex dc7b5fabcf83..e435e1b58b60 100644\n--- a/vllm/model_executor/models/config.py\n+++ b/vllm/model_executor/models/config.py\n@@ -529,6 +529,17 @@ def verify_and_update_config(vllm_config: \"VllmConfig\") -> None:\n \n \n class EmbeddingGemma2ModelConfig(Gemma4Config):\n+ @staticmethod\n+ def verify_and_update_model_config(model_config: \"ModelConfig\") -> None:\n+ # Trained with Matryoshka Representation Learning (see the model card),\n+ # but the published configs don't declare the supported dimensions.\n+ # Only fill in the default; keep explicit settings such as overrides.\n+ hf_config = model_config.hf_config\n+ if not hasattr(hf_config, \"matryoshka_dimensions\") and not hasattr(\n+ hf_config, \"is_matryoshka\"\n+ ):\n+ hf_config.matryoshka_dimensions = [128, 256, 512, 768]\n+\n @staticmethod\n def verify_and_update_config(vllm_config: \"VllmConfig\") -> None:\n Gemma4Config.verify_and_update_config(vllm_config)\n\ndiff --git a/tests/models/multimodal/pooling/test_embedding_gemma2.py b/tests/models/multimodal/pooling/test_embedding_gemma2.py\nindex ff4f7e9fb167..3e88eca4bbfc 100644\n--- a/tests/models/multimodal/pooling/test_embedding_gemma2.py\n+++ b/tests/models/multimodal/pooling/test_embedding_gemma2.py\n@@ -91,6 +91,25 @@ def test_text_parity(vllm_runner, st_model, prompt):\n )\n \n \n+@needs_model\n+def test_matryoshka_parity(vllm_runner, st_model):\n+ from vllm import PoolingParams\n+\n+ prompt = \"task: search result | query: what is vllm\"\n+ # 768 also needs embedding_size to report the 768-d output (#60978).\n+ dims = [128, 256, 512]\n+ with vllm_runner(MODEL, runner=\"pooling\", max_model_len=8192) as vm:\n+ outs = vm.embed(\n+ [prompt] * len(dims),\n+ pooling_params=[PoolingParams(dimensions=d) for d in dims],\n+ )\n+ for d, out in zip(dims, outs):\n+ ref = st_model.encode([prompt], truncate_dim=d, normalize_embeddings=True)\n+ assert len(out) == d\n+ sim = _cos([out], ref).min().item()\n+ assert sim >= TEXT_COS, f\"Matryoshka {d}d cosine {sim} < {TEXT_COS}\"\n+\n+\n @needs_model\n def test_mm_recipe(vllm_runner, st_model):\n from PIL import Image\n@@ -648,6 +667,38 @@ def test_config_capping_and_explicit_limits():\n assert cfg_explicit_16k.model_config.max_model_len == 16384\n \n \n+def _update_matryoshka_config(**hf_config_fields):\n+ from types import SimpleNamespace\n+\n+ from vllm.model_executor.models.config import EmbeddingGemma2ModelConfig\n+\n+ hf_config = SimpleNamespace(**hf_config_fields)\n+ EmbeddingGemma2ModelConfig.verify_and_update_model_config(\n+ SimpleNamespace(hf_config=hf_config)\n+ )\n+ return hf_config\n+\n+\n+def test_sets_matryoshka_dimensions_from_model_card():\n+ assert _update_matryoshka_config().matryoshka_dimensions == [128, 256, 512, 768]\n+\n+\n+@pytest.mark.parametrize(\n+ \"fields\",\n+ [\n+ {\"matryoshka_dimensions\": [768, 256]},\n+ {\"matryoshka_dimensions\": None},\n+ {\"is_matryoshka\": True},\n+ {\"is_matryoshka\": False},\n+ ],\n+)\n+def test_keeps_declared_matryoshka_config(fields):\n+ hf_config = _update_matryoshka_config(**fields)\n+ assert getattr(hf_config, \"matryoshka_dimensions\", None) == fields.get(\n+ \"matryoshka_dimensions\"\n+ )\n+\n+\n def test_sentence_transformer_tokenizer_config_max_seq_length(tmp_path):\n \"\"\"Verify get_sentence_transformer_tokenizer_config accepts config\n with only max_seq_length.\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: vllm-project/vllm\nPull request: [Bugfix][Benchmark] Keep numeric-string prompts as strings in CustomDataset\nLabels: bug, performance, ready\nFiles changed (2): tests/benchmarks/test_custom_dataset_seed.py, vllm/benchmarks/datasets/datasets.py\n\n## Description (results removed)\n\n## Overview\n\n## Claims\n\n- JSON string prompts are kept exactly as written, regardless of what other rows contain.\n- `output_tokens` and other columns are unaffected.\n\n## Validation\n[results removed]\n## Details\n\nThe other two `pd.read_json` callers in `datasets.py` read list-valued columns (`turns` / `messages`), which pandas does not coerce, so they are left alone.\n\nNot a duplicate: no open PR references #65071. #60506 and #61776 also touch `CustomDataset` but address output lengths / audio without a tokenizer in `sample()`, not the `read_json` dtype.\n\n---\n\nAI assistance (Claude) was used to locate the root cause, write the fix and test, and run the validation above; I reviewed every changed line and ran the tests locally.\n\n## Diff\n\n```diff\ndiff --git a/vllm/benchmarks/datasets/datasets.py b/vllm/benchmarks/datasets/datasets.py\nindex 3746ac727e0f..322e409aac4f 100644\n--- a/vllm/benchmarks/datasets/datasets.py\n+++ b/vllm/benchmarks/datasets/datasets.py\n@@ -2451,7 +2451,10 @@ def load_data(self) -> None:\n \n # Load the JSONL file\n if self.dataset_path.endswith(\".jsonl\"):\n- jsonl_data = pd.read_json(path_or_buf=self.dataset_path, lines=True)\n+ # Keep prompts like \"00123\" as strings instead of inferring numbers.\n+ jsonl_data = pd.read_json(\n+ path_or_buf=self.dataset_path, lines=True, dtype={\"prompt\": str}\n+ )\n \n # check if the JSONL file has a 'prompt' column\n if \"prompt\" not in jsonl_data.columns:\n\ndiff --git a/tests/benchmarks/test_custom_dataset_seed.py b/tests/benchmarks/test_custom_dataset_seed.py\nindex d23ce40b53e7..e38b1451655c 100644\n--- a/tests/benchmarks/test_custom_dataset_seed.py\n+++ b/tests/benchmarks/test_custom_dataset_seed.py\n@@ -5,9 +5,11 @@\n from pathlib import Path\n \n import pytest\n-from transformers import AutoTokenizer, PreTrainedTokenizerBase\n+from tokenizers import Tokenizer\n+from tokenizers.models import WordLevel\n+from transformers import AutoTokenizer, PreTrainedTokenizerBase, TokenizersBackend\n \n-from vllm.benchmarks.datasets import get_samples\n+from vllm.benchmarks.datasets import CustomDataset, get_samples\n \n \n @pytest.fixture(scope=\"session\")\n@@ -75,3 +77,22 @@ def test_custom_dataset_same_seed_is_deterministic(\n prompts_b = [s.prompt for s in samples_b]\n \n assert prompts_a == prompts_b\n+\n+\n+@pytest.mark.benchmark\n+def test_custom_dataset_keeps_numeric_string_prompts(tmp_path: Path) -> None:\n+ \"\"\"All-numeric string prompts must not be inferred as numbers by pandas.\"\"\"\n+ prompts = [\"00123\", \"00456\"]\n+ jsonl = tmp_path / \"data.jsonl\"\n+ jsonl.write_text(\n+ \"\".join(json.dumps({\"prompt\": p, \"output_tokens\": 4}) + \"\\n\" for p in prompts)\n+ )\n+ tokenizer = TokenizersBackend(\n+ tokenizer_object=Tokenizer(WordLevel({\"[UNK]\": 0}, unk_token=\"[UNK]\")),\n+ unk_token=\"[UNK]\",\n+ )\n+\n+ dataset = CustomDataset(dataset_path=str(jsonl), disable_shuffle=True)\n+ requests = dataset.sample(tokenizer, num_requests=2, skip_chat_template=True)\n+\n+ assert [r.prompt for r in requests] == prompts\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ROCm/aiter\nPull request: [FlyDSL] Fix grouped GEMM C ABI overflow for large EP buffers\nLabels: FlyDSL\nFiles changed (4): aiter/ops/flydsl/grouped_gemm_mxfp4.py, aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py, op_tests/tuning_tests/test_grouped_gemm_launch_abi.py, op_tests/tuning_tests/test_grouped_gemm_launch_address.py\n\n## Description (results removed)\n\n## Summary\n\nFixes #7241. Grouped GEMM can launch large EP buffers without overflowing FlyDSL's host C ABI. Buffers used only for their base address now cross the launcher as typed pointers.\n\n## Motivation\n\nA flattened BF16 buffer shaped `[64, 8192, 7168]` has 3,758,096,384 elements. FlyDSL 0.4.1 packs runtime tensor dimensions as signed int32, so its generated `:4` raises the reported `struct.error`. `ep_arena_handle` is already a `Constexpr[int]` and is excluded from runtime packing; wrapping that constant in Int64 does not address this layout overflow.\n\n## Changes\n\n- Preserve argument order, stream, and existing specialization keys, including the constexpr arena address.\n\n## Performance\n[results removed]\n## Testing\n[results removed]\n## Documentation\n\n- [x] No public documentation change is needed: this fixes internal argument transport without changing the public operator API.\n\n## Breaking Changes\n\nNone to the public API. The internal grouped JIT launcher now accepts pointer arguments for address-only operands.\n\n## PR Self-Review\n\n### Reviewed revision\n\nd40a74c2d7079f90cf67b52135b83f7cb72c1536\n\n### Behavior and intent\n\n### PR-specific question\n\n### Changed op tests\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/aiter/ops/flydsl/grouped_gemm_mxfp4.py b/aiter/ops/flydsl/grouped_gemm_mxfp4.py\nindex 5934f0552f4..6c1724ed89c 100644\n--- a/aiter/ops/flydsl/grouped_gemm_mxfp4.py\n+++ b/aiter/ops/flydsl/grouped_gemm_mxfp4.py\n@@ -7,6 +7,7 @@\n \n import os\n \n+import flydsl.expr as fx\n import torch\n \n from .kernels.mega_moe_gfx1250.types import Stage2ScatterContext\n@@ -16,38 +17,6 @@\n _SUPPORTED_CLUSTER_N = (1, 2, 3, 4)\n \n \n-def _launch_address(tensor: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:\n- \"\"\"Rank-1 tensor at ``tensor``'s base address.\n-\n- The launcher cache must not specialize on buffer rank. ``view(-1)`` does\n- that for a contiguous buffer. Compact FP4 scales are a strided window on\n- the dispatch-wire pitch, so that view is rejected. The kernel steps rows\n- with ``a_scale_row_stride_bytes`` and only needs the base pointer, which a\n- unit-stride span of the pitched storage still provides.\n- \"\"\"\n- if tensor.numel() == 0:\n- empty = tensor if tensor.dtype == dtype else tensor.view(dtype)\n- return empty.view(0)\n- if not tensor.is_contiguous():\n- last = 0\n- for size, stride in zip(tensor.shape, tensor.stride()):\n- if size > 1:\n- last += (size - 1) * stride\n- span = last + 1\n- # view(dtype) needs the pitched span to be a whole number of elements.\n- # The bytes in between rows are the wire padding, so rounding up to\n- # the dtype stays inside the row pitch.\n- byte_span = span * tensor.element_size()\n- unit = dtype.itemsize\n- if byte_span % unit:\n- byte_span = (byte_span + unit - 1) // unit * unit\n- span = byte_span // tensor.element_size()\n- tensor = torch.as_strided(tensor, (span,), (1,))\n- if tensor.dtype != dtype:\n- tensor = tensor.view(dtype)\n- return tensor.view(-1)\n-\n-\n def _select_bool_env(name: str, csv_value: int) -> int:\n \"\"\"Select a strict 0/1 environment override or the CSV setting.\"\"\"\n value = os.environ.get(name)\n@@ -224,11 +193,12 @@ def flydsl_grouped_gemm_a8w4_masked(\n else:\n raise TypeError(f\"bias must be bf16, fp32 or fp16, got {bias.dtype}\")\n bias_ptr = ptr_arg(bias) if bias is not None else ptr_arg(a)\n- # These tensor arguments only supply base addresses, so normalize their\n- # ranks without specializing the compiled callable on buffer shapes.\n- quant_scale_tensor = (\n- out if quant_scale is None else quant_scale.view(torch.uint8)\n- ).view(-1)\n+ # These arguments only supply base addresses. Pass pointers below so large\n+ # buffers do not cross the C ABI with signed 32-bit tensor dimensions.\n+ quant_scale_tensor = out if quant_scale is None else quant_scale\n+ out_dtype = fx.Float16 if out_is_f16 else fx.BFloat16\n+ if stage1_quant_out:\n+ out_dtype = fx.Uint8\n n_tiles = (N + tile_n - 1) // tile_n\n cluster_n = _select_cluster_n(n_tiles, cluster_n)\n cluster_m = _select_cluster_m(cluster_m, cluster_n, stage1_act)\n@@ -273,7 +243,7 @@ def flydsl_grouped_gemm_a8w4_masked(\n f\"{stage2_scatter.combine_quant_bits} needs N % {n_align} == 0 to \"\n f\"keep the scale plane cache-line aligned, got N={N}\"\n )\n- ep_row_map_tensor = (ep_row_map if ep_row_map is not None else out).view(-1)\n+ ep_row_map_tensor = ep_row_map if ep_row_map is not None else out\n gemm_spec = (\n K,\n tile_m,\n@@ -316,11 +286,11 @@ def flydsl_grouped_gemm_a8w4_masked(\n )\n _run_compiled(\n launch_gemm_a8w4_tdm,\n- out.view(-1),\n+ ptr_arg(out, out_dtype),\n ptr_arg(a),\n ptr_arg(w),\n- _launch_address(a_scales, torch.int32),\n- _launch_address(w_scales, torch.int32),\n+ ptr_arg(a_scales, fx.Int32),\n+ ptr_arg(w_scales, fx.Int32),\n contiguous_m,\n stream,\n N,\n@@ -330,10 +300,10 @@ def flydsl_grouped_gemm_a8w4_masked(\n bias_ptr,\n float(swiglu_limit),\n *quant_spec,\n- quant_scale_tensor,\n+ ptr_arg(quant_scale_tensor),\n *tdm_spec,\n *ep_spec,\n- ep_row_map_tensor,\n+ ptr_arg(ep_row_map_tensor, fx.Int32),\n float(situ_beta),\n float(situ_linear_beta),\n *layout_spec,\ndiff --git a/aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py b/aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py\nindex 8ade7bc72bf..b83f1426d1a 100644\n--- a/aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py\n+++ b/aiter/ops/flydsl/kernels/mxfp4_preshuffle_gfx1250_tdm.py\n@@ -2528,11 +2528,11 @@ def issue_scatter_group(group, scatter_vector, vector_pass):\n \n @flyc.jit\n def launch_gemm_a8w4_tdm(\n- arg_c: fx.Tensor,\n+ arg_c: fx.Pointer,\n arg_a: fx.Pointer,\n arg_b: fx.Pointer,\n- arg_scale_a: fx.Tensor,\n- arg_scale_b: fx.Tensor,\n+ arg_scale_a: fx.Pointer,\n+ arg_scale_b: fx.Pointer,\n i32_m: fx.Int32,\n stream: fx.Stream,\n N: fx.Int32,\n@@ -2553,7 +2553,7 @@ def launch_gemm_a8w4_tdm(\n f32_swiglu_limit: fx.Float32,\n stage1_quant_out: Constexpr[int] = 0,\n quant_wmma_rep: Constexpr[int] = 1,\n- arg_quant_scale: fx.Tensor = None,\n+ arg_quant_scale: fx.Pointer = None,\n cluster_n: Constexpr[int] = 1,\n cluster_m: Constexpr[int] = 1,\n next_stage_prefetch: Constexpr[int] = 0,\n@@ -2567,7 +2567,7 @@ def launch_gemm_a8w4_tdm(\n ep_destination_stride: Constexpr[int] = 0,\n ep_world_size: Constexpr[int] = 0,\n ep_quant_bits: Constexpr[int] = 0,\n- arg_ep_row_map: fx.Tensor = None,\n+ arg_ep_row_map: fx.Pointer = None,\n f32_situ_beta: fx.Float32 = 1.0,\n f32_situ_linear_beta: fx.Float32 = 1.0,\n row_major_ascale: Constexpr[int] = 0,\n@@ -2706,15 +2706,15 @@ def run_task(task_id, rows):\n if arg_quant_scale is None:\n arg_quant_scale = arg_c\n kargs = (\n- fx.get_iter(arg_c),\n+ arg_c,\n arg_a,\n arg_b,\n- fx.get_iter(arg_scale_a),\n- fx.get_iter(arg_scale_b),\n+ arg_scale_a,\n+ arg_scale_b,\n arg_m_tile_map,\n arg_bias,\n- fx.get_iter(arg_quant_scale),\n- fx.get_iter(arg_ep_row_map),\n+ arg_quant_scale,\n+ arg_ep_row_map,\n i32_m,\n N,\n f32_swiglu_limit,\ndiff --git a/op_tests/tuning_tests/test_grouped_gemm_launch_abi.py b/op_tests/tuning_tests/test_grouped_gemm_launch_abi.py\nnew file mode 100644\nindex 00000000000..7bc6fab2c40\n--- /dev/null\n+++ b/op_tests/tuning_tests/test_grouped_gemm_launch_abi.py\n@@ -0,0 +1,225 @@\n+# SPDX-License-Identifier: MIT\n+# Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved.\n+\n+\"\"\"CPU regression tests for grouped GEMM's host C ABI (issue #7241).\"\"\"\n+\n+import ctypes\n+import inspect\n+\n+import pytest\n+import torch\n+\n+pytest.importorskip(\"flydsl.compiler\")\n+\n+from flydsl.compiler.jit_executor import CallState\n+from flydsl.compiler.jit_function import _build_call_spec\n+\n+from aiter.ops.flydsl import grouped_gemm_mxfp4 as grouped\n+from aiter.ops.flydsl.kernels import tensor_shim\n+from aiter.ops.flydsl.kernels.mega_moe_gfx1250.types import Stage2ScatterContext\n+from aiter.ops.flydsl.kernels.mxfp4_preshuffle_gfx1250_tdm import launch_gemm_a8w4_tdm\n+\n+_ADDRESS_ARGS = (\n+ \"arg_c\",\n+ \"arg_a\",\n+ \"arg_b\",\n+ \"arg_scale_a\",\n+ \"arg_scale_b\",\n+ \"arg_m_tile_map\",\n+ \"arg_bias\",\n+ \"arg_quant_scale\",\n+ \"arg_ep_row_map\",\n+)\n+\n+\n+@pytest.fixture\n+def dispatch(monkeypatch):\n+ \"\"\"Exercise the real host C ABI while replacing GPU compilation/execution.\"\"\"\n+ signature = inspect.signature(launch_gemm_a8w4_tdm.func)\n+ names = tuple(signature.parameters)\n+ compiled = []\n+ launches = []\n+\n+ def compile_and_run(exe, *args):\n+ assert exe is launch_gemm_a8w4_tdm\n+ slots = _build_call_spec(signature, args)\n+ address_slots = {\n+ names[index]: ctype\n+ for index, ctype, _fill in slots\n+ if index >= 0 and names[index] in _ADDRESS_ARGS\n+ }\n+ state = CallState(slots, lambda _packed: None)\n+\n+ def dispatch(*live_args):\n+ state(live_args)\n+ launches.append(\n+ {\n+ names[index]: storage.value\n+ for (index, _ctype, _fill), storage in zip(\n+ slots, state._tls.storages\n+ )\n+ if index >= 0\n+ }\n+ )\n+\n+ compiled.append(dispatch)\n+ dispatch(*args)\n+ assert address_slots == dict.fromkeys(_ADDRESS_ARGS, ctypes.c_void_p)\n+ assert not any(\n+ index >= 0 and names[index] == \"ep_arena_handle\"\n+ for index, _ctype, _fill in slots\n+ )\n+ return dispatch\n+\n+ monkeypatch.setattr(tensor_shim, \"_compile_and_run\", compile_and_run)\n+ monkeypatch.setattr(\n+ launch_gemm_a8w4_tdm, \"_cf_by_specialization\", {}, raising=False\n+ )\n+ return compiled, launches\n+\n+\n+@pytest.mark.parametrize(\"ep_quant_bits\", [None, 0, 4, 8])\n+@pytest.mark.parametrize(\"use_default_buffers\", [False, True])\n+def test_large_buffers_pack_on_first_and_cached_calls(\n+ dispatch, ep_quant_bits, use_default_buffers\n+):\n+ # Meta tensors exercise multi-billion-element dimensions without allocating\n+ # GPU memory. Arena addresses remain constexprs and are not ABI slots.\n+ compiled, launches = dispatch\n+ arena_handle = 132319086288896\n+\n+ def meta(shape, dtype=torch.uint8):\n+ return torch.empty(shape, dtype=dtype, device=\"meta\")\n+\n+ source_map = meta((64, 8192), torch.int32)\n+ scatter = (\n+ None\n+ if ep_quant_bits is None\n+ else Stage2ScatterContext(\n+ arena_handle=arena_handle,\n+ combine_input_offset=1611085056,\n+ slot_stride_bytes=16384,\n+ max_tokens_per_rank=8192,\n+ world_size=4,\n+ source_token_map=source_map,\n+ combine_quant_bits=ep_quant_bits,\n+ )\n+ )\n+ for shape in [(64, 8192, 7168), (64, 1, 7168)]:\n+ out = meta(shape, torch.bfloat16)\n+ assert (\n+ grouped.flydsl_grouped_gemm_a8w4_masked(\n+ out,\n+ meta((64, 256)),\n+ meta((64, 7168, 128)),\n+ meta((2**33,)), # int32 view still has 2**31 elements\n+ meta((2**33,)),\n+ meta((64,), torch.int32),\n+ n_experts=64,\n+ contiguous_m=shape[0] * shape[1],\n+ N=7168,\n+ K=256,\n+ stream=0,\n+ quant_scale=None if use_default_buffers else meta((2**31,)),\n+ ep_row_map=(\n+ None if use_default_buffers else meta((2**31,), torch.int32)\n+ ),\n+ stage2_scatter=scatter,\n+ )\n+ is out\n+ )\n+\n+ assert len(compiled) == 1\n+ assert len(launches) == 2\n+\n+\n+@pytest.mark.parametrize(\"dtype\", [torch.bfloat16, torch.float16, torch.uint8])\n+def test_pitched_and_offset_addresses_survive_cached_dispatch(dispatch, dtype):\n+ compiled, launches = dispatch\n+ for rows in (64, 128):\n+ out = torch.empty((rows, 256), dtype=dtype)\n+ a = torch.empty((rows, 260), dtype=torch.uint8)[:, 4:]\n+ w = torch.empty((1, 256, 128), dtype=torch.uint8)\n+ # Compact scales are a pitched window with a nonzero storage offset.\n+ storage = torch.empty(rows * 512 + 4, dtype=torch.uint8)\n+ a_scales = torch.as_strided(storage, (rows, 224), (512, 1), storage_offset=4)\n+ w_scales = torch.empty((256, 8), dtype=torch.uint8)\n+ tile_map = torch.empty(1, dtype=torch.int32)\n+ quant_scale = torch.empty((rows, 8), dtype=torch.uint8)[:, 4:]\n+ row_map = torch.empty(rows + 1, dtype=torch.int32)[1:]\n+ assert (\n+ grouped.flydsl_grouped_gemm_a8w4_masked(\n+ out,\n+ a,\n+ w,\n+ a_scales,\n+ w_scales,\n+ tile_map,\n+ n_experts=1,\n+ contiguous_m=rows,\n+ N=256,\n+ K=256,\n+ stream=0,\n+ out_is_f16=int(dtype == torch.float16),\n+ stage1_act=int(dtype == torch.uint8),\n+ stage1_quant_out=int(dtype == torch.uint8),\n+ quant_scale=quant_scale,\n+ ep_row_map=row_map,\n+ )\n+ is out\n+ )\n+ expected = {\n+ \"arg_c\": out,\n+ \"arg_a\": a,\n+ \"arg_b\": w,\n+ \"arg_scale_a\": a_scales,\n+ \"arg_scale_b\": w_scales,\n+ \"arg_m_tile_map\": tile_map,\n+ \"arg_bias\": a,\n+ \"arg_quant_scale\": quant_scale,\n+ \"arg_ep_row_map\": row_map,\n+ }\n+ assert {name: launches[-1][name] for name in expected} == {\n+ name: tensor.data_ptr() for name, tensor in expected.items()\n+ }\n+ assert launches[-1][\"i32_m\"] == rows\n+ assert len(compiled) == 1\n+ assert len(launches) == 2\n+\n+\n+def test_large_device_pointer_is_preserved_by_the_cabi():\n+ address = 132319086288896\n+ pointer = tensor_shim.flyc.from_c_void_p(tensor_shim.fx.Uint8, address)\n+\n+ def launcher(buffer):\n+ pass\n+\n+ slots = _build_call_spec(inspect.signature(launcher), (pointer,))\n+ state = CallState(slots, lambda _packed: None)\n+ state((pointer,))\n+ assert state._tls.storages[0].value == address\n+\n+\n+def test_changing_arena_selects_a_new_specialization(dispatch):\n+ compiled, launches = dispatch\n+ out = torch.empty((64, 256), dtype=torch.bfloat16, device=\"meta\")\n+ data = torch.empty((64, 256), dtype=torch.uint8, device=\"meta\")\n+ ids = torch.empty(64, dtype=torch.int32, device=\"meta\")\n+ for handle in (132319086288896, 132319086288896, 132319086292992):\n+ scatter = Stage2ScatterContext(handle, 1611085056, 16384, 8192, 4, ids)\n+ grouped.flydsl_grouped_gemm_a8w4_masked(\n+ out,\n+ data,\n+ data,\n+ data,\n+ data,\n+ ids,\n+ n_experts=1,\n+ contiguous_m=64,\n+ N=256,\n+ K=256,\n+ stream=0,\n+ stage2_scatter=scatter,\n+ )\n+ assert len(compiled) == 2\n+ assert len(launches) == 3\ndiff --git a/op_tests/tuning_tests/test_grouped_gemm_launch_address.py b/op_tests/tuning_tests/test_grouped_gemm_launch_address.py\ndeleted file mode 100644\nindex 752c124ae39..00000000000\n--- a/op_tests/tuning_tests/test_grouped_gemm_launch_address.py\n+++ /dev/null\n@@ -1,56 +0,0 @@\n-# SPDX-License-Identifier: MIT\n-# Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved.\n-\"\"\"Launcher addresses keep the base pointer of a pitched scale plane.\n-\n-Compact FP4 scales are a strided window on the dispatch wire. The grouped\n-GEMM launcher has to hand the kernel that base address as a rank-1 tensor\n-without packing the pitch out of the buffer.\n-\n-No GPU. Importing the launcher pulls torch in.\n-\n-Run:\n- python3 -m unittest op_tests.tuning_tests.test_grouped_gemm_launch_address -v\n-\"\"\"\n-\n-import os\n-import unittest\n-\n-os.environ.setdefault(\"GPU_ARCHS\", \"gfx1250\")\n-os.environ.setdefault(\"CU_NUM\", \"256\")\n-\n-try:\n- import torch\n-\n- from aiter.ops.flydsl.grouped_gemm_mxfp4 import _launch_address\n-\n- _IMPORT_ERR = None\n-except Exception as e: # noqa: BLE001\n- torch = _launch_address = None\n- _IMPORT_ERR = e\n-\n-\n-class LaunchAddressTest(unittest.TestCase):\n- def setUp(self):\n- if _IMPORT_ERR is not None:\n- self.skipTest(f\"import failed: {_IMPORT_ERR}\")\n-\n- def test_contiguous_buffer_flattens(self):\n- weights = torch.arange(16, dtype=torch.int32)\n- flat = _launch_address(weights, torch.int32)\n- self.assertEqual(flat.shape, (16,))\n- self.assertTrue(torch.equal(flat, weights))\n- self.assertEqual(flat.data_ptr(), weights.data_ptr())\n-\n- def test_pitched_scale_keeps_base_address(self):\n- # 8 scale rows of 224 B on a 512 B wire pitch, matching a compact\n- # FP4 dispatch window that view(-1) rejects.\n- storage = torch.arange(8 * 512, dtype=torch.uint8)\n- scales = torch.as_strided(storage, (8, 224), (512, 1))\n- with self.assertRaises(RuntimeError):\n- scales.view(torch.int32).view(-1)\n- flat = _launch_address(scales, torch.int32)\n- self.assertEqual(flat.ndim, 1)\n- self.assertEqual(flat.dtype, torch.int32)\n- self.assertTrue(flat.is_contiguous())\n- self.assertEqual(flat.data_ptr(), scales.data_ptr())\n- self.assertEqual(flat.view(torch.uint8)[:224].tolist(), list(range(224)))\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(backends): report cached-token usage during vLLM and SGLang streaming\nLabels: external-contribution, size/XL, backend::vllm, fix, backend::sglang, frontend\nFiles changed (13): components/src/dynamo/frontend/sglang_processor.py, components/src/dynamo/frontend/tests/test_sglang_processor_metrics_unit.py, components/src/dynamo/frontend/tests/test_sglang_processor_unit.py, components/src/dynamo/frontend/tests/test_vllm_processor_unit.py, components/src/dynamo/frontend/usage.py, components/src/dynamo/frontend/vllm_processor.py, components/src/dynamo/sglang/request_handlers/llm/decode_handler.py, components/src/dynamo/sglang/tests/test_sglang_decode_handler.py, components/src/dynamo/thunderagent_router/__main__.py, components/src/dynamo/thunderagent_router/tests/test_main.py, components/src/dynamo/vllm/handlers.py, components/src/dynamo/vllm/tests/test_vllm_delta_streaming.py, lib/llm/src/protocols/openai/delta_common.rs\n\n## Description (results removed)\n\n## Summary\n\nPreviously, both adapters attached `completion_usage` only at completion. Continuous-usage clients could receive generated-token totals but no cache details before then, including when they disconnected early.\n\nCloses #14850 (vLLM) and #14938 (SGLang).\n\n## Implementation\n\n- Both adapters emit usage on the first usable report per choice, when prompt/cache metadata changes, and at completion. Explicit zero and unavailable cache counts remain distinct.\n- vLLM maintains an O(1) request-wide cumulative completion total, advancing it as each choice is emitted so snapshots do not include later, un-emitted choices.\n- SGLang captures usage before metadata-upload cleanup clears engine metadata and continues treating incomplete usage as optional. Token and native terminal paths share the helper that preserves explicit zero cache counts.\n- The optional Python vLLM and SGLang chat processors now retain sparse usage metadata and count generated tokens locally. Both use shared metadata-retention and response-projection helpers. All streamed usage, including terminal usage, requires `include_usage`; intermediate usage additionally requires `continuous_usage_stats`. Non-streaming usage remains available. Metadata survives suppressed deltas and SGLang batched flushes.\n\nThunderAgent counts output token IDs until a terminal engine usage report arrives, preserving correct completion totals on early disconnect or stream errors.\n\n## Reviewer entry points\n\n- `components/src/dynamo/vllm/handlers.py`: `BaseWorkerHandler.generate_tokens`\n- `components/src/dynamo/sglang/request_handlers/llm/decode_handler.py`: `_process_token_stream`\n- `components/src/dynamo/frontend/{vllm,sglang}_processor.py`: `_generate_and_stream`\n- Backend delta/usage tests, Python frontend usage tests, and the Rust `delta_common.rs` metadata-persistence test.\n\n## Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/frontend/sglang_processor.py b/components/src/dynamo/frontend/sglang_processor.py\nindex db631193a800..3fda3b1de7bd 100644\n--- a/components/src/dynamo/frontend/sglang_processor.py\n+++ b/components/src/dynamo/frontend/sglang_processor.py\n@@ -42,6 +42,7 @@\n )\n from .structural_tag_policy import runtime_structural_tag_options\n from .thinking import runtime_default_thinking_mode\n+from .usage import response_usage, update_usage_metadata\n from .utils import (\n PreprocessError,\n PromptLogprobsAccumulator,\n@@ -805,7 +806,7 @@ async def _generate_and_stream(\n pending_token_ids: list[int] = []\n pending_log_probs: list[float] | None = None\n pending_top_logprobs: list[list[dict[str, Any]]] | None = None\n- pending_usage: dict[str, Any] | None = None\n+ latest_usage: dict[str, Any] = {}\n pending_terminal: dict[str, Any] | None = None\n first_chunk = True\n input_tokens = len(tokens)\n@@ -828,7 +829,7 @@ def flush_pending(\n nonlocal pending_token_ids\n nonlocal pending_log_probs\n nonlocal pending_top_logprobs\n- nonlocal pending_usage\n+ nonlocal latest_usage\n nonlocal first_chunk\n nonlocal post_proc_total_ms\n nonlocal token_count\n@@ -850,13 +851,13 @@ def flush_pending(\n \n choice = post.process_output(mapped_response)\n \n- if post.locally_finished and pending_usage is None:\n- pending_usage = {\n+ if post.locally_finished and not latest_usage:\n+ latest_usage = {\n \"prompt_tokens\": input_tokens,\n \"completion_tokens\": cumulative_output_tokens,\n \"total_tokens\": input_tokens + cumulative_output_tokens,\n }\n- usage_for_metrics = pending_usage\n+ usage_for_metrics = latest_usage\n \n if self.debug_perf:\n t_pp1 = time.monotonic()\n@@ -872,8 +873,14 @@ def flush_pending(\n \"model\": request[\"model\"],\n \"object\": \"chat.completion.chunk\",\n }\n- if pending_usage:\n- dynamo_out[\"usage\"] = pending_usage\n+ if usage := response_usage(\n+ request,\n+ latest_usage,\n+ prompt_tokens=input_tokens,\n+ completion_tokens=cumulative_output_tokens,\n+ finished=bool(finish_reason or post.locally_finished),\n+ ):\n+ dynamo_out[\"usage\"] = usage\n response_nvext: dict[str, Any] = {}\n effective_stop_reason = (\n stop_reason\n@@ -920,10 +927,25 @@ def flush_pending(\n pending_token_ids = []\n pending_log_probs = None\n pending_top_logprobs = None\n- pending_usage = None\n first_chunk = False\n return envelope\n \n+ def finalize_terminal(terminal: dict[str, Any]) -> dict[str, Any]:\n+ data = terminal[\"data\"]\n+ if usage := response_usage(\n+ request,\n+ latest_usage,\n+ prompt_tokens=input_tokens,\n+ completion_tokens=cumulative_output_tokens,\n+ finished=True,\n+ ):\n+ data[\"usage\"] = usage\n+ cached_tokens = _cached_tokens_from_usage(latest_usage)\n+ if cached_tokens is not None:\n+ data[\"llm_metrics\"][\"cached_tokens\"] = cached_tokens\n+ prompt_logprobs.attach(data)\n+ return terminal\n+\n async for dynamo_response in dynamo_stream:\n if dynamo_response.is_error():\n comments = dynamo_response.comments() or []\n@@ -960,11 +982,12 @@ def flush_pending(\n )\n break\n prompt_logprobs.update(engine_response)\n+ if usage := engine_response.get(\"completion_usage\"):\n+ update_usage_metadata(latest_usage, usage)\n if pending_terminal is not None:\n if prompt_logprobs.needs_payload and not backend_finished:\n continue\n- prompt_logprobs.attach(pending_terminal[\"data\"])\n- yield pending_terminal\n+ yield finalize_terminal(pending_terminal)\n break\n \n new_ids = engine_response[\"token_ids\"]\n@@ -1013,8 +1036,6 @@ def flush_pending(\n stop_reason = engine_response.get(\"stop_reason\")\n stop_terminated = raw_finish_reason in {\"eos\", \"stop\"}\n \n- if usage := engine_response.get(\"completion_usage\"):\n- pending_usage = usage\n engine_data = engine_response.get(\"engine_data\")\n \n pending_token_ids.extend(new_ids)\n@@ -1052,7 +1073,7 @@ def flush_pending(\n break\n else:\n if pending_terminal is not None:\n- yield pending_terminal\n+ yield finalize_terminal(pending_terminal)\n except (InvalidArgument, Unknown):\n raise\n except Exception as e:\ndiff --git a/components/src/dynamo/frontend/usage.py b/components/src/dynamo/frontend/usage.py\nnew file mode 100644\nindex 000000000000..6c86639f13d8\n--- /dev/null\n+++ b/components/src/dynamo/frontend/usage.py\n@@ -0,0 +1,41 @@\n+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+# SPDX-License-Identifier: Apache-2.0\n+\n+from typing import Any\n+\n+\n+def update_usage_metadata(metadata: dict[str, Any], usage: dict[str, Any]) -> None:\n+ \"\"\"Retain known prompt/cache details across sparse backend reports.\"\"\"\n+ for field in (\n+ \"prompt_tokens\",\n+ \"prompt_tokens_details\",\n+ \"completion_tokens_details\",\n+ ):\n+ if usage.get(field) is not None:\n+ metadata[field] = usage[field]\n+\n+\n+def response_usage(\n+ request: dict[str, Any],\n+ metadata: dict[str, Any],\n+ *,\n+ prompt_tokens: int,\n+ completion_tokens: int,\n+ finished: bool,\n+) -> dict[str, Any] | None:\n+ \"\"\"Project locally counted usage according to the client's streaming options.\"\"\"\n+ if not metadata:\n+ return None\n+ if request.get(\"stream\", False):\n+ options = request.get(\"stream_options\") or {}\n+ if not options.get(\"include_usage\", False):\n+ return None\n+ if not finished and not options.get(\"continuous_usage_stats\", False):\n+ return None\n+ prompt_tokens = metadata.get(\"prompt_tokens\", prompt_tokens)\n+ return {\n+ **metadata,\n+ \"prompt_tokens\": prompt_tokens,\n+ \"completion_tokens\": completion_tokens,\n+ \"total_tokens\": prompt_tokens + completion_tokens,\n+ }\ndiff --git a/components/src/dynamo/frontend/vllm_processor.py b/components/src/dynamo/frontend/vllm_processor.py\nindex d5582f25e69f..5b59b4e92a38 100644\n--- a/components/src/dynamo/frontend/vllm_processor.py\n+++ b/components/src/dynamo/frontend/vllm_processor.py\n@@ -50,6 +50,7 @@\n runtime_structural_tag_options,\n )\n from .thinking import runtime_default_thinking_mode\n+from .usage import response_usage, update_usage_metadata\n from .utils import (\n PromptLogprobsAccumulator,\n as_error_envelope,\n@@ -1258,6 +1259,7 @@ async def _generate_and_stream(\n # content-part counts here too (else frontend metrics report zero media).\n input_tokens = len(tokens)\n cumulative_output_tokens = 0\n+ usage_metadata: dict[str, Any] = {}\n # Per-request reasoning-token usage (NVBug 6678449b); see\n # _ReasoningUsageAnnotator. Must be per-request, never module-level.\n # The counts live on the post-processors, which are per-request too.\n@@ -1278,6 +1280,16 @@ async def _generate_and_stream(\n pending_terminals: dict[int, dict[str, Any]] = {}\n locally_stopped_requests: set[str] = set()\n \n+ def attach_usage(output: dict[str, Any], *, finished: bool) -> None:\n+ if usage := response_usage(\n+ request,\n+ usage_metadata,\n+ prompt_tokens=input_tokens,\n+ completion_tokens=cumulative_output_tokens,\n+ finished=finished,\n+ ):\n+ output[\"usage\"] = reasoning_usage.annotate(usage)\n+\n try:\n _inject_routing_metadata(dynamo_preproc, dynamo_preproc, mm_routing_info)\n with _nvtx.annotate(\"mm_frontend:routed_engine_generate\", color=\"red\"):\n@@ -1331,6 +1343,9 @@ async def _generate_and_stream(\n break\n \n prompt_logprobs.update(engine_response)\n+ # Keep sparse metadata even when a choice is suppressed locally.\n+ if backend_usage := engine_response.get(\"completion_usage\"):\n+ update_usage_metadata(usage_metadata, backend_usage)\n \n output_idx = engine_response.get(\"index\", 0) or 0\n output_request_id = output_request_ids.get(output_idx)\n@@ -1366,6 +1381,7 @@ async def _generate_and_stream(\n if prompt_logprobs.needs_payload and pending_idx != output_idx:\n continue\n terminal = pending_terminals.pop(pending_idx)\n+ attach_usage(terminal, finished=True)\n prompt_logprobs.attach(terminal)\n yield {\"_dynamo_annotated\": True, \"data\": terminal}\n \n@@ -1461,8 +1477,11 @@ async def _generate_and_stream(\n \"model\": request[\"model\"],\n \"object\": \"chat.completion.chunk\",\n }\n- if usage := engine_response.get(\"completion_usage\"):\n- dynamo_out[\"usage\"] = reasoning_usage.annotate(usage)\n+ attach_usage(\n+ dynamo_out,\n+ finished=bool(raw_finish_reason)\n+ or output_request_id in locally_stopped_requests,\n+ )\n prompt_logprobs.attach(dynamo_out)\n if (\n output_request_id in locally_stopped_requests\n@@ -1496,6 +1515,7 @@ async def _generate_and_stream(\n yield envelope\n else:\n for terminal in pending_terminals.values():\n+ attach_usage(terminal, finished=True)\n yield {\"_dynamo_annotated\": True, \"data\": terminal}\n _nvtx.end_range(rng_stream)\n except VLLMClientError:\ndiff --git a/components/src/dynamo/sglang/request_handlers/llm/decode_handler.py b/components/src/dynamo/sglang/request_handlers/llm/decode_handler.py\nindex dd6fcb3ba7f9..f36bd37c2f6b 100644\n--- a/components/src/dynamo/sglang/request_handlers/llm/decode_handler.py\n+++ b/components/src/dynamo/sglang/request_handlers/llm/decode_handler.py\n@@ -207,7 +207,7 @@ def _kv_cache_hit_engine_data(meta_info: Mapping[str, Any]) -> Dict[str, Any]:\n \n \n def _sglang_completion_usage(meta_info: Mapping[str, Any]) -> Dict[str, Any] | None:\n- \"\"\"Build Dynamo's completion_usage from SGLang's terminal meta_info.\"\"\"\n+ \"\"\"Build Dynamo's completion_usage from SGLang metadata.\"\"\"\n prompt_tokens = meta_info.get(\"prompt_tokens\")\n completion_tokens = meta_info.get(\"completion_tokens\")\n if prompt_tokens is None or completion_tokens is None:\n@@ -218,7 +218,7 @@ def _sglang_completion_usage(meta_info: Mapping[str, Any]) -> Dict[str, Any] | N\n \"total_tokens\": prompt_tokens + completion_tokens,\n }\n cached_tokens = meta_info.get(\"cached_tokens\")\n- if cached_tokens is not None and cached_tokens > 0:\n+ if cached_tokens is not None:\n usage[\"prompt_tokens_details\"] = {\"cached_tokens\": cached_tokens}\n return usage\n \n@@ -1066,6 +1066,7 @@ async def _process_token_stream(\n request_id_future: asyncio.Future[str] = asyncio.Future()\n request_ids: set[str] = set()\n first_output_seen = False\n+ usage_metadata_by_index: dict[int, tuple[int, int | None]] = {}\n async with self._cancellation_monitor(\n request_id_future,\n context,\n@@ -1147,6 +1148,20 @@ async def _process_token_stream(\n # the engine's opaque engine_data passthrough (surfaced by the frontend\n # as nvext.routed_experts); disaggregated_params stays KV-transfer only.\n engine_data[\"routed_experts\"] = routed_experts\n+ # The frontend retains prompt/cache metadata and counts output\n+ # tokens itself. Capture changes before metadata upload clears it.\n+ usage_metadata = (\n+ meta_info.get(\"prompt_tokens\"),\n+ meta_info.get(\"cached_tokens\"),\n+ )\n+ changed = (\n+ finish_reason\n+ or usage_metadata_by_index.get(output_idx) != usage_metadata\n+ )\n+ if changed and (usage := _sglang_completion_usage(meta_info)):\n+ out[\"completion_usage\"] = usage\n+ usage_metadata_by_index[output_idx] = usage_metadata\n+\n if finish_reason:\n prompt_payload = (\n _shared_logprobs.extract_prompt_logprobs_from_sglang_meta(\n@@ -1163,9 +1178,6 @@ async def _process_token_stream(\n )\n if kv_cache_hit:\n engine_data[\"kv_cache_hit\"] = kv_cache_hit\n- completion_usage = _sglang_completion_usage(meta_info)\n- if completion_usage is not None:\n- out[\"completion_usage\"] = completion_usage\n if metadata_uploader is not None:\n try:\n await metadata_uploader.upload_choice(output_idx, meta_info)\ndiff --git a/components/src/dynamo/thunderagent_router/__main__.py b/components/src/dynamo/thunderagent_router/__main__.py\nindex 57361d43746a..2a9299888e94 100644\n--- a/components/src/dynamo/thunderagent_router/__main__.py\n+++ b/components/src/dynamo/thunderagent_router/__main__.py\n@@ -283,7 +283,6 @@ async def generate(self, request: dict[str, Any]):\n \n prompt_tokens_seen = 0\n completion_tokens_seen = 0\n- usage_completion_seen = False\n first_chunk = True\n selected_worker_id = None\n proof = (\n@@ -339,18 +338,20 @@ async def generate(self, request: dict[str, Any]):\n prompt_tokens_seen = int(\n usage.get(\"prompt_tokens\", prompt_tokens_seen)\n )\n- if isinstance(usage.get(\"completion_tokens\"), int):\n- completion_tokens_seen = int(usage[\"completion_tokens\"])\n- usage_completion_seen = True\n token_ids_out = (\n chunk.get(\"token_ids\", []) if isinstance(chunk, dict) else []\n )\n if isinstance(token_ids_out, list) and token_ids_out:\n- # Engine usage is authoritative if present; only the\n- # token-id fallback path increments completion_tokens_seen.\n- if not usage_completion_seen:\n- completion_tokens_seen += len(token_ids_out)\n+ completion_tokens_seen += len(token_ids_out)\n self._scheduler.record_output_tokens(program_id, len(token_ids_out))\n+ # Intermediate usage can be sparse. Only a terminal report can\n+ # replace the token count used when a stream is interrupted.\n+ if (\n+ isinstance(usage, dict)\n+ and chunk.get(\"finish_reason\")\n+ and isinstance(usage.get(\"completion_tokens\"), int)\n+ ):\n+ completion_tokens_seen = usage[\"completion_tokens\"]\n \n if proof is not None:\n _inject_thunderagent_route_proof(chunk, proof)\ndiff --git a/components/src/dynamo/vllm/handlers.py b/components/src/dynamo/vllm/handlers.py\nindex 9b578985a320..ac67a5ecf9e4 100644\n--- a/components/src/dynamo/vllm/handlers.py\n+++ b/components/src/dynamo/vllm/handlers.py\n@@ -3375,16 +3375,16 @@ def _build_prompt_from_request(\n @staticmethod\n def _build_completion_usage(\n request_output: RequestOutput,\n- completion_token_counts: dict[int, int] | None = None,\n+ completion_tokens: int | None = None,\n ) -> Dict[str, Any]:\n \"\"\"\n Build completion usage statistics.\n \n Args:\n request_output: vLLM RequestOutput object\n- completion_token_counts: Optional cumulative generated-token counts by\n- output index. DELTA-mode streams need this\n- because the final vLLM chunk is not cumulative.\n+ completion_tokens: Optional cumulative request-wide generated-token\n+ count. DELTA-mode streams maintain this total because\n+ each vLLM chunk contains only newly generated tokens.\n \n Returns:\n Dict with prompt_tokens, completion_tokens, total_tokens, prompt_tokens_details\n@@ -3395,9 +3395,7 @@ def _build_completion_usage(\n else None\n )\n \n- if completion_token_counts is not None:\n- completion_tokens = sum(completion_token_counts.values())\n- else:\n+ if completion_tokens is None:\n completion_tokens = sum(\n len(output.token_ids) for output in request_output.outputs\n )\n@@ -3518,6 +3516,8 @@ async def generate_tokens(\n )\n \n total_output_tokens_by_index: dict[int, int] = {}\n+ total_output_tokens = 0\n+ usage_metadata_by_index: dict[int, tuple[int | None, int | None]] = {}\n raw_routed_experts_by_output: dict[int, Any] = {}\n raw_sampling_mask_by_output: dict[int, Any] = {}\n # vLLM surfaces prompt_logprobs once (at end-of-prefill) and clears\n@@ -3568,6 +3568,10 @@ async def generate_tokens(\n (output, output_idx, token_ids, finish_reason, stop_reason)\n )\n \n+ usage_metadata = (\n+ len(res.prompt_token_ids) if res.prompt_token_ids else None,\n+ getattr(res, \"num_cached_tokens\", None),\n+ )\n for (\n output,\n output_idx,\n@@ -3575,6 +3579,7 @@ async def generate_tokens(\n finish_reason,\n stop_reason,\n ) in prepared_outputs:\n+ total_output_tokens += len(token_ids)\n out: Dict[str, Any] = {\n \"index\": output_idx,\n \"token_ids\": token_ids,\n@@ -3613,18 +3618,26 @@ async def generate_tokens(\n if top_logprobs is not None:\n out[\"top_logprobs\"] = top_logprobs\n \n+ # The frontend retains prompt/cache metadata and counts output\n+ # tokens itself. Send changes and final totals, not per-token usage.\n+ if (\n+ finish_reason\n+ or usage_metadata_by_index.get(output_idx) != usage_metadata\n+ ):\n+ out[\n+ \"completion_usage\"\n+ ] = BaseWorkerHandler._build_completion_usage(\n+ request_output=res,\n+ completion_tokens=total_output_tokens,\n+ )\n+ usage_metadata_by_index[output_idx] = usage_metadata\n+\n if finish_reason:\n out[\"finish_reason\"] = normalized_finish_reason\n if engine_prompt_token_ids is not None:\n out[\"engine_data\"] = {\n \"prompt_token_ids\": list(engine_prompt_token_ids)\n }\n- out[\n- \"completion_usage\"\n- ] = BaseWorkerHandler._build_completion_usage(\n- request_output=res,\n- completion_token_counts=total_output_tokens_by_index,\n- )\n # With n > 1, later samples hit the prompt blocks earlier\n # ones just cached, and vLLM keeps the first buffered\n # sample's count when it merges outputs, so no sample's\ndiff --git a/lib/llm/src/protocols/openai/delta_common.rs b/lib/llm/src/protocols/openai/delta_common.rs\nindex 0ee9312e3fb6..9fafd9e7b0de 100644\n--- a/lib/llm/src/protocols/openai/delta_common.rs\n+++ b/lib/llm/src/protocols/openai/delta_common.rs\n@@ -217,6 +217,60 @@ pub(crate) fn force_include_usage(stream_options: &mut Option None:\n+ def __init__(\n+ self, chunks: Optional[list[dict[str, Any]]] = None, *, error=None\n+ ) -> None:\n self.chunks = chunks if chunks is not None else []\n+ self.error = error\n self.sent: Optional[dict[str, Any]] = None\n \n async def generate_from_request(self, preprocessed):\n@@ -133,6 +137,8 @@ async def generate_from_request(self, preprocessed):\n async def stream():\n for chunk in self.chunks:\n yield chunk\n+ if self.error is not None:\n+ raise self.error\n \n return stream()\n \n[... diff truncated: 1 more file(s) not shown]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(backends): report cached-token usage during vLLM and SGLang streaming\nLabels: external-contribution, size/XL, backend::vllm, fix, backend::sglang, frontend\nFiles changed (13): components/src/dynamo/frontend/sglang_processor.py, components/src/dynamo/frontend/tests/test_sglang_processor_metrics_unit.py, components/src/dynamo/frontend/tests/test_sglang_processor_unit.py, components/src/dynamo/frontend/tests/test_vllm_processor_unit.py, components/src/dynamo/frontend/usage.py, components/src/dynamo/frontend/vllm_processor.py, components/src/dynamo/sglang/request_handlers/llm/decode_handler.py, components/src/dynamo/sglang/tests/test_sglang_decode_handler.py, components/src/dynamo/thunderagent_router/__main__.py, components/src/dynamo/thunderagent_router/tests/test_main.py, components/src/dynamo/vllm/handlers.py, components/src/dynamo/vllm/tests/test_vllm_delta_streaming.py, lib/llm/src/protocols/openai/delta_common.rs\n\n## Description (results removed)\n\n## Summary\n\nPreviously, both adapters attached `completion_usage` only at completion. Continuous-usage clients could receive generated-token totals but no cache details before then, including when they disconnected early.\n\nCloses #14850 (vLLM) and #14938 (SGLang).\n\n## Implementation\n\n- Both adapters emit usage on the first usable report per choice, when prompt/cache metadata changes, and at completion. Explicit zero and unavailable cache counts remain distinct.\n- vLLM maintains an O(1) request-wide cumulative completion total, advancing it as each choice is emitted so snapshots do not include later, un-emitted choices.\n- SGLang captures usage before metadata-upload cleanup clears engine metadata and continues treating incomplete usage as optional. Token and native terminal paths share the helper that preserves explicit zero cache counts.\n- The optional Python vLLM and SGLang chat processors now retain sparse usage metadata and count generated tokens locally. Both use shared metadata-retention and response-projection helpers. All streamed usage, including terminal usage, requires `include_usage`; intermediate usage additionally requires `continuous_usage_stats`. Non-streaming usage remains available. Metadata survives suppressed deltas and SGLang batched flushes.\n\nThunderAgent counts output token IDs until a terminal engine usage report arrives, preserving correct completion totals on early disconnect or stream errors.\n\n## Reviewer entry points\n\n- `components/src/dynamo/vllm/handlers.py`: `BaseWorkerHandler.generate_tokens`\n- `components/src/dynamo/sglang/request_handlers/llm/decode_handler.py`: `_process_token_stream`\n- `components/src/dynamo/frontend/{vllm,sglang}_processor.py`: `_generate_and_stream`\n- Backend delta/usage tests, Python frontend usage tests, and the Rust `delta_common.rs` metadata-persistence test.\n\n## Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/frontend/sglang_processor.py b/components/src/dynamo/frontend/sglang_processor.py\nindex 5a25d3e64140..5892c927c7b0 100644\n--- a/components/src/dynamo/frontend/sglang_processor.py\n+++ b/components/src/dynamo/frontend/sglang_processor.py\n@@ -42,6 +42,7 @@\n )\n from .structural_tag_policy import runtime_structural_tag_options\n from .thinking import runtime_default_thinking_mode\n+from .usage import response_usage, update_usage_metadata\n from .utils import (\n PreprocessError,\n as_error_envelope,\n@@ -796,7 +797,7 @@ async def _generate_and_stream(\n pending_token_ids: list[int] = []\n pending_log_probs: list[float] | None = None\n pending_top_logprobs: list[list[dict[str, Any]]] | None = None\n- pending_usage: dict[str, Any] | None = None\n+ latest_usage: dict[str, Any] = {}\n first_chunk = True\n input_tokens = len(tokens)\n cumulative_output_tokens = 0\n@@ -818,7 +819,7 @@ def flush_pending(\n nonlocal pending_token_ids\n nonlocal pending_log_probs\n nonlocal pending_top_logprobs\n- nonlocal pending_usage\n+ nonlocal latest_usage\n nonlocal first_chunk\n nonlocal post_proc_total_ms\n nonlocal token_count\n@@ -840,13 +841,13 @@ def flush_pending(\n \n choice = post.process_output(mapped_response)\n \n- if post.locally_finished and pending_usage is None:\n- pending_usage = {\n+ if post.locally_finished and not latest_usage:\n+ latest_usage = {\n \"prompt_tokens\": input_tokens,\n \"completion_tokens\": cumulative_output_tokens,\n \"total_tokens\": input_tokens + cumulative_output_tokens,\n }\n- usage_for_metrics = pending_usage\n+ usage_for_metrics = latest_usage\n \n if self.debug_perf:\n t_pp1 = time.monotonic()\n@@ -862,8 +863,14 @@ def flush_pending(\n \"model\": request[\"model\"],\n \"object\": \"chat.completion.chunk\",\n }\n- if pending_usage:\n- dynamo_out[\"usage\"] = pending_usage\n+ if usage := response_usage(\n+ request,\n+ latest_usage,\n+ prompt_tokens=input_tokens,\n+ completion_tokens=cumulative_output_tokens,\n+ finished=bool(finish_reason or post.locally_finished),\n+ ):\n+ dynamo_out[\"usage\"] = usage\n response_nvext: dict[str, Any] = {}\n effective_stop_reason = (\n stop_reason\n@@ -909,7 +916,6 @@ def flush_pending(\n pending_token_ids = []\n pending_log_probs = None\n pending_top_logprobs = None\n- pending_usage = None\n first_chunk = False\n return envelope\n \n@@ -972,7 +978,8 @@ def flush_pending(\n stop_terminated = raw_finish_reason in {\"eos\", \"stop\"}\n \n if usage := engine_response.get(\"completion_usage\"):\n- pending_usage = usage\n+ # Cache reports can be sparse and arrive on buffered chunks.\n+ update_usage_metadata(latest_usage, usage)\n engine_data = engine_response.get(\"engine_data\")\n \n pending_token_ids.extend(new_ids)\ndiff --git a/components/src/dynamo/frontend/usage.py b/components/src/dynamo/frontend/usage.py\nnew file mode 100644\nindex 000000000000..6c86639f13d8\n--- /dev/null\n+++ b/components/src/dynamo/frontend/usage.py\n@@ -0,0 +1,41 @@\n+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+# SPDX-License-Identifier: Apache-2.0\n+\n+from typing import Any\n+\n+\n+def update_usage_metadata(metadata: dict[str, Any], usage: dict[str, Any]) -> None:\n+ \"\"\"Retain known prompt/cache details across sparse backend reports.\"\"\"\n+ for field in (\n+ \"prompt_tokens\",\n+ \"prompt_tokens_details\",\n+ \"completion_tokens_details\",\n+ ):\n+ if usage.get(field) is not None:\n+ metadata[field] = usage[field]\n+\n+\n+def response_usage(\n+ request: dict[str, Any],\n+ metadata: dict[str, Any],\n+ *,\n+ prompt_tokens: int,\n+ completion_tokens: int,\n+ finished: bool,\n+) -> dict[str, Any] | None:\n+ \"\"\"Project locally counted usage according to the client's streaming options.\"\"\"\n+ if not metadata:\n+ return None\n+ if request.get(\"stream\", False):\n+ options = request.get(\"stream_options\") or {}\n+ if not options.get(\"include_usage\", False):\n+ return None\n+ if not finished and not options.get(\"continuous_usage_stats\", False):\n+ return None\n+ prompt_tokens = metadata.get(\"prompt_tokens\", prompt_tokens)\n+ return {\n+ **metadata,\n+ \"prompt_tokens\": prompt_tokens,\n+ \"completion_tokens\": completion_tokens,\n+ \"total_tokens\": prompt_tokens + completion_tokens,\n+ }\ndiff --git a/components/src/dynamo/frontend/vllm_processor.py b/components/src/dynamo/frontend/vllm_processor.py\nindex 1e2a75f20534..ab05634d2ec6 100644\n--- a/components/src/dynamo/frontend/vllm_processor.py\n+++ b/components/src/dynamo/frontend/vllm_processor.py\n@@ -50,6 +50,7 @@\n runtime_structural_tag_options,\n )\n from .thinking import runtime_default_thinking_mode\n+from .usage import response_usage, update_usage_metadata\n from .utils import (\n as_error_envelope,\n backend_invalid_argument_to_http_error,\n@@ -1252,6 +1253,7 @@ async def _generate_and_stream(\n # content-part counts here too (else frontend metrics report zero media).\n input_tokens = len(tokens)\n cumulative_output_tokens = 0\n+ usage_metadata: dict[str, Any] = {}\n # Per-request reasoning-token usage (NVBug 6678449b); see\n # _ReasoningUsageAnnotator. Must be per-request, never module-level.\n # The counts live on the post-processors, which are per-request too.\n@@ -1325,6 +1327,10 @@ async def _generate_and_stream(\n # consume tokens without emitting a visible delta.\n chunk_tokens = len(engine_response.get(\"token_ids\") or [])\n cumulative_output_tokens += chunk_tokens\n+ # Workers send prompt/cache metadata only when it changes. Capture\n+ # it even if a tool/reasoning parser suppresses this chunk's text.\n+ if backend_usage := engine_response.get(\"completion_usage\"):\n+ update_usage_metadata(usage_metadata, backend_usage)\n \n output_idx = engine_response.get(\"index\", 0) or 0\n output_request_id = output_request_ids.get(output_idx)\n@@ -1424,7 +1430,13 @@ async def _generate_and_stream(\n \"model\": request[\"model\"],\n \"object\": \"chat.completion.chunk\",\n }\n- if usage := engine_response.get(\"completion_usage\"):\n+ if usage := response_usage(\n+ request,\n+ usage_metadata,\n+ prompt_tokens=input_tokens,\n+ completion_tokens=cumulative_output_tokens,\n+ finished=bool(raw_finish_reason),\n+ ):\n dynamo_out[\"usage\"] = reasoning_usage.annotate(usage)\n envelope[\"data\"] = dynamo_out\n \ndiff --git a/components/src/dynamo/sglang/request_handlers/llm/decode_handler.py b/components/src/dynamo/sglang/request_handlers/llm/decode_handler.py\nindex 511fe74afdb1..412b464f86f0 100644\n--- a/components/src/dynamo/sglang/request_handlers/llm/decode_handler.py\n+++ b/components/src/dynamo/sglang/request_handlers/llm/decode_handler.py\n@@ -207,7 +207,7 @@ def _kv_cache_hit_engine_data(meta_info: Mapping[str, Any]) -> Dict[str, Any]:\n \n \n def _sglang_completion_usage(meta_info: Mapping[str, Any]) -> Dict[str, Any] | None:\n- \"\"\"Build Dynamo's completion_usage from SGLang's terminal meta_info.\"\"\"\n+ \"\"\"Build Dynamo's completion_usage from SGLang metadata.\"\"\"\n prompt_tokens = meta_info.get(\"prompt_tokens\")\n completion_tokens = meta_info.get(\"completion_tokens\")\n if prompt_tokens is None or completion_tokens is None:\n@@ -218,7 +218,7 @@ def _sglang_completion_usage(meta_info: Mapping[str, Any]) -> Dict[str, Any] | N\n \"total_tokens\": prompt_tokens + completion_tokens,\n }\n cached_tokens = meta_info.get(\"cached_tokens\")\n- if cached_tokens is not None and cached_tokens > 0:\n+ if cached_tokens is not None:\n usage[\"prompt_tokens_details\"] = {\"cached_tokens\": cached_tokens}\n return usage\n \n@@ -1054,6 +1054,7 @@ async def _process_token_stream(\n request_id_future: asyncio.Future[str] = asyncio.Future()\n request_ids: set[str] = set()\n first_output_seen = False\n+ usage_metadata_by_index: dict[int, tuple[int, int | None]] = {}\n async with self._cancellation_monitor(\n request_id_future,\n context,\n@@ -1134,6 +1135,20 @@ async def _process_token_stream(\n # the engine's opaque engine_data passthrough (surfaced by the frontend\n # as nvext.routed_experts); disaggregated_params stays KV-transfer only.\n engine_data[\"routed_experts\"] = routed_experts\n+ # The frontend retains prompt/cache metadata and counts output\n+ # tokens itself. Capture changes before metadata upload clears it.\n+ usage_metadata = (\n+ meta_info.get(\"prompt_tokens\"),\n+ meta_info.get(\"cached_tokens\"),\n+ )\n+ changed = (\n+ finish_reason\n+ or usage_metadata_by_index.get(output_idx) != usage_metadata\n+ )\n+ if changed and (usage := _sglang_completion_usage(meta_info)):\n+ out[\"completion_usage\"] = usage\n+ usage_metadata_by_index[output_idx] = usage_metadata\n+\n if finish_reason:\n prompt_payload = (\n _shared_logprobs.extract_prompt_logprobs_from_sglang_meta(\n@@ -1150,9 +1165,6 @@ async def _process_token_stream(\n )\n if kv_cache_hit:\n engine_data[\"kv_cache_hit\"] = kv_cache_hit\n- completion_usage = _sglang_completion_usage(meta_info)\n- if completion_usage is not None:\n- out[\"completion_usage\"] = completion_usage\n if metadata_uploader is not None:\n try:\n await metadata_uploader.upload_choice(output_idx, meta_info)\ndiff --git a/components/src/dynamo/thunderagent_router/__main__.py b/components/src/dynamo/thunderagent_router/__main__.py\nindex 57361d43746a..2a9299888e94 100644\n--- a/components/src/dynamo/thunderagent_router/__main__.py\n+++ b/components/src/dynamo/thunderagent_router/__main__.py\n@@ -283,7 +283,6 @@ async def generate(self, request: dict[str, Any]):\n \n prompt_tokens_seen = 0\n completion_tokens_seen = 0\n- usage_completion_seen = False\n first_chunk = True\n selected_worker_id = None\n proof = (\n@@ -339,18 +338,20 @@ async def generate(self, request: dict[str, Any]):\n prompt_tokens_seen = int(\n usage.get(\"prompt_tokens\", prompt_tokens_seen)\n )\n- if isinstance(usage.get(\"completion_tokens\"), int):\n- completion_tokens_seen = int(usage[\"completion_tokens\"])\n- usage_completion_seen = True\n token_ids_out = (\n chunk.get(\"token_ids\", []) if isinstance(chunk, dict) else []\n )\n if isinstance(token_ids_out, list) and token_ids_out:\n- # Engine usage is authoritative if present; only the\n- # token-id fallback path increments completion_tokens_seen.\n- if not usage_completion_seen:\n- completion_tokens_seen += len(token_ids_out)\n+ completion_tokens_seen += len(token_ids_out)\n self._scheduler.record_output_tokens(program_id, len(token_ids_out))\n+ # Intermediate usage can be sparse. Only a terminal report can\n+ # replace the token count used when a stream is interrupted.\n+ if (\n+ isinstance(usage, dict)\n+ and chunk.get(\"finish_reason\")\n+ and isinstance(usage.get(\"completion_tokens\"), int)\n+ ):\n+ completion_tokens_seen = usage[\"completion_tokens\"]\n \n if proof is not None:\n _inject_thunderagent_route_proof(chunk, proof)\ndiff --git a/components/src/dynamo/vllm/handlers.py b/components/src/dynamo/vllm/handlers.py\nindex 9b578985a320..ac67a5ecf9e4 100644\n--- a/components/src/dynamo/vllm/handlers.py\n+++ b/components/src/dynamo/vllm/handlers.py\n@@ -3375,16 +3375,16 @@ def _build_prompt_from_request(\n @staticmethod\n def _build_completion_usage(\n request_output: RequestOutput,\n- completion_token_counts: dict[int, int] | None = None,\n+ completion_tokens: int | None = None,\n ) -> Dict[str, Any]:\n \"\"\"\n Build completion usage statistics.\n \n Args:\n request_output: vLLM RequestOutput object\n- completion_token_counts: Optional cumulative generated-token counts by\n- output index. DELTA-mode streams need this\n- because the final vLLM chunk is not cumulative.\n+ completion_tokens: Optional cumulative request-wide generated-token\n+ count. DELTA-mode streams maintain this total because\n+ each vLLM chunk contains only newly generated tokens.\n \n Returns:\n Dict with prompt_tokens, completion_tokens, total_tokens, prompt_tokens_details\n@@ -3395,9 +3395,7 @@ def _build_completion_usage(\n else None\n )\n \n- if completion_token_counts is not None:\n- completion_tokens = sum(completion_token_counts.values())\n- else:\n+ if completion_tokens is None:\n completion_tokens = sum(\n len(output.token_ids) for output in request_output.outputs\n )\n@@ -3518,6 +3516,8 @@ async def generate_tokens(\n )\n \n total_output_tokens_by_index: dict[int, int] = {}\n+ total_output_tokens = 0\n+ usage_metadata_by_index: dict[int, tuple[int | None, int | None]] = {}\n raw_routed_experts_by_output: dict[int, Any] = {}\n raw_sampling_mask_by_output: dict[int, Any] = {}\n # vLLM surfaces prompt_logprobs once (at end-of-prefill) and clears\n@@ -3568,6 +3568,10 @@ async def generate_tokens(\n (output, output_idx, token_ids, finish_reason, stop_reason)\n )\n \n+ usage_metadata = (\n+ len(res.prompt_token_ids) if res.prompt_token_ids else None,\n+ getattr(res, \"num_cached_tokens\", None),\n+ )\n for (\n output,\n output_idx,\n@@ -3575,6 +3579,7 @@ async def generate_tokens(\n finish_reason,\n stop_reason,\n ) in prepared_outputs:\n+ total_output_tokens += len(token_ids)\n out: Dict[str, Any] = {\n \"index\": output_idx,\n \"token_ids\": token_ids,\n@@ -3613,18 +3618,26 @@ async def generate_tokens(\n if top_logprobs is not None:\n out[\"top_logprobs\"] = top_logprobs\n \n+ # The frontend retains prompt/cache metadata and counts output\n+ # tokens itself. Send changes and final totals, not per-token usage.\n+ if (\n+ finish_reason\n+ or usage_metadata_by_index.get(output_idx) != usage_metadata\n+ ):\n+ out[\n+ \"completion_usage\"\n+ ] = BaseWorkerHandler._build_completion_usage(\n+ request_output=res,\n+ completion_tokens=total_output_tokens,\n+ )\n+ usage_metadata_by_index[output_idx] = usage_metadata\n+\n if finish_reason:\n out[\"finish_reason\"] = normalized_finish_reason\n if engine_prompt_token_ids is not None:\n out[\"engine_data\"] = {\n \"prompt_token_ids\": list(engine_prompt_token_ids)\n }\n- out[\n- \"completion_usage\"\n- ] = BaseWorkerHandler._build_completion_usage(\n- request_output=res,\n- completion_token_counts=total_output_tokens_by_index,\n- )\n # With n > 1, later samples hit the prompt blocks earlier\n # ones just cached, and vLLM keeps the first buffered\n # sample's count when it merges outputs, so no sample's\ndiff --git a/lib/llm/src/protocols/openai/delta_common.rs b/lib/llm/src/protocols/openai/delta_common.rs\nindex 0ee9312e3fb6..9fafd9e7b0de 100644\n--- a/lib/llm/src/protocols/openai/delta_common.rs\n+++ b/lib/llm/src/protocols/openai/delta_common.rs\n@@ -217,6 +217,60 @@ pub(crate) fn force_include_usage(stream_options: &mut Option None:\n+ def __init__(\n+ self, chunks: Optional[list[dict[str, Any]]] = None, *, error=None\n+ ) -> None:\n self.chunks = chunks if chunks is not None else []\n+ self.error = error\n self.sent: Optional[dict[str, Any]] = None\n \n async def generate_from_request(self, preprocessed):\n@@ -133,6 +137,8 @@ async def generate_from_request(self, preprocessed):\n async def stream():\n for chunk in self.chunks:\n yield chunk\n+ if self.error is not None:\n+ raise self.error\n \n return stream()\n \n@@ -223,3 +229,46 @@ async def test_a_placed_program_does_not_consult_the_first_chunk():\n await drive(handler)\n \n assert scheduler.back_fills == []\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\"ending\", [\"finish\", \"disconnect\", \"error\"])\n+async def test_sparse_usage_counts_tokens_until_a_terminal_report(ending):\n+ handler = make_handler()\n+ scheduler = FakeScheduler(replica_hint=(7, 0))\n+ handler._scheduler = scheduler\n+ chunks = [\n+ {\n+ \"token_ids\": [101],\n+ \"completion_usage\": {\"prompt_tokens\": 3, \"completion_tokens\": 1},\n+ },\n+ {\"token_ids\": [102, 103]},\n+ ]\n+ if ending == \"finish\":\n+ chunks.append(\n+ {\n+ \"token_ids\": [104],\n+ \"finish_reason\": \"stop\",\n+ \"completion_usage\": {\n+ \"prompt_tokens\": 3,\n+ \"completion_tokens\": 9,\n+ },\n+ }\n+ )\n+ handler._kv_router = FakeKvRouter(\n+ chunks,\n+ error=RuntimeError(\"engine stream failed\") if ending == \"error\" else None,\n+ )\n+ stream = handler.generate(\n+ {\"token_ids\": [1, 2, 3], \"agent_context\": {\"session_id\": \"p1\"}}\n+ )\n+ await anext(stream)\n+ await anext(stream)\n+ if ending == \"disconnect\":\n+ await stream.aclose()\n+ elif ending == \"error\":\n+ with pytest.raises(RuntimeError, match=\"engine stream failed\"):\n+ await anext(stream)\n+ else:\n+ assert len([chunk async for chunk in stream]) == 1\n+ assert scheduler.completed_requests == [(\"p1\", 3, 9 if ending == \"finish\" else 3)]\ndiff --git a/components/src/dynamo/vllm/tests/test_vllm_delta_streaming.py b/components/src/dynamo/vllm/tests/test_vllm_delta_streaming.py\nindex 1f863f5d4040..1cf4526ebc36 100644\n--- a/components/src/dynamo/vllm/tests/test_vllm_delta_streaming.py\n+++ b/components/src/dynamo/vllm/tests/test_vllm_delta_streaming.py\n@@ -139,6 +139,88 @@ async def test_generate_tokens_passes_delta_chunks_without_cumulative_slicing():\n }\n \n \n+@pytest.mark.asyncio\n+async def test_generate_tokens_reports_cached_usage_before_finish():\n+ responses = [\n+ _request_output(\n+ [output],\n+ prompt_token_ids=[10, 11, 12],\n+ num_cached_tokens=2,\n+ )\n+ for output in (\n+ _output([1]),\n+ _output([2, 3]),\n+ _output([], finish_reason=\"length\"),\n+ )\n+ ]\n+\n+ chunks, _ = await _collect_handler_chunks(responses)\n+\n+ assert [chunk[\"token_ids\"] for chunk in chunks] == [[1], [2, 3], []]\n+ assert \"finish_reason\" not in chunks[0]\n+ assert \"finish_reason\" not in chunks[1]\n+ assert chunks[-1][\"finish_reason\"] == \"length\"\n+ assert \"completion_usage\" not in chunks[1]\n+ for chunk, completion_tokens in [(chunks[0], 1), (chunks[-1], 3)]:\n+ assert chunk[\"completion_usage\"] == {\n+ \"prompt_tokens\": 3,\n+ \"completion_tokens\": completion_tokens,\n+ \"total_tokens\": 3 + completion_tokens,\n+ \"prompt_tokens_details\": {\"cached_tokens\": 2},\n+ }\n+\n+\n+@pytest.mark.asyncio\n+@pytest.mark.parametrize(\"cached_tokens\", [0, 2])\n+async def test_generate_tokens_reports_cache_count_when_it_becomes_available(\n+ cached_tokens,\n+):\n+ responses = [\n+ _request_output(\n+ [_output([token_id])],\n+ prompt_token_ids=[10, 11, 12],\n+ num_cached_tokens=cache_count,\n+ )\n+ for token_id, cache_count in [(1, None), (2, cached_tokens)]\n+ ]\n+\n+ chunks, _ = await _collect_handler_chunks(responses)\n+\n+ assert all(\"finish_reason\" not in chunk for chunk in chunks)\n+ assert chunks[0][\"completion_usage\"][\"prompt_tokens_details\"] is None\n+ assert chunks[1][\"completion_usage\"][\"prompt_tokens_details\"] == {\n+ \"cached_tokens\": cached_tokens\n+ }\n+\n+\n+@pytest.mark.asyncio\n+async def test_generate_tokens_reports_prompt_and_cache_metadata_changes():\n+ responses = [\n+ _request_output(\n+ [_output([index])],\n+ prompt_token_ids=list(range(prompt_tokens)),\n+ num_cached_tokens=cached_tokens,\n+ )\n+ for index, (prompt_tokens, cached_tokens) in enumerate(\n+ [(3, 0), (3, 0), (4, 0), (4, 2), (4, 2)]\n+ )\n+ ]\n+\n+ chunks, _ = await _collect_handler_chunks(responses)\n+\n+ assert [\"completion_usage\" in chunk for chunk in chunks] == [\n+ True,\n+ False,\n+ True,\n+ True,\n+ False,\n+ ]\n+ assert chunks[2][\"completion_usage\"][\"prompt_tokens\"] == 4\n+ assert chunks[3][\"completion_usage\"][\"prompt_tokens_details\"] == {\n+ \"cached_tokens\": 2\n+ }\n+\n+\n @pytest.mark.asyncio\n async def test_generate_tokens_keeps_final_empty_delta_chunk_for_usage():\n responses = [\n@@ -199,8 +281,19 @@ async def test_generate_tokens_tracks_interleaved_output_indexes_independently()\n (1, [12]),\n (1, []),\n ]\n- assert chunks[2][\"completion_usage\"][\"completion_tokens\"] == 5\n+ assert chunks[2][\"completion_usage\"][\"completion_tokens\"] == 4\n assert chunks[-1][\"completion_usage\"][\"completion_tokens\"] == 5\n+ assert \"completion_usage\" not in chunks[3]\n+ assert [\n+ chunk[\"completion_usage\"][\"completion_tokens\"]\n+ for chunk in chunks\n+ if \"completion_usage\" in chunk\n+ ] == [\n+ 1,\n+ 3,\n+ 4,\n+ 5,\n+ ]\n \n \n @pytest.mark.asyncio\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(operator): complete LWS worker generation cleanup\nLabels: documentation, external-contribution, size/XL, deployment::k8s, fix\nFiles changed (6): deploy/operator/internal/controller/dgd_component_program.go, deploy/operator/internal/controller/dgd_worker_rollout_reconciler.go, deploy/operator/internal/controller/dgd_worker_rollout_reconciler_test.go, deploy/operator/internal/controller/dgd_workload_program_test.go, deploy/operator/internal/controller/dynamographdeployment_controller.go, deploy/operator/internal/controller/lws_worker_availability_test.go\n\n## Description (results removed)\n\n## Summary\n\nUpdating a pod-template label on an LWS-backed DGD creates a replacement worker generation, but the rollout treats LWS's unreported availability as zero and cannot scale down the previous generation. The multinode path also leaves drained old DCDs behind and advances the current worker hash before the update is complete.\n\n- Require every replacement worker component to reach the full desired ready count from the DGD before deleting old DCDs. Retain the existing checks that old DCDs have observed scale-to-zero and all old pods have terminated. `Recreate` can still drain old replicas before starting replacements.\n- Keep replacement replicas running while a drained old DCD waits for deletion finalizers. Deletion can advance its generation after the final status update; retain the zero-replica and pod-termination checks without waiting for an impossible status acknowledgement.\n- Advance the current worker hash only after old DCD deletion is observed. Preserve first-deployment hash initialization and level-based cleanup for deployments whose hash has already advanced.\n- Match old pods by DCD selector, or by worker hash only for DGD-managed worker pods, since native LWS leader/worker templates omit the selector. Exclude checkpoint capture pods that share a worker hash, keeping the drain check consistent with the Pod watch. Admit worker-hash membership and terminality events so cleanup resumes when serving pods terminate or disappear.\n\n## Validation\n[results removed]\n## Related Issues\n\nCloses #15958\n\n## Diff\n\n```diff\ndiff --git a/deploy/operator/internal/controller/dgd_component_program.go b/deploy/operator/internal/controller/dgd_component_program.go\nindex 5482f0d5868c..31882566eca1 100644\n--- a/deploy/operator/internal/controller/dgd_component_program.go\n+++ b/deploy/operator/internal/controller/dgd_component_program.go\n@@ -177,29 +177,68 @@ func (p *componentProgram) reconcileWorkerRollout(\n \treturn p.reconcileMultinodeWorkerRollout(ctx, dgd)\n }\n \n-// reconcileMultinodeWorkerRollout gates hash projection on informer observation of the target DCD.\n+// reconcileMultinodeWorkerRollout retires drained old DCDs once replacements are ready,\n+// then advances the worker hash after their deletion is observed. Requires non-nil dgd.\n func (p *componentProgram) reconcileMultinodeWorkerRollout(\n \tctx context.Context,\n \tdgd *nvidiacomv1beta1.DynamoGraphDeployment,\n ) error {\n+\t// Plan the hash transition without marking an unfinished generation as current.\n \ttransition, err := p.rollout.planUnsupportedWorkerHashTransition(dgd)\n \tif err != nil {\n \t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n \t}\n-\tif !transition.needsCommit() {\n-\t\treturn nil\n-\t}\n \n-\tobserved, err := p.rollout.dcdObservesWorkerHash(ctx, dgd, transition.next.v2)\n+\t// Cleanup remains level-based after the hash annotation has already advanced.\n+\tdesired, err := desiredWorkerHashes(dgd)\n \tif err != nil {\n \t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n \t}\n-\tif !observed {\n+\tnewWorkerHash := activeWorkerHashForDCDGeneration(dgd, desired)\n+\toldDCDs, err := p.rollout.listOldWorkerDCDs(ctx, dgd, newWorkerHash)\n+\tif err != nil {\n+\t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n+\t}\n+\n+\t// Require each replacement's full DGD desired count, not its temporary rollout target.\n+\tif len(oldDCDs) > 0 || transition.hashChanged {\n+\t\tnewInfo, err := p.rollout.getWorkerInfoForWorkerHash(ctx, dgd, newWorkerHash)\n+\t\tif err != nil {\n+\t\t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n+\t\t}\n+\t\tupdatedComponents, totalWorkerComponents := completedWorkerComponents(dgd, nil, newInfo)\n+\t\tif len(updatedComponents) != totalWorkerComponents {\n+\t\t\treturn nil\n+\t\t}\n+\t}\n+\n+\t// Wait for scale-to-zero observation and all old pods to terminate before deletion.\n+\tif len(oldDCDs) > 0 {\n+\t\tdrained, err := p.rollout.oldWorkerDCDsDrained(ctx, dgd, oldDCDs)\n+\t\tif err != nil {\n+\t\t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n+\t\t}\n+\t\tif !drained {\n+\t\t\treturn nil\n+\t\t}\n+\t\tif err := p.rollout.deleteWorkerDCDs(ctx, oldDCDs); err != nil {\n+\t\t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n+\t\t}\n \t\treturn nil\n \t}\n \n-\tif err := p.rollout.commitUnsupportedWorkerHashTransition(ctx, dgd, transition, false); err != nil {\n-\t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n+\t// Commit only after old deletions are observed; first deployment only needs DCD visibility.\n+\tif transition.needsCommit() {\n+\t\tobserved, err := p.rollout.dcdObservesWorkerHash(ctx, dgd, transition.next.v2)\n+\t\tif err != nil {\n+\t\t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n+\t\t}\n+\t\tif !observed {\n+\t\t\treturn nil\n+\t\t}\n+\t\tif err := p.rollout.commitUnsupportedWorkerHashTransition(ctx, dgd, transition, false); err != nil {\n+\t\t\treturn failWorkloadProgram(reasonRollingUpdateFailed, err)\n+\t\t}\n \t}\n \treturn nil\n }\ndiff --git a/deploy/operator/internal/controller/dgd_worker_rollout_reconciler.go b/deploy/operator/internal/controller/dgd_worker_rollout_reconciler.go\nindex e58fd5ea56ba..c3a9b769601c 100644\n--- a/deploy/operator/internal/controller/dgd_worker_rollout_reconciler.go\n+++ b/deploy/operator/internal/controller/dgd_worker_rollout_reconciler.go\n@@ -789,11 +789,11 @@ func (r *dgdWorkerRolloutReconciler) oldWorkerDCDsDrained(\n // dcdComponentState holds replica signals extracted from a DCD's Spec and Status.\n type dcdComponentState struct {\n \tSpec int32 `json:\"spec\"` // DCD Spec.Replicas (declared intent)\n-\tAvailable int32 `json:\"available\"` // Status.Component.AvailableReplicas (serving traffic)\n+\tAvailable int32 `json:\"available\"` // AvailableReplicas, or ReadyReplicas when availability is not reported\n \tActual int32 `json:\"actual\"` // Status.Component.Replicas (non-terminated pods, excludes Terminating)\n }\n \n-// dcdComponentStateFromDCD extracts replica signals from a single DCD.\n+// dcdComponentStateFromDCD extracts replica signals from a non-nil DCD.\n func dcdComponentStateFromDCD(dcd *nvidiacomv1beta1.DynamoComponentDeployment) dcdComponentState {\n \ts := dcdComponentState{Spec: 1}\n \tif dcd.Spec.Replicas != nil {\n@@ -803,6 +803,9 @@ func dcdComponentStateFromDCD(dcd *nvidiacomv1beta1.DynamoComponentDeployment) d\n \t\ts.Actual = dcd.Status.Component.Replicas\n \t\tif dcd.Status.Component.AvailableReplicas != nil {\n \t\t\ts.Available = *dcd.Status.Component.AvailableReplicas\n+\t\t} else if dcd.Status.Component.ReadyReplicas != nil {\n+\t\t\t// LWS only reports readiness; an explicit availability count, including zero, wins.\n+\t\t\ts.Available = *dcd.Status.Component.ReadyReplicas\n \t\t}\n \t}\n \treturn s\n@@ -954,9 +957,13 @@ func oldWorkerDCDsAtZero(dcds []*nvidiacomv1beta1.DynamoComponentDeployment) boo\n \t\tif dcd == nil || dcd.Spec.Replicas == nil || *dcd.Spec.Replicas != 0 {\n \t\t\treturn false\n \t\t}\n-\t\tif dcd.Status.ObservedGeneration < dcd.Generation {\n+\n+\t\t// Deletion can advance generation after the drain was observed, but the\n+\t\t// DCD controller only finalizes deleting objects and cannot acknowledge it.\n+\t\tif dcd.DeletionTimestamp.IsZero() && dcd.Status.ObservedGeneration < dcd.Generation {\n \t\t\treturn false\n \t\t}\n+\n \t\tif dcd.Status.Component == nil || dcd.Status.Component.Replicas != 0 {\n \t\t\treturn false\n \t\t}\n@@ -966,19 +973,31 @@ func oldWorkerDCDsAtZero(dcds []*nvidiacomv1beta1.DynamoComponentDeployment) boo\n \n // oldWorkerPodsTerminated reports whether every pod belonging to an old DCD\n // is in a terminal phase. A deletion timestamp does not make a pod terminal:\n-// Pending, Running, and Unknown pods continue to block Recreate until they\n+// Pending, Running, and Unknown pods continue to block cleanup until they\n // reach Failed or Succeeded, or disappear from the informer cache.\n+// Pods must already be scoped to the same DGD component as the old DCDs.\n func oldWorkerPodsTerminated(dcds []*nvidiacomv1beta1.DynamoComponentDeployment, pods []corev1.Pod) bool {\n+\t// Native LWS pods omit the DCD selector, so retain both generation identities.\n \toldDCDNames := make(map[string]struct{}, len(dcds))\n+\toldWorkerHashes := make(map[string]struct{}, len(dcds))\n \tfor _, dcd := range dcds {\n-\t\tif dcd != nil && dcd.Name != \"\" {\n+\t\tif dcd == nil {\n+\t\t\tcontinue\n+\t\t}\n+\t\tif dcd.Name != \"\" {\n \t\t\toldDCDNames[dcd.Name] = struct{}{}\n \t\t}\n+\t\tif workerHash := dcd.Labels[consts.KubeLabelDynamoWorkerHash]; workerHash != \"\" {\n+\t\t\toldWorkerHashes[workerHash] = struct{}{}\n+\t\t}\n \t}\n \n+\t// Wait for serving pods; checkpoint captures can share the hash without being workers.\n \tfor i := range pods {\n \t\tpod := &pods[i]\n-\t\tif _, old := oldDCDNames[pod.Labels[consts.KubeLabelDynamoSelector]]; !old {\n+\t\t_, oldSelector := oldDCDNames[pod.Labels[consts.KubeLabelDynamoSelector]]\n+\t\t_, oldHash := oldWorkerHashes[pod.Labels[consts.KubeLabelDynamoWorkerHash]]\n+\t\tif !oldSelector && !(oldHash && isDGDManagedWorkerPod(pod)) {\n \t\t\tcontinue\n \t\t}\n \t\tif !isTerminalPhase(pod.Status.Phase) {\ndiff --git a/deploy/operator/internal/controller/dynamographdeployment_controller.go b/deploy/operator/internal/controller/dynamographdeployment_controller.go\nindex 01767dd2dd17..2423fc9fddee 100644\n--- a/deploy/operator/internal/controller/dynamographdeployment_controller.go\n+++ b/deploy/operator/internal/controller/dynamographdeployment_controller.go\n@@ -416,10 +416,12 @@ func isDGDManagedWorkerPod(obj client.Object) bool {\n \tif !ok || pod == nil {\n \t\treturn false\n \t}\n+\n+\t// Native LWS pods carry a worker hash instead of the DCD selector.\n \tlabels := pod.GetLabels()\n \treturn labels[consts.KubeLabelDynamoGraphDeploymentName] != \"\" &&\n \t\tlabels[consts.KubeLabelDynamoComponent] != \"\" &&\n-\t\tlabels[consts.KubeLabelDynamoSelector] != \"\" &&\n+\t\t(labels[consts.KubeLabelDynamoSelector] != \"\" || labels[consts.KubeLabelDynamoWorkerHash] != \"\") &&\n \t\tdynamo.IsWorkerComponent(labels[consts.KubeLabelDynamoComponentType])\n }\n \n@@ -444,7 +446,7 @@ func dgdComponentPodIndexValue(dgdName, componentName string) string {\n }\n \n // dgdWorkerPodEventPredicate admits only events that can change whether a\n-// Recreate rollout is blocked by an old pod. Creation and deletion change pod\n+// worker rollout is blocked by an old pod. Creation and deletion change pod\n // membership; updates matter only when membership or terminality changes. A\n // deletion timestamp alone leaves the pod non-terminal and does not enqueue.\n func dgdWorkerPodEventPredicate() predicate.Predicate {\n@@ -468,7 +470,8 @@ func dgdWorkerPodEventPredicate() predicate.Predicate {\n \t\t\tnewPod := e.ObjectNew.(*corev1.Pod)\n \t\t\tif oldPod.Labels[consts.KubeLabelDynamoGraphDeploymentName] != newPod.Labels[consts.KubeLabelDynamoGraphDeploymentName] ||\n \t\t\t\toldPod.Labels[consts.KubeLabelDynamoComponent] != newPod.Labels[consts.KubeLabelDynamoComponent] ||\n-\t\t\t\toldPod.Labels[consts.KubeLabelDynamoSelector] != newPod.Labels[consts.KubeLabelDynamoSelector] {\n+\t\t\t\toldPod.Labels[consts.KubeLabelDynamoSelector] != newPod.Labels[consts.KubeLabelDynamoSelector] ||\n+\t\t\t\toldPod.Labels[consts.KubeLabelDynamoWorkerHash] != newPod.Labels[consts.KubeLabelDynamoWorkerHash] {\n \t\t\t\treturn true\n \t\t\t}\n \t\t\treturn isTerminalPhase(oldPod.Status.Phase) != isTerminalPhase(newPod.Status.Phase)\ndiff --git a/deploy/operator/internal/controller/dgd_worker_rollout_reconciler_test.go b/deploy/operator/internal/controller/dgd_worker_rollout_reconciler_test.go\nindex b8a998b2266d..8b90298a841e 100644\n--- a/deploy/operator/internal/controller/dgd_worker_rollout_reconciler_test.go\n+++ b/deploy/operator/internal/controller/dgd_worker_rollout_reconciler_test.go\n@@ -4047,9 +4047,10 @@ func TestOldWorkerDCDsAtZero(t *testing.T) {\n \t}\n \n \ttests := []struct {\n-\t\tname string\n-\t\tdcds []*nvidiacomv1beta1.DynamoComponentDeployment\n-\t\twant bool\n+\t\tname string\n+\t\tdcds []*nvidiacomv1beta1.DynamoComponentDeployment\n+\t\tdeleting bool\n+\t\twant bool\n \t}{\n \t\t{\n \t\t\tname: \"no old generations\",\n@@ -4082,6 +4083,22 @@ func TestOldWorkerDCDsAtZero(t *testing.T) {\n \t\t\t},\n \t\t\twant: false,\n \t\t},\n+\t\t{\n+\t\t\tname: \"deletion advances generation after scale-down was observed\",\n+\t\t\tdcds: []*nvidiacomv1beta1.DynamoComponentDeployment{\n+\t\t\t\tnewDCD(0, 3, 2, ptr.To(int32(0))),\n+\t\t\t},\n+\t\t\tdeleting: true,\n+\t\t\twant: true,\n+\t\t},\n+\t\t{\n+\t\t\tname: \"deleting generation still reports non-terminated replicas\",\n+\t\t\tdcds: []*nvidiacomv1beta1.DynamoComponentDeployment{\n+\t\t\t\tnewDCD(0, 3, 2, ptr.To(int32(1))),\n+\t\t\t},\n+\t\t\tdeleting: true,\n+\t\t\twant: false,\n+\t\t},\n \t\t{\n \t\t\tname: \"replica status has not been reported\",\n \t\t\tdcds: []*nvidiacomv1beta1.DynamoComponentDeployment{\n@@ -4116,14 +4133,21 @@ func TestOldWorkerDCDsAtZero(t *testing.T) {\n \n \tfor _, tt := range tests {\n \t\tt.Run(tt.name, func(t *testing.T) {\n+\t\t\tt.Log(\"Check drain status while live or waiting for deletion finalizers\")\n+\t\t\tif tt.deleting {\n+\t\t\t\tfor _, dcd := range tt.dcds {\n+\t\t\t\t\tdcd.DeletionTimestamp = ptr.To(metav1.Now())\n+\t\t\t\t}\n+\t\t\t}\n \t\t\tassert.Equal(t, tt.want, oldWorkerDCDsAtZero(tt.dcds))\n \t\t})\n \t}\n }\n \n func TestOldWorkerPodsTerminated(t *testing.T) {\n+\tt.Log(\"Define old generations with and without worker hashes\")\n \toldDCDs := []*nvidiacomv1beta1.DynamoComponentDeployment{\n-\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"old-worker-a\"}},\n+\t\t{ObjectMeta: metav1.ObjectMeta{Name: \"old-worker-a\", Labels: map[string]string{consts.KubeLabelDynamoWorkerHash: \"old-hash\"}}},\n \t\t{ObjectMeta: metav1.ObjectMeta{Name: \"old-worker-b\"}},\n \t}\n \tnewPod := func(name, selector string, phase corev1.PodPhase) corev1.Pod {\n@@ -4184,7 +4208,7 @@ func TestOldWorkerPodsTerminated(t *testing.T) {\n \t\t\twant: true,\n \t\t},\n \t\t{\n-\t\t\tname: \"pod without a workload selector does not block\",\n+\t\t\tname: \"pod without a workload identity does not block\",\n \t\t\tpods: []corev1.Pod{newPod(\"checkpoint\", \"\", corev1.PodRunning)},\n \t\t\twant: true,\n \t\t},\n@@ -4196,10 +4220,50 @@ func TestOldWorkerPodsTerminated(t *testing.T) {\n \t\t\t},\n \t\t\twant: false,\n \t\t},\n+\t\t{\n+\t\t\tname: \"running native LWS pod blocks\",\n+\t\t\tpods: []corev1.Pod{{\n+\t\t\t\tObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\n+\t\t\t\t\tconsts.KubeLabelDynamoGraphDeploymentName: \"test-dgd\",\n+\t\t\t\t\tconsts.KubeLabelDynamoComponent: \"worker\",\n+\t\t\t\t\tconsts.KubeLabelDynamoComponentType: consts.ComponentTypeWorker,\n+\t\t\t\t\tconsts.KubeLabelDynamoWorkerHash: \"old-hash\",\n+\t\t\t\t}},\n+\t\t\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n+\t\t\t}},\n+\t\t\twant: false,\n+\t\t},\n+\t\t{\n+\t\t\tname: \"terminal native LWS pod does not block\",\n+\t\t\tpods: []corev1.Pod{{\n+\t\t\t\tObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\n+\t\t\t\t\tconsts.KubeLabelDynamoGraphDeploymentName: \"test-dgd\",\n+\t\t\t\t\tconsts.KubeLabelDynamoComponent: \"worker\",\n+\t\t\t\t\tconsts.KubeLabelDynamoComponentType: consts.ComponentTypeWorker,\n+\t\t\t\t\tconsts.KubeLabelDynamoWorkerHash: \"old-hash\",\n+\t\t\t\t}},\n+\t\t\t\tStatus: corev1.PodStatus{Phase: corev1.PodSucceeded},\n+\t\t\t}},\n+\t\t\twant: true,\n+\t\t},\n+\t\t{\n+\t\t\tname: \"native LWS pod from a new generation does not block\",\n+\t\t\tpods: []corev1.Pod{{\n+\t\t\t\tObjectMeta: metav1.ObjectMeta{Labels: map[string]string{\n+\t\t\t\t\tconsts.KubeLabelDynamoGraphDeploymentName: \"test-dgd\",\n+\t\t\t\t\tconsts.KubeLabelDynamoComponent: \"worker\",\n+\t\t\t\t\tconsts.KubeLabelDynamoComponentType: consts.ComponentTypeWorker,\n+\t\t\t\t\tconsts.KubeLabelDynamoWorkerHash: \"new-hash\",\n+\t\t\t\t}},\n+\t\t\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n+\t\t\t}},\n+\t\t\twant: true,\n+\t\t},\n \t}\n \n \tfor _, tt := range tests {\n \t\tt.Run(tt.name, func(t *testing.T) {\n+\t\t\tt.Log(\"Check whether any old-generation pod still blocks cleanup\")\n \t\t\tassert.Equal(t, tt.want, oldWorkerPodsTerminated(oldDCDs, tt.pods))\n \t\t})\n \t}\n@@ -4287,66 +4351,91 @@ func TestListDGDComponentPodsUsesCompositeIndex(t *testing.T) {\n }\n \n func TestDGDWorkerPodEventPredicate(t *testing.T) {\n-\tnewPod := func(phase corev1.PodPhase) *corev1.Pod {\n-\t\treturn &corev1.Pod{\n-\t\t\tObjectMeta: metav1.ObjectMeta{\n+\tfor _, tt := range []struct {\n+\t\tname string\n+\t\tlabel string\n+\t}{\n+\t\t{name: \"legacy selector\", label: consts.KubeLabelDynamoSelector},\n+\t\t{name: \"native LWS worker hash\", label: consts.KubeLabelDynamoWorkerHash},\n+\t} {\n+\t\tt.Run(tt.name, func(t *testing.T) {\n+\t\t\tt.Log(\"Create worker pods with the selected generation identity\")\n+\t\t\tnewPod := func(phase corev1.PodPhase) *corev1.Pod {\n+\t\t\t\treturn &corev1.Pod{\n+\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n+\t\t\t\t\t\tName: \"worker\",\n+\t\t\t\t\t\tNamespace: \"default\",\n+\t\t\t\t\t\tLabels: map[string]string{\n+\t\t\t\t\t\t\tconsts.KubeLabelDynamoGraphDeploymentName: \"test-dgd\",\n+\t\t\t\t\t\t\tconsts.KubeLabelDynamoComponent: \"worker\",\n+\t\t\t\t\t\t\tconsts.KubeLabelDynamoComponentType: consts.ComponentTypeWorker,\n+\t\t\t\t\t\t\ttt.label: \"old-worker\",\n+\t\t\t\t\t\t},\n+\t\t\t\t\t},\n+\t\t\t\t\tStatus: corev1.PodStatus{Phase: phase},\n+\t\t\t\t}\n+\t\t\t}\n+\n+\t\t\tpred := dgdWorkerPodEventPredicate()\n+\t\t\trunning := newPod(corev1.PodRunning)\n+\t\t\tfailed := newPod(corev1.PodFailed)\n+\t\t\tsucceeded := newPod(corev1.PodSucceeded)\n+\t\t\tdeleting := running.DeepCopy()\n+\t\t\tdeleting.DeletionTimestamp = ptr.To(metav1.Now())\n+\t\t\tunrelated := running.DeepCopy()\n+\t\t\tdelete(unrelated.Labels, tt.label)\n+\t\t\tfrontend := running.DeepCopy()\n+\t\t\tfrontend.Labels[consts.KubeLabelDynamoComponentType] = consts.ComponentTypeFrontend\n+\t\t\tmoved := running.DeepCopy()\n+\t\t\tmoved.Labels[tt.label] = \"another-old-worker\"\n+\n+\t\t\tt.Log(\"Admit membership and terminality changes while ignoring unrelated events\")\n+\t\t\tassert.True(t, pred.Create(event.CreateEvent{Object: running}), \"pod creation changes drain membership\")\n+\t\t\tassert.False(t, pred.Create(event.CreateEvent{Object: frontend}), \"non-worker pods must be ignored\")\n+\t\t\tassert.True(t, pred.Delete(event.DeleteEvent{Object: running}), \"pod deletion can unblock a drain\")\n+\t\t\tassert.False(t, pred.Delete(event.DeleteEvent{Object: unrelated}), \"unmanaged pods must be ignored\")\n+\t\t\tassert.True(t, pred.Update(event.UpdateEvent{ObjectOld: running, ObjectNew: failed}), \"transition to Failed can unblock a drain\")\n+\t\t\tassert.True(t, pred.Update(event.UpdateEvent{ObjectOld: running, ObjectNew: succeeded}), \"transition to Succeeded can unblock a drain\")\n+\t\t\tassert.False(t, pred.Update(event.UpdateEvent{ObjectOld: running, ObjectNew: deleting}), \"deletion timestamp alone does not make a pod terminal\")\n+\t\t\tassert.False(t, pred.Update(event.UpdateEvent{ObjectOld: failed, ObjectNew: succeeded}), \"terminal-to-terminal transitions are irrelevant\")\n+\t\t\tassert.True(t, pred.Update(event.UpdateEvent{ObjectOld: running, ObjectNew: moved}), \"generation identity changes move the pod between drain memberships\")\n+\t\t\tassert.True(t, pred.Update(event.UpdateEvent{ObjectOld: unrelated, ObjectNew: running}), \"becoming a managed worker pod changes drain membership\")\n+\t\t\tassert.False(t, pred.Generic(event.GenericEvent{Object: running}))\n+\t\t})\n+\t}\n+}\n+\n+func TestMapDGDWorkerPodToRequests(t *testing.T) {\n+\tfor _, tt := range []struct {\n+\t\tname string\n+\t\tlabel string\n+\t}{\n+\t\t{name: \"legacy selector\", label: consts.KubeLabelDynamoSelector},\n+\t\t{name: \"native LWS worker hash\", label: consts.KubeLabelDynamoWorkerHash},\n+\t} {\n+\t\tt.Run(tt.name, func(t *testing.T) {\n+\t\t\tt.Log(\"Create a managed worker pod with the selected generation identity\")\n+\t\t\tpod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{\n \t\t\t\tName: \"worker\",\n \t\t\t\tNamespace: \"default\",\n \t\t\t\tLabels: map[string]string{\n \t\t\t\t\tconsts.KubeLabelDynamoGraphDeploymentName: \"test-dgd\",\n \t\t\t\t\tconsts.KubeLabelDynamoComponent: \"worker\",\n \t\t\t\t\tconsts.KubeLabelDynamoComponentType: consts.ComponentTypeWorker,\n-\t\t\t\t\tconsts.KubeLabelDynamoSelector: \"old-worker\",\n+\t\t\t\t\ttt.label: \"old-worker\",\n \t\t\t\t},\n-\t\t\t},\n-\t\t\tStatus: corev1.PodStatus{Phase: phase},\n-\t\t}\n-\t}\n+\t\t\t}}\n \n-\tpred := dgdWorkerPodEventPredicate()\n-\trunning := newPod(corev1.PodRunning)\n-\tfailed := newPod(corev1.PodFailed)\n-\tsucceeded := newPod(corev1.PodSucceeded)\n-\tdeleting := running.DeepCopy()\n-\tdeleting.DeletionTimestamp = ptr.To(metav1.Now())\n-\tunrelated := running.DeepCopy()\n-\tdelete(unrelated.Labels, consts.KubeLabelDynamoSelector)\n-\tfrontend := running.DeepCopy()\n-\tfrontend.Labels[consts.KubeLabelDynamoComponentType] = consts.ComponentTypeFrontend\n-\tmoved := running.DeepCopy()\n-\tmoved.Labels[consts.KubeLabelDynamoSelector] = \"another-old-worker\"\n-\n-\tassert.True(t, pred.Create(event.CreateEvent{Object: running}), \"pod creation changes drain membership\")\n-\tassert.False(t, pred.Create(event.CreateEvent{Object: frontend}), \"non-worker pods must be ignored\")\n-\tassert.True(t, pred.Delete(event.DeleteEvent{Object: running}), \"pod deletion can unblock a drain\")\n-\tassert.False(t, pred.Delete(event.DeleteEvent{Object: unrelated}), \"unmanaged pods must be ignored\")\n-\tassert.True(t, pred.Update(event.UpdateEvent{ObjectOld: running, ObjectNew: failed}), \"transition to Failed can unblock a drain\")\n-\tassert.True(t, pred.Update(event.UpdateEvent{ObjectOld: running, ObjectNew: succeeded}), \"transition to Succeeded can unblock a drain\")\n-\tassert.False(t, pred.Update(event.UpdateEvent{ObjectOld: running, ObjectNew: deleting}), \"deletion timestamp alone does not make a pod terminal\")\n-\tassert.False(t, pred.Update(event.UpdateEvent{ObjectOld: failed, ObjectNew: succeeded}), \"terminal-to-terminal transitions are irrelevant\")\n-\tassert.True(t, pred.Update(event.UpdateEvent{ObjectOld: running, ObjectNew: moved}), \"selector changes move the pod between drain memberships\")\n-\tassert.True(t, pred.Update(event.UpdateEvent{ObjectOld: unrelated, ObjectNew: running}), \"becoming a managed worker pod changes drain membership\")\n-\tassert.False(t, pred.Generic(event.GenericEvent{Object: running}))\n-}\n+\t\t\tt.Log(\"Map the pod event to its graph deployment\")\n+\t\t\trequests := mapDGDWorkerPodToRequests(context.Background(), pod)\n+\t\t\trequire.Len(t, requests, 1)\n+\t\t\tassert.Equal(t, types.NamespacedName{Namespace: \"default\", Name: \"test-dgd\"}, requests[0].NamespacedName)\n \n-func TestMapDGDWorkerPodToRequests(t *testing.T) {\n-\tpod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{\n-\t\tName: \"worker\",\n-\t\tNamespace: \"default\",\n-\t\tLabels: map[string]string{\n-\t\t\tconsts.KubeLabelDynamoGraphDeploymentName: \"test-dgd\",\n-\t\t\tconsts.KubeLabelDynamoComponent: \"worker\",\n-\t\t\tconsts.KubeLabelDynamoComponentType: consts.ComponentTypeWorker,\n-\t\t\tconsts.KubeLabelDynamoSelector: \"old-worker\",\n-\t\t},\n-\t}}\n-\n-\trequests := mapDGDWorkerPodToRequests(context.Background(), pod)\n-\trequire.Len(t, requests, 1)\n-\tassert.Equal(t, types.NamespacedName{Namespace: \"default\", Name: \"test-dgd\"}, requests[0].NamespacedName)\n-\n-\tdelete(pod.Labels, consts.KubeLabelDynamoGraphDeploymentName)\n-\tassert.Empty(t, mapDGDWorkerPodToRequests(context.Background(), pod))\n+\t\t\tt.Log(\"Ignore pods without a parent graph deployment\")\n+\t\t\tdelete(pod.Labels, consts.KubeLabelDynamoGraphDeploymentName)\n+\t\t\tassert.Empty(t, mapDGDWorkerPodToRequests(context.Background(), pod))\n+\t\t})\n+\t}\n }\n \n // --- reconcileRollingUpdate state machine tests ---\n@@ -4954,6 +5043,33 @@ func TestBuildRollingUpdateContext(t *testing.T) {\n \t\t\texpectedOld: map[string]int32{\"worker\": 0},\n \t\t\texpectedNew: map[string]int32{\"worker\": 3},\n \t\t},\n+\t\t{\n+\t\t\tname: \"recreate preserves replacement replicas while old deletion advances generation\",\n+\t\t\tservices: map[string]*nvidiacomv1alpha1.DynamoComponentDeploymentSharedSpec{\n+\t\t\t\t\"worker\": {\n+\t\t\t\t\tComponentType: consts.ComponentTypeWorker,\n+\t\t\t\t\tReplicas: ptr.To(int32(3)),\n+\t\t\t\t\tAnnotations: map[string]string{\n+\t\t\t\t\t\tKubeAnnotationDeploymentStrategy: string(common.DeploymentStrategyRecreate),\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t},\n+\t\t\toldDCDs: func(dgd *nvidiacomv1beta1.DynamoGraphDeployment, _ string) []runtime.Object {\n+\t\t\t\toldDCD := makeOldDCD(dgd, \"test-dgd\", \"worker\", consts.ComponentTypeWorker, \"\", 0, 0, 0)\n+\t\t\t\toldDCD.Generation = 3\n+\t\t\t\toldDCD.Status.ObservedGeneration = 2\n+\t\t\t\toldDCD.DeletionTimestamp = ptr.To(metav1.Now())\n+\t\t\t\toldDCD.Finalizers = []string{\"test.example/hold-deletion\"}\n+\t\t\t\treturn []runtime.Object{oldDCD}\n+\t\t\t},\n+\t\t\tnewDCDs: func(dgd *nvidiacomv1beta1.DynamoGraphDeployment, newHash string) []runtime.Object {\n+\t\t\t\treturn []runtime.Object{\n+\t\t\t\t\tmakeNewDCD(dgd, \"test-dgd\", \"worker\", consts.ComponentTypeWorker, newHash, 3, 3, 3),\n+\t\t\t\t}\n+\t\t\t},\n+\t\t\texpectedOld: map[string]int32{\"worker\": 0},\n+\t\t\texpectedNew: map[string]int32{\"worker\": 3},\n+\t\t},\n \t\t{\n \t\t\tname: \"recreate waits for terminating old pod after DCD reaches zero\",\n \t\t\tservices: map[string]*nvidiacomv1alpha1.DynamoComponentDeploymentSharedSpec{\ndiff --git a/deploy/operator/internal/controller/dgd_workload_program_test.go b/deploy/operator/internal/controller/dgd_workload_program_test.go\nindex a4208e01fe53..67046cae865c 100644\n--- a/deploy/operator/internal/controller/dgd_workload_program_test.go\n+++ b/deploy/operator/internal/controller/dgd_workload_program_test.go\n@@ -719,7 +719,7 @@ func TestComponentProgram_ReconcileWorkerRollout(t *testing.T) {\n \t\tassert.Equal(t, \"old-worker-hash\", dgd.Annotations[commonconsts.AnnotationCurrentWorkerHashV2])\n \t})\n \n-\tt.Run(\"multinode component workload commits hash once target DCD is observed in cache\", func(t *testing.T) {\n+\tt.Run(\"multinode component workload waits for readiness before committing an updated hash\", func(t *testing.T) {\n \t\tdgd := createTestDGD(\"test-dgd\", map[string]*nvidiacomv1alpha1.DynamoComponentDeploymentSharedSpec{\n \t\t\t\"worker\": {\n \t\t\t\tComponentType: commonconsts.ComponentTypeWorker,\n@@ -755,7 +755,13 @@ func TestComponentProgram_ReconcileWorkerRollout(t *testing.T) {\n \t\tprogram := reconciler.newComponentProgram()\n \t\tstatus := dgd.DeepCopy().Status\n \n-\t\tt.Log(\"Reconcile: hash must advance to the observed target generation\")\n+\t\tt.Log(\"An observed replacement without readiness must not advance the current hash\")\n+\t\trequire.NoError(t, program.reconcileWorkerRollout(context.Background(), dgd, &status))\n+\t\tassert.Equal(t, \"old-worker-hash\", dgd.Annotations[commonconsts.AnnotationCurrentWorkerHashV2])\n+\n+\t\tt.Log(\"Reach the DGD's default desired count of one before advancing the hash\")\n+\t\ttargetDCD.Status.Component = &nvidiacomv1beta1.ComponentReplicaStatus{ReadyReplicas: ptr.To(int32(1))}\n+\t\trequire.NoError(t, reconciler.Update(context.Background(), targetDCD))\n \t\trequire.NoError(t, program.reconcileWorkerRollout(context.Background(), dgd, &status))\n \n \t\tassert.Nil(t, status.RollingUpdate)\n@@ -1119,6 +1125,12 @@ func TestComponentWorkloadsReconciler_FirstGenMultinodeStampsWorkerHash(t *testi\n \trollout := newDGDWorkerRolloutReconciler(r.Client, r.Recorder)\n \tworkloads := newComponentWorkloadsReconciler(r.Client, r.Recorder, rollout)\n \n+\tt.Log(\"Do not initialize the current hash before any worker DCD is observed\")\n+\tprogram := &componentProgram{rollout: rollout}\n+\tstatus := dgd.DeepCopy().Status\n+\trequire.NoError(t, program.reconcileWorkerRollout(context.Background(), dgd, &status))\n+\tassert.Empty(t, dgd.Annotations[commonconsts.AnnotationCurrentWorkerHashV2])\n+\n \tt.Log(\"Reconcile: every generated worker DCD must carry the computed hash in its label and name\")\n \t_, err := workloads.Reconcile(context.Background(), dgd, nil, nil)\n \trequire.NoError(t, err)\n@@ -1141,6 +1153,11 @@ func TestComponentWorkloadsReconciler_FirstGenMultinodeStampsWorkerHash(t *testi\n \t\tassert.True(t, strings.HasSuffix(dcd.Name, expectedHash),\n \t\t\t\"DCD %s must have the worker hash as name suffix\", dcd.Name)\n \t}\n+\n+\tt.Log(\"Initialize the first generation once both DCDs are visible, without requiring readiness\")\n+\trequire.NoError(t, program.reconcileWorkerRollout(context.Background(), dgd, &status))\n+\tassert.Equal(t, expectedHash, dgd.Annotations[commonconsts.AnnotationCurrentWorkerHashV2])\n+\tassert.Nil(t, status.RollingUpdate)\n }\n \n // TestComponentWorkloadsReconciler_RemovedWorkerComponentDrainedToZero guards the\ndiff --git a/deploy/operator/internal/controller/lws_worker_availability_test.go b/deploy/operator/internal/controller/lws_worker_availability_test.go\nnew file mode 100644\nindex 000000000000..ab847ccf3731\n--- /dev/null\n+++ b/deploy/operator/internal/controller/lws_worker_availability_test.go\n@@ -0,0 +1,520 @@\n+/*\n+ * SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+ * SPDX-License-Identifier: Apache-2.0\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package controller\n+\n+import (\n+\t\"context\"\n+\t\"testing\"\n+\n+\t\"github.com/stretchr/testify/assert\"\n+\t\"github.com/stretchr/testify/require\"\n+\tcorev1 \"k8s.io/api/core/v1\"\n+\tapierrors \"k8s.io/apimachinery/pkg/api/errors\"\n+\tmetav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n+\t\"k8s.io/utils/ptr\"\n+\t\"sigs.k8s.io/controller-runtime/pkg/client\"\n+\t\"sigs.k8s.io/controller-runtime/pkg/event\"\n+\tleaderworkersetv1 \"sigs.k8s.io/lws/api/leaderworkerset/v1\"\n+\n+\tnvidiacomv1alpha1 \"github.com/ai-dynamo/dynamo/deploy/operator/api/v1alpha1\"\n+\tnvidiacomv1beta1 \"github.com/ai-dynamo/dynamo/deploy/operator/api/v1beta1\"\n+\t\"github.com/ai-dynamo/dynamo/deploy/operator/internal/common\"\n+\t\"github.com/ai-dynamo/dynamo/deploy/operator/internal/consts\"\n+\t\"github.com/ai-dynamo/dynamo/deploy/operator/internal/dynamo\"\n+)\n+\n+func TestLWSAvailabilityDrivesWorkerGenerationCleanup(t *testing.T) {\n+\tt.Log(\"Define replacement readiness and the old groups that must remain available\")\n+\ttests := []struct {\n+\t\tname string\n+\t\tdesired int32\n+\t\tnewReady int32\n+\t\twantOld int32\n+\t\thashAlreadyUpdated bool\n+\t}{\n+\t\t{name: \"unready replacement preserves old group\", desired: 1, newReady: 0, wantOld: 1},\n+\t\t{name: \"ready replacement retires old group\", desired: 1, newReady: 1, wantOld: 0},\n+\t\t{name: \"unready replacements preserve all old groups\", desired: 3, newReady: 0, wantOld: 3},\n+\t\t{name: \"one ready replacement retires one old group\", desired: 3, newReady: 1, wantOld: 2},\n+\t\t{name: \"partial readiness retires only covered old groups\", desired: 3, newReady: 2, wantOld: 1},\n+\t\t{name: \"all ready replacements retire all old groups\", desired: 3, newReady: 3, wantOld: 0},\n+\t\t{name: \"cleanup resumes after hash update\", desired: 1, newReady: 1, wantOld: 0, hashAlreadyUpdated: true},\n+\t}\n+\n+\tfor _, tt := range tests {\n+\t\tt.Run(tt.name, func(t *testing.T) {\n+\t\t\tt.Log(\"Create a multi-node worker deployment with an old generation\")\n+\t\t\tdgd := createTestDGD(\"test-dgd\", map[string]*nvidiacomv1alpha1.DynamoComponentDeploymentSharedSpec{\n+\t\t\t\t\"worker\": {\n+\t\t\t\t\tComponentType: consts.ComponentTypeWorker,\n+\t\t\t\t\tReplicas: ptr.To(tt.desired),\n+\t\t\t\t\tMultinode: &nvidiacomv1alpha1.MultinodeSpec{NodeCount: 2},\n+\t\t\t\t},\n+\t\t\t})\n+\t\t\tdgd.Annotations = map[string]string{consts.AnnotationCurrentWorkerHashV2: testOldWorkerHash}\n+\t\t\tnewHash := betaDGDWorkersSpecHash(t, dgd)\n+\t\t\texpectedCurrentHash := testOldWorkerHash\n+\t\t\tif tt.hashAlreadyUpdated {\n+\t\t\t\texpectedCurrentHash = newHash\n+\t\t\t\tdgd.Annotations[consts.AnnotationCurrentWorkerHashV2] = newHash\n+\t\t\t}\n+\t\t\tgenerations := []struct {\n+\t\t\t\thash string\n+\t\t\t\tready int32\n+\t\t\t}{\n+\t\t\t\t{hash: testOldWorkerHash, ready: tt.desired},\n+\t\t\t\t{hash: newHash, ready: tt.newReady},\n+\t\t\t}\n+\t\t\tdcds := make([]*nvidiacomv1beta1.DynamoComponentDeployment, 0, len(generations))\n+\n+\t\t\tt.Log(\"Populate each DCD through the production LWS status mapping\")\n+\t\t\tfor _, generation := range generations {\n+\t\t\t\tdcd := createTestDCD(t, dgd, &nvidiacomv1alpha1.DynamoComponentDeployment{\n+\t\t\t\t\tObjectMeta: metav1.ObjectMeta{\n+\t\t\t\t\t\tName: dynamo.GetDCDResourceName(dgd, \"worker\", generation.hash),\n+\t\t\t\t\t\tNamespace: dgd.Namespace,\n+\t\t\t\t\t\tLabels: map[string]string{\n+\t\t\t\t\t\t\tconsts.KubeLabelDynamoGraphDeploymentName: dgd.Name,\n+\t\t\t\t\t\t\tconsts.KubeLabelDynamoWorkerHash: generation.hash,\n+\t\t\t\t\t\t},\n+\t\t\t\t\t},\n+\t\t\t\t\tSpec: nvidiacomv1alpha1.DynamoComponentDeploymentSpec{\n+\t\t\t\t\t\tDynamoComponentDeploymentSharedSpec: nvidiacomv1alpha1.DynamoComponentDeploymentSharedSpec{\n+\t\t\t\t\t\t\tServiceName: \"worker\",\n+\t\t\t\t\t\t\tComponentType: consts.ComponentTypeWorker,\n+\t\t\t\t\t\t\tReplicas: ptr.To(tt.desired),\n+\t\t\t\t\t\t\tMultinode: &nvidiacomv1alpha1.MultinodeSpec{NodeCount: 2},\n+\t\t\t\t\t\t},\n+\t\t\t\t\t},\n+\t\t\t\t})\n+\t\t\t\tlws := &leaderworkersetv1.LeaderWorkerSet{\n+\t\t\t\t\tObjectMeta: metav1.ObjectMeta{Name: dcd.Name},\n+\t\t\t\t\tSpec: leaderworkersetv1.LeaderWorkerSetSpec{Replicas: ptr.To(tt.desired)},\n+\t\t\t\t\tStatus: leaderworkersetv1.LeaderWorkerSetStatus{\n+\t\t\t\t\t\tReplicas: tt.desired,\n+\t\t\t\t\t\tUpdatedReplicas: tt.desired,\n+\t\t\t\t\t\tReadyReplicas: generation.ready,\n+\t\t\t\t\t},\n+\t\t\t\t}\n+\t\t\t\toriginal := lws.DeepCopy()\n+\t\t\t\tstatus := getLeaderWorkerSetReplicasStatus(lws)\n+\t\t\t\tassert.Equal(t, original, lws, \"status mapping must not mutate the LWS\")\n+\t\t\t\tassert.Nil(t, status.AvailableReplicas, \"LWS does not report a separate availability count\")\n+\t\t\t\tstatus.RuntimeNamespace = \"test-dgd-\" + generation.hash\n+\t\t\t\tdcd.Status.Component = &status\n+\t\t\t\tdcds = append(dcds, dcd)\n+\t\t\t}\n+\n+\t\t\tt.Log(\"Calculate rollout targets using readiness when LWS availability is absent\")\n+\t\t\tr := createTestReconcilerWithStatus(dgd, withObjects(dcds[0], dcds[1]))\n+\t\t\tctx := context.Background()\n+\t\t\trollout, err := r.buildRollingUpdateContext(ctx, dgd)\n+\t\t\trequire.NoError(t, err)\n+\t\t\tassert.Equal(t, tt.wantOld, rollout.OldWorkerReplicaTargetsByComponent[\"worker\"])\n+\t\t\tassert.Equal(t, tt.desired, rollout.NewWorkerReplicaTargetsByComponent[\"worker\"])\n+\n+\t\t\tt.Log(\"Persist old-generation scale-down without changing replacement intent\")\n+\t\t\trequire.NoError(t, r.scaleOldWorkerDCDs(ctx, dgd, rollout))\n+\t\t\toldDCD := &nvidiacomv1beta1.DynamoComponentDeployment{}\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(dcds[0]), oldDCD))\n+\t\t\tassert.Equal(t, ptr.To(tt.wantOld), oldDCD.Spec.Replicas)\n+\t\t\tnewDCD := &nvidiacomv1beta1.DynamoComponentDeployment{}\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(dcds[1]), newDCD))\n+\t\t\tassert.Equal(t, ptr.To(tt.desired), newDCD.Spec.Replicas)\n+\n+\t\t\tt.Log(\"Keep the old DCD while it still reports live replicas\")\n+\t\t\tprogram := &componentProgram{rollout: r}\n+\t\t\tprogramStatus := dgd.DeepCopy().Status\n+\t\t\trequire.NoError(t, program.reconcileWorkerRollout(ctx, dgd, &programStatus))\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(oldDCD), oldDCD))\n+\t\t\tassert.Nil(t, oldDCD.DeletionTimestamp)\n+\t\t\tassert.Equal(t, expectedCurrentHash, dgd.Annotations[consts.AnnotationCurrentWorkerHashV2])\n+\t\t\tif tt.wantOld != 0 {\n+\t\t\t\treturn\n+\t\t\t}\n+\n+\t\t\tt.Log(\"Wait until the old DCD has observed its scale-to-zero generation\")\n+\t\t\toldDCD.Generation = 2\n+\t\t\toldDCD.Status.ObservedGeneration = 1\n+\t\t\toldDCD.Status.Component.Replicas = 0\n+\t\t\toldDCD.Status.Component.ReadyReplicas = ptr.To(int32(0))\n+\t\t\toldDCD.Status.Component.AvailableReplicas = nil\n+\t\t\trequire.NoError(t, r.Update(ctx, oldDCD))\n+\t\t\trequire.NoError(t, program.reconcileWorkerRollout(ctx, dgd, &programStatus))\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(oldDCD), oldDCD))\n+\t\t\tassert.Nil(t, oldDCD.DeletionTimestamp)\n+\n+\t\t\tt.Log(\"Preserve the old generation while native LWS leader and worker pods are still running\")\n+\t\t\toldDCD.Status.ObservedGeneration = oldDCD.Generation\n+\t\t\toldDCD.Finalizers = []string{\"test.dynamo.nvidia.com/hold-deletion\"}\n+\t\t\trequire.NoError(t, r.Update(ctx, oldDCD))\n+\t\t\toldPod := &corev1.Pod{\n+\t\t\t\tObjectMeta: metav1.ObjectMeta{\n+\t\t\t\t\tName: \"old-worker\", Namespace: dgd.Namespace,\n+\t\t\t\t\tLabels: map[string]string{\n+\t\t\t\t\t\tconsts.KubeLabelDynamoGraphDeploymentName: dgd.Name,\n+\t\t\t\t\t\tconsts.KubeLabelDynamoComponent: \"worker\",\n+\t\t\t\t\t\tconsts.KubeLabelDynamoWorkerHash: testOldWorkerHash,\n+\t\t\t\t\t\tconsts.KubeLabelDynamoComponentType: consts.ComponentTypeWorker,\n+\t\t\t\t\t\tdcdWorkloadRoleLabel: string(dynamo.RoleWorker),\n+\t\t\t\t\t},\n+\t\t\t\t\tFinalizers: []string{\"test.dynamo.nvidia.com/hold-deletion\"},\n+\t\t\t\t},\n+\t\t\t\tStatus: corev1.PodStatus{Phase: corev1.PodRunning},\n+\t\t\t}\n+\t\t\toldLeader := oldPod.DeepCopy()\n+\t\t\toldLeader.Name = \"old-leader\"\n+\t\t\toldLeader.Labels[dcdWorkloadRoleLabel] = string(dynamo.RoleLeader)\n+\t\t\trequire.NoError(t, r.Create(ctx, oldLeader))\n+\t\t\trequire.NoError(t, r.Delete(ctx, oldLeader))\n+\t\t\trequire.NoError(t, r.Create(ctx, oldPod))\n+\t\t\trequire.NoError(t, r.Delete(ctx, oldPod))\n+\t\t\trequire.NoError(t, program.reconcileWorkerRollout(ctx, dgd, &programStatus))\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(oldDCD), oldDCD))\n+\t\t\tassert.Nil(t, oldDCD.DeletionTimestamp)\n+\n+\t\t\tt.Log(\"Keep waiting for the leader after its worker disappears\")\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(oldPod), oldPod))\n+\t\t\toldPod.Finalizers = nil\n+\t\t\trequire.NoError(t, r.Update(ctx, oldPod))\n+\t\t\trequire.NoError(t, program.reconcileWorkerRollout(ctx, dgd, &programStatus))\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(oldDCD), oldDCD))\n+\t\t\tassert.Nil(t, oldDCD.DeletionTimestamp)\n+\n+\t\t\tt.Log(\"Delete the drained old DCD after its final pod disappears\")\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(oldLeader), oldLeader))\n+\t\t\toldLeader.Finalizers = nil\n+\t\t\trequire.NoError(t, r.Update(ctx, oldLeader))\n+\t\t\trequire.NoError(t, program.reconcileWorkerRollout(ctx, dgd, &programStatus))\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(oldDCD), oldDCD))\n+\t\t\trequire.NotNil(t, oldDCD.DeletionTimestamp)\n+\t\t\tassert.Equal(t, expectedCurrentHash, dgd.Annotations[consts.AnnotationCurrentWorkerHashV2])\n+\n+\t\t\tt.Log(\"Keep the old hash and runtime projection until the DCD deletion is observed\")\n+\t\t\trequire.NoError(t, program.reconcileWorkerRollout(ctx, dgd, &programStatus))\n+\t\t\tassert.Equal(t, expectedCurrentHash, dgd.Annotations[consts.AnnotationCurrentWorkerHashV2])\n+\t\t\trollout, err = r.buildRollingUpdateContext(ctx, dgd)\n+\t\t\trequire.NoError(t, err)\n+\t\t\tassert.True(t, rollout.InProgress())\n+\t\t\toldStatuses, err := r.aggregateOldWorkerComponentStatuses(ctx, dgd, rollout)\n+\t\t\trequire.NoError(t, err)\n+\t\t\tstatuses := map[string]nvidiacomv1beta1.ComponentReplicaStatus{\"worker\": *newDCD.Status.Component}\n+\t\t\tmergeWorkerComponentStatuses(statuses, oldStatuses)\n+\t\t\tassert.Equal(t, oldDCD.Status.Component.RuntimeNamespace, statuses[\"worker\"].RuntimeNamespace)\n+\n+\t\t\tt.Log(\"Observe deletion and reconcile repeatedly without retaining the old projection\")\n+\t\t\trequire.NoError(t, r.Get(ctx, client.ObjectKeyFromObject(oldDCD), oldDCD))\n+\t\t\toldDCD.Finalizers = nil\n+\t\t\trequire.NoError(t, r.Update(ctx, oldDCD))\n+\t\t\trequire.NoError(t, program.reconcileWorkerRollout(ctx, dgd, &programStatus))\n+\t\t\trequire.NoError(t, program.reconcileWorkerRollout(ctx, dgd, &programStatus))\n+\t\t\tassert.True(t, apierrors.IsNotFound(r.Get(ctx, client.ObjectKeyFromObject(oldDCD), oldDCD)))\n+\t\t\trollout, err = r.buildRollingUpdateContext(ctx, dgd)\n+\t\t\trequire.NoError(t, err)\n+\t\t\tassert.False(t, rollout.InProgress())\n+\t\t\tassert.Equal(t, newHash, dgd.Annotations[consts.AnnotationCurrentWorkerHashV2])\n+\t\t\toldStatuses, err = r.aggregateOldWorkerComponentStatuses(ctx, dgd, rollout)\n+\t\t\trequire.NoError(t, err)\n[... diff truncated: 0 more file(s) not shown]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(helm): wait for the KAI queue controller before creating Dynamo queues\nLabels: documentation, external-contribution, size/L, deployment::k8s, fix\nFiles changed (6): deploy/helm/charts/platform/Chart.yaml, deploy/helm/charts/platform/README.md, deploy/helm/charts/platform/README.md.gotmpl, deploy/helm/charts/platform/templates/kai-queue-wait.yaml, deploy/helm/charts/platform/tests/kai_queue_wait_test.yaml, deploy/helm/charts/platform/values.yaml\n\n## Description (results removed)\n\n## Summary\n\n[output with results removed]\n\nThis PR adds a post-install/post-upgrade hook Job (weight 90) that runs between those two points. It waits for `queue-controller` to exist and become Available, then confirms with a server-side dry-run that the webhook actually admits a Queue. The dry-run step is needed because KAI's Deployment has no readiness probe and reports Available before the webhook serves.\n\n## Details\n\n- **`templates/kai-queue-wait.yaml`**: hook objects at weight 80, all with `before-hook-creation,hook-succeeded`:\n - a ServiceAccount;\n - a namespaced Role (`get/list/watch` on Deployments) and RoleBinding;\n - a ClusterRole (`create` on `queues.scheduling.run.ai`) and ClusterRoleBinding. A server-side dry-run requires `create` permission; nothing is persisted, and both objects are removed on success;\n - a ConfigMap with a top-level probe Queue, `-kai-queue-wait-probe`, that never collides with the Dynamo Queues.\n- **The Job (weight 90)** runs three kubectl steps, with no shell needed in the image:\n 1. init `wait-for-create`: `kubectl wait --for=create deployment/queue-controller`, because kai-operator creates the Deployment at runtime;\n 2. init `wait-for-available`: `kubectl wait --for=condition=Available`, so retries aren't spent while the image pulls;\n- The template follows the `grove-preflight` hook from #16546: the same hook annotations and `hook-output-log-policy`, the same hardened pod/container security context (`podSecurityContext: null` means the default), plus `imagePullSecrets`, `affinity` and `activeDeadlineSeconds`. Tolerations come from `kai-scheduler.global.tolerations`.\n- It renders only for bundled KAI (`global.kai-scheduler.install`) with its queue-controller enabled (`kai-scheduler.queuecontroller.enabled`; a missing value counts as true). External KAI or a disabled queue-controller has no webhook to wait for.\n- Every field has a template default, so `helm upgrade --reuse-values` from a release that predates `kaiQueueWait` still renders.\n- **`values.yaml`**: a new `kaiQueueWait` block (`enabled`, `image: registry.k8s.io/kubectl:v1.34.12`, `imagePullSecrets`, `activeDeadlineSeconds: 600`, `affinity`, `podSecurityContext`). `podSecurityContext` is typed `(object)` for helm-docs. The image is distroless and runs as UID 0, hence the default `runAsUser: 65532`. kubectl ≥ 1.31 is required for `--for=create`.\n- **`Chart.yaml`**: a comment at the `kai-scheduler` dependency noting that the hook depends on KAI's `queue-controller` Deployment name.\n- **`README.md`**: regenerated with helm-docs.\n- **`tests/kai_queue_wait_test.yaml`**: 16 helm-unittest cases covering:\n - when the hook renders, including with the queue-controller disabled;\n - hook ordering and the three steps' arguments;\n - the probe Queue;\n - namespaced and cluster RBAC;\n - security defaults and overrides;\n - image pinning and the `--reuse-values` defaults.\n\n## Validation\n[results removed]\n## Related Issues\n\n- Closes #16126\n\n## Summary by CodeRabbit\n\n* **New Features**\n * The platform Helm chart now waits for the KAI queue controller to become available when bundled KAI integration is enabled. The wait is enabled by default and times out after 600 seconds.\n * Configure the wait job’s image, image pull secrets, scheduling, pod security settings, and tolerations.\n* **Documentation**\n * Added chart values documentation for the queue-controller wait settings and their defaults.\n\n## Diff\n\n```diff\ndiff --git a/deploy/helm/charts/platform/Chart.yaml b/deploy/helm/charts/platform/Chart.yaml\nindex 1dbe2132d8b7..5f342033c346 100644\n--- a/deploy/helm/charts/platform/Chart.yaml\n+++ b/deploy/helm/charts/platform/Chart.yaml\n@@ -39,6 +39,8 @@ dependencies:\n version: 12.0.18\n repository: \"https://charts.bitnami.com/bitnami\"\n condition: global.etcd.install\n+ # templates/kai-queue-wait.yaml depends on KAI's queue-controller Deployment and\n+ # kai-queue-validation-v2 webhook configuration names.\n - name: kai-scheduler\n version: v0.17.0\n repository: oci://ghcr.io/kai-scheduler/kai-scheduler\ndiff --git a/deploy/helm/charts/platform/templates/kai-queue-wait.yaml b/deploy/helm/charts/platform/templates/kai-queue-wait.yaml\nnew file mode 100644\nindex 000000000000..a9377a229a6b\n--- /dev/null\n+++ b/deploy/helm/charts/platform/templates/kai-queue-wait.yaml\n@@ -0,0 +1,196 @@\n+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+# SPDX-License-Identifier: Apache-2.0\n+\n+{{- /*\n+ Holds the kai.yaml Queue hooks (weight 100) until bundled KAI's queue-controller webhook admits\n+ Queues. KAI creates it at runtime without a readiness probe, so the Job ends with a server-side\n+ dry-run. Template defaults keep `--reuse-values` from older releases working.\n+*/ -}}\n+{{- $kai := index .Values.global \"kai-scheduler\" | default dict -}}\n+{{- $kaiValues := index .Values \"kai-scheduler\" | default dict -}}\n+{{- $config := .Values.kaiQueueWait | default dict -}}\n+{{- /* With kai-config managed outside the chart, queue-controller may never appear during install. */ -}}\n+{{- $kaiConfigApplied := or (ne (dig \"kaiConfigDeployer\" \"enabled\" true $kaiValues) false) (dig \"kaiConfig\" \"render\" false $kaiValues) -}}\n+{{- if and ($kai.install | default false) (ne (dig \"enabled\" true $config) false) (ne (dig \"queuecontroller\" \"enabled\" true $kaiValues) false) $kaiConfigApplied -}}\n+{{- $name := printf \"%s-kai-queue-wait\" (.Release.Name | trunc 48 | trimSuffix \"-\") -}}\n+{{- $identity := printf \"%s/%s\" .Release.Namespace .Release.Name | sha256sum | trunc 8 -}}\n+{{- $clusterRbac := printf \"%s-%s\" ($name | trunc 54 | trimSuffix \"-\") $identity -}}\n+{{- $deadline := $config.activeDeadlineSeconds | default 600 | int -}}\n+{{- $podSecurityContext := $config.podSecurityContext -}}\n+{{- if eq $podSecurityContext nil -}}\n+{{- $podSecurityContext = dict \"runAsNonRoot\" true \"runAsUser\" 65532 \"seccompProfile\" (dict \"type\" \"RuntimeDefault\") -}}\n+{{- end -}}\n+{{- $tolerations := dig \"global\" \"tolerations\" list $kaiValues -}}\n+{{- $annotations := dict \"helm.sh/hook\" \"post-install,post-upgrade\" \"helm.sh/hook-weight\" \"80\" \"helm.sh/hook-delete-policy\" \"before-hook-creation,hook-succeeded\" }}\n+apiVersion: v1\n+kind: ServiceAccount\n+metadata:\n+ name: {{ $name }}\n+ namespace: {{ .Release.Namespace }}\n+ annotations: {{- toYaml $annotations | nindent 4 }}\n+---\n+apiVersion: rbac.authorization.k8s.io/v1\n+kind: Role\n+metadata:\n+ name: {{ $name }}\n+ namespace: {{ .Release.Namespace }}\n+ annotations: {{- toYaml $annotations | nindent 4 }}\n+rules:\n+ - apiGroups: [apps]\n+ resources: [deployments]\n+ verbs: [get, list, watch]\n+---\n+apiVersion: rbac.authorization.k8s.io/v1\n+kind: RoleBinding\n+metadata:\n+ name: {{ $name }}\n+ namespace: {{ .Release.Namespace }}\n+ annotations: {{- toYaml $annotations | nindent 4 }}\n+roleRef:\n+ apiGroup: rbac.authorization.k8s.io\n+ kind: Role\n+ name: {{ $name }}\n+subjects:\n+ - kind: ServiceAccount\n+ name: {{ $name }}\n+ namespace: {{ .Release.Namespace }}\n+---\n+{{- /* The dry-run needs create; nothing is persisted. `wait --for=create` only gets the named object. */}}\n+apiVersion: rbac.authorization.k8s.io/v1\n+kind: ClusterRole\n+metadata:\n+ name: {{ $clusterRbac }}\n+ annotations: {{- toYaml $annotations | nindent 4 }}\n+rules:\n+ - apiGroups: [scheduling.run.ai]\n+ resources: [queues]\n+ verbs: [create]\n+ - apiGroups: [admissionregistration.k8s.io]\n+ resources: [validatingwebhookconfigurations]\n+ resourceNames: [kai-queue-validation-v2]\n+ verbs: [get]\n+---\n+apiVersion: rbac.authorization.k8s.io/v1\n+kind: ClusterRoleBinding\n+metadata:\n+ name: {{ $clusterRbac }}\n+ annotations: {{- toYaml $annotations | nindent 4 }}\n+roleRef:\n+ apiGroup: rbac.authorization.k8s.io\n+ kind: ClusterRole\n+ name: {{ $clusterRbac }}\n+subjects:\n+ - kind: ServiceAccount\n+ name: {{ $name }}\n+ namespace: {{ .Release.Namespace }}\n+---\n+apiVersion: v1\n+kind: ConfigMap\n+metadata:\n+ name: {{ $name }}\n+ namespace: {{ .Release.Namespace }}\n+ annotations: {{- toYaml $annotations | nindent 4 }}\n+data:\n+ queue.yaml: |\n+ apiVersion: scheduling.run.ai/v2\n+ kind: Queue\n+ metadata:\n+ name: {{ printf \"%s-probe\" ($name | trunc 57 | trimSuffix \"-\") }}\n+ spec:\n+ resources:\n+ cpu: {quota: -1, limit: -1, overQuotaWeight: 1}\n+ gpu: {quota: -1, limit: -1, overQuotaWeight: 1}\n+ memory: {quota: -1, limit: -1, overQuotaWeight: 1}\n+---\n+apiVersion: batch/v1\n+kind: Job\n+metadata:\n+ name: {{ $name }}\n+ namespace: {{ .Release.Namespace }}\n+ annotations:\n+ helm.sh/hook: post-install,post-upgrade\n+ helm.sh/hook-weight: \"90\"\n+ helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded\n+ helm.sh/hook-output-log-policy: hook-failed\n+spec:\n+ activeDeadlineSeconds: {{ $deadline }}\n+ # Retries the admission check with pod backoff (10s, 20s, ...).\n+ backoffLimit: 6\n+ template:\n+ spec:\n+ serviceAccountName: {{ $name }}\n+ restartPolicy: Never\n+ {{- with $config.imagePullSecrets }}\n+ imagePullSecrets: {{- toYaml . | nindent 8 }}\n+ {{- end }}\n+ {{- with $tolerations }}\n+ tolerations: {{- toYaml . | nindent 8 }}\n+ {{- end }}\n+ {{- with $config.affinity }}\n+ affinity: {{- toYaml . | nindent 8 }}\n+ {{- end }}\n+ {{- with $podSecurityContext }}\n+ securityContext: {{- toYaml . | nindent 8 }}\n+ {{- end }}\n+ {{- /* A dry-run passes while no Queue webhook is registered, and KAI creates the webhook and the Deployment in no fixed order. */}}\n+ initContainers:\n+ - name: wait-for-create\n+ {{- include \"dynamo-platform.kaiQueueWaitContainer\" (dict \"config\" $config) | nindent 10 }}\n+ args:\n+ - wait\n+ - --for=create\n+ - deployment/queue-controller\n+ - --namespace={{ .Release.Namespace }}\n+ - --timeout={{ $deadline }}s\n+ - name: wait-for-available\n+ {{- include \"dynamo-platform.kaiQueueWaitContainer\" (dict \"config\" $config) | nindent 10 }}\n+ args:\n+ - wait\n+ - --for=condition=Available\n+ - deployment/queue-controller\n+ - --namespace={{ .Release.Namespace }}\n+ - --timeout={{ $deadline }}s\n+ - name: wait-for-queue-webhook\n+ {{- include \"dynamo-platform.kaiQueueWaitContainer\" (dict \"config\" $config) | nindent 10 }}\n+ args:\n+ - wait\n+ - --for=create\n+ - validatingwebhookconfiguration/kai-queue-validation-v2\n+ - --timeout={{ $deadline }}s\n+ containers:\n+ - name: check-admission\n+ {{- include \"dynamo-platform.kaiQueueWaitContainer\" (dict \"config\" $config) | nindent 10 }}\n+ args:\n+ - create\n+ - --dry-run=server\n+ - --filename=/probe/queue.yaml\n+ volumes:\n+ - name: tmp\n+ emptyDir: {}\n+ - name: probe\n+ configMap:\n+ name: {{ $name }}\n+{{- end }}\n+\n+{{- define \"dynamo-platform.kaiQueueWaitContainer\" -}}\n+image: {{ .config.image | default \"registry.k8s.io/kubectl:v1.34.12\" | quote }}\n+command: [kubectl]\n+env:\n+ # Writable discovery cache; the root filesystem is read-only.\n+ - name: HOME\n+ value: /tmp\n+volumeMounts:\n+ - name: tmp\n+ mountPath: /tmp\n+ - name: probe\n+ mountPath: /probe\n+ readOnly: true\n+securityContext:\n+ allowPrivilegeEscalation: false\n+ readOnlyRootFilesystem: true\n+ capabilities:\n+ drop: [ALL]\n+resources:\n+ requests: {cpu: 10m, memory: 32Mi}\n+ limits: {memory: 128Mi}\n+{{- end }}\ndiff --git a/deploy/helm/charts/platform/values.yaml b/deploy/helm/charts/platform/values.yaml\nindex b6c2d8b4a1aa..71c17fbcbae4 100644\n--- a/deploy/helm/charts/platform/values.yaml\n+++ b/deploy/helm/charts/platform/values.yaml\n@@ -372,6 +372,21 @@ kai-scheduler:\n # -- Affinity for kai-scheduler pods\n affinity: {}\n \n+# Hook Job that holds the Dynamo Queues until bundled KAI's queue-controller webhook admits Queues.\n+kaiQueueWait:\n+ # -- Wait for the bundled KAI queue-controller before creating the Dynamo Queues. Disable only when the webhook is known to be serving, or when Queue validation is disabled in kai-config.\n+ enabled: true\n+ # -- Image providing kubectl 1.31 or later, which can wait for a resource to be created. Override for an internal registry.\n+ image: registry.k8s.io/kubectl:v1.34.12\n+ # -- Existing pull secrets for the wait image.\n+ imagePullSecrets: []\n+ # -- Maximum Job duration in seconds, including retries. The Helm timeout still bounds the hook.\n+ activeDeadlineSeconds: 600\n+ # -- Affinity for the wait Job. Tolerations are inherited from kai-scheduler.global.tolerations.\n+ affinity: {}\n+ # -- (object) Full replacement of the wait pod security context. Null defaults to runAsNonRoot=true, runAsUser=65532 and seccompProfile.type=RuntimeDefault. On OpenShift, supply a context without runAsUser for admission to assign it.\n+ podSecurityContext: null\n+\n # etcd configuration - distributed key-value store\n # Installation is controlled by global.etcd.install above.\n etcd:\n\n[2 documentation file diff(s) omitted]\ndiff --git a/deploy/helm/charts/platform/tests/kai_queue_wait_test.yaml b/deploy/helm/charts/platform/tests/kai_queue_wait_test.yaml\nnew file mode 100644\nindex 000000000000..e56358ef3c26\n--- /dev/null\n+++ b/deploy/helm/charts/platform/tests/kai_queue_wait_test.yaml\n@@ -0,0 +1,174 @@\n+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+# SPDX-License-Identifier: Apache-2.0\n+\n+suite: bundled KAI queue-controller wait\n+templates:\n+ - templates/kai-queue-wait.yaml\n+release:\n+ name: dynamo-platform\n+ namespace: dynamo-system\n+tests:\n+ - it: renders the hook for bundled KAI\n+ set: {global.kai-scheduler.install: true}\n+ asserts:\n+ - hasDocuments: {count: 7}\n+ - it: omits the hook when KAI integration is disabled\n+ asserts:\n+ - hasDocuments: {count: 0}\n+ - it: omits the hook for externally managed KAI\n+ set: {global.kai-scheduler.enabled: true}\n+ asserts:\n+ - hasDocuments: {count: 0}\n+ - it: can be disabled\n+ set: {global.kai-scheduler.install: true, kaiQueueWait.enabled: false}\n+ asserts:\n+ - hasDocuments: {count: 0}\n+ - it: omits the hook when bundled KAI runs without its queue-controller\n+ set: {global.kai-scheduler.install: true, kai-scheduler.queuecontroller.enabled: false}\n+ asserts:\n+ - hasDocuments: {count: 0}\n+ - it: omits the hook when kai-config is managed outside the chart\n+ set: {global.kai-scheduler.install: true, kai-scheduler.kaiConfigDeployer.enabled: false}\n+ asserts:\n+ - hasDocuments: {count: 0}\n+ - it: renders the hook when kai-config is rendered as a release resource\n+ set:\n+ global.kai-scheduler.install: true\n+ kai-scheduler.kaiConfigDeployer.enabled: false\n+ kai-scheduler.kaiConfig.render: true\n+ asserts:\n+ - hasDocuments: {count: 7}\n+ - it: renders with template defaults when values predate kaiQueueWait (helm upgrade --reuse-values)\n+ set: {global.kai-scheduler.install: true, kaiQueueWait: null}\n+ documentSelector: {path: kind, value: Job}\n+ asserts:\n+ - equal: {path: spec.activeDeadlineSeconds, value: 600}\n+ - equal: {path: 'spec.template.spec.containers[0].image', value: registry.k8s.io/kubectl:v1.34.12}\n+ - equal: {path: spec.template.spec.securityContext.runAsUser, value: 65532}\n+ # Pins values.yaml to the template fallback above.\n+ - it: uses the same default image from values.yaml\n+ set: {global.kai-scheduler.install: true}\n+ documentSelector: {path: kind, value: Job}\n+ asserts:\n+ - equal: {path: 'spec.template.spec.initContainers[0].image', value: registry.k8s.io/kubectl:v1.34.12}\n+ - equal: {path: 'spec.template.spec.initContainers[1].image', value: registry.k8s.io/kubectl:v1.34.12}\n+ - equal: {path: 'spec.template.spec.containers[0].image', value: registry.k8s.io/kubectl:v1.34.12}\n+ - it: runs after the KAI config deployer and before the Queue hooks\n+ set: {global.kai-scheduler.install: true}\n+ documentSelector: {path: kind, value: Job}\n+ asserts:\n+ - equal: {path: metadata.name, value: dynamo-platform-kai-queue-wait}\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook\"]', value: 'post-install,post-upgrade'}\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook-weight\"]', value: '90'}\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook-delete-policy\"]', value: 'before-hook-creation,hook-succeeded'}\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook-output-log-policy\"]', value: hook-failed}\n+ - equal: {path: spec.backoffLimit, value: 6}\n+ - it: waits for queue-controller and its webhook registration, then dry-runs a Queue through the webhook\n+ set: {global.kai-scheduler.install: true}\n+ documentSelector: {path: kind, value: Job}\n+ asserts:\n+ - equal:\n+ path: 'spec.template.spec.initContainers[0].args'\n+ value: [wait, --for=create, deployment/queue-controller, --namespace=dynamo-system, --timeout=600s]\n+ - equal:\n+ path: 'spec.template.spec.initContainers[1].args'\n+ value: [wait, --for=condition=Available, deployment/queue-controller, --namespace=dynamo-system, --timeout=600s]\n+ # A dry-run passes while no webhook is registered, so this step must precede check-admission.\n+ - equal:\n+ path: 'spec.template.spec.initContainers[2].args'\n+ value: [wait, --for=create, validatingwebhookconfiguration/kai-queue-validation-v2, --timeout=600s]\n+ - equal:\n+ path: 'spec.template.spec.containers[0].args'\n+ value: [create, --dry-run=server, --filename=/probe/queue.yaml]\n+ - equal: {path: 'spec.template.spec.volumes[1].configMap.name', value: dynamo-platform-kai-queue-wait}\n+ - it: ships a top-level probe Queue that never collides with the Dynamo Queues\n+ set: {global.kai-scheduler.install: true}\n+ documentSelector: {path: kind, value: ConfigMap}\n+ asserts:\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook-weight\"]', value: '80'}\n+ - matchRegex: {path: 'data[\"queue.yaml\"]', pattern: 'kind: Queue'}\n+ - matchRegex: {path: 'data[\"queue.yaml\"]', pattern: 'name: dynamo-platform-kai-queue-wait-probe\\n'}\n+ - notMatchRegex: {path: 'data[\"queue.yaml\"]', pattern: parentQueue}\n+ - it: grants only Queue create and read of the Queue webhook configuration, cluster-wide, and removes it on success\n+ set: {global.kai-scheduler.install: true}\n+ documentSelector: {path: kind, value: ClusterRole}\n+ asserts:\n+ - matchRegex: {path: metadata.name, pattern: '^dynamo-platform-kai-queue-wait-[0-9a-f]{8}$'}\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook-weight\"]', value: '80'}\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook-delete-policy\"]', value: 'before-hook-creation,hook-succeeded'}\n+ - equal:\n+ path: rules\n+ value:\n+ - apiGroups: [scheduling.run.ai]\n+ resources: [queues]\n+ verbs: [create]\n+ - apiGroups: [admissionregistration.k8s.io]\n+ resources: [validatingwebhookconfigurations]\n+ resourceNames: [kai-queue-validation-v2]\n+ verbs: [get]\n+ - it: grants only Deployment read access in the release namespace before the Job and removes it on success\n+ set: {global.kai-scheduler.install: true}\n+ documentSelector: {path: kind, value: Role}\n+ asserts:\n+ - equal: {path: metadata.namespace, value: dynamo-system}\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook-weight\"]', value: '80'}\n+ - equal: {path: 'metadata.annotations[\"helm.sh/hook-delete-policy\"]', value: 'before-hook-creation,hook-succeeded'}\n+ - equal:\n+ path: rules\n+ value:\n+ - apiGroups: [apps]\n+ resources: [deployments]\n+ verbs: [get, list, watch]\n+ - it: retains secure pod and container defaults\n+ set: {global.kai-scheduler.install: true}\n+ documentSelector: {path: kind, value: Job}\n+ asserts:\n+ - equal:\n+ path: spec.template.spec.securityContext\n+ value:\n+ runAsNonRoot: true\n+ runAsUser: 65532\n+ seccompProfile: {type: RuntimeDefault}\n+ - equal: {path: 'spec.template.spec.containers[0].securityContext.readOnlyRootFilesystem', value: true}\n+ - equal: {path: 'spec.template.spec.initContainers[0].securityContext.allowPrivilegeEscalation', value: false}\n+ - it: lets OpenShift assign the UID\n+ set:\n+ global.kai-scheduler.install: true\n+ kaiQueueWait.podSecurityContext:\n+ runAsNonRoot: true\n+ seccompProfile: {type: RuntimeDefault}\n+ documentSelector: {path: kind, value: Job}\n+ asserts:\n+ - notExists: {path: spec.template.spec.securityContext.runAsUser}\n+ - it: honors image, pull secret, deadline and affinity overrides\n+ set:\n+ global.kai-scheduler.install: true\n+ kaiQueueWait.image: registry.example.com/kubectl:v1.35.0\n+ kaiQueueWait.imagePullSecrets: [{name: mirror}]\n+ kaiQueueWait.activeDeadlineSeconds: 120\n+ kaiQueueWait.affinity:\n+ nodeAffinity:\n+ requiredDuringSchedulingIgnoredDuringExecution:\n+ nodeSelectorTerms:\n+ - matchExpressions:\n+ - {key: kubernetes.io/os, operator: In, values: [linux]}\n+ documentSelector: {path: kind, value: Job}\n+ asserts:\n+ - equal: {path: 'spec.template.spec.initContainers[0].image', value: registry.example.com/kubectl:v1.35.0}\n+ - equal: {path: 'spec.template.spec.initContainers[1].image', value: registry.example.com/kubectl:v1.35.0}\n+ - equal: {path: 'spec.template.spec.containers[0].image', value: registry.example.com/kubectl:v1.35.0}\n+ - equal: {path: spec.template.spec.imagePullSecrets, value: [{name: mirror}]}\n+ - equal: {path: spec.activeDeadlineSeconds, value: 120}\n+ - contains: {path: 'spec.template.spec.initContainers[1].args', content: --timeout=120s}\n+ - exists: {path: spec.template.spec.affinity.nodeAffinity}\n+ - it: schedules alongside KAI pods\n+ set:\n+ global.kai-scheduler.install: true\n+ kai-scheduler.global.tolerations:\n+ - {key: dedicated, operator: Equal, value: system, effect: NoSchedule}\n+ documentSelector: {path: kind, value: Job}\n+ asserts:\n+ - equal:\n+ path: spec.template.spec.tolerations\n+ value:\n+ - {key: dedicated, operator: Equal, value: system, effect: NoSchedule}\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(router): fail closed while a prefill target is activating\nLabels: documentation, external-contribution, size/XL, deployment::k8s, fix, frontend, router\nFiles changed (14): components/src/dynamo/frontend/sglang_processor.py, components/src/dynamo/frontend/tests/test_sglang_processor_metrics_unit.py, components/src/dynamo/frontend/tests/test_sglang_processor_unit.py, components/src/dynamo/frontend/tests/test_vllm_processor_unit.py, components/src/dynamo/frontend/vllm_processor.py, docs/fern/pages/developer-guide/knowledge-base/modular-components/router/disaggregated-serving.md, lib/bindings/python/rust/engine.rs, lib/bindings/python/rust/errors.rs, lib/bindings/python/rust/llm/routed_engine.rs, lib/bindings/python/src/dynamo/_core.pyi, lib/bindings/python/src/dynamo/llm/exceptions.py, lib/llm/src/kv_router/prefill_router/activation.rs, lib/llm/src/kv_router/prefill_router/mod.rs, tests/router/test_router_e2e_with_mockers.py\n\n## Description (results removed)\n\n## Overview:\n\nIn prefill/decode-disaggregated serving, the frontend can route requests to a decode-only worker with no prefill hop during a worker rollout. The decode WorkerSet becomes selectable as soon as its prefill peer registers, but the `PrefillRouter` only learns its target at that point and builds the binding asynchronously. Until that build completes the hop forwarded requests straight to decode as aggregated, and a disaggregated-only decode worker rejects them:\n\n```\nBackendUnknown: RuntimeError: bootstrap_info is required for disaggregated decode but was not provided\n```\n\n## Details:\n\nThe disagg startup lifecycle e2e in `tests/router/test_router_e2e_with_mockers.py` now rejects decode-only 200s once both roles have registered (see Validation).\n\n**Known limitation:** `RetryManager` lives inside the WorkerSet pipeline, so migration retries re-dispatch to the same namespace rather than hopping to the previous generation. During the window the client therefore sees a retryable 503 rather than a transparent retry. A bounded wait for activation before erroring would be a reasonable follow-up.\n\n- `lib/llm/src/kv_router/prefill_router/mod.rs`, the lifecycle branch at the top of `PrefillRouter::generate`, and `prefill_activation_pending_error`.\n- `lib/llm/src/kv_router/prefill_router/activation.rs`, `activation_snapshot()`.\n- `lib/bindings/python/rust/errors.rs`, `routed_error_to_pyerr` and `worker_unavailable_to_dynamo`, for the Python-processor path.\n\n## Validation\n[results removed]\n## Related Issues\n\n- Closes #16529\n\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Requests that arrive while a prefill worker is activating now receive a retryable error instead of being routed to decode without a prefill step.\n* **Documentation**\n * Updated the automatic prefill routing guide to explain the retryable error returned while routing is activating.\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/frontend/sglang_processor.py b/components/src/dynamo/frontend/sglang_processor.py\nindex 3fda3b1de7bd..85282c7be497 100644\n--- a/components/src/dynamo/frontend/sglang_processor.py\n+++ b/components/src/dynamo/frontend/sglang_processor.py\n@@ -25,7 +25,7 @@\n from dynamo.common.utils.input_params import resolve_thinking_token_budget\n from dynamo.frontend.frontend_args import FrontendConfig\n from dynamo.llm import ModelCardInstanceId, PythonAsyncEngine, RoutedEngine\n-from dynamo.llm.exceptions import InvalidArgument, Unknown\n+from dynamo.llm.exceptions import InvalidArgument, Unknown, WorkerUnavailable\n \n from .sglang_prepost import (\n ReasoningParser,\n@@ -1074,7 +1074,7 @@ def finalize_terminal(terminal: dict[str, Any]) -> dict[str, Any]:\n else:\n if pending_terminal is not None:\n yield finalize_terminal(pending_terminal)\n- except (InvalidArgument, Unknown):\n+ except (InvalidArgument, Unknown, WorkerUnavailable):\n raise\n except Exception as e:\n logger.exception(\"Error generating response for request %s\", request_id)\ndiff --git a/components/src/dynamo/frontend/vllm_processor.py b/components/src/dynamo/frontend/vllm_processor.py\nindex 5b59b4e92a38..554c53d4f4f5 100644\n--- a/components/src/dynamo/frontend/vllm_processor.py\n+++ b/components/src/dynamo/frontend/vllm_processor.py\n@@ -41,7 +41,7 @@\n from dynamo.common.utils.input_params import resolve_thinking_token_budget\n from dynamo.frontend.frontend_args import FrontendConfig\n from dynamo.llm import ModelCardInstanceId, PythonAsyncEngine, RoutedEngine\n-from dynamo.llm.exceptions import HttpError\n+from dynamo.llm.exceptions import HttpError, WorkerUnavailable\n from dynamo.vllm.errors import vllm_client_error_to_http_error\n \n from .prepost import StreamingPostProcessor, preprocess_chat_request\n@@ -1523,6 +1523,11 @@ def attach_usage(output: dict[str, Any], *, finished: bool) -> None:\n # translates them at Dynamo's HTTP boundary. The generic handler\n # below is reserved for genuine internal failures.\n raise\n+ except WorkerUnavailable:\n+ # The routed pipeline rejected the request as retryable (for example,\n+ # prefill routing is still activating). An error envelope would turn\n+ # that 503 into a 500; let the binding restore the class instead.\n+ raise\n except Exception as e:\n backend_error = backend_invalid_argument_to_http_error(e)\n if backend_error is not None:\ndiff --git a/lib/bindings/python/rust/engine.rs b/lib/bindings/python/rust/engine.rs\nindex 2e3f239604a2..903b0ed7a242 100644\n--- a/lib/bindings/python/rust/engine.rs\n+++ b/lib/bindings/python/rust/engine.rs\n@@ -30,7 +30,9 @@ use crate::PyAsyncRequestStream;\n use dynamo_runtime::pipeline::ManyIn;\n \n use super::context::{Context, callable_accepts_kwarg};\n-use super::errors::{http_like_error_to_dynamo, py_exception_to_backend_error};\n+use super::errors::{\n+ http_like_error_to_dynamo, py_exception_to_backend_error, worker_unavailable_to_dynamo,\n+};\n use crate::python_payload::{PythonPayload, PythonResponseItem};\n \n /// Add bindings from this crate to the provided module\n@@ -382,6 +384,12 @@ pub(crate) fn map_python_exception(error: PyErr) -> DynamoError {\n Python::with_gil(|py| {\n error.display(py);\n \n+ // Checked before the backend mapping, whose `DynamoException` fallback\n+ // would otherwise classify it as `Unknown`.\n+ if let Some(error) = worker_unavailable_to_dynamo(py, &error) {\n+ return error;\n+ }\n+\n if let Some((backend_err, message)) = py_exception_to_backend_error(py, &error) {\n let mut builder = DynamoError::builder()\n .error_type(ErrorType::Backend(backend_err))\ndiff --git a/lib/bindings/python/rust/errors.rs b/lib/bindings/python/rust/errors.rs\nindex bef7c47a617f..aee0148a71ea 100644\n--- a/lib/bindings/python/rust/errors.rs\n+++ b/lib/bindings/python/rust/errors.rs\n@@ -36,6 +36,55 @@ pub fn queue_rejection_to_pyerr(rejection: dynamo_kv_router::scheduling::QueueRe\n error\n }\n \n+// Raised by `RoutedEngine.generate` when the routed pipeline reports that no\n+// worker on the request's route can serve it yet (for example, prefill routing\n+// is still activating). Python chat processors re-raise it unchanged, and\n+// `map_python_exception` restores `ErrorClass::WorkerUnavailable` so the client\n+// gets the intended HTTP 503 instead of a generic 500.\n+pyo3::create_exception!(dynamo._core, WorkerUnavailable, DynamoException);\n+\n+/// Convert a routed-pipeline error to a Python exception, keeping the\n+/// `WorkerUnavailable` class that the generic [`crate::to_pyerr`] would drop.\n+pub fn routed_error_to_pyerr(err: anyhow::Error) -> PyErr {\n+ if is_worker_unavailable(err.as_ref()) {\n+ return WorkerUnavailable::new_err(err.to_string());\n+ }\n+ crate::to_pyerr(err)\n+}\n+\n+fn is_worker_unavailable(error: &(dyn std::error::Error + 'static)) -> bool {\n+ let mut current = Some(error);\n+ while let Some(cause) = current {\n+ // `class()` normalizes `WorkerUnavailable` to `Unavailable`; the raw\n+ // error type keeps the migratable worker-scoped distinction.\n+ if cause\n+ .downcast_ref::()\n+ .is_some_and(|error| error.error_type() == ErrorClass::WorkerUnavailable)\n+ {\n+ return true;\n+ }\n+ current = cause.source();\n+ }\n+ false\n+}\n+\n+pub(crate) fn worker_unavailable_to_dynamo(py: Python<'_>, err: &PyErr) -> Option {\n+ if !err.is_instance_of::(py) {\n+ return None;\n+ }\n+ let message = err\n+ .value(py)\n+ .str()\n+ .map(|s| s.to_string_lossy().into_owned())\n+ .unwrap_or_default();\n+ Some(\n+ DynamoError::builder()\n+ .class(ErrorClass::WorkerUnavailable)\n+ .message(message)\n+ .build(),\n+ )\n+}\n+\n // Raised by the in-process `SelectionService` bindings for selector failures\n // that are not malformed input. Instances carry `kind` (a stable,\n // machine-readable category) and `status_code` (an HTTP-style status) so\n@@ -105,6 +154,7 @@ macro_rules! define_dynamo_exceptions {\n \"SelectionServiceError\",\n m.py().get_type::(),\n )?;\n+ m.add(\"WorkerUnavailable\", m.py().get_type::())?;\n $(\n m.add(stringify!($name), m.py().get_type::<$name>())?;\n )*\n@@ -246,6 +296,26 @@ mod tests {\n message: String,\n }\n \n+ #[test]\n+ fn worker_unavailable_survives_class_normalization_and_context() {\n+ let rejection = DynamoError::builder()\n+ .class(ErrorClass::WorkerUnavailable)\n+ .message(\"prefill routing is still activating\")\n+ .build();\n+ // `class()` reports the normalized `Unavailable`; detection must not rely on it.\n+ assert_eq!(rejection.class(), ErrorClass::Unavailable);\n+ assert!(is_worker_unavailable(&rejection));\n+\n+ let wrapped = anyhow::Error::from(rejection).context(\"routed pipeline failed\");\n+ assert!(is_worker_unavailable(wrapped.as_ref()));\n+\n+ let pool_unavailable = DynamoError::builder()\n+ .class(ErrorClass::Unavailable)\n+ .message(\"no workers\")\n+ .build();\n+ assert!(!is_worker_unavailable(&pool_unavailable));\n+ }\n+\n #[test]\n fn invalid_request_conversion_uses_only_public_message() {\n let error = DynamoError::builder()\ndiff --git a/lib/bindings/python/rust/llm/routed_engine.rs b/lib/bindings/python/rust/llm/routed_engine.rs\nindex 47e228792ece..f10ec6a654b5 100644\n--- a/lib/bindings/python/rust/llm/routed_engine.rs\n+++ b/lib/bindings/python/rust/llm/routed_engine.rs\n@@ -13,6 +13,7 @@ use dynamo_runtime::logging::{DistributedTraceContext, otel_parent_context_from_\n use dynamo_runtime::pipeline::{AsyncEngineContextProvider, SingleIn};\n use dynamo_runtime::protocols::annotated::Annotated as RsAnnotated;\n \n+use crate::errors::routed_error_to_pyerr;\n use crate::to_pyerr;\n \n #[pyclass]\n@@ -68,7 +69,10 @@ impl RoutedEngine {\n crate::future_into_py(\n py,\n async move {\n- let mut stream = inner.generate(request_context).await.map_err(to_pyerr)?;\n+ let mut stream = inner\n+ .generate(request_context)\n+ .await\n+ .map_err(routed_error_to_pyerr)?;\n let task_context = stream.context();\n let (tx, rx) = tokio::sync::mpsc::channel::>(32);\n \ndiff --git a/lib/bindings/python/src/dynamo/_core.pyi b/lib/bindings/python/src/dynamo/_core.pyi\nindex 0dd211ef4acf..d7581bae659e 100644\n--- a/lib/bindings/python/src/dynamo/_core.pyi\n+++ b/lib/bindings/python/src/dynamo/_core.pyi\n@@ -3236,6 +3236,15 @@ class WorkerOverloaded(DynamoException):\n \n ...\n \n+class WorkerUnavailable(DynamoException):\n+ \"\"\"No worker on the request's route can serve it yet (HTTP 503).\n+\n+ Raised by `RoutedEngine.generate`, for example while prefill routing is\n+ still activating. Re-raise it unchanged to keep the 503.\n+ \"\"\"\n+\n+ ...\n+\n class SelectionServiceError(DynamoException):\n \"\"\"\n Raised by `SelectionService` for selector failures that are not malformed\ndiff --git a/lib/bindings/python/src/dynamo/llm/exceptions.py b/lib/bindings/python/src/dynamo/llm/exceptions.py\nindex 061e9d36b52d..12c65c7cdb95 100644\n--- a/lib/bindings/python/src/dynamo/llm/exceptions.py\n+++ b/lib/bindings/python/src/dynamo/llm/exceptions.py\n@@ -17,6 +17,7 @@\n from dynamo._core import StreamIncomplete as StreamIncomplete\n from dynamo._core import Unknown as Unknown\n from dynamo._core import WorkerOverloaded as WorkerOverloaded\n+from dynamo._core import WorkerUnavailable as WorkerUnavailable\n \n logger = logging.getLogger(__name__)\n \ndiff --git a/lib/llm/src/kv_router/prefill_router/activation.rs b/lib/llm/src/kv_router/prefill_router/activation.rs\nindex a30e16ceef83..6af2abac4633 100644\n--- a/lib/llm/src/kv_router/prefill_router/activation.rs\n+++ b/lib/llm/src/kv_router/prefill_router/activation.rs\n@@ -20,6 +20,15 @@ use dynamo_runtime::{\n };\n \n use super::{PrefillBinding, PrefillBuildContext, PrefillLifecycleState, PrefillRouter};\n+\n+/// Routing state of a prefill hop, resolved atomically by [`PrefillRouter::activation_snapshot`].\n+pub(super) enum ActivationSnapshot {\n+ Active(Arc),\n+ /// A target is set but its binding is not published yet: fail closed.\n+ Pending,\n+ /// No prefill target (never set, or cleared): passthrough to decode is safe.\n+ Untargeted,\n+}\n use crate::{\n discovery::{LoadThresholdHandle, ModelManager, WorkerSetTarget},\n kv_router::{RouterLoadSource, RoutingHost, RoutingLoadContext, SelectionPolicySource},\n@@ -632,6 +641,28 @@ impl PrefillRouter {\n PrefillLifecycleState::from_atomic(self.lifecycle.load(Ordering::Acquire))\n }\n \n+ /// One consistent view of target, lifecycle and binding, read under the\n+ /// target lock. Both publishers (`set_target` and the build loop) store the\n+ /// binding and lifecycle while holding that lock, so a routing decision made\n+ /// from this snapshot cannot interleave with a Pending->Active transition the\n+ /// way two separate lock-free reads can.\n+ pub(super) fn activation_snapshot(&self) -> ActivationSnapshot {\n+ let target = self.target.lock();\n+ match self.lifecycle_state() {\n+ PrefillLifecycleState::Active => match self.binding.load_full() {\n+ Some(binding) => ActivationSnapshot::Active(binding),\n+ // The binding is stored before `Active` under this lock, so this\n+ // arm is not expected; resolve by target rather than panicking.\n+ None if target.is_some() => ActivationSnapshot::Pending,\n+ None => ActivationSnapshot::Untargeted,\n+ },\n+ PrefillLifecycleState::Pending if target.is_some() => ActivationSnapshot::Pending,\n+ PrefillLifecycleState::Pending | PrefillLifecycleState::Unavailable => {\n+ ActivationSnapshot::Untargeted\n+ }\n+ }\n+ }\n+\n #[cfg(test)]\n pub(crate) fn target_endpoint_id(&self) -> Option {\n self.target_tx\n@@ -654,6 +685,7 @@ mod tests {\n DistributedRuntime, Runtime,\n discovery::{DiscoverySpec, EventTransportKind},\n distributed::{DiscoveryBackend, DistributedConfig, RequestPlaneMode},\n+ error::{ErrorType, match_error_chain},\n pipeline::{\n AsyncEngine, AsyncEngineContextProvider, ManyOut, Operator, ResponseStream, SingleIn,\n network::Ingress,\n@@ -762,6 +794,37 @@ mod tests {\n worker\n }\n \n+ /// Worker 99 is the downstream aggregated path, which must never be reached.\n+ async fn await_activation(router: &PrefillRouter, expected_prefill_worker: u32) {\n+ tokio::time::timeout(Duration::from_secs(5), async {\n+ loop {\n+ match router\n+ .generate(SingleIn::new(request()), Arc::new(PrefillWorker(99)))\n+ .await\n+ {\n+ Err(error) => {\n+ assert!(\n+ match_error_chain(error.as_ref(), &[ErrorType::WorkerUnavailable], &[]),\n+ \"activation window must surface WorkerUnavailable, got: {error}\"\n+ );\n+ tokio::task::yield_now().await;\n+ }\n+ Ok(mut response) => {\n+ let worker = response.next().await.unwrap().data.unwrap().token_ids[0];\n+ while response.next().await.is_some() {}\n+ assert_eq!(\n+ worker, expected_prefill_worker,\n+ \"activated router must route through prefill\"\n+ );\n+ break;\n+ }\n+ }\n+ }\n+ })\n+ .await\n+ .expect(\"committed prefill target must activate\");\n+ }\n+\n #[tokio::test]\n async fn committed_prefill_uses_selected_card_and_admission_across_endpoint_reuse() {\n // The request-plane server is process-global, but other Tokio tests\n@@ -903,18 +966,7 @@ mod tests {\n );\n let (admissions, admitted_ids) = watch::channel(vec![ids[0]]);\n router.set_target(Some(target(1, 64, admitted_ids)));\n- tokio::time::timeout(Duration::from_secs(5), async {\n- loop {\n- let worker = prefilled_worker(&router).await;\n- if worker != 99 {\n- assert_eq!(worker, 0);\n- break;\n- }\n- tokio::task::yield_now().await;\n- }\n- })\n- .await\n- .expect(\"committed prefill target must activate\");\n+ await_activation(&router, 0).await;\n assert_eq!(\n router.available_worker_ids_for(&group_id, &endpoint.id()),\n Some(HashSet::from([ids[0]]))\n@@ -1021,18 +1073,7 @@ mod tests {\n .available_worker_ids_for(\"other-group\", &endpoint.id())\n .is_none()\n );\n- tokio::time::timeout(Duration::from_secs(5), async {\n- loop {\n- let worker = prefilled_worker(&router).await;\n- if worker != 99 {\n- assert_eq!(worker, 2);\n- break;\n- }\n- tokio::task::yield_now().await;\n- }\n- })\n- .await\n- .expect(\"same-endpoint successor must activate\");\n+ await_activation(&router, 2).await;\n assert_eq!(\n router.available_worker_ids_for(&group_id, &endpoint.id()),\n Some(HashSet::from([ids[2]]))\ndiff --git a/lib/llm/src/kv_router/prefill_router/mod.rs b/lib/llm/src/kv_router/prefill_router/mod.rs\nindex ac6d889a232a..1c0818c99fc8 100644\n--- a/lib/llm/src/kv_router/prefill_router/mod.rs\n+++ b/lib/llm/src/kv_router/prefill_router/mod.rs\n@@ -16,7 +16,7 @@ use dynamo_kv_router::{\n config::RouterConfigOverride, protocols::RoutingConstraints,\n };\n use dynamo_runtime::{\n- error::{ErrorType, match_error_chain},\n+ error::{DynamoError, ErrorClass, ErrorType, match_error_chain},\n pipeline::{\n AsyncEngineContextProvider, Context, ManyOut, Operator, ResponseStream, RouterMode,\n ServerStreamingEngine, SingleIn, async_trait, propagate_first_response_guard,\n@@ -45,6 +45,7 @@ mod admission;\n mod conditional_bypass;\n mod handoff;\n mod query;\n+use activation::ActivationSnapshot;\n use handoff::PrefillTask;\n pub use query::PrefillReservation;\n \n@@ -151,6 +152,20 @@ fn into_decode_request(\n req\n }\n \n+/// The request reached a decode WorkerSet whose prefill target is known but\n+/// whose prefill binding is still being built. `WorkerUnavailable` is the\n+/// migratable sibling of `Unavailable`: it maps to HTTP 503 and lets the retry\n+/// layer re-dispatch rather than treating the whole model as down.\n+fn prefill_activation_pending_error(model_name: &str, namespace: &str) -> anyhow::Error {\n+ DynamoError::builder()\n+ .class(ErrorClass::WorkerUnavailable)\n+ .message(format!(\n+ \"prefill routing for model {model_name} in namespace {namespace} is still activating\"\n+ ))\n+ .build()\n+ .into()\n+}\n+\n fn extract_bootstrap_info(params: &serde_json::Value) -> Option {\n let bootstrap_host = params.get(\"bootstrap_host\")?.as_str()?.to_string();\n let bootstrap_port = u16::try_from(params.get(\"bootstrap_port\")?.as_u64()?).ok()?;\n@@ -365,16 +380,49 @@ impl\n // Save original max_tokens for decode\n let original_max_tokens = req.stop_conditions.max_tokens;\n \n- // If the prefill router is not activated (no prefill workers discovered) or has been\n- // deactivated (all prefill workers died), route directly to the backend. Model admission\n- // remains gated by the registered worker topology before the request reaches this stage.\n+ // Query-only requests are owned by the decode RoutingHost. In particular,\n+ // do not turn an advisory worker lookup into conditional local execution.\n+ let query_only = req.get_annotation_value(\"query_instance_id\").is_some();\n+\n+ // Hot path: an active router with a published binding never takes the\n+ // target lock. Anything else is resolved from one locked snapshot.\n if self.lifecycle_state() != PrefillLifecycleState::Active {\n- return next.generate(context.map(|_| req)).await;\n+ match self.activation_snapshot() {\n+ // Activation completed between the lock-free read and the snapshot:\n+ // continue through the prefill path below.\n+ ActivationSnapshot::Active(_) => {}\n+ // Model admission gates on the registered worker topology, which counts\n+ // a prefill worker as live the moment it registers. This router only\n+ // learns the matching target then, and its binding is built\n+ // asynchronously. Until that build completes the namespace is already\n+ // selectable, so forwarding the request would hand a decode-only worker\n+ // an aggregated request it cannot run (`bootstrap_info is required for\n+ // disaggregated decode`). Fail closed with a migratable error instead:\n+ // the retry layer re-dispatches and the client sees a retryable 503\n+ // rather than a backend failure.\n+ ActivationSnapshot::Pending if !query_only => {\n+ tracing::debug!(\n+ request_id = %request_id,\n+ model_name = %self.model_name,\n+ namespace = %self.namespace,\n+ \"Prefill router target is still activating; rejecting request instead of \\\n+ forwarding it to decode without a prefill hop\"\n+ );\n+ return Err(prefill_activation_pending_error(\n+ &self.model_name,\n+ &self.namespace,\n+ ));\n+ }\n+ // Query-only previews never reach the engine. Otherwise no prefill\n+ // target was ever set (aggregated-capable deployment) or every prefill\n+ // worker left (target cleared): route directly to the backend.\n+ ActivationSnapshot::Pending | ActivationSnapshot::Untargeted => {\n+ return next.generate(context.map(|_| req)).await;\n+ }\n+ }\n }\n \n- // Query-only requests are owned by the decode RoutingHost. In particular,\n- // do not turn an advisory worker lookup into conditional local execution.\n- if req.get_annotation_value(\"query_instance_id\").is_some() {\n+ if query_only {\n return next.generate(context.map(|_| req)).await;\n }\n \n@@ -476,8 +524,25 @@ impl\n session_affinity.as_ref().clone(),\n );\n }\n- let Some(binding) = self.binding.load_full() else {\n- return next.generate(context.map(|_| req)).await;\n+ let binding = match self.binding.load_full() {\n+ Some(binding) => binding,\n+ // The target was replaced after the gate above (a WorkerSet succession\n+ // while this request awaited the phase barrier): `set_target` cleared the\n+ // binding. Resolve from one locked snapshot: the successor may already\n+ // have activated, in which case serve through it; if it is still\n+ // building, fail closed rather than forward to decode without a prefill hop.\n+ None => match self.activation_snapshot() {\n+ ActivationSnapshot::Active(binding) => binding,\n+ ActivationSnapshot::Pending => {\n+ return Err(prefill_activation_pending_error(\n+ &self.model_name,\n+ &self.namespace,\n+ ));\n+ }\n+ ActivationSnapshot::Untargeted => {\n+ return next.generate(context.map(|_| req)).await;\n+ }\n+ },\n };\n \n // Keyed on the prefill mode, not the decode set's, and checked after\n@@ -864,6 +929,199 @@ mod tests {\n .unwrap()\n }\n \n+ #[derive(Default)]\n+ struct CountingDecodeHost {\n+ requests: AtomicUsize,\n+ }\n+\n+ #[async_trait]\n+ impl AsyncEngine, ManyOut>, Error>\n+ for CountingDecodeHost\n+ {\n+ async fn generate(\n+ &self,\n+ request: SingleIn,\n+ ) -> Result>, Error> {\n+ self.requests.fetch_add(1, Ordering::Relaxed);\n+ Ok(ResponseStream::new(\n+ Box::pin(stream::empty()),\n+ request.context(),\n+ ))\n+ }\n+ }\n+\n+ fn inference_request() -> PreprocessedRequest {\n+ PreprocessedRequest::builder()\n+ .model(\"test\".to_string())\n+ .token_ids(vec![1, 2, 3])\n+ .stop_conditions(Default::default())\n+ .sampling_options(Default::default())\n+ .output_options(Default::default())\n+ .build()\n+ .unwrap()\n+ }\n+\n+ /// A decode WorkerSet's router as the watcher creates it: enabled, no\n+ /// target yet, lifecycle `Pending`, no conditional disaggregation.\n+ fn fresh_decode_router() -> Arc {\n+ let (_activation_tx, activation_rx) = oneshot::channel();\n+ PrefillRouter::new(\n+ activation_rx,\n+ Arc::new(ModelManager::new()),\n+ RouterMode::RoundRobin,\n+ 16,\n+ None,\n+ None,\n+ None,\n+ SessionAffinityMode::Hard,\n+ \"model\".to_string(),\n+ \"namespace\".to_string(),\n+ crate::discovery::LoadThresholdHandle::new(Default::default()),\n+ CancellationToken::new(),\n+ )\n+ }\n+\n+ /// Set the pending state directly so the test does not need a live endpoint.\n+ fn mark_target_pending(router: &PrefillRouter) {\n+ *router.target.lock() = Some(WorkerSetTargetId::Committed {\n+ group: \"namespace/prefill/generate\".to_string(),\n+ generation: 1,\n+ });\n+ router.binding.store(None);\n+ router.lifecycle.store(\n+ PrefillLifecycleState::Pending as u8,\n+ std::sync::atomic::Ordering::Release,\n+ );\n+ }\n+\n+ // -- Activation-window behavior (worker rollout race) --\n+ //\n+ // Admission counts a prefill worker as live once it registers, but this\n+ // router's binding is built asynchronously after `set_target`. A decode-only\n+ // worker cannot run the aggregated request a passthrough would send it.\n+\n+ #[tokio::test]\n+ async fn pending_target_fails_closed_instead_of_forwarding_to_decode() {\n+ let router = fresh_decode_router();\n+ mark_target_pending(&router);\n+ assert!(matches!(\n+ router.activation_snapshot(),\n+ ActivationSnapshot::Pending\n+ ));\n+\n+ let host = Arc::new(CountingDecodeHost::default());\n+ let error = router\n+ .generate(SingleIn::new(inference_request()), host.clone())\n+ .await\n+ .expect_err(\"a pending prefill target must not pass through to decode\");\n+\n+ assert!(\n+ match_error_chain(error.as_ref(), &[ErrorType::WorkerUnavailable], &[]),\n+ \"expected WorkerUnavailable so the error maps to a retryable 503, got: {error}\"\n+ );\n+ assert!(\n+ crate::migration::is_migratable(error.as_ref()),\n+ \"the retry layer must be able to re-dispatch this request\"\n+ );\n+ assert_eq!(\n+ host.requests.load(Ordering::Relaxed),\n+ 0,\n+ \"decode must not see a request without its prefill hop\"\n+ );\n+ }\n+\n+ #[tokio::test]\n+ async fn untargeted_router_still_passes_through() {\n+ let router = fresh_decode_router();\n+ assert!(matches!(\n+ router.activation_snapshot(),\n+ ActivationSnapshot::Untargeted\n+ ));\n+\n+ let host = Arc::new(CountingDecodeHost::default());\n+ router\n+ .generate(SingleIn::new(inference_request()), host.clone())\n+ .await\n+ .expect(\"no target means plain passthrough\");\n+ assert_eq!(host.requests.load(Ordering::Relaxed), 1);\n+ }\n+\n+ #[tokio::test]\n+ async fn cleared_target_still_passes_through() {\n+ let router = fresh_decode_router();\n+ mark_target_pending(&router);\n+ router.set_target(None);\n+ assert_eq!(router.lifecycle_state(), PrefillLifecycleState::Unavailable);\n+ assert!(matches!(\n+ router.activation_snapshot(),\n+ ActivationSnapshot::Untargeted\n+ ));\n+\n+ let host = Arc::new(CountingDecodeHost::default());\n+ router\n+ .generate(SingleIn::new(inference_request()), host.clone())\n+ .await\n+ .expect(\"a deactivated router passes through\");\n+ assert_eq!(host.requests.load(Ordering::Relaxed), 1);\n+ }\n+\n+ #[tokio::test]\n+ async fn pending_target_still_serves_query_only_requests() {\n+ // Routing previews never reach the engine, so they are not at risk and\n+ // must keep working while the prefill binding is being built.\n+ let router = fresh_decode_router();\n+ mark_target_pending(&router);\n+\n+ let host = Arc::new(QueryOnlyDecodeHost::default());\n+ router\n+ .generate(SingleIn::new(query_only_request()), host.clone())\n+ .await\n+ .expect(\"query-only requests bypass the activation gate\");\n+ assert_eq!(host.requests.load(Ordering::Relaxed), 1);\n+ }\n+\n+ #[tokio::test(start_paused = true)]\n+ async fn target_replaced_mid_flight_fails_closed_at_binding_load() {\n+ // The lifecycle gate runs once at the top of `generate`; the binding is\n+ // loaded only after the prefill phase barrier. A WorkerSet succession in\n+ // between clears the binding and moves the router back to `Pending`.\n+ // Hold the phase barrier so the request is parked in that gap, replace\n+ // the target, then release it: the request must fail closed rather than\n+ // reach the missing-binding passthrough.\n+ let router = fresh_decode_router();\n+ router.lifecycle.store(\n+ PrefillLifecycleState::Active as u8,\n+ std::sync::atomic::Ordering::Release,\n+ );\n+ let tracker = Arc::new(RequestTracker::new());\n+ let barrier = tracker.set_phase(RequestPhase::Prefill).await;\n+ let mut request = inference_request();\n+ request.tracker = Some(tracker.clone());\n+\n+ let host = Arc::new(CountingDecodeHost::default());\n+ let in_flight = tokio::spawn({\n+ let router = router.clone();\n+ let host = host.clone();\n+ async move { router.generate(SingleIn::new(request), host).await }\n+ });\n+ // With paused time this sleep completes only once every other task is\n+ // idle, i.e. once the request has passed the gate and parked on the barrier.\n+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;\n+\n+ mark_target_pending(&router);\n+ drop(barrier);\n+\n+ let error = match in_flight.await.unwrap() {\n+ Ok(_) => panic!(\"a replaced target must not pass through to decode\"),\n+ Err(error) => error,\n+ };\n+ assert!(\n+ match_error_chain(error.as_ref(), &[ErrorType::WorkerUnavailable], &[]),\n+ \"expected WorkerUnavailable after a mid-flight target replacement, got: {error}\"\n+ );\n+ assert_eq!(host.requests.load(Ordering::Relaxed), 0);\n+ }\n+\n #[test]\n fn client_cancellation_does_not_cancel_prefill_context() {\n for kill in [false, true] {\ndiff --git a/components/src/dynamo/frontend/tests/test_sglang_processor_metrics_unit.py b/components/src/dynamo/frontend/tests/test_sglang_processor_metrics_unit.py\nindex f22a40b3663d..6c16e3f921fd 100644\n--- a/components/src/dynamo/frontend/tests/test_sglang_processor_metrics_unit.py\n+++ b/components/src/dynamo/frontend/tests/test_sglang_processor_metrics_unit.py\n@@ -203,6 +203,7 @@ def _load_processor_module(module_stubs):\n HttpError=type(\"HttpError\", (Exception,), {}),\n InvalidArgument=type(\"InvalidArgument\", (Exception,), {}),\n Unknown=type(\"Unknown\", (Exception,), {}),\n+ WorkerUnavailable=type(\"WorkerUnavailable\", (Exception,), {}),\n )\n remove_module(\"dynamo.frontend.sglang_processor\")\n return importlib.import_module(\"dynamo.frontend.sglang_processor\")\ndiff --git a/components/src/dynamo/frontend/tests/test_sglang_processor_unit.py b/components/src/dynamo/frontend/tests/test_sglang_processor_unit.py\nindex 8e52b0d68450..f8902c681a93 100644\n--- a/components/src/dynamo/frontend/tests/test_sglang_processor_unit.py\n+++ b/components/src/dynamo/frontend/tests/test_sglang_processor_unit.py\n@@ -81,7 +81,7 @@\n random_call_id,\n random_uuid,\n )\n-from dynamo.llm.exceptions import InvalidArgument\n+from dynamo.llm.exceptions import InvalidArgument, Unknown, WorkerUnavailable\n from dynamo.sglang.thinking_budget import apply_thinking_budget\n \n # Needs sglang packages (gpu_1 container), but does not allocate GPU VRAM.\n@@ -1153,6 +1153,42 @@ def _qwen_guided_request_without_separation(tool_choice):\n return request\n \n \n+@pytest.mark.parametrize(\n+ (\"routed_error\", \"expected\"),\n+ [\n+ (WorkerUnavailable(\"prefill routing is still activating\"), WorkerUnavailable),\n+ (RuntimeError(\"worker crashed\"), Unknown),\n+ ],\n+)\n+def test_routed_engine_rejection_keeps_worker_unavailable(\n+ tokenizer, routed_error, expected\n+):\n+ class RejectingRoutedEngine(FakeRoutedEngine):\n+ async def generate(self, preprocessed, **kwargs):\n+ raise routed_error\n+\n+ processor = SglangProcessor(\n+ tokenizer=tokenizer,\n+ routed_engine=RejectingRoutedEngine(),\n+ tool_call_parser_name=\"qwen25\",\n+ reasoning_parser_name=\"qwen3\",\n+ eos_token_ids=[tokenizer.eos_token_id],\n+ )\n+ request = {\n+ \"model\": MODEL,\n+ \"messages\": [{\"role\": \"user\", \"content\": \"Say hello.\"}],\n+ \"max_tokens\": 4,\n+ }\n+\n+ async def collect():\n+ return [item async for item in processor.generator(request)]\n+\n+ with pytest.raises(expected) as caught:\n+ asyncio.run(collect())\n+ if expected is WorkerUnavailable:\n+ assert caught.value is routed_error\n+\n+\n @pytest.mark.parametrize(\n \"tool_choice\",\n [\ndiff --git a/components/src/dynamo/frontend/tests/test_vllm_processor_unit.py b/components/src/dynamo/frontend/tests/test_vllm_processor_unit.py\nindex 4912da4a7b18..672bfa381d4d 100644\n--- a/components/src/dynamo/frontend/tests/test_vllm_processor_unit.py\n+++ b/components/src/dynamo/frontend/tests/test_vllm_processor_unit.py\n@@ -34,7 +34,7 @@\n _prepare_request,\n build_tool_call_guided_decoding,\n )\n-from dynamo.llm.exceptions import HttpError, InvalidArgument\n+from dynamo.llm.exceptions import HttpError, InvalidArgument, WorkerUnavailable\n \n # NOTE: dynamo.frontend.vllm_processor is imported lazily inside the tests that\n # need it (and via the vllm_processor_module fixture). Importing it at module\n@@ -2061,6 +2061,22 @@ def process_outputs(self, outputs):\n ]\n assert routed_engine.yielded == 1\n \n+ @pytest.mark.asyncio\n+ async def test_worker_unavailable_is_raised_not_enveloped(\n+ self, vllm_processor_module\n+ ):\n+ rejection = WorkerUnavailable(\"prefill routing is still activating\")\n+\n+ class _RejectingRoutedEngine(_FakeRoutedEngine):\n+ async def generate(self, preprocessed, **kwargs):\n+ raise rejection\n+\n+ processor = _make_processor(vllm_processor_module, _RejectingRoutedEngine([]))\n+\n+ with pytest.raises(WorkerUnavailable) as caught:\n+ await _run_generate(processor, _base_preproc())\n+ assert caught.value is rejection\n+\n @pytest.mark.asyncio\n @pytest.mark.parametrize(\n \"request_options\", [{}, {\"logprobs\": False, \"top_logprobs\": 0}]\ndiff --git a/tests/router/test_router_e2e_with_mockers.py b/tests/router/test_router_e2e_with_mockers.py\nindex a8000aa0dd99..d76c49638e6c 100644\n--- a/tests/router/test_router_e2e_with_mockers.py\n+++ b/tests/router/test_router_e2e_with_mockers.py\n@@ -1072,7 +1072,7 @@ async def _wait_for_expected_disagg_worker_ids(\n ) as response:\n if response.status != 200:\n await response.read()\n- await asyncio.sleep(0.25)\n+ await asyncio.sleep(0.05)\n continue\n \n body = await response.text()\n@@ -1087,6 +1087,16 @@ async def _wait_for_expected_disagg_worker_ids(\n last_worker_ids = worker_ids\n prefill_worker_id = worker_ids[\"prefill_worker_id\"]\n decode_worker_id = worker_ids[\"decode_worker_id\"]\n+ # Both roles are registered, so a 200 that decode served as its own\n+ # prefill means the prefill hop was skipped (#16529); the activation\n+ # window must fail closed with a retryable 503 instead.\n+ assert decode_worker_id is None or prefill_worker_id not in (\n+ None,\n+ decode_worker_id,\n+ ), (\n+ \"Request was served by decode without a prefill hop after the \"\n+ f\"prefill worker registered; worker IDs: {worker_ids}\"\n+ )\n if (\n prefill_worker_id is not None\n and decode_worker_id is not None\n\n[1 documentation file diff(s) omitted]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(container): reuse upstream TRT-LLM NIXL stack\nLabels: documentation, size/L, fix, backend::trtllm, container, human-review\nFiles changed (11): container/context.yaml, container/deps/requirements.trtllm.txt, container/templates/aws.Dockerfile, container/templates/dev.Dockerfile, container/templates/trtllm_runtime.Dockerfile, container/templates/wheel_builder.Dockerfile, docs/fern/components/releases.data.ts, docs/fern/pages/developer-guide/knowledge-base/modular-components/backends/tensorrt-llm/overview.md, docs/fern/pages/reference/general/compatibility.mdx, docs/fern/pages/reference/general/releases-machine-readable.mdx, tests/dependencies/test_trtllm_nixl.py\n\n## Description (results removed)\n\n### Overview\n\nEvery process in the TRT-LLM image currently preloads NIXL, adding startup overhead even to commands such as `stat`. Reuse the native NIXL library and Python bindings from the pinned TRT-LLM image, remove the global NIXL preload, and retain the separate `libstdc++` preload. EFA images add the API-compatible LIBFABRIC 1.5.2 plugin, preserving main's CUDA-context and endpoint-synchronization fixes.\n\n### Key Changes\n\nCore container logic: **28 added / 27 removed lines**, excluding tests, documentation, comments, and whitespace; low complexity. The full diff covers 11 files, with no new package dependencies or Rust/backend changes.\n\n- [trtllm_runtime.Dockerfile](https://github.com/ai-dynamo/dynamo/blob/271f8995398be07dcd5f45b9cdd5d006ec5c3b9a/container/templates/trtllm_runtime.Dockerfile): register upstream Python bindings, remove the second NIXL installation and global preload, and validate imports/native loading during the build.\n- [aws.Dockerfile](https://github.com/ai-dynamo/dynamo/blob/271f8995398be07dcd5f45b9cdd5d006ec5c3b9a/container/templates/aws.Dockerfile): add the LIBFABRIC plugin and select its SDK directory. Accept equal package versions or the qualified native/plugin pair `1.5.0/1.5.2`, and verify plugin API 1 during the build.\n- [wheel_builder.Dockerfile](https://github.com/ai-dynamo/dynamo/blob/271f8995398be07dcd5f45b9cdd5d006ec5c3b9a/container/templates/wheel_builder.Dockerfile): skip the TRT-LLM NIXL build unless EFA needs the plugin; align development-image paths and documentation with the inherited stack.\n\n### Validation\n[results removed]\n## Summary by CodeRabbit\n\n* **Compatibility**\n * Updated the TensorRT-LLM NIXL version to 1.5.0.\n * AWS EFA containers now include the required LIBFABRIC plugin while using NIXL components from the upstream release image.\n* **Documentation**\n * Clarified NIXL requirements for TensorRT-LLM containers, including guidance for matching versions when changing the base image.\n\n## Diff\n\n```diff\ndiff --git a/container/context.yaml b/container/context.yaml\nindex 69cde1d087c4..263744931ae5 100644\n--- a/container/context.yaml\n+++ b/container/context.yaml\n@@ -187,6 +187,7 @@ trtllm:\n runtime_image_tag: 1.4.0rc2\n # Per-arch baseline stem (re-captured against tensorrt-llm/release, both arches).\n baseline_sbom: release@93a3eaf1\n+ # EFA adds the API-compatible LIBFABRIC plugin, including its CUDA-context fix.\n nixl_ref: v1.5.2\n enable_media_ffmpeg: \"false\"\n enable_gpu_memory_service: \"true\"\ndiff --git a/container/templates/aws.Dockerfile b/container/templates/aws.Dockerfile\nindex 7188654dc772..dbf25d154e0f 100644\n--- a/container/templates/aws.Dockerfile\n+++ b/container/templates/aws.Dockerfile\n@@ -39,26 +39,26 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \\\n ENV EFA_VERSION=\"${EFA_VERSION}\"\n \n {% if framework == \"trtllm\" %}\n-# After the upstream mesonpy refactor, libplugin_LIBFABRIC.so lands under the\n-# Dynamo venv while the rest of the NIXL plugin set (GDS/UCX/POSIX) remains at\n-# the canonical arch-specific location. Copy LIBFABRIC alongside the others so\n-# NIXL_PLUGIN_DIR resolves every backend from a single directory, and expose a\n-# stable arch-agnostic alias at /opt/nvidia/nvda_nixl/plugins.\n-#\n-# Also clear LD_PRELOAD (the upstream trtllm_runtime stage's ai-dynamo/nixl#1668\n-# workaround force-loads TRT-LLM's bundled NIXL 0.9.0; that conflicts with the\n-# Dynamo-built NIXL 0.10.1 plugins). LIBFABRIC goes through libfabric directly\n-# (not UCX), so it is unaffected by the UCX 1.20.0 hang that LD_PRELOAD works\n-# around — and LIBFABRIC is the recommended backend for EFA.\n-RUN --mount=from=wheel_builder,source=/opt/nvidia/nvda_nixl,target=/tmp/nvda_nixl \\\n- rm -rf /opt/nvidia/nvda_nixl && \\\n- cp -Pfr /tmp/nvda_nixl /opt/nvidia/nvda_nixl && \\\n- export LD_PRELOAD=/opt/nvidia/nvda_nixl/lib64/libnixl.so && \\\n- export NIXL_PLUGIN_DIR=/opt/nvidia/nvda_nixl/lib64/plugins && \\\n- ldconfig\n+# Upstream NIXL ships UCX/GDS but no LIBFABRIC backend. Add only the missing\n+# API-compatible plugin, preserving its native libraries and Python\n+# bindings. The EFA installer above supplies libfabric at runtime.\n+# The qualified 1.5.0/1.5.2 pair shares plugin API 1; 1.5.2 fixes CUDA VMM\n+# registration and EFA endpoint synchronization. New version pairs fail closed.\n+ARG NIXL_REF\n+ARG TARGETARCH\n+RUN --mount=from=wheel_builder,source=/opt/nvidia/nvda_nixl/lib64/plugins/libplugin_LIBFABRIC.so,target=/tmp/libplugin_LIBFABRIC.so \\\n+ python3 -c 'import importlib.metadata as m, os; versions = (m.version(\"nixl\"), os.environ[\"NIXL_REF\"].removeprefix(\"v\")); assert versions[0] == versions[1] or versions == (\"1.5.0\", \"1.5.2\"), f\"Unqualified upstream/plugin NIXL versions: {versions}\"' && \\\n+ ARCH_ALT=$([ \"${TARGETARCH}\" = \"amd64\" ] && echo \"x86_64\" || echo \"aarch64\") && \\\n+ plugin_dir=\"/opt/nvidia/nvda_nixl/lib/${ARCH_ALT}-linux-gnu/plugins\" && \\\n+ test -d \"${plugin_dir}\" && \\\n+ cp /tmp/libplugin_LIBFABRIC.so \"${plugin_dir}/\" && \\\n+ ln -sfnT \"${plugin_dir}\" /opt/nvidia/nvda_nixl/plugins && \\\n+ LD_LIBRARY_PATH=/usr/local/cuda/compat/lib.real:${LD_LIBRARY_PATH} \\\n+ python3 -c 'import ctypes, sys; plugin = ctypes.CDLL(sys.argv[1]); plugin.nixl_plugin_init.restype = ctypes.POINTER(ctypes.c_int); assert plugin.nixl_plugin_init().contents.value == 1, \"Unsupported NIXL plugin API\"' \"${plugin_dir}/libplugin_LIBFABRIC.so\"\n \n-ENV LD_PRELOAD=/opt/nvidia/nvda_nixl/lib64/libnixl.so\n-ENV NIXL_PLUGIN_DIR=/opt/nvidia/nvda_nixl/lib64/plugins\n+# TRT-LLM's native wrapper and Python bindings can load NIXL from different\n+# upstream directories. Select the SDK plugins explicitly in either load order.\n+ENV NIXL_PLUGIN_DIR=/opt/nvidia/nvda_nixl/plugins\n {% endif %}\n \n {% if target == \"runtime\" %}\ndiff --git a/container/templates/dev.Dockerfile b/container/templates/dev.Dockerfile\nindex 7ad5c58da972..2a74fe586495 100644\n--- a/container/templates/dev.Dockerfile\n+++ b/container/templates/dev.Dockerfile\n@@ -231,9 +231,13 @@ ENV NIXL_LIB_DIR=/opt/intel/intel_nixl/lib/x86_64-linux-gnu \\\n ENV NIXL_PREFIX=/opt/nvidia/nvda_nixl \\\n NIXL_LIB_DIR=/opt/nvidia/nvda_nixl/lib/x86_64-linux-gnu \\\n NIXL_PLUGIN_DIR=/opt/nvidia/nvda_nixl/lib/x86_64-linux-gnu/plugins\n-{% elif framework == \"trtllm\" or (framework == \"vllm\" and device == \"cuda\") %}\n-# trtllm and vLLM CUDA dev images inherit upstream containers that ship NIXL\n-# inside Python wheels. These env vars provide a stable prefix for source builds.\n+{% elif framework == \"trtllm\" %}\n+# Reuse TRT-LLM's native SDK for source builds as well as runtime transfers.\n+ENV NIXL_PREFIX=/opt/nvidia/nvda_nixl\n+# Runtime registers both architecture-specific native paths with ldconfig.\n+# Keep those inherited paths rather than selecting another Python wheel copy.\n+{% elif framework == \"vllm\" and device == \"cuda\" %}\n+# vLLM's NIXL wheel provides the stable prefix used for source builds.\n # For vLLM CUDA, /opt/dynamo/nixl is a symlink to the wheel's\n # .nixl_cu${CUDA_MAJOR}.mesonpy.libs directory, with headers added by the dev stage.\n ENV NIXL_PREFIX=/opt/dynamo/nixl \\\n@@ -266,8 +270,10 @@ ENV CUDA_HOME=/usr/local/cuda \\\n # Framework-specific paths are conditionally added in /etc/profile.d/50-framework-paths.sh\n ARG PYTHON_VERSION\n ENV LD_LIBRARY_PATH=\\\n+{% if framework != \"trtllm\" %}\n ${NIXL_LIB_DIR}:\\\n ${NIXL_PLUGIN_DIR}:\\\n+{% endif %}\n /usr/local/ucx/lib:\\\n /usr/local/ucx/lib/ucx:\\\n ${LD_LIBRARY_PATH}\ndiff --git a/container/templates/trtllm_runtime.Dockerfile b/container/templates/trtllm_runtime.Dockerfile\nindex 5abd859d3ef0..e4331c916ed2 100644\n--- a/container/templates/trtllm_runtime.Dockerfile\n+++ b/container/templates/trtllm_runtime.Dockerfile\n@@ -39,7 +39,6 @@ FROM ${RUNTIME_IMAGE}:${RUNTIME_IMAGE_TAG} AS pre_runtime\n \n ARG ENABLE_GPU_MEMORY_SERVICE\n ARG TARGETARCH\n-ARG NIXL_REF\n \n # Remove the upstream runtime's Git LFS package without pruning shared dependencies.\n RUN apt-get purge -y git-lfs && rm -rf /var/lib/apt/lists/*\n@@ -169,16 +168,15 @@ RUN --mount=type=bind,source=./container/deps/trtllm/_dynamo_pmix_hostname.py,ta\n mkdir -p /opt/dynamo && ln -sfn \"$t\" /opt/dynamo/mpi && \\\n echo \"MPI for ${TARGETARCH}: $(readlink -f /opt/dynamo/mpi)\"\n \n-# LD_PRELOAD pins TRT-LLM's bundled libnixl to dodge ai-dynamo/nixl#1668\n-# (nixl-cu13's UCX 1.20.0 hangs with two agents/host); drop it when fixed.\n-# NIXL_VERSION= clears the base image's stale value (see nixl-versions.txt).\n+# Reuse upstream's native NIXL and matching Python bindings. Only libstdc++\n+# needs preloading; loading NIXL into every process adds CI startup overhead.\n+# Clear upstream's stale NIXL_VERSION; record installed metadata below.\n ENV DYNAMO_HOME=/workspace \\\n HOME=/home/dynamo \\\n PATH=/opt/dynamo/mpi/bin:/usr/local/bin/etcd:${PATH} \\\n- LD_PRELOAD=/opt/dynamo/libstdc++.so.6:/usr/local/lib/python3.12/dist-packages/tensorrt_llm/libs/nixl/libnixl.so \\\n+ LD_PRELOAD=/opt/dynamo/libstdc++.so.6 \\\n LD_LIBRARY_PATH=/opt/dynamo/mpi/lib:${LD_LIBRARY_PATH} \\\n OPAL_PREFIX=/opt/dynamo/mpi \\\n- NIXL_PLUGIN_DIR=/usr/local/lib/python3.12/dist-packages/tensorrt_llm/libs/nixl/plugins \\\n NIXL_VERSION=\n \n WORKDIR /workspace\n@@ -199,8 +197,6 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \\\n librdmacm1 \\\n rdma-core \\\n libjemalloc2 && \\\n- test -f /usr/local/lib/python3.12/dist-packages/tensorrt_llm/libs/nixl/libnixl.so && \\\n- test -d \"${NIXL_PLUGIN_DIR}\" && \\\n ARCH_ALT=$([ \"${TARGETARCH}\" = \"amd64\" ] && echo \"x86_64\" || echo \"aarch64\") && \\\n printf '%s\\n' \\\n \"/usr/local/tensorrt/lib\" \\\n@@ -278,6 +274,15 @@ ENV GRPC_DEFAULT_SSL_ROOTS_FILE_PATH=/etc/ssl/certs/ca-certificates.crt\n COPY --from=dynamo_base_export / /\n ENV PATH=/opt/uv/bin:${PATH}\n \n+# Upstream ships matching NIXL bindings outside the standard Python search path.\n+# Register that directory for system Python and both Dynamo venvs instead of\n+# installing a second NIXL/UCX stack. Fail early if the upstream layout changes.\n+RUN test -d /opt/nvidia/nvda_nixl/lib/python3/dist-packages/nixl_cu13 && \\\n+ python3 -c 'import sysconfig; from pathlib import Path; Path(sysconfig.get_path(\"purelib\"), \"dynamo-nixl.pth\").write_text(\"/opt/nvidia/nvda_nixl/lib/python3/dist-packages\\n\")'\n+\n+RUN python3 -c 'import ctypes, importlib.metadata as m; import nixl._api, nixl._bindings; ctypes.CDLL(\"libnixl.so\"); print(\"nixl:\", m.version(\"nixl\")); print(\"bindings:\", nixl._bindings.__file__)' \\\n+ > /opt/dynamo/nixl-versions.txt && cat /opt/dynamo/nixl-versions.txt\n+\n # dynamo user (group 0 for OpenShift), clear upstream /workspace baggage\n # (otherwise pytest collects broken tutorial test files), and create the\n # Dynamo venv on non-dev. --system-site-packages keeps upstream's solve\n@@ -313,15 +318,6 @@ RUN --mount=type=cache,id=uv-root-{{ context.dynamo.uv_version }},target=/root/.\n uv pip install --no-deps /opt/dynamo/wheelhouse/ai_dynamo*any.whl && \\\n uv pip install --no-deps /opt/dynamo/wheelhouse/aisimulate*.whl && \\\n \\\n- # nixl/nixl-cu13 for `import nixl` (dynamo.nixl_connect); version from NIXL_REF.\n- # LD_PRELOAD swaps the runtime .so (nixl#1668).\n- echo \"${NIXL_REF}\" | grep -qE '^v[0-9]+\\.[0-9]+\\.[0-9]+$' || { echo \"NIXL_REF must be a vX.Y.Z release tag; got '${NIXL_REF}'\" >&2; exit 1; } && \\\n- _nixl_ver=\"${NIXL_REF#v}\" && \\\n- uv pip install --no-deps \"nixl==${_nixl_ver}\" \"nixl-cu13==${_nixl_ver}\" && \\\n- \\\n- # Record effective NIXL versions (pip vs loaded .so) for diagnosis.\n- { uv pip show nixl nixl-cu13 | grep -E '^(Name|Version)'; echo \"loaded_libnixl: ${LD_PRELOAD##*:}\"; } | tee /opt/dynamo/nixl-versions.txt && \\\n- \\\n # Third-party deps Dynamo wheels declare but upstream lacks. The\n # requirements.trtllm.txt file itself carries a `--no-binary imageio-ffmpeg`\n # directive that keeps the GPL-encumbered prebuilt ffmpeg off disk; IMAGEIO_FFMPEG_EXE\n@@ -775,10 +771,9 @@ ENV DYNAMO_HOME=/workspace \\\n HOME=/home/dynamo \\\n PATH=/opt/dynamo/mpi/bin:/opt/uv/bin:/usr/local/bin/etcd:${PATH} \\\n IMAGEIO_FFMPEG_EXE=/usr/local/bin/ffmpeg \\\n- LD_PRELOAD=/opt/dynamo/libstdc++.so.6:/usr/local/lib/python3.12/dist-packages/tensorrt_llm/libs/nixl/libnixl.so \\\n+ LD_PRELOAD=/opt/dynamo/libstdc++.so.6 \\\n LD_LIBRARY_PATH=/opt/dynamo/mpi/lib:${LD_LIBRARY_PATH} \\\n OPAL_PREFIX=/opt/dynamo/mpi \\\n- NIXL_PLUGIN_DIR=/usr/local/lib/python3.12/dist-packages/tensorrt_llm/libs/nixl/plugins \\\n NIXL_VERSION=\n {% else %}\n ENV DYNAMO_HOME=/workspace \\\n@@ -786,10 +781,9 @@ ENV DYNAMO_HOME=/workspace \\\n VIRTUAL_ENV=/opt/dynamo/venv \\\n PATH=/opt/dynamo/venv/bin:/opt/dynamo/mpi/bin:/opt/uv/bin:/usr/local/bin/etcd:${PATH} \\\n IMAGEIO_FFMPEG_EXE=/usr/local/bin/ffmpeg \\\n- LD_PRELOAD=/opt/dynamo/libstdc++.so.6:/usr/local/lib/python3.12/dist-packages/tensorrt_llm/libs/nixl/libnixl.so \\\n+ LD_PRELOAD=/opt/dynamo/libstdc++.so.6 \\\n LD_LIBRARY_PATH=/opt/dynamo/mpi/lib:${LD_LIBRARY_PATH} \\\n OPAL_PREFIX=/opt/dynamo/mpi \\\n- NIXL_PLUGIN_DIR=/usr/local/lib/python3.12/dist-packages/tensorrt_llm/libs/nixl/plugins \\\n NIXL_VERSION=\n {% endif %}\n \ndiff --git a/container/templates/wheel_builder.Dockerfile b/container/templates/wheel_builder.Dockerfile\nindex eee58ef57543..57a2bf1b5e5c 100644\n--- a/container/templates/wheel_builder.Dockerfile\n+++ b/container/templates/wheel_builder.Dockerfile\n@@ -800,13 +800,14 @@ RUN --mount=type=cache,id=uv-root-{{ context.dynamo.uv_version }},target=/root/.\n ##################################\n ##### wheel_builder ##############\n ##################################\n-{% if (\"nixl_ref\" in context[framework] or device == \"xpu\") and target != \"frontend\" %}\n+{% if (\"nixl_ref\" in context[framework] or device == \"xpu\") and target != \"frontend\" and (framework != \"trtllm\" or make_efa) %}\n # Builds NIXL (native + Python wheel), then consolidates all wheels.\n # Runtime templates COPY from this stage.\n # Note: XPU triggers this path even when the framework section lacks nixl_ref,\n # because no upstream XPU runtime image ships pre-built NIXL.\n # Note: frontend is excluded — it installs NIXL from PyPI at NIXL_REF, so\n # nothing in that image consumes a from-source NIXL build.\n+# TRT-LLM reuses upstream NIXL; only EFA needs its missing LIBFABRIC plugin.\n \n FROM wheel_builder_base AS wheel_builder\n \n@@ -844,7 +845,8 @@ RUN --mount=type=secret,id=aws-web-identity-token,target=/run/secrets/aws-token\n -Dcudapath_lib=\"/usr/local/cuda/lib64\" \\\n -Dcudapath_inc=\"/usr/local/cuda/include\" \\\n -Ducx_path=\"/usr/local/ucx\" \\\n- -Dlibfabric_path=\"/usr/local/libfabric\"; \\\n+ -Dlibfabric_path=\"/usr/local/libfabric\"{% if framework == \"trtllm\" %} \\\n+ -Denable_plugins=LIBFABRIC -Dbuild_tests=false -Dbuild_examples=false{% endif %}; \\\n elif [ \"$DEVICE\" = \"xpu\" ]; then \\\n meson setup build/ --prefix=/opt/intel/intel_nixl --buildtype=release \\\n -Ducx_path=\"/usr/local/ucx\"; \\\n@@ -878,7 +880,7 @@ RUN echo \"$NIXL_LIB_DIR\" > /etc/ld.so.conf.d/nixl.conf && \\\n echo \"$NIXL_PLUGIN_DIR\" >> /etc/ld.so.conf.d/nixl.conf && \\\n ldconfig\n \n-{% if not (framework == \"sglang\" and device == \"cuda\" and target in (\"runtime\", \"dev\", \"local-dev\")) %}\n+{% if framework != \"trtllm\" and not (framework == \"sglang\" and device == \"cuda\" and target in (\"runtime\", \"dev\", \"local-dev\")) %}\n # Build NIXL wheel → /opt/dynamo/dist/nixl/nixl*.whl (C++ transport library, all targets)\n ARG PYTHON_VERSION\n RUN --mount=type=secret,id=aws-web-identity-token,target=/run/secrets/aws-token \\\n@@ -900,7 +902,8 @@ COPY --from=runtime_wheel_builder /opt/dynamo/dist/ /opt/dynamo/dist/\n COPY --from=runtime_wheel_builder /opt/dynamo/rust-licenses/ /opt/dynamo/rust-licenses/\n \n {% else %}\n-# The frontend installs NIXL from PyPI and Triton ships no NIXL. Keep this alias\n+# TRT-LLM reuses upstream NIXL, the frontend installs it from PyPI, and Triton\n+# ships no NIXL. Keep this alias\n # so downstream stages can still COPY Dynamo wheels and build tools from a\n # common wheel_builder stage name.\n FROM runtime_wheel_builder AS wheel_builder\ndiff --git a/tests/dependencies/test_trtllm_nixl.py b/tests/dependencies/test_trtllm_nixl.py\nnew file mode 100644\nindex 000000000000..a3213b42df95\n--- /dev/null\n+++ b/tests/dependencies/test_trtllm_nixl.py\n@@ -0,0 +1,126 @@\n+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n+# SPDX-License-Identifier: Apache-2.0\n+\n+\"\"\"Exercise the inherited TRT-LLM NIXL stack without a global preload.\n+\n+A second NIXL/UCX installation can import successfully yet conflict with\n+TRT-LLM's native wrapper. Check real CPU transfers and loaded library identities\n+in both load orders, in the built image's unmodified loader environment.\n+TRT-LLM's native wrapper requires the NVIDIA driver even for a CPU transfer;\n+this test loads no model and allocates no GPU tensors.\n+\"\"\"\n+\n+import importlib.util\n+import subprocess\n+import sys\n+from pathlib import Path\n+\n+import pytest\n+\n+pytestmark = [\n+ pytest.mark.trtllm,\n+ pytest.mark.core,\n+ pytest.mark.pre_merge,\n+ pytest.mark.post_merge,\n+ pytest.mark.gpu_1,\n+ pytest.mark.integration,\n+ pytest.mark.timeout(90),\n+ pytest.mark.skipif(\n+ importlib.util.find_spec(\"tensorrt_llm\") is None,\n+ reason=\"requires the built TRT-LLM image\",\n+ ),\n+ pytest.mark.skipif(not sys.platform.startswith(\"linux\"), reason=\"Linux only\"),\n+]\n+\n+\n+def _probe(order):\n+ # This function also runs as a standalone subprocess to isolate native state.\n+ import ctypes\n+ import os\n+ import time\n+\n+ def mapped(name):\n+ return {\n+ str(Path(line.split()[-1]).resolve())\n+ for line in Path(\"/proc/self/maps\").read_text().splitlines()\n+ if Path(line.split()[-1]).name == name\n+ or Path(line.split()[-1]).name.startswith(name + \".\")\n+ }\n+\n+ assert not mapped(\"libnixl.so\"), \"ordinary processes must not preload NIXL\"\n+ spec = importlib.util.find_spec(\"tensorrt_llm\")\n+ libs = Path(spec.origin).parent / \"libs\"\n+\n+ def load_native():\n+ ctypes.CDLL(str(libs / \"libtensorrt_llm.so\"), mode=ctypes.RTLD_GLOBAL)\n+ ctypes.CDLL(\n+ str(libs / \"libtensorrt_llm_nixl_wrapper.so\"), mode=ctypes.RTLD_GLOBAL\n+ )\n+\n+ if order == \"native-first\":\n+ load_native()\n+ from nixl._api import nixl_agent\n+\n+ if order == \"python-first\":\n+ load_native()\n+ sender = nixl_agent(f\"packaging-{os.getpid()}-sender\")\n+ receiver = nixl_agent(f\"packaging-{os.getpid()}-receiver\")\n+ # Upstream also sets EFA_VERSION in images without the EFA plugin.\n+ efa_plugins = Path(\"/opt/nvidia/nvda_nixl/lib\").glob(\n+ \"*-linux-gnu/plugins/libplugin_LIBFABRIC.so\"\n+ )\n+ if any(efa_plugins):\n+ assert (\n+ \"LIBFABRIC\" in sender.get_plugin_list()\n+ ), \"EFA plugin must be discoverable in both native/Python load orders\"\n+ source = ctypes.create_string_buffer(bytes(range(256)) * 2048)\n+ target = ctypes.create_string_buffer(len(source))\n+ local = [(ctypes.addressof(source), len(source), 0, \"\")]\n+ remote = [(ctypes.addressof(target), len(target), 0, \"\")]\n+ source_registration = sender.register_memory(local, \"DRAM\")\n+ target_registration = receiver.register_memory(remote, \"DRAM\")\n+ handle = None\n+ try:\n+ sender.add_remote_agent(receiver.get_agent_metadata())\n+ # Registration includes metadata; transfer descriptors contain only\n+ # the address, length, and device ID.\n+ handle = sender.initialize_xfer(\n+ \"WRITE\",\n+ sender.get_xfer_descs([entry[:3] for entry in local], \"DRAM\"),\n+ receiver.get_xfer_descs([entry[:3] for entry in remote], \"DRAM\"),\n+ receiver.name,\n+ )\n+ state = sender.transfer(handle)\n+ deadline = time.monotonic() + 15\n+ while state != \"DONE\":\n+ assert state in (\"PROC\", \"IN_PROG\"), state\n+ assert time.monotonic() < deadline, \"CPU transfer did not complete\"\n+ time.sleep(0.001)\n+ state = sender.check_xfer_state(handle)\n+ assert source.raw == target.raw, \"NIXL CPU transfer corrupted data\"\n+ for name in (\"libnixl.so\", \"libucp.so\", \"libucs.so\", \"libuct.so\"):\n+ paths = mapped(name)\n+ assert len(paths) == 1, f\"expected one loaded {name}, got {paths}\"\n+ finally:\n+ if handle is not None:\n+ sender.release_xfer_handle(handle)\n+ sender.deregister_memory(source_registration)\n+ receiver.deregister_memory(target_registration)\n+\n+\n+@pytest.mark.parametrize(\"order\", [\"native-first\", \"python-first\"])\n+def test_native_and_python_nixl_share_a_working_stack(order):\n+ result = subprocess.run(\n+ [sys.executable, str(Path(__file__).resolve()), order],\n+ capture_output=True,\n+ text=True,\n+ timeout=60,\n+ )\n+ assert result.returncode == 0, (\n+ f\"NIXL compatibility failed in {order} load order:\\n\"\n+ f\"stdout: {result.stdout}\\nstderr: {result.stderr}\"\n+ )\n+\n+\n+if __name__ == \"__main__\":\n+ _probe(sys.argv[1])\n\n[5 documentation file diff(s) omitted]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(container): reuse upstream TRT-LLM NIXL stack\nLabels: documentation, size/L, fix, backend::trtllm, container, human-review\nFiles changed (11): container/context.yaml, container/deps/requirements.trtllm.txt, container/templates/aws.Dockerfile, container/templates/dev.Dockerfile, container/templates/trtllm_runtime.Dockerfile, container/templates/wheel_builder.Dockerfile, docs/fern/components/releases.data.ts, docs/fern/pages/developer-guide/knowledge-base/modular-components/backends/tensorrt-llm/overview.md, docs/fern/pages/reference/general/compatibility.mdx, docs/fern/pages/reference/general/releases-machine-readable.mdx, tests/dependencies/test_trtllm_nixl.py\n\n## Description (results removed)\n\n### Overview\n\nEvery process in the TRT-LLM image currently preloads NIXL, adding startup overhead even to commands such as `stat`. Reuse the native NIXL library and Python bindings from the pinned TRT-LLM image, remove the global NIXL preload, and retain the separate `libstdc++` preload. EFA images add the API-compatible LIBFABRIC 1.5.2 plugin, preserving main's CUDA-context and endpoint-synchronization fixes.\n\n### Key Changes\n\nCore container logic: **28 added / 27 removed lines**, excluding tests, documentation, comments, and whitespace; low complexity. The full diff covers 11 files, with no new package dependencies or Rust/backend changes.\n\n- [trtllm_runtime.Dockerfile](https://github.com/ai-dynamo/dynamo/blob/271f8995398be07dcd5f45b9cdd5d006ec5c3b9a/container/templates/trtllm_runtime.Dockerfile): register upstream Python bindings, remove the second NIXL installation and global preload, and validate imports/native loading during the build.\n- [aws.Dockerfile](https://github.com/ai-dynamo/dynamo/blob/271f8995398be07dcd5f45b9cdd5d006ec5c3b9a/container/templates/aws.Dockerfile): add the LIBFABRIC plugin and select its SDK directory. Accept equal package versions or the qualified native/plugin pair `1.5.0/1.5.2`, and verify plugin API 1 during the build.\n- [wheel_builder.Dockerfile](https://github.com/ai-dynamo/dynamo/blob/271f8995398be07dcd5f45b9cdd5d006ec5c3b9a/container/templates/wheel_builder.Dockerfile): skip the TRT-LLM NIXL build unless EFA needs the plugin; align development-image paths and documentation with the inherited stack.\n\n### Validation\n[results removed]\n## Summary by CodeRabbit\n\n* **Compatibility**\n * Updated the TensorRT-LLM NIXL version to 1.5.0.\n * AWS EFA containers now include the required LIBFABRIC plugin while using NIXL components from the upstream release image.\n* **Documentation**\n * Clarified NIXL requirements for TensorRT-LLM containers, including guidance for matching versions when changing the base image.\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/common/configuration/groups/runtime_args.py b/components/src/dynamo/common/configuration/groups/runtime_args.py\nindex 03c2e02a271d..29a7cffad013 100644\n--- a/components/src/dynamo/common/configuration/groups/runtime_args.py\n+++ b/components/src/dynamo/common/configuration/groups/runtime_args.py\n@@ -289,7 +289,7 @@ def add_arguments(self, parser: argparse.ArgumentParser) -> None:\n flag_name=\"--connector\",\n env_var=\"DYN_CONNECTOR\",\n default=[],\n- help=\"[Deprecated for vLLM] Use --kv-transfer-config instead. For TRT-LLM, options: nixl, lmcache, kvbm, null, none.\",\n+ help=\"[Deprecated for vLLM] Use --kv-transfer-config instead. TensorRT-LLM supports only none; KVBM integration has been removed.\",\n nargs=\"*\",\n )\n \ndiff --git a/components/src/dynamo/trtllm/args.py b/components/src/dynamo/trtllm/args.py\nindex 8f464d7b1017..8e9e81139438 100644\n--- a/components/src/dynamo/trtllm/args.py\n+++ b/components/src/dynamo/trtllm/args.py\n@@ -37,7 +37,7 @@ def _warn_deprecated(message: str) -> None:\n DEFAULT_ENCODE_COMPONENT = \"encode\"\n DEFAULT_DIFFUSION_COMPONENT = \"diffusion\"\n DEFAULT_ENDPOINT_NAME = \"generate\"\n-VALID_TRTLLM_CONNECTORS = {\"none\", \"kvbm\"}\n+VALID_TRTLLM_CONNECTORS = {\"none\"}\n \n \n def _forward_pass_metrics_enabled(config: DynamoRuntimeConfig) -> bool:\n@@ -74,12 +74,18 @@ def validate(self) -> None:\n self.publish_metrics or _forward_pass_metrics_enabled(self)\n )\n \n- # fix the connector as trtllm accepts only one connector and it should be in VALID_TRTLLM_CONNECTORS\n- # while the runtime args accepts a list of connectors\n+ # Shared runtime defaults may select connectors used by other backends.\n+ # Explicit KVBM configuration must fail rather than silently disabling it.\n+ if self.connector and \"kvbm\" in self.connector:\n+ raise ValueError(\n+ \"TRT-LLM KVBM integration has been removed. Remove --connector kvbm \"\n+ \"or DYN_CONNECTOR=kvbm; use --connector none.\"\n+ )\n+\n if self.connector:\n if len(self.connector) > 1:\n raise ValueError(\n- \"TRT-LLM supports at most one connector entry. Use `--connector none` or `--connector kvbm`.\"\n+ \"TRT-LLM supports at most one connector entry. Use `--connector none`.\"\n )\n elif self.connector[0] not in VALID_TRTLLM_CONNECTORS:\n source = (\n@@ -93,13 +99,6 @@ def validate(self) -> None:\n )\n self.connector = [\"none\"]\n \n- def has_connector(self, connector_name: str) -> bool:\n- return (\n- self.connector is not None\n- and len(self.connector) > 0\n- and connector_name == self.connector[0]\n- )\n-\n \n @register_encoder(Config)\n def _preprocess_for_encode_config(config: Config) -> Dict[str, Any]:\ndiff --git a/components/src/dynamo/trtllm/publisher.py b/components/src/dynamo/trtllm/publisher.py\nindex 66d9fa543c2e..a99c205e4917 100644\n--- a/components/src/dynamo/trtllm/publisher.py\n+++ b/components/src/dynamo/trtllm/publisher.py\n@@ -1,22 +1,10 @@\n # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n # SPDX-License-Identifier: Apache-2.0\n \n-\"\"\"\n-TensorRT-LLM KV Event Publisher Module\n-\n-This module contains the Publisher class that retrieves KV cache events from TensorRT-LLM\n-and publishes them either to ZMQ (for consolidator) or NATS (direct to router).\n-\n-Key Components:\n-- ZmqKvEventPublisher: Pure Python ZMQ PUBLISHER that publishes TensorRT-LLM KV events\n- to ZMQ (so the consolidator can subscribe). This is different from KvEventPublisher\n- in dynamo.llm, which is a Rust-based class that can optionally subscribe from a ZMQ\n- source and publishes to NATS.\n-- Publisher: Main class that coordinates event publishing (ZMQ or NATS) and metrics publishing.\n+\"\"\"Publish TensorRT-LLM KV events to Dynamo and engine metrics to their consumers.\n \n-Event Flow:\n-- With Consolidator: Engine → ZmqKvEventPublisher (ZMQ PUB) → Consolidator → KvEventPublisher (dynamo.llm, ZMQ SUB) → NATS → Router\n-- Without Consolidator: Engine → KvEventPublisher (NATS PUB) → Router\n+Polling reads native engine events; streaming subscribes to TRT-LLM's ZMQ source.\n+Both publish directly through Dynamo's KV event pipeline to the router.\n \"\"\"\n \n import asyncio\n@@ -25,7 +13,6 @@\n import os\n import re\n import threading\n-import time\n import traceback\n import weakref\n from collections.abc import AsyncGenerator\n@@ -34,8 +21,6 @@\n from queue import Queue\n from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, Union, cast\n \n-import msgspec\n-import zmq\n from prometheus_client import CollectorRegistry\n \n from dynamo.common.utils.prometheus import LLMBackendMetrics\n@@ -236,152 +221,6 @@ def _to_signed_i64(value: int | None) -> int | None:\n return value\n \n \n-class ZmqKvEventPublisher:\n- \"\"\"\n- Pure Python ZMQ PUBLISHER for TensorRT-LLM KV events.\n-\n- This class publishes TensorRT-LLM's KV cache events to ZMQ so that the consolidator\n- can subscribe to them. This is different from KvEventPublisher in dynamo.llm,\n- which is a Rust-based class that can optionally subscribe from a ZMQ source\n- and publishes to NATS.\n-\n- Event Format: [timestamp, [events], data_parallel_rank]\n- Message Format: multipart ZMQ message [topic, sequence, payload] where payload is\n- msgpack-serialized batch.\n- When attention DP is enabled for DeepSeek-style models, `data_parallel_rank` is set to the attention DP rank.\n- Otherwise, it defaults to 0.\n-\n- Usage:\n- Used by Publisher class when consolidator is enabled (zmq_endpoint provided).\n- Publishes events from TensorRT-LLM engine to ZMQ for consolidator to consume.\n- \"\"\"\n-\n- def __init__(self, zmq_endpoint: str, kv_block_size: int, topic: str = \"\") -> None:\n- \"\"\"\n- Initialize ZMQ publisher.\n-\n- Args:\n- zmq_endpoint: ZMQ endpoint to bind to (e.g., \"tcp://*:20081\")\n- kv_block_size: Size of KV cache blocks in tokens\n- topic: ZMQ topic to publish on (empty string for all topics)\n- \"\"\"\n- self.zmq_endpoint = zmq_endpoint\n- self.kv_block_size = kv_block_size\n- self.topic = topic\n- self.ctx = zmq.Context()\n- self.socket = self.ctx.socket(zmq.PUB)\n- self.socket.bind(zmq_endpoint)\n- self.sequence = 0\n- self.data_parallel_rank = (\n- 0 # TensorRT-LLM doesn't use DP for now (but does support attention DP)\n- )\n- logging.info(\n- f\"TensorRT-LLM: ZMQ KV event publisher initialized - bound to {zmq_endpoint} \"\n- f\"with topic '{topic}', kv_block_size={kv_block_size}\"\n- )\n-\n- def publish_stored(\n- self,\n- token_ids: list[int],\n- num_block_tokens: list[int],\n- block_hashes: list[int],\n- parent_hash: Optional[int] = None,\n- block_mm_infos: Optional[list[dict | None]] = None,\n- attention_dp_rank: int = 0,\n- lora_name: Optional[str] = None,\n- cache_salt: Optional[str] = None,\n- ) -> None:\n- \"\"\"Publish a BlockStored event.\n-\n- Note: event_id is managed internally via self.sequence counter.\n- \"\"\"\n- # Convert block hashes to signed i64 format\n- block_hashes_signed = [_to_signed_i64(h) for h in block_hashes]\n- parent_hash_signed = (\n- _to_signed_i64(parent_hash) if parent_hash is not None else None\n- )\n-\n- # Create event in the same format as vLLM's ZmqEventPublisher:\n- # All blocks should have the same size (kv_block_size)\n- event: dict[str, Any] = {\n- \"type\": \"BlockStored\",\n- \"block_hashes\": block_hashes_signed,\n- \"parent_block_hash\": parent_hash_signed,\n- \"token_ids\": token_ids,\n- \"block_size\": self.kv_block_size,\n- }\n- if lora_name is not None:\n- event[\"lora_name\"] = lora_name\n- if cache_salt is not None:\n- event[\"cache_salt\"] = cache_salt\n-\n- # Add multimodal info if present\n- if block_mm_infos is not None:\n- event[\"block_mm_infos\"] = block_mm_infos\n-\n- self._publish_event(event, attention_dp_rank)\n-\n- def publish_removed(\n- self, block_hashes: list[int], attention_dp_rank: int = 0\n- ) -> None:\n- \"\"\"Publish a BlockRemoved event.\n-\n- Note: event_id is managed internally via self.sequence counter.\n- \"\"\"\n- # Convert block hashes to signed i64 format (vLLM compatibility)\n- block_hashes_signed = [_to_signed_i64(h) for h in block_hashes]\n-\n- event = {\n- \"type\": \"BlockRemoved\",\n- \"block_hashes\": block_hashes_signed,\n- }\n-\n- self._publish_event(event, attention_dp_rank)\n-\n- def publish_all_cleared(self, attention_dp_rank: int = 0) -> None:\n- \"\"\"Publish an AllBlocksCleared event for one attention DP rank.\"\"\"\n- event = {\"type\": \"AllBlocksCleared\"}\n- self._publish_event(event, attention_dp_rank)\n-\n- def _publish_event(self, event: dict, attention_dp_rank: int = 0):\n- \"\"\"Publish a single event to ZMQ in vLLM batch format.\"\"\"\n- try:\n- # Create batch in vLLM format: [timestamp, [events], data_parallel_rank]\n- # The third element (data_parallel_rank) is used by the router for dp_rank routing\n- timestamp = time.time()\n- batch = [timestamp, [event], attention_dp_rank]\n- event_type = event.get(\"type\", \"Unknown\")\n- logging.debug(\n- f\"TensorRT-LLM: ZMQ publisher sending {event_type} event (dp_rank={attention_dp_rank}) to {self.zmq_endpoint}\"\n- )\n-\n- # Serialize with msgspec's msgpack implementation to match the\n- # vLLM wire format without depending on the separate msgpack\n- # package.\n- payload = msgspec.msgpack.encode(batch)\n-\n- # Create multipart message: [topic, sequence, payload]\n- # Format matches what consolidator expects: 3 frames [topic, sequence, payload]\n- sequence_bytes = self.sequence.to_bytes(8, byteorder=\"big\")\n- self.sequence += 1\n-\n- # Send multipart message (blocking send to ensure delivery)\n- # Topic is empty string for \"all topics\" (vLLM compatibility)\n- self.socket.send_multipart(\n- [self.topic.encode(), sequence_bytes, payload], flags=0\n- )\n- except Exception as e:\n- logging.error(f\"Failed to publish ZMQ event: {e}\", exc_info=True)\n-\n- def shutdown(self) -> None:\n- \"\"\"Shutdown the ZMQ publisher.\"\"\"\n- if self.socket:\n- self.socket.close()\n- if self.ctx:\n- self.ctx.term()\n- logging.info(\"ZMQ KV event publisher shut down\")\n-\n-\n class ManagedThread(threading.Thread):\n \"\"\"\n A thread that runs a task and handles errors.\n@@ -493,19 +332,11 @@ class Publisher:\n Main publisher class for TensorRT-LLM KV events and metrics.\n \n Retrieves KV cache events and stats from TensorRT-LLM engine and publishes them:\n- - KV Events: Routes to either ZMQ (if consolidator enabled) or NATS (if no consolidator)\n+ - KV Events: Publishes native polling or streaming events directly to Dynamo\n - Metrics: Worker-load samples via WorkerMetricsPublisher and, when opted in,\n forward-pass metrics via FpmDirectPublisher; both read the engine's\n iteration stats, which KV events never need\n \n- Publisher Selection Logic:\n- - If zmq_endpoint provided: Uses ZmqKvEventPublisher (ZMQ PUB) → Consolidator → NATS\n- - If zmq_endpoint None: Uses KvEventPublisher (NATS PUB) → Router directly\n-\n- Note: The ZmqKvEventPublisher used here is the pure Python ZMQ publisher defined\n- in this module, not the Rust-based KvEventPublisher from dynamo.llm (which is\n- used in main.py as the worker-side subscriber from consolidator to NATS).\n-\n ``kv_state_endpoint`` selects the exact Dynamo endpoint that owns the published\n KV event and recovery state. ``None`` maps KV state to the serving endpoint; it\n does not change the endpoint used for request routing.\n@@ -521,7 +352,6 @@ def __init__(\n component_gauges: LLMBackendMetrics,\n additional_metrics: Any = None,\n event_buffer_max_size: int = 0,\n- zmq_endpoint: Optional[str] = None,\n enable_local_indexer: bool = False,\n metrics_collector: Any = None,\n kv_state_endpoint: Optional[str] = None,\n@@ -572,7 +402,6 @@ def __init__(\n self.kv_event_publishers: Optional[\n Dict[int, KvEventPublisher]\n ] = None # One per attention_dp_rank\n- self.zmq_kv_event_publisher = None # ZMQ publisher for consolidator\n self.publish_kv_cache_events_thread: Optional[ManagedThread] = None\n self.publish_stats_thread: Optional[ManagedThread] = None\n # A set to store the block hash of partial block (i.e. block containing less than kv_block_size tokens) hashes.\n@@ -584,22 +413,6 @@ def __init__(\n # independent rank-local sequences before gathering them on rank 0.\n self._last_engine_event_id_by_rank: dict[int, int] = {}\n \n- # The consolidator is part of the polling path only.\n- if (\n- zmq_endpoint\n- and self.kv_event_publication_mode is KvEventPublicationMode.POLLING\n- ):\n- logging.info(\n- f\"TensorRT-LLM: Initializing ZMQ KV event publisher with endpoint={zmq_endpoint}\"\n- )\n- self.zmq_kv_event_publisher = ZmqKvEventPublisher(\n- zmq_endpoint, self.kv_block_size\n- )\n- else:\n- logging.info(\n- \"TensorRT-LLM: ZMQ endpoint not provided, ZMQ publisher will not be initialized\"\n- )\n-\n async def _create_metrics_publisher_endpoint(self):\n logging.debug(\"Creating metrics publisher endpoint\")\n if self.metrics_publisher is None:\n@@ -649,11 +462,11 @@ def initialize(self) -> None:\n # - STREAMING: TRT-LLM publishes ZMQ batches; Dynamo subscribes and\n # forwards them to its event pipeline.\n # - POLLING: Dynamo reads events from the engine, then publishes them\n- # directly or through the consolidator.\n+ # directly to Dynamo.\n # - DISABLED: no KV events are passed through this worker.\n if self.kv_event_publication_mode is KvEventPublicationMode.STREAMING:\n # TensorRT-LLM's streaming event manager publishes ZMQ batches itself;\n- # Dynamo subscribes directly and does not poll the engine or use a consolidator.\n+ # Dynamo subscribes directly and does not poll the engine.\n #\n # NOTE: This is currently a live, best-effort subscription. The Dynamo\n # ZMQ relay forwards every batch it receives, but does not yet detect\n@@ -690,31 +503,20 @@ def initialize(self) -> None:\n self.attention_dp_size,\n )\n elif self.kv_event_publication_mode is KvEventPublicationMode.POLLING:\n- # Publisher selection based on consolidator configuration:\n- # - With consolidator: ZmqKvEventPublisher → ZMQ → Consolidator → NATS → Router\n- # - Without consolidator: KvEventPublisher → NATS → Router (direct)\n- if self.zmq_kv_event_publisher:\n- logging.info(\n- \"KV Event Consolidator enabled - using ZMQ publisher only. \"\n- \"Consolidator will publish consolidated events to NATS.\"\n- )\n- self.kv_event_publishers = None\n- else:\n- # No consolidator: use NATS publisher (router subscribes directly).\n- self.kv_event_publishers = {}\n- for rank in range(self.attention_dp_size):\n- self.kv_event_publishers[rank] = KvEventPublisher(\n- endpoint=self.endpoint,\n- worker_id=self.worker_id,\n- kv_block_size=self.kv_block_size,\n- dp_rank=rank,\n- enable_local_indexer=self.enable_local_indexer,\n- kv_state_endpoint=self.kv_state_endpoint,\n- image_token_id=self.image_token_id,\n- )\n- logging.info(\n- f\"Created {self.attention_dp_size} KV event publisher(s) for attention DP ranks\"\n+ self.kv_event_publishers = {}\n+ for rank in range(self.attention_dp_size):\n+ self.kv_event_publishers[rank] = KvEventPublisher(\n+ endpoint=self.endpoint,\n+ worker_id=self.worker_id,\n+ kv_block_size=self.kv_block_size,\n+ dp_rank=rank,\n+ enable_local_indexer=self.enable_local_indexer,\n+ kv_state_endpoint=self.kv_state_endpoint,\n+ image_token_id=self.image_token_id,\n )\n+ logging.info(\n+ f\"Created {self.attention_dp_size} KV event publisher(s) for attention DP ranks\"\n+ )\n \n # Polling is the only mode that needs a worker polling thread.\n self._init_publish_kv_cache_events_thread()\n@@ -987,15 +789,15 @@ def handle_stats(stats):\n async def _publish_kv_cache_events_task(self):\n \"\"\"\n Publish kv cache events to the events publisher.\n- Routes to ZMQ (if kv event consolidation is enabled) or NATS (if no kv event consolidation).\n+ Native engine events publish directly to Dynamo.\n \"\"\"\n if self.engine is None:\n logging.error(\"LLM engine not initialized!\")\n return\n \n # Check that at least one publisher is available\n- if not self.kv_event_publishers and self.zmq_kv_event_publisher is None:\n- logging.error(\"No KV event publisher initialized (neither NATS nor ZMQ)!\")\n+ if not self.kv_event_publishers:\n+ logging.error(\"No KV event publisher initialized!\")\n return\n \n await self._polling_loop(\n@@ -1011,10 +813,7 @@ async def _publish_kv_cache_events_task(self):\n return True\n \n def _handle_kv_event_drain(self, events):\n- if self.zmq_kv_event_publisher:\n- self._handle_zmq_kv_event_batch(events)\n- else:\n- self._handle_kv_event_batch(events)\n+ self._handle_kv_event_batch(events)\n \n def _record_kv_event_drain_batch(self, batch_size: int) -> None:\n if self.additional_metrics is not None:\n@@ -1172,35 +971,6 @@ def _normalize_kv_event(self, event):\n self.update_max_window_size(event)\n return None\n \n- def _handle_zmq_kv_event(self, event):\n- normalized = self._normalize_kv_event(event)\n- if normalized is None:\n- return\n- attention_dp_rank, normalized_event = normalized\n- zmq_publisher = self.zmq_kv_event_publisher\n- assert zmq_publisher is not None\n-\n- if normalized_event[\"type\"] == \"stored\":\n- zmq_publisher.publish_stored(\n- normalized_event[\"token_ids\"],\n- normalized_event[\"num_block_tokens\"],\n- normalized_event[\"block_hashes\"],\n- normalized_event[\"parent_hash\"],\n- normalized_event[\"block_mm_infos\"],\n- attention_dp_rank,\n- normalized_event[\"lora_name\"],\n- normalized_event[\"cache_salt\"],\n- )\n- else:\n- zmq_publisher.publish_removed(\n- normalized_event[\"block_hashes\"], attention_dp_rank\n- )\n-\n- def _handle_zmq_kv_event_batch(self, events):\n- \"\"\"Preserve singleton publication for the optional ZMQ consolidator.\"\"\"\n- for event in events:\n- self._handle_zmq_kv_event(event)\n-\n def _handle_kv_event_batch(self, events):\n events_by_rank: dict[int, list[\"KvStoredEventInput | KvRemovedEventInput\"]] = {}\n for event in events:\n@@ -1270,10 +1040,6 @@ async def cleanup(self) -> None:\n if self.publish_kv_cache_events_thread.is_alive():\n logging.warning(\"KV cache events thread did not stop within timeout\")\n \n- # Shutdown ZMQ publisher if it exists\n- if self.zmq_kv_event_publisher:\n- self.zmq_kv_event_publisher.shutdown()\n-\n # Shutdown FpmDirectPublisher (stops the per-rank serialization tasks\n # and the event-plane publisher task on the Rust side). PyO3 surfaces\n # shutdown failures as PyRuntimeError; narrower catch keeps real\n@@ -1331,7 +1097,6 @@ async def get_publisher(\n component_gauges: LLMBackendMetrics,\n additional_metrics: Any = None,\n event_buffer_max_size: int = 0,\n- zmq_endpoint: Optional[str] = None,\n enable_local_indexer: bool = False,\n metrics_collector: Any = None,\n kv_state_endpoint: Optional[str] = None,\n@@ -1351,7 +1116,6 @@ async def get_publisher(\n component_gauges=component_gauges,\n additional_metrics=additional_metrics,\n event_buffer_max_size=event_buffer_max_size,\n- zmq_endpoint=zmq_endpoint,\n enable_local_indexer=enable_local_indexer,\n metrics_collector=metrics_collector,\n kv_state_endpoint=kv_state_endpoint,\ndiff --git a/components/src/dynamo/trtllm/snapshot.py b/components/src/dynamo/trtllm/snapshot.py\nindex b00e74402055..b1f2eec2a938 100644\n--- a/components/src/dynamo/trtllm/snapshot.py\n+++ b/components/src/dynamo/trtllm/snapshot.py\n@@ -171,7 +171,6 @@ def _validate_supported_snapshot_config(config: Any) -> None:\n ),\n (not config.encode_endpoint, \"--encode-endpoint\"),\n (not config.frontend_decoding, \"--frontend-decoding\"),\n- (not config.has_connector(\"kvbm\"), \"--connector kvbm\"),\n )\n if not supported\n ]\ndiff --git a/components/src/dynamo/trtllm/workers/llm_worker.py b/components/src/dynamo/trtllm/workers/llm_worker.py\nindex e7fbaf09b770..cbd79ff61e98 100644\n--- a/components/src/dynamo/trtllm/workers/llm_worker.py\n+++ b/components/src/dynamo/trtllm/workers/llm_worker.py\n@@ -24,11 +24,7 @@\n SchedulerConfig,\n )\n from tensorrt_llm.llmapi.llm import SamplingParams\n-from tensorrt_llm.llmapi.llm_args import (\n- TOKENIZER_ALIASES,\n- KvCacheConnectorConfig,\n- LoadFormat,\n-)\n+from tensorrt_llm.llmapi.llm_args import TOKENIZER_ALIASES, LoadFormat\n from tensorrt_llm.llmapi.llm_utils import update_llm_args_with_extra_options\n from tensorrt_llm.llmapi.tokenizer import tokenizer_factory\n from tensorrt_llm.metrics import MetricsCollector\n@@ -51,7 +47,6 @@\n from dynamo.common.utils.runtime import parse_endpoint\n from dynamo.common.utils.topology import apply_topology_config\n from dynamo.llm import (\n- KvEventPublisher,\n MediaDecoder,\n MediaFetcher,\n ModelInput,\n@@ -178,22 +173,6 @@ def _resolve_image_token_id(model_type: str, config: Config) -> Optional[int]:\n return resolve_routing_image_token_id(config.model, _resolve_model_dir(config))\n \n \n-def build_kv_connector_config(config: Config):\n- if config.connector:\n- if config.connector[0] == \"kvbm\":\n- return KvCacheConnectorConfig(\n- connector_module=\"kvbm.trtllm_integration.connector\",\n- connector_scheduler_class=\"DynamoKVBMConnectorLeader\",\n- connector_worker_class=\"DynamoKVBMConnectorWorker\",\n- )\n- elif config.connector[0] == \"none\":\n- return None\n- else:\n- logging.error(f\"Invalid connector: {config.connector[0]}\")\n- sys.exit(1)\n- return None\n-\n-\n def _warn_override_collisions(target: dict, source: dict, path: str = \"\") -> None:\n \"\"\"Log warnings for keys in *source* that will overwrite existing values in *target*.\"\"\"\n for key, new_val in source.items():\n@@ -370,9 +349,6 @@ async def init_llm_worker(\n free_gpu_memory_fraction=config.free_gpu_memory_fraction\n )\n \n- if config.has_connector(\"kvbm\"):\n- kv_cache_config.enable_partial_reuse = False\n-\n dynamic_batch_config = DynamicBatchConfig(\n enable_batch_size_tuning=True,\n enable_max_num_tokens_tuning=False,\n@@ -382,7 +358,6 @@ async def init_llm_worker(\n capacity_scheduler_policy=CapacitySchedulerPolicy.GUARANTEED_NO_EVICT,\n dynamic_batch_config=dynamic_batch_config,\n )\n- kv_connector_config = build_kv_connector_config(config)\n \n try:\n model_loader_extra_config = _parse_model_loader_extra_config(\n@@ -449,7 +424,6 @@ async def init_llm_worker(\n \"enable_iter_perf_stats\": (\n config.publish_metrics or config.publish_forward_pass_metrics\n ),\n- \"kv_connector_config\": kv_connector_config,\n }\n \n arg_map[\"load_format\"] = engine_load_format\n@@ -561,42 +535,6 @@ async def init_llm_worker(\n )\n sys.exit(1)\n \n- trtllm_zmq_bind_endpoint = None # Endpoint for TensorRT-LLM to bind and publish\n- consolidator_output_endpoint = (\n- None # Endpoint where consolidator publishes (workers subscribe to this)\n- )\n-\n- try:\n- from kvbm.trtllm_integration.consolidator_config import (\n- get_consolidator_endpoints,\n- should_enable_consolidator,\n- )\n-\n- if (\n- kv_event_publication_mode is KvEventPublicationMode.POLLING\n- and should_enable_consolidator(arg_map)\n- ):\n- # get_consolidator_endpoints returns (trtllm_bind_endpoint, output_bind_endpoint, output_connect_endpoint)\n- consolidator_endpoints = get_consolidator_endpoints()\n- trtllm_zmq_bind_endpoint = consolidator_endpoints[0] # TRTLLM bind endpoint\n- consolidator_output_endpoint = consolidator_endpoints[\n- 1\n- ] # Consolidator output bind endpoint (for KVBM connector)\n- consolidator_output_connect_endpoint = consolidator_endpoints[\n- 2\n- ] # Consolidator output connect endpoint (for worker publisher)\n- except ImportError:\n- # kvbm package is not installed\n- logging.info(\n- \"kvbm package not installed - skipping KV event consolidator setup.\"\n- )\n- except Exception as e:\n- logging.error(\n- f\"Failed to set up consolidator endpoints: {e}. \"\n- \"Continuing without KV event consolidation.\",\n- exc_info=True,\n- )\n-\n logging.info(f\"TensorRT-LLM engine args: {arg_map}\")\n engine_args = arg_map\n \n@@ -1025,28 +963,6 @@ async def init_llm_worker(\n ), # Native engine compatibility\n ]\n \n- # Create worker-side publisher for consolidated events if consolidator is enabled\n- # This subscribes to consolidator's ZMQ output and publishes to NATS with worker_id\n- consolidator_publisher = None\n- if (\n- kv_event_publication_mode is KvEventPublicationMode.POLLING\n- and consolidator_output_endpoint\n- ):\n- # Use the connect endpoint directly (already provided by get_consolidator_endpoints)\n- consolidator_publisher = KvEventPublisher(\n- endpoint=endpoint,\n- kv_block_size=kv_cache_block_size,\n- zmq_endpoint=consolidator_output_connect_endpoint,\n- zmq_topic=\"\",\n- enable_local_indexer=config.enable_local_indexer,\n- kv_state_endpoint=config.kv_state_endpoint,\n- image_token_id=image_token_id,\n- )\n- logging.info(\n- f\"Created worker-side publisher for consolidated events: \"\n- f\"subscribing to {consolidator_output_connect_endpoint}, worker_id={endpoint.connection_id()}\"\n- )\n-\n async with get_publisher(\n endpoint,\n engine,\n@@ -1056,7 +972,6 @@ async def init_llm_worker(\n component_gauges=component_gauges,\n additional_metrics=additional_metrics,\n event_buffer_max_size=event_buffer_max_size,\n- zmq_endpoint=trtllm_zmq_bind_endpoint,\n enable_local_indexer=config.enable_local_indexer,\n metrics_collector=metrics_collector,\n kv_state_endpoint=config.kv_state_endpoint,\n@@ -1086,9 +1001,6 @@ async def init_llm_worker(\n health_check_payload=health_check_payload,\n )\n \n- # Shutdown consolidator publisher if it was created\n- if consolidator_publisher:\n- consolidator_publisher.shutdown()\n else:\n handler = RequestHandlerFactory().get_request_handler(handler_config)\n if config.load_format == \"gms\":\ndiff --git a/lib/bindings/kvbm/python/kvbm/_core.pyi b/lib/bindings/kvbm/python/kvbm/_core.pyi\nindex 663b377d9cb5..293eaabcbbad 100644\n--- a/lib/bindings/kvbm/python/kvbm/_core.pyi\n+++ b/lib/bindings/kvbm/python/kvbm/_core.pyi\n@@ -82,7 +82,7 @@ class NcclBootstrap:\n Returns:\n --------\n NcclCommRef\n- Owning reference; pass to KvbmWorker/PyTrtllmKvConnectorWorker\n+ Owning reference; pass to KvbmWorker\n \"\"\"\n ...\n \n@@ -103,7 +103,7 @@ class NcclCommRef:\n Owning reference to an NCCL communicator; calls ncclCommDestroy on drop.\n \n Returned by NcclBootstrap.init_communicator. Pass to workers\n- (KvbmWorker, PyTrtllmKvConnectorWorker) so they keep the comm alive.\n+ (KvbmWorker) so they keep the comm alive.\n \"\"\"\n \n def as_raw(self) -> int:\n@@ -398,283 +398,3 @@ class SchedulerOutput:\n \n def __init__(self) -> None:\n ...\n-\n-\n-class PyTrtllmKvConnectorWorker:\n- \"\"\"\n- TensorRT-LLM KV connector worker for KVBM integration.\n-\n- This class handles KV cache operations on the worker side for TRT-LLM,\n- including registration of KV caches, offloading, and loading operations.\n- \"\"\"\n-\n- def __init__(\n- self,\n- py_drt: Optional[Any],\n- trtllm_rank: str,\n- nccl_rank: Optional[int] = None,\n- world_size: Optional[int] = None,\n- nccl_comm_ref: Optional[\"NcclCommRef\"] = None,\n- ) -> None:\n- \"\"\"\n- Create a PyTrtllmKvConnectorWorker instance.\n-\n- Parameters:\n- -----------\n- py_drt: Optional[Any]\n- The distributed runtime object (DistributedRuntime)\n- trtllm_rank: str\n- The TRT-LLM rank identifier\n- nccl_rank: Optional[int]\n- NCCL rank for replicated mode (None = sharded mode).\n- Required for MLA support optimization (replicated mode).\n- world_size: Optional[int]\n- World size for replicated mode.\n- Required for MLA support optimization.\n- nccl_comm_ref: Optional[NcclCommRef]\n- Owning NCCL comm ref from NcclBootstrap.init_communicator().\n- Required for MLA support optimization.\n- \"\"\"\n- ...\n-\n- def register_kv_caches(\n- self,\n- num_device_blocks: int,\n- page_size: int,\n- device_id: int,\n- dtype_width_bytes: int,\n- kv_cache_tensor: Any,\n- raw_event_handles: List[int],\n- ) -> None:\n- \"\"\"\n- Register KV cache tensors with the connector worker.\n-\n- Parameters:\n- -----------\n- num_device_blocks: int\n- Number of device blocks to manage\n- page_size: int\n- Page size for blocks\n- device_id: int\n- CUDA device ID\n- dtype_width_bytes: int\n- Data type width in bytes (e.g., 2 for fp16)\n- kv_cache_tensor: Any\n- The KV cache tensor (torch.Tensor)\n- raw_event_handles: List[int]\n- List of raw CUDA event handles\n- \"\"\"\n- ...\n-\n- def bind_connector_meta(self, metadata: bytes) -> None:\n- \"\"\"\n- Bind connector metadata from the leader.\n-\n- Parameters:\n- -----------\n- metadata: bytes\n- Serialized connector metadata\n- \"\"\"\n- ...\n-\n- def execute_offload_operations(self) -> None:\n- \"\"\"\n- Execute pending offload operations.\n- \"\"\"\n- ...\n-\n- def save_kv_layer(self, layer_idx: int) -> None:\n- \"\"\"\n- Save a KV cache layer.\n-\n- Parameters:\n- -----------\n- layer_idx: int\n- Index of the layer to save\n- \"\"\"\n- ...\n-\n- def start_load_kv(self) -> None:\n- \"\"\"\n- Start loading KV cache data.\n- \"\"\"\n- ...\n-\n- def get_finished(\n- self,\n- finished_gen_req_ids: List[int],\n- started_loading_req_ids: List[int],\n- ) -> tuple:\n- \"\"\"\n- Get finished offloading and onboarding request IDs.\n-\n- Parameters:\n- -----------\n- finished_gen_req_ids: List[int]\n- List of request IDs that have finished generation\n- started_loading_req_ids: List[int]\n- List of request IDs that have started loading\n-\n- Returns:\n- --------\n- tuple\n- A tuple of (finished_offloading, finished_onboarding) request ID lists\n- \"\"\"\n- ...\n-\n- def submit_offload_on_event(self, event: int) -> None:\n- \"\"\"\n- Submit offload operations to be executed when the given event completes.\n-\n- Parameters:\n- -----------\n- event: int\n- Raw CUDA event handle\n- \"\"\"\n- ...\n-\n-\n-class PyTrtllmKvConnectorLeader:\n- \"\"\"\n- TensorRT-LLM KV connector leader for KVBM integration.\n-\n- This class handles KV cache coordination on the leader side for TRT-LLM,\n- including slot management, token matching, and metadata building.\n- \"\"\"\n-\n- def __init__(\n- self,\n- worker_id: int,\n- drt: Optional[Any],\n- page_size: int,\n- leader: Any,\n- consolidator_trtllm_endpoint: Optional[str] = None,\n- consolidator_output_endpoint: Optional[str] = None,\n- ) -> None:\n- \"\"\"\n- Create a PyTrtllmKvConnectorLeader instance.\n-\n- Parameters:\n- -----------\n- worker_id: int\n- The worker ID for this leader\n- drt: Optional[Any]\n- The distributed runtime object (currently unused)\n- page_size: int\n- Page size for blocks\n- leader: Any\n- The KVBM leader object (PyKvbmLeader)\n- consolidator_trtllm_endpoint: Optional[str]\n- TRT-LLM consolidator endpoint\n- consolidator_output_endpoint: Optional[str]\n- Output consolidator endpoint\n- \"\"\"\n- ...\n-\n- def get_num_new_matched_tokens(\n- self,\n- request_id: str,\n- request_num_tokens: int,\n- num_computed_tokens: int,\n- ) -> tuple:\n- \"\"\"\n- Get the number of newly matched tokens for a request.\n-\n- Parameters:\n- -----------\n- request_id: str\n- The request identifier\n- request_num_tokens: int\n- Total number of tokens in the request\n- num_computed_tokens: int\n- Number of already computed tokens\n-\n- Returns:\n- --------\n- tuple\n- A tuple of (num_matched_tokens, is_complete)\n- \"\"\"\n- ...\n-\n- def update_state_after_alloc(\n- self,\n- request_id: str,\n- block_ids: List[int],\n- context_current_position: int,\n- ) -> None:\n- \"\"\"\n- Update state after block allocation.\n-\n- Parameters:\n- -----------\n- request_id: str\n- The request identifier\n- block_ids: List[int]\n- List of allocated block IDs\n- context_current_position: int\n- Current context position\n- \"\"\"\n- ...\n-\n- def build_connector_metadata(self, scheduler_output: SchedulerOutput) -> bytes:\n- \"\"\"\n- Build connector metadata from scheduler output.\n-\n- Parameters:\n- -----------\n- scheduler_output: SchedulerOutput\n- The scheduler output\n-\n- Returns:\n- --------\n- bytes\n- Serialized connector metadata\n- \"\"\"\n- ...\n-\n- def request_finished(self, request_id: str, block_ids: List[int]) -> bool:\n- \"\"\"\n- Mark a request as finished.\n-\n- Parameters:\n- -----------\n- request_id: str\n- The request identifier\n- block_ids: List[int]\n- List of block IDs used by the request\n-\n- Returns:\n- --------\n- bool\n- True if the request was successfully marked as finished\n- \"\"\"\n- ...\n-\n- def has_slot(self, request_id: str) -> bool:\n- \"\"\"\n- Check if a slot exists for the given request.\n-\n- Parameters:\n- -----------\n- request_id: str\n- The request identifier\n-\n- Returns:\n- --------\n- bool\n- True if a slot exists\n- \"\"\"\n- ...\n-\n- def create_slot(self, request: KvbmRequest, tokens: List[int]) -> None:\n- \"\"\"\n- Create a slot for a request.\n-\n- Parameters:\n- -----------\n- request: KvbmRequest\n- The KVBM request object\n- tokens: List[int]\n- List of tokens for the request\n- \"\"\"\n- ...\ndiff --git a/lib/bindings/kvbm/python/kvbm/trtllm_integration/__init__.py b/lib/bindings/kvbm/python/kvbm/trtllm_integration/__init__.py\ndeleted file mode 100644\nindex e5725ea5a481..000000000000\n--- a/lib/bindings/kvbm/python/kvbm/trtllm_integration/__init__.py\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n-# SPDX-License-Identifier: Apache-2.0\ndiff --git a/lib/bindings/kvbm/python/kvbm/trtllm_integration/connector/__init__.py b/lib/bindings/kvbm/python/kvbm/trtllm_integration/connector/__init__.py\ndeleted file mode 100644\nindex a2ffe44601f1..000000000000\n--- a/lib/bindings/kvbm/python/kvbm/trtllm_integration/connector/__init__.py\n+++ /dev/null\n@@ -1,7 +0,0 @@\n-# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n-# SPDX-License-Identifier: Apache-2.0\n-\n-from .kvbm_connector_leader import DynamoKVBMConnectorLeader\n-from .kvbm_connector_worker import DynamoKVBMConnectorWorker\n-\n-__all__ = [\"DynamoKVBMConnectorLeader\", \"DynamoKVBMConnectorWorker\"]\ndiff --git a/lib/bindings/kvbm/python/kvbm/trtllm_integration/connector/kvbm_connector_leader.py b/lib/bindings/kvbm/python/kvbm/trtllm_integration/connector/kvbm_connector_leader.py\ndeleted file mode 100644\nindex 527387edd361..000000000000\n--- a/lib/bindings/kvbm/python/kvbm/trtllm_integration/connector/kvbm_connector_leader.py\n+++ /dev/null\n@@ -1,227 +0,0 @@\n-# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n-# SPDX-License-Identifier: Apache-2.0\n-\n-import logging\n-import os\n-from typing import List, Optional\n-\n-import tensorrt_llm\n-from kvbm import KvbmLeader\n-from kvbm.trtllm_integration.consolidator_config import get_consolidator_mode, is_truthy\n-from kvbm.trtllm_integration.rust import KvbmRequest\n-from kvbm.trtllm_integration.rust import KvConnectorLeader as RustKvConnectorLeader\n-from kvbm.trtllm_integration.rust import SchedulerOutput as RustSchedulerOutput\n-from kvbm.utils import is_dyn_runtime_enabled, nvtx_annotate\n-from tensorrt_llm._torch.pyexecutor.connectors.kv_cache_connector import (\n- KvCacheConnectorScheduler,\n- SchedulerOutput,\n-)\n-from tensorrt_llm.bindings.internal.batch_manager import LlmRequest\n-from tensorrt_llm.llmapi.llm_args import TorchLlmArgs\n-\n-logger = logging.getLogger(__name__)\n-\n-DistributedRuntime = None\n-if is_dyn_runtime_enabled():\n- from dynamo.runtime import DistributedRuntime\n-\n-\n-class DynamoKVBMConnectorLeader(KvCacheConnectorScheduler):\n- def __init__(\n- self,\n- llm_args: TorchLlmArgs,\n- consolidator_trtllm_endpoint: Optional[str] = None,\n- ):\n- super().__init__(llm_args)\n-\n- drt: Optional[object] = None\n- if is_dyn_runtime_enabled():\n- drt = DistributedRuntime.detached()\n-\n- self.drt = drt\n-\n- mappings = self._llm_args.parallel_config.to_mapping()\n-\n- world_size = mappings.world_size\n- self.block_size = self._llm_args.kv_cache_config.tokens_per_block\n-\n- # Set bytes_per_block to 0, because we will retrieve the actual value from the worker side.\n- leader = KvbmLeader(world_size, drt=self.drt)\n-\n- # Check if consolidator is enabled first\n- consolidator_enabled = is_truthy(\n- os.getenv(\"DYN_KVBM_KV_EVENTS_ENABLE_CONSOLIDATOR\", \"true\")\n- )\n-\n- trtllm_ep = None\n- consolidator_output_ep = None\n- consolidator_mode = None\n- if consolidator_enabled:\n- consolidator_mode = get_consolidator_mode()\n- # Get consolidator endpoint from environment variable\n- # DYN_KVBM_TRTLLM_ZMQ_PORT contains just the port number (e.g., \"20081\")\n- zmq_port = os.getenv(\"DYN_KVBM_TRTLLM_ZMQ_PORT\")\n-\n- if zmq_port:\n- try:\n- port_num = int(zmq_port)\n- trtllm_ep = f\"tcp://127.0.0.1:{port_num}\"\n- # Calculate consolidator output endpoint\n- # Derive from KVBM leader port (default 56001) + 1000 offset\n- kvbm_pub_port_str = os.getenv(\n- \"DYN_KVBM_LEADER_ZMQ_PUB_PORT\", \"56001\"\n- )\n- kvbm_pub_port = int(kvbm_pub_port_str)\n- # Use 1000 as the offset. This needs to be aligned with the offset used in the consolidator config.\n- consolidator_port_offset = 1000\n- output_port = kvbm_pub_port + consolidator_port_offset\n- consolidator_output_ep = f\"tcp://0.0.0.0:{output_port}\"\n-\n- logger.info(\n- f\"KV Event Consolidator: Using ZMQ port from DYN_KVBM_TRTLLM_ZMQ_PORT - trtllm={trtllm_ep}, output={consolidator_output_ep} (derived from KVBM port {kvbm_pub_port})\"\n- )\n- except ValueError as e:\n- logger.error(\n- f\"KV Event Consolidator: Invalid port value - {e}. Consolidator will not be enabled.\"\n- )\n- trtllm_ep = None\n- consolidator_output_ep = None\n- else:\n- logger.error(\n- \"KV Event Consolidator: No ZMQ port found - consolidator will not be enabled. \"\n- \"Set this environment variable before running TensorRT-LLM:\\n\"\n- \" export DYN_KVBM_TRTLLM_ZMQ_PORT=20081\"\n- )\n- trtllm_ep = None\n- consolidator_output_ep = None\n- else:\n- logger.info(\n- \"KV Event Consolidator disabled via DYN_KVBM_KV_EVENTS_ENABLE_CONSOLIDATOR\"\n- )\n-\n- print(f\"KvConnectorLeader initialized with rank: {mappings.rank}\")\n- self._connector = RustKvConnectorLeader(\n- mappings.rank,\n- self.drt,\n- self.block_size,\n- leader,\n- consolidator_trtllm_endpoint=trtllm_ep,\n- consolidator_output_endpoint=consolidator_output_ep,\n- consolidator_mode=consolidator_mode,\n- )\n-\n- @nvtx_annotate(category=\"scheduler\")\n- def build_connector_meta(self, scheduler_output: SchedulerOutput) -> bytes:\n- \"\"\"\n- Build the metadata for the worker.\n- This is called by the KV Cache Manager when adding a sequence.\n- Args:\n- scheduler_output: The data for all inflight requests.\n- Returns:\n- The metadata for the workers.\n- \"\"\"\n- output = RustSchedulerOutput()\n-\n- for req in scheduler_output.new_requests:\n- if not hasattr(req, \"num_scheduled_tokens\"):\n- raise ValueError(\n- f\"\"\"num_scheduled_tokens is not found in the SchedulerOutput!\n- You're currently using TRTLLM {tensorrt_llm.__version__}\n- The mimimum supported version is 1.2.0rc2\"\"\"\n- )\n- output.add_new_request(\n- str(req.request_id),\n- req.new_tokens,\n- req.new_block_ids,\n- req.computed_position,\n- req.priorities, # Pass retention priorities for offload filtering\n- list(req.block_hashes),\n- )\n-\n- resumed_from_preemption = False\n- for req in scheduler_output.cached_requests:\n- output.add_cached_request(\n- str(req.request_id),\n- resumed_from_preemption,\n- req.new_tokens,\n- req.new_block_ids,\n- req.computed_position,\n[... diff truncated: 19 more file(s) not shown]\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(vllm): size DeepStack rows in the multimodal embedding cache budget\nLabels: external-contribution, size/M, backend::vllm, fix, multimodal\nFiles changed (2): components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py, components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py\n\n## Description (results removed)\n\n## Summary\n\nThe multimodal embedding cache could use more host memory than `multimodal_embedding_cache_capacity_gb`:\n\n- **Evicted entries were still saved.** An entry evicted in the same step that planned its save stayed in `saves`, so the worker stored an entry the scheduler no longer tracked. The eviction loop now removes it from `saves`.\n\n## Validation\n[results removed]\n## Related Issues\n\n- Closes #17244\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py b/components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py\nindex 664141c517ad..59c73e93f902 100644\n--- a/components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py\n+++ b/components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py\n@@ -201,6 +201,12 @@ def __init__(self, vllm_config: \"VllmConfig\", role: ECConnectorRole) -> None:\n [], dtype=vllm_config.model_config.dtype\n ).element_size()\n self._bytes_per_embed = hidden_size * dtype_bytes\n+ # vLLM >= 0.32 measures each modality's encoder output width at startup;\n+ # DeepStack models (e.g. Qwen3-VL) emit rows wider than the hidden size.\n+ measured_widths = getattr(transfer_config, \"mm_encoder_output_widths\", {})\n+ self._bytes_per_embed_by_modality = {\n+ modality: width * dtype_bytes for modality, width in measured_widths.items()\n+ }\n self._capacity_bytes = int(capacity_gb * 1024**3)\n \n self._cache_order: OrderedDict[str, int] = OrderedDict() # hash → size_bytes\n@@ -246,10 +252,12 @@ def __init__(self, vllm_config: \"VllmConfig\", role: ECConnectorRole) -> None:\n \n logger.info(\n \"DynamoMultimodalEmbeddingCacheConnector initialized: \"\n- \"capacity_gb=%.2f, capacity_bytes=%d, bytes_per_embed=%d\",\n+ \"capacity_gb=%.2f, capacity_bytes=%d, bytes_per_embed=%d, \"\n+ \"bytes_per_embed_by_modality=%s\",\n capacity_gb,\n self._capacity_bytes,\n self._bytes_per_embed,\n+ self._bytes_per_embed_by_modality,\n )\n \n # ==============================\n@@ -295,9 +303,13 @@ def update_state_after_alloc(self, request: \"Request\", index: int) -> None:\n then mark for GPU→CPU save so the worker persists the newly\n computed embedding. Silently skips items larger than total capacity.\n \"\"\"\n- mm_hash: str = request.mm_features[index].identifier\n+ feature = request.mm_features[index]\n+ mm_hash: str = feature.identifier\n num_embeds: int = request.get_num_encoder_embeds(index)\n- size_bytes: int = num_embeds * self._bytes_per_embed\n+ bytes_per_embed = self._bytes_per_embed_by_modality.get(\n+ feature.modality, self._bytes_per_embed\n+ )\n+ size_bytes: int = num_embeds * bytes_per_embed\n \n if mm_hash in self._cache_order:\n self._cache_order.move_to_end(mm_hash)\n@@ -322,6 +334,8 @@ def update_state_after_alloc(self, request: \"Request\", index: int) -> None:\n evicted_hash, evicted_bytes = self._cache_order.popitem(last=False)\n self._num_used_bytes -= evicted_bytes\n self._evicts_this_step.add(evicted_hash)\n+ # The worker evicts before it saves, so drop any save planned this step.\n+ self._saves_this_step.discard(evicted_hash)\n num_evicted += 1\n \n self._cache_order[mm_hash] = size_bytes\ndiff --git a/components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py b/components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py\nindex d866eb3055f7..fd18f909a5dd 100644\n--- a/components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py\n+++ b/components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py\n@@ -20,23 +20,33 @@\n ]\n \n \n-def _make_vllm_config(capacity_gb: float = 1.0) -> MagicMock:\n+def _make_vllm_config(\n+ capacity_gb: float = 1.0, encoder_output_widths: dict[str, int] | None = None\n+) -> MagicMock:\n config = MagicMock()\n config.ec_transfer_config.ec_connector_extra_config = {\n \"multimodal_embedding_cache_capacity_gb\": capacity_gb,\n }\n+ config.ec_transfer_config.mm_encoder_output_widths = encoder_output_widths or {}\n config.model_config.get_hidden_size.return_value = 4096\n config.model_config.dtype = torch.float16\n config.parallel_config.data_parallel_rank = 0\n return config\n \n \n-def _make_request(hashes_and_embeds: list[tuple[str, int]]) -> MagicMock:\n+# What vLLM measures for a DeepStack model with three levels (e.g. Qwen3-VL).\n+_DEEPSTACK_WIDTHS = {\"image\": 4 * 4096, \"video\": 4 * 4096}\n+\n+\n+def _make_request(\n+ hashes_and_embeds: list[tuple[str, int]], modality: str = \"image\"\n+) -> MagicMock:\n request = MagicMock()\n features = []\n for h, _ in hashes_and_embeds:\n f = MagicMock()\n f.identifier = h\n+ f.modality = modality\n features.append(f)\n request.mm_features = features\n \n@@ -211,6 +221,64 @@ def test_skip_oversized_item(self):\n assert \"huge_hash\" not in conn._cache_order\n \n \n+class TestEmbeddingRowSize:\n+ def _make_connector(self, encoder_output_widths: dict[str, int]):\n+ with patch.object(mod.ECConnectorBase, \"__init__\", return_value=None):\n+ return mod.DynamoMultimodalEmbeddingCacheConnector(\n+ vllm_config=_make_vllm_config(\n+ encoder_output_widths=encoder_output_widths\n+ ),\n+ role=MagicMock(),\n+ )\n+\n+ def _run_worker_step(\n+ self,\n+ conn,\n+ meta: \"mod.MultimodalEmbeddingCacheConnectorMetadata\",\n+ encoder_cache: dict[str, torch.Tensor],\n+ ) -> None:\n+ # Same order as vLLM's model runner: loads and evicts, then one save\n+ # per embedding the encoder computed this step.\n+ with patch.object(conn, \"_get_connector_metadata\", return_value=meta):\n+ conn.start_load_caches(encoder_cache=encoder_cache)\n+ for mm_hash in encoder_cache:\n+ conn.save_caches(encoder_cache=encoder_cache, mm_hash=mm_hash)\n+\n+ def test_budget_uses_measured_width_per_modality(self):\n+ conn = self._make_connector(_DEEPSTACK_WIDTHS)\n+ for mm_hash, modality in ((\"v\", \"video\"), (\"a\", \"audio\")):\n+ conn.update_state_after_alloc(\n+ _make_request([(mm_hash, 10)], modality=modality), 0\n+ )\n+\n+ assert dict(conn._cache_order) == {\n+ \"v\": 10 * 4 * 4096 * 2,\n+ \"a\": 10 * 4096 * 2,\n+ }\n+\n+ def test_deepstack_capacity_bounds_stored_bytes(self):\n+ conn = self._make_connector(_DEEPSTACK_WIDTHS)\n+ image_bytes = 10 * 4 * 4096 * 2\n+ conn._capacity_bytes = 2 * image_bytes\n+\n+ for mm_hash in (\"a\", \"b\", \"c\"):\n+ conn.update_state_after_alloc(_make_request([(mm_hash, 10)]), 0)\n+ meta = conn.build_connector_meta(MagicMock())\n+\n+ assert meta.evicts == [\"a\"]\n+ assert sorted(meta.saves) == [\"b\", \"c\"]\n+ assert conn._num_used_bytes == 2 * image_bytes\n+\n+ encoder_cache = {\n+ mm_hash: torch.zeros(10, 4 * 4096, dtype=torch.float16)\n+ for mm_hash in (\"a\", \"b\", \"c\")\n+ }\n+ self._run_worker_step(conn, meta, encoder_cache)\n+\n+ assert set(conn._cpu_store) == {\"b\", \"c\"}\n+ assert sum(t.nbytes for t in conn._cpu_store.values()) == 2 * image_bytes\n+\n+\n class TestSchedulerMetrics:\n \"\"\"Prometheus metrics emitted by the scheduler-role connector.\"\"\"\n \n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(vllm): size DeepStack rows in the multimodal embedding cache budget\nLabels: external-contribution, size/M, backend::vllm, fix, multimodal\nFiles changed (2): components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py, components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py\n\n## Description (results removed)\n\n## Summary\n\nThe multimodal embedding cache could use more host memory than `multimodal_embedding_cache_capacity_gb`:\n\n- **Evicted entries were still saved.** An entry evicted in the same step that planned its save stayed in `saves`, so the worker stored an entry the scheduler no longer tracked. The eviction loop now removes it from `saves`.\n\n## Validation\n[results removed]\n## Related Issues\n\n- Closes #17244\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py b/components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py\nindex 664141c517ad..b15582584ced 100644\n--- a/components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py\n+++ b/components/src/dynamo/vllm/multimodal_utils/multimodal_embedding_cache_connector.py\n@@ -46,6 +46,28 @@ def _get_device(vllm_config: \"VllmConfig\") -> str:\n return \"cuda\"\n \n \n+_VISION_MODALITIES = frozenset({\"image\", \"video\"})\n+\n+\n+def _deepstack_vision_width(hf_config) -> int | None:\n+ \"\"\"Row width of DeepStack image/video embeddings, or None if not DeepStack.\n+\n+ DeepStack models (e.g. Qwen3-VL) concatenate one feature map per\n+ DeepStack level onto each visual token, so a stored image or video row\n+ is out_hidden_size * (1 + len(deepstack_visual_indexes)) wide instead of\n+ the text hidden size. Qwen3-Omni nests its vision config under\n+ thinker_config.\n+ \"\"\"\n+ for config in (hf_config, getattr(hf_config, \"thinker_config\", None)):\n+ vision_config = getattr(config, \"vision_config\", None)\n+ deepstack_visual_indexes = getattr(\n+ vision_config, \"deepstack_visual_indexes\", None\n+ )\n+ if deepstack_visual_indexes:\n+ return vision_config.out_hidden_size * (1 + len(deepstack_visual_indexes))\n+ return None\n+\n+\n @dataclass\n class MultimodalEmbeddingCacheConnectorMetadata(ECConnectorMetadata):\n \"\"\"Commands from scheduler to worker for CPU embedding cache management.\"\"\"\n@@ -196,11 +218,17 @@ def __init__(self, vllm_config: \"VllmConfig\", role: ECConnectorRole) -> None:\n \n # --- Scheduler-side: logical LRU for CPU embedding cache ---\n # Mirrors EncoderCacheManager but for the CPU tier, tracking bytes.\n- hidden_size = vllm_config.model_config.get_hidden_size()\n dtype_bytes = torch.tensor(\n [], dtype=vllm_config.model_config.dtype\n ).element_size()\n- self._bytes_per_embed = hidden_size * dtype_bytes\n+ self._bytes_per_embed = vllm_config.model_config.get_hidden_size() * dtype_bytes\n+ # Audio rows (Qwen3-Omni) stay at the hidden size.\n+ vision_width = _deepstack_vision_width(vllm_config.model_config.hf_config)\n+ self._bytes_per_vision_embed = (\n+ self._bytes_per_embed\n+ if vision_width is None\n+ else vision_width * dtype_bytes\n+ )\n self._capacity_bytes = int(capacity_gb * 1024**3)\n \n self._cache_order: OrderedDict[str, int] = OrderedDict() # hash → size_bytes\n@@ -243,13 +271,16 @@ def __init__(self, vllm_config: \"VllmConfig\", role: ECConnectorRole) -> None:\n \n # --- Worker-side: dumb CPU tensor store ---\n self._cpu_store: dict[str, torch.Tensor] = {}\n+ self._warned_row_bytes = False\n \n logger.info(\n \"DynamoMultimodalEmbeddingCacheConnector initialized: \"\n- \"capacity_gb=%.2f, capacity_bytes=%d, bytes_per_embed=%d\",\n+ \"capacity_gb=%.2f, capacity_bytes=%d, bytes_per_embed=%d, \"\n+ \"bytes_per_vision_embed=%d\",\n capacity_gb,\n self._capacity_bytes,\n self._bytes_per_embed,\n+ self._bytes_per_vision_embed,\n )\n \n # ==============================\n@@ -295,9 +326,15 @@ def update_state_after_alloc(self, request: \"Request\", index: int) -> None:\n then mark for GPU→CPU save so the worker persists the newly\n computed embedding. Silently skips items larger than total capacity.\n \"\"\"\n- mm_hash: str = request.mm_features[index].identifier\n+ feature = request.mm_features[index]\n+ mm_hash: str = feature.identifier\n num_embeds: int = request.get_num_encoder_embeds(index)\n- size_bytes: int = num_embeds * self._bytes_per_embed\n+ bytes_per_embed = (\n+ self._bytes_per_vision_embed\n+ if feature.modality in _VISION_MODALITIES\n+ else self._bytes_per_embed\n+ )\n+ size_bytes: int = num_embeds * bytes_per_embed\n \n if mm_hash in self._cache_order:\n self._cache_order.move_to_end(mm_hash)\n@@ -322,6 +359,9 @@ def update_state_after_alloc(self, request: \"Request\", index: int) -> None:\n evicted_hash, evicted_bytes = self._cache_order.popitem(last=False)\n self._num_used_bytes -= evicted_bytes\n self._evicts_this_step.add(evicted_hash)\n+ # The worker applies evicts before the encoder runs, so a save\n+ # planned earlier this step would store an untracked entry.\n+ self._saves_this_step.discard(evicted_hash)\n num_evicted += 1\n \n self._cache_order[mm_hash] = size_bytes\n@@ -396,4 +436,19 @@ def save_caches(\n mm_hash,\n )\n return\n- self._cpu_store[mm_hash] = encoder_cache[mm_hash].cpu()\n+ embedding = encoder_cache[mm_hash].cpu()\n+ self._cpu_store[mm_hash] = embedding\n+\n+ # The scheduler budgets from model config; flag models whose stored\n+ # rows differ so capacity_gb is not silently exceeded.\n+ row_bytes = embedding.shape[-1] * embedding.element_size()\n+ budgets = (self._bytes_per_embed, self._bytes_per_vision_embed)\n+ if row_bytes not in budgets and not self._warned_row_bytes:\n+ self._warned_row_bytes = True\n+ logger.warning(\n+ \"Embedding cache budgets %d bytes per embedding (%d for image \"\n+ \"and video), but encoder output rows are %d bytes; host memory \"\n+ \"use will not match multimodal_embedding_cache_capacity_gb.\",\n+ *budgets,\n+ row_bytes,\n+ )\ndiff --git a/components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py b/components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py\nindex d866eb3055f7..5367c10510a8 100644\n--- a/components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py\n+++ b/components/src/dynamo/vllm/tests/multimodal_utils/test_vllm_multimodal_embedding_cache_connector.py\n@@ -20,23 +20,45 @@\n ]\n \n \n-def _make_vllm_config(capacity_gb: float = 1.0) -> MagicMock:\n+def _make_vllm_config(\n+ capacity_gb: float = 1.0, hf_config: SimpleNamespace | None = None\n+) -> MagicMock:\n config = MagicMock()\n config.ec_transfer_config.ec_connector_extra_config = {\n \"multimodal_embedding_cache_capacity_gb\": capacity_gb,\n }\n config.model_config.get_hidden_size.return_value = 4096\n+ config.model_config.hf_config = (\n+ SimpleNamespace() if hf_config is None else hf_config\n+ )\n config.model_config.dtype = torch.float16\n config.parallel_config.data_parallel_rank = 0\n return config\n \n \n-def _make_request(hashes_and_embeds: list[tuple[str, int]]) -> MagicMock:\n+def _deepstack_hf_config() -> SimpleNamespace:\n+ # Qwen3-VL-235B-A22B: out_hidden_size 4096, three DeepStack levels.\n+ return SimpleNamespace(\n+ vision_config=SimpleNamespace(\n+ out_hidden_size=4096, deepstack_visual_indexes=[8, 16, 24]\n+ )\n+ )\n+\n+\n+def _omni_hf_config() -> SimpleNamespace:\n+ # Qwen3-Omni keeps its DeepStack vision config under the thinker.\n+ return SimpleNamespace(thinker_config=_deepstack_hf_config())\n+\n+\n+def _make_request(\n+ hashes_and_embeds: list[tuple[str, int]], modality: str = \"image\"\n+) -> MagicMock:\n request = MagicMock()\n features = []\n for h, _ in hashes_and_embeds:\n f = MagicMock()\n f.identifier = h\n+ f.modality = modality\n features.append(f)\n request.mm_features = features\n \n@@ -211,6 +233,113 @@ def test_skip_oversized_item(self):\n assert \"huge_hash\" not in conn._cache_order\n \n \n+class TestEmbeddingRowSize:\n+ \"\"\"The per-embedding byte budget must match the encoder-cache row width.\"\"\"\n+\n+ def _make_connector(self, hf_config: SimpleNamespace | None = None):\n+ with patch.object(mod.ECConnectorBase, \"__init__\", return_value=None):\n+ return mod.DynamoMultimodalEmbeddingCacheConnector(\n+ vllm_config=_make_vllm_config(hf_config=hf_config),\n+ role=MagicMock(),\n+ )\n+\n+ def _run_worker_step(\n+ self,\n+ conn,\n+ meta: \"mod.MultimodalEmbeddingCacheConnectorMetadata\",\n+ encoder_cache: dict[str, torch.Tensor],\n+ ) -> None:\n+ # Same order as vLLM's model runner: loads and evicts, then one save\n+ # per embedding the encoder computed this step.\n+ with patch.object(conn, \"_get_connector_metadata\", return_value=meta):\n+ conn.start_load_caches(encoder_cache=encoder_cache)\n+ for mm_hash in encoder_cache:\n+ conn.save_caches(encoder_cache=encoder_cache, mm_hash=mm_hash)\n+\n+ def _save_all(self, conn, encoder_cache: dict[str, torch.Tensor]) -> None:\n+ meta = mod.MultimodalEmbeddingCacheConnectorMetadata(saves=list(encoder_cache))\n+ self._run_worker_step(conn, meta, encoder_cache)\n+\n+ @pytest.mark.parametrize(\n+ \"vision_config\",\n+ [\n+ SimpleNamespace(out_hidden_size=4096),\n+ SimpleNamespace(out_hidden_size=4096, deepstack_visual_indexes=[]),\n+ ],\n+ ids=[\"no_deepstack_attr\", \"empty_deepstack\"],\n+ )\n+ def test_vision_model_without_deepstack_uses_hidden_size(self, vision_config):\n+ conn = self._make_connector(SimpleNamespace(vision_config=vision_config))\n+ assert conn._bytes_per_vision_embed == 4096 * 2\n+\n+ @pytest.mark.parametrize(\n+ \"hf_config\",\n+ [_deepstack_hf_config(), _omni_hf_config()],\n+ ids=[\"qwen3_vl\", \"qwen3_omni\"],\n+ )\n+ def test_budget_follows_modality(self, hf_config):\n+ conn = self._make_connector(hf_config)\n+ for mm_hash, modality in ((\"i\", \"image\"), (\"v\", \"video\"), (\"a\", \"audio\")):\n+ conn.update_state_after_alloc(\n+ _make_request([(mm_hash, 10)], modality=modality), 0\n+ )\n+\n+ # Image and video rows carry the DeepStack levels; audio rows do not.\n+ assert dict(conn._cache_order) == {\n+ \"i\": 10 * 4 * 4096 * 2,\n+ \"v\": 10 * 4 * 4096 * 2,\n+ \"a\": 10 * 4096 * 2,\n+ }\n+\n+ def test_deepstack_capacity_bounds_stored_bytes(self):\n+ conn = self._make_connector(_deepstack_hf_config())\n+ image_bytes = 10 * 4 * 4096 * 2\n+ conn._capacity_bytes = 2 * image_bytes\n+\n+ # Three new images in one step with room for two: \"a\" is evicted\n+ # in the same step it was planned for saving.\n+ for mm_hash in (\"a\", \"b\", \"c\"):\n+ conn.update_state_after_alloc(_make_request([(mm_hash, 10)]), 0)\n+ meta = conn.build_connector_meta(MagicMock())\n+\n+ assert meta.evicts == [\"a\"]\n+ assert sorted(meta.saves) == [\"b\", \"c\"]\n+ assert conn._num_used_bytes == 2 * image_bytes\n+\n+ encoder_cache = {\n+ mm_hash: torch.zeros(10, 4 * 4096, dtype=torch.float16)\n+ for mm_hash in (\"a\", \"b\", \"c\")\n+ }\n+ self._run_worker_step(conn, meta, encoder_cache)\n+\n+ assert set(conn._cpu_store) == {\"b\", \"c\"}\n+ assert sum(t.nbytes for t in conn._cpu_store.values()) == 2 * image_bytes\n+\n+ def test_matching_rows_do_not_warn(self):\n+ conn = self._make_connector(_omni_hf_config())\n+ encoder_cache = {\n+ \"image\": torch.zeros(3, 4 * 4096, dtype=torch.float16),\n+ \"audio\": torch.zeros(3, 4096, dtype=torch.float16),\n+ }\n+\n+ with patch.object(mod.logger, \"warning\") as warn:\n+ self._save_all(conn, encoder_cache)\n+\n+ warn.assert_not_called()\n+ assert set(conn._cpu_store) == {\"image\", \"audio\"}\n+\n+ def test_wider_rows_than_budget_warn_once(self):\n+ conn = self._make_connector()\n+ rows = torch.zeros(3, 4 * 4096, dtype=torch.float16)\n+\n+ with patch.object(mod.logger, \"warning\") as warn:\n+ self._save_all(conn, {\"a\": rows, \"b\": rows.clone()})\n+\n+ warn.assert_called_once()\n+ assert warn.call_args[0][1:] == (4096 * 2, 4096 * 2, 4 * 4096 * 2)\n+ assert set(conn._cpu_store) == {\"a\", \"b\"}\n+\n+\n class TestSchedulerMetrics:\n \"\"\"Prometheus metrics emitted by the scheduler-role connector.\"\"\"\n \n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(router): forward the conditional-disagg bypass marker only on request\nLabels: documentation, external-contribution, size/L, fix, router\nFiles changed (1): lib/llm/src/kv_router/prefill_router/mod.rs\n\n## Description (results removed)\n\n## Overview:\n\nThis PR forwards the marker only when the client asked for it in `nvext.annotations`, the same contract as `request_id`. Default clients never see it.\n\n## Details:\n\n- `prefill_router/mod.rs`: the existing guard still strips client-supplied copies of the marker (clients cannot force the bypass); whether anything was stripped is remembered as the opt-in. `with_bypass_marker` prepends the frame only when that flag is set.\n- Tests: `bypass_marker_frame_precedes_engine_output_when_requested` (pins the frame shape: `event:` name, no data, `: true` comment, ahead of engine output) and `generate_forwards_bypass_marker_only_to_opted_in_clients` (end to end: process-local runtime, real KV router and routing host over a recording dispatch; asserts the opted-in client gets the marker first, the default client gets none, and the decode hop sees the router-owned marker exactly once in both cases).\n\nRepro: stream the same chat request twice on a disaggregated deployment so the second run has a cached prefix. The second run's first frame is `event: x-bypass-remote-prefill` / `: true`; `openai-python` 2.28.0 raises `JSONDecodeError`, `openai-node` 6.9.0 raises `SyntaxError`.\n\n`with_bypass_marker`, the `client_requested_bypass_marker` capture in `generate`, then the end-to-end test.\n\n## Related Issues\n\n- Closes #17267\n\n## Diff\n\n```diff\ndiff --git a/lib/llm/src/kv_router/prefill_router/mod.rs b/lib/llm/src/kv_router/prefill_router/mod.rs\nindex da2bed8335e9..550741c72d12 100644\n--- a/lib/llm/src/kv_router/prefill_router/mod.rs\n+++ b/lib/llm/src/kv_router/prefill_router/mod.rs\n@@ -349,6 +349,25 @@ impl PrefillRouterLifecycle for PrefillRouter {\n }\n }\n \n+/// Prepend the `x-bypass-remote-prefill` marker to a bypassed response stream\n+/// only when the client listed it in `nvext.annotations` (same contract as\n+/// `request_id`). It is an annotation-only frame, serialised as `event:` with\n+/// no `data:` line; the OpenAI Python and Node SDKs abort on it, so it is\n+/// never sent unrequested.\n+fn with_bypass_marker(\n+ response_stream: ManyOut>,\n+ client_requested: bool,\n+) -> Result>> {\n+ if !client_requested {\n+ return Ok(response_stream);\n+ }\n+ let ctx = response_stream.context();\n+ let annotation =\n+ Annotated::::from_annotation(BYPASS_REMOTE_PREFILL_ANNOTATION, &true)?;\n+ let merged = stream::once(async move { annotation }).chain(response_stream);\n+ Ok(ResponseStream::new(Box::pin(merged), ctx))\n+}\n+\n impl Drop for PrefillRouter {\n fn drop(&mut self) {\n tracing::debug!(\"Dropping PrefillRouter, cancelling background activation task\");\n@@ -378,8 +397,13 @@ impl\n // Conditional-disagg bypass is a router-owned decision. Drop any\n // client-supplied marker before the policy runs so normal disagg\n // requests cannot accidentally or maliciously skip remote prefill.\n+ // A client that lists the marker in `nvext.annotations` is only asking\n+ // to be told when the bypass happens (like `request_id`), so remember\n+ // that before the marker is removed.\n+ let annotations_before = req.annotations.len();\n req.annotations\n .retain(|annotation| annotation != BYPASS_REMOTE_PREFILL_ANNOTATION);\n+ let client_requested_bypass_marker = req.annotations.len() != annotations_before;\n \n // Save original max_tokens for decode\n let original_max_tokens = req.stop_conditions.max_tokens;\n@@ -470,13 +494,7 @@ impl\n let response_stream = decode_host\n .dispatch_kv_plan(conditional_request, decision.plan)\n .await?;\n- let ctx = response_stream.context();\n- let annotation = Annotated::::from_annotation(\n- BYPASS_REMOTE_PREFILL_ANNOTATION,\n- &true,\n- )?;\n- let merged = stream::once(async move { annotation }).chain(response_stream);\n- return Ok(ResponseStream::new(Box::pin(merged), ctx));\n+ return with_bypass_marker(response_stream, client_requested_bypass_marker);\n }\n Ok(None) => {\n (req, context) = conditional_request.into_parts();\n@@ -907,16 +925,20 @@ mod tests {\n }\n \n pub(super) fn active_conditional_router() -> Arc {\n+ active_conditional_router_with(KvRouterConfig {\n+ conditional_disagg_enabled: true,\n+ ..Default::default()\n+ })\n+ }\n+\n+ fn active_conditional_router_with(config: KvRouterConfig) -> Arc {\n let (_activation_tx, activation_rx) = oneshot::channel();\n let router = PrefillRouter::new(\n activation_rx,\n Arc::new(ModelManager::new()),\n RouterMode::KV,\n 16,\n- Some(KvRouterConfig {\n- conditional_disagg_enabled: true,\n- ..Default::default()\n- }),\n+ Some(config),\n None,\n None,\n SessionAffinityMode::Hard,\n@@ -1340,6 +1362,183 @@ mod tests {\n );\n }\n \n+ fn bypassed_stream() -> ManyOut> {\n+ let request = SingleIn::new(query_only_request());\n+ let output = Annotated::from_data(LLMEngineOutput {\n+ token_ids: vec![7],\n+ ..Default::default()\n+ });\n+ ResponseStream::new(\n+ Box::pin(stream::once(async move { output })),\n+ request.context(),\n+ )\n+ }\n+\n+ #[tokio::test]\n+ async fn bypass_marker_frame_precedes_engine_output_when_requested() {\n+ let mut stream = with_bypass_marker(bypassed_stream(), true).unwrap();\n+ let marker = stream.next().await.expect(\"marker frame\");\n+ assert_eq!(\n+ marker.event.as_deref(),\n+ Some(BYPASS_REMOTE_PREFILL_ANNOTATION)\n+ );\n+ assert!(marker.data.is_none());\n+ assert_eq!(marker.comment, Some(vec![\"true\".to_string()]));\n+ let output = stream.next().await.expect(\"engine output\");\n+ assert_eq!(output.data.map(|d| d.token_ids), Some(vec![7]));\n+ assert!(stream.next().await.is_none());\n+ }\n+\n+ #[derive(Default)]\n+ struct RecordingDecodeDispatch {\n+ annotations: Mutex>>,\n+ }\n+\n+ #[async_trait]\n+ impl\n+ dynamo_runtime::pipeline::StreamingDispatch>\n+ for RecordingDecodeDispatch\n+ {\n+ async fn generate(\n+ &self,\n+ request: SingleIn>,\n+ ) -> Result>, Error> {\n+ let (addressed, context) = request.transfer(());\n+ let (request, _, _) = addressed.into_parts();\n+ self.annotations.lock().push(request.annotations.clone());\n+ let output = Annotated::from_data(LLMEngineOutput {\n+ token_ids: vec![7],\n+ finish_reason: Some(FinishReason::Stop),\n+ ..Default::default()\n+ });\n+ Ok(ResponseStream::new(\n+ Box::pin(stream::once(async move { output })),\n+ context.context(),\n+ ))\n+ }\n+\n+ async fn generate_bidirectional(\n+ &self,\n+ _instance: dynamo_runtime::component::Instance,\n+ _address: String,\n+ _input: dynamo_runtime::pipeline::ManyIn,\n+ ) -> Result>, Error> {\n+ unreachable!(\"the routing host dispatches unary requests\")\n+ }\n+ }\n+\n+ #[tokio::test]\n+ async fn generate_forwards_bypass_marker_only_to_opted_in_clients() {\n+ use crate::kv_router::LlmDispatch;\n+ use crate::{kv_router::KvRouter, local_model::runtime_config::ModelRuntimeConfig};\n+ use dynamo_runtime::{DistributedRuntime, Runtime, distributed::DistributedConfig};\n+\n+ let runtime = Runtime::from_current().unwrap();\n+ let distributed =\n+ DistributedRuntime::new(runtime.clone(), DistributedConfig::process_local())\n+ .await\n+ .unwrap();\n+ let endpoint = distributed\n+ .namespace(\"conditional-bypass-marker\")\n+ .unwrap()\n+ .component(\"decode\")\n+ .unwrap()\n+ .endpoint(\"generate\");\n+ let client = endpoint.client().await.unwrap();\n+ endpoint.register_endpoint_instance().await.unwrap();\n+ let worker_id = client.wait_for_instances().await.unwrap()[0].id();\n+ let (_workers_tx, workers) =\n+ watch::channel(HashMap::from([(worker_id, ModelRuntimeConfig::default())]));\n+ let config = KvRouterConfig {\n+ skip_initial_worker_wait: true,\n+ use_kv_events: false,\n+ router_track_active_blocks: false,\n+ ..Default::default()\n+ };\n+ let chooser = KvRouter::new(\n+ endpoint,\n+ client.clone(),\n+ workers,\n+ None,\n+ 16,\n+ SelectionPolicySource::Registry,\n+ Some(config),\n+ None,\n+ \"decode\",\n+ None,\n+ false,\n+ None,\n+ None,\n+ )\n+ .await\n+ .unwrap();\n+ let dispatch = Arc::new(RecordingDecodeDispatch::default());\n+ let host = Arc::new(\n+ RoutingHost::builder(client, RouterMode::KV)\n+ .kv_router(Arc::new(chooser))\n+ .dispatch(Arc::clone(&dispatch) as LlmDispatch)\n+ .build()\n+ .await\n+ .unwrap(),\n+ );\n+ // No KV events in this test, so nothing is cached and the net-new ratio is\n+ // 1.0; a ratio threshold above 1.0 makes the ISL policy bypass every request.\n+ let router = active_conditional_router_with(KvRouterConfig {\n+ conditional_disagg_enabled: true,\n+ conditional_disagg_eff_isl_ratio_threshold: 2.0,\n+ ..Default::default()\n+ });\n+ assert!(router.decode_routing_host.set(host).is_ok());\n+ let downstream = Arc::new(QueryOnlyDecodeHost::default());\n+\n+ for opted_in in [false, true] {\n+ let mut request = query_only_request();\n+ request.annotations = if opted_in {\n+ vec![BYPASS_REMOTE_PREFILL_ANNOTATION.to_string()]\n+ } else {\n+ Vec::new()\n+ };\n+ let mut stream = router\n+ .generate(SingleIn::new(request), downstream.clone())\n+ .await\n+ .expect(\"conditional disagg should bypass to the decode host\");\n+ let first = stream.next().await.expect(\"first frame\");\n+ if opted_in {\n+ assert_eq!(\n+ first.event.as_deref(),\n+ Some(BYPASS_REMOTE_PREFILL_ANNOTATION)\n+ );\n+ assert!(first.data.is_none());\n+ let output = stream.next().await.expect(\"engine output\");\n+ assert_eq!(output.data.map(|d| d.token_ids), Some(vec![7]));\n+ } else {\n+ assert!(\n+ first.event.is_none(),\n+ \"default client must not get the marker\"\n+ );\n+ assert_eq!(first.data.map(|d| d.token_ids), Some(vec![7]));\n+ }\n+ assert!(stream.next().await.is_none());\n+ }\n+\n+ // The decode hop saw the router-owned marker exactly once per request:\n+ // the client-supplied copy was stripped and the router's copy added.\n+ let seen = dispatch.annotations.lock().clone();\n+ assert_eq!(seen.len(), 2);\n+ for annotations in &seen {\n+ assert_eq!(\n+ annotations\n+ .iter()\n+ .filter(|annotation| *annotation == BYPASS_REMOTE_PREFILL_ANNOTATION)\n+ .count(),\n+ 1\n+ );\n+ }\n+ assert_eq!(downstream.requests.load(Ordering::Relaxed), 0);\n+ drop(router);\n+ runtime.shutdown();\n+ }\n+\n #[test]\n fn decode_router_override_disables_overlap_and_prefill_tracking() {\n let override_config = build_decode_router_override(\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(router): forward the conditional-disagg bypass marker only on request\nLabels: documentation, external-contribution, size/L, fix, router\nFiles changed (1): lib/llm/src/kv_router/prefill_router/mod.rs\n\n## Description (results removed)\n\n## Overview:\n\nThis PR forwards the marker only when the client asked for it in `nvext.annotations`, the same contract as `request_id`. Default clients never see it.\n\n## Details:\n\n- `prefill_router/mod.rs`: the existing guard still strips client-supplied copies of the marker (clients cannot force the bypass); whether anything was stripped is remembered as the opt-in. `with_bypass_marker` prepends the frame only when that flag is set.\n- Tests: `bypass_marker_frame_precedes_engine_output_when_requested` (pins the frame shape: `event:` name, no data, `: true` comment, ahead of engine output) and `generate_forwards_bypass_marker_only_to_opted_in_clients` (end to end: process-local runtime, real KV router and routing host over a recording dispatch; asserts the opted-in client gets the marker first, the default client gets none, and the decode hop sees the router-owned marker exactly once in both cases).\n\nRepro: stream the same chat request twice on a disaggregated deployment so the second run has a cached prefix. The second run's first frame is `event: x-bypass-remote-prefill` / `: true`; `openai-python` 2.28.0 raises `JSONDecodeError`, `openai-node` 6.9.0 raises `SyntaxError`.\n\n`with_bypass_marker`, the `client_requested_bypass_marker` capture in `generate`, then the end-to-end test.\n\n## Related Issues\n\n- Closes #17267\n\n## Diff\n\n```diff\ndiff --git a/lib/llm/src/kv_router/prefill_router/mod.rs b/lib/llm/src/kv_router/prefill_router/mod.rs\nindex 59768efaad16..ebfc030d5b25 100644\n--- a/lib/llm/src/kv_router/prefill_router/mod.rs\n+++ b/lib/llm/src/kv_router/prefill_router/mod.rs\n@@ -349,6 +349,25 @@ impl PrefillRouterLifecycle for PrefillRouter {\n }\n }\n \n+/// Prepend the `x-bypass-remote-prefill` marker to a bypassed response stream\n+/// only when the client listed it in `nvext.annotations` (same contract as\n+/// `request_id`). It is an annotation-only frame, serialised as `event:` with\n+/// no `data:` line; the OpenAI Python and Node SDKs abort on it, so it is\n+/// never sent unrequested.\n+fn with_bypass_marker(\n+ response_stream: ManyOut>,\n+ client_requested: bool,\n+) -> Result>> {\n+ if !client_requested {\n+ return Ok(response_stream);\n+ }\n+ let ctx = response_stream.context();\n+ let annotation =\n+ Annotated::::from_annotation(BYPASS_REMOTE_PREFILL_ANNOTATION, &true)?;\n+ let merged = stream::once(async move { annotation }).chain(response_stream);\n+ Ok(ResponseStream::new(Box::pin(merged), ctx))\n+}\n+\n impl Drop for PrefillRouter {\n fn drop(&mut self) {\n tracing::debug!(\"Dropping PrefillRouter, cancelling background activation task\");\n@@ -378,8 +397,13 @@ impl\n // Conditional-disagg bypass is a router-owned decision. Drop any\n // client-supplied marker before the policy runs so normal disagg\n // requests cannot accidentally or maliciously skip remote prefill.\n+ // A client that lists the marker in `nvext.annotations` is only asking\n+ // to be told when the bypass happens (like `request_id`), so remember\n+ // that before the marker is removed.\n+ let annotations_before = req.annotations.len();\n req.annotations\n .retain(|annotation| annotation != BYPASS_REMOTE_PREFILL_ANNOTATION);\n+ let client_requested_bypass_marker = req.annotations.len() != annotations_before;\n \n // Save original max_tokens for decode\n let original_max_tokens = req.stop_conditions.max_tokens;\n@@ -470,13 +494,7 @@ impl\n let response_stream = decode_host\n .dispatch_kv_plan(conditional_request, decision.plan)\n .await?;\n- let ctx = response_stream.context();\n- let annotation = Annotated::::from_annotation(\n- BYPASS_REMOTE_PREFILL_ANNOTATION,\n- &true,\n- )?;\n- let merged = stream::once(async move { annotation }).chain(response_stream);\n- return Ok(ResponseStream::new(Box::pin(merged), ctx));\n+ return with_bypass_marker(response_stream, client_requested_bypass_marker);\n }\n Ok(None) => {\n (req, context) = conditional_request.into_parts();\n@@ -900,16 +918,20 @@ mod tests {\n }\n \n pub(super) fn active_conditional_router() -> Arc {\n+ active_conditional_router_with(KvRouterConfig {\n+ conditional_disagg_enabled: true,\n+ ..Default::default()\n+ })\n+ }\n+\n+ fn active_conditional_router_with(config: KvRouterConfig) -> Arc {\n let (_activation_tx, activation_rx) = oneshot::channel();\n let router = PrefillRouter::new(\n activation_rx,\n Arc::new(ModelManager::new()),\n RouterMode::KV,\n 16,\n- Some(KvRouterConfig {\n- conditional_disagg_enabled: true,\n- ..Default::default()\n- }),\n+ Some(config),\n None,\n None,\n SessionAffinityMode::Hard,\n@@ -1332,6 +1354,186 @@ mod tests {\n );\n }\n \n+ fn bypassed_stream() -> ManyOut> {\n+ let request = SingleIn::new(query_only_request());\n+ let output = Annotated::from_data(LLMEngineOutput {\n+ token_ids: vec![7],\n+ ..Default::default()\n+ });\n+ ResponseStream::new(\n+ Box::pin(stream::once(async move { output })),\n+ request.context(),\n+ )\n+ }\n+\n+ #[tokio::test]\n+ async fn bypass_marker_frame_precedes_engine_output_when_requested() {\n+ let mut stream = with_bypass_marker(bypassed_stream(), true).unwrap();\n+ let marker = stream.next().await.expect(\"marker frame\");\n+ assert_eq!(\n+ marker.event.as_deref(),\n+ Some(BYPASS_REMOTE_PREFILL_ANNOTATION)\n+ );\n+ assert!(marker.data.is_none());\n+ assert_eq!(marker.comment, Some(vec![\"true\".to_string()]));\n+ let output = stream.next().await.expect(\"engine output\");\n+ assert_eq!(output.data.map(|d| d.token_ids), Some(vec![7]));\n+ assert!(stream.next().await.is_none());\n+ }\n+\n+ #[derive(Default)]\n+ struct RecordingDecodeDispatch {\n+ annotations: Mutex>>,\n+ }\n+\n+ #[async_trait]\n+ impl\n+ dynamo_runtime::pipeline::StreamingDispatch>\n+ for RecordingDecodeDispatch\n+ {\n+ async fn generate(\n+ &self,\n+ request: SingleIn>,\n+ ) -> Result>, Error> {\n+ let (addressed, context) = request.transfer(());\n+ let (request, _, _) = addressed.into_parts();\n+ self.annotations.lock().push(request.annotations.clone());\n+ let output = Annotated::from_data(LLMEngineOutput {\n+ token_ids: vec![7],\n+ finish_reason: Some(FinishReason::Stop),\n+ ..Default::default()\n+ });\n+ Ok(ResponseStream::new(\n+ Box::pin(stream::once(async move { output })),\n+ context.context(),\n+ ))\n+ }\n+\n+ async fn generate_bidirectional(\n+ &self,\n+ _instance: dynamo_runtime::component::Instance,\n+ _address: String,\n+ _input: dynamo_runtime::pipeline::ManyIn,\n+ ) -> Result>, Error> {\n+ unreachable!(\"the routing host dispatches unary requests\")\n+ }\n+ }\n+\n+ #[tokio::test]\n+ async fn generate_forwards_bypass_marker_only_to_opted_in_clients() {\n+ use crate::{kv_router::KvRouter, local_model::runtime_config::ModelRuntimeConfig};\n+ use dynamo_runtime::{\n+ DistributedRuntime, Runtime,\n+ distributed::DistributedConfig,\n+ pipeline::{PushRouter, StreamingDispatch},\n+ };\n+\n+ let runtime = Runtime::from_current().unwrap();\n+ let distributed =\n+ DistributedRuntime::new(runtime.clone(), DistributedConfig::process_local())\n+ .await\n+ .unwrap();\n+ let endpoint = distributed\n+ .namespace(\"conditional-bypass-marker\")\n+ .unwrap()\n+ .component(\"decode\")\n+ .unwrap()\n+ .endpoint(\"generate\");\n+ let client = endpoint.client().await.unwrap();\n+ endpoint.register_endpoint_instance().await.unwrap();\n+ let worker_id = client.wait_for_instances().await.unwrap()[0].id();\n+ let (_workers_tx, workers) =\n+ watch::channel(HashMap::from([(worker_id, ModelRuntimeConfig::default())]));\n+ let config = KvRouterConfig {\n+ skip_initial_worker_wait: true,\n+ use_kv_events: false,\n+ router_track_active_blocks: false,\n+ ..Default::default()\n+ };\n+ let chooser = KvRouter::new(\n+ endpoint,\n+ client.clone(),\n+ workers,\n+ None,\n+ 16,\n+ SelectionPolicySource::Registry,\n+ Some(config),\n+ None,\n+ \"decode\",\n+ None,\n+ false,\n+ None,\n+ None,\n+ )\n+ .await\n+ .unwrap();\n+ let dispatch = Arc::new(RecordingDecodeDispatch::default());\n+ let inner = PushRouter::from_client_with_dispatch(\n+ client,\n+ RouterMode::KV,\n+ Arc::clone(&dispatch) as Arc>,\n+ )\n+ .await\n+ .unwrap();\n+ let host = Arc::new(RoutingHost::new(inner, Arc::new(chooser), None).unwrap());\n+ // No KV events in this test, so nothing is cached and the net-new ratio is\n+ // 1.0; a ratio threshold above 1.0 makes the ISL policy bypass every request.\n+ let router = active_conditional_router_with(KvRouterConfig {\n+ conditional_disagg_enabled: true,\n+ conditional_disagg_eff_isl_ratio_threshold: 2.0,\n+ ..Default::default()\n+ });\n+ assert!(router.decode_routing_host.set(host).is_ok());\n+ let downstream = Arc::new(QueryOnlyDecodeHost::default());\n+\n+ for opted_in in [false, true] {\n+ let mut request = query_only_request();\n+ request.annotations = if opted_in {\n+ vec![BYPASS_REMOTE_PREFILL_ANNOTATION.to_string()]\n+ } else {\n+ Vec::new()\n+ };\n+ let mut stream = router\n+ .generate(SingleIn::new(request), downstream.clone())\n+ .await\n+ .expect(\"conditional disagg should bypass to the decode host\");\n+ let first = stream.next().await.expect(\"first frame\");\n+ if opted_in {\n+ assert_eq!(\n+ first.event.as_deref(),\n+ Some(BYPASS_REMOTE_PREFILL_ANNOTATION)\n+ );\n+ assert!(first.data.is_none());\n+ let output = stream.next().await.expect(\"engine output\");\n+ assert_eq!(output.data.map(|d| d.token_ids), Some(vec![7]));\n+ } else {\n+ assert!(\n+ first.event.is_none(),\n+ \"default client must not get the marker\"\n+ );\n+ assert_eq!(first.data.map(|d| d.token_ids), Some(vec![7]));\n+ }\n+ assert!(stream.next().await.is_none());\n+ }\n+\n+ // The decode hop saw the router-owned marker exactly once per request:\n+ // the client-supplied copy was stripped and the router's copy added.\n+ let seen = dispatch.annotations.lock().clone();\n+ assert_eq!(seen.len(), 2);\n+ for annotations in &seen {\n+ assert_eq!(\n+ annotations\n+ .iter()\n+ .filter(|annotation| *annotation == BYPASS_REMOTE_PREFILL_ANNOTATION)\n+ .count(),\n+ 1\n+ );\n+ }\n+ assert_eq!(downstream.requests.load(Ordering::Relaxed), 0);\n+ drop(router);\n+ runtime.shutdown();\n+ }\n+\n #[test]\n fn decode_router_override_disables_overlap_and_prefill_tracking() {\n let override_config = build_decode_router_override(\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "B) fails"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(profiler): size Hub checkpoints from file metadata\nLabels: external-contribution, size/L, fix, planner\nFiles changed (2): components/src/dynamo/profiler/tests/unit/test_model_info.py, components/src/dynamo/profiler/utils/model_info.py\n\n## Description (results removed)\n\n### Overview\n\n### Key Changes\n\nAbout 50 lines in [`profiler/utils/model_info.py`](https://github.com/Alex-Wengg/dynamo/blob/fix/16140-profiler-hub-file-sizes/components/src/dynamo/profiler/utils/model_info.py): request `files_metadata=True` and pick the weight files the way vLLM's default loader does. That means repo-root files of the first format present, minus PEFT adapters and training state, and only the files in `model.safetensors.index.json` when the repo has one (a small JSON download). If any selected file lacks a size, or the index can't be read (a gated repo without access, or a network error), the existing estimate is kept.\n\n### Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/profiler/utils/model_info.py b/components/src/dynamo/profiler/utils/model_info.py\nindex 18aac4e09775..c9983e0722da 100644\n--- a/components/src/dynamo/profiler/utils/model_info.py\n+++ b/components/src/dynamo/profiler/utils/model_info.py\n@@ -1,6 +1,7 @@\n # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n # SPDX-License-Identifier: Apache-2.0\n \n+import importlib\n import json\n import logging\n from pathlib import Path\n@@ -22,6 +23,15 @@ class HuggingFaceDownloadError(Exception):\n pass\n \n _load_model_config_from_model_path = None\n+\n+# huggingface_hub raises its HTTP client's network errors, which are not\n+# OSError: httpx in 1.x, httpx2 in 2.x. Older versions use requests (OSError).\n+HUB_NETWORK_ERRORS: tuple[type[Exception], ...] = ()\n+for _client in (\"httpx\", \"httpx2\"):\n+ try:\n+ HUB_NETWORK_ERRORS += (importlib.import_module(_client).HTTPError,)\n+ except ImportError:\n+ pass\n logger = logging.getLogger(__name__)\n \n DTYPE_BYTES_MAP = {\n@@ -85,24 +95,85 @@ def get_local_model_weight_size(\n return total_size_bytes / (1024**2)\n \n \n+# Checkpoint formats in the order vLLM's default loader prefers them.\n+HUB_WEIGHT_EXTENSIONS = (\".safetensors\", \".bin\", \".pt\", \".pth\")\n+SAFETENSORS_INDEX_NAME = \"model.safetensors.index.json\"\n+# Root files that are not model weights: PEFT adapters and training state,\n+# as in vLLM's filter_files_not_needed_for_inference.\n+NON_WEIGHT_FILENAMES = {\n+ \"adapter_model.safetensors\",\n+ \"adapter_model.bin\",\n+ \"training_args.bin\",\n+ \"optimizer.bin\",\n+ \"optimizer.pt\",\n+ \"scheduler.bin\",\n+ \"scheduler.pt\",\n+ \"scaler.pt\",\n+}\n+\n+\n+def _select_hub_checkpoint_files(model_name: str, info, token: Optional[str]) -> list:\n+ \"\"\"Return the Hub repo files that vLLM would load as the model weights.\n+\n+ Like vLLM's default loader, this takes the repo-root files of the first\n+ format present, skips non-weight files, and keeps only the files listed in\n+ ``model.safetensors.index.json`` when the repo has one. That counts one\n+ copy when a repo ships the weights twice (gpt2 in two formats, Mistral's\n+ consolidated file, Llama's ``original/`` folder).\n+ \"\"\"\n+ siblings = info.siblings or []\n+ root_files = [\n+ sibling\n+ for sibling in siblings\n+ if \"/\" not in sibling.rfilename\n+ and sibling.rfilename not in NON_WEIGHT_FILENAMES\n+ ]\n+ for ext in HUB_WEIGHT_EXTENSIONS:\n+ files = [sibling for sibling in root_files if sibling.rfilename.endswith(ext)]\n+ if not files:\n+ continue\n+ if ext == \".safetensors\" and any(\n+ sibling.rfilename == SAFETENSORS_INDEX_NAME for sibling in siblings\n+ ):\n+ try:\n+ index_path = hf_hub_download(\n+ repo_id=model_name,\n+ filename=SAFETENSORS_INDEX_NAME,\n+ revision=info.sha,\n+ token=token,\n+ )\n+ with open(index_path) as f:\n+ indexed = set(json.load(f)[\"weight_map\"].values())\n+ except (OSError, ValueError, KeyError, *HUB_NETWORK_ERRORS) as e:\n+ # Gated repos refuse the download; the network can fail.\n+ logger.warning(\n+ \"Cannot read %s for %s: %s\", SAFETENSORS_INDEX_NAME, model_name, e\n+ )\n+ return []\n+ files = [sibling for sibling in files if sibling.rfilename in indexed]\n+ # An indexed file missing from the repo would make the sum too small.\n+ if len(files) != len(indexed):\n+ return []\n+ return files\n+ return []\n+\n+\n def get_model_weight_size_from_hub(\n model_name: str,\n token: Optional[str] = None,\n ) -> float:\n \"\"\"Return model size in MB by querying Hugging Face Hub API.\"\"\"\n try:\n- info = model_info(model_name, token=token)\n+ # Sibling file sizes are only populated when file metadata is requested.\n+ info = model_info(model_name, token=token, files_metadata=True)\n \n- # Filter for model weight files (safetensors or pytorch bin files)\n- # Also filter out files with None size\n- weight_extensions = [\".safetensors\", \".bin\", \".pt\", \".pth\"]\n total_size_bytes = 0\n-\n- if info.siblings is not None:\n- for sibling in info.siblings:\n- if any(sibling.rfilename.endswith(ext) for ext in weight_extensions):\n- if sibling.size is not None:\n- total_size_bytes += sibling.size\n+ checkpoint_files = _select_hub_checkpoint_files(model_name, info, token)\n+ # A partial sum would undercount, so fall back to the estimate instead.\n+ if checkpoint_files and all(\n+ sibling.size is not None for sibling in checkpoint_files\n+ ):\n+ total_size_bytes = sum(sibling.size for sibling in checkpoint_files)\n \n # If no file sizes were available, try to estimate from safetensors metadata\n if total_size_bytes == 0 and info.safetensors is not None:\n\ndiff --git a/components/src/dynamo/profiler/tests/unit/test_model_info.py b/components/src/dynamo/profiler/tests/unit/test_model_info.py\nindex 1a85e74f4b01..8f219abec718 100644\n--- a/components/src/dynamo/profiler/tests/unit/test_model_info.py\n+++ b/components/src/dynamo/profiler/tests/unit/test_model_info.py\n@@ -19,6 +19,7 @@\n from dynamo.profiler.utils.model_info import (\n get_mamba_cache_align_block_size,\n get_model_context_length,\n+ get_model_weight_size_from_hub,\n )\n except ImportError as e:\n pytest.skip(f\"Skip (missing dependency): {e}\", allow_module_level=True)\n@@ -157,3 +158,187 @@ class DownloadError(Exception):\n )\n \n assert get_model_context_length(\"test/model\") == 4096\n+\n+\n+MIB = 1024**2\n+\n+\n+def _patch_hub(monkeypatch, tmp_path, files, index=None, parameters=None) -> list:\n+ \"\"\"Serve `files` from a fake Hub repo, with an optional safetensors index.\n+\n+ An exception as `index` lists the index but makes downloading it fail.\n+ \"\"\"\n+ siblings = list(files)\n+ index_path = tmp_path / \"model.safetensors.index.json\"\n+ if isinstance(index, Exception):\n+ siblings.append((index_path.name, 1))\n+ elif index is not None:\n+ weight_map = {f\"weight{i}\": name for i, name in enumerate(index)}\n+ index_path.write_text(json.dumps({\"weight_map\": weight_map}))\n+ siblings.append((index_path.name, index_path.stat().st_size))\n+ info = SimpleNamespace(\n+ sha=\"abc123\",\n+ siblings=[\n+ SimpleNamespace(rfilename=name, size=size) for name, size in siblings\n+ ],\n+ safetensors=(\n+ SimpleNamespace(parameters=parameters) if parameters is not None else None\n+ ),\n+ )\n+ calls = []\n+\n+ def fake_model_info(*args, **kwargs):\n+ calls.append(kwargs)\n+ return info\n+\n+ def fake_hf_hub_download(**kwargs):\n+ assert index is not None, \"downloaded an index the repo does not have\"\n+ assert kwargs[\"revision\"] == info.sha\n+ if isinstance(index, Exception):\n+ raise index\n+ return str(index_path)\n+\n+ monkeypatch.setattr(\"dynamo.profiler.utils.model_info.model_info\", fake_model_info)\n+ monkeypatch.setattr(\n+ \"dynamo.profiler.utils.model_info.hf_hub_download\", fake_hf_hub_download\n+ )\n+ return calls\n+\n+\n+def test_model_weight_size_from_hub_uses_checkpoint_file_sizes(\n+ monkeypatch, tmp_path\n+) -> None:\n+ \"\"\"Packed GPTQ weights are sized from the file, not two bytes per param.\"\"\"\n+ calls = _patch_hub(\n+ monkeypatch,\n+ tmp_path,\n+ [(\"config.json\", 1024), (\"model.safetensors\", 768_148_704)],\n+ parameters={\"I32\": 968_884_224, \"BF16\": 131_164_160, \"F16\": 394_240},\n+ )\n+\n+ assert get_model_weight_size_from_hub(\"test/gptq\") == 768_148_704 / MIB\n+ assert calls[0][\"files_metadata\"] is True\n+\n+\n+@pytest.mark.parametrize(\n+ \"files, index, expected_mib\",\n+ [\n+ # gpt2: the same weights in two formats.\n+ (\n+ [(\"model.safetensors\", 548 * MIB), (\"pytorch_model.bin\", 548 * MIB)],\n+ None,\n+ 548,\n+ ),\n+ # Mistral: a consolidated file next to the indexed shards.\n+ (\n+ [\n+ (\"consolidated.safetensors\", 14 * MIB),\n+ (\"model-00001-of-00002.safetensors\", 8 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 6 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 14,\n+ ),\n+ # Devstral: two shard sets; the model index picks one.\n+ (\n+ [\n+ (\"consolidated-00001-of-00002.safetensors\", 7 * MIB),\n+ (\"consolidated-00002-of-00002.safetensors\", 3 * MIB),\n+ (\"consolidated.safetensors.index.json\", 1),\n+ (\"model-00001-of-00002.safetensors\", 6 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 4 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 10,\n+ ),\n+ # A single file left next to the indexed shards of the same name.\n+ (\n+ [\n+ (\"model-00001-of-00002.safetensors\", 5 * MIB),\n+ (\"model-00002-of-00002.safetensors\", 4 * MIB),\n+ (\"model.safetensors\", 9 * MIB),\n+ ],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ 9,\n+ ),\n+ # An Accelerate checkpoint: optimizer state is larger than the model.\n+ (\n+ [\n+ (\"optimizer.bin\", 4 * MIB),\n+ (\"pytorch_model.bin\", 2 * MIB),\n+ (\"scheduler.bin\", 1),\n+ ],\n+ None,\n+ 2,\n+ ),\n+ # A PEFT adapter next to full PyTorch shards.\n+ (\n+ [\n+ (\"adapter_model.safetensors\", 1 * MIB),\n+ (\"pytorch_model-00001-of-00002.bin\", 9 * MIB),\n+ (\"pytorch_model-00002-of-00002.bin\", 3 * MIB),\n+ (\"training_args.bin\", 1),\n+ ],\n+ None,\n+ 12,\n+ ),\n+ ],\n+)\n+def test_model_weight_size_from_hub_counts_one_checkpoint_copy(\n+ monkeypatch, tmp_path, files, index, expected_mib\n+) -> None:\n+ _patch_hub(monkeypatch, tmp_path, files, index=index)\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == expected_mib\n+\n+\n+@pytest.mark.parametrize(\n+ \"files, index\",\n+ [\n+ # Sizes missing for part of the checkpoint.\n+ (\n+ [\n+ (\"model-00001-of-00002.safetensors\", 4 * MIB),\n+ (\"model-00002-of-00002.safetensors\", None),\n+ ],\n+ None,\n+ ),\n+ # The index lists a shard the repo does not have.\n+ (\n+ [(\"model-00001-of-00002.safetensors\", 4 * MIB)],\n+ [\"model-00001-of-00002.safetensors\", \"model-00002-of-00002.safetensors\"],\n+ ),\n+ # A gated repo lists its index but refuses the download.\n+ (\n+ [(\"model-00001-of-00001.safetensors\", 4 * MIB)],\n+ OSError(\"403 Client Error\"),\n+ ),\n+ # No weights at the repo root.\n+ ([(\"checkpoints/model.safetensors\", 4 * MIB)], None),\n+ ],\n+)\n+def test_model_weight_size_from_hub_estimates_without_checkpoint_sizes(\n+ monkeypatch, tmp_path, files, index\n+) -> None:\n+ _patch_hub(monkeypatch, tmp_path, files, index=index, parameters={\"BF16\": 3 * MIB})\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == 6\n+\n+\n+@pytest.mark.parametrize(\"client\", [\"httpx\", \"httpx2\"])\n+@pytest.mark.parametrize(\"error_name\", [\"ConnectError\", \"ReadTimeout\"])\n+def test_model_weight_size_from_hub_estimates_on_index_transport_error(\n+ monkeypatch, tmp_path, client, error_name\n+) -> None:\n+ \"\"\"huggingface_hub raises httpx (1.x) or httpx2 (2.x) errors, not OSError.\"\"\"\n+ module = pytest.importorskip(client)\n+ error = getattr(module, error_name)(\"index download failed\")\n+ _patch_hub(\n+ monkeypatch,\n+ tmp_path,\n+ [(\"model-00001-of-00001.safetensors\", 4 * MIB)],\n+ index=error,\n+ parameters={\"BF16\": 3 * MIB},\n+ )\n+\n+ assert get_model_weight_size_from_hub(\"test/model\") == 6\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: ai-dynamo/dynamo\nPull request: fix(multimodal): preserve NVDEC frames when host buffers are reused\nLabels: external-contribution, size/L, fix, multimodal\nFiles changed (3): components/src/dynamo/common/multimodal/nvdec_decoder.py, components/src/dynamo/common/tests/multimodal/test_nvdec_decoder.py, components/src/dynamo/common/tests/multimodal/test_nvdec_decoder_gpu.py\n\n## Description (results removed)\n\n### Overview\n\nDynamo's NVDEC adapter can return later-frame pixels at earlier sampled indices because saved arrays share the decoder's reused host buffers. Copy CPU `uint8` frames before the next decode so each sample preserves its pixels.\n\n### Key Changes\n\nTwo added lines of production logic; no new dependency or public API.\n\n- [nvdec_decoder.py](components/src/dynamo/common/multimodal/nvdec_decoder.py): copy CPU `uint8` frames. Dtype conversion and CUDA-to-host transfer already create independent storage and retain their existing behavior.\n- [test_nvdec_decoder.py](components/src/dynamo/common/tests/multimodal/test_nvdec_decoder.py): cover source mutation, row-padded storage, dtype conversion and reused buffers under different sampling limits.\n- [test_nvdec_decoder_gpu.py](components/src/dynamo/common/tests/multimodal/test_nvdec_decoder_gpu.py): compare H.264/H.265 pixels with immediately copied reference frames and check CUDA DLPack and CUDA-array-interface inputs.\n\n### Validation\n[results removed]\n## Summary by CodeRabbit\n\n* **Bug Fixes**\n * Fixed video decoding so sampled frames retain their correct image data when the decoder reuses memory. This prevents earlier frames from being overwritten by later ones and keeps returned frame contents consistent with their reported indices and metadata.\n * Frame conversion now preserves independent image data for CPU and GPU inputs, including images with padded rows and non-`uint8` pixel values.\n\n## Diff\n\n```diff\ndiff --git a/components/src/dynamo/common/multimodal/nvdec_decoder.py b/components/src/dynamo/common/multimodal/nvdec_decoder.py\nindex ce394304cbfc..c27d6521952f 100644\n--- a/components/src/dynamo/common/multimodal/nvdec_decoder.py\n+++ b/components/src/dynamo/common/multimodal/nvdec_decoder.py\n@@ -163,13 +163,12 @@ def _gpu_id() -> int:\n \n \n def _frame_to_rgb_hwc(frame) -> np.ndarray:\n- \"\"\"Copy a decoded (device) RGB frame to a host ``(H, W, 3)`` uint8 array.\n+ \"\"\"Return host ``(H, W, 3)`` uint8 pixels independent of decoder storage.\n \n- A 2.x ``DecodedFrame`` (``output_color_type=RGB``) holds a CUDA buffer and\n- supports the DLPack protocol, so torch wraps it zero-copy on the GPU and\n- ``.cpu()`` copies to host. Returns a single frame: ``decode_video_nvdec`` stacks\n- these into ``(num_frames, H, W, 3)``, so a batched replacement here has to drop\n- that stack too.\n+ With ``use_device_memory=False``, DLPack exposes host memory, so ``.cpu()``\n+ does not copy and ``.numpy()`` still aliases the decoder's buffer. Copy\n+ before another decode can reuse that storage. CUDA-to-host transfer and\n+ dtype conversion already allocate independent storage.\n \"\"\"\n import torch\n \n@@ -180,6 +179,8 @@ def _frame_to_rgb_hwc(frame) -> np.ndarray:\n arr = tensor.cpu().numpy()\n if arr.dtype != np.uint8:\n arr = arr.astype(np.uint8)\n+ elif tensor.device.type == \"cpu\":\n+ arr = arr.copy()\n return arr\n \n \ndiff --git a/components/src/dynamo/common/tests/multimodal/test_nvdec_decoder.py b/components/src/dynamo/common/tests/multimodal/test_nvdec_decoder.py\nindex 4a8e4dcccb20..44c8a4cca230 100644\n--- a/components/src/dynamo/common/tests/multimodal/test_nvdec_decoder.py\n+++ b/components/src/dynamo/common/tests/multimodal/test_nvdec_decoder.py\n@@ -24,7 +24,9 @@ def _clear_cache():\n nd.nvdec_available.cache_clear()\n \n \n-def _fake_pynv(num_frames: int = 10, h: int = 4, w: int = 6):\n+def _fake_pynv(\n+ num_frames: int = 10, h: int = 4, w: int = 6, reuse_buffer: bool = False\n+):\n \"\"\"A stand-in PyNvVideoCodec module returning deterministic HWC uint8 frames.\"\"\"\n mod = types.ModuleType(\"PyNvVideoCodec\")\n \n@@ -36,11 +38,15 @@ def __init__(\n self, src, gpu_id=0, output_color_type=None, use_device_memory=False\n ):\n self._n = num_frames\n+ self._frame = np.empty((h, w, 3), dtype=np.uint8)\n \n def __len__(self):\n return self._n\n \n def __getitem__(self, i):\n+ if reuse_buffer:\n+ self._frame.fill(i % 256)\n+ return self._frame\n return np.full((h, w, 3), i % 256, dtype=np.uint8)\n \n def get_fps(self):\n@@ -163,6 +169,63 @@ def test_should_use_nvdec_false_when_unavailable(monkeypatch):\n assert nd.should_use_nvdec(\"h264\") is False\n \n \n+ [comment with results removed]\n+@pytest.mark.vllm\n+@pytest.mark.multimodal\n+@pytest.mark.parametrize(\"dtype\", [np.uint8, np.float32])\n+@pytest.mark.parametrize(\"row_padding\", [0, 2], ids=[\"contiguous\", \"row-padded\"])\n+def test_frame_conversion_preserves_data_when_source_is_reused(dtype, row_padding):\n+ # NumPy exports CPU DLPack storage just like a host-memory DecodedFrame.\n+ width = 6 + row_padding\n+ source = np.arange(4 * width * 3, dtype=dtype).reshape(4, width, 3)[:, :6]\n+ expected = source.astype(np.uint8, copy=True)\n+\n+ frame = nd._frame_to_rgb_hwc(source)\n+ source.fill(255)\n+\n+ assert frame.dtype == np.uint8\n+ assert not np.shares_memory(frame, source)\n+ np.testing.assert_array_equal(frame, expected)\n+\n+\n+@pytest.mark.vllm\n+@pytest.mark.multimodal\n+@pytest.mark.parametrize(\n+ \"total,num_frames,fps,expected_indices\",\n+ [\n+ (1, 5, -1, [0]), # single-frame clip\n+ (10, 1, -1, [0]), # one requested frame from a longer clip\n+ (10, 4, -1, [0, 3, 6, 9]), # uniform sampling\n+ (10, 32, -1, list(range(10))), # capped at the source frame count\n+ (90, 32, 1, [0, 44, 89]), # three seconds at one sampled frame per second\n+ ],\n+)\n+def test_decode_preserves_frames_when_decoder_reuses_host_buffer(\n+ monkeypatch, total, num_frames, fps, expected_indices\n+):\n+ monkeypatch.setitem(\n+ sys.modules, \"PyNvVideoCodec\", _fake_pynv(total, reuse_buffer=True)\n+ )\n+ # Exercise the real conversion helper: returning a view here would make\n+ # every saved frame contain the last sampled index by the time we stack.\n+ frames, metadata = nd.decode_video_nvdec(b\"fakebytes\", num_frames, fps=fps)\n+\n+ assert frames.shape == (len(expected_indices), 4, 6, 3)\n+ assert frames.dtype == np.uint8\n+ assert frames.flags[\"C_CONTIGUOUS\"]\n+ expected = np.broadcast_to(\n+ np.asarray(expected_indices, dtype=np.uint8)[:, None, None, None],\n+ frames.shape,\n+ )\n+ np.testing.assert_array_equal(frames, expected)\n+ assert metadata == {\n+ \"fps\": 30.0,\n+ \"frames_indices\": expected_indices,\n+ \"total_num_frames\": total,\n+ \"do_sample_frames\": len(expected_indices) == total,\n+ }\n+\n+\n def test_decode_matches_frame_contract(monkeypatch):\n monkeypatch.setitem(\n sys.modules, \"PyNvVideoCodec\", _fake_pynv(num_frames=10, h=4, w=6)\ndiff --git a/components/src/dynamo/common/tests/multimodal/test_nvdec_decoder_gpu.py b/components/src/dynamo/common/tests/multimodal/test_nvdec_decoder_gpu.py\nindex e7309abc3831..7443a0ecfe78 100644\n--- a/components/src/dynamo/common/tests/multimodal/test_nvdec_decoder_gpu.py\n+++ b/components/src/dynamo/common/tests/multimodal/test_nvdec_decoder_gpu.py\n@@ -28,6 +28,7 @@\n pytest.mark.post_merge,\n pytest.mark.gpu_1,\n pytest.mark.vllm,\n+ pytest.mark.multimodal,\n ]\n \n \n@@ -83,15 +84,66 @@ def _decode_and_assert(codec: str) -> int:\n assert frames[:, :, :, :].max() > 0 # real pixels, not a black clip\n assert metadata[\"total_num_frames\"] >= 8\n assert len(metadata[\"frames_indices\"]) == 8\n+\n+ import PyNvVideoCodec as nvc\n+ import torch\n+\n+ # Copy each reference frame before another decode can reuse its storage.\n+ # Shape/nonzero assertions alone miss the bug where every returned frame\n+ # aliases the last one; compare the actual pixels at each sampled index.\n+ decoder = nvc.SimpleDecoder(\n+ str(path),\n+ gpu_id=nd._gpu_id(),\n+ output_color_type=nvc.OutputColorType.RGB,\n+ use_device_memory=False,\n+ )\n+ reference = [\n+ torch.from_dlpack(decoder[index]).cpu().numpy().copy()\n+ for index in metadata[\"frames_indices\"]\n+ ]\n+ assert not np.array_equal(reference[0], reference[-1]), \"fixture must vary\"\n+ np.testing.assert_array_equal(frames, np.stack(reference))\n return 0\n \n \n+def _assert_cuda_frame_conversion() -> None:\n+ import numpy as np\n+ import torch\n+\n+ from dynamo.common.multimodal import nvdec_decoder as nd\n+\n+ class CudaArrayOnly:\n+ def __init__(self, tensor):\n+ self.tensor = tensor\n+\n+ @property\n+ def __cuda_array_interface__(self):\n+ return self.tensor.__cuda_array_interface__\n+\n+ for dtype in (np.uint8, np.float32):\n+ values = np.arange(72, dtype=dtype).reshape(4, 6, 3)\n+ if dtype == np.float32:\n+ values += 0.5\n+ expected = values.astype(np.uint8)\n+ for array_only in (False, True):\n+ source = torch.from_numpy(values).to(f\"cuda:{nd._gpu_id()}\")\n+ frame = CudaArrayOnly(source) if array_only else source\n+ result = nd._frame_to_rgb_hwc(frame)\n+ source.fill_(255)\n+ torch.cuda.synchronize(source.device)\n+\n+ assert isinstance(result, np.ndarray)\n+ assert result.dtype == np.uint8\n+ np.testing.assert_array_equal(result, expected)\n+\n+\n def _run_worker() -> int:\n for codec in sorted(_FIXTURES):\n print(f\"Validating NVDEC {codec}\", file=sys.stderr, flush=True)\n status = _decode_and_assert(codec)\n if status != 0:\n return status\n+ _assert_cuda_frame_conversion()\n return 0\n \n \n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: deepspeedai/DeepSpeed\nPull request: Fix scalar parameter byte-view broadcasts\nFiles changed (4): deepspeed/runtime/engine.py, deepspeed/runtime/utils.py, deepspeed/runtime/zero/partition_parameters.py, tests/unit/runtime/test_scalar_parameter_broadcast.py\n\n## Description (results removed)\n\nFixes #8639.\n\nPrepared with AI assistance; I reviewed the diff and ran the tests above.\n\n## Diff\n\n```diff\ndiff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py\nindex 520b7c4c758b..20580f53d6b3 100644\n--- a/deepspeed/runtime/engine.py\n+++ b/deepspeed/runtime/engine.py\n@@ -28,7 +28,7 @@\n import deepspeed\n \n from deepspeed import comm as dist\n-from deepspeed.runtime.utils import see_memory_usage, DummyOptim, register_output_backward_hooks, check_internal_apis_for_count_used_parameters\n+from deepspeed.runtime.utils import see_memory_usage, DummyOptim, register_output_backward_hooks, check_internal_apis_for_count_used_parameters, view_as_uint8\n from .zero.offload_config import OffloadDeviceEnum, OffloadStateTypeEnum\n from deepspeed.runtime.base_optimizer import ZeROOptimizer\n from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer\n@@ -1970,12 +1970,12 @@ def is_replicated(p):\n # Broadcast the model for different parameters\n if is_moe_param(p):\n if torch.is_tensor(p) and is_replicated(p):\n- dist.broadcast(p.data.view(torch.uint8),\n+ dist.broadcast(view_as_uint8(p.data),\n groups._get_expert_broadcast_src_rank(p.group_name),\n group=self.expert_data_parallel_group[p.group_name])\n else:\n if torch.is_tensor(p) and is_replicated(p):\n- dist.broadcast(p.data.view(torch.uint8),\n+ dist.broadcast(view_as_uint8(p.data),\n groups._get_broadcast_src_rank(),\n group=self.seq_data_parallel_group)\n \ndiff --git a/deepspeed/runtime/utils.py b/deepspeed/runtime/utils.py\nindex 4d23aac3e21e..47f9789aab7b 100644\n--- a/deepspeed/runtime/utils.py\n+++ b/deepspeed/runtime/utils.py\n@@ -47,6 +47,13 @@ def __init__(self, params):\n self.param_groups.append({'params': params})\n \n \n+def view_as_uint8(tensor):\n+ # PyTorch cannot reinterpret a scalar as a dtype with a different element size.\n+ if tensor.ndim == 0:\n+ tensor = tensor.unsqueeze(0)\n+ return tensor.view(torch.uint8)\n+\n+\n def filter_empty_parameters(params):\n \"\"\"Filter out empty parameters (numel == 0) from optimizer params.\n \ndiff --git a/deepspeed/runtime/zero/partition_parameters.py b/deepspeed/runtime/zero/partition_parameters.py\nindex 3a3e32585298..d045df2bde7b 100644\n--- a/deepspeed/runtime/zero/partition_parameters.py\n+++ b/deepspeed/runtime/zero/partition_parameters.py\n@@ -23,7 +23,7 @@\n \n from deepspeed.utils import groups\n import deepspeed\n-from ..utils import see_memory_usage, get_only_unique_item\n+from ..utils import see_memory_usage, get_only_unique_item, view_as_uint8\n from deepspeed.runtime.zero.config import DeepSpeedZeroConfig\n from deepspeed.runtime.zero.utils import assert_ints_same_as_other_ranks, is_zero_param\n from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum\n@@ -467,7 +467,7 @@ def wrapped_fn_to_apply(module_to_apply_fn_to: Module) -> None:\n fn_to_apply(module_to_apply_fn_to)\n \n for param in params_to_apply_fn_to:\n- dist.broadcast(param.data.view(torch.uint8), 0, group=param.ds_process_group)\n+ dist.broadcast(view_as_uint8(param.data), 0, group=param.ds_process_group)\n \n for param in params_to_apply_fn_to:\n param.partition(has_been_updated=True)\n@@ -1197,9 +1197,9 @@ def _zero_init_param(self, param):\n self._convert_to_deepspeed_param(param)\n partition_group = self.get_partition_dp_group(param)\n if dist.get_world_group() == partition_group:\n- dist.broadcast(param.data.view(torch.uint8), 0, partition_group)\n+ dist.broadcast(view_as_uint8(param.data), 0, partition_group)\n else:\n- dist.broadcast(param.data.view(torch.uint8), dist.get_global_rank(partition_group, 0), partition_group)\n+ dist.broadcast(view_as_uint8(param.data), dist.get_global_rank(partition_group, 0), partition_group)\n param.partition()\n \n def _convert_to_zero_parameters(self, param_list):\n@@ -2539,7 +2539,7 @@ def _exit(self, *exc):\n f\"the accelerator device. If you don't need to broadcast updates, use modifier_rank=None.\")\n \n handles = [\n- dist.broadcast(p.data.view(torch.uint8),\n+ dist.broadcast(view_as_uint8(p.data),\n self.src_rank_by_group[id(p.ds_process_group)],\n group=p.ds_process_group,\n async_op=True) for p in self.params\ndiff --git a/tests/unit/runtime/test_scalar_parameter_broadcast.py b/tests/unit/runtime/test_scalar_parameter_broadcast.py\nnew file mode 100644\nindex 000000000000..7eb2769bc9bd\n--- /dev/null\n+++ b/tests/unit/runtime/test_scalar_parameter_broadcast.py\n@@ -0,0 +1,44 @@\n+# Copyright (c) DeepSpeed Team.\n+# SPDX-License-Identifier: Apache-2.0\n+# DeepSpeed Team\n+\n+import pytest\n+import torch\n+from torch import nn\n+\n+import deepspeed\n+import deepspeed.comm as dist\n+from unit.common import DistributedTest\n+\n+\n+class ScalarModel(nn.Module):\n+\n+ def __init__(self):\n+ super().__init__()\n+ self.weight = nn.Parameter(torch.tensor(float(dist.get_rank() + 1)))\n+\n+\n+class TestScalarParameterBroadcast(DistributedTest):\n+ world_size = 2\n+ backend = \"gloo\"\n+ requires_cuda_env = False\n+\n+ @pytest.mark.parametrize(\"zero_stage\", [0, 3])\n+ def test_initialization_broadcasts_scalar_parameter(self, zero_stage):\n+ engine, _, _, _ = deepspeed.initialize(\n+ model=ScalarModel(),\n+ config={\n+ \"train_micro_batch_size_per_gpu\": 1,\n+ \"zero_optimization\": {\n+ \"stage\": zero_stage\n+ }\n+ },\n+ )\n+ parameter = engine.module.weight\n+ if zero_stage == 3:\n+ with deepspeed.zero.GatheredParameters([parameter]):\n+ assert parameter.shape == torch.Size([])\n+ assert parameter.item() == 1.0\n+ else:\n+ assert parameter.shape == torch.Size([])\n+ assert parameter.item() == 1.0\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: deepspeedai/DeepSpeed\nPull request: Fix numerical stability in Triton masked softmax\nLabels: will-review\nFiles changed (2): deepspeed/ops/transformer/inference/triton/softmax.py, tests/unit/ops/transformer/inference/test_softmax.py\n\n## Description (results removed)\n\nFixes #8780. A mask that suppresses the row max made every `exp()` underflow to 0, giving 0/0 = NaN. Now the row max is subtracted again after the mask is added.\nThe first shift stays to keep FP32 mask precision.\n\n## Diff\n\n```diff\ndiff --git a/deepspeed/ops/transformer/inference/triton/softmax.py b/deepspeed/ops/transformer/inference/triton/softmax.py\nindex 1ee10d63e6cf..8c115752ee81 100644\n--- a/deepspeed/ops/transformer/inference/triton/softmax.py\n+++ b/deepspeed/ops/transformer/inference/triton/softmax.py\n@@ -40,6 +40,7 @@ def masked_softmax_kernel(output_ptr, input_ptr, stride, mask_ptr, mask_stride,\n mask = tl.load(mask_ptrs, mask=col_offsets < n_cols, other=0).to(tl.float32)\n row_minus_max = row - tl.max(row, axis=0)\n row_minus_max = row_minus_max + mask\n+ row_minus_max = row_minus_max - tl.max(row_minus_max, axis=0)\n numerator = tl.exp(row_minus_max)\n denominator = tl.sum(numerator, axis=0)\n softmax_output = numerator / denominator\ndiff --git a/tests/unit/ops/transformer/inference/test_softmax.py b/tests/unit/ops/transformer/inference/test_softmax.py\nindex 83785ac38ebb..d17470ce6c12 100644\n--- a/tests/unit/ops/transformer/inference/test_softmax.py\n+++ b/tests/unit/ops/transformer/inference/test_softmax.py\n@@ -48,3 +48,21 @@ def test_softmax(batch, sequence, channels, dtype, use_triton_ops):\n ds_out = run_softmax_ds(input_ds, use_triton_ops)\n ref_out = run_softmax_reference(input_ref)\n assert (allclose(ds_out, ref_out))\n+\n+\n+@pytest.mark.inference_ops\n+@pytest.mark.parametrize(\"dtype\", [torch.float16, torch.float32])\n+@pytest.mark.parametrize(\"mask_value\", [-1000., -float('inf')])\n+def test_masked_softmax_when_max_is_masked(dtype, mask_value):\n+ if not deepspeed.get_accelerator().is_triton_supported():\n+ pytest.skip(\"triton is not supported on this system\")\n+\n+ from deepspeed.ops.transformer.inference.triton import softmax\n+\n+ device = deepspeed.accelerator.get_accelerator().device_name()\n+ input_ds = torch.tensor([[0., -200.]], dtype=dtype, device=device)\n+ mask = torch.tensor([[mask_value, 0.]], dtype=dtype, device=device)\n+\n+ ds_out = softmax(input_ds, mask)\n+ ref_out = torch.tensor([[0., 1.]], dtype=dtype, device=device)\n+ assert allclose(ds_out, ref_out)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: deepspeedai/DeepSpeed\nPull request: Fix race between folded checkpoint load and metadata drop in AutoEP+AutoTP test\nFiles changed (1): tests/unit/v1/moe/test_autoep_autotp_checkpoint.py\n\n## Description (results removed)\n\nFixes #8925.\n\n## Problem\n\n## Fix\n\nAdd a `dist.barrier()` in `_drop_folding_metadata_from_model_checkpoints` before rank 0 rewrites the files, as suggested in the issue. It sits in the helper, not at the call site, so every caller waits for all ranks to finish reading.\n\n## Validation\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/tests/unit/v1/moe/test_autoep_autotp_checkpoint.py b/tests/unit/v1/moe/test_autoep_autotp_checkpoint.py\nindex 86a7660661a1..a8dade69c309 100644\n--- a/tests/unit/v1/moe/test_autoep_autotp_checkpoint.py\n+++ b/tests/unit/v1/moe/test_autoep_autotp_checkpoint.py\n@@ -216,6 +216,8 @@ def _load_torch_checkpoint(path):\n def _drop_folding_metadata_from_model_checkpoints(checkpoint_dir):\n model_paths = sorted(glob.glob(os.path.join(str(checkpoint_dir), \"folded\", \"mp_rank_*_model_states.pt\")))\n assert model_paths\n+ # Every rank must finish reading these files before rank 0 rewrites them.\n+ dist.barrier()\n if dist.get_rank() == 0:\n for path in model_paths:\n state = _load_torch_checkpoint(path)\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: deepspeedai/DeepSpeed\nPull request: fix test_multiple_request_boundaries_before_step\nFiles changed (1): tests/unit/v1/zero/test_zero2_offload_multi_backward.py\n\n## Description (results removed)\n\nFixes: https://github.com/deepspeedai/DeepSpeed/issues/9025\n\n## Rationale And Limit\n\n## Validation\n[results removed]\n## Compatibility And Submission\n\n**No runtime, configuration, checkpoint, or public API behavior changes.** The engine, ZeRO-1/2 and ZeRO-3 destruction paths, BF16 optimizer destruction, and distributed harness were inspected; no sibling production changes are proposed. The full CPU suite, other accelerators, ZeRO-3, NVMe offload, FP16, and additional parallelism modes were not validated. Production convergence, throughput, and peak-memory measurements are not applicable to this test-only launcher change.\n\nPublic GitHub API searches for issue 9025, request-boundary tests, and SIGABRT found no matching open PR during the November 6, 2026 investigation. This proposal does not duplicate the earlier request-boundary gradient fix: it changes only test-process lifetime.\n\nAI assistance was used. A human submitter must review the changed lines and validation limitations before submitting and providing any required sign-off. No commit, push, or PR creation was performed by this task.\n\n## Diff\n\n```diff\ndiff --git a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py\nindex e778ff8812e7..0f513e5587fc 100644\n--- a/tests/unit/v1/zero/test_zero2_offload_multi_backward.py\n+++ b/tests/unit/v1/zero/test_zero2_offload_multi_backward.py\n@@ -268,11 +268,14 @@ def _run_request_boundaries(rank, rendezvous, zero_stage, cpu_offload, accumulat\n @pytest.mark.parametrize(\"accumulation_dtype\", [\"bf16\", \"fp32\"])\n @pytest.mark.parametrize(\"checkpointed\", [False, True], ids=[\"plain\", \"reentrant\"])\n def test_multiple_request_boundaries_before_step(tmp_path, zero_stage, cpu_offload, accumulation_dtype, checkpointed):\n- torch.multiprocessing.spawn(_run_request_boundaries,\n- args=(f\"file://{tmp_path / 'rendezvous'}\", zero_stage, cpu_offload, accumulation_dtype,\n- checkpointed),\n- nprocs=2,\n- join=True)\n+ # Match DistributedTest's forkserver lifecycle: spawn also runs native global\n+ # destructors during interpreter shutdown, beyond the explicit engine/group cleanup.\n+ torch.multiprocessing.start_processes(_run_request_boundaries,\n+ args=(f\"file://{tmp_path / 'rendezvous'}\", zero_stage, cpu_offload,\n+ accumulation_dtype, checkpointed),\n+ nprocs=2,\n+ join=True,\n+ start_method=\"forkserver\")\n \n \n class TestZero2OffloadOverflowRecovery(DistributedTest):\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: huggingface/transformers\nPull request: Fix model_input_names singleton issue causing shared state\nFiles changed (2): src/transformers/tokenization_utils_base.py, tests/tokenization/test_tokenization_utils.py\n\n## Description (results removed)\n\n# What does this PR do?\n\nFixes #42024\n\nI found this while testing tokenizers - when you modify `model_input_names` on one tokenizer instance, it was affecting all other instances of the same tokenizer class.\n\nThe problem is that `model_input_names` is defined as a class-level list, and in the `__init__` method (line 1417), when no custom `model_input_names` is provided, it was just referencing the class attribute directly instead of making a copy.\n\nSo all instances were sharing the same list object. This is a classic Python gotcha with mutable class attributes.\n\nThe fix is simple - wrap it in `list()` to create a new list for each instance:\n\n**Before:**\n```python\nself.model_input_names = kwargs.pop(\"model_input_names\", self.model_input_names)\n```\n\n**After:**\n```python\nself.model_input_names = list(kwargs.pop(\"model_input_names\", self.model_input_names))\n```\n\nThis ensures each tokenizer instance gets its own independent copy of the list. Now modifications to one instance won't affect others.\n\nThe reproduction from the issue shows the problem clearly - with the fix, the second tokenizer instance will have the original list values instead of inheriting the modifications from the first instance.\n\n## Diff\n\n```diff\ndiff --git a/src/transformers/tokenization_utils_base.py b/src/transformers/tokenization_utils_base.py\nindex 10feaff36b1c..48bc88e78289 100644\n--- a/src/transformers/tokenization_utils_base.py\n+++ b/src/transformers/tokenization_utils_base.py\n@@ -1068,7 +1068,7 @@ def __init__(self, **kwargs):\n f\"Truncation side should be selected between 'right' and 'left', current value: {self.truncation_side}\"\n )\n \n- self.model_input_names = kwargs.pop(\"model_input_names\", self.model_input_names)\n+ self.model_input_names = list(kwargs.pop(\"model_input_names\", self.model_input_names))\n \n # By default, do not clean up tokenization spaces for both fast and slow tokenizers\n self.clean_up_tokenization_spaces = kwargs.pop(\"clean_up_tokenization_spaces\", False)\ndiff --git a/tests/tokenization/test_tokenization_utils.py b/tests/tokenization/test_tokenization_utils.py\nindex c144622dbb75..02eb8460c982 100644\n--- a/tests/tokenization/test_tokenization_utils.py\n+++ b/tests/tokenization/test_tokenization_utils.py\n@@ -32,6 +32,7 @@\n ProphetNetTokenizer,\n PythonBackend,\n TensorType,\n+ TokenizersBackend,\n TokenSpan,\n is_tokenizers_available,\n )\n@@ -294,6 +295,16 @@ def test_instantiation_from_tokenizers_json_file(self):\n bert_tokenizer.save(os.path.join(tmpdirname, \"tokenizer.json\"))\n PreTrainedTokenizerFast(tokenizer_file=os.path.join(tmpdirname, \"tokenizer.json\"))\n \n+ @require_tokenizers\n+ def test_model_input_names_not_shared_between_instances(self):\n+ tokenizer_1 = TokenizersBackend(tokenizer_object=Tokenizer(WordPiece(unk_token=\"[UNK]\")))\n+ tokenizer_2 = TokenizersBackend(tokenizer_object=Tokenizer(WordPiece(unk_token=\"[UNK]\")))\n+\n+ tokenizer_1.model_input_names.append(\"pixel_values\")\n+ self.assertIn(\"pixel_values\", tokenizer_1.model_input_names)\n+ self.assertNotIn(\"pixel_values\", tokenizer_2.model_input_names)\n+ self.assertNotIn(\"pixel_values\", TokenizersBackend.model_input_names)\n+\n def test_vocab_file_in_config_does_not_escape_repo(self):\n # Regression test for path traversal (CWE-22): a vocab-file argument injected into\n # `tokenizer_config.json` must not override the repository-resolved path nor be opened\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: huggingface/transformers\nPull request: Fix boolean padding in ClapFeatureExtractor (#23648)\nFiles changed (2): src/transformers/models/clap/feature_extraction_clap.py, tests/models/clap/test_feature_extraction_clap.py\n\n## Description (results removed)\n\n[[image]](https://transformers-ci.huggingface.cool/d/pytest-observability-by-pr/pytest-observability-branch?var-pr=49960)\n\nFixes #23648\n\n### Description\n\nIn `ClapFeatureExtractor.__call__`, `padding = padding if padding else self.padding` leaves `padding=True` as a boolean. In `_get_input_mel`, `padding == \"repeat\"` and `padding == \"repeatpad\"` both evaluate to `False`, causing `padding=True` to fall through to constant zero padding instead of using the configured `self.padding` strategy (`repeatpad`).\n\nFollowing @ArthurZucker's recommendation in #23648, this PR:\n- Maps boolean `padding=True` to `self.padding` in `ClapFeatureExtractor.__call__`.\n- Updates the method type annotation and docstring to reflect `bool` support.\n\n## Diff\n\n```diff\ndiff --git a/src/transformers/models/clap/feature_extraction_clap.py b/src/transformers/models/clap/feature_extraction_clap.py\nindex 0a271e94b8c4..31e929771285 100644\n--- a/src/transformers/models/clap/feature_extraction_clap.py\n+++ b/src/transformers/models/clap/feature_extraction_clap.py\n@@ -263,7 +263,7 @@ def __call__(\n self,\n raw_speech: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],\n truncation: str | None = None,\n- padding: str | None = None,\n+ padding: bool | str | None = None,\n max_length: int | None = None,\n sampling_rate: int | None = None,\n return_tensors: str | TensorType | None = None,\n@@ -284,8 +284,9 @@ def __call__(\n If `config.fusion` is set to True, shorter audios also need to return 4 mels, which will just be a\n copy of the original mel obtained from the padded audio.\n - `rand_trunc` will select a random crop of the mel spectrogram.\n- padding (`str`, *optional*):\n- Padding pattern for shorter audio inputs. Three patterns were originally implemented:\n+ padding (`bool`, `str`, *optional*):\n+ Padding pattern for shorter audio inputs. If `True`, defaults to `self.padding`.\n+ Available patterns:\n - `repeatpad`: the audio is repeated, and then padded to fit the `max_length`.\n - `repeat`: the audio is repeated and then cut to fit the `max_length`\n - `pad`: the audio is padded.\n@@ -299,7 +300,8 @@ def __call__(\n pipeline.\n \"\"\"\n truncation = truncation if truncation is not None else self.truncation\n- padding = padding if padding else self.padding\n+ if padding is True or padding is None:\n+ padding = self.padding\n \n if sampling_rate is not None:\n if sampling_rate != self.sampling_rate:\ndiff --git a/tests/models/clap/test_feature_extraction_clap.py b/tests/models/clap/test_feature_extraction_clap.py\nindex 4cd73372dd87..92204f2ad4d4 100644\n--- a/tests/models/clap/test_feature_extraction_clap.py\n+++ b/tests/models/clap/test_feature_extraction_clap.py\n@@ -144,6 +144,20 @@ def test_double_precision_pad(self):\n pt_processed = feature_extractor.pad([{\"input_features\": inputs}], return_tensors=\"pt\")\n self.assertTrue(pt_processed.input_features.dtype == torch.float32)\n \n+ def test_padding_boolean(self):\n+ feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())\n+ speech_inputs = floats_list((1, 800))[0]\n+\n+ np.random.seed(0)\n+ out_default = feature_extractor(speech_inputs, return_tensors=\"np\").input_features\n+ np.random.seed(0)\n+ out_bool = feature_extractor(speech_inputs, padding=True, return_tensors=\"np\").input_features\n+ np.random.seed(0)\n+ out_repeatpad = feature_extractor(speech_inputs, padding=\"repeatpad\", return_tensors=\"np\").input_features\n+\n+ self.assertTrue(np.allclose(out_bool, out_default, atol=1e-3))\n+ self.assertTrue(np.allclose(out_bool, out_repeatpad, atol=1e-3))\n+\n # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest._load_datasamples\n def _load_datasamples(self, num_samples):\n ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: huggingface/transformers\nPull request: [timesfm] Fix fp16 overflow on pad_val in _forward_transform\nFiles changed (2): src/transformers/models/timesfm/modeling_timesfm.py, src/transformers/models/timesfm/modular_timesfm.py\n\n## Description (results removed)\n\n[[image]](https://transformers-ci.huggingface.cool/d/pytest-observability-by-pr/pytest-observability-branch?var-pr=50021)\n\nFixes #50020\n\n#47547 replaced `torch.tensor(pad_val, dtype=...)` with `torch.full((), pad_val, dtype=...)` for CUDA graphs. TimesFM's `pad_val` is 1123581321.0, which doesn't fit in fp16: `torch.tensor` silently gave `inf`, but `torch.full` checks for overflow on CUDA and raises (so does a Python scalar in `torch.where`, see the comment below).\n\n## Diff\n\n```diff\ndiff --git a/src/transformers/models/timesfm/modeling_timesfm.py b/src/transformers/models/timesfm/modeling_timesfm.py\nindex c52d1eb22991..821a2f4997a1 100644\n--- a/src/transformers/models/timesfm/modeling_timesfm.py\n+++ b/src/transformers/models/timesfm/modeling_timesfm.py\n@@ -358,11 +358,8 @@ def _forward_transform(\n \n # Normalize each patch\n outputs = (inputs - mu[:, None, None]) / sigma[:, None, None]\n- outputs = torch.where(\n- torch.abs(inputs - self.config.pad_val) < self.config.tolerance,\n- torch.full((), self.config.pad_val, dtype=outputs.dtype, device=outputs.device),\n- outputs,\n- )\n+ # padded positions keep their value (`pad_val`), which does not fit in fp16: no scalar to cast\n+ outputs = torch.where(torch.abs(inputs - self.config.pad_val) < self.config.tolerance, inputs, outputs)\n return outputs, (mu, sigma)\n \n @merge_with_config_defaults\ndiff --git a/src/transformers/models/timesfm/modular_timesfm.py b/src/transformers/models/timesfm/modular_timesfm.py\nindex 98b5065facaa..00c740ab4aab 100644\n--- a/src/transformers/models/timesfm/modular_timesfm.py\n+++ b/src/transformers/models/timesfm/modular_timesfm.py\n@@ -315,11 +315,8 @@ def _forward_transform(\n \n # Normalize each patch\n outputs = (inputs - mu[:, None, None]) / sigma[:, None, None]\n- outputs = torch.where(\n- torch.abs(inputs - self.config.pad_val) < self.config.tolerance,\n- torch.full((), self.config.pad_val, dtype=outputs.dtype, device=outputs.device),\n- outputs,\n- )\n+ # padded positions keep their value (`pad_val`), which does not fit in fp16: no scalar to cast\n+ outputs = torch.where(torch.abs(inputs - self.config.pad_val) < self.config.tolerance, inputs, outputs)\n return outputs, (mu, sigma)\n \n @merge_with_config_defaults\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: pytorch/pytorch\nPull request: [XPU][UT]fix test_effn_attn_uniform_zero_bias on XPU\nLabels: triaged, open source, Merged, ciflow/trunk, topic: not user facing, module: inductor, ciflow/inductor, ciflow/xpu, module: xpu, ready for review\nFiles changed (1): test/inductor/test_cuda_repro.py\n\n## Description (results removed)\n\nFixes https://github.com/pytorch/pytorch/issues/196552\n## Motivation & Root Cause\n\n```text\nAssertionError: 0 != 1 at test_cuda_repro.py:298 (self.assertEqual(len(biases), 1)), reached from test_cuda_repro.py:328\n```\n```python\nF.scaled_dot_product_attention(..., attn_mask=padding_mask)\n```\nunder `sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION)` and expects exactly one `aten._scaled_dot_product_efficient_attention` node in the joint graph.\n\n### Root Cause\nOn XPU, `select_sdp_backend_xpu` falls back to the math backend from its `efficient_attention` branch \n- Emits a `TORCH_WARN_ONCE(\"SDPA Memory Efficient Attention backend is not supported on XPU, falling back to math backend\")`.\n- Returns `sdp::SDPBackend::math`.\nhttps://github.com/pytorch/pytorch/blob/58f9067c977702ef7d0155f61c79e6d9c738ebf1/aten/src/ATen/native/mkldnn/xpu/Attention.cpp#L224-L235\n\n## Solution\nThis PR replaces `F.scaled_dot_product_attention` with `aten._scaled_dot_product_efficient_attention.default` in the\nruntime-mask test case to avoid the XPU math backend fallback.\n\ncc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @gujinghui @fengyuan14 @guangyey\n\n## Diff\n\n```diff\ndiff --git a/test/inductor/test_cuda_repro.py b/test/inductor/test_cuda_repro.py\nindex 5b493217a532c..47e216172e8ee 100644\n--- a/test/inductor/test_cuda_repro.py\n+++ b/test/inductor/test_cuda_repro.py\n@@ -352,12 +352,9 @@ def capture_bias(graph):\n biases.extend(node.args[3] for node in nodes)\n \n torch._dynamo.reset()\n- with (\n- config.patch(\n- numerics=\"strict\" if strict else \"default\",\n- joint_custom_post_pass=capture_bias,\n- ),\n- sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION),\n+ with config.patch(\n+ numerics=\"strict\" if strict else \"default\",\n+ joint_custom_post_pass=capture_bias,\n ):\n compiled = torch.compile(fn, fullgraph=True)\n actual = compiled(*args)\n@@ -378,9 +375,13 @@ def capture_bias(graph):\n # Only compiler-proven zero masks may be removed; a runtime mask must\n # remain an FX input because its contents can change between calls.\n def runtime_mask_fn(query, key, value, attention_mask):\n- return F.scaled_dot_product_attention(\n- query, key, value, attn_mask=attention_mask\n- )\n+ return aten._scaled_dot_product_efficient_attention.default(\n+ query,\n+ key,\n+ value,\n+ attention_mask.expand(batch_size, num_heads, seq_len, seq_len),\n+ False,\n+ )[0]\n \n padding_mask = torch.zeros(\n batch_size,\n@@ -399,11 +400,10 @@ def runtime_mask_fn(query, key, value, attention_mask):\n \n # Reuse the same compiled graph with different mask contents.\n padding_mask.zero_()\n- with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):\n- self.assertEqual(\n- compiled_runtime_mask_fn(query, key, value, padding_mask),\n- runtime_mask_fn(query, key, value, padding_mask),\n- )\n+ self.assertEqual(\n+ compiled_runtime_mask_fn(query, key, value, padding_mask),\n+ runtime_mask_fn(query, key, value, padding_mask),\n+ )\n \n @unittest.skipIf(\n not PLATFORM_SUPPORTS_MEM_EFF_ATTENTION,\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: pytorch/pytorch\nPull request: [linalg] Fix SVD driver validation and ROCm fallback semantics\nLabels: module: rocm, triaged, open source, Merged, ciflow/trunk, release notes: linalg_frontend, topic: bc breaking, ciflow/rocm-mi300\nFiles changed (5): aten/src/ATen/native/BatchLinearAlgebra.cpp, aten/src/ATen/native/cuda/linalg/BatchLinearAlgebraLib.cpp, test/test_linalg.py, torch/_meta_registrations.py, torch/linalg/__init__.py\n\n## Description (results removed)\n\nFixes #198425\n\n## BC-breaking?\n\nYes, for `driver=` in `torch.linalg.svd` and `torch.linalg.svdvals`, including their `out=` forms (details drafted with GitHub Copilot):\n\n> - Invalid driver names now raise on every device, including CPU, MPS and out-of-tree backends that share the structured meta, and under Meta and FakeTensor, for empty and non-empty inputs, with the new message `torch.linalg.svd: unknown svd driver . Expected one of gesvd, gesvdj, or gesvda.` Before, non-empty inputs raised the backend's message (``keyword argument `driver=` is only supported on CUDA inputs with cuSOLVER backend`` off cuSOLVER, `unknown svd driver in svd_cusolver computation` on NVIDIA cuSOLVER), non-empty ROCm inputs accepted any name silently, and empty inputs raised nothing.\n> - Valid names on inputs that do not use cuSOLVER/hipSOLVER (CPU, MPS, or MAGMA as the preferred backend) now raise the existing `driver=` message on empty inputs too; before, only non-empty inputs raised.\n> - On ROCm, valid names are ignored with a once-only `UserWarning`, and the default `gesvdj` path keeps its `gesvd` fallback. Before, they were ignored silently and disabled that fallback.\n>\n\nSee #198425 for the problem and the discussion behind this fix.\n\n## Diff\n\n```diff\ndiff --git a/aten/src/ATen/native/BatchLinearAlgebra.cpp b/aten/src/ATen/native/BatchLinearAlgebra.cpp\nindex fdf211a90351e..7dd62958188d6 100644\n--- a/aten/src/ATen/native/BatchLinearAlgebra.cpp\n+++ b/aten/src/ATen/native/BatchLinearAlgebra.cpp\n@@ -761,6 +761,12 @@ TORCH_META_FUNC(_linalg_svd)(const Tensor& A,\n std::optional driver) {\n at::native::checkIsMatrix(A, \"linalg.svd\");\n at::native::checkFloatingOrComplex(A, \"linalg.svd\");\n+ if (driver.has_value()) {\n+ TORCH_CHECK(\n+ *driver == \"gesvd\" || *driver == \"gesvdj\" || *driver == \"gesvda\",\n+ \"torch.linalg.svd: unknown svd driver \", *driver,\n+ \". Expected one of gesvd, gesvdj, or gesvda.\");\n+ }\n \n auto sizes = A.sizes().vec();\n const auto m = sizes.cend()[-2];\n@@ -3147,6 +3153,14 @@ TORCH_IMPL_FUNC(_linalg_svd_out)(const Tensor& A,\n const Tensor & U,\n const Tensor & S,\n const Tensor & Vh) {\n+ TORCH_CHECK(at::native::svd_uses_cusolver(A) || !driver.has_value(),\n+ \"torch.linalg.svd: keyword argument `driver=` is only supported on CUDA inputs with cuSOLVER backend.\");\n+ if (driver.has_value() && at::globalContext().hasROCM()) {\n+ TORCH_WARN_ONCE(\n+ \"torch.linalg.svd: the `driver` argument is ignored on ROCm; \"\n+ \"the default algorithm and fallback behavior are unchanged.\");\n+ }\n+\n // Half optimisation half precondition for some parts of the LAPACK / cuSOLVER\n // In particular, the call to lapackSvd to compute lwork fails otherwise\n if (A.numel() == 0) {\n@@ -3165,12 +3179,6 @@ TORCH_IMPL_FUNC(_linalg_svd_out)(const Tensor& A,\n return;\n }\n \n- // We need to distinguish the cuSOLVER case, as cuSOLVER expects F-contig matrices, but\n- // it computes V rather than Vh\n- const bool use_cusolver = at::native::svd_uses_cusolver(A);\n- TORCH_CHECK(use_cusolver || !driver.has_value(),\n- \"torch.linalg.svd: keyword argument `driver=` is only supported on CUDA inputs with cuSOLVER backend.\");\n-\n // A always needs to be copied as its contents will be destroyed during the computation of the SVD\n // Now, MAGMA needs the copy to be on CPU, while cuSOLVER needs it to be on CUDA, so we'll defer\n // the copy as a column major matrix to the backends.\ndiff --git a/aten/src/ATen/native/cuda/linalg/BatchLinearAlgebraLib.cpp b/aten/src/ATen/native/cuda/linalg/BatchLinearAlgebraLib.cpp\nindex 77357c370de9d..9b19e2b211331 100644\n--- a/aten/src/ATen/native/cuda/linalg/BatchLinearAlgebraLib.cpp\n+++ b/aten/src/ATen/native/cuda/linalg/BatchLinearAlgebraLib.cpp\n@@ -753,8 +753,10 @@ void svd_cusolver(const Tensor& A,\n // The default heuristic is to use gesvdj driver\n #ifdef USE_ROCM\n const auto driver_v = std::string_view(\"gesvdj\");\n+ const bool user_selected_driver = false;\n #else\n const auto driver_v = driver.value_or(\"gesvdj\");\n+ const bool user_selected_driver = driver.has_value();\n #endif\n \n if (driver_v == \"gesvd\") {\n@@ -777,7 +779,7 @@ void svd_cusolver(const Tensor& A,\n // We do a transpose here to make it also work for (m < n) matrices.\n svd_cusolver_gesvdaStridedBatched(A, U, S, V, info, full_matrices, compute_uv);\n } else {\n- TORCH_CHECK(false, \"torch.linalg.svd: unknown svd driver \", driver_v, \" in svd_cusolver computation. \", check_svd_doc);\n+ TORCH_INTERNAL_ASSERT(false, \"Unexpected SVD driver: \", driver_v);\n }\n \n // Need convergence check\n@@ -790,14 +792,14 @@ void svd_cusolver(const Tensor& A,\n TORCH_WARN_ONCE(\"torch.linalg.svd: During SVD computation with the selected cusolver driver, \",\n _format_non_converging_batches(svd_non_converging_batches),\n \" failed to converge. \",\n- (driver.has_value()\n+ (user_selected_driver\n ? \"It is recommended to redo this SVD with another driver. \"\n : \"A more accurate method will be used to compute the SVD as a fallback. \"),\n check_svd_doc);\n \n- // We'll do the fallback if user doesn't specify a driver and the default heuristic doesn't converge well.\n- // However, if user manually chooses a driver, should we just do a warning or a hard crash?\n- if (!driver.has_value()) {\n+ // Fall back when using the default driver. On ROCm, the unsupported driver\n+ // argument is ignored and must not suppress the fallback.\n+ if (!user_selected_driver) {\n svd_cusolver_gesvd(A, U, S, V, info, full_matrices, compute_uv, false, svd_non_converging_batches);\n }\n }\ndiff --git a/torch/_meta_registrations.py b/torch/_meta_registrations.py\nindex 0d60016062b05..7adb78a71401a 100644\n--- a/torch/_meta_registrations.py\n+++ b/torch/_meta_registrations.py\n@@ -1845,6 +1845,10 @@ def _linalg_svd_meta(\n ):\n checkIsMatrix(A, \"linalg.svd\")\n checkFloatingOrComplex(A, \"linalg.svd\")\n+ torch._check(\n+ driver is None or driver in (\"gesvd\", \"gesvdj\", \"gesvda\"),\n+ lambda: f\"torch.linalg.svd: unknown svd driver {driver}. Expected one of gesvd, gesvdj, or gesvda.\",\n+ )\n \n batch_dims = list(A.shape[:-2])\n m = A.shape[-2]\ndiff --git a/torch/linalg/__init__.py b/torch/linalg/__init__.py\nindex 07f8be97133ff..85f97eb456fe8 100644\n--- a/torch/linalg/__init__.py\n+++ b/torch/linalg/__init__.py\n@@ -1772,7 +1772,7 @@\n \n The parameter :attr:`full_matrices` chooses between the full (default) and reduced SVD.\n \n-The :attr:`driver` kwarg may be used in CUDA with a cuSOLVER backend to choose the algorithm used to compute the SVD.\n+The :attr:`driver` kwarg may be used on NVIDIA CUDA with a cuSOLVER backend to choose the algorithm used to compute the SVD.\n The choice of a driver is a trade-off between accuracy and speed.\n \n - If :attr:`A` is well-conditioned (its `condition number`_ is not too large), or you do not mind some precision loss.\n@@ -1784,6 +1784,10 @@\n \n By default (:attr:`driver`\\ `= None`), we call `'gesvdj'` and, if it fails, we fallback to `'gesvd'`.\n \n+On ROCm, valid non-``None`` driver names are ignored with a once-only warning.\n+They do not change the default algorithm or disable its fallback.\n+Invalid driver names raise an error, including for empty inputs.\n+\n Differences with `numpy.linalg.svd`:\n \n - Unlike `numpy.linalg.svd`, this function always returns a tuple of three tensors\n@@ -1844,8 +1848,10 @@\n `U` and `Vh`. Default: `True`.\n \n Keyword args:\n- driver (str, optional): name of the cuSOLVER method to be used. This keyword argument only works on CUDA inputs.\n+ driver (str, optional): name of the cuSOLVER method to be used on NVIDIA CUDA inputs.\n Available options are: `None`, `gesvd`, `gesvdj`, and `gesvda`.\n+ On ROCm, non-``None`` values are ignored with a once-only warning.\n+ Non-``None`` values require the cuSOLVER/hipSOLVER backend, even for empty inputs.\n Default: `None`.\n out (tuple, optional): output tuple of three tensors. Ignored if `None`.\n \n@@ -1914,8 +1920,10 @@\n A (Tensor): tensor of shape `(*, m, n)` where `*` is zero or more batch dimensions.\n \n Keyword args:\n- driver (str, optional): name of the cuSOLVER method to be used. This keyword argument only works on CUDA inputs.\n+ driver (str, optional): name of the cuSOLVER method to be used on NVIDIA CUDA inputs.\n Available options are: `None`, `gesvd`, `gesvdj`, and `gesvda`.\n+ On ROCm, non-``None`` values are ignored with a once-only warning.\n+ Non-``None`` values require the cuSOLVER/hipSOLVER backend, even for empty inputs.\n Check :func:`torch.linalg.svd` for details.\n Default: `None`.\n out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.\n\ndiff --git a/test/test_linalg.py b/test/test_linalg.py\nindex b41fffd727868..333e65fbebde8 100644\n--- a/test/test_linalg.py\n+++ b/test/test_linalg.py\n@@ -4,6 +4,7 @@\n import torch\n import torch.autograd.forward_ad as fwAD\n import torch.nn.functional as F\n+from torch._subclasses.fake_tensor import FakeTensorMode\n import numpy as np\n \n import os\n@@ -57,6 +58,7 @@\n from torch.testing._internal.common_utils import (\n IS_LINUX,\n TEST_WITH_SLOW,\n+ set_warn_always_context,\n )\n \n f8_msg = \"FP8 is only supported on H100+, SM 8.9 and MI300+, XPU and CPU devices\"\n@@ -3065,6 +3067,123 @@ def mul_svd_factors(U, S, Vh):\n S_s = torch.svd(A, compute_uv=False).S\n self.assertEqual(S_s, S)\n \n+ def _svd_driver_calls(self, A, driver):\n+ return (\n+ (\"svd\", partial(torch.linalg.svd, A, driver=driver)),\n+ (\"svd_out\", partial(\n+ torch.linalg.svd, A, driver=driver,\n+ out=(A.new_empty(0), A.real.new_empty(0), A.new_empty(0)))),\n+ (\"svdvals\", partial(torch.linalg.svdvals, A, driver=driver)),\n+ (\"svdvals_out\", partial(\n+ torch.linalg.svdvals, A, driver=driver, out=A.real.new_empty(0))),\n+ )\n+\n+ def _assert_svd_driver_error(self, A, driver, msg):\n+ for op, call in self._svd_driver_calls(A, driver):\n+ with self.subTest(shape=A.shape, op=op):\n+ with self.assertRaisesRegex(RuntimeError, msg):\n+ call()\n+\n+ def _call_without_rocm_driver_warning(self, call):\n+ with warnings.catch_warnings(record=True) as caught:\n+ warnings.simplefilter(\"always\")\n+ with set_warn_always_context(True):\n+ result = call()\n+ self.assertFalse([w.message for w in caught if \"ignored on ROCm\" in str(w.message)])\n+ return result\n+\n+ @onlyNativeDeviceTypes\n+ @parametrize(\"mode\", (\"real\", \"fake\"))\n+ @parametrize(\"op\", (\"svd\", \"svd_out\", \"svdvals\", \"svdvals_out\"))\n+ def test_svd_driver_validation(self, device, mode, op):\n+ with FakeTensorMode() if mode == \"fake\" else contextlib.nullcontext():\n+ for shape in ((2, 2), (0, 0), (2, 0), (0, 2), (0, 2, 2)):\n+ A = torch.empty(shape, device=device)\n+ for driver in (\"invalid\", \"\"):\n+ with self.subTest(shape=shape, driver=driver):\n+ with self.assertRaisesRegex(RuntimeError, \"torch.linalg.svd: unknown svd driver\"):\n+ dict(self._svd_driver_calls(A, driver))[op]()\n+\n+ @onlyCPU\n+ @parametrize(\"mode\", (\"fake\", \"meta\"))\n+ @dtypes(torch.float32, torch.complex64)\n+ def test_svd_driver_meta(self, device, dtype, mode):\n+ with FakeTensorMode() if mode == \"fake\" else contextlib.nullcontext():\n+ for shape in ((2, 2), (0, 0), (2, 0), (0, 2), (0, 2, 2)):\n+ A = torch.empty(shape, device=\"meta\" if mode == \"meta\" else device, dtype=dtype)\n+ if mode == \"meta\":\n+ # Meta ignores the device; test_svd_driver_validation covers the other modes.\n+ for driver in (\"invalid\", \"\"):\n+ with self.subTest(driver=driver):\n+ self._assert_svd_driver_error(A, driver, \"torch.linalg.svd: unknown svd driver\")\n+ expected = [call() for _, call in self._svd_driver_calls(A, None)]\n+ for driver in (\"gesvd\", \"gesvdj\", \"gesvda\"):\n+ for (op, call), result in zip(self._svd_driver_calls(A, driver), expected):\n+ with self.subTest(shape=shape, driver=driver, op=op):\n+ actual = call()\n+ actual = actual if isinstance(actual, tuple) else (actual,)\n+ result = result if isinstance(result, tuple) else (result,)\n+ for tensor, reference in zip(actual, result):\n+ self.assertEqual(tensor.shape, reference.shape)\n+ self.assertEqual(tensor.dtype, reference.dtype)\n+ self.assertEqual(tensor.stride(), reference.stride())\n+\n+ @onlyCPU\n+ def test_svd_driver_cpu(self, device):\n+ msg = \"keyword argument `driver=` is only supported on CUDA inputs with cuSOLVER backend\"\n+\n+ for driver in (\"gesvd\", \"gesvdj\", \"gesvda\"):\n+ for shape in ((2, 2), (0, 0), (2, 0), (0, 2), (0, 2, 2)):\n+ self._assert_svd_driver_error(\n+ torch.empty(shape, device=device), driver, msg)\n+\n+ @onlyCUDA\n+ @skipIfRocm\n+ @skipCUDAIf(not torch.cuda.has_magma, \"requires MAGMA\")\n+ @setLinalgBackendsToDefaultFinally\n+ def test_svd_driver_magma(self, device):\n+ torch.backends.cuda.preferred_linalg_library(\"magma\")\n+ msg = \"keyword argument `driver=` is only supported on CUDA inputs with cuSOLVER backend\"\n+\n+ for shape in ((2, 2), (0, 0), (2, 0), (0, 2), (0, 2, 2)):\n+ A = torch.empty(shape, device=device)\n+ for driver in (\"gesvd\", \"gesvdj\", \"gesvda\"):\n+ self._assert_svd_driver_error(A, driver, msg)\n+ self._assert_svd_driver_error(A, \"invalid\", \"torch.linalg.svd: unknown svd driver\")\n+\n+ @onlyNativeDeviceTypes\n+ @skipCPUIfNoLapack\n+ @skipCUDAIfNoCusolver\n+ @dtypes(torch.float32, torch.complex64)\n+ def test_svd_driver_default(self, device, dtype):\n+ for shape in ((2, 2), (0, 0), (2, 0), (0, 2), (0, 2, 2)):\n+ A = (torch.diag(torch.tensor([2.0, 1.0], device=device, dtype=dtype))\n+ if shape == (2, 2) else torch.empty(shape, device=device, dtype=dtype))\n+ U, S, Vh = torch.linalg.svd(A)\n+ k = min(shape[-2:])\n+ self.assertEqual((U[..., :k] * S.unsqueeze(-2)) @ Vh[..., :k, :], A)\n+ for op, call in self._svd_driver_calls(A, None):\n+ actual = self._call_without_rocm_driver_warning(call)\n+ self.assertEqual(actual, S if \"svdvals\" in op else (U, S, Vh))\n+\n+ @onlyCUDA\n+ @skipCUDAIfNoCusolver\n+ @skipCUDAIfNotRocm\n+ @dtypes(torch.float32, torch.complex64)\n+ def test_svd_driver_ignored_on_rocm(self, device, dtype):\n+ # These convergent controls check warnings and ignored selection, not fallback execution.\n+ for shape in ((2, 2), (0, 0), (2, 0), (0, 2), (0, 2, 2)):\n+ A = (torch.diag(torch.tensor([2.0, 1.0], device=device, dtype=dtype))\n+ if shape == (2, 2) else torch.empty(shape, device=device, dtype=dtype))\n+ expected = [self._call_without_rocm_driver_warning(call)\n+ for _, call in self._svd_driver_calls(A, None)]\n+ for driver in (\"gesvd\", \"gesvdj\", \"gesvda\"):\n+ for (op, call), result in zip(self._svd_driver_calls(A, driver), expected):\n+ with self.subTest(shape=shape, driver=driver, op=op):\n+ with self.assertWarnsOnceRegex(UserWarning, \".*driver.*ignored on ROCm\"):\n+ actual = call()\n+ self.assertEqual(actual, result)\n+\n @skipCPUIfNoLapack\n @skipCUDAIf(\n not TEST_WITH_ROCM and _get_torch_cuda_version() < (12, 8) and not torch.cuda.has_magma,\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: pytorch/pytorch\nPull request: Fix int32 plane offset overflow in adaptive_max_pool2d CUDA kernels\nLabels: triaged, open source, Merged, ciflow/trunk, release notes: cuda, topic: bug fixes\nFiles changed (2): aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu, test/nn/test_pooling.py\n\n## Description (results removed)\n\nFixes #197461. The report was derived from the kernel source; I reproduced both the backward and the forward crash on an H200 and this fixes both. After review I switched to a 32-bit/64-bit dispatch so ordinary sizes keep the old code (the timing below compares it with main), and the 64-bit path now also covers a single H*W plane past 2^31 elements. I reviewed the diff and the new test, and the tests below were run on our H200 server.\n\nThe description below was drafted with Claude Code and reviewed by me:\n\n> The three adaptive_max_pool2d CUDA kernels (forward, backward, atomic\n> backward) select their plane with `int o_plane = blockIdx.x` and then offset\n> the base pointers by `o_plane * osizeH * osizeW` (output, indices) and\n> `i_plane * isizeH * isizeW` (gradInput). The sizes are `int` kernel\n> parameters, so the whole product is 32-bit and wraps once a plane starts at\n> element 2^31. The backward always runs the atomic kernel, so any input with\n> N*C*H*W > 2^31 whose last plane starts past INT_MAX takes an illegal memory\n> access; the forward hits the same wrap on the output/indices side once the\n> output exceeds 2^31 elements. The input side of the forward was already fine\n> because `istrideD` is int64_t.\n>\n> The kernels now take an `index_t` template parameter for the plane index and\n> for the plane-local math (argmax, the H/W sizes and the loop indices), and the\n> launchers pick `int` when everything fits in 32 bits and `int64_t` otherwise,\n> the same scheme AdaptiveAveragePooling.cu uses. The forward checks the output\n> and the size of one input plane, which argmax indexes into; the input itself is\n> addressed through `int64_t` strides, so a large input with a small output (e.g.\n> global pooling) stays on the 32-bit path. The backward checks gradInput and\n> gradOutput. Making the plane index `int64_t` unconditionally also fixes the\n> ordinary shapes: with a 64-bit plane base, nvcc can no longer keep the\n> per-element indexing in 32-bit arithmetic, and the float/half/bfloat16 forward\n> kernels went from 32 to 40/38 registers. Computing the offset with a single\n> widening multiply did not change that. With the dispatch, the `int`\n> instantiations compile to the same SASS as main, so only tensors that need\n> 64-bit indexing take the 64-bit path.\n>\n> Test Plan:\n>\n> New test `test_adaptive_max_pool2d_large_plane_offset` in\n> test/nn/test_pooling.py pools 33 planes of 8192x8192 (the last one starts at\n> element 2^31) and compares the last plane's output, indices and gradient\n> against the same plane pooled on its own. output_size=128 covers the backward\n> overflow and a forward that stays on the 32-bit path with an input past 2^31\n> elements (peak 8.4 GiB); output_size=8192 also covers the forward output and\n> indices overflow (peak 33.0 GiB); the memory requirement is set per case so\n> the backward case still runs on 24 GB GPUs. A second new test,\n> `test_adaptive_max_pool2d_large_single_plane`, pools a single 46341x46341 plane\n> (more than 2^31 elements) with the maximum in its last element and checks the\n> returned index and where the gradient lands.\n>\n>\n> ```\n> python test/nn/test_pooling.py -k test_adaptive_max_pool2d_large_plane_offset -v # nightly 2.15.0.dev20260923: illegal memory access (both cases); with fix: OK\n> python test/nn/test_pooling.py -k test_adaptive_max_pool2d_large_single_plane -v # nightly: wrong index; with fix: OK\n> compute-sanitizer --tool memcheck python repro.py bwd_n33 # 0 errors\n> compute-sanitizer --tool memcheck python repro.py fwd_n33 # 0 errors\n> ```\n>\n> Timing (H200, torch.utils.benchmark median in ms, main and the patched\n> libtorch_cuda run alternately on the same idle GPU): the forward and backward\n> of this PR are within run-to-run noise of main for every case, while the\n> argmax and the sizes became `index_t`; the `int` instantiations now compile to\n>\n> | dtype | input -> output size | fwd main | fwd int64 everywhere | fwd this PR | bwd main | bwd this PR |\n> | --- | --- | --- | --- | --- | --- | --- |\n> | fp32 | (128, 2048, 7, 7) -> 1 | 0.3769 | 0.3752 | 0.3768 | 0.1750 | 0.1748 |\n> | fp32 | (8, 64, 224, 224) -> 75 | 0.1107 | 0.1063 | 0.1108 | 0.0983 | 0.0982 |\n> | fp32 | (4, 3, 1024, 1024) -> 32 | 0.1406 | 0.1376 | 0.1411 | 0.0170 | 0.0164 |\n> | fp16 | (8, 64, 224, 224) -> 75 | 0.1135 | 0.1113 | 0.1134 | 0.0667 | 0.0666 |\n> | fp16 | (4, 3, 1024, 1024) -> 32 | 0.0727 | 0.0718 | 0.0727 | 0.0101 | 0.0098 |\n\n## Diff\n\n```diff\ndiff --git a/aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu b/aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu\nindex 93cb55d43b1df..cacac3d17b0b0 100644\n--- a/aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu\n+++ b/aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu\n@@ -6,6 +6,7 @@\n #include \n #include \n #include \n+#include \n #include \n #include \n \n@@ -42,26 +43,26 @@ __device__ inline int64_t end_index(int64_t a, int64_t b, int64_t c) {\n * this function adaptively maxpools an input 4D tensor along dimensions 2 and 3\n * 4D input, 4D output, 4D argmax x and y\n */\n- template \n+ template \n __global__ void adaptivemaxpool(const T *input, T *output, int64_t *indices,\n- int isizeH, int isizeW,\n- int osizeH, int osizeW,\n+ index_t isizeH, index_t isizeW,\n+ index_t osizeH, index_t osizeW,\n int64_t istrideD, int64_t istrideH, int64_t istrideW)\n {\n // iterators\n- int oh, ow;\n+ index_t oh, ow;\n \n // compute offsets based on thread/block ID\n- int o_plane = blockIdx.x;\n- int i_plane = o_plane;\n+ index_t o_plane = blockIdx.x;\n+ index_t i_plane = o_plane;\n \n- int ostartW = threadIdx.x;\n- int oendW = osizeW;\n- const int ostepW = blockDim.x;\n+ index_t ostartW = threadIdx.x;\n+ index_t oendW = osizeW;\n+ const index_t ostepW = blockDim.x;\n \n- int ostartH = blockDim.y*blockIdx.y + threadIdx.y;\n- int oendH = osizeH;\n- const int ostepH = blockDim.y*gridDim.y;\n+ index_t ostartH = blockDim.y*blockIdx.y + threadIdx.y;\n+ index_t oendH = osizeH;\n+ const index_t ostepH = blockDim.y*gridDim.y;\n // select input/output plane\n output = output + o_plane*osizeH*osizeW;\n input = input + i_plane*istrideD;\n@@ -70,23 +71,23 @@ __global__ void adaptivemaxpool(const T *input, T *output, int64_t *indices,\n // For all output pixels...\n for(oh = ostartH; oh < oendH; oh += ostepH) {\n \n- int istartH = start_index(oh, osizeH, isizeH);\n- int iendH = end_index(oh, osizeH, isizeH);\n- int kH = iendH - istartH;\n+ index_t istartH = start_index(oh, osizeH, isizeH);\n+ index_t iendH = end_index(oh, osizeH, isizeH);\n+ index_t kH = iendH - istartH;\n \n for(ow = ostartW; ow < oendW; ow += ostepW) {\n- int istartW = start_index(ow, osizeW, isizeW);\n- int iendW = end_index(ow, osizeW, isizeW);\n+ index_t istartW = start_index(ow, osizeW, isizeW);\n+ index_t iendW = end_index(ow, osizeW, isizeW);\n \n- int kW = iendW - istartW;\n+ index_t kW = iendW - istartW;\n \n // Compute the mean of the input image...\n const T *ptr_input = input + istartH*istrideH + istartW*istrideW;\n T *ptr_output = output + oh*osizeW + ow;\n int64_t *ptr_ind = indices + oh*osizeW + ow;\n- int argmax = istartH * isizeW + istartW;\n+ index_t argmax = istartH * isizeW + istartW;\n T max = at::numeric_limits::lower_bound(); // -Infinity\n- int ih, iw;\n+ index_t ih, iw;\n for(ih = 0; ih < kH; ih++) {\n for(iw = 0; iw < kW; iw++) {\n T val = ptr_input[iw*istrideW];\n@@ -108,26 +109,26 @@ __global__ void adaptivemaxpool(const T *input, T *output, int64_t *indices,\n * Description:\n * this function computes the gradInput from weight and gradOutput\n */\n- template \n+ template \n __global__ void adaptivemaxgradinput(T *gradInput, const T *gradOutput, const int64_t *indices,\n- int isizeH, int isizeW,\n- int osizeH, int osizeW)\n+ index_t isizeH, index_t isizeW,\n+ index_t osizeH, index_t osizeW)\n {\n // iterators\n- int oh, ow;\n+ index_t oh, ow;\n \n // compute offsets based on thread/block ID\n- int o_plane = blockIdx.x;\n- int i_plane = o_plane;\n+ index_t o_plane = blockIdx.x;\n+ index_t i_plane = o_plane;\n //int k = blockIdx.x % sizeD;\n \n- int ostartW = threadIdx.x;\n- int oendW = osizeW;\n- int ostepW = blockDim.x;\n+ index_t ostartW = threadIdx.x;\n+ index_t oendW = osizeW;\n+ index_t ostepW = blockDim.x;\n \n- int ostartH = blockDim.y*blockIdx.y + threadIdx.y;\n- int oendH = osizeH;\n- int ostepH = blockDim.y*gridDim.y;\n+ index_t ostartH = blockDim.y*blockIdx.y + threadIdx.y;\n+ index_t oendH = osizeH;\n+ index_t ostepH = blockDim.y*gridDim.y;\n \n // select input/output plane\n gradOutput = gradOutput + o_plane*osizeH*osizeW;\n@@ -143,7 +144,7 @@ __global__ void adaptivemaxgradinput(T *gradInput, const T *gradOutput, const in\n const int64_t *ptr_ind = indices + oh*osizeW + ow;\n T z = *ptr_gradOutput;\n \n- int argmax = (*ptr_ind);\n+ index_t argmax = (*ptr_ind);\n \n gradInput[argmax] += z;\n }\n@@ -155,26 +156,26 @@ __global__ void adaptivemaxgradinput(T *gradInput, const T *gradOutput, const in\n * this function computes the gradInput from weight and gradOutput\n * when kH != dH or kW != dW (uses atomic add)\n */\n- template \n+ template \n __global__ void atomicadaptivemaxgradinput(\n T *gradInput, const T *gradOutput, const int64_t *indices,\n- int isizeH, int isizeW, int osizeH, int osizeW\n+ index_t isizeH, index_t isizeW, index_t osizeH, index_t osizeW\n )\n {\n // iterators\n- int oh, ow;\n+ index_t oh, ow;\n \n // compute offsets based on thread/block ID\n- int o_plane = blockIdx.x;\n- int i_plane = o_plane;\n+ index_t o_plane = blockIdx.x;\n+ index_t i_plane = o_plane;\n \n- int ostartW = threadIdx.x;\n- int oendW = osizeW;\n- int ostepW = blockDim.x;\n+ index_t ostartW = threadIdx.x;\n+ index_t oendW = osizeW;\n+ index_t ostepW = blockDim.x;\n \n- int ostartH = blockDim.y*blockIdx.y + threadIdx.y;\n- int oendH = osizeH;\n- int ostepH = blockDim.y*gridDim.y;\n+ index_t ostartH = blockDim.y*blockIdx.y + threadIdx.y;\n+ index_t oendH = osizeH;\n+ index_t ostepH = blockDim.y*gridDim.y;\n \n // select input/output plane\n gradOutput = gradOutput + o_plane*osizeH*osizeW;\n@@ -190,7 +191,7 @@ __global__ void atomicadaptivemaxgradinput(\n const int64_t *ptr_ind = indices + oh*osizeW + ow;\n T z = *ptr_gradOutput;\n \n- int argmax = (*ptr_ind);\n+ index_t argmax = (*ptr_ind);\n \n // atomic add since different threads could update same variable\n fastAtomicAdd(gradInput, argmax, isizeH * isizeW, z, true);\n@@ -221,6 +222,12 @@ const Tensor& indices) {\n \n const at::Tensor output_c = output.is_contiguous() ? output : at::empty(output.sizes(), output.options());\n const at::Tensor indices_c = indices.is_contiguous() ? indices : at::empty(indices.sizes(), indices.options());\n+ // The input is indexed through int64_t strides, so besides the output only the input plane, which\n+ // argmax indexes into, needs to fit in 32 bits.\n+ const auto index_type = canUse32BitIndexMath(output_c) &&\n+ input.size(-2) * input.size(-1) <= std::numeric_limits::max()\n+ ? ScalarType::Int\n+ : ScalarType::Long;\n \n if (input.ndimension() == 3) {\n int64_t sizeD = input.size(0);\n@@ -244,22 +251,24 @@ const Tensor& indices) {\n dim3 threads(32, 8);\n \n // run maxpool kernel\n- adaptivemaxpool<<<\n- blocks,\n- threads,\n- 0,\n- at::cuda::getCurrentCUDAStream()>>>(\n- input_data,\n- output_data,\n- indices_data,\n- isizeH,\n- isizeW,\n- osizeH,\n- osizeW,\n- istrideD,\n- istrideH,\n- istrideW);\n- C10_CUDA_KERNEL_LAUNCH_CHECK();\n+ AT_DISPATCH_INDEX_TYPES(index_type, \"adaptive_max_pool2d_cuda_index\", [&] {\n+ adaptivemaxpool<<<\n+ blocks,\n+ threads,\n+ 0,\n+ at::cuda::getCurrentCUDAStream()>>>(\n+ input_data,\n+ output_data,\n+ indices_data,\n+ isizeH,\n+ isizeW,\n+ osizeH,\n+ osizeW,\n+ istrideD,\n+ istrideH,\n+ istrideW);\n+ C10_CUDA_KERNEL_LAUNCH_CHECK();\n+ });\n });\n } else {\n Tensor input_ = input.contiguous();\n@@ -293,22 +302,24 @@ const Tensor& indices) {\n dim3 threads(32, 8);\n \n // run maxpool kernel\n- adaptivemaxpool<<<\n- blocks,\n- threads,\n- 0,\n- at::cuda::getCurrentCUDAStream()>>>(\n- input_data,\n- output_data,\n- indices_data,\n- isizeH,\n- isizeW,\n- osizeH,\n- osizeW,\n- istrideD,\n- istrideH,\n- istrideW);\n- C10_CUDA_KERNEL_LAUNCH_CHECK();\n+ AT_DISPATCH_INDEX_TYPES(index_type, \"adaptive_max_pool2d_cuda_index\", [&] {\n+ adaptivemaxpool<<<\n+ blocks,\n+ threads,\n+ 0,\n+ at::cuda::getCurrentCUDAStream()>>>(\n+ input_data,\n+ output_data,\n+ indices_data,\n+ isizeH,\n+ isizeW,\n+ osizeH,\n+ osizeW,\n+ istrideD,\n+ istrideH,\n+ istrideW);\n+ C10_CUDA_KERNEL_LAUNCH_CHECK();\n+ });\n });\n }\n \n@@ -347,6 +358,9 @@ TORCH_IMPL_FUNC(adaptive_max_pool2d_backward_out_cuda)\n const at::Tensor gradOutput_ = gradOutput.contiguous();\n const at::Tensor indices_ = indices.contiguous();\n const at::Tensor gradInput_c = gradInput.is_contiguous() ? gradInput : at::empty(gradInput.sizes(), gradInput.options());\n+ const auto index_type = canUse32BitIndexMath(gradInput_c) && canUse32BitIndexMath(gradOutput_)\n+ ? ScalarType::Int\n+ : ScalarType::Long;\n \n if (input.ndimension() == 3) {\n int64_t sizeD = input.size(0);\n@@ -376,37 +390,39 @@ TORCH_IMPL_FUNC(adaptive_max_pool2d_backward_out_cuda)\n dim3 blocks(sizeD, blocksH);\n dim3 threads(32, 8);\n \n- if (atomic) {\n- // run updateGradInput kernel, accumulate gradients atomically\n- atomicadaptivemaxgradinput<<<\n- blocks,\n- threads,\n- 0,\n- at::cuda::getCurrentCUDAStream()>>>(\n- gradInput_data,\n- gradOutput_data,\n- indices_data,\n- isizeH,\n- isizeW,\n- osizeH,\n- osizeW);\n- C10_CUDA_KERNEL_LAUNCH_CHECK();\n- } else {\n- // run updateGradInput kernel\n- adaptivemaxgradinput<<<\n- blocks,\n- threads,\n- 0,\n- at::cuda::getCurrentCUDAStream()>>>(\n- gradInput_data,\n- gradOutput_data,\n- indices_data,\n- isizeH,\n- isizeW,\n- osizeH,\n- osizeW);\n- C10_CUDA_KERNEL_LAUNCH_CHECK();\n- }\n+ AT_DISPATCH_INDEX_TYPES(index_type, \"adaptive_max_pool2d_backward_cuda_index\", [&] {\n+ if (atomic) {\n+ // run updateGradInput kernel, accumulate gradients atomically\n+ atomicadaptivemaxgradinput<<<\n+ blocks,\n+ threads,\n+ 0,\n+ at::cuda::getCurrentCUDAStream()>>>(\n+ gradInput_data,\n+ gradOutput_data,\n+ indices_data,\n+ isizeH,\n+ isizeW,\n+ osizeH,\n+ osizeW);\n+ C10_CUDA_KERNEL_LAUNCH_CHECK();\n+ } else {\n+ // run updateGradInput kernel\n+ adaptivemaxgradinput<<<\n+ blocks,\n+ threads,\n+ 0,\n+ at::cuda::getCurrentCUDAStream()>>>(\n+ gradInput_data,\n+ gradOutput_data,\n+ indices_data,\n+ isizeH,\n+ isizeW,\n+ osizeH,\n+ osizeW);\n+ C10_CUDA_KERNEL_LAUNCH_CHECK();\n+ }\n+ });\n });\n } else {\n int64_t sizeB = input.size(0);\n@@ -437,37 +453,39 @@ TORCH_IMPL_FUNC(adaptive_max_pool2d_backward_out_cuda)\n dim3 blocks(sizeB * sizeD, blocksH);\n dim3 threads(32, 8);\n \n- if (atomic) {\n- // run updateGradInput kernel, accumulate gradients atomically\n- atomicadaptivemaxgradinput<<<\n- blocks,\n- threads,\n- 0,\n- at::cuda::getCurrentCUDAStream()>>>(\n- gradInput_data,\n- gradOutput_data,\n- indices_data,\n- isizeH,\n- isizeW,\n- osizeH,\n- osizeW);\n- C10_CUDA_KERNEL_LAUNCH_CHECK();\n- } else {\n- // run updateGradInput kernel, accumulate gradients atomically\n- adaptivemaxgradinput<<<\n- blocks,\n- threads,\n- 0,\n- at::cuda::getCurrentCUDAStream()>>>(\n- gradInput_data,\n- gradOutput_data,\n- indices_data,\n- isizeH,\n- isizeW,\n- osizeH,\n- osizeW);\n- C10_CUDA_KERNEL_LAUNCH_CHECK();\n- }\n+ AT_DISPATCH_INDEX_TYPES(index_type, \"adaptive_max_pool2d_backward_cuda_index\", [&] {\n+ if (atomic) {\n+ // run updateGradInput kernel, accumulate gradients atomically\n+ atomicadaptivemaxgradinput<<<\n+ blocks,\n+ threads,\n+ 0,\n+ at::cuda::getCurrentCUDAStream()>>>(\n+ gradInput_data,\n+ gradOutput_data,\n+ indices_data,\n+ isizeH,\n+ isizeW,\n+ osizeH,\n+ osizeW);\n+ C10_CUDA_KERNEL_LAUNCH_CHECK();\n+ } else {\n+ // run updateGradInput kernel\n+ adaptivemaxgradinput<<<\n+ blocks,\n+ threads,\n+ 0,\n+ at::cuda::getCurrentCUDAStream()>>>(\n+ gradInput_data,\n+ gradOutput_data,\n+ indices_data,\n+ isizeH,\n+ isizeW,\n+ osizeH,\n+ osizeW);\n+ C10_CUDA_KERNEL_LAUNCH_CHECK();\n+ }\n+ });\n });\n }\n \ndiff --git a/test/nn/test_pooling.py b/test/nn/test_pooling.py\nindex 3b9f1f8620afc..2d5bb943ff131 100644\n--- a/test/nn/test_pooling.py\n+++ b/test/nn/test_pooling.py\n@@ -2543,6 +2543,38 @@ def test_avg_pool2d_backward_nonoverlapping_large(self, device):\n self.assertEqual(grad_input[..., ph * k :, :].count_nonzero().item(), 0)\n self.assertEqual(grad_input[..., :, pw * k :].count_nonzero().item(), 0)\n \n+ [comment with results removed]\n+ # output_size=128 overflows the int32 gradInput plane offset; 8192 also overflows\n+ # the output and indices plane offsets. The last plane is checked against the same\n+ # plane pooled on its own. See #197461.\n+ @largeTensorTest(lambda self, device, size: (10 if size == 128 else 36) * 2**30)\n+ @parametrize_test(\"size\", [128, 8192])\n+ def test_adaptive_max_pool2d_large_plane_offset(self, device, size):\n+ x = torch.randn(33, 1, 8192, 8192, device=device, dtype=torch.half)\n+ x.requires_grad_()\n+ out, idx = F.adaptive_max_pool2d(x, size, return_indices=True)\n+ (grad,) = torch.autograd.grad(out.sum(), x)\n+ x_last = x[-1:].detach().requires_grad_()\n+ out_last, idx_last = F.adaptive_max_pool2d(x_last, size, return_indices=True)\n+ (grad_last,) = torch.autograd.grad(out_last.sum(), x_last)\n+ self.assertEqual(out[-1:], out_last)\n+ self.assertEqual(idx[-1:], idx_last)\n+ self.assertEqual(grad[-1:], grad_last)\n+\n+ [comment with results removed]\n+ # last element does not fit in int32.\n+ @largeTensorTest(\"12GB\", device=\"cuda\")\n+ def test_adaptive_max_pool2d_large_single_plane(self, device):\n+ n = 46341\n+ x = torch.zeros(1, 1, n, n, device=device, dtype=torch.half)\n+ x[..., -1, -1] = 1\n+ x.requires_grad_()\n+ out, idx = F.adaptive_max_pool2d(x, 1024, return_indices=True)\n+ self.assertEqual(idx[0, 0, -1, -1].item(), n * n - 1)\n+ (grad,) = torch.autograd.grad(out.sum(), x)\n+ self.assertEqual(grad[0, 0, -1, -1].item(), 1)\n+ self.assertEqual(grad.sum(dtype=torch.float).item(), 1024 * 1024)\n+\n @parametrize_test(\"channels_last\", [False, True])\n @parametrize_test(\n \"shape,pool_kwargs\",\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: pytorch/pytorch\nPull request: [DCP] Fix QuantizedHuggingFaceStorageReader loading only part of each MXFP4 tensor\nLabels: triaged, open source, Merged, ciflow/trunk, release notes: distributed (checkpoint), bot-triaged, ciflow/torchtitan\nFiles changed (2): test/distributed/checkpoint/test_hf_safetensor_e2e.py, torch/distributed/checkpoint/quantized_hf_storage.py\n\n## Description (results removed)\n\n- [x] Added/updated tests\n- [ ] Updated documentation (if applicable)\n- [ ] Included benchmark results (for PRs impacting perf)\n\n---\n\nFixes #200365\n\n## BC-breaking?\n\nNo\n\nSee #200365. Details of the fix and tests are under Agent details.\n\n>\n> The fix rewrites each `*_blocks` chunk to the dequantized layout and re-keys the matching `storage_data` entry, since `ReadItem`s use the chunk offset as their storage index (rewriting only the chunks turns the partial load into a `KeyError` in `read_data()`).\n>\n>\n> Authored with Claude (AI assistant).\n\n## Diff\n\n```diff\ndiff --git a/torch/distributed/checkpoint/quantized_hf_storage.py b/torch/distributed/checkpoint/quantized_hf_storage.py\nindex cd4ea438fc5c7..f4cf8a7b41e71 100644\n--- a/torch/distributed/checkpoint/quantized_hf_storage.py\n+++ b/torch/distributed/checkpoint/quantized_hf_storage.py\n@@ -10,6 +10,7 @@\n from torch.distributed.checkpoint._hf_utils import _metadata_fn\n from torch.distributed.checkpoint.metadata import (\n ChunkStorageMetadata,\n+ MetadataIndex,\n TensorStorageMetadata,\n )\n from torch.distributed.checkpoint.planner import LoadPlanner, ReadItem\n@@ -83,12 +84,28 @@ def read_metadata(self) -> Any:\n # Save the quantized tensor shapes for lookup when dequantization.\n self._tensor_full_shapes[fqn + \"_quantized\"] = tensor_metadata.size\n *prefix_shape, G, B = tensor_metadata.size\n- dequantized_size = torch.Size([*prefix_shape, G * B * 2])\n+ values_per_group = B * 2\n+ dequantized_size = torch.Size([*prefix_shape, G * values_per_group])\n \n # Update the metadata with the size after dequantization.\n # Metadata used by planner to slice state dict.\n tensor_metadata.size = dequantized_size\n self._tensor_full_shapes[fqn] = dequantized_size\n+\n+ # The planner intersects read requests with the chunks, so they\n+ # must use the dequantized layout too. storage_data is keyed by\n+ # chunk offset, so re-key it to match.\n+ storage_data = metadata.storage_data\n+ chunks = []\n+ for chunk in tensor_metadata.chunks:\n+ *prefix, group_offset, _ = chunk.offsets\n+ offsets = torch.Size([*prefix, group_offset * values_per_group])\n+ *prefix, num_groups, _ = chunk.sizes\n+ sizes = torch.Size([*prefix, num_groups * values_per_group])\n+ chunks.append(ChunkStorageMetadata(offsets, sizes))\n+ info = storage_data.pop(MetadataIndex(fqn, chunk.offsets))\n+ storage_data[MetadataIndex(fqn, offsets)] = info\n+ tensor_metadata.chunks = chunks\n elif fqn in self._weight_scale_mapping and fqn.endswith(\n \".weight_packed\"\n ):\n\ndiff --git a/test/distributed/checkpoint/test_hf_safetensor_e2e.py b/test/distributed/checkpoint/test_hf_safetensor_e2e.py\nindex 9ae745f39a979..041bfadfbce6a 100644\n--- a/test/distributed/checkpoint/test_hf_safetensor_e2e.py\n+++ b/test/distributed/checkpoint/test_hf_safetensor_e2e.py\n@@ -453,6 +453,39 @@ def test_compressed_tensors_non_mxfp4_loads_raw(self, case: str) -> None:\n torch.equal(state_dict[fqn].view(torch.uint8), t.view(torch.uint8))\n )\n \n+ @with_temp_dir\n+ def test_gpt_oss_mxfp4_loading(self) -> None:\n+ \"\"\"GPT-OSS MXFP4 _blocks load in full, not just the first G values per row.\"\"\"\n+ try:\n+ import safetensors # noqa: F401\n+ except ImportError:\n+ print(\"safetensors not installed\")\n+ return\n+\n+ # GPT-OSS _blocks [experts, rows, groups, 16] and _scales [experts, rows,\n+ # groups] hold the same bytes as compressed-tensors MXFP4.\n+ experts, rows, cols = 2, 3, 128\n+ packed, scale, expected = random_compressed_tensors_mxfp4(experts * rows, cols)\n+ fqn = \"model.layers.0.mlp.experts.down_proj\"\n+ save_hf_checkpoint(\n+ self.temp_dir,\n+ {\n+ \"model.safetensors\": {\n+ f\"{fqn}_blocks\": packed.reshape(experts, rows, cols // 32, 16),\n+ f\"{fqn}_scales\": scale.reshape(experts, rows, cols // 32),\n+ }\n+ },\n+ )\n+\n+ state_dict = {f\"{fqn}_blocks\": torch.zeros(experts, rows, cols)}\n+ dist_cp.load(\n+ state_dict=state_dict,\n+ storage_reader=QuantizedHuggingFaceStorageReader(path=self.temp_dir),\n+ )\n+ torch.testing.assert_close(\n+ state_dict[f\"{fqn}_blocks\"], expected.reshape(experts, rows, cols)\n+ )\n+\n \n class TestCompressedTensorsMXFP4ShardedLoad(DTensorTestBase):\n @with_comms\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: pytorch/pytorch\nPull request: [inductor] Fix max-autotune benchmark inputs for views rebased to a negative offset\nLabels: open source, Merged, ciflow/trunk, module: inductor, ciflow/inductor, release notes: inductor, ciflow/rocm-mi300, ciflow/h100, ciflow/b200, ciflow/torchtitan, ready for review\nFiles changed (2): test/inductor/test_max_autotune.py, torch/_inductor/select_algorithm.py\n\n## Description (results removed)\n\n* __->__ #200911\n\nFixes #200810\n\n## Summary\nInductor represents a graph input relative to its data pointer, while `as_strided`'s `storage_offset` is relative to the tensor's storage. An input produced by slicing carries a non-zero `storage_offset` (`arange(N)[x:]` gives `+x`), so rebasing an `as_strided` offset onto that input can go negative:\n\n y = base[2048:] # input storage_offset = +2048\n y.as_strided((64, 32), (32, 1), 0) # rebased view offset = 0 - 2048 = -2048\n\nIn max-autotune mode, Inductor benchmarks the candidate kernel configs on generated example inputs, and those examples were not built with that offset in mind. This PR fixes three places in `AlgorithmSelectorCache`:\n\n- `benchmark_example_value` read the layout offset after `unwrap_view()` had already dropped it;\n- `generate_example_value` sized the example storage without accounting for the offset, so the data pointer ended up in the wrong place;\n- `get_inputs` handed the negative offset straight to eager `as_strided`, which rejects it.\n\nEach now recognises the view offset shift and requests the storage size needed to hold both the buffer and the view.\n\n---\n_Generated by my agent, reviewed by me._\n\n## Root cause\n\nSince #184232, an `as_strided` offset on a graph input is rebased onto the input's data pointer, so a view reaching before that pointer gets a negative layout offset. Two places in max-autotune's benchmark input materialization did not account for it:\n\n2. `benchmark_example_value` read `node.get_layout().offset` *after* `unwrap_view()`, so the offset was silently dropped: the fake input's data pointer sat at storage offset 0 of an allocation sized only for the input's own span, while the generated kernel still folded the offset into its own pointer arithmetic (`A = arg_A + -2048`). Every template benchmark read 8KB before its allocation. This was latent behind (1).\n\n## Sizing the benchmark storage\n[results removed]\n## Test Plan\n[results removed]\n## Not fixed here (pre-existing, tracked separately)\n\nTwo other places assume the same data-pointer-relative offset convention. Both predate this change and are untouched by it:\n\n g = torch.compile(f, fullgraph=True)\n a = torch.arange(4096, device=\"cuda\")[2048:] # storage_offset 2048\n b = torch.arange(4096, device=\"cuda\")[:2048] # storage_offset 0\n g(a) # correct\n g(b) # max diff vs eager: 65536.0\n\n This is silent wrong output, and I have also seen it raise an illegal memory access. It looks like a missing guard from #184232 rather than part of this fix.\n\n---\n\n## Diff\n\n```diff\ndiff --git a/torch/_inductor/select_algorithm.py b/torch/_inductor/select_algorithm.py\nindex 076c1ab76fc26..a16b4ee8ec357 100644\n--- a/torch/_inductor/select_algorithm.py\n+++ b/torch/_inductor/select_algorithm.py\n@@ -5423,10 +5423,23 @@ def addmm_unique_example_inputs_extern():\n hint_override=hint_override,\n )\n \n+ storage_offset = cast(int, storage_offset)\n+ # Layout offsets are relative to the input data pointer, so views\n+ # reaching before it have a negative offset and as_strided\n+ # rejects those. Allocate the base to cover the rebased view and\n+ # shift the offset into it instead. The base comes from\n+ [comment with results removed]\n+ # -storage_offset elements in, so this stays absolute.\n+ shift = max(0, -storage_offset)\n+ storage_offset += shift\n+\n # Check if the required storage size exceeds the current storage\n # to avoid illegal memory access\n- needed_size = torch._prims_common.compute_required_storage_length(\n- sizes, strides, cast(int, storage_offset)\n+ needed_size = (\n+ torch._prims_common.compute_required_storage_length(\n+ sizes, strides, storage_offset\n+ )\n+ + shift\n )\n current_size = base.untyped_storage().size() // base.element_size()\n if needed_size > current_size:\n@@ -5460,8 +5473,13 @@ def addmm_unique_example_inputs_extern():\n # Only used for benchmarking tensor setup, not correctness.\n # Offset is almost always 0; use that as fallback.\n out_offset = V.graph.sizevars.optimization_hint(layout.offset, fallback=0)\n- needed_out_size = torch._prims_common.compute_required_storage_length(\n- out.size(), out.stride(), out_offset\n+ out_shift = max(0, -out_offset)\n+ out_offset += out_shift\n+ needed_out_size = (\n+ torch._prims_common.compute_required_storage_length(\n+ out.size(), out.stride(), out_offset\n+ )\n+ + out_shift\n )\n # untyped_storage() counts bytes, unlike the deprecated TypedStorage.size().\n current_out_size = out_base.untyped_storage().size() // out_base.element_size()\n@@ -6404,6 +6422,25 @@ def benchmark_example_value(node, hint_override: int | None = None):\n # Preserve the original dtype before unwrapping, since dtype views\n # (e.g. uint8 -> float4_e2m1fn_x2) would be lost by unwrap_view.\n original_dtype = node.get_dtype()\n+ # Read before unwrapping: the view's offset is relative to the buffer\n+ # being unwrapped away, and unwrap_view would drop it.\n+ view_offset = V.graph.sizevars.optimization_hint_with_override(\n+ node.get_layout().offset,\n+ hint_override=hint_override,\n+ )\n+ # The kernel indexes the whole view, which reaches past the buffer for a\n+ # positive offset, so size the fake input for the view's span as well.\n+ view_span = torch._prims_common.compute_required_storage_length(\n+ V.graph.sizevars.optimization_hints_with_override(\n+ node.get_size(),\n+ hint_override=hint_override,\n+ ),\n+ V.graph.sizevars.optimization_hints_with_override(\n+ get_strides_with_layout_constraints(node),\n+ hint_override=hint_override,\n+ ),\n+ 0,\n+ )\n if isinstance(node, ir.BaseView):\n node = node.unwrap_view()\n \n@@ -6430,6 +6467,8 @@ def benchmark_example_value(node, hint_override: int | None = None):\n V.graph.get_allocation_size(node),\n hint_override=hint_override,\n ),\n+ view_offset,\n+ view_span,\n )\n # Restore dtype if it was lost by unwrapping a dtype view\n if result.dtype != original_dtype:\n@@ -6438,27 +6477,46 @@ def benchmark_example_value(node, hint_override: int | None = None):\n \n @staticmethod\n def generate_example_value(\n- size, stride, device, dtype, extra_size, allocation_size=None\n+ size,\n+ stride,\n+ device,\n+ dtype,\n+ extra_size,\n+ allocation_size=None,\n+ view_offset=0,\n+ view_span=None,\n ):\n+ # Named for rand_strided, which the generated code calls positionally.\n+ reserve = size if allocation_size is None else allocation_size\n+ reserve_span = torch._prims_common.compute_required_storage_length(\n+ reserve, stride, 0\n+ )\n+ if view_span is None:\n+ # No separate view: the kernel indexes the buffer itself.\n+ view_span = torch._prims_common.compute_required_storage_length(\n+ size, stride, 0\n+ )\n+ # A negative view_offset reaches before the buffer and cannot be given\n+ # to as_strided, so place the data pointer that much further in.\n+ shift = max(0, -view_offset)\n+ # The kernel can index both the buffer and the whole view, so the\n+ # storage holds shift elements in front of the data pointer and then\n+ # whichever of the two reaches further past it. A negative extra_size\n+ # means the buffer has no leading region, not that it needs less of one.\n+ backing_size = max(extra_size, 0) + shift + max(reserve_span, view_span)\n+ # rand_strided allocates reserve_span + extra_size, and only pads behind,\n+ # so the view's room in front of the buffer is requested as padding.\n+ pad_after = backing_size - reserve_span\n # preserve rng states to avoid the rand_strided call below changes\n # the rng states for the real model code.\n with preserve_rng_state():\n- if allocation_size is None or allocation_size == size:\n- return rand_strided(\n- size,\n- stride,\n- device=device,\n- dtype=dtype,\n- extra_size=extra_size,\n- )\n- else:\n- return rand_strided(\n- allocation_size,\n- stride,\n- device=device,\n- dtype=dtype,\n- extra_size=extra_size,\n- ).as_strided(size, stride)\n+ return rand_strided(\n+ reserve,\n+ stride,\n+ device=device,\n+ dtype=dtype,\n+ extra_size=pad_after,\n+ ).as_strided(size, stride, shift)\n \n @staticmethod\n def key_of(node):\n\ndiff --git a/test/inductor/test_max_autotune.py b/test/inductor/test_max_autotune.py\nindex 94d1049d54689..dc2cb2bfed5c3 100644\n--- a/test/inductor/test_max_autotune.py\n+++ b/test/inductor/test_max_autotune.py\n@@ -81,6 +81,7 @@\n TritonTemplate,\n TritonTemplateCaller,\n )\n+from torch._prims_common import compute_required_storage_length\n from torch.testing._internal.common_cuda import PLATFORM_SUPPORTS_FP8, SM90OrLater\n from torch.testing._internal.common_device_type import largeTensorTest\n from torch.testing._internal.common_utils import (\n@@ -3602,6 +3603,123 @@ def mm(x, w):\n a = x[7 * batch :]\n torch.testing.assert_close(result, torch.mm(a, w), rtol=1e-2, atol=1e-2)\n \n+ @fresh_cache()\n+ @skipIfXpu\n+ @parametrize(\"view_offset,shift,extern_offset\", ((-2048, 2048, 0), (2048, 0, 2048)))\n+ def test_max_autotune_mm_rebased_storage_offset_input(\n+ self, view_offset, shift, extern_offset\n+ ):\n+ \"\"\"\n+ Regression test for https://github.com/pytorch/pytorch/issues/200810.\n+ as_strided storage offsets are relative to the input's storage, so a\n+ view of an input gets rebased to a data-pointer-relative layout offset\n+ that can point outside the input's own allocation: -2048 for\n+ x[2048:].as_strided((64, 32), (32, 1), 0) and 2048 for\n+ x[:2048].as_strided((64, 32), (32, 1), 2048). Kernels fold that offset\n+ into their own pointer arithmetic, and eager as_strided rejects the\n+ negative case, so the benchmark inputs have to be materialized with a\n+ data pointer at the same relative position in a big enough allocation.\n+ \"\"\"\n+ start = 2048 if view_offset < 0 else 0\n+ as_strided_offset = max(view_offset, 0)\n+ x = torch.arange(4096, device=GPU_TYPE, dtype=torch.float32)[\n+ start : start + 2048\n+ ]\n+ w = torch.ones(32, 64, device=GPU_TYPE)\n+\n+ def mm(a, b):\n+ return torch.mm(a.as_strided((64, 32), (32, 1), as_strided_offset), b)\n+\n+ autotune_args = []\n+ orig_get_inputs = AlgorithmSelectorCache.get_inputs.__func__\n+\n+ def spy(cls, *args, **kwargs):\n+ inputs = orig_get_inputs(cls, *args, **kwargs)\n+ autotune_args.append(inputs)\n+ return inputs\n+\n+ with (\n+ mock.patch.object(AlgorithmSelectorCache, \"get_inputs\", classmethod(spy)),\n+ config.patch(\n+ {\n+ \"max_autotune\": True,\n+ \"max_autotune_gemm_backends\": \"TRITON\",\n+ }\n+ ),\n+ ):\n+ result = torch.compile(mm, fullgraph=True)(x, w)\n+\n+ # Loads before the graph input pointer read back 0 on ROCm, so the\n+ # negative case computes zeros there and cannot be compared. Same\n+ # limitation as test_as_strided_past_input_extent in test_torchinductor.py.\n+ if view_offset >= 0 or not TEST_WITH_ROCM:\n+ torch.testing.assert_close(result, mm(x, w), rtol=1e-2, atol=1e-2)\n+\n+ self.assertTrue(autotune_args, \"autotuning did not build benchmark inputs\")\n+ # The fake input has to satisfy as_strided with the data pointer placed\n+ # where the kernel's folded offset expects it: shift elements in front,\n+ # then enough storage for the view on either side of the buffer.\n+ fake_x = autotune_args[0].triton.input_tensors[0]\n+ fake_items = fake_x.untyped_storage().size() // fake_x.element_size()\n+ ptr_off = (\n+ fake_x.data_ptr() - fake_x.untyped_storage().data_ptr()\n+ ) // fake_x.element_size()\n+ buffer_span = compute_required_storage_length((2048,), (1,), 0)\n+ view_span = compute_required_storage_length((64, 32), (32, 1), 0)\n+ self.assertEqual(fake_x.storage_offset(), shift)\n+ self.assertEqual(ptr_off, shift)\n+ # The kernel indexes the whole view, so the storage covers the buffer as\n+ # well as the view, whichever reaches further past the data pointer.\n+ self.assertEqual(fake_items, shift + max(buffer_span, view_span))\n+ # The aten input stays a view at the rebased offset, backed by a base\n+ # that also covers the input's own allocation.\n+ extern_x = autotune_args[0].extern.input_tensors[0]\n+ self.assertEqual(tuple(extern_x.size()), (64, 32))\n+ self.assertEqual(tuple(extern_x.stride()), (32, 1))\n+ self.assertEqual(extern_x.storage_offset(), extern_offset)\n+ self.assertEqual(\n+ extern_x.untyped_storage().size() // extern_x.element_size(), 4096\n+ )\n+\n+ @fresh_cache()\n+ @skipIfXpu\n+ def test_max_autotune_negative_offset_layout(self):\n+ \"\"\"\n+ Regression test for https://github.com/pytorch/pytorch/issues/200810.\n+ A layout with a negative offset that is not a view of anything reaches\n+ benchmark_example_value with the same negative value as both extra_size\n+ and view_offset. Its storage still has to be allocated: a negative\n+ offset means the buffer has no leading region, not that it needs less.\n+ \"\"\"\n+ from torch._inductor import ir\n+\n+ captured = {}\n+\n+ def patched_lowering(*args, **kwargs):\n+ layout = ir.FixedLayout(\n+ torch.device(GPU_TYPE), torch.float32, [64, 32], [32, 1], -2048\n+ )\n+ captured[\"example\"] = AlgorithmSelectorCache.benchmark_example_value(layout)\n+ return orig_add_lowering(*args, **kwargs)\n+\n+ orig_add_lowering = torch._inductor.lowering.lowerings[aten.add.Tensor]\n+ with patch.dict(\n+ torch._inductor.lowering.lowerings,\n+ {aten.add.Tensor: patched_lowering},\n+ ):\n+ torch.compile(lambda x: x + 1)(\n+ torch.randn(64, 32, device=GPU_TYPE, dtype=torch.float32)\n+ )\n+\n+ example = captured[\"example\"]\n+ self.assertEqual(tuple(example.size()), (64, 32))\n+ # The data pointer is shifted in by -offset so the view can start at 0.\n+ self.assertEqual(example.storage_offset(), 2048)\n+ self.assertGreaterEqual(\n+ example.untyped_storage().size() // example.element_size(),\n+ 2048 + compute_required_storage_length((64, 32), (32, 1), 0),\n+ )\n+\n @fresh_cache()\n @skipIfXpu\n @unittest.skipIf(TEST_WITH_ROCM, \"Test requires CUDA\")\n@@ -7677,6 +7795,8 @@ class TestMaxAutotuneAsyncPipelined(TestMaxAutotune, TestEpilogueFusionStaticAna\n \"test_autotune_device_guard\": \"Flaky on trunk\",\n \"test_template_bad_epilogue_fusion\": \"Benchmarking path is different\",\n \"test_persistent_tma_epilogue_fusion_store_cache\": \"Epilogue fusion disabled in async pipelining\",\n+ \"test_max_autotune_mm_rebased_storage_offset_input\": \"get_inputs is not called on the pipelined path, so the benchmark inputs this test inspects are never built here\",\n+ \"test_max_autotune_negative_offset_layout\": \"test-only lowering patch, drops the benchmark inputs the pipelined path needs\",\n # grouped_mm's input_gen_fns forces\n # return_multi_template=False, so do_autotuning() takes its\n # pipelined-only branch and returns None instead of timings,\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: pytorch/pytorch\nPull request: Fix test_nccl_user_buffer_registration for NCCL 2.32 NVLS log text\nLabels: triaged, open source, Merged, ciflow/trunk, topic: not user facing, ciflow/h100-distributed, bot-triaged, missing actionable issue, ciflow/b200-distributed\nFiles changed (1): test/distributed/test_c10d_nccl.py\n\n## Description (results removed)\n\n## Summary\nNCCL 2.32 changed the NVLS user-buffer registration debug message from \n`successfully registered NVLS` → `NVLS UB registered`.\n\n- NCCL ≥ 2.32 → `\"NVLS UB registered\"`\n- NCCL 2.24.3–2.31 → `\"successfully registered NVLS\"`\n- older → `\"local-registered\"`\n\nFixes #201408\n\nSupported by @d4l3k (see comment on #201408: “sounds good, pr fixing this is welcome”)\n\n## Test Plan\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/test/distributed/test_c10d_nccl.py b/test/distributed/test_c10d_nccl.py\nindex 20eab775987eb..7a9b50b9cc4ab 100644\n--- a/test/distributed/test_c10d_nccl.py\n+++ b/test/distributed/test_c10d_nccl.py\n@@ -4633,7 +4633,10 @@ def test_nccl_user_buffer_registration(self):\n nccl_debug_file_content = f.read()\n # if buffers were registered and NVLS reduction ran, NCCL_DEBUG\n # should show successful registration in debug output\n- if torch.cuda.nccl.version() >= (2, 24, 3):\n+ nccl_version = torch.cuda.nccl.version()\n+ if nccl_version >= (2, 32):\n+ self.assertRegex(nccl_debug_file_content, \"NVLS UB registered\")\n+ elif nccl_version >= (2, 24, 3):\n self.assertRegex(\n nccl_debug_file_content, \"successfully registered NVLS\"\n )\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: pytorch/pytorch\nPull request: [fix] angle for -0.0\nLabels: module: cpu, triaged, open source, Merged, ciflow/trunk, topic: not user facing, ciflow/mps, module: inductor, ciflow/inductor, bot-triaged, ciflow/torchtitan\nFiles changed (20): aten/src/ATen/cpu/vec/sve/vec_double.h, aten/src/ATen/cpu/vec/sve/vec_float.h, aten/src/ATen/cpu/vec/vec128/vec128_double_neon.h, aten/src/ATen/cpu/vec/vec128/vec128_float_neon.h, aten/src/ATen/cpu/vec/vec128/vec128_reduced_precision_common_neon.h, aten/src/ATen/cpu/vec/vec128/zarch/vec128_zarch.h, aten/src/ATen/cpu/vec/vec256/vec256_16bit_float.h, aten/src/ATen/cpu/vec/vec256/vec256_double.h, aten/src/ATen/cpu/vec/vec256/vec256_float.h, aten/src/ATen/cpu/vec/vec256/vsx/vec256_double_vsx.h, aten/src/ATen/cpu/vec/vec256/vsx/vec256_float_vsx.h, aten/src/ATen/cpu/vec/vec512/vec512_bfloat16.h, aten/src/ATen/cpu/vec/vec512/vec512_double.h, aten/src/ATen/cpu/vec/vec512/vec512_float.h, aten/src/ATen/native/cpu/zmath.h, aten/src/ATen/native/cuda/UnaryComplexKernels.cu, aten/src/ATen/native/mps/kernels/UnaryKernel.metal, test/test_unary_ufuncs.py, torch/_inductor/decomposition.py, torch/testing/_internal/common_methods_invocations.py\n\n## Description (results removed)\n\nFixes #78413\nSupported by @Isalia20 \n\nFixes `angle` for `-0.0` input values in the cpu & cuda backends and inductor. \n\nAI helped me with intel intrinsics and I verified it with the docs.\n\ncc @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @aditew01 @voznesenskym @penguinwu @EikanWang @Guobing-Chen @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo\n\n## Diff\n\n```diff\ndiff --git a/aten/src/ATen/cpu/vec/sve/vec_double.h b/aten/src/ATen/cpu/vec/sve/vec_double.h\nindex 03266534f15e2..51a64a9a2227d 100644\n--- a/aten/src/ATen/cpu/vec/sve/vec_double.h\n+++ b/aten/src/ATen/cpu/vec/sve/vec_double.h\n@@ -170,7 +170,8 @@ class Vectorized {\n const auto nan_mask = svcmpuo_f64(ptrue, values, ZERO_F64);\n const auto pi = svdup_n_f64(c10::pi);\n \n- const auto neg_mask = svcmplt_f64(ptrue, values, ZERO_F64);\n+ const auto neg_mask =\n+ svcmplt_n_s64(ptrue, svreinterpret_s64_f64(values), 0);\n auto angle = svsel_f64(neg_mask, pi, ZERO_F64);\n angle = svsel_f64(nan_mask, nan_vec, angle);\n return angle;\ndiff --git a/aten/src/ATen/cpu/vec/sve/vec_float.h b/aten/src/ATen/cpu/vec/sve/vec_float.h\nindex 0d1d3b80ac0f7..850d5d81d469f 100644\n--- a/aten/src/ATen/cpu/vec/sve/vec_float.h\n+++ b/aten/src/ATen/cpu/vec/sve/vec_float.h\n@@ -253,7 +253,8 @@ class Vectorized {\n const auto nan_mask = svcmpuo_f32(ptrue, values, ZERO_F32);\n const auto pi = svdup_n_f32(c10::pi);\n \n- const auto neg_mask = svcmplt_f32(ptrue, values, ZERO_F32);\n+ const auto neg_mask =\n+ svcmplt_n_s32(ptrue, svreinterpret_s32_f32(values), 0);\n auto angle = svsel_f32(neg_mask, pi, ZERO_F32);\n angle = svsel_f32(nan_mask, nan_vec, angle);\n return angle;\ndiff --git a/aten/src/ATen/cpu/vec/vec128/vec128_double_neon.h b/aten/src/ATen/cpu/vec/vec128/vec128_double_neon.h\nindex b6d13e24544bb..df6e1ee8404e6 100644\n--- a/aten/src/ATen/cpu/vec/vec128/vec128_double_neon.h\n+++ b/aten/src/ATen/cpu/vec/vec128/vec128_double_neon.h\n@@ -177,7 +177,10 @@ class Vectorized {\n Vectorized angle() const {\n auto zero = Vectorized(0.0);\n auto pi = Vectorized(c10::pi);\n- auto tmp = blendv(zero, pi, vreinterpretq_f64_u64(vcltzq_f64(values)));\n+ auto tmp = blendv(\n+ zero,\n+ pi,\n+ vreinterpretq_f64_u64(vcltzq_s64(vreinterpretq_s64_f64(values))));\n return blendv(tmp, *this, isnan());\n }\n Vectorized real() const {\ndiff --git a/aten/src/ATen/cpu/vec/vec128/vec128_float_neon.h b/aten/src/ATen/cpu/vec/vec128/vec128_float_neon.h\nindex e1927a4d67513..2110bd45bcab1 100644\n--- a/aten/src/ATen/cpu/vec/vec128/vec128_float_neon.h\n+++ b/aten/src/ATen/cpu/vec/vec128/vec128_float_neon.h\n@@ -293,7 +293,7 @@ class Vectorized {\n Vectorized angle() const {\n auto zero = Vectorized(0);\n auto pi = Vectorized(c10::pi);\n- auto tmp = blendv(zero, pi, *this < zero);\n+ auto tmp = blendv(zero, pi, pi.copysign(*this) < zero);\n return blendv(tmp, *this, isnan());\n }\n Vectorized real() const {\ndiff --git a/aten/src/ATen/cpu/vec/vec128/vec128_reduced_precision_common_neon.h b/aten/src/ATen/cpu/vec/vec128/vec128_reduced_precision_common_neon.h\nindex 5fb3679f37239..f169c69ae8f01 100644\n--- a/aten/src/ATen/cpu/vec/vec128/vec128_reduced_precision_common_neon.h\n+++ b/aten/src/ATen/cpu/vec/vec128/vec128_reduced_precision_common_neon.h\n@@ -126,8 +126,8 @@ struct Vectorized16 {\n Derived angle() const {\n auto zero = Derived(0);\n auto pi = Derived(c10::pi);\n- auto tmp =\n- Derived::blendv(zero, pi, *static_cast(this) < zero);\n+ auto tmp = Derived::blendv(\n+ zero, pi, pi.copysign(*static_cast(this)) < zero);\n return Derived::blendv(\n tmp,\n *static_cast(this),\ndiff --git a/aten/src/ATen/cpu/vec/vec128/zarch/vec128_zarch.h b/aten/src/ATen/cpu/vec/vec128/zarch/vec128_zarch.h\nindex 08f1a7dd8fa9b..5b547ca4f963b 100644\n--- a/aten/src/ATen/cpu/vec/vec128/zarch/vec128_zarch.h\n+++ b/aten/src/ATen/cpu/vec/vec128/zarch/vec128_zarch.h\n@@ -672,7 +672,9 @@ struct Vectorized()>> {\n std::enable_if_t, int> = 0>\n Vectorized angle() const {\n auto tmp = blendv(\n- Vectorized(0), Vectorized(c10::pi), *this < Vectorized(0));\n+ Vectorized(0),\n+ Vectorized(c10::pi),\n+ Vectorized(c10::pi).copysign(*this) < Vectorized(0));\n return blendv(tmp, *this, isnan());\n }\n \ndiff --git a/aten/src/ATen/cpu/vec/vec256/vec256_16bit_float.h b/aten/src/ATen/cpu/vec/vec256/vec256_16bit_float.h\nindex 56e4b00735b03..e9e59609a33ad 100644\n--- a/aten/src/ATen/cpu/vec/vec256/vec256_16bit_float.h\n+++ b/aten/src/ATen/cpu/vec/vec256/vec256_16bit_float.h\n@@ -414,8 +414,7 @@ class Vectorized16 {\n const auto nan_mask = _mm256_cmp_ps(not_nan_mask, zero_vec, _CMP_EQ_OQ);\n const auto pi = _mm256_set1_ps(c10::pi);\n \n- const auto neg_mask = _mm256_cmp_ps(values_2, zero_vec, _CMP_LT_OQ);\n- auto angle = _mm256_blendv_ps(zero_vec, pi, neg_mask);\n+ auto angle = _mm256_blendv_ps(zero_vec, pi, values_2);\n angle = _mm256_blendv_ps(angle, nan_vec, nan_mask);\n return angle;\n };\ndiff --git a/aten/src/ATen/cpu/vec/vec256/vec256_double.h b/aten/src/ATen/cpu/vec/vec256/vec256_double.h\nindex 0d8a040e9cec7..9d6ed67e950cd 100644\n--- a/aten/src/ATen/cpu/vec/vec256/vec256_double.h\n+++ b/aten/src/ATen/cpu/vec/vec256/vec256_double.h\n@@ -135,8 +135,7 @@ class Vectorized {\n const auto nan_mask = _mm256_cmp_pd(not_nan_mask, zero_vec, _CMP_EQ_OQ);\n const auto pi = _mm256_set1_pd(c10::pi);\n \n- const auto neg_mask = _mm256_cmp_pd(values, zero_vec, _CMP_LT_OQ);\n- auto angle = _mm256_blendv_pd(zero_vec, pi, neg_mask);\n+ auto angle = _mm256_blendv_pd(zero_vec, pi, values);\n angle = _mm256_blendv_pd(angle, nan_vec, nan_mask);\n return angle;\n }\ndiff --git a/aten/src/ATen/cpu/vec/vec256/vec256_float.h b/aten/src/ATen/cpu/vec/vec256/vec256_float.h\nindex f3af1a0b5b893..5878442e9c31a 100644\n--- a/aten/src/ATen/cpu/vec/vec256/vec256_float.h\n+++ b/aten/src/ATen/cpu/vec/vec256/vec256_float.h\n@@ -171,8 +171,7 @@ class Vectorized {\n const auto nan_mask = _mm256_cmp_ps(not_nan_mask, zero_vec, _CMP_EQ_OQ);\n const auto pi = _mm256_set1_ps(c10::pi);\n \n- const auto neg_mask = _mm256_cmp_ps(values, zero_vec, _CMP_LT_OQ);\n- auto angle = _mm256_blendv_ps(zero_vec, pi, neg_mask);\n+ auto angle = _mm256_blendv_ps(zero_vec, pi, values);\n angle = _mm256_blendv_ps(angle, nan_vec, nan_mask);\n return angle;\n }\ndiff --git a/aten/src/ATen/cpu/vec/vec256/vsx/vec256_double_vsx.h b/aten/src/ATen/cpu/vec/vec256/vsx/vec256_double_vsx.h\nindex 68cd8f7ce75bb..2c90f2dcdea3f 100644\n--- a/aten/src/ATen/cpu/vec/vec256/vsx/vec256_double_vsx.h\n+++ b/aten/src/ATen/cpu/vec/vec256/vsx/vec256_double_vsx.h\n@@ -289,7 +289,8 @@ class Vectorized {\n auto tmp = blendv(\n Vectorized(0),\n Vectorized(c10::pi),\n- *this < Vectorized(0));\n+ Vectorized(c10::pi).copysign(*this) <\n+ Vectorized(0));\n return blendv(tmp, *this, isnan());\n }\n Vectorized real() const {\ndiff --git a/aten/src/ATen/cpu/vec/vec256/vsx/vec256_float_vsx.h b/aten/src/ATen/cpu/vec/vec256/vsx/vec256_float_vsx.h\nindex 9e22f65f17cb1..68d250d69aae2 100644\n--- a/aten/src/ATen/cpu/vec/vec256/vsx/vec256_float_vsx.h\n+++ b/aten/src/ATen/cpu/vec/vec256/vsx/vec256_float_vsx.h\n@@ -330,7 +330,8 @@ class Vectorized {\n auto tmp = blendv(\n Vectorized(0),\n Vectorized(c10::pi),\n- *this < Vectorized(0));\n+ Vectorized(c10::pi).copysign(*this) <\n+ Vectorized(0));\n return blendv(tmp, *this, isnan());\n }\n Vectorized real() const {\ndiff --git a/aten/src/ATen/cpu/vec/vec512/vec512_bfloat16.h b/aten/src/ATen/cpu/vec/vec512/vec512_bfloat16.h\nindex f84f07f6c3485..629a923133718 100644\n--- a/aten/src/ATen/cpu/vec/vec512/vec512_bfloat16.h\n+++ b/aten/src/ATen/cpu/vec/vec512/vec512_bfloat16.h\n@@ -458,7 +458,7 @@ class Vectorized16 {\n _mm512_castsi512_ps(non_nan_mask_vec), zero_vec, _CMP_EQ_OQ);\n const auto pi = _mm512_set1_ps(c10::pi);\n \n- const auto neg_mask = _mm512_cmp_ps_mask(values, zero_vec, _CMP_LT_OQ);\n+ const auto neg_mask = _mm512_movepi32_mask(_mm512_castps_si512(values));\n auto angle = _mm512_mask_blend_ps(neg_mask, zero_vec, pi);\n angle = _mm512_mask_blend_ps(nan_mask, angle, nan_vec);\n return angle;\ndiff --git a/aten/src/ATen/cpu/vec/vec512/vec512_double.h b/aten/src/ATen/cpu/vec/vec512/vec512_double.h\nindex c89f177fb8c56..b8b748db89aad 100644\n--- a/aten/src/ATen/cpu/vec/vec512/vec512_double.h\n+++ b/aten/src/ATen/cpu/vec/vec512/vec512_double.h\n@@ -167,7 +167,7 @@ class Vectorized {\n _mm512_cmp_pd_mask(_mm512_castsi512_pd(not_nan), zero_vec, _CMP_EQ_OQ);\n const auto pi = _mm512_set1_pd(c10::pi);\n \n- const auto neg_mask = _mm512_cmp_pd_mask(values, zero_vec, _CMP_LT_OQ);\n+ const auto neg_mask = _mm512_movepi64_mask(_mm512_castpd_si512(values));\n auto angle = _mm512_mask_blend_pd(neg_mask, zero_vec, pi);\n angle = _mm512_mask_blend_pd(nan_mask, angle, nan_vec);\n return angle;\ndiff --git a/aten/src/ATen/cpu/vec/vec512/vec512_float.h b/aten/src/ATen/cpu/vec/vec512/vec512_float.h\nindex b3cf1ee48b427..8d433c0abb798 100644\n--- a/aten/src/ATen/cpu/vec/vec512/vec512_float.h\n+++ b/aten/src/ATen/cpu/vec/vec512/vec512_float.h\n@@ -230,7 +230,7 @@ class Vectorized {\n _mm512_castsi512_ps(not_nan_vec), zero_vec, _CMP_EQ_OQ);\n const auto pi = _mm512_set1_ps(c10::pi);\n \n- const auto neg_mask = _mm512_cmp_ps_mask(values, zero_vec, _CMP_LT_OQ);\n+ const auto neg_mask = _mm512_movepi32_mask(_mm512_castps_si512(values));\n auto angle = _mm512_mask_blend_ps(neg_mask, zero_vec, pi);\n angle = _mm512_mask_blend_ps(nan_mask, angle, nan_vec);\n return angle;\ndiff --git a/aten/src/ATen/native/cpu/zmath.h b/aten/src/ATen/native/cpu/zmath.h\nindex 2b4f44db085c9..90c128716d450 100644\n--- a/aten/src/ATen/native/cpu/zmath.h\n+++ b/aten/src/ATen/native/cpu/zmath.h\n@@ -3,7 +3,8 @@\n // Complex number math operations that act as no-ops for other dtypes.\n #include \n #include \n-#include\n+#include \n+#include \n \n namespace at::native {\n inline namespace CPU_CAPABILITY {\n@@ -44,7 +45,7 @@ inline VALUE_TYPE angle_impl (SCALAR_TYPE z) {\n if (at::_isnan(z)) {\n return z;\n }\n- return z < 0 ? c10::pi : 0;\n+ return std::signbit(static_cast>(z)) ? c10::pi : 0;\n }\n \n template<>\ndiff --git a/aten/src/ATen/native/cuda/UnaryComplexKernels.cu b/aten/src/ATen/native/cuda/UnaryComplexKernels.cu\nindex d0a6812b30236..abd5fdead2627 100644\n--- a/aten/src/ATen/native/cuda/UnaryComplexKernels.cu\n+++ b/aten/src/ATen/native/cuda/UnaryComplexKernels.cu\n@@ -17,7 +17,7 @@ __host__ __device__ static inline scalar_t angle_wrapper(scalar_t v) {\n if (at::_isnan(v)){\n return v;\n }\n- return v < 0 ? M_PI : 0;\n+ return signbit(static_cast>(v)) ? M_PI : 0;\n }\n \n template\ndiff --git a/aten/src/ATen/native/mps/kernels/UnaryKernel.metal b/aten/src/ATen/native/mps/kernels/UnaryKernel.metal\nindex 7a6693d07c2f4..290c39ad063d7 100644\n--- a/aten/src/ATen/native/mps/kernels/UnaryKernel.metal\n+++ b/aten/src/ATen/native/mps/kernels/UnaryKernel.metal\n@@ -13,7 +13,8 @@ struct angle_functor {\n }\n template , bool> = true>\n inline T operator()(const T x) {\n- return T(isnan(x) ? x : x < 0 ? M_PI_F : 0.0);\n+ const bool neg = ::metal::signbit(static_cast>(x));\n+ return T(isnan(x) ? x : neg ? M_PI_F : 0.0);\n }\n template , bool> = true>\n inline float operator()(const T x) {\ndiff --git a/torch/_inductor/decomposition.py b/torch/_inductor/decomposition.py\nindex c0dd19cf10212..f158a06bd1f68 100644\n--- a/torch/_inductor/decomposition.py\n+++ b/torch/_inductor/decomposition.py\n@@ -697,7 +697,9 @@ def angle(x: torch.Tensor) -> torch.Tensor:\n type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,\n )\n pi = torch.scalar_tensor(math.pi, dtype=dtype, device=x.device)\n- ret = torch.where(x < 0, pi, 0.0)\n+ # mps has no integer signbit and integers have no -0\n+ is_neg = torch.signbit(x) if x.is_floating_point() else x < 0\n+ ret = torch.where(is_neg, pi, 0.0)\n return torch.where(torch.isnan(x), float(\"nan\"), ret)\n \n \ndiff --git a/test/test_unary_ufuncs.py b/test/test_unary_ufuncs.py\nindex 8618455106077..8b9283161337d 100644\n--- a/test/test_unary_ufuncs.py\n+++ b/test/test_unary_ufuncs.py\n@@ -721,6 +721,18 @@ def test_polygamma_neg(self, device):\n ):\n torch.polygamma(-1, torch.tensor([1.0, 2.0], device=device))\n \n+ @dtypes(torch.float16, torch.bfloat16, torch.float32, torch.float64)\n+ def test_angle_signed_zero(self, device, dtype):\n+ x = torch.tensor([-0.0, 0.0, -1.0, 1.0, nan], device=device, dtype=dtype)\n+ x_np = x.cpu().to(\n+ torch.float64 if dtype == torch.float64 else torch.float32\n+ ).numpy()\n+\n+ actual = torch.angle(x)\n+ expected = torch.from_numpy(np.angle(x_np)).to(dtype)\n+\n+ self.assertEqual(actual, expected)\n+\n @dtypes(torch.complex64, torch.complex128)\n def test_abs_angle_complex_to_float(self, device, dtype):\n # Constructs random complex values\ndiff --git a/torch/testing/_internal/common_methods_invocations.py b/torch/testing/_internal/common_methods_invocations.py\nindex 61059af5e006e..b29260bca2ddc 100644\n--- a/torch/testing/_internal/common_methods_invocations.py\n+++ b/torch/testing/_internal/common_methods_invocations.py\n@@ -19190,12 +19190,7 @@ def sample_inputs_abs(op_info, device, dtype, requires_grad, op_kwargs=None, **k\n supports_sparse_csc=True,\n supports_sparse_bsr=True,\n supports_sparse_bsc=True,\n- supports_complex_to_float=True,\n- skips=(\n- # Ref: https://github.com/pytorch/pytorch/issues/78413\n- DecorateInfo(unittest.expectedFailure, 'TestUnaryUfuncs', 'test_reference_numerics_small',\n- dtypes=(torch.bfloat16, torch.float16, torch.float32, torch.float64),),\n- )),\n+ supports_complex_to_float=True),\n UnaryUfuncInfo('isfinite',\n ref=np.isfinite,\n dtypes=all_types_and_complex_and(torch.bool, torch.bfloat16, torch.float16, torch.chalf),\n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: pytorch/pytorch\nPull request: [compile] fix rand, uniform for unsupported dtypes\nLabels: triaged, open source, Merged, ciflow/trunk, topic: not user facing, module: inductor, ciflow/inductor, bot-triaged\nFiles changed (5): test/inductor/test_torchinductor.py, torch/_meta_registrations.py, torch/_prims/__init__.py, torch/_refs/__init__.py, torch/testing/_internal/common_methods_invocations.py\n\n## Description (results removed)\n\nFixes #198862\nSupported by @Isalia20\n\n## Diff\n\n```diff\ndiff --git a/torch/_meta_registrations.py b/torch/_meta_registrations.py\nindex e90cd9ac0a586..dca9331e6e51e 100644\n--- a/torch/_meta_registrations.py\n+++ b/torch/_meta_registrations.py\n@@ -574,6 +574,12 @@ def meta_randint_low(\n @register_meta([aten.rand.default, aten.rand.out])\n @out_wrapper()\n def meta_rand_default(size, *, dtype=None, layout=None, device=None, pin_memory=None):\n+ if dtype is not None:\n+ torch._check_not_implemented(\n+ dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64)\n+ or dtype.is_complex,\n+ lambda: f'\"check_uniform_bounds\" not implemented for {dtype}',\n+ )\n return torch.empty(\n size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory\n )\ndiff --git a/torch/_prims/__init__.py b/torch/_prims/__init__.py\nindex d474d35359a91..a52b38fe76f0a 100644\n--- a/torch/_prims/__init__.py\n+++ b/torch/_prims/__init__.py\n@@ -2856,6 +2856,11 @@ def _uniform_meta(\n stride: ShapeType,\n generator: torch.Generator | None = None,\n ) -> TensorLikeType:\n+ torch._check_not_implemented(\n+ dtype in (torch.float16, torch.bfloat16, torch.float32, torch.float64)\n+ or dtype.is_complex,\n+ lambda: f'\"check_uniform_bounds\" not implemented for {dtype}',\n+ )\n return TensorMeta(shape=shape, strides=stride, dtype=dtype, device=device)\n \n \ndiff --git a/torch/_refs/__init__.py b/torch/_refs/__init__.py\nindex c347ef20fc93d..9656304d7eb90 100644\n--- a/torch/_refs/__init__.py\n+++ b/torch/_refs/__init__.py\n@@ -6757,7 +6757,6 @@ def exponential(self, rate=1, generator=None):\n def geometric(self, p, generator=None):\n if generator is not None:\n raise AssertionError(\"generator is not supported in refs\")\n- # TODO: fix inductor rand_like for integer, bool dtypes\n torch._check(\n not utils.is_complex_dtype(self.dtype)\n and not utils.is_boolean_dtype(self.dtype),\n@@ -6767,7 +6766,9 @@ def geometric(self, p, generator=None):\n 0 < p and p < 1,\n lambda: f\"geometric_ expects p to be in (0, 1), but got p={p}\",\n )\n- return torch.floor(torch.log1p(-torch.rand_like(self)) / math.log1p(-p)) + 1\n+ rand_dtype = self.dtype if utils.is_float_dtype(self.dtype) else torch.float32\n+ u = torch.rand_like(self, dtype=rand_dtype)\n+ return torch.floor(torch.log1p(-u) / math.log1p(-p)) + 1\n \n \n @register_decomposition(aten.log_normal)\ndiff --git a/test/inductor/test_torchinductor.py b/test/inductor/test_torchinductor.py\nindex e0713f329e4d9..196d9e3c98149 100644\n--- a/test/inductor/test_torchinductor.py\n+++ b/test/inductor/test_torchinductor.py\n@@ -8542,6 +8542,25 @@ def fn(x):\n self.assertEqual(res.stride(), ref.stride())\n self.assertTrue(bool(((res >= 0.0) & (res <= 1.0)).all()))\n \n+ def test_rand_uniform_unsupported_dtype(self):\n+ def rand(x):\n+ return torch.rand(x.shape, dtype=x.dtype, device=x.device)\n+\n+ def rand_like(x):\n+ return torch.rand_like(x)\n+\n+ def uniform_(x):\n+ return x.uniform_()\n+\n+ for dtype in (torch.int64, torch.bool, torch.float8_e4m3fn):\n+ x = torch.zeros(8, device=self.device).to(dtype)\n+ for fn in (rand, rand_like, uniform_):\n+ with self.assertRaises(NotImplementedError):\n+ fn(x)\n+ torch._dynamo.reset()\n+ with self.assertRaises(NotImplementedError):\n+ torch.compile(fn)(x)\n+\n def test_complex_from_real_imag(self):\n def fn(x, y):\n return aten.complex.default(x, y)\ndiff --git a/torch/testing/_internal/common_methods_invocations.py b/torch/testing/_internal/common_methods_invocations.py\nindex a742025eb0b10..1eac8e0525bb8 100644\n--- a/torch/testing/_internal/common_methods_invocations.py\n+++ b/torch/testing/_internal/common_methods_invocations.py\n@@ -23607,8 +23607,6 @@ def sample_inputs_abs(op_info, device, dtype, requires_grad, op_kwargs=None, **k\n decorators=(\n # dtypes that do not support check_uniform_bounds of rand_like\n DecorateInfo(unittest.skip('Skipped!'), 'TestCommon', 'test_dtypes'),\n- DecorateInfo(unittest.expectedFailure, 'TestCommon', 'test_python_ref_meta',\n- dtypes=(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64)),\n DecorateInfo(unittest.expectedFailure, 'TestCommon', 'test_python_ref_torch_fallback',\n dtypes=(torch.int8, torch.uint8, torch.int16, torch.int32, torch.int64)),\n \n\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]} {"messages": [{"role": "system", "content": "You predict whether a proposed fix to an LLM inference engine or ML-systems library passes validation. You get the repository, the pull request (its description with test results removed) and the diff of this revision. passes = the validating tests and checks pass with this patch; fails = they fail with this patch (a CI test failure, a breakage that got it reverted, or a reviewer's rerun that still fails). Answer with the option letter and its text."}, {"role": "user", "content": "Repository: triton-lang/triton\nPull request: [Frontend] Fix pointer subtraction with unsigned offsets\nFiles changed (2): python/test/unit/language/test_core.py, python/triton/language/semantic.py\n\n## Description (results removed)\n\n- [x] I have written a PR description following these [rules](https://cbea.ms/git-commit/#why-not-how).\n- [x] I have run `pre-commit run --from-ref origin/main --to-ref HEAD`.\n- [x] I have added tests.\n - `/python/test` for end-to-end tests\n- [x] I have not added any `lit` tests.\n\n## Summary\n\nSubtracting an unsigned offset narrower than 64 bits from a pointer can move the pointer forward instead of backward. The unsigned negation wraps around before pointer addition, producing an incorrect address.\n\nFixes #12240.\n\n## Testing\n[results removed]\n\n## Diff\n\n```diff\ndiff --git a/python/triton/language/semantic.py b/python/triton/language/semantic.py\nindex 0a102506bdea..116c87716a63 100644\n--- a/python/triton/language/semantic.py\n+++ b/python/triton/language/semantic.py\n@@ -291,6 +291,11 @@ def sub(self, input: TensorTy | numbers.Number, other: TensorTy | numbers.Number\n scalar_ty = input.type.scalar\n # ptr - offset\n if scalar_ty.is_ptr():\n+ # Negate unsigned offsets in a signed type to avoid unsigned wraparound.\n+ if other.dtype.is_int_unsigned() and other.dtype.int_bitwidth < 64:\n+ other_type = other.type.with_element_ty(tl.int64)\n+ other_handle = self.builder.create_int_cast(other.handle, other_type.to_ir(self.builder), False)\n+ other = self.make_tensor(other_handle, other_type)\n return self.add(input, self.minus(other), sanitize_overflow=False)\n # float - float\n if scalar_ty.is_floating():\n\ndiff --git a/python/test/unit/language/test_core.py b/python/test/unit/language/test_core.py\nindex d0e462b931db..5d18f821642e 100644\n--- a/python/test/unit/language/test_core.py\n+++ b/python/test/unit/language/test_core.py\n@@ -532,6 +532,22 @@ def kernel(x, y, ORDER: tl.constexpr, SIZE: tl.constexpr):\n np.testing.assert_allclose(y, to_numpy(y_tri))\n \n \n+@pytest.mark.interpreter\n+def test_ptr_sub_unsigned_offset(device):\n+\n+ @triton.jit\n+ def kernel(X, Y):\n+ i = tl.arange(0, 64)\n+ tl.store(Y + i, tl.load(X + 300 - i.to(tl.uint8)))\n+\n+ x = to_triton(np.arange(1024, dtype=np.float32), device=device)\n+ y = to_triton(np.empty(64, dtype=np.float32), device=device)\n+ kernel[(1, )](x, y)\n+\n+ expected = np.array([300., 299., 298., 297., 296.], dtype=np.float32)\n+ np.testing.assert_array_equal(to_numpy(y)[:5], expected)\n+\n+\n @pytest.mark.interpreter\n @pytest.mark.parametrize(\"dtype_x, dtype_y\", [ #\n (dtype_x, dtype_y) for dtype_x in int_dtypes for dtype_y in int_dtypes\n```\n\nDoes this revision of the patch pass validation?\nA) passes\nB) fails"}, {"role": "assistant", "content": "A) passes"}]}