From 2e130de2d4c44d0b7f40eb3cd7f69a6d07a6f988 Mon Sep 17 00:00:00 2001 From: Ronald1995 Date: Tue, 24 Nov 2026 16:36:11 +0800 Subject: [PATCH 1/3] refactor: drop worker overrides that duplicate upstream NPUWorker overrides a set of worker RPCs that upstream vllm/v1/worker/gpu_worker.py::Worker already implements with the same behavior. Every method declared on the class was audited against the effective upstream implementation (gpu_worker.Worker, falling back to WorkerBase) on both supported vLLM lanes - v0.33.0 and the pinned main commit c410543d - with a normalized AST comparison. The methods deleted here only restate upstream: - add_lora / remove_lora / list_loras / pin_lora: byte-identical bodies - get_model / reset_encoder_cache / take_draft_token_ids: byte-identical - get_supported_tasks: body and decorators identical, the only difference was a redundant quoted return annotation - reset_mm_cache: upstream calls model_runner.reset_mm_cache() directly; the getattr/callable guard protected a runner shape that no longer exists - get_draft_model: was a NotImplementedError stub; every supported runner implements the accessor (MRv2 returns the speculator's draft model) - compute_weight_checksums / reset_weights: upstream reads the model via model_runner.get_model(), and MRv2's get_model() is literally "return self.model", so the local _weight_checksum_model() fallback was dead code. reset_weights keeps upstream's zero_weights() semantics but no longer logs the weight_nz_mode advisory; the NZ guard in the weight-update path (_check_nz_disabled) is untouched. Dead code that only those methods used goes away with them: the _weight_checksum_model() helper and the LoRARequest / SupportedTask / DraftTokenIds / compute_tensor_digests / zero_weights imports. Tests that asserted the removed behavior are dropped, and tests/ut/worker/test_worker_inheritance.py now asserts that these RPCs are inherited from gpu_worker.Worker. Static checks only: ruff check, ruff format --check and py_compile pass, and the audit re-runs to zero duplicated methods on both lanes. Signed-off-by: Ronald1995 --- tests/ut/worker/test_worker_inheritance.py | 29 +++++----- tests/ut/worker/test_worker_weight_checker.py | 53 ++--------------- vllm_ascend/worker/worker.py | 58 +------------------ 3 files changed, 20 insertions(+), 120 deletions(-) diff --git a/tests/ut/worker/test_worker_inheritance.py b/tests/ut/worker/test_worker_inheritance.py index e8e5726138ec..a9247c704806 100644 --- a/tests/ut/worker/test_worker_inheritance.py +++ b/tests/ut/worker/test_worker_inheritance.py @@ -23,7 +23,6 @@ "_compile_or_warm_up_model", "_maybe_activate_jit_monitor", "_get_cudagraph_capture_context", - "get_draft_model", "_set_draft_weight_update_target", "get_compilation_match_table", "get_encoder_timing_stats", @@ -74,6 +73,20 @@ def test_shutdown_weight_transfer_engine_is_inherited(): assert NPUWorker.shutdown_weight_transfer_engine is GPUWorker.shutdown_weight_transfer_engine +@pytest.mark.parametrize( + "name", + ("reset_mm_cache", "get_draft_model", "compute_weight_checksums", "reset_weights"), +) +def test_model_accessors_are_inherited(name): + from vllm.v1.worker.gpu_worker import Worker as GPUWorker + + from vllm_ascend.worker.worker import NPUWorker + + # Every supported runner exposes get_model()/get_draft_model()/reset_mm_cache(), + # so these worker RPCs need no Ascend override. + assert getattr(NPUWorker, name) is getattr(GPUWorker, name) + + @pytest.mark.parametrize("configured", [False, True]) def test_shutdown_weight_transfer_engine_releases_trainer_connection(configured): from vllm_ascend.worker.worker import NPUWorker @@ -103,20 +116,6 @@ def test_shutdown_weight_transfer_engine_rejects_active_update(): worker.weight_transfer_engine.shutdown.assert_not_called() -@pytest.mark.parametrize("reset", [None, "absent", "callable"]) -def test_reset_mm_cache_preserves_optional_runner_method(reset): - from vllm_ascend.worker.worker import NPUWorker - - worker = object.__new__(NPUWorker) - reset_fn = Mock() if reset == "callable" else reset - runner = SimpleNamespace() if reset == "absent" else SimpleNamespace(reset_mm_cache=reset_fn) - worker.model_runner = runner - worker.reset_mm_cache() - if reset == "callable": - reset_fn.assert_called_once_with() - assert worker.model_runner is runner - - @pytest.fixture def worker_constructor(monkeypatch): """Mock external setup while retaining both real Worker constructors.""" diff --git a/tests/ut/worker/test_worker_weight_checker.py b/tests/ut/worker/test_worker_weight_checker.py index 4fb9af21549f..b12b88695cfb 100644 --- a/tests/ut/worker/test_worker_weight_checker.py +++ b/tests/ut/worker/test_worker_weight_checker.py @@ -3,14 +3,14 @@ """Unit tests for the NPUWorker weight-checker methods. The checksum/reset behavior comes from the paired vLLM's -``vllm.model_executor.model_loader.weight_checksum`` (PR #51350); these tests -only cover the NPUWorker wiring: method presence, rank-key prefixes, model -access for both runner shapes, and the weight_nz_mode warning. +``vllm.model_executor.model_loader.weight_checksum`` (PR #51350) and the worker +methods themselves are inherited from vLLM's ``gpu_worker.Worker``; these tests +pin the contract the NPU worker relies on: method presence, the rank-key +prefix, and the checksum/reset behavior over a real model. """ from types import SimpleNamespace from typing import Any, cast -from unittest.mock import MagicMock import pytest import torch @@ -19,7 +19,6 @@ from vllm.v1.worker import gpu_worker from vllm_ascend._310p.worker_310p import NPUWorker310 -from vllm_ascend.worker import worker as npu_worker_module from vllm_ascend.worker.worker import NPUWorker @@ -39,15 +38,6 @@ def mock_parallel_groups(monkeypatch): monkeypatch.setattr(gpu_worker, name, lambda: group) -@pytest.fixture -def mock_ascend_config(monkeypatch): - monkeypatch.setattr( - npu_worker_module, - "get_ascend_config", - lambda: SimpleNamespace(weight_nz_mode=0), - ) - - def _make_worker(dp_rank: int) -> NPUWorker: worker = object.__new__(NPUWorker) worker.parallel_config = ParallelConfig(data_parallel_size=2, data_parallel_rank=dp_rank) @@ -78,7 +68,7 @@ def test_compute_weight_checksums_prefixes_keys(mock_parallel_groups): assert all(all(c in "0123456789abcdef" for c in digest) for digest in checksums.values()) -def test_reset_weights_zeroes_params_not_buffers(mock_parallel_groups, mock_ascend_config): +def test_reset_weights_zeroes_params_not_buffers(mock_parallel_groups): model = _TinyModel() worker = _make_worker(dp_rank=0) worker.model_runner = cast(Any, SimpleNamespace(get_model=lambda: model)) @@ -87,36 +77,3 @@ def test_reset_weights_zeroes_params_not_buffers(mock_parallel_groups, mock_asce assert torch.all(model.linear.weight == 0) assert model.scale.item() == 2.0 - - -def test_reset_weights_warns_under_nz_mode(mock_parallel_groups, monkeypatch): - """weight_nz_mode=1: reset still zeroes params and logs the NZ warning.""" - monkeypatch.setattr( - npu_worker_module, - "get_ascend_config", - lambda: SimpleNamespace(weight_nz_mode=1), - ) - mock_logger = MagicMock() - monkeypatch.setattr(npu_worker_module, "logger", mock_logger) - model = _TinyModel() - worker = _make_worker(dp_rank=0) - worker.model_runner = cast(Any, SimpleNamespace(get_model=lambda: model)) - - worker.reset_weights() - - assert torch.all(model.linear.weight == 0) - mock_logger.warning.assert_called_once() - assert "weight_nz_mode" in mock_logger.warning.call_args.args[0] - - -def test_methods_work_with_v2_runner_shape(mock_parallel_groups, mock_ascend_config): - model = _TinyModel() - # The v2 model runner only exposes the model attribute, no get_model(). - worker = _make_worker(dp_rank=0) - worker.model_runner = cast(Any, SimpleNamespace(model=model)) - - checksums = worker.compute_weight_checksums() - assert set(checksums) == {"dp0:pp0:pcp0:tp0:linear.weight"} - - worker.reset_weights() - assert torch.all(model.linear.weight == 0) diff --git a/vllm_ascend/worker/worker.py b/vllm_ascend/worker/worker.py index 6a09d5ba2cde..b6320b28347f 100644 --- a/vllm_ascend/worker/worker.py +++ b/vllm_ascend/worker/worker.py @@ -51,11 +51,8 @@ from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorHandshakeMetadata from vllm.distributed.parallel_state import get_pp_group, get_tp_group from vllm.logger import logger -from vllm.lora.request import LoRARequest -from vllm.model_executor.model_loader.weight_checksum import compute_tensor_digests, zero_weights from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors -from vllm.tasks import SupportedTask from vllm.utils.mem_constants import GiB_bytes from vllm.utils.mem_utils import MemorySnapshot, format_gib, memory_profiling from vllm.utils.torch_utils import STR_DTYPE_TO_TORCH_DTYPE @@ -71,7 +68,7 @@ SlidingWindowSpec, UniformTypeKVCacheSpecs, ) -from vllm.v1.outputs import EMPTY_MODEL_RUNNER_OUTPUT, AsyncModelRunnerOutput, DraftTokenIds, ModelRunnerOutput +from vllm.v1.outputs import EMPTY_MODEL_RUNNER_OUTPUT, AsyncModelRunnerOutput, ModelRunnerOutput from vllm.v1.utils import report_usage_stats from vllm.v1.worker import gpu_worker from vllm.v1.worker.gpu_worker import AsyncIntermediateTensors @@ -301,14 +298,6 @@ def _maybe_activate_jit_monitor(self) -> None: def _get_cudagraph_capture_context(self) -> AbstractContextManager[None]: raise NotImplementedError("GPUWorker._get_cudagraph_capture_context is not validated on Ascend.") - def reset_mm_cache(self) -> None: - reset_fn = getattr(self.model_runner, "reset_mm_cache", None) - if callable(reset_fn): - reset_fn() - - def get_draft_model(self) -> nn.Module | None: - raise NotImplementedError("GPUWorker.get_draft_model is not validated on Ascend.") - def supports_draft_weight_updates(self) -> bool: return False @@ -1169,30 +1158,6 @@ def _warm_up_atb(self): c = torch.rand((4, 4), dtype=torch.float32).npu() torch_npu._npu_matmul_add_fp32(x, weight, c) - def get_model(self) -> nn.Module: - return self.model_runner.get_model() - - def _weight_checksum_model(self) -> nn.Module: - # The v1 model runner exposes get_model(); the v2 runner (still under - # development) only exposes the model attribute. - get_model = getattr(self.model_runner, "get_model", None) - if callable(get_model): - return get_model() - return self.model_runner.model - - def compute_weight_checksums(self) -> dict[str, str]: - prefix = self._weight_checksum_prefix() - digests = compute_tensor_digests(self._weight_checksum_model()) - return {prefix + name: digest for name, digest in digests.items()} - - def reset_weights(self) -> None: - if get_ascend_config().weight_nz_mode: - logger.warning( - "weight_nz_mode is enabled: weight transfer update is unavailable, " - "reset weights can only be restored via checkpoint reload (reload_weights)." - ) - zero_weights(self._weight_checksum_model()) - def get_kv_connector_handshake_metadata( self, ) -> dict[tuple[int, ...], KVConnectorHandshakeMetadata] | None: @@ -1360,21 +1325,6 @@ def profile( return profiler.stop() - def add_lora(self, lora_request: LoRARequest) -> bool: - return self.model_runner.add_lora(lora_request) - - def remove_lora(self, lora_id: int) -> bool: - return self.model_runner.remove_lora(lora_id) - - def list_loras(self) -> set[int]: - return self.model_runner.list_loras() - - def pin_lora(self, lora_id: int) -> bool: - return self.model_runner.pin_lora(lora_id) - - def reset_encoder_cache(self) -> None: - self.model_runner.reset_encoder_cache() - def synchronize_device(self) -> None: torch.npu.synchronize() @@ -1439,12 +1389,6 @@ def _init_worker_distributed_environment(self) -> None: def get_supported_pooling_tasks(self): return self.model_runner.get_supported_pooling_tasks() - def get_supported_tasks(self) -> "tuple[SupportedTask, ...]": - return self.model_runner.get_supported_tasks() - - def take_draft_token_ids(self) -> DraftTokenIds | None: - return self.model_runner.take_draft_token_ids() - def update_config(self, overrides: dict[str, Any]) -> None: self.model_runner.update_config(overrides) From 7d382db7c7b6e9ba5be81ed543dd195cd339a292 Mon Sep 17 00:00:00 2001 From: Ronald1995 Date: Tue, 24 Nov 2026 19:36:40 +0800 Subject: [PATCH 2/3] test: cover get_draft_model behavior per review The identity assertion for get_draft_model only pinned that NPUWorker resolves the RPC to the upstream method, but this RPC used to raise on Ascend, so review asked for behavior coverage of a configured drafter. Bind the upstream runner implementation that this RPC resolves to (Model Runner V2) and cover its three states: no speculator, a DraftModelSpeculator carrying a draft module, and a non-draft speculator. The draft module is returned by identity only in the configured case; the other two yield None. The identity checks for the remaining accessors stay unchanged. Verified on both supported vLLM lanes (v0.33.0 and main@c410543d) on NPU: 116 passed on each. Signed-off-by: Ronald1995 --- tests/ut/worker/test_worker_inheritance.py | 42 +++++++++++++++++++--- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/tests/ut/worker/test_worker_inheritance.py b/tests/ut/worker/test_worker_inheritance.py index a9247c704806..b4fc3c9df134 100644 --- a/tests/ut/worker/test_worker_inheritance.py +++ b/tests/ut/worker/test_worker_inheritance.py @@ -4,8 +4,8 @@ import importlib import inspect import sys -from types import ModuleType, SimpleNamespace -from unittest.mock import Mock, call +from types import MethodType, ModuleType, SimpleNamespace +from unittest.mock import MagicMock, Mock, call import pytest @@ -75,18 +75,50 @@ def test_shutdown_weight_transfer_engine_is_inherited(): @pytest.mark.parametrize( "name", - ("reset_mm_cache", "get_draft_model", "compute_weight_checksums", "reset_weights"), + ("reset_mm_cache", "compute_weight_checksums", "reset_weights"), ) def test_model_accessors_are_inherited(name): from vllm.v1.worker.gpu_worker import Worker as GPUWorker from vllm_ascend.worker.worker import NPUWorker - # Every supported runner exposes get_model()/get_draft_model()/reset_mm_cache(), - # so these worker RPCs need no Ascend override. + # Every supported runner exposes get_model()/reset_mm_cache(), so these + # worker RPCs need no Ascend override. assert getattr(NPUWorker, name) is getattr(GPUWorker, name) +@pytest.mark.parametrize("drafter", ["absent", "draft-model", "other-speculator"]) +def test_get_draft_model_reports_the_runner_drafter(drafter): + """This RPC used to raise on Ascend; it now reports the runner's drafter. + + Bind the real upstream runner implementation so both branches of its + isinstance() gate run: a configured DraftModelSpeculator yields its draft + module, while no drafter (or a non-draft speculator) yields None. + """ + import torch + from vllm.v1.worker.gpu.model_runner import GPUModelRunner + from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator + + from vllm_ascend.worker.worker import NPUWorker + + draft_model = torch.nn.Linear(2, 2) if drafter == "draft-model" else None + if drafter == "draft-model": + speculator = MagicMock(spec=DraftModelSpeculator) + speculator.model = draft_model + elif drafter == "other-speculator": + speculator = object() # e.g. a speculator that carries no draft model + else: + speculator = None + + runner = SimpleNamespace(speculator=speculator) + runner.get_draft_model = MethodType(GPUModelRunner.get_draft_model, runner) + + worker = object.__new__(NPUWorker) + worker.model_runner = runner + + assert worker.get_draft_model() is draft_model + + @pytest.mark.parametrize("configured", [False, True]) def test_shutdown_weight_transfer_engine_releases_trainer_connection(configured): from vllm_ascend.worker.worker import NPUWorker From 49a2db1297c3126ec3fe406fd0451c9a01208a22 Mon Sep 17 00:00:00 2001 From: Ronald1995 Date: Tue, 24 Nov 2026 21:15:47 +0800 Subject: [PATCH 3/3] test: annotate the draft-model speculator union for mypy test_get_draft_model_reports_the_runner_drafter bound the speculator variable to MagicMock in the first parametrization branch, so assigning object() in the 'other-speculator' branch tripped mypy with 'Incompatible types in assignment (expression has type object, variable has type MagicMock)' on Python 3.10, 3.11 and 3.12, failing the pre-commit job and with it the ci-gate. Declare the object | None union before the branches and keep the mock in its own local so the attribute write stays typed. The generated objects are unchanged, so the test still exercises the same three drafter states. Signed-off-by: Ronald1995 --- tests/ut/worker/test_worker_inheritance.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/ut/worker/test_worker_inheritance.py b/tests/ut/worker/test_worker_inheritance.py index b4fc3c9df134..e039e449dcc8 100644 --- a/tests/ut/worker/test_worker_inheritance.py +++ b/tests/ut/worker/test_worker_inheritance.py @@ -102,9 +102,14 @@ def test_get_draft_model_reports_the_runner_drafter(drafter): from vllm_ascend.worker.worker import NPUWorker draft_model = torch.nn.Linear(2, 2) if drafter == "draft-model" else None + # The runner only reads isinstance()/attribute state from this slot, so the + # parameterization mixes a mock with plain objects on purpose. Annotate the + # union up front so mypy does not pin it to the first MagicMock branch. + speculator: object | None if drafter == "draft-model": - speculator = MagicMock(spec=DraftModelSpeculator) - speculator.model = draft_model + mock_speculator = MagicMock(spec=DraftModelSpeculator) + mock_speculator.model = draft_model + speculator = mock_speculator elif drafter == "other-speculator": speculator = object() # e.g. a speculator that carries no draft model else: