[CI] Ignore ruff D209, rejoin the docstrings it split, and silence incompatible-rule warnings (#57212)
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
1085b64425
commit
651a88c09a
@@ -365,8 +365,7 @@ class AttentionBackend(ABC):
|
||||
@classmethod
|
||||
def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...] | None:
|
||||
"""Layouts this backend's kernels can consume, most preferred first, or
|
||||
None when the kernels consume any layout and express no preference.
|
||||
"""
|
||||
None when the kernels consume any layout and express no preference."""
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
@@ -558,8 +557,7 @@ M = TypeVar("M")
|
||||
class AttentionCGSupport(Enum):
|
||||
"""Constants for the cudagraph support of the attention backend
|
||||
Here we do not consider the cascade attention, as currently
|
||||
it is never cudagraph supported.
|
||||
"""
|
||||
it is never cudagraph supported."""
|
||||
|
||||
ALWAYS = 3
|
||||
"""Cudagraph always supported; supports mixed-prefill-decode"""
|
||||
|
||||
@@ -84,8 +84,7 @@ class CPUAttentionBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def supports_attn_type(cls, attn_type: str) -> bool:
|
||||
"""CPU attention supports decoder,
|
||||
encoder-only and encoder-decoder attention.
|
||||
"""
|
||||
encoder-only and encoder-decoder attention."""
|
||||
return attn_type in (
|
||||
AttentionType.DECODER,
|
||||
AttentionType.ENCODER,
|
||||
|
||||
@@ -398,8 +398,7 @@ class FlashInferBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
|
||||
"""NVFP4 stores K and V as separate per-head slots of packed fp4 data
|
||||
plus fp8 block scales.
|
||||
"""
|
||||
plus fp8 block scales."""
|
||||
if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_nvfp4:
|
||||
return spec
|
||||
hs_k = nvfp4_kv_cache_full_dim(spec.head_size)
|
||||
|
||||
@@ -63,8 +63,7 @@ _SPLIT_OCCUPANCY_MULTIPLIER = 2
|
||||
|
||||
def _compute_num_kv_splits(max_seq_len: int, num_threads: int) -> int:
|
||||
"""Mirrors TritonMLAImpl's _compute_num_kv_splits, using the CPU thread
|
||||
count in place of SM count.
|
||||
"""
|
||||
count in place of SM count."""
|
||||
ideal_splits = 1
|
||||
while ideal_splits < max(1, max_seq_len // _MIN_WORK_PER_SPLIT):
|
||||
ideal_splits *= 2
|
||||
|
||||
@@ -847,8 +847,7 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
prefill_meta: "FlashMLASparseMetadata.FP8SeparatePrefillDecode.Prefill",
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""All-gather this rank's upconverted KV shard so the chunk's rows attend
|
||||
the whole context, and map their top-k onto the rank-major result.
|
||||
"""
|
||||
the whole context, and map their top-k onto the rank-major result."""
|
||||
shard_rows = int(chunk.chunk_tot_seqlen)
|
||||
assert self.gathered_kv_workspace is not None
|
||||
gathered_kv = self.gathered_kv_workspace[: self.dcp_world_size * shard_rows]
|
||||
|
||||
@@ -1118,8 +1118,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
|
||||
def _prefill_split_seq_lens(self, seq_lens_cpu: torch.Tensor) -> torch.Tensor:
|
||||
"""Per-request KV lengths the prefill chunker budgets logits with;
|
||||
subclasses whose logits rows are wider than the context override.
|
||||
"""
|
||||
subclasses whose logits rows are wider than the context override."""
|
||||
return seq_lens_cpu
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -70,8 +70,7 @@ class MLAPrefillBackend(ABC):
|
||||
def supports_quant_output(self, quant_key: "QuantKey") -> bool:
|
||||
"""Whether `run_prefill_new_tokens` can write quantized output
|
||||
directly (fused) for the given quant key, skipping the post-quant
|
||||
pass. Overridden by backends that support it.
|
||||
"""
|
||||
pass. Overridden by backends that support it."""
|
||||
return False
|
||||
|
||||
def supports_out(self) -> bool:
|
||||
|
||||
@@ -110,8 +110,7 @@ class RocmAiterUnifiedAttentionBackend(RocmAttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
"""Keep K and V packed in the content dim, unlike the native HIP
|
||||
kernels the base class targets.
|
||||
"""
|
||||
kernels the base class targets."""
|
||||
# block_size == 1 is the per-token page-size probe (see
|
||||
# Platform.get_page_size_bytes); real blocks must be gatherable in
|
||||
# 16-token units by the ROCm kernel.
|
||||
|
||||
@@ -244,8 +244,7 @@ class RocmAttentionBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
"""K and V as two head groups so the native HIP kernels address each side
|
||||
as one contiguous region (x-packed interior applied in split_kv_cache).
|
||||
"""
|
||||
as one contiguous region (x-packed interior applied in split_kv_cache)."""
|
||||
if spec.state_content_bytes is not None:
|
||||
return spec
|
||||
assert spec.head_size == spec.head_size_v, (
|
||||
|
||||
@@ -275,8 +275,7 @@ class TritonAttentionBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
|
||||
"""Per-token-head modes pack inline fp32 scales after each head's
|
||||
data, so the content is (data + one scale) per K/V side.
|
||||
"""
|
||||
data, so the content is (data + one scale) per K/V side."""
|
||||
mode = spec.kv_quant_mode
|
||||
if spec.state_content_bytes is not None or not mode.is_per_token_head:
|
||||
return spec
|
||||
|
||||
@@ -45,8 +45,7 @@ def _store_quantized_value(
|
||||
BLOCK_GRP: tl.constexpr,
|
||||
):
|
||||
"""Uniform quantization of values to VQB bits, pack, and store with
|
||||
scale/zero in the per-block SoA metadata region (Opt#3 layout).
|
||||
"""
|
||||
scale/zero in the per-block SoA metadata region (Opt#3 layout)."""
|
||||
if VQB == 3:
|
||||
val_vec = tl.load(Value_ptr + base + d_offs, mask=d_mask, other=0.0).to(
|
||||
tl.float32
|
||||
|
||||
@@ -461,8 +461,7 @@ class KVCacheCoordinator(ABC):
|
||||
) -> tuple[tuple[list[KVCacheBlock], ...], int, int]:
|
||||
"""Returns the per-group hit blocks, the hit length, and the number of
|
||||
``num_uncached_common_prefix_tokens`` (a shared prefix that a
|
||||
sparse-retention group has not cached yet; 0 unless hybrid).
|
||||
"""
|
||||
sparse-retention group has not cached yet; 0 unless hybrid)."""
|
||||
pass
|
||||
|
||||
def new_step_starts(self) -> None:
|
||||
|
||||
@@ -856,8 +856,7 @@ class KVCacheManager:
|
||||
self, request_id: str, start_token: int, end_token: int
|
||||
) -> list[int]:
|
||||
"""The request's block ids covering [start_token, end_token), from
|
||||
the groups whose new blocks are zeroed by the worker.
|
||||
"""
|
||||
the groups whose new blocks are zeroed by the worker."""
|
||||
ids: list[int] = []
|
||||
for mgr in self.coordinator.single_type_managers:
|
||||
if mgr.records_new_block_ids:
|
||||
|
||||
@@ -178,8 +178,7 @@ class SchedulerInterface(ABC):
|
||||
|
||||
def has_unfinished_requests(self) -> bool:
|
||||
"""Returns True if there are unfinished requests in the scheduler's
|
||||
internal queue.
|
||||
"""
|
||||
internal queue."""
|
||||
return self.get_num_unfinished_requests() > 0
|
||||
|
||||
@abstractmethod
|
||||
@@ -199,8 +198,7 @@ class SchedulerInterface(ABC):
|
||||
|
||||
def has_requests(self) -> bool:
|
||||
"""Returns True if there are unfinished requests, or finished requests
|
||||
not yet returned in SchedulerOutputs.
|
||||
"""
|
||||
not yet returned in SchedulerOutputs."""
|
||||
return self.has_unfinished_requests() or self.has_finished_requests()
|
||||
|
||||
@property
|
||||
|
||||
@@ -43,8 +43,7 @@ class RequestQueue(ABC):
|
||||
@abstractmethod
|
||||
def prepend_requests(self, requests: "RequestQueue") -> None:
|
||||
"""Prepend all requests from another queue to the front of this
|
||||
queue.
|
||||
"""
|
||||
queue."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -161,16 +160,14 @@ class PriorityRequestQueue(RequestQueue):
|
||||
"""Add a request to the queue according to priority policy.
|
||||
|
||||
Note: In a priority queue, there is no concept of prepending to the
|
||||
front. Requests are ordered by (priority, arrival_time).
|
||||
"""
|
||||
front. Requests are ordered by (priority, arrival_time)."""
|
||||
self.add_request(request)
|
||||
|
||||
def prepend_requests(self, requests: RequestQueue) -> None:
|
||||
"""Add all requests from another queue according to priority policy.
|
||||
|
||||
Note: In a priority queue, there is no concept of prepending to the
|
||||
front. Requests are ordered by (priority, arrival_time).
|
||||
"""
|
||||
front. Requests are ordered by (priority, arrival_time)."""
|
||||
for request in requests:
|
||||
self.add_request(request)
|
||||
|
||||
|
||||
@@ -871,8 +871,7 @@ class AsyncLLM(EngineClient):
|
||||
) -> None:
|
||||
"""Submit a pre-aborted request so the connector's request_finished
|
||||
hook runs to free any pre-admission KV-transfer resources (e.g. NIXL
|
||||
prefill blocks pinned on the P node).
|
||||
"""
|
||||
prefill blocks pinned on the P node)."""
|
||||
request = EngineCoreRequest(
|
||||
request_id=request_id,
|
||||
prompt_token_ids=[0],
|
||||
|
||||
@@ -598,8 +598,7 @@ class EngineCore:
|
||||
|
||||
def _should_throttle_prefills(self) -> bool:
|
||||
"""Whether to defer new prefills this step (DP prefill balancing).
|
||||
Overridden by the DP engine core; never throttles otherwise.
|
||||
"""
|
||||
Overridden by the DP engine core; never throttles otherwise."""
|
||||
return False
|
||||
|
||||
def step(self) -> tuple[dict[int, EngineCoreOutputs], bool]:
|
||||
@@ -1623,8 +1622,7 @@ class EngineCoreProc(EngineCore):
|
||||
@staticmethod
|
||||
def _convert_msgspec_args(method, args):
|
||||
"""If a provided arg type doesn't match corresponding target method
|
||||
arg type, try converting to msgspec object.
|
||||
"""
|
||||
arg type, try converting to msgspec object."""
|
||||
if not args:
|
||||
return args
|
||||
arg_types = signature(method).parameters.values()
|
||||
@@ -2006,8 +2004,7 @@ class EngineCoreProc(EngineCore):
|
||||
|
||||
class DPEngineCoreProc(EngineCoreProc):
|
||||
"""ZMQ-wrapper for running EngineCore in background process
|
||||
in a data parallel context.
|
||||
"""
|
||||
in a data parallel context."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -248,8 +248,7 @@ class EngineCoreClient(ABC):
|
||||
|
||||
def dp_engines_running(self) -> bool:
|
||||
"""Returns True if data parallel engines are collectively in a
|
||||
running state.
|
||||
"""
|
||||
running state."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def commit_elastic_ep(self) -> None:
|
||||
@@ -446,8 +445,7 @@ class InprocClient(EngineCoreClient):
|
||||
@dataclass
|
||||
class BackgroundResources:
|
||||
"""Used as a finalizer for clean shutdown, avoiding
|
||||
circular reference back to the client object.
|
||||
"""
|
||||
circular reference back to the client object."""
|
||||
|
||||
ctx: zmq.Context
|
||||
# If CoreEngineProcManager, it manages local engines;
|
||||
@@ -801,8 +799,7 @@ class MPClient(EngineCoreClient):
|
||||
|
||||
def _apply_ready_response(self, payload: bytes) -> None:
|
||||
"""Decode an EngineCoreReadyResponse and sync any post-initialization
|
||||
config changes (e.g. auto-fitted max_model_len) back to the frontend.
|
||||
"""
|
||||
config changes (e.g. auto-fitted max_model_len) back to the frontend."""
|
||||
vllm_config = self.vllm_config
|
||||
response = (
|
||||
msgspec.msgpack.decode(payload, type=EngineCoreReadyResponse)
|
||||
@@ -1333,8 +1330,7 @@ class AsyncMPClient(MPClient):
|
||||
|
||||
class DPAsyncMPClient(AsyncMPClient):
|
||||
"""Asyncio-compatible client for multi-proc, multi-engine (data parallel)
|
||||
EngineCore. Assumes external load-balancing by default.
|
||||
"""
|
||||
EngineCore. Assumes external load-balancing by default."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -1518,8 +1514,7 @@ class DPAsyncMPClient(AsyncMPClient):
|
||||
|
||||
class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
"""Asyncio-compatible client for multi-proc, multi-engine (data parallel)
|
||||
EngineCore. Load-balances between multiple engine processes.
|
||||
"""
|
||||
EngineCore. Load-balances between multiple engine processes."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -1827,8 +1822,7 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
num_redundant_experts: int,
|
||||
) -> None:
|
||||
"""Prepare scale up by creating new engine cores and reconfiguring
|
||||
existing ones.
|
||||
"""
|
||||
existing ones."""
|
||||
self._setup_elastic_ep_reconfig_bootstrap()
|
||||
|
||||
# Phase 1: Send reconfig messages to existing engines
|
||||
@@ -1920,8 +1914,7 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
|
||||
async def _commit_scale_down_elastic_ep(self, new_data_parallel_size: int) -> None:
|
||||
"""Scale down the data parallel size by shutting down and
|
||||
reconfiguring existing engine cores.
|
||||
"""
|
||||
reconfiguring existing engine cores."""
|
||||
cur_data_parallel_size = len(self.core_engines)
|
||||
|
||||
self.eep_scaling_cache = ElasticScalingCache(
|
||||
|
||||
@@ -147,8 +147,7 @@ class BaseIncrementalDetokenizer(IncrementalDetokenizer, ABC):
|
||||
|
||||
def get_next_output_text(self, finished: bool, delta: bool) -> str:
|
||||
"""If delta is True, only new text since the last call to
|
||||
this method is returned
|
||||
"""
|
||||
this method is returned"""
|
||||
# We return the full output text if the sequence is finished.
|
||||
buffer_length = 0 if finished else self.stop_buffer_length
|
||||
if not delta:
|
||||
|
||||
@@ -1041,8 +1041,7 @@ def get_engine_zmq_addresses(
|
||||
|
||||
Set ``defer_api_server_ports=False`` only when the consumer cannot
|
||||
report a bound port back (e.g. the Rust front-end). IPC paths are
|
||||
unaffected.
|
||||
"""
|
||||
unaffected."""
|
||||
parallel_config = vllm_config.parallel_config
|
||||
local_engine_count = parallel_config.data_parallel_size_local
|
||||
local_start_index = parallel_config.data_parallel_rank_local
|
||||
|
||||
@@ -284,8 +284,7 @@ class Executor(ABC):
|
||||
@abstractmethod
|
||||
def check_health(self) -> None:
|
||||
"""Checks if the executor is healthy. If not, it should raise an
|
||||
exception.
|
||||
"""
|
||||
exception."""
|
||||
raise NotImplementedError
|
||||
|
||||
def shutdown(self) -> None:
|
||||
|
||||
@@ -384,8 +384,7 @@ class MultiprocExecutor(Executor):
|
||||
ec_output_aggregator: ECOutputAggregator | None = None,
|
||||
) -> Any:
|
||||
"""Returns single result if unique_reply_rank and/or an output
|
||||
aggregator is provided, otherwise list.
|
||||
"""
|
||||
aggregator is provided, otherwise list."""
|
||||
assert self.rpc_broadcast_mq is not None, (
|
||||
"collective_rpc should not be called on follower node"
|
||||
)
|
||||
@@ -452,8 +451,7 @@ class MultiprocExecutor(Executor):
|
||||
def _ensure_worker_termination(worker_procs: list[BaseProcess]):
|
||||
"""Ensure that all worker processes are terminated. Assumes workers have
|
||||
received termination requests. Waits for processing, then sends
|
||||
termination and kill signals if needed.
|
||||
"""
|
||||
termination and kill signals if needed."""
|
||||
|
||||
def wait_for_termination(procs, timeout):
|
||||
if not time:
|
||||
@@ -854,8 +852,7 @@ class WorkerProc:
|
||||
@staticmethod
|
||||
def worker_main(*args, **kwargs):
|
||||
"""Worker initialization and execution loops.
|
||||
This runs a background process
|
||||
"""
|
||||
This runs a background process"""
|
||||
# Signal handler used for graceful termination.
|
||||
# SystemExit exception is only raised once to allow this and worker
|
||||
# processes to terminate without error
|
||||
@@ -1099,8 +1096,7 @@ class WorkerProc:
|
||||
def set_multiprocessing_worker_envs(local_world_size: int = 1):
|
||||
"""Set up environment variables that should be used when there are workers
|
||||
in a multiprocessing environment. This should be called by the parent
|
||||
process before worker processes are created
|
||||
"""
|
||||
process before worker processes are created"""
|
||||
_maybe_force_spawn()
|
||||
|
||||
if current_platform.is_cpu() or "OMP_NUM_THREADS" in os.environ:
|
||||
|
||||
@@ -55,8 +55,7 @@ try:
|
||||
|
||||
class RayWorkerWrapper(WorkerWrapperBase):
|
||||
"""Ray wrapper for vllm.worker.Worker, allowing Worker to be
|
||||
lazily initialized after Ray sets CUDA_VISIBLE_DEVICES.
|
||||
"""
|
||||
lazily initialized after Ray sets CUDA_VISIBLE_DEVICES."""
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
@@ -1252,8 +1252,7 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
|
||||
|
||||
def get_max_layers_per_page_size(self) -> int:
|
||||
"""Max number of layers sharing a page size. For a balanced bucket
|
||||
this equals the number of repetitions of the layer pattern.
|
||||
"""
|
||||
this equals the number of repetitions of the layer pattern."""
|
||||
return Counter(
|
||||
spec.page_size_bytes for spec in self.kv_cache_specs.values()
|
||||
).most_common(1)[0][1]
|
||||
|
||||
@@ -49,8 +49,7 @@ class KVCacheLayout(Enum):
|
||||
@property
|
||||
def is_block_compact(self) -> bool:
|
||||
"""True when each page's [H, N, C] bytes form one contiguous run; i.e.
|
||||
the L and B dimensions are outermost.
|
||||
"""
|
||||
the L and B dimensions are outermost."""
|
||||
return set(self.value[:2]) == {_DIM_L, _DIM_B}
|
||||
|
||||
@property
|
||||
|
||||
@@ -472,8 +472,7 @@ class CopyRun:
|
||||
"""A strided byte correspondence between this worker's physical page and
|
||||
a canonical page: for i in range(num_fragments), fragment i spans
|
||||
[local_offset + i * local_stride, +fragment_size) in the worker's page and
|
||||
[canonical_offset + i * canonical_stride, +fragment_size) canonically.
|
||||
"""
|
||||
[canonical_offset + i * canonical_stride, +fragment_size) canonically."""
|
||||
|
||||
local_offset: int
|
||||
canonical_offset: int
|
||||
@@ -554,8 +553,7 @@ class TransferResult:
|
||||
class OffloadingWorker(ABC):
|
||||
"""Runs in the worker process. Performs async KV transfers for ONE
|
||||
offloaded medium (e.g. CPU). Direction is explicit via submit_store /
|
||||
submit_load, so there is no (src_medium, dst_medium) routing.
|
||||
"""
|
||||
submit_load, so there is no (src_medium, dst_medium) routing."""
|
||||
|
||||
@abstractmethod
|
||||
def submit_store(
|
||||
|
||||
@@ -126,8 +126,7 @@ def compute_sub_block_ptrs(
|
||||
class CopyPlan(NamedTuple):
|
||||
"""Precomputed fragment-copy template for one data ref under the canonical
|
||||
CPU layout, unrolled from the ref's mapped runs. Offsets are relative to
|
||||
the per-block base pointers on each side.
|
||||
"""
|
||||
the per-block base pointers on each side."""
|
||||
|
||||
frag_offsets_src: np.ndarray
|
||||
frag_offsets_dst: np.ndarray
|
||||
@@ -165,8 +164,7 @@ def _canonical_page_ids(
|
||||
) -> np.ndarray:
|
||||
"""Global canonical page ids matching compute_sub_block_ptrs' enumeration.
|
||||
These identify canonical pages consistently across ranks, so they key
|
||||
CanonicalPageMapping.is_writer rotation.
|
||||
"""
|
||||
CanonicalPageMapping.is_writer rotation."""
|
||||
if blocks_per_chunk == 1:
|
||||
return block_ids[:count]
|
||||
flat = (
|
||||
@@ -179,8 +177,7 @@ def _canonical_block_sizes(
|
||||
layer_refs_per_group: list[list[CanonicalKVCacheRef]], num_tensors: int
|
||||
) -> list[int]:
|
||||
"""Canonical CPU bytes per GPU block for each tensor, taken from the refs'
|
||||
mappings. Requires every ref to carry a mapping.
|
||||
"""
|
||||
mappings. Requires every ref to carry a mapping."""
|
||||
canonical_bytes_per_block = [0] * num_tensors
|
||||
for layer_refs in layer_refs_per_group:
|
||||
for ref in layer_refs:
|
||||
@@ -343,8 +340,7 @@ class SingleDirectionOffloadingHandler:
|
||||
"""Upper bound on the number of copy descriptors for a transfer.
|
||||
|
||||
Exact for the direct layout. The canonical path may fill fewer:
|
||||
writer rotation later drops the blocks this rank does not write.
|
||||
"""
|
||||
writer rotation later drops the blocks this rank does not write."""
|
||||
num_copy_ops = 0
|
||||
for g_idx, (group_size, layer_refs) in enumerate(
|
||||
zip(group_sizes, self.layer_refs_per_group)
|
||||
@@ -373,8 +369,7 @@ class SingleDirectionOffloadingHandler:
|
||||
"""Fill one group's copy descriptors for the direct (worker-private)
|
||||
layout: one whole-page copy per (block, ref).
|
||||
|
||||
Returns (op_idx past the filled descriptors, bytes added).
|
||||
"""
|
||||
Returns (op_idx past the filled descriptors, bytes added)."""
|
||||
num_bytes = 0
|
||||
for data_ref in self.layer_refs_per_group[g_idx]:
|
||||
t_idx = data_ref.tensor_idx
|
||||
@@ -417,8 +412,7 @@ class SingleDirectionOffloadingHandler:
|
||||
scatter each block through the ref's precomputed CopyPlan, keeping
|
||||
only the blocks this rank writes.
|
||||
|
||||
Returns (op_idx past the filled descriptors, bytes added).
|
||||
"""
|
||||
Returns (op_idx past the filled descriptors, bytes added)."""
|
||||
assert self._canonical_copy_plans is not None
|
||||
# Zero-copy reinterpretation for pointer arithmetic: uint64 and the
|
||||
# buffers' int64 are bit-equivalent for addresses
|
||||
@@ -505,8 +499,7 @@ class SingleDirectionOffloadingHandler:
|
||||
) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Keep only the blocks this rank writes: replicated ranks take turns
|
||||
writing shared canonical pages, keyed by the rank-consistent CPU-side
|
||||
canonical page id.
|
||||
"""
|
||||
canonical page id."""
|
||||
cpu_page_ids = _canonical_page_ids(
|
||||
group_dst,
|
||||
self.dst_blocks_per_chunk,
|
||||
|
||||
@@ -28,8 +28,7 @@ def _all_workers_barrier() -> None:
|
||||
"""Block until every worker rank has reached this point (gloo cpu group).
|
||||
|
||||
A superset of the node-local mmap openers suffices: once the barrier
|
||||
releases, every worker sharing the region file has mapped it.
|
||||
"""
|
||||
releases, every worker sharing the region file has mapped it."""
|
||||
from vllm.distributed.parallel_state import (
|
||||
get_inner_dp_world_group,
|
||||
get_world_group,
|
||||
@@ -162,8 +161,7 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
|
||||
def _uses_shared_region(self) -> bool:
|
||||
"""Whether the worker CPU buffer is the shared mmap region (vs a private
|
||||
per-rank tensor); replicated-layout dedup is gated on this being True.
|
||||
"""
|
||||
per-rank tensor); replicated-layout dedup is gated on this being True."""
|
||||
return current_platform.is_cuda_alike()
|
||||
|
||||
def create_worker(self, kv_caches: CanonicalKVCaches) -> CPUOffloadingWorker:
|
||||
|
||||
@@ -216,8 +216,7 @@ class AsyncLookupManager(ABC):
|
||||
def mark_miss(self, keys: Collection[OffloadKey]) -> None:
|
||||
"""Force the cached verdict for ``keys`` to False after a failed load, so
|
||||
the scheduler stops re-issuing the doomed promotion (livelock, #49176).
|
||||
Keys with no cached entry are skipped.
|
||||
"""
|
||||
Keys with no cached entry are skipped."""
|
||||
for key in keys:
|
||||
state = self._lookup_state.get(key)
|
||||
if state is not None:
|
||||
|
||||
@@ -168,8 +168,7 @@ class ExampleSecondaryTierManager(SecondaryTierManager):
|
||||
@override
|
||||
def drain_jobs(self) -> None:
|
||||
"""Synchronous tier — submit_*() returns only after the operation
|
||||
completes, so there is nothing to wait for.
|
||||
"""
|
||||
completes, so there is nothing to wait for."""
|
||||
return
|
||||
|
||||
def get_num_chunks(self) -> int:
|
||||
|
||||
@@ -139,8 +139,7 @@ def _load_block(
|
||||
) -> None:
|
||||
"""Read one KV block from disk; remove the file only on a provable short
|
||||
read (a too-short file is genuine corruption) and leave it untouched on any
|
||||
other error.
|
||||
"""
|
||||
other error."""
|
||||
fd: int | None = None
|
||||
view_slice = view.cast("B")[offset : offset + block_size]
|
||||
o_direct = O_DIRECT if use_o_direct else 0
|
||||
|
||||
@@ -269,8 +269,7 @@ class FileSystemTierManager(SecondaryTierManager):
|
||||
@override
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""Collect finished jobs; a failed promotion marks only its failed keys
|
||||
as a miss here (scheduler thread).
|
||||
"""
|
||||
as a miss here (scheduler thread)."""
|
||||
results = []
|
||||
for job_id, success, transfer_time in self._pool.get_finished():
|
||||
if self.events is not None:
|
||||
|
||||
@@ -143,8 +143,7 @@ class CPUPrimaryTierOffloadingManager(CPUOffloadingManager):
|
||||
|
||||
class _SecondaryTierFacingParent(ParentManager):
|
||||
"""Wrapper that implements ParentManager by delegating to the
|
||||
TieringOffloadingManager with exclude_tier_idx set to the origin tier.
|
||||
"""
|
||||
TieringOffloadingManager with exclude_tier_idx set to the origin tier."""
|
||||
|
||||
__slots__ = ("_m", "_origin_idx")
|
||||
|
||||
|
||||
@@ -308,8 +308,7 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
def _poll_active_transfers(self) -> None:
|
||||
"""Poll all in-flight transfers once; move newly-completed (success or
|
||||
failure) into ``_pending_results`` and release their NIXL handles.
|
||||
"""
|
||||
failure) into ``_pending_results`` and release their NIXL handles."""
|
||||
for job_id, entry in list(self._transfers.items()):
|
||||
try:
|
||||
state = self._agent.check_xfer_state(entry.xfer_handle)
|
||||
@@ -364,8 +363,7 @@ class ObjectStoreSecondaryTierManager(SecondaryTierManager):
|
||||
|
||||
def get_finished_jobs(self) -> Iterable[JobResult]:
|
||||
"""Poll transfers; a failed promotion marks its cached verdicts False
|
||||
here (scheduler thread).
|
||||
"""
|
||||
here (scheduler thread)."""
|
||||
self._poll_active_transfers()
|
||||
results = self._pending_results
|
||||
self._pending_results = []
|
||||
|
||||
@@ -134,8 +134,7 @@ class P2PDestInfo:
|
||||
|
||||
def _parse_source(kv_params: dict | None) -> P2PSourceInfo | None:
|
||||
"""Parse the consumer sub-dict (PD ``remote_prefiller`` or symmetric
|
||||
``remote_kv_source``) into a ``P2PSourceInfo``, or None if absent/incomplete.
|
||||
"""
|
||||
``remote_kv_source``) into a ``P2PSourceInfo``, or None if absent/incomplete."""
|
||||
role = _remote_prefiller_params(kv_params)
|
||||
do_probe = False
|
||||
if role is None:
|
||||
@@ -156,8 +155,7 @@ def _parse_source(kv_params: dict | None) -> P2PSourceInfo | None:
|
||||
|
||||
def _parse_dest(kv_params: dict | None) -> P2PDestInfo | None:
|
||||
"""Parse the producer ``remote_decoder`` sub-dict into a ``P2PDestInfo``,
|
||||
or None if the block is absent (not a remote-decode request).
|
||||
"""
|
||||
or None if the block is absent (not a remote-decode request)."""
|
||||
role = _remote_decoder_params(kv_params)
|
||||
if role is None:
|
||||
return None
|
||||
|
||||
@@ -414,8 +414,7 @@ class TieringOffloadingSpec(CPUOffloadingSpec):
|
||||
"""Require a mapping on every ref and record layer portability.
|
||||
|
||||
Fails loudly rather than persist direct-layout bytes under a
|
||||
canonical format identity.
|
||||
"""
|
||||
canonical format identity."""
|
||||
all_refs = [
|
||||
ref for group_refs in kv_caches.group_data_refs for ref in group_refs
|
||||
]
|
||||
|
||||
@@ -91,8 +91,7 @@ def load_stat_logger_plugin_factories() -> list[StatLoggerFactory]:
|
||||
|
||||
class AggregateStatLoggerBase(StatLoggerBase):
|
||||
"""Abstract base class for loggers that
|
||||
aggregate across multiple DP engines.
|
||||
"""
|
||||
aggregate across multiple DP engines."""
|
||||
|
||||
@abstractmethod
|
||||
def __init__(self, vllm_config: VllmConfig, engine_indexes: list[int]): ...
|
||||
|
||||
@@ -1820,8 +1820,7 @@ def get_required(obj: object, attr: str):
|
||||
|
||||
def getattr_from_list(obj: object, attrs: list[str], default: object = None):
|
||||
"""Try to get the first attr that exists in the object
|
||||
from a list of attrs. Otherwise return None.
|
||||
"""
|
||||
from a list of attrs. Otherwise return None."""
|
||||
for attr in attrs:
|
||||
if hasattr(obj, attr):
|
||||
return getattr(obj, attr)
|
||||
|
||||
@@ -82,8 +82,7 @@ class RayPrometheusMetric:
|
||||
|
||||
class RayGaugeWrapper(RayPrometheusMetric):
|
||||
"""Wraps around ray.util.metrics.Gauge to provide same API as
|
||||
prometheus_client.Gauge
|
||||
"""
|
||||
prometheus_client.Gauge"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -117,8 +116,7 @@ class RayGaugeWrapper(RayPrometheusMetric):
|
||||
|
||||
class RayCounterWrapper(RayPrometheusMetric):
|
||||
"""Wraps around ray.util.metrics.Counter to provide same API as
|
||||
prometheus_client.Counter
|
||||
"""
|
||||
prometheus_client.Counter"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -143,8 +141,7 @@ class RayCounterWrapper(RayPrometheusMetric):
|
||||
|
||||
class RayHistogramWrapper(RayPrometheusMetric):
|
||||
"""Wraps around ray.util.metrics.Histogram to provide same API as
|
||||
prometheus_client.Histogram
|
||||
"""
|
||||
prometheus_client.Histogram"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -129,8 +129,7 @@ class LogitBiasLogitsProcessor(LogitsProcessor):
|
||||
|
||||
def is_argmax_invariant(self) -> bool:
|
||||
"""Logit bias can rebalance token probabilities and change the
|
||||
outcome of argmax in greedy sampling.
|
||||
"""
|
||||
outcome of argmax in greedy sampling."""
|
||||
return False
|
||||
|
||||
def update_state(self, batch_update: BatchUpdate | None):
|
||||
@@ -189,8 +188,7 @@ class MinTokensLogitsProcessor(LogitsProcessor):
|
||||
|
||||
def is_argmax_invariant(self) -> bool:
|
||||
"""By censoring stop tokens, min-tokens can change the outcome
|
||||
of the argmax operation in greedy sampling.
|
||||
"""
|
||||
of the argmax operation in greedy sampling."""
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -69,8 +69,7 @@ class BatchUpdateBuilder:
|
||||
@property
|
||||
def removed(self) -> list[RemovedRequest]:
|
||||
"""Removed request indices sorted in
|
||||
descending order
|
||||
"""
|
||||
descending order"""
|
||||
self._ensure_removed_sorted()
|
||||
return self._removed
|
||||
|
||||
|
||||
@@ -90,8 +90,7 @@ def _typestr(val: Any) -> tuple[str, str] | None:
|
||||
|
||||
def _encode_type_info_recursive(obj: Any) -> Any:
|
||||
"""Recursively encode type information for nested structures of
|
||||
lists/dicts.
|
||||
"""
|
||||
lists/dicts."""
|
||||
if obj is None:
|
||||
return None
|
||||
if type(obj) is list:
|
||||
@@ -105,8 +104,7 @@ def _decode_type_info_recursive(
|
||||
type_info: Any, data: Any, convert_fn: Callable[[Sequence[str], Any], Any]
|
||||
) -> Any:
|
||||
"""Recursively decode type information for nested structures of
|
||||
lists/dicts.
|
||||
"""
|
||||
lists/dicts."""
|
||||
if type_info is None:
|
||||
return data
|
||||
if isinstance(type_info, dict):
|
||||
|
||||
@@ -259,8 +259,7 @@ class SimpleCPUOffloadScheduler:
|
||||
gpu_config: "KVCacheConfig", cpu_capacity_bytes: int
|
||||
) -> "KVCacheConfig":
|
||||
"""Derive a CPU KVCacheConfig from the GPU config.
|
||||
Same kv_cache_groups, num_blocks scaled by CPU/GPU memory ratio.
|
||||
"""
|
||||
Same kv_cache_groups, num_blocks scaled by CPU/GPU memory ratio."""
|
||||
# Import here to avoid potential circular imports
|
||||
from vllm.v1.kv_cache_interface import KVCacheTensor
|
||||
|
||||
@@ -315,8 +314,7 @@ class SimpleCPUOffloadScheduler:
|
||||
|
||||
def bind_gpu_block_pool(self, gpu_block_pool: BlockPool) -> None:
|
||||
"""Bind GPU block pool so that we can touch blocks during stores.
|
||||
Called by Scheduler after kv_cache_manager is ready.
|
||||
"""
|
||||
Called by Scheduler after kv_cache_manager is ready."""
|
||||
self._gpu_block_pool = gpu_block_pool
|
||||
|
||||
def get_num_new_matched_tokens(
|
||||
@@ -1131,8 +1129,7 @@ class SimpleCPUOffloadScheduler:
|
||||
block_ids: list[int],
|
||||
) -> tuple[bool, dict[str, Any] | None]:
|
||||
"""Always returns (False, None). GPU blocks are protected by ref_cnt,
|
||||
so the scheduler can free blocks immediately.
|
||||
"""
|
||||
so the scheduler can free blocks immediately."""
|
||||
req_id = request.request_id
|
||||
|
||||
# Release any temp CPU hit pin from get_num_new_matched_tokens()
|
||||
|
||||
@@ -396,8 +396,7 @@ class ExtractHiddenStatesProposer:
|
||||
|
||||
def validate_same_kv_cache_group(self, kv_cache_config: KVCacheConfig) -> None:
|
||||
"""Validate all drafting layers belong to the same KV cache group
|
||||
and record the group index for common_attn_metadata selection.
|
||||
"""
|
||||
and record the group index for common_attn_metadata selection."""
|
||||
assert len(self.attn_layer_names) == 1
|
||||
layer = self.attn_layer_names[0]
|
||||
for gid, group in enumerate(kv_cache_config.kv_cache_groups):
|
||||
|
||||
@@ -221,8 +221,7 @@ class Gemma4Proposer(SpecDecodeBaseProposer):
|
||||
def validate_same_kv_cache_group(self, kv_cache_config: KVCacheConfig) -> None:
|
||||
"""Draft layers span multiple KV cache groups (sliding + full
|
||||
attention with different head dimensions), so skip the base
|
||||
class single-group assertion.
|
||||
"""
|
||||
class single-group assertion."""
|
||||
|
||||
def initialize_attn_backend(
|
||||
self,
|
||||
@@ -230,8 +229,7 @@ class Gemma4Proposer(SpecDecodeBaseProposer):
|
||||
kernel_block_sizes: list[int] | None = None,
|
||||
) -> None:
|
||||
"""Create separate AttentionGroup objects per KV cache spec
|
||||
so that each head-dim variant gets its own metadata builder.
|
||||
"""
|
||||
so that each head-dim variant gets its own metadata builder."""
|
||||
all_attn_layers = get_layers_from_vllm_config(
|
||||
self.vllm_config,
|
||||
AttentionLayerBase, # type: ignore[type-abstract]
|
||||
|
||||
@@ -785,8 +785,7 @@ class SpecDecodeBaseProposer:
|
||||
block_size: int,
|
||||
) -> torch.Tensor:
|
||||
"""Update positions, slot mappings, and sequence metadata for the
|
||||
next draft step. Returns the updated positions tensor.
|
||||
"""
|
||||
next draft step. Returns the updated positions tensor."""
|
||||
positions_1d = positions[0] if self.uses_mrope else positions
|
||||
if self.uses_mrope:
|
||||
out_pos = self.mrope_positions[0, :batch_size]
|
||||
|
||||
@@ -847,6 +847,5 @@ def update_num_computed_tokens_for_batch_change(
|
||||
|
||||
def unconditional_to_conditional_rates(rates: list[float]) -> list[float]:
|
||||
"""Convert per-position unconditional rates to per-position conditional
|
||||
rates for the early-terminating rejection loop (c_i = p_i / p_{i-1}).
|
||||
"""
|
||||
rates for the early-terminating rejection loop (c_i = p_i / p_{i-1})."""
|
||||
return [p / q if q > 0.0 else 0.0 for p, q in zip(rates, [1.0, *rates[:-1]])]
|
||||
|
||||
+4
-8
@@ -144,8 +144,7 @@ class CpuGpuBuffer:
|
||||
|
||||
def copy_to_cpu(self, n: int | None = None) -> torch.Tensor:
|
||||
"""NOTE: Because this method is non-blocking, explicit synchronization
|
||||
is needed to ensure the data is copied to CPU.
|
||||
"""
|
||||
is needed to ensure the data is copied to CPU."""
|
||||
if n is None:
|
||||
return self.cpu.copy_(self.gpu, non_blocking=True)
|
||||
return self.cpu[:n].copy_(self.gpu[:n], non_blocking=True)
|
||||
@@ -159,8 +158,7 @@ def get_engine_client_zmq_addr(
|
||||
"""Return an IPC path (``local_only=True``) or ``tcp://host:port``.
|
||||
|
||||
``port=0`` lets the kernel assign the port at ``bind()`` time; the
|
||||
caller must recover it via ``getsockopt(zmq.LAST_ENDPOINT)``.
|
||||
"""
|
||||
caller must recover it via ``getsockopt(zmq.LAST_ENDPOINT)``."""
|
||||
if local_only:
|
||||
return get_open_zmq_ipc_path()
|
||||
return get_tcp_uri(host, port)
|
||||
@@ -265,8 +263,7 @@ class APIServerProcessManager:
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Return (inputs, outputs) reported by each child, indexed by
|
||||
``client_index``. Raises ``RuntimeError`` on timeout or premature
|
||||
child exit.
|
||||
"""
|
||||
child exit."""
|
||||
n = len(self._address_pipes)
|
||||
inputs: list[str | None] = [None] * n
|
||||
outputs: list[str | None] = [None] * n
|
||||
@@ -427,8 +424,7 @@ class RustFrontendProcessManager:
|
||||
|
||||
class _SubprocessWrapper:
|
||||
"""Wraps subprocess.Popen to provide the BaseProcess-like interface
|
||||
needed by wait_for_completion_or_failure.
|
||||
"""
|
||||
needed by wait_for_completion_or_failure."""
|
||||
|
||||
def __init__(self, proc, name: str):
|
||||
self._proc = proc
|
||||
|
||||
@@ -76,8 +76,7 @@ class EncoderCudaGraphManager:
|
||||
model: SupportsEncoderCudaGraph,
|
||||
):
|
||||
"""Initialize CUDA graph manager with provided token budgets
|
||||
and max batch size.
|
||||
"""
|
||||
and max batch size."""
|
||||
self.vllm_config = vllm_config
|
||||
self.device = device
|
||||
self.dtype = dtype
|
||||
|
||||
@@ -62,8 +62,7 @@ class AttentionState(NamedTuple):
|
||||
@dataclass(frozen=True)
|
||||
class BatchExecutionDescriptor:
|
||||
"""Describes the shape of the batch and CG mode to run; this is used to make shape
|
||||
matches between the capture and runtime.
|
||||
"""
|
||||
matches between the capture and runtime."""
|
||||
|
||||
cg_mode: CUDAGraphMode
|
||||
num_tokens: int
|
||||
@@ -91,8 +90,7 @@ def make_cudagraph_stats(
|
||||
class CreateForwardFn(Protocol):
|
||||
"""Factory that prepares inputs (OUTSIDE the graph) and returns a
|
||||
forward_fn. Called with warmup=True for the warmup pass and warmup=False
|
||||
for the captured pass.
|
||||
"""
|
||||
for the captured pass."""
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
@@ -955,8 +953,7 @@ def profile_cudagraph_memory(runner: "GPUModelRunner") -> int:
|
||||
def _extrapolate_full_graph_memory(mem_samples: list[int], total_graphs: int) -> int:
|
||||
"""Extrapolate the total FULL capture cost from samples of the largest
|
||||
graphs. The first capture allocates the pool baseline; later graphs mostly
|
||||
reuse it, so the second sample is taken as the per-graph cost.
|
||||
"""
|
||||
reuse it, so the second sample is taken as the per-graph cost."""
|
||||
if not mem_samples:
|
||||
return 0
|
||||
first_capture = mem_samples[0]
|
||||
@@ -993,8 +990,7 @@ def _init_minimal_kv_cache_for_profiling(runner: "GPUModelRunner") -> None:
|
||||
|
||||
def _teardown_profiling_state(runner: "GPUModelRunner") -> None:
|
||||
"""Release the profiling KV cache and captured graphs while keeping model
|
||||
weights, so the real ``initialize_kv_cache`` starts from a clean slate.
|
||||
"""
|
||||
weights, so the real ``initialize_kv_cache`` starts from a clean slate."""
|
||||
torch.accelerator.synchronize()
|
||||
if hasattr(runner.model_state, "_mamba_ctx"):
|
||||
runner.model_state._mamba_ctx = None
|
||||
|
||||
@@ -2228,8 +2228,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Release GPU tensors (model weights, KV caches, workspace) so that
|
||||
memory is reclaimable when running in the same process.
|
||||
"""
|
||||
memory is reclaimable when running in the same process."""
|
||||
torch.accelerator.synchronize()
|
||||
self.cudagraph_manager = None
|
||||
self.fast_prefill = None
|
||||
|
||||
@@ -144,8 +144,7 @@ class ModelState(ABC):
|
||||
) -> None:
|
||||
"""Hook run on real batches before the forward pass (after block tables
|
||||
are gathered). Used by mamba "align" prefix caching to pre-copy state
|
||||
across block boundaries. No-op by default.
|
||||
"""
|
||||
across block boundaries. No-op by default."""
|
||||
return None
|
||||
|
||||
def postprocess_state(
|
||||
|
||||
@@ -38,8 +38,7 @@ def compute_need_sampled_mask(input_batch: InputBatch) -> np.ndarray | None:
|
||||
"""Return a bool array of shape `[input_batch.num_reqs]` marking requests
|
||||
that produce a sampled token this step, and therefore must have that token
|
||||
(and the draft block proposed from it) propagated to the earlier PP stages.
|
||||
Returns None if no request in the batch produces a sample.
|
||||
"""
|
||||
Returns None if no request in the batch produces a sample."""
|
||||
old_computed = input_batch.num_computed_tokens_np
|
||||
prefill_len = input_batch.prefill_len_np
|
||||
# Exclude non-final prefill chunks (they don't produce a sample).
|
||||
@@ -179,8 +178,7 @@ class PPHandler:
|
||||
|
||||
def receive(self, input_batch: InputBatch) -> bool:
|
||||
"""Returns True iff sampled tokens need to be gathered from *all*
|
||||
requests in the batch.
|
||||
"""
|
||||
requests in the batch."""
|
||||
assert not self.is_last_rank
|
||||
need_sampled_mask = compute_need_sampled_mask(input_batch)
|
||||
if need_sampled_mask is None:
|
||||
|
||||
@@ -76,8 +76,7 @@ MAX_COMPACT_SUPPORT = 2048
|
||||
|
||||
class SamplingMaskTensors(NamedTuple):
|
||||
"""Device-side masks pending async D2H: compact ids, plus the bitmask as
|
||||
the exact fallback for rows wider than ``max_num_kept``.
|
||||
"""
|
||||
the exact fallback for rows wider than ``max_num_kept``."""
|
||||
|
||||
# [num_requests, max_num_kept]
|
||||
token_ids: torch.Tensor
|
||||
|
||||
@@ -107,8 +107,7 @@ class Sampler:
|
||||
self, idx_mapping_np: np.ndarray, include_token_ids: bool = True
|
||||
) -> tuple[int, int] | None:
|
||||
"""(num_logprobs, max_per_req_token_ids) for the given requests, or
|
||||
None when none of them want logprobs.
|
||||
"""
|
||||
None when none of them want logprobs."""
|
||||
max_num_logprobs = self.sampling_states.max_num_logprobs(idx_mapping_np)
|
||||
max_token_ids = (
|
||||
self.logprob_token_ids_state.max_num_token_ids(idx_mapping_np)
|
||||
|
||||
@@ -190,8 +190,7 @@ class AdaptiveVerificationManager:
|
||||
"""Dummy-run kwargs whose step timings seed the cost tables.
|
||||
|
||||
Run these inside StepTimingCollector.collect(), then hand the block's
|
||||
timings to set_initial_cost_curves.
|
||||
"""
|
||||
timings to set_initial_cost_curves."""
|
||||
max_num_tokens = self.req_states.max_num_batched_tokens
|
||||
size = self._cudagraph_limit = capture_sizes[-1] if capture_sizes else 0
|
||||
# Also profile beyond the capture limit: real steps run there
|
||||
@@ -261,8 +260,7 @@ class AdaptiveVerificationManager:
|
||||
input_batch: "InputBatch",
|
||||
) -> None:
|
||||
"""Publish this step's raw confidences for the ranking kernel and start
|
||||
copying them to the CPU, where a later step's budget reads them.
|
||||
"""
|
||||
copying them to the CPU, where a later step's budget reads them."""
|
||||
num_reqs = input_batch.num_reqs
|
||||
ready_idx = self._stale_idx ^ 1
|
||||
with gpu_sync_allowed():
|
||||
|
||||
@@ -72,8 +72,7 @@ def _prepare_dflash_inputs_to_capture(
|
||||
|
||||
class DFlashCudaGraphManager(CudaGraphManager):
|
||||
"""DFlash CudaGraphManager for the parallel-drafting query forward,
|
||||
building its own attention metadata from scratch.
|
||||
"""
|
||||
building its own attention metadata from scratch."""
|
||||
|
||||
def capture(
|
||||
self,
|
||||
|
||||
@@ -28,8 +28,7 @@ def _should_share(eagle: nn.Module, flag: str, draft, target) -> bool:
|
||||
|
||||
def get_target_lm_head(target_model: nn.Module, target_language_model: nn.Module):
|
||||
"""The target's lm_head — from get_language_model() for
|
||||
*ForConditionalGeneration targets, else the top-level module.
|
||||
"""
|
||||
*ForConditionalGeneration targets, else the top-level module."""
|
||||
return getattr(target_language_model, "lm_head", None) or getattr(
|
||||
target_model, "lm_head", None
|
||||
)
|
||||
|
||||
@@ -268,8 +268,7 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
@property
|
||||
def attn_vllm_config(self) -> VllmConfig:
|
||||
"""Config for the draft's attention metadata builders. Overridden by
|
||||
speculators whose attention mode differs from the target's.
|
||||
"""
|
||||
speculators whose attention mode differs from the target's."""
|
||||
return self.vllm_config
|
||||
|
||||
def set_attn(
|
||||
|
||||
@@ -481,8 +481,7 @@ class AsyncGPUPoolingModelRunnerOutput(AsyncModelRunnerOutput):
|
||||
|
||||
class ExecuteModelState(NamedTuple):
|
||||
"""Ephemeral cached state transferred between execute_model() and
|
||||
sample_tokens(), after execute_model() returns None.
|
||||
"""
|
||||
sample_tokens(), after execute_model() returns None."""
|
||||
|
||||
scheduler_output: "SchedulerOutput"
|
||||
logits: torch.Tensor
|
||||
@@ -1072,8 +1071,7 @@ class GPUModelRunner(
|
||||
first scheduled token (column j is position start - 1 - j); -1 where
|
||||
the position is before the prompt or already past it. Generated
|
||||
positions are left to the model: under async scheduling the CPU token
|
||||
table holds placeholders for them.
|
||||
"""
|
||||
table holds placeholders for them."""
|
||||
buf = self.lookback_token_ids
|
||||
assert buf is not None
|
||||
buf.np.fill(-1)
|
||||
@@ -3206,8 +3204,7 @@ class GPUModelRunner(
|
||||
|
||||
def _get_encoder_output_from_cache(self, mm_hash: str) -> torch.Tensor | None:
|
||||
"""Return a cached encoder output for multimodal
|
||||
embedding gather.
|
||||
"""
|
||||
embedding gather."""
|
||||
return self.encoder_cache.get(mm_hash, None)
|
||||
|
||||
def _gather_mm_embeddings(
|
||||
@@ -4179,8 +4176,7 @@ class GPUModelRunner(
|
||||
|
||||
This is true when `discard_request_mask` is set for every scheduled
|
||||
request (e.g., for chunked prefill requests that are not the last
|
||||
prefill chunk).
|
||||
"""
|
||||
prefill chunk)."""
|
||||
num_reqs = self.input_batch.num_reqs
|
||||
return bool(self.discard_request_mask.np[:num_reqs].all())
|
||||
|
||||
@@ -6573,8 +6569,7 @@ class GPUModelRunner(
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Release GPU tensors (model weights, KV caches, workspace) so that
|
||||
memory is reclaimable when running in the same process.
|
||||
"""
|
||||
memory is reclaimable when running in the same process."""
|
||||
from vllm.model_executor.layers.rotary_embedding import _ROPE_DICT
|
||||
from vllm.v1.worker.workspace import reset_workspace_manager
|
||||
|
||||
|
||||
@@ -336,8 +336,7 @@ class Worker(WorkerBase):
|
||||
def _scoped_allocator_max_split(self, max_split_size_mb: int):
|
||||
"""Temporarily set max_split_size_mb to reduce allocator fragmentation at the
|
||||
cost of more cudaMalloc calls (negligible in practice). Restores the original
|
||||
value on exit.
|
||||
"""
|
||||
value on exit."""
|
||||
if not current_platform.is_cuda():
|
||||
yield
|
||||
return
|
||||
|
||||
@@ -77,8 +77,7 @@ def compute_plan_fingerprint(
|
||||
def _plan_path(fingerprint: str) -> str:
|
||||
"""Plans are regenerable derived state, so they live under the standard
|
||||
vLLM cache root (like the torch.compile cache) and relocate with
|
||||
``VLLM_CACHE_ROOT`` instead of needing a location knob of their own.
|
||||
"""
|
||||
``VLLM_CACHE_ROOT`` instead of needing a location knob of their own."""
|
||||
# VLLM_CACHE_ROOT is already user-expanded by envs.py.
|
||||
return os.path.join(
|
||||
envs.VLLM_CACHE_ROOT, "startup_plan", f"startup_plan_{fingerprint}.json"
|
||||
@@ -135,8 +134,7 @@ def _applicable_kv_cache_memory_bytes(
|
||||
def maybe_apply_startup_plan(worker: "Worker") -> None:
|
||||
"""If enabled and ``--kv-cache-memory`` was not set explicitly, apply a
|
||||
persisted plan by setting ``worker.cache_config.kv_cache_memory_bytes``.
|
||||
No-op unless ``VLLM_ENABLE_STARTUP_PLAN=1``.
|
||||
"""
|
||||
No-op unless ``VLLM_ENABLE_STARTUP_PLAN=1``."""
|
||||
if (
|
||||
not envs.VLLM_ENABLE_STARTUP_PLAN
|
||||
or worker.cache_config.kv_cache_memory_bytes is not None
|
||||
@@ -169,8 +167,7 @@ def maybe_apply_startup_plan(worker: "Worker") -> None:
|
||||
def maybe_save_startup_plan(worker: "Worker", kv_cache_memory_bytes: int) -> None:
|
||||
"""Atomically persist this boot's profiling result for future boots.
|
||||
No-op unless ``VLLM_ENABLE_STARTUP_PLAN=1``; failures are logged,
|
||||
never raised.
|
||||
"""
|
||||
never raised."""
|
||||
if not envs.VLLM_ENABLE_STARTUP_PLAN:
|
||||
return
|
||||
fingerprint = compute_plan_fingerprint(
|
||||
|
||||
@@ -128,8 +128,7 @@ class WorkerBase:
|
||||
|
||||
def synchronize_device(self) -> None:
|
||||
"""Block until in-flight device work completes; backends outside
|
||||
``torch.accelerator`` must override with their own wait.
|
||||
"""
|
||||
``torch.accelerator`` must override with their own wait."""
|
||||
if torch.accelerator.is_available():
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user