[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
+1
-2
@@ -1974,8 +1974,7 @@ class rocm_aiter_ops:
|
||||
enabled aiter. Only aiter's Triton kernels exist on gfx12 (no CK build),
|
||||
so this deliberately stays off the gfx9/CK `@if_aiter_supported` umbrella
|
||||
and gates only the Triton paths rdna4 uses. The gfx12 analog of
|
||||
`is_enabled()`.
|
||||
"""
|
||||
`is_enabled()`."""
|
||||
if not current_platform.is_rocm() or not IS_AITER_FOUND:
|
||||
return False
|
||||
from vllm.platforms.rocm import on_rdna4
|
||||
|
||||
@@ -65,8 +65,7 @@ def create_txt_slices_jsonl(
|
||||
trust_remote_code: bool = False,
|
||||
) -> None:
|
||||
"""Read *input_path*, slice it into prompts, and write JSONL to
|
||||
*output_path*.
|
||||
"""
|
||||
*output_path*."""
|
||||
tokenizer = AutoTokenizer.from_pretrained(
|
||||
tokenizer_name, trust_remote_code=trust_remote_code
|
||||
)
|
||||
|
||||
@@ -4383,8 +4383,7 @@ class PrefixRepetitionRandomDataset(BenchmarkDataset):
|
||||
|
||||
def _generate_exact_length_tokens(target_length: int) -> tuple[list[int], int]:
|
||||
"""Generate tokens that decode and re-encode to exactly
|
||||
target_length.
|
||||
"""
|
||||
target_length."""
|
||||
# Generate random tokens
|
||||
tokens = np.random.randint(0, vocab_size, size=target_length).tolist()
|
||||
|
||||
|
||||
@@ -22,8 +22,7 @@ AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=6 * 60 * 60)
|
||||
|
||||
class StreamedResponseHandler:
|
||||
"""Handles streaming HTTP responses by accumulating chunks until complete
|
||||
messages are available.
|
||||
"""
|
||||
messages are available."""
|
||||
|
||||
def __init__(self):
|
||||
self.buffer = ""
|
||||
@@ -31,8 +30,7 @@ class StreamedResponseHandler:
|
||||
|
||||
def add_chunk(self, chunk_bytes: bytes) -> list[str]:
|
||||
"""Add a chunk of bytes to the buffer and return any complete
|
||||
messages.
|
||||
"""
|
||||
messages."""
|
||||
chunk_str = self._decoder.decode(chunk_bytes)
|
||||
self.buffer += chunk_str
|
||||
|
||||
|
||||
@@ -150,8 +150,7 @@ class CompilerManager:
|
||||
def compile_context(self, compile_range: Range) -> Generator[None, None, None]:
|
||||
"""Provide compilation context for the duration of compilation to set
|
||||
any torch global properties we want to scope to a single Inductor
|
||||
compilation (e.g. partition rules, pass context).
|
||||
"""
|
||||
compilation (e.g. partition rules, pass context)."""
|
||||
with pass_context(compile_range):
|
||||
if self.compilation_config.use_inductor_graph_partition:
|
||||
with inductor_partition_rule_context(
|
||||
|
||||
@@ -153,8 +153,7 @@ def _get_vllm_functorch_config() -> dict[str, Any]:
|
||||
"""Return the functorch config overrides that vLLM applies at compile time.
|
||||
|
||||
Used by both set_functorch_config() and get_inductor_factors() to ensure
|
||||
the compile-time config and cache key are always consistent.
|
||||
"""
|
||||
the compile-time config and cache key are always consistent."""
|
||||
cfg: dict[str, Any] = {}
|
||||
if not envs.VLLM_USE_MEGA_AOT_ARTIFACT:
|
||||
cfg["bundled_autograd_cache"] = False
|
||||
|
||||
@@ -66,8 +66,7 @@ def _view_flashinfer_nvfp4_scale_out_as_int32(
|
||||
|
||||
def _norm_input_weight_dtype_match(match: pm.Match) -> bool:
|
||||
"""Prevent fusion when the norm input and weight dtypes differ (e.g. a Gemma
|
||||
fp32 weight.float()+1 gamma), covering rms_norm and fused_add_rms_norm.
|
||||
"""
|
||||
fp32 weight.float()+1 gamma), covering rms_norm and fused_add_rms_norm."""
|
||||
for node in match.nodes:
|
||||
if node.target == _IR_RMS_NORM_OP:
|
||||
x, weight = node.args[0], node.args[1]
|
||||
|
||||
@@ -30,8 +30,7 @@ logger = init_logger(__name__)
|
||||
|
||||
class SplitCoalescingPass(VllmInductorPass):
|
||||
"""Replace duplicate ``split_with_sizes`` nodes with a single canonical
|
||||
node when they share the same input tensor and split sizes.
|
||||
"""
|
||||
node when they share the same input tensor and split sizes."""
|
||||
|
||||
@VllmInductorPass.time_and_log
|
||||
def __call__(self, graph: fx.Graph) -> None:
|
||||
|
||||
@@ -36,8 +36,7 @@ logger = init_logger(__name__)
|
||||
|
||||
class CompilationMode(enum.IntEnum):
|
||||
"""The compilation approach used for torch.compile-based compilation of the
|
||||
model.
|
||||
"""
|
||||
model."""
|
||||
|
||||
NONE = 0
|
||||
"""No torch.compile compilation is applied, model runs in fully eager pytorch mode.
|
||||
@@ -337,8 +336,7 @@ class PassConfig:
|
||||
class DynamicShapesType(str, enum.Enum):
|
||||
"""Types of dynamic shapes handling in torch.compile().
|
||||
see Dynamic shapes and vllm guard dropping in torch_compile.md
|
||||
for more details.
|
||||
"""
|
||||
for more details."""
|
||||
|
||||
BACKED = "backed"
|
||||
"""Use backed dynamic shapes. torch.compile() guards on backed dynamic
|
||||
|
||||
@@ -1005,8 +1005,7 @@ class ModelConfig:
|
||||
|
||||
def _get_transformers_backend_cls(self) -> str:
|
||||
"""Determine which Transformers modeling backend class will be used if
|
||||
`model_impl` is set to `transformers` or `auto`.
|
||||
"""
|
||||
`model_impl` is set to `transformers` or `auto`."""
|
||||
cls = "Transformers"
|
||||
# If 'hf_config is not hf_text_config' it's a nested config, i.e. multimodal
|
||||
cls += "MultiModal" if self.hf_config is not self.hf_text_config else ""
|
||||
|
||||
@@ -524,8 +524,7 @@ class MultiModalConfig:
|
||||
|
||||
def get_video_pruning_spec(self) -> tuple[VideoPruningMethod, float] | None:
|
||||
"""Return `(method, rate)` when video pruning is enabled, else None.
|
||||
`rate` is the fraction of video tokens to prune.
|
||||
"""
|
||||
`rate` is the fraction of video tokens to prune."""
|
||||
if self.video_pruning_rate is not None and self.video_pruning_rate > 0:
|
||||
return (self.video_pruning_method, float(self.video_pruning_rate))
|
||||
return None
|
||||
|
||||
@@ -156,8 +156,7 @@ class ObservabilityConfig:
|
||||
cls, value: list[DetailedTraceModules] | None
|
||||
) -> list[DetailedTraceModules] | None:
|
||||
"""Handle the legacy case where users might provide a comma-separated
|
||||
string instead of a list of strings.
|
||||
"""
|
||||
string instead of a list of strings."""
|
||||
if value is not None and len(value) == 1 and "," in value[0]:
|
||||
value = cast(list[DetailedTraceModules], value[0].split(","))
|
||||
return value
|
||||
|
||||
@@ -47,15 +47,13 @@ class ReasoningConfig:
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
"""Returns True if reasoning is enabled (i.e. if token IDs have been
|
||||
initialized), False otherwise.
|
||||
"""
|
||||
initialized), False otherwise."""
|
||||
return self._enabled
|
||||
|
||||
@property
|
||||
def reasoning_start_token_ids(self) -> list[int] | None:
|
||||
"""Token IDs derived from `reasoning_start_str`. Set automatically by
|
||||
`initialize_token_ids`. Not intended to be configured directly.
|
||||
"""
|
||||
`initialize_token_ids`. Not intended to be configured directly."""
|
||||
return self._reasoning_start_token_ids
|
||||
|
||||
@property
|
||||
|
||||
@@ -543,8 +543,7 @@ class SpeculativeConfig:
|
||||
@staticmethod
|
||||
def _acceptance_length_to_rates(length: float, n: int) -> list[float]:
|
||||
"""Mean acceptance length to unconditional per-position rates, using
|
||||
the minimum-variance schedule.
|
||||
"""
|
||||
the minimum-variance schedule."""
|
||||
num_drafts = length - 1 # expected number of accepted draft tokens
|
||||
num_full = int(num_drafts)
|
||||
return (
|
||||
@@ -558,8 +557,7 @@ class SpeculativeConfig:
|
||||
length: float | None,
|
||||
) -> list[float]:
|
||||
"""Return per-position unconditional acceptance rates from exactly one
|
||||
of `rates` or `length` (validates range, length, and monotonicity).
|
||||
"""
|
||||
of `rates` or `length` (validates range, length, and monotonicity)."""
|
||||
if (rates is None) == (length is None):
|
||||
raise ValueError(
|
||||
"rejection_sample_method='synthetic' requires exactly one of "
|
||||
|
||||
@@ -84,8 +84,7 @@ def config(
|
||||
|
||||
def get_field(cls: ConfigType, name: str) -> Any:
|
||||
"""Get the default factory field of a dataclass by name. Used for getting
|
||||
default factory fields in `EngineArgs`.
|
||||
"""
|
||||
default factory fields in `EngineArgs`."""
|
||||
if not is_dataclass(cls):
|
||||
raise TypeError("The given class is not a dataclass.")
|
||||
try:
|
||||
@@ -122,8 +121,7 @@ def is_init_field(cls: ConfigType, name: str) -> bool:
|
||||
def replace(dataclass_instance: ConfigT, /, **kwargs) -> ConfigT:
|
||||
"""Like [`dataclasses.replace`](https://docs.python.org/3/library/dataclasses.html#dataclasses.replace),
|
||||
but compatible with Pydantic dataclasses which use `pydantic.fields.Field` instead
|
||||
of `dataclasses.field`
|
||||
"""
|
||||
of `dataclasses.field`"""
|
||||
cls = type(dataclass_instance)
|
||||
dataclass_dict = dataclass_instance.__dict__
|
||||
dataclass_dict = {k: v for k, v in dataclass_dict.items() if is_init_field(cls, k)}
|
||||
|
||||
+2
-4
@@ -153,8 +153,7 @@ IS_DENSE = False
|
||||
|
||||
def enable_norm_fusion(cfg: "VllmConfig") -> bool:
|
||||
"""Enable if either RMS norm or quant FP8 custom op is active;
|
||||
otherwise Inductor handles fusion.
|
||||
"""
|
||||
otherwise Inductor handles fusion."""
|
||||
return (
|
||||
cfg.compilation_config.is_custom_op_enabled("rms_norm")
|
||||
or cfg.compilation_config.is_custom_op_enabled("quant_fp8")
|
||||
@@ -744,8 +743,7 @@ class VllmConfig:
|
||||
|
||||
def _is_dflash2_draft(self) -> bool:
|
||||
"""Whether the DFlash draft is a DFlash2 one, by the architecture the
|
||||
speculator selects on (v1/worker/gpu/spec_decode/__init__.py).
|
||||
"""
|
||||
speculator selects on (v1/worker/gpu/spec_decode/__init__.py)."""
|
||||
spec = self.speculative_config
|
||||
if spec is None or spec.method != "dflash":
|
||||
return False
|
||||
|
||||
@@ -70,8 +70,7 @@ class SleepModeBackend(ABC):
|
||||
|
||||
def state(self) -> SleepModeState:
|
||||
"""Current lifecycle state. Lets ``/health`` distinguish a healthy-idle
|
||||
(suspended) engine from a healthy-serving one (see RFC #34303).
|
||||
"""
|
||||
(suspended) engine from a healthy-serving one (see RFC #34303)."""
|
||||
return self._state
|
||||
|
||||
# -- Capability introspection (no instance required) --
|
||||
@@ -84,30 +83,26 @@ class SleepModeBackend(ABC):
|
||||
@classmethod
|
||||
def preserves_communicators(cls) -> bool:
|
||||
"""If False, collective communicators (e.g. NCCL) are destroyed by
|
||||
``suspend`` and the executor must re-initialize them on ``resume``.
|
||||
"""
|
||||
``suspend`` and the executor must re-initialize them on ``resume``."""
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def preserves_compiled_artifacts(cls) -> bool:
|
||||
"""If True, torch.compile / JIT kernels survive suspend/resume and need
|
||||
not be recompiled on resume.
|
||||
"""
|
||||
not be recompiled on resume."""
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def preserves_graphs_with_communicators(cls) -> bool:
|
||||
"""If True, CUDA graphs containing collective communicators (e.g. NCCL)
|
||||
stay valid after resume. False when communicators are rebuilt (embedded
|
||||
comm handles go stale).
|
||||
"""
|
||||
comm handles go stale)."""
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def supports_durable_storage(cls) -> bool:
|
||||
"""If True, suspended state can be persisted beyond the process
|
||||
lifetime (disk or object storage) and restored in a new process.
|
||||
"""
|
||||
lifetime (disk or object storage) and restored in a new process."""
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@@ -156,8 +156,7 @@ def should_nccl_symm_mem_allreduce(world_size: int, input_tensor: torch.Tensor)
|
||||
|
||||
def should_nccl_symm_mem_ag_rs() -> bool:
|
||||
"""Check whether NCCL symmetric memory should be used for
|
||||
AllGather / ReduceScatter collectives.
|
||||
"""
|
||||
AllGather / ReduceScatter collectives."""
|
||||
from vllm.distributed.device_communicators.pynccl_allocator import (
|
||||
is_symmetric_memory_enabled,
|
||||
)
|
||||
|
||||
@@ -650,8 +650,7 @@ class MessageQueue:
|
||||
|
||||
def shutdown(self):
|
||||
"""If this is an idle reader, wakes it up so it can clean up and shut
|
||||
down
|
||||
"""
|
||||
down"""
|
||||
self.shutting_down = True
|
||||
if self._spin_condition is not None:
|
||||
self._spin_condition.cancel()
|
||||
@@ -761,8 +760,7 @@ class MessageQueue:
|
||||
|
||||
def should_warn(self) -> bool:
|
||||
"""Returns true if it's time to log a warning for a timeout that is not
|
||||
indefinite
|
||||
"""
|
||||
indefinite"""
|
||||
if self._should_warn:
|
||||
elapsed = time.monotonic() - self.started
|
||||
if elapsed >= VLLM_RINGBUFFER_WARNING_INTERVAL * self.n_warning:
|
||||
|
||||
@@ -15,8 +15,7 @@ from collections import OrderedDict
|
||||
|
||||
class CacheEntry:
|
||||
"""A single cache entry. Read `.block_ids` and `.ready` freely;
|
||||
mutations only through EmbeddingCache methods.
|
||||
"""
|
||||
mutations only through EmbeddingCache methods."""
|
||||
|
||||
__slots__ = ("block_ids", "_pin_count")
|
||||
|
||||
|
||||
@@ -84,8 +84,7 @@ class EplbCommunicator(ABC):
|
||||
@property
|
||||
def needs_profile_buffer_reservation(self) -> bool:
|
||||
"""Whether the profile path must run a dummy collective operation to reserve
|
||||
communication buffers.
|
||||
"""
|
||||
communication buffers."""
|
||||
return True
|
||||
|
||||
def set_stream(self, cuda_stream: torch.cuda.Stream | None) -> None:
|
||||
@@ -443,8 +442,7 @@ class NixlEplbCommunicator(EplbCommunicator):
|
||||
|
||||
def _exchange_remote_send_meta(self) -> None:
|
||||
"""Exchange per-layer per-tensor metadata so receivers can compute
|
||||
remote RDMA addresses at transfer time.
|
||||
"""
|
||||
remote RDMA addresses at transfer time."""
|
||||
local_meta: dict[tuple[int, int], tuple[int, int, int]] = {}
|
||||
for layer_idx, layer_tensors in enumerate(self._all_expert_weights):
|
||||
for t_idx, t in enumerate(layer_tensors):
|
||||
|
||||
@@ -51,8 +51,7 @@ def get_kv_connector_cache_layout(vllm_config: VllmConfig | None = None):
|
||||
|
||||
class KVOutputAggregator:
|
||||
"""Utility class to aggregate the output of all workers into a single
|
||||
output corresponding to Rank 0 for scheduler.
|
||||
"""
|
||||
output corresponding to Rank 0 for scheduler."""
|
||||
|
||||
def __init__(self, expected_finished_count: int):
|
||||
# Complete transfer tracker. Used to track finished requests
|
||||
|
||||
@@ -278,8 +278,7 @@ class ExampleHiddenStatesConnector(KVConnectorBase_V1, SupportsHMA):
|
||||
|
||||
def _on_write_done(self, req_id: str, future: Future) -> None:
|
||||
"""Surface any exception from the disk-write thread and drop the
|
||||
completed future from the in-flight tracking dict.
|
||||
"""
|
||||
completed future from the in-flight tracking dict."""
|
||||
self._req_futures.pop(req_id, None)
|
||||
exc = future.exception()
|
||||
if exc is not None:
|
||||
|
||||
@@ -231,8 +231,7 @@ class LMCacheMPRequestTracker:
|
||||
####
|
||||
def needs_retrieve(self) -> bool:
|
||||
"""Check whether the current request needs retrieve, will be used
|
||||
update_stage_after_alloc
|
||||
"""
|
||||
update_stage_after_alloc"""
|
||||
return (
|
||||
self.num_lmcache_hit_blocks > self.num_vllm_hit_blocks
|
||||
and self.state != LMCacheMPRequestState.READY
|
||||
@@ -240,8 +239,7 @@ class LMCacheMPRequestTracker:
|
||||
|
||||
def is_ready_for_retrieving(self) -> bool:
|
||||
"""Check whether the current request is ready for retrieving,
|
||||
will be used in process_loading_requests
|
||||
"""
|
||||
will be used in process_loading_requests"""
|
||||
return (
|
||||
self.state == LMCacheMPRequestState.WAITING_FOR_LOAD
|
||||
and self.needs_retrieve()
|
||||
|
||||
@@ -718,8 +718,7 @@ class MooncakeConnectorScheduler:
|
||||
|
||||
def _get_remote_prefill_token_count(self, num_prompt_tokens: int) -> int:
|
||||
"""D-side only. Returns N-1 for Mamba models since the decoder
|
||||
always recomputes the last token and must start from h(N-1).
|
||||
"""
|
||||
always recomputes the last token and must start from h(N-1)."""
|
||||
if self._has_mamba and num_prompt_tokens > 1:
|
||||
return num_prompt_tokens - 1
|
||||
return num_prompt_tokens
|
||||
@@ -730,8 +729,7 @@ class MooncakeConnectorScheduler:
|
||||
derive h(N) correctly.
|
||||
|
||||
Guarded by ``_p_side_truncated`` to avoid repeated truncation if the
|
||||
request is preempted and rescheduled.
|
||||
"""
|
||||
request is preempted and rescheduled."""
|
||||
params = request.kv_transfer_params
|
||||
if (
|
||||
params is not None
|
||||
@@ -1677,8 +1675,7 @@ class MooncakeConnectorWorker:
|
||||
def _bind_sender_thread_device(self) -> None:
|
||||
"""ThreadPoolExecutor initializer — binds each pool thread to the
|
||||
correct CUDA device. CUDA device selection is thread-local, so
|
||||
without this, NVLink transfers fail for TP ranks > 0.
|
||||
"""
|
||||
without this, NVLink transfers fail for TP ranks > 0."""
|
||||
current_platform.set_device(self.device_id)
|
||||
|
||||
def _send_blocks(
|
||||
@@ -1904,8 +1901,7 @@ class MooncakeConnectorWorker:
|
||||
|
||||
def get_kv_connector_stats(self) -> KVConnectorStats | None:
|
||||
"""Return transfer stats collected since the last call, or None
|
||||
if nothing has been recorded in this interval.
|
||||
"""
|
||||
if nothing has been recorded in this interval."""
|
||||
if self.xfer_stats.is_empty():
|
||||
return None
|
||||
return self.xfer_stats.clone_and_reset()
|
||||
|
||||
@@ -73,8 +73,7 @@ class ExternalCachedBlockPool:
|
||||
|
||||
class MooncakeStoreCoordinator:
|
||||
"""Mirror of ``HybridKVCacheCoordinator.find_longest_cache_hit`` over an
|
||||
``ExternalCachedBlockPool``.
|
||||
"""
|
||||
``ExternalCachedBlockPool``."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -2629,8 +2629,7 @@ class LookupKeyClient:
|
||||
non_block: bool = False,
|
||||
) -> MooncakeLookupResult | None:
|
||||
"""If non_block is True, will return None until the result is ready,
|
||||
so the caller retries on a later step.
|
||||
"""
|
||||
so the caller retries on a later step."""
|
||||
future = self.futures.get(req_id)
|
||||
if future is None:
|
||||
future = self.executor.submit(self._lookup, num_tokens, list(block_hashes))
|
||||
|
||||
@@ -548,8 +548,7 @@ class MoRIIOConnectorScheduler:
|
||||
self, request_id: ReqId, transfer_id: TransferId | None = None
|
||||
):
|
||||
"""Unmap request_id/transfer_id. Uses transfer_id for lookup if
|
||||
exact request_id match fails (handles input_processor mutation).
|
||||
"""
|
||||
exact request_id match fails (handles input_processor mutation)."""
|
||||
if request_id in self.request_id_to_transfer_id:
|
||||
tid = self.request_id_to_transfer_id[request_id]
|
||||
del self.request_id_to_transfer_id[request_id]
|
||||
|
||||
@@ -400,8 +400,7 @@ class NixlBaseConnectorScheduler:
|
||||
def _get_remote_prefill_token_count(self, num_prompt_tokens: int) -> int:
|
||||
"""D-side only. The number of prompt tokens to load from the prefiller.
|
||||
Stops short of the trailing ``_prefill_backoff()`` tokens that the decoder
|
||||
will recompute locally.
|
||||
"""
|
||||
will recompute locally."""
|
||||
backoff = self._prefill_backoff()
|
||||
if backoff and num_prompt_tokens > backoff:
|
||||
return num_prompt_tokens - backoff
|
||||
@@ -414,8 +413,7 @@ class NixlBaseConnectorScheduler:
|
||||
multi-module MTP it is the drafter's whole lookahead window.
|
||||
|
||||
Guarded by ``_p_side_truncated`` to avoid repeated truncation if the
|
||||
request is preempted and rescheduled.
|
||||
"""
|
||||
request is preempted and rescheduled."""
|
||||
backoff = self._prefill_backoff()
|
||||
params = request.kv_transfer_params
|
||||
if (
|
||||
|
||||
@@ -1873,8 +1873,7 @@ class NixlBaseConnectorWorker:
|
||||
) -> np.ndarray:
|
||||
"""Build remote desc regions (conv sub-projections + ssm) per layer.
|
||||
For hetero-TP, each D rank reads only its sub-projection slice from
|
||||
the P rank. Returns an Nx3 uint64 array.
|
||||
"""
|
||||
the P rank. Returns an Nx3 uint64 array."""
|
||||
assert nixl_agent_meta.kv_caches_base_addr, (
|
||||
"Remote KV cache base addresses must not be empty."
|
||||
)
|
||||
@@ -2657,8 +2656,7 @@ class NixlBaseConnectorWorker:
|
||||
@cached_property
|
||||
def _attention_kv_caches(self) -> list[torch.Tensor]:
|
||||
"""Device KV caches of attention layers (mamba states excluded),
|
||||
as consumed by the receive post-process.
|
||||
"""
|
||||
as consumed by the receive post-process."""
|
||||
assert self.device_kv_caches, (
|
||||
"_attention_kv_caches accessed before register_kv_caches"
|
||||
)
|
||||
|
||||
@@ -315,8 +315,7 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
executes on the writer; the handshake runs on the background executor
|
||||
and the request is re-queued onto ``_reg_send_inbox`` once it
|
||||
completes (at which point ``_ensure_handshake`` returns ``None`` and we
|
||||
send directly).
|
||||
"""
|
||||
send directly)."""
|
||||
remote_pp_size = reg_data.get("remote_pp_size", 1)
|
||||
fut = self._ensure_handshake(
|
||||
reg_data["remote_engine_id"],
|
||||
@@ -508,8 +507,7 @@ class NixlPushConnectorWorker(NixlBaseConnectorWorker):
|
||||
``BlockIds`` is canonically a tuple of per-group lists, but some
|
||||
registration payloads collapse a single-group case to a flat
|
||||
list. Re-wrap that case so downstream group-aware helpers see a
|
||||
consistent shape.
|
||||
"""
|
||||
consistent shape."""
|
||||
if block_ids and not isinstance(block_ids[0], (list, tuple)):
|
||||
return (list(block_ids),)
|
||||
return block_ids
|
||||
|
||||
@@ -37,8 +37,7 @@ def canonical_format_id(kv_cache_layout: str) -> str:
|
||||
Canonical pages keep the worker's KV layout family, so the id couples the
|
||||
format version with that family; consumers must match it exactly. The family
|
||||
keeps its historical NHD/HND spelling so ids stay stable for KV persisted
|
||||
before the layout enum existed.
|
||||
"""
|
||||
before the layout enum existed."""
|
||||
layout = KVCacheLayout[kv_cache_layout]
|
||||
legacy = {KVCacheLayout.LBNHC: "nhd", KVCacheLayout.LBHNC: "hnd"}
|
||||
family = legacy.get(layout, layout.name.lower())
|
||||
@@ -122,8 +121,7 @@ def _interleave_cp_tokens(
|
||||
ctx: _RankContext,
|
||||
) -> tuple[CopyRun, ...]:
|
||||
"""Place each region's num_tokens rows at their canonical token positions,
|
||||
one run per chunk of interleaved tokens.
|
||||
"""
|
||||
one run per chunk of interleaved tokens."""
|
||||
runs: list[CopyRun] = []
|
||||
for region in regions:
|
||||
if ctx.cp_size == 1:
|
||||
@@ -258,8 +256,7 @@ def _attention_byte_regions(
|
||||
cp_size: int,
|
||||
) -> list[ByteRegion] | None:
|
||||
"""Byte regions of an attention page, given this rank's head shard.
|
||||
None when the physical layout is not recognized (fail closed).
|
||||
"""
|
||||
None when the physical layout is not recognized (fail closed)."""
|
||||
bs, heads, head_size = spec.block_size, spec.num_kv_heads, spec.head_size
|
||||
if tuple(kv_cache.shape) == (num_blocks, heads, bs, 2 * head_size):
|
||||
return _packed_kv_regions(kv_cache, spec, head_shard, num_head_shards, cp_size)
|
||||
@@ -373,8 +370,7 @@ def _is_exact_partition(intervals: list[tuple[int, int]], size: int) -> bool:
|
||||
|
||||
def _verify_tiling(layer_name: str, per_rank: list[CanonicalPageMapping]) -> None:
|
||||
"""Whichever ranks a block elects as writers must tile the canonical page
|
||||
exactly once, and each rank's runs must cover exactly its local page.
|
||||
"""
|
||||
exactly once, and each rank's runs must cover exactly its local page."""
|
||||
size = per_rank[0].canonical_page_size_bytes
|
||||
num_writers = per_rank[0].num_writers
|
||||
for mapping in per_rank:
|
||||
|
||||
@@ -79,8 +79,7 @@ def get_offloading_event_group_spec(
|
||||
class _OffloadEventMetadata:
|
||||
"""BlockStored payload snapshot for one OffloadKey, captured while the
|
||||
Request is available and kept until the final matching removal event.
|
||||
``medium`` and ``ownership`` are forwarded from the OffloadingEvent.
|
||||
"""
|
||||
``medium`` and ``ownership`` are forwarded from the OffloadingEvent."""
|
||||
|
||||
# The chunk's constituent block hashes; the last one is the OffloadKey.
|
||||
block_hashes: tuple[BlockHash, ...]
|
||||
@@ -256,8 +255,7 @@ class OffloadingEventsTracker:
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Drop all tracked state; pending payloads are stale after a
|
||||
manager cache reset.
|
||||
"""
|
||||
manager cache reset."""
|
||||
self._pending_event_metadata.clear()
|
||||
|
||||
def _build_event_metadata(
|
||||
@@ -268,8 +266,7 @@ class OffloadingEventsTracker:
|
||||
) -> _OffloadEventMetadata:
|
||||
"""Build the payload snapshot for one offloaded chunk: its
|
||||
constituent per-block hashes, the whole chunk's tokens, and the
|
||||
per-block ``block_size``.
|
||||
"""
|
||||
per-block ``block_size``."""
|
||||
hashes_per_chunk = group_config.hashes_per_chunk
|
||||
assert hashes_per_chunk > 0
|
||||
assert chunk_idx >= 0
|
||||
|
||||
@@ -676,8 +676,7 @@ class OffloadingConnectorScheduler:
|
||||
start_chunk_idx: int,
|
||||
) -> int | None:
|
||||
"""Return the number of consecutive offloaded chunks from the start,
|
||||
or None if the backend deferred a lookup.
|
||||
"""
|
||||
or None if the backend deferred a lookup."""
|
||||
hit_count = 0
|
||||
defer_lookup = False
|
||||
for local_idx, key in enumerate(keys):
|
||||
@@ -712,8 +711,7 @@ class OffloadingConnectorScheduler:
|
||||
"""Return the end index (in `keys`) of the last run of
|
||||
`sliding_window_size` consecutive hits, scanning from the end.
|
||||
The first run may need a larger window for a partial rightmost chunk.
|
||||
Returns 0 on miss, None if the backend deferred a lookup.
|
||||
"""
|
||||
Returns 0 on miss, None if the backend deferred a lookup."""
|
||||
defer_lookup = False
|
||||
pending_in_window = False
|
||||
consecutive_hits = 0
|
||||
|
||||
@@ -59,8 +59,7 @@ def ensure_divisibility(numerator, denominator):
|
||||
|
||||
def divide(numerator, denominator):
|
||||
"""Ensure that numerator is divisible by the denominator and return
|
||||
the division value.
|
||||
"""
|
||||
the division value."""
|
||||
ensure_divisibility(numerator, denominator)
|
||||
return numerator // denominator
|
||||
|
||||
|
||||
@@ -141,8 +141,7 @@ class WeightTransferTrainerFactory:
|
||||
class_name: str | None = None,
|
||||
) -> None:
|
||||
"""Register a trainer engine. Same conventions as
|
||||
`WeightTransferEngineFactory.register_engine`.
|
||||
"""
|
||||
`WeightTransferEngineFactory.register_engine`."""
|
||||
if name in cls._registry:
|
||||
raise ValueError(
|
||||
f"Weight transfer trainer engine '{name}' is already registered."
|
||||
|
||||
@@ -40,8 +40,7 @@ class IPCWeightTransferInitInfo(WeightTransferInitInfo):
|
||||
`packed` is a must-agree wire param: the trainer ships it here at the init
|
||||
handshake so the worker decodes with the same setting the trainer encoded
|
||||
with. The consumer rebuilds from the IPC handle + `tensor_sizes`, so it does
|
||||
not need the buffer size (producer-only).
|
||||
"""
|
||||
not need the buffer size (producer-only)."""
|
||||
|
||||
packed: bool = False
|
||||
|
||||
@@ -54,8 +53,7 @@ class IPCTrainerInitInfo(TrainerInitInfo):
|
||||
|
||||
`packed` / `packed_buffer_size_bytes` are the transfer's wire params. The
|
||||
trainer propagates `packed` to the worker at `trainer_init` so the two sides
|
||||
cannot disagree. `backend` is the factory dispatch key.
|
||||
"""
|
||||
cannot disagree. `backend` is the factory dispatch key."""
|
||||
|
||||
backend: ClassVar[str] = "ipc"
|
||||
packed: bool = False
|
||||
|
||||
@@ -118,8 +118,7 @@ def worker_init_payload(init_info: NCCLWeightTransferInitInfo) -> dict:
|
||||
"""Serialize a worker init info for `init_weight_transfer_engine`, dropping
|
||||
the unset rendezvous field (the UID in TCP mode) so the wire payload carries
|
||||
only the mode actually in use. Shared by the dense and sparse trainer
|
||||
engines so the two cannot drift.
|
||||
"""
|
||||
engines so the two cannot drift."""
|
||||
return {key: value for key, value in asdict(init_info).items() if value is not None}
|
||||
|
||||
|
||||
|
||||
@@ -69,8 +69,7 @@ class NCCLTrainerInitInfo(TrainerInitInfo):
|
||||
propagates them to the worker at `trainer_init` so the two sides cannot
|
||||
disagree. Note this defaults to packed, unlike the worker-side
|
||||
`NCCLWeightTransferInitInfo`, whose default only applies when no trainer
|
||||
ships a value. `backend` is the factory dispatch key.
|
||||
"""
|
||||
ships a value. `backend` is the factory dispatch key."""
|
||||
|
||||
backend: ClassVar[str] = "nccl"
|
||||
|
||||
@@ -365,8 +364,7 @@ class NCCLTrainerWeightTransferEngine(TrainerWeightTransferEngine[NCCLTrainerIni
|
||||
def _broadcast(self, source: WeightSource, meta: list[ParamMeta]) -> None:
|
||||
"""Iterate the source (materializing each tensor — a collective on all
|
||||
ranks) and, on the sender, broadcast from rank 0, packed or one-by-one.
|
||||
Non-sender ranks only replay the iteration to stay in the collective.
|
||||
"""
|
||||
Non-sender ranks only replay the iteration to stay in the collective."""
|
||||
if not self.is_sender:
|
||||
for _ in source:
|
||||
pass
|
||||
|
||||
@@ -214,8 +214,7 @@ class RdtRouter:
|
||||
|
||||
def class_of(self, name: str) -> int:
|
||||
"""The name's owner class — the planner's bucketing key, since all names
|
||||
of a chunk must share one producer.
|
||||
"""
|
||||
of a chunk must share one producer."""
|
||||
return self._class_of.get(name, 0)
|
||||
|
||||
def owners(self, name: str) -> list[int]:
|
||||
@@ -286,8 +285,7 @@ class RdtRouter:
|
||||
def bind(self, actors: list, produce_methods: list, consumer_id: int) -> None:
|
||||
"""Attach this consumer's producer handles. Rebuilt wholesale per init,
|
||||
never appended to: every owner index is a position in these lists, so a
|
||||
rejoining engine that re-inits must not shift them.
|
||||
"""
|
||||
rejoining engine that re-inits must not shift them."""
|
||||
if len(actors) != len(produce_methods):
|
||||
raise ValueError("actors and produce_methods must be parallel")
|
||||
self._actors = list(actors)
|
||||
@@ -350,6 +348,5 @@ def buffer_alloc_bytes(nbytes: int, presize: int = 0) -> int:
|
||||
optional ``presize`` floor, and a coarse 256MB round-up, so the buffer is
|
||||
allocated ONCE and never regrows. Regrowth is a correctness hazard, not just a
|
||||
perf one -- see ``buffer_presize_gb``. Shared by the consumer's receive buffers
|
||||
and the producer's serve rings.
|
||||
"""
|
||||
and the producer's serve rings."""
|
||||
return max(nbytes, presize, -(-nbytes // (256 << 20)) * (256 << 20))
|
||||
|
||||
@@ -134,8 +134,7 @@ class _PendingPull:
|
||||
|
||||
``targets``/``blob`` must stay strongly referenced until it completes:
|
||||
``set_target_for_ref`` stores WEAKREFS, so dropping them silently reroutes the
|
||||
transfer into a fallback buffer.
|
||||
"""
|
||||
transfer into a fallback buffer."""
|
||||
|
||||
ref: "Any"
|
||||
keys: "list[FetchKey]"
|
||||
@@ -562,8 +561,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
|
||||
def _build_static_plan(self, init_info: ShardedRDTWeightTransferInitInfo) -> None:
|
||||
"""Build the chunk/free plan once. It never changes across syncs, so
|
||||
``update_weights`` needs no per-sync names.
|
||||
"""
|
||||
``update_weights`` needs no per-sync names."""
|
||||
if not init_info.group_lens:
|
||||
raise ValueError(
|
||||
"Sharded RDT engine requires init_info.group_lens (the gather-"
|
||||
@@ -587,8 +585,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
Both sides are sized from the static plan: receive buffers are
|
||||
``ring_depth`` slots at the largest chunk's ``pack_bytes``, and each bound
|
||||
producer is asked to pre-register a serve ring at the max bytes this
|
||||
consumer will pull from it. A no-op when this worker has no chunks.
|
||||
"""
|
||||
consumer will pull from it. A no-op when this worker has no chunks."""
|
||||
plan = self._cached_plan
|
||||
if plan is None or not plan.chunks:
|
||||
return
|
||||
@@ -633,8 +630,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
``data_parallel_index``, not ``data_parallel_rank``: vLLM resets the
|
||||
latter to 0 in a dense worker but keeps the former as the distinct global
|
||||
DP rank. Same formula as the sibling ``nccl_engine``, so dense-via-TP and
|
||||
MoE-via-DP+EP both yield distinct 0..C-1.
|
||||
"""
|
||||
MoE-via-DP+EP both yield distinct 0..C-1."""
|
||||
pc = self.parallel_config
|
||||
return pc.data_parallel_index * pc.world_size + pc.rank # world_size = TP*PP
|
||||
|
||||
@@ -642,16 +638,14 @@ class ShardedRDTWeightTransferEngine(
|
||||
"""Total inference-worker count. Prefers the driver-supplied
|
||||
``init_info.num_consumers`` (authoritative -- the driver knows the whole
|
||||
fleet); else ``world_size_across_dp``, the same stride
|
||||
``_global_worker_index`` indexes with, so the two agree at any pp.
|
||||
"""
|
||||
``_global_worker_index`` indexes with, so the two agree at any pp."""
|
||||
if self._num_consumers_override > 0:
|
||||
return self._num_consumers_override
|
||||
return self.parallel_config.world_size_across_dp
|
||||
|
||||
def start_weight_update(self) -> None:
|
||||
"""Put the model's params on meta so layerwise reload streams them in
|
||||
as each layer's slices land. Baked replay uses checkpoint format.
|
||||
"""
|
||||
as each layer's slices land. Baked replay uses checkpoint format."""
|
||||
from vllm.model_executor.model_loader.reload import (
|
||||
initialize_layerwise_reload,
|
||||
)
|
||||
@@ -660,8 +654,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
|
||||
def finish_weight_update(self) -> None:
|
||||
"""Drain the deferred pull/process pipeline (so every layer is fully
|
||||
loaded) before finalizing the layerwise reload.
|
||||
"""
|
||||
loaded) before finalizing the layerwise reload."""
|
||||
from vllm.model_executor.model_loader.reload import (
|
||||
finalize_layerwise_reload,
|
||||
)
|
||||
@@ -674,8 +667,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
device sync: post-processing is deferred to background threads and a
|
||||
sync here would block on them and serialize the pull/process pipeline.
|
||||
Completion is guaranteed by ``drain_pending`` in
|
||||
``finish_weight_update``.
|
||||
"""
|
||||
``finish_weight_update``."""
|
||||
self.receive_weights(self.parse_update_info(update_info))
|
||||
|
||||
def receive_weights(
|
||||
@@ -717,8 +709,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
device: torch.device,
|
||||
) -> list[tuple[str, torch.Tensor]]:
|
||||
"""Zero-storage lazies for ``names``, dtype/shape from the init metadata,
|
||||
all feeding the bake's recording sink.
|
||||
"""
|
||||
all feeding the bake's recording sink."""
|
||||
return [
|
||||
(
|
||||
name,
|
||||
@@ -986,8 +977,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
|
||||
def _ensure_proc_worker(self) -> None:
|
||||
"""Lazily create the per-slot events, the background CUDA stream, the work
|
||||
queue, and the single processing thread. Idempotent.
|
||||
"""
|
||||
queue, and the single processing thread. Idempotent."""
|
||||
if self._proc_thread is not None:
|
||||
return
|
||||
import queue
|
||||
@@ -1046,8 +1036,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
def _mark_slot_done(self, slot: int) -> None:
|
||||
"""Publish that a queued item's read-done event has been recorded (or the
|
||||
item failed) so a pull waiting to reuse ``slot`` can proceed to its
|
||||
CUDA-event synchronize.
|
||||
"""
|
||||
CUDA-event synchronize."""
|
||||
with self._slot_cv:
|
||||
self._slot_done[slot] += 1
|
||||
self._slot_cv.notify_all()
|
||||
@@ -1063,8 +1052,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
"""Block until the background thread has processed every queued item and
|
||||
its stream work is complete, then re-raise any error it hit. Called from
|
||||
the worker's ``finish_weight_update`` before ``finalize_layerwise_reload``
|
||||
so every baked layer is fully loaded (and ``info.reset()``-ed) first.
|
||||
"""
|
||||
so every baked layer is fully loaded (and ``info.reset()``-ed) first."""
|
||||
if self._proc_queue is not None:
|
||||
self._proc_queue.join() # every put() item task_done()'d
|
||||
# The scatter thread feeds the quant thread, so join it SECOND (all
|
||||
@@ -1116,8 +1104,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
which is exactly what an owner class is. The cut is a pure function of
|
||||
the bake and the ownership table. Copy order within a chunk is bake
|
||||
order, and a module's copies may span chunks (materialize/quant fire on
|
||||
its first/last chunk; see ``_build_call_plan``).
|
||||
"""
|
||||
its first/last chunk; see ``_build_call_plan``)."""
|
||||
assert self._router is not None
|
||||
by_class: dict[int, list[_Scatter]] = {}
|
||||
for copies in modules:
|
||||
@@ -1248,8 +1235,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
pulls nothing from. Refs are held and drained in ``drain_pending`` so
|
||||
every signal has EXECUTED before the sync ends: ``begin_sync`` resets
|
||||
the counters, and a straggler landing in the next sync would credit a
|
||||
group it does not belong to.
|
||||
"""
|
||||
group it does not belong to."""
|
||||
assert self._router is not None
|
||||
self._pending_frees.extend(self._router.free_group(group_idx))
|
||||
|
||||
@@ -1384,8 +1370,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
the modules' scatters via ``ready``; touches only the scattered params
|
||||
(never a receive slot), so it can overlap subsequent chunks' RDMA and
|
||||
scatters. ``info.reset()`` is what makes finalize skip the layer —
|
||||
drain_pending joins the quant queue before finalize runs.
|
||||
"""
|
||||
drain_pending joins the quant queue before finalize runs."""
|
||||
from vllm.model_executor.layers.quantization.base_config import (
|
||||
QuantizeMethodBase,
|
||||
)
|
||||
@@ -1418,8 +1403,7 @@ class ShardedRDTWeightTransferEngine(
|
||||
|
||||
def _quant_worker_loop(self) -> None:
|
||||
"""Dedicated quant thread: drains (completed_modules, scatter-done event)
|
||||
batches. Errors surface via _proc_error like the scatter thread's.
|
||||
"""
|
||||
batches. Errors surface via _proc_error like the scatter thread's."""
|
||||
torch.cuda.set_device(self.device)
|
||||
q = self._quant_queue
|
||||
assert q is not None
|
||||
|
||||
@@ -206,8 +206,7 @@ class FakeRDTTensor(torch.Tensor):
|
||||
|
||||
def _meta(self) -> torch.Tensor:
|
||||
"""A zero-storage meta tensor of this fake's shape/dtype, so PyTorch
|
||||
itself computes post-op geometry rather than us reimplementing it.
|
||||
"""
|
||||
itself computes post-op geometry rather than us reimplementing it."""
|
||||
return torch.empty(self.shape, dtype=self.dtype, device="meta")
|
||||
|
||||
@classmethod
|
||||
@@ -251,8 +250,7 @@ class FakeRDTTensor(torch.Tensor):
|
||||
):
|
||||
"""Append the op and return a child, or a tuple of children for
|
||||
multi-return ops. Each child's geometry comes from running the op on a
|
||||
meta tensor.
|
||||
"""
|
||||
meta tensor."""
|
||||
meta = self_._meta()
|
||||
with torch._C.DisableTorchFunctionSubclass():
|
||||
meta_result = func(meta, *args, **kwargs)
|
||||
|
||||
@@ -132,8 +132,7 @@ PRODUCE_METHOD_NAME = "rdt_produce_weights_batched"
|
||||
@dataclass
|
||||
class _SharedPack:
|
||||
"""One generation of one slot-sharing group: the rendezvous state for a
|
||||
single chunk, identified by the consumers' issue index.
|
||||
"""
|
||||
single chunk, identified by the consumers' issue index."""
|
||||
|
||||
group: int
|
||||
slot: int
|
||||
@@ -467,8 +466,7 @@ class _RDTProducerServer:
|
||||
|
||||
def end_sync(self) -> list[int]:
|
||||
"""Block until every published group has been freed by its consumers;
|
||||
return the remaining freed keys so the engine drops its last refs.
|
||||
"""
|
||||
return the remaining freed keys so the engine drops its last refs."""
|
||||
with self._cache_cond:
|
||||
self._wait_for(
|
||||
lambda: bool(self._inflight_groups),
|
||||
@@ -481,8 +479,7 @@ class _RDTProducerServer:
|
||||
|
||||
def set_gather_error(self, message: str) -> None:
|
||||
"""Record a trainer-side gather failure so blocked serves / publishes
|
||||
stop waiting and surface it.
|
||||
"""
|
||||
stop waiting and surface it."""
|
||||
with self._cache_cond:
|
||||
self._gather_error = RuntimeError(message)
|
||||
self._cache_cond.notify_all()
|
||||
@@ -511,8 +508,7 @@ class _RDTProducerServer:
|
||||
def _new_serve_buffer(self, nbytes: int) -> torch.Tensor:
|
||||
"""Allocate + NIXL-register one serve slot: the single allocation seam,
|
||||
so registration cannot be skipped on either of the two paths that make
|
||||
buffers (the init-time reservation and the serve-path backstop).
|
||||
"""
|
||||
buffers (the init-time reservation and the serve-path backstop)."""
|
||||
t = torch.empty(nbytes, dtype=torch.uint8, device=self._serve_device)
|
||||
with self._reg_lock:
|
||||
register_nixl_memory(t)
|
||||
@@ -584,15 +580,13 @@ class _RDTProducerServer:
|
||||
def _share_group(self, consumer_id: int) -> int:
|
||||
"""The slot-sharing group ``consumer_id`` belongs to: its index within
|
||||
its own deployment, since that is what fixes the plan. Without a width
|
||||
the group is the consumer itself and nothing is shared.
|
||||
"""
|
||||
the group is the consumer itself and nothing is shared."""
|
||||
return consumer_id % self._share_width if self._share_width > 0 else consumer_id
|
||||
|
||||
def _sharers_of(self, sg: int) -> frozenset:
|
||||
"""The LIVE consumers of group ``sg``: the rendezvous width. Derived from
|
||||
``begin_sync``'s live set, so a degraded sync narrows the barrier instead
|
||||
of waiting forever on a dead deployment. Caller holds ``_cache_cond``.
|
||||
"""
|
||||
of waiting forever on a dead deployment. Caller holds ``_cache_cond``."""
|
||||
cached = self._sharers.get(sg)
|
||||
if cached is None:
|
||||
if not self._sharing_active or self._live_ids is None:
|
||||
@@ -628,8 +622,7 @@ class _RDTProducerServer:
|
||||
def _await_shared_pack(self, gen: _SharedPack) -> torch.Tensor:
|
||||
"""Block until this generation's packer published its blob, and return
|
||||
it. A failed pack is re-raised here, so every sharer of a bad pack fails
|
||||
instead of reading a half-written slot.
|
||||
"""
|
||||
instead of reading a half-written slot."""
|
||||
with self._cache_cond:
|
||||
self._wait_for(
|
||||
lambda: not gen.done and gen.error is None,
|
||||
@@ -650,8 +643,7 @@ class _RDTProducerServer:
|
||||
"""Group ``sg``'s ring slot ``idx``, grown if this chunk outgrew the
|
||||
reservation. Growing registers memory while the fabric is busy, the
|
||||
hazard ``reserve_serve_buffer`` exists to avoid, so it is a backstop: the
|
||||
reservation is sized from the same static plan as this pack.
|
||||
"""
|
||||
reservation is sized from the same static plan as this pack."""
|
||||
with self._serve_lock:
|
||||
buffer = self._serve_rings.setdefault(sg, [None] * self._nring)[idx]
|
||||
if buffer is not None and buffer.numel() >= need:
|
||||
@@ -663,8 +655,7 @@ class _RDTProducerServer:
|
||||
|
||||
def _fail_shared_pack(self, gen: _SharedPack, exc: BaseException) -> None:
|
||||
"""Publish a pack failure so waiting sharers raise instead of hanging on
|
||||
a generation that will never complete.
|
||||
"""
|
||||
a generation that will never complete."""
|
||||
with self._cache_cond:
|
||||
gen.error = exc
|
||||
self._cache_cond.notify_all()
|
||||
@@ -866,8 +857,7 @@ class ShardedRDTTrainerWeightTransferEngine(
|
||||
def _rpc(self, method: str, *args: Any) -> Any:
|
||||
"""Call one of the server actor's methods and block for the result.
|
||||
The single seam through which the engine talks to its server, so tests
|
||||
can inject a local (non-Ray) fake server.
|
||||
"""
|
||||
can inject a local (non-Ray) fake server."""
|
||||
import ray
|
||||
|
||||
return ray.get(getattr(self._server, method).remote(*args))
|
||||
@@ -944,8 +934,7 @@ class ShardedRDTTrainerWeightTransferEngine(
|
||||
"""Fire publish_group WITHOUT waiting on the RPC (the gather loop
|
||||
overlaps the publish's server-side rebuild with the next group's
|
||||
gather) and return a handle that ``_await_publish`` resolves. Ray actor
|
||||
handle in production; a plain (non-Ray) fake server runs inline.
|
||||
"""
|
||||
handle in production; a plain (non-Ray) fake server runs inline."""
|
||||
method = self._server.publish_group
|
||||
remote = getattr(method, "remote", None)
|
||||
if remote is not None:
|
||||
@@ -956,8 +945,7 @@ class ShardedRDTTrainerWeightTransferEngine(
|
||||
"""Resolve one async publish so a server-side rebuild error surfaces at
|
||||
window depth instead of at end_sync. Publishes carry nothing back —
|
||||
freed groups flow only through wait_freed/end_sync (one channel; see
|
||||
publish_group).
|
||||
"""
|
||||
publish_group)."""
|
||||
import ray
|
||||
|
||||
if isinstance(ref, ray.ObjectRef):
|
||||
@@ -1144,8 +1132,7 @@ class ShardedRDTTrainerWeightTransferEngine(
|
||||
by stall watchdog 300s later: consumers route pulls here, the pull
|
||||
passes the served-names guard, and the cache wait never completes. With
|
||||
it, that is an immediate error naming the weight. One set lookup per
|
||||
name per sync.
|
||||
"""
|
||||
name per sync."""
|
||||
if self._held_names is None:
|
||||
return
|
||||
for name, tensor in zip(names, tensors):
|
||||
@@ -1346,8 +1333,7 @@ class ShardedRDTTrainerWeightTransferEngine(
|
||||
credit releases when every live consumer has signaled the group). So
|
||||
the loop self-paces to the consumers' pull rate with at most
|
||||
`gather_lookahead + 1` groups resident. Runs on every rank; only the
|
||||
sender has an `update_future` to fail fast on.
|
||||
"""
|
||||
sender has an `update_future` to fail fast on."""
|
||||
assert self.source is not None # guaranteed by trainer_init
|
||||
# The live IDS ride along with the count: the free barrier needs only
|
||||
# the count, but the slot-sharing rendezvous needs to know WHICH
|
||||
|
||||
@@ -68,8 +68,7 @@ class SparseNCCLTrainerInitInfo(TrainerInitInfo):
|
||||
|
||||
Same rendezvous shape as the dense NCCL backend (the sender opens its
|
||||
endpoint as NCCL rank 0), but with no packed wire params: sparse transfers
|
||||
are never packed. `backend` is the factory dispatch key.
|
||||
"""
|
||||
are never packed. `backend` is the factory dispatch key."""
|
||||
|
||||
backend: ClassVar[str] = "sparse_nccl"
|
||||
|
||||
@@ -368,8 +367,7 @@ class SparseNCCLTrainerWeightTransferEngine(
|
||||
rebuild or free the patch tensors as soon as a send method returns rather
|
||||
than relying on same-stream ordering. See
|
||||
`NCCLTrainerWeightTransferEngine._post_send_sync` for why there is no
|
||||
cross-rank barrier.
|
||||
"""
|
||||
cross-rank barrier."""
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.current_stream().synchronize()
|
||||
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
"""The CLI entrypoints of vLLM.
|
||||
|
||||
Note that all future modules must be lazily loaded within main
|
||||
to avoid certain eager import breakage.
|
||||
"""
|
||||
to avoid certain eager import breakage."""
|
||||
|
||||
import importlib.metadata
|
||||
import sys
|
||||
|
||||
@@ -295,8 +295,7 @@ class GenerateBaseServing(BaseServing, BeamSearchOnlineMixin):
|
||||
) -> _T:
|
||||
"""Wrap a `create_*` coroutine so that, if it raises or returns an
|
||||
ErrorResponse (i.e. the request never reached the engine), the KV
|
||||
connector is notified to free any pinned remote-prefill blocks.
|
||||
"""
|
||||
connector is notified to free any pinned remote-prefill blocks."""
|
||||
kv_transfer_params = self.has_kv_connector and request.kv_transfer_params
|
||||
if not kv_transfer_params or not kv_transfer_params.get("do_remote_prefill"):
|
||||
return await awaitable
|
||||
|
||||
@@ -123,8 +123,7 @@ class OpenAIServingModels:
|
||||
|
||||
async def init_static_loras(self):
|
||||
"""Loads all static LoRA modules.
|
||||
Raises if any fail to load
|
||||
"""
|
||||
Raises if any fail to load"""
|
||||
if self.static_lora_modules is None:
|
||||
return
|
||||
for lora in self.static_lora_modules:
|
||||
@@ -149,8 +148,7 @@ class OpenAIServingModels:
|
||||
|
||||
async def show_available_models(self) -> ModelList:
|
||||
"""Show available models. This includes the base model and all
|
||||
adapters.
|
||||
"""
|
||||
adapters."""
|
||||
model_list = await self.registry.show_available_models()
|
||||
lora_cards = [
|
||||
ModelCard(
|
||||
|
||||
@@ -408,8 +408,7 @@ class ParsableContext(ConversationContext):
|
||||
|
||||
def need_builtin_tool_call(self) -> bool:
|
||||
"""Return true if the last message is a builtin tool call
|
||||
that the request has enabled.
|
||||
"""
|
||||
that the request has enabled."""
|
||||
last_message = self.response_messages[-1]
|
||||
if last_message.type != "function_call":
|
||||
return False
|
||||
|
||||
@@ -52,8 +52,7 @@ logger = init_logger(__name__)
|
||||
|
||||
def _parse_harmony_format_message(chat_msg: dict) -> Message:
|
||||
"""Reconstruct a Message from Harmony-format dict,
|
||||
preserving channel, recipient, and content_type.
|
||||
"""
|
||||
preserving channel, recipient, and content_type."""
|
||||
author_dict = chat_msg["author"]
|
||||
role = author_dict.get("role")
|
||||
name = author_dict.get("name")
|
||||
|
||||
@@ -117,8 +117,7 @@ def serialize_messages(msgs):
|
||||
|
||||
class ResponseRawMessageAndToken(OpenAIBaseModel):
|
||||
"""Class to show the raw message.
|
||||
If message / tokens diverge, tokens is the source of truth
|
||||
"""
|
||||
If message / tokens diverge, tokens is the source of truth"""
|
||||
|
||||
message: str
|
||||
tokens: list[int]
|
||||
|
||||
@@ -44,8 +44,7 @@ class PluginWithoutIOProcessorPlugins(PoolingIOProcessor):
|
||||
|
||||
class PluginWithIOProcessorPlugins(PoolingIOProcessor):
|
||||
"""IO Processor plugins are a feature that allows pre- and post-processing
|
||||
of the model input and output for pooling models.
|
||||
"""
|
||||
of the model input and output for pooling models."""
|
||||
|
||||
name = "plugin"
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Encode/decode utilities for multimodal tensors and field metadata
|
||||
over JSON/HTTP, used by the disaggregated generate endpoint.
|
||||
"""
|
||||
over JSON/HTTP, used by the disaggregated generate endpoint."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -126,8 +126,7 @@ def _format_error(err: object) -> str:
|
||||
|
||||
def _is_internal_loc_segment(segment: str) -> bool:
|
||||
"""True if `segment` is a Pydantic-internal wrapper/union-branch
|
||||
marker rather than a user-meaningful field name or list index.
|
||||
"""
|
||||
marker rather than a user-meaningful field name or list index."""
|
||||
if _BRACKETED_INTERNAL_RE.search(segment):
|
||||
return True
|
||||
return segment.lower() in _INTERNAL_LOC_MARKERS
|
||||
|
||||
@@ -63,8 +63,7 @@ def _attach_router(app: FastAPI):
|
||||
@router.post("/v1/load_lora_adapter", dependencies=[Depends(validate_json_request)])
|
||||
async def load_lora_adapter(request: LoadLoRAAdapterRequest, raw_request: Request):
|
||||
"""Handle POST /v1/load_lora_adapter: load a LoRA adapter into the
|
||||
serving engine.
|
||||
"""
|
||||
serving engine."""
|
||||
handler: OpenAIServingModels = models(raw_request)
|
||||
response = await handler.load_lora_adapter(request)
|
||||
if isinstance(response, ErrorResponse):
|
||||
@@ -86,8 +85,7 @@ def _attach_router(app: FastAPI):
|
||||
request: UnloadLoRAAdapterRequest, raw_request: Request
|
||||
):
|
||||
"""Handle POST /v1/unload_lora_adapter: unload a LoRA adapter from
|
||||
the serving engine.
|
||||
"""
|
||||
the serving engine."""
|
||||
handler: OpenAIServingModels = models(raw_request)
|
||||
response = await handler.unload_lora_adapter(request)
|
||||
if isinstance(response, ErrorResponse):
|
||||
|
||||
@@ -30,8 +30,7 @@ EndpointFn = Callable[[RequestType, Request], Awaitable[Any]]
|
||||
def _snapshot_handler_levels() -> list[tuple[logging.Handler, int]]:
|
||||
"""Snapshot handler levels for loggers that may be affected by third-party
|
||||
logging configuration side effects (e.g. model_hosting_container_standards
|
||||
calling configure_root_logger() at import time).
|
||||
"""
|
||||
calling configure_root_logger() at import time)."""
|
||||
loggers = [logging.getLogger(), logging.getLogger("vllm")]
|
||||
seen: set[int] = set()
|
||||
snapshot: list[tuple[logging.Handler, int]] = []
|
||||
@@ -74,8 +73,7 @@ def _attach_router(
|
||||
model_config: ModelConfig | None = None,
|
||||
):
|
||||
"""Register the SageMaker hosting routes (/ping, /invocations) on the
|
||||
app.
|
||||
"""
|
||||
app."""
|
||||
import model_hosting_container_standards.sagemaker as sagemaker_standards
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -33,8 +33,7 @@ def set_default_fingerprint_mode(
|
||||
custom_value: str | None = None,
|
||||
) -> None:
|
||||
"""Configure the fingerprint mode for subsequent ``get_system_fingerprint``
|
||||
calls. Called once at server startup.
|
||||
"""
|
||||
calls. Called once at server startup."""
|
||||
global _DEFAULT_MODE, _CUSTOM_VALUE
|
||||
_DEFAULT_MODE = mode
|
||||
_CUSTOM_VALUE = custom_value
|
||||
@@ -42,8 +41,7 @@ def set_default_fingerprint_mode(
|
||||
|
||||
def get_system_fingerprint(vllm_config: Any) -> str | None:
|
||||
"""Return the fingerprint for ``vllm_config`` using the mode configured by
|
||||
``set_default_fingerprint_mode``.
|
||||
"""
|
||||
``set_default_fingerprint_mode``."""
|
||||
return build_system_fingerprint(vllm_config, _DEFAULT_MODE, _CUSTOM_VALUE)
|
||||
|
||||
|
||||
|
||||
@@ -92,8 +92,7 @@ def asr_inter_chunk_separator(
|
||||
|
||||
class SpeechToTextBaseServing(GenerateBaseServing):
|
||||
"""Base class for speech-to-text operations like transcription and
|
||||
translation.
|
||||
"""
|
||||
translation."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -427,8 +426,7 @@ class SpeechToTextBaseServing(GenerateBaseServing):
|
||||
stream_generator_method: Callable[..., AsyncGenerator[str, None]],
|
||||
) -> T | V | AsyncGenerator[str, None] | ErrorResponse:
|
||||
"""Base method for speech-to-text operations like transcription and
|
||||
translation.
|
||||
"""
|
||||
translation."""
|
||||
if request.stream and request.use_beam_search:
|
||||
return self.create_error_response(
|
||||
"Streaming is not currently supported with beam search"
|
||||
|
||||
@@ -581,8 +581,7 @@ _constrain_to_fx_strides_patched = False
|
||||
def _apply_constrain_to_fx_strides_patch():
|
||||
"""Patch lowering.constrain_to_fx_strides globally. Safe to call
|
||||
multiple times; only the first call does anything.
|
||||
Only applies for torch >= 2.11 and < 2.12.
|
||||
"""
|
||||
Only applies for torch >= 2.11 and < 2.12."""
|
||||
global _constrain_to_fx_strides_patched
|
||||
if _constrain_to_fx_strides_patched:
|
||||
return
|
||||
|
||||
+1
-2
@@ -2249,8 +2249,7 @@ def compile_factors() -> dict[str, object]:
|
||||
"""Return env vars used for torch.compile cache keys.
|
||||
|
||||
Start with every known vLLM env var; drop entries in `ignored_factors`;
|
||||
hash everything else. This keeps the cache key aligned across workers.
|
||||
"""
|
||||
hash everything else. This keeps the cache key aligned across workers."""
|
||||
ignored_factors: set[str] = {
|
||||
"MAX_JOBS",
|
||||
"VLLM_RPC_BASE_PATH",
|
||||
|
||||
@@ -209,8 +209,7 @@ def is_forward_context_available() -> bool:
|
||||
|
||||
def in_piecewise_cudagraph() -> bool:
|
||||
"""Whether the current forward runs in piecewise cudagraph mode (graph
|
||||
segments separated by eager breaks), at capture or replay time.
|
||||
"""
|
||||
segments separated by eager breaks), at capture or replay time."""
|
||||
return (
|
||||
is_forward_context_available()
|
||||
and get_forward_context().cudagraph_runtime_mode == CUDAGraphMode.PIECEWISE
|
||||
|
||||
+1
-2
@@ -216,8 +216,7 @@ def _configure_vllm_root_logger() -> None:
|
||||
def init_logger(name: str) -> _VllmLogger:
|
||||
"""The main purpose of this function is to ensure that loggers are
|
||||
retrieved in such a way that we can be sure the root vllm logger has
|
||||
already been configured.
|
||||
"""
|
||||
already been configured."""
|
||||
logger = logging.getLogger(name)
|
||||
|
||||
for method_name, method in _METHODS_TO_PATCH.items():
|
||||
|
||||
@@ -733,8 +733,7 @@ class MergedColumnParallelLinearVariableSliceWithLoRA(
|
||||
lora_b: torch.Tensor | list[torch.Tensor],
|
||||
):
|
||||
"""Override to handle single tensor weights
|
||||
that need to be split into slices.
|
||||
"""
|
||||
that need to be split into slices."""
|
||||
self.reset_lora(index)
|
||||
|
||||
# Handle case where checkpoint has single tensor weights
|
||||
|
||||
@@ -90,8 +90,7 @@ class LoRAModel:
|
||||
def clone(self, lora_model_id: int) -> "LoRAModel":
|
||||
"""Return a copy of the object with different ids.
|
||||
|
||||
Will share the underlying tensors.
|
||||
"""
|
||||
Will share the underlying tensors."""
|
||||
return self.__class__(
|
||||
lora_model_id,
|
||||
rank=self.rank,
|
||||
|
||||
@@ -28,8 +28,7 @@ class WorkerLoRAManager:
|
||||
"""WorkerLoRAManager that manages LoRA models on the worker side.
|
||||
|
||||
Every request, the requested LoRAs will be loaded (unless they are already
|
||||
loaded), and every other LoRA will be unloaded.
|
||||
"""
|
||||
loaded), and every other LoRA will be unloaded."""
|
||||
|
||||
_manager_cls: type[LoRAModelManager] = LoRAModelManager
|
||||
|
||||
@@ -75,8 +74,7 @@ class WorkerLoRAManager:
|
||||
@contextmanager
|
||||
def dummy_lora_cache(self):
|
||||
"""Use this context manager to reuse the dummy lora model
|
||||
to avoid creating it repeatedly.
|
||||
"""
|
||||
to avoid creating it repeatedly."""
|
||||
self._cached_dummy_lora = None
|
||||
yield
|
||||
self._cached_dummy_lora = False
|
||||
@@ -251,8 +249,7 @@ class LRUCacheWorkerLoRAManager(WorkerLoRAManager):
|
||||
|
||||
Uses an LRU Cache. Every request, the requested LoRAs will be loaded
|
||||
(unless they are already loaded) and least recently used LoRAs will
|
||||
be unloaded if the cache is above capacity.
|
||||
"""
|
||||
be unloaded if the cache is above capacity."""
|
||||
|
||||
_manager_cls: type[LRUCacheLoRAModelManager] = LRUCacheLoRAModelManager
|
||||
|
||||
|
||||
@@ -135,8 +135,7 @@ class CustomOp(nn.Module):
|
||||
|
||||
def forward_native(self, *args, **kwargs):
|
||||
"""PyTorch-native implementation; OOT plugins override via
|
||||
:meth:`forward_oot`.
|
||||
"""
|
||||
:meth:`forward_oot`."""
|
||||
raise NotImplementedError
|
||||
|
||||
def forward_oot(self, *args, **kwargs):
|
||||
|
||||
@@ -10,8 +10,7 @@ from vllm.model_executor.hw_agnostic.custom_op import CustomOp
|
||||
@CustomOp.register("rms_norm")
|
||||
class RMSNorm(CustomOp):
|
||||
"""``x -> w * x / sqrt(E[x^2] + eps)``. With ``residual``, fuses
|
||||
``residual += x`` then RMSNorm and returns ``(normalized, residual)``.
|
||||
"""
|
||||
``residual += x`` then RMSNorm and returns ``(normalized, residual)``."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -881,8 +881,7 @@ def choose_mp_linear_kernel(
|
||||
|
||||
def init_mxfp8_linear_kernel(*, bmm_batch_size: int | None = None) -> Mxfp8LinearKernel:
|
||||
"""Select and instantiate the best MXFP8 linear kernel for the
|
||||
current platform.
|
||||
"""
|
||||
current platform."""
|
||||
config = Mxfp8LinearLayerConfig(bmm_batch_size=bmm_batch_size)
|
||||
|
||||
platform = current_platform._enum
|
||||
@@ -934,8 +933,7 @@ def init_mxfp4_linear_kernel(
|
||||
activation_quant_key: QuantKey | None = None,
|
||||
) -> MxFp4LinearKernel:
|
||||
"""Select and instantiate the best MXFP4 linear kernel for the
|
||||
current platform.
|
||||
"""
|
||||
current platform."""
|
||||
config = MxFp4LinearLayerConfig(
|
||||
activation_quant_key=activation_quant_key,
|
||||
)
|
||||
@@ -982,8 +980,7 @@ def init_mxfp6_linear_kernel(
|
||||
activation_quant_key: QuantKey | None = None,
|
||||
) -> MxFp6LinearKernel:
|
||||
"""Select and instantiate the best MXFP6 linear kernel for the
|
||||
current platform.
|
||||
"""
|
||||
current platform."""
|
||||
config = MxFp6LinearLayerConfig(
|
||||
weight_quant_key=weight_quant_key,
|
||||
activation_quant_key=activation_quant_key,
|
||||
@@ -1071,8 +1068,7 @@ def init_wfp8_a16_linear_kernel(
|
||||
|
||||
def init_nvfp4_linear_kernel(use_a16: bool = False) -> NvFp4LinearKernel:
|
||||
"""Select and instantiate the best NVFP4 linear kernel for the
|
||||
current platform.
|
||||
"""
|
||||
current platform."""
|
||||
config = NvFp4LinearLayerConfig()
|
||||
a16_kernels = (
|
||||
FlashInferCuteDslNvFp4W4A16LinearKernel,
|
||||
|
||||
@@ -177,8 +177,7 @@ class FlashInferCutlassNvFp4LinearKernel(NvFp4LinearKernel):
|
||||
|
||||
def input_quant_key(self) -> QuantKey | None:
|
||||
"""This kernel supports dynamic quantization of the input. By
|
||||
convention, pre-quantized blockscales must use the swizzled layout.
|
||||
"""
|
||||
convention, pre-quantized blockscales must use the swizzled layout."""
|
||||
return kNvfp4Dynamic
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -41,8 +41,7 @@ class FP8BlockParams(FP8Params):
|
||||
@property
|
||||
def block_scale_attr(self) -> str:
|
||||
"""Fp8LinearMethod registers the block scale as ``weight_scale_inv``,
|
||||
compressed-tensors as ``weight_scale``.
|
||||
"""
|
||||
compressed-tensors as ``weight_scale``."""
|
||||
return (
|
||||
self.WEIGHT_SCALE
|
||||
if self.weight_scale_inv is None
|
||||
|
||||
@@ -174,8 +174,7 @@ class CutlassFP8ScaledMMLinearKernel(FP8ScaledMMLinearKernel):
|
||||
|
||||
def input_quant_key(self) -> QuantKey | None:
|
||||
"""Only static per-tensor activation quantization is supported for external
|
||||
quantization.
|
||||
"""
|
||||
quantization."""
|
||||
if self.config.activation_quant_key == kFp8StaticTensorSym:
|
||||
return kFp8StaticTensorSym
|
||||
return None
|
||||
@@ -185,8 +184,7 @@ class CutlassFP8ScaledMMLinearKernel(FP8ScaledMMLinearKernel):
|
||||
x: torch.Tensor, dim: int, alignment: int, value: float = 0.0
|
||||
) -> torch.Tensor:
|
||||
"""Pad tensor ``x`` along ``dim`` to the next multiple of
|
||||
``alignment``.
|
||||
"""
|
||||
``alignment``."""
|
||||
remainder = x.shape[dim] % alignment
|
||||
if remainder == 0:
|
||||
return x
|
||||
|
||||
@@ -804,8 +804,7 @@ _ACTIVATION_REGISTRY = LazyDict(
|
||||
|
||||
def _get_gelu_pytorch_tanh() -> nn.Module:
|
||||
"""Get PyTorch GELU with tanh approximation, with ROCm fallback
|
||||
and fast GELU for ARM.
|
||||
"""
|
||||
and fast GELU for ARM."""
|
||||
if current_platform.is_rocm():
|
||||
# TODO:[ROCm] PyTorch native GELU with tanh is unstable with torch.compile
|
||||
logger.warning_once(
|
||||
|
||||
@@ -1568,8 +1568,7 @@ class MLACommonBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: "AttentionSpec") -> "AttentionSpec":
|
||||
"""Per-token-head modes pack an inline fp32 scale pair after the
|
||||
latent data (single-sided: ``head_size_v == 0`` for MLA).
|
||||
"""
|
||||
latent data (single-sided: ``head_size_v == 0`` for MLA)."""
|
||||
spec = super().customize_spec(spec)
|
||||
mode = spec.kv_quant_mode
|
||||
if spec.state_content_bytes is not None or not mode.is_per_token_head:
|
||||
|
||||
@@ -55,8 +55,7 @@ _FI_SUPPORTED_DTYPES = (torch.bfloat16, torch.float16)
|
||||
|
||||
def _max_token_num(tp_size: int, hidden_size: int, dtype: torch.dtype) -> int | None:
|
||||
"""Workspace token budget for flashinfer fused all-reduce, or None if the
|
||||
current world size / device is unsupported. Mirrors ``FlashInferAllReduce``.
|
||||
"""
|
||||
current world size / device is unsupported. Mirrors ``FlashInferAllReduce``."""
|
||||
from vllm.config.compilation import PassConfig
|
||||
|
||||
max_size_mb = PassConfig.default_fi_allreduce_fusion_max_size_mb().get(tp_size)
|
||||
|
||||
@@ -170,8 +170,7 @@ def _fused_embed_eh_norm_kernel(
|
||||
``table[ids]``, zero it at position 0, RMSNorm(embed) with enorm and
|
||||
RMSNorm(prev_hidden) with hnorm, written side-by-side into ``out`` ([N, 2H])
|
||||
ready for the eh_proj GEMM. Replaces embedding lookup + where + 2x RMSNorm +
|
||||
cat. Requires the full table on-rank (replicated embedding).
|
||||
"""
|
||||
cat. Requires the full table on-rank (replicated embedding)."""
|
||||
tok = tl.program_id(0)
|
||||
off = tl.arange(0, BLOCK)
|
||||
mask = off < H
|
||||
|
||||
@@ -56,8 +56,7 @@ class MoEActivation(Enum):
|
||||
@property
|
||||
def custom_op_name(self) -> str:
|
||||
"""Maps to the CustomOp name of activations
|
||||
in vllm/model_executor/layers/activation.py.
|
||||
"""
|
||||
in vllm/model_executor/layers/activation.py."""
|
||||
return _CUSTOM_OP_NAMES[self]
|
||||
|
||||
def without_mul(self) -> "MoEActivation":
|
||||
|
||||
@@ -36,8 +36,7 @@ def is_aiter_mxfp8_moe_available() -> bool:
|
||||
nightly lacking #3811 would wrongly select FlyDSL instead of falling back to
|
||||
the native Triton dot_scaled path. #3811 added no probe-able public symbol,
|
||||
so detect the ``minimax_m3_mxfp8`` tuned config it shipped. Every check fails
|
||||
closed (returns False -> triton dot_scaled), which is always safe.
|
||||
"""
|
||||
closed (returns False -> triton dot_scaled), which is always safe."""
|
||||
if not (current_platform.is_rocm() and current_platform.supports_mx()):
|
||||
return False
|
||||
try:
|
||||
|
||||
@@ -192,8 +192,7 @@ class CPUUnquantizedExperts(mk.FusedMoEExpertsModular):
|
||||
|
||||
def _pad_moe_intermediate(self, layer: torch.nn.Module) -> None:
|
||||
"""Zero-pad the per-partition MoE intermediate dim of both weights and
|
||||
the expert bias, see `_padded_intermediate_size`.
|
||||
"""
|
||||
the expert bias, see `_padded_intermediate_size`."""
|
||||
intermediate_size = self.moe_config.intermediate_size_per_partition
|
||||
padded_size = self._padded_intermediate_size(self.moe_config)
|
||||
if padded_size == intermediate_size:
|
||||
@@ -953,8 +952,7 @@ class CPUExpertsInt4(mk.FusedMoEExpertsModular):
|
||||
|
||||
class CPUExpertsInt8(mk.FusedMoEExpertsModular):
|
||||
"""CPU INT8 W8A8 per-channel weight / dynamic per-token activation
|
||||
modular MoE experts.
|
||||
"""
|
||||
modular MoE experts."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -1287,8 +1285,7 @@ class ArmCPUExpertsInt8(mk.FusedMoEExpertsModular):
|
||||
|
||||
class ZenCPUExpertsInt8(mk.FusedMoEExpertsModular):
|
||||
"""AMD Zen INT8 MoE with per-token activation and channelwise weight
|
||||
quantization, dispatched through zentorch.
|
||||
"""
|
||||
quantization, dispatched through zentorch."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -34,8 +34,7 @@ from vllm.triton_utils import tl, triton
|
||||
|
||||
def _select_cfg(M, N, K, block_m):
|
||||
"""Pick the launch config from host constants only (M=num_valid_tokens, N, K,
|
||||
block_m) — graph-capture safe (no GPU-scalar branch).
|
||||
"""
|
||||
block_m) — graph-capture safe (no GPU-scalar branch)."""
|
||||
# Per-regime winners (measured, isolated cuda-event A/B on gfx950, GPU 3):
|
||||
# BLOCK_K=256 (fewer K-iters + bigger MX scale-load coalesced with the dot),
|
||||
# num_stages=2 (software-pipeline overlaps the E8M0 scale-load with the scaled
|
||||
|
||||
@@ -55,28 +55,24 @@ class MoEKernelOracle(ABC, Generic[BackendT]):
|
||||
@abstractmethod
|
||||
def backend_enum_cls(self) -> type[BackendT]:
|
||||
"""Return the concrete `Enum` class enumerating this oracle's
|
||||
backends (e.g. `UnquantizedMoeBackend`, `Fp8MoeBackend`).
|
||||
"""
|
||||
backends (e.g. `UnquantizedMoeBackend`, `Fp8MoeBackend`)."""
|
||||
|
||||
@abstractmethod
|
||||
def get_priority_backends(self, moe_config: FusedMoEConfig) -> list[BackendT]:
|
||||
"""Return platform-appropriate backends in priority order for
|
||||
this `moe_config`.
|
||||
"""
|
||||
this `moe_config`."""
|
||||
|
||||
@abstractmethod
|
||||
def backend_to_kernel_cls(
|
||||
self, backend: BackendT
|
||||
) -> list[type[mk.FusedMoEExperts]]:
|
||||
"""Map a backend enum value to its concrete `FusedMoEExperts`
|
||||
subclasses, in selection priority order.
|
||||
"""
|
||||
subclasses, in selection priority order."""
|
||||
|
||||
@abstractmethod
|
||||
def map_backend(self, runner_backend: MoEBackend) -> BackendT:
|
||||
"""Map a user-facing `MoEBackend` (from the runner config) to
|
||||
this oracle's enum.
|
||||
"""
|
||||
this oracle's enum."""
|
||||
|
||||
@abstractmethod
|
||||
def select_backend(
|
||||
@@ -108,8 +104,7 @@ class MoEKernelOracle(ABC, Generic[BackendT]):
|
||||
routing_tables: tuple[torch.Tensor, torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> mk.FusedMoEKernel:
|
||||
"""Construct the `FusedMoEKernel` (Prepare/Finalize + Experts
|
||||
combinator) for the chosen backend.
|
||||
"""
|
||||
combinator) for the chosen backend."""
|
||||
|
||||
def convert_to_kernel_format(
|
||||
self,
|
||||
|
||||
@@ -451,8 +451,7 @@ def _humming_fp8_weight_schema(
|
||||
layer: RoutedExperts, weight: torch.Tensor, weight_scale: torch.Tensor
|
||||
) -> dict[str, Any]:
|
||||
"""Build the humming weight schema from the canonical on-device fp8/mxfp8
|
||||
tensors (scale dtype/shape, block size), not the producing quant method.
|
||||
"""
|
||||
tensors (scale dtype/shape, block size), not the producing quant method."""
|
||||
# mxfp8: e8m0 group-32 scales (stored as uint8 bytes or e8m0). humming has
|
||||
# no compressed-tensors mxfp8 loader; its modelopt schema fits both sources.
|
||||
if weight_scale.dtype in (torch.uint8, torch.float8_e8m0fnu):
|
||||
|
||||
@@ -224,8 +224,7 @@ def _humming_int8_weight_schema(
|
||||
weight: torch.Tensor, weight_scale: torch.Tensor
|
||||
) -> dict[str, Any]:
|
||||
"""Build the humming compressed-tensors int8 schema from the canonical
|
||||
on-device tensors; humming does the signed-int8 -> native conversion.
|
||||
"""
|
||||
on-device tensors; humming does the signed-int8 -> native conversion."""
|
||||
config: dict[str, Any] = {
|
||||
"quant_method": "compressed-tensors",
|
||||
"format": "int-quantized",
|
||||
|
||||
@@ -512,8 +512,7 @@ def _process_weights_flashinfer(
|
||||
|
||||
def _pad_w13_shard_cols(x: torch.Tensor, unit: int, padded_unit: int) -> torch.Tensor:
|
||||
"""Zero-pad each of the two gate/up shards of a ``(E, rows, 2 * unit)``
|
||||
tensor along its last dim, from ``unit`` to ``padded_unit`` columns.
|
||||
"""
|
||||
tensor along its last dim, from ``unit`` to ``padded_unit`` columns."""
|
||||
if padded_unit == unit:
|
||||
return x
|
||||
e, rows, _ = x.shape
|
||||
@@ -1081,8 +1080,7 @@ def _humming_wna16_weight_schema(
|
||||
quant_config: QuantizationConfig | QuantizationArgs | None,
|
||||
) -> dict[str, Any]:
|
||||
"""Humming weight schema for a WNA16 checkpoint, derived from the quant
|
||||
config rather than the running kernel.
|
||||
"""
|
||||
config rather than the running kernel."""
|
||||
from vllm.model_executor.layers.quantization.auto_awq import AutoAWQConfig
|
||||
from vllm.model_executor.layers.quantization.auto_gptq import AutoGPTQConfig
|
||||
|
||||
|
||||
@@ -331,8 +331,7 @@ def map_mxfp4_backend(runner_backend: MoEBackend) -> list[Mxfp4MoeBackend]:
|
||||
|
||||
def _get_priority_backends_for_gpt_oss() -> list[Mxfp4MoeBackend]:
|
||||
"""Available backends in priority order, BF16-act variant before
|
||||
activation-quantized variant within each vendor family.
|
||||
"""
|
||||
activation-quantized variant within each vendor family."""
|
||||
_AVAILABLE_BACKENDS = [
|
||||
Mxfp4MoeBackend.FLASHINFER_TRTLLM_MXFP4_BF16,
|
||||
Mxfp4MoeBackend.FLASHINFER_TRTLLM_MXFP4_MXFP8,
|
||||
@@ -411,8 +410,7 @@ def _resolve_activation_key(
|
||||
model_activation_key: QuantKey | None,
|
||||
) -> QuantKey | None:
|
||||
"""Combine the model-supplied activation key with the user override.
|
||||
Raises on conflict (both set and disagreeing).
|
||||
"""
|
||||
Raises on conflict (both set and disagreeing)."""
|
||||
user_override = _user_moe_activation_override()
|
||||
if user_override is None:
|
||||
return model_activation_key
|
||||
@@ -462,8 +460,7 @@ def _filter_by_activation(
|
||||
) -> list[Mxfp4MoeBackend]:
|
||||
"""Pick variants matching ``requested_activation_key``; without one,
|
||||
prefer BF16 if the list has any, else keep the list as-is so explicit
|
||||
non-BF16 picks (e.g. the ``_afp8`` aliases) still land.
|
||||
"""
|
||||
non-BF16 picks (e.g. the ``_afp8`` aliases) still land."""
|
||||
if requested_activation_key is not None:
|
||||
return [
|
||||
b
|
||||
|
||||
@@ -71,8 +71,7 @@ class ZeroExpertRouter(BaseRouter):
|
||||
input_ids: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Compute routing with full bias, compute zero expert output,
|
||||
mask zero expert IDs.
|
||||
"""
|
||||
mask zero expert IDs."""
|
||||
topk_weights, topk_ids = fused_topk_bias(
|
||||
hidden_states=hidden_states,
|
||||
gating_output=router_logits,
|
||||
|
||||
@@ -163,8 +163,7 @@ class SparseIndexerTopk(torch.nn.Module):
|
||||
) -> str:
|
||||
"""Resolve the decode top-k implementation from the configured
|
||||
backend ("auto" = the pre-existing chain, or a validated explicit
|
||||
value).
|
||||
"""
|
||||
value)."""
|
||||
if self._backend == "auto":
|
||||
return self._resolve_auto(logits, topk_tokens, num_rows)
|
||||
|
||||
@@ -211,8 +210,7 @@ class SparseIndexerTopk(torch.nn.Module):
|
||||
self, logits: torch.Tensor, topk_tokens: int, num_rows: int
|
||||
) -> str:
|
||||
"""The pre-existing priority chain: cooperative -> persistent ->
|
||||
per_row. deep_select/flashinfer/torch are opt-in only.
|
||||
"""
|
||||
per_row. deep_select/flashinfer/torch are opt-in only."""
|
||||
if not self._cooperative_constraints(logits, topk_tokens, num_rows):
|
||||
return "cooperative"
|
||||
if self._is_cuda and topk_tokens in (512, 1024, 2048):
|
||||
@@ -274,8 +272,7 @@ class SparseIndexerTopk(torch.nn.Module):
|
||||
max_seq_len: int,
|
||||
) -> None:
|
||||
"""Run the resolved decode top-k implementation, writing into
|
||||
topk_indices (int32, -1 fill for rows shorter than topk_tokens).
|
||||
"""
|
||||
topk_indices (int32, -1 fill for rows shorter than topk_tokens)."""
|
||||
backend = self.resolve_backend(logits, topk_tokens, logits.shape[0])
|
||||
if backend == "deep_select":
|
||||
row_ends = self._row_ends(seq_lens, next_n, logits.shape[0])
|
||||
|
||||
@@ -158,8 +158,7 @@ class LinearMethodBase(QuantizeMethodBase):
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Apply the weights in layer to the input tensor.
|
||||
Expects create_weights to have been called before on the layer.
|
||||
"""
|
||||
Expects create_weights to have been called before on the layer."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
|
||||
@@ -861,8 +861,7 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""ROCm forward using AITER Triton fused projection+attention when
|
||||
available, otherwise falling back to the generic CUDA path.
|
||||
"""
|
||||
available, otherwise falling back to the generic CUDA path."""
|
||||
if GDN_AITER_TRITON_AVAILABLE:
|
||||
num_tokens = hidden_states.size(0)
|
||||
projected_states_qkvz, _ = self.in_proj_qkvz(hidden_states)
|
||||
|
||||
@@ -261,8 +261,7 @@ class MambaStateShapeCalculator:
|
||||
@classmethod
|
||||
def extra_groups_for_head_shards(cls, ngroups: int, tp_size: int):
|
||||
"""Compute the increase in group numbers to account for
|
||||
replication in order to accompany the head shards.
|
||||
"""
|
||||
replication in order to accompany the head shards."""
|
||||
# in the case ngoups % tp_size == 0, this will be zero
|
||||
if ngroups % tp_size == 0:
|
||||
return 0
|
||||
|
||||
@@ -59,8 +59,7 @@ def get_ssm_device_name() -> str:
|
||||
|
||||
def _canonical_cache_dtype(cache_dtype: str) -> str:
|
||||
"""Canonical key for config lookup. bf16 and fp16 share the same tuned
|
||||
configs because the kernel only sees bit width when accessing state.
|
||||
"""
|
||||
configs because the kernel only sees bit width when accessing state."""
|
||||
return "float16" if cache_dtype == "bfloat16" else cache_dtype
|
||||
|
||||
|
||||
@@ -161,8 +160,7 @@ _ssm_config_override: tuple[int, int] | None = None
|
||||
@contextmanager
|
||||
def override_ssm_config(config: tuple[int, int]):
|
||||
"""Pin ``try_get_optimal_ssm_config`` to ``config`` for the duration of
|
||||
the context. Used by the tuning benchmark to time specific configs.
|
||||
"""
|
||||
the context. Used by the tuning benchmark to time specific configs."""
|
||||
global _ssm_config_override
|
||||
prev = _ssm_config_override
|
||||
_ssm_config_override = config
|
||||
|
||||
@@ -210,8 +210,7 @@ class LamportWorkspace:
|
||||
@property
|
||||
def workspace(self) -> torch.Tensor:
|
||||
"""Device tensor (int64) that can be passed to the kernel
|
||||
as ``void** workspace``.
|
||||
"""
|
||||
as ``void** workspace``."""
|
||||
return self._workspace
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -46,24 +46,21 @@ class QuantizeMethodBase(ABC):
|
||||
):
|
||||
"""Create weights for a layer.
|
||||
|
||||
The weights will be set as attributes of the layer.
|
||||
"""
|
||||
The weights will be set as attributes of the layer."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def apply(self, layer: torch.nn.Module, *args, **kwargs) -> torch.Tensor:
|
||||
"""Apply the weights in layer to the input tensor.
|
||||
|
||||
Expects create_weights to have been called before on the layer.
|
||||
"""
|
||||
Expects create_weights to have been called before on the layer."""
|
||||
raise NotImplementedError
|
||||
|
||||
# Not required functions
|
||||
def embedding(self, layer: torch.nn.Module, *args, **kwargs) -> torch.Tensor:
|
||||
"""Gather embeddings in the layer based on indices in the input tensor.
|
||||
|
||||
Expects create_weights to have been called before on the layer.
|
||||
"""
|
||||
Expects create_weights to have been called before on the layer."""
|
||||
raise NotImplementedError
|
||||
|
||||
# Not required functions
|
||||
@@ -76,8 +73,7 @@ class QuantizeMethodBase(ABC):
|
||||
Quantization methods that need special weight handling (e.g. repacked
|
||||
weights) override this.
|
||||
|
||||
Expects create_weights to have been called before on the layer.
|
||||
"""
|
||||
Expects create_weights to have been called before on the layer."""
|
||||
layer.weight = embed_tokens.weight
|
||||
return layer
|
||||
|
||||
|
||||
@@ -665,8 +665,7 @@ class CompressedTensorsConfig(QuantizationConfig):
|
||||
) -> bool:
|
||||
"""Weight N-bit INT (pack-quantized for sub-byte, int-quantized for 8-bit)
|
||||
with static per-tensor INT8 input/output activation quant, applied as a float
|
||||
fake-quant around a weight-only matmul.
|
||||
"""
|
||||
fake-quant around a weight-only matmul."""
|
||||
is_int_pack_format = format in (
|
||||
CompressionFormat.pack_quantized.value,
|
||||
CompressionFormat.int_quantized.value,
|
||||
@@ -702,8 +701,7 @@ class CompressedTensorsConfig(QuantizationConfig):
|
||||
format: str | None,
|
||||
) -> bool:
|
||||
"""Weight N-bit INT with symmetric dynamic INT activation quant
|
||||
via Humming kernel.
|
||||
"""
|
||||
via Humming kernel."""
|
||||
if input_quant is None:
|
||||
return False
|
||||
is_pack_format = format == CompressionFormat.pack_quantized.value
|
||||
|
||||
+1
-2
@@ -37,8 +37,7 @@ def _dequant_gather_kernel(
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
"""Gather embedding rows by token id, unpack int32-packed INT weights, and
|
||||
dequantize to ``out`` dtype in one pass (no int8 intermediate).
|
||||
"""
|
||||
dequantize to ``out`` dtype in one pass (no int8 intermediate)."""
|
||||
row = tl.program_id(0)
|
||||
col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
|
||||
col_mask = col < hidden
|
||||
|
||||
+1
-2
@@ -211,8 +211,7 @@ class CompressedTensorsWNA8O8Int(CompressedTensorsScheme):
|
||||
|
||||
def _pack_int_quantized_weight(self, layer: torch.nn.Module) -> None:
|
||||
"""Normalize an int-quantized (plain int8) weight to the canonical
|
||||
``weight_packed`` int32 + ``weight_shape`` layout the MP kernels expect.
|
||||
"""
|
||||
``weight_packed`` int32 + ``weight_shape`` layout the MP kernels expect."""
|
||||
weight = layer.weight
|
||||
out_features, in_features = weight.shape
|
||||
packed = pack_to_int32(weight.data.contiguous(), self.num_bits)
|
||||
|
||||
@@ -86,8 +86,7 @@ class INCConfigParser:
|
||||
|
||||
def is_explicitly_configured(name: str) -> bool:
|
||||
"""Return True if *name* has an explicit entry in extra_config,
|
||||
either via exact key match or via a regex pattern key.
|
||||
"""
|
||||
either via exact key match or via a regex pattern key."""
|
||||
if not self._config.extra_config:
|
||||
return False
|
||||
if name in self._config.extra_config:
|
||||
|
||||
@@ -48,8 +48,7 @@ class INCScheme(ABC):
|
||||
layer_config: "INCLayerConfig",
|
||||
) -> "FusedMoEMethodBase | None":
|
||||
"""Optional. Override if this scheme supports MoE.
|
||||
Default raises NotImplementedError.
|
||||
"""
|
||||
Default raises NotImplementedError."""
|
||||
raise NotImplementedError(
|
||||
f"{type(self).__name__} does not support MoE layers. "
|
||||
f"Layer config: {layer_config}"
|
||||
|
||||
@@ -1988,8 +1988,7 @@ class KNvfp4Static(QuantKeyScheme):
|
||||
|
||||
class KNvfp4Dynamic(QuantKeyScheme):
|
||||
"""NVFP4 activation scheme (W4A4). Has a static global input scale on disk;
|
||||
the per-group scale is computed at runtime inside the kernel.
|
||||
"""
|
||||
the per-group scale is computed at runtime inside the kernel."""
|
||||
|
||||
key = kNvfp4Dynamic
|
||||
|
||||
@@ -2026,8 +2025,7 @@ class KNvfp4Dynamic(QuantKeyScheme):
|
||||
|
||||
class KFp8StaticTensor(QuantKeyScheme):
|
||||
"""Plain per-tensor static FP8 — bivalent: serves BOTH the weight slot and
|
||||
the activation slot (W8A8). One key in both QuantSpec slots.
|
||||
"""
|
||||
the activation slot (W8A8). One key in both QuantSpec slots."""
|
||||
|
||||
key = kFp8StaticTensorSym
|
||||
|
||||
@@ -2097,8 +2095,7 @@ class KFp8StaticTensor(QuantKeyScheme):
|
||||
|
||||
class KFp8StaticChannel(QuantKeyScheme):
|
||||
"""Per-channel static FP8 weight (the 'PcPt' weight). Weight-role only —
|
||||
there is no static per-channel *activation* today.
|
||||
"""
|
||||
there is no static per-channel *activation* today."""
|
||||
|
||||
key = kFp8StaticTokenSym
|
||||
|
||||
@@ -2139,8 +2136,7 @@ class KFp8StaticChannel(QuantKeyScheme):
|
||||
class KFp8Block128(QuantKeyScheme):
|
||||
"""128x128 block-static FP8 weight ('PbWo'). Weight-role only. ModelOpt
|
||||
exports the scale 4-D [out_blk,1,in_blk,1]; process squeezes to 2-D.
|
||||
No transpose (block kernel keeps [out,in]).
|
||||
"""
|
||||
No transpose (block kernel keeps [out,in])."""
|
||||
|
||||
key = kFp8Static128BlockSym
|
||||
|
||||
@@ -2196,8 +2192,7 @@ class KFp8Block128(QuantKeyScheme):
|
||||
|
||||
class KMxfp8Static(QuantKeyScheme):
|
||||
"""MXFP8 weight: fp8-e4m3 values + per-32-block e8m0 (uint8) scale.
|
||||
Weight-role only. process is validate-only plus an idempotency guard.
|
||||
"""
|
||||
Weight-role only. process is validate-only plus an idempotency guard."""
|
||||
|
||||
key = kMxfp8Static
|
||||
|
||||
@@ -2272,8 +2267,7 @@ class KDynamicNoParam(QuantKeyScheme):
|
||||
"""Dynamic activation with no stored scale (W8A8): quantized at runtime in
|
||||
the kernel. NOT the same as activation=None (weight-only) — init_fp8 needs a
|
||||
non-None activation key. Activation-role only. Serves the fp8 per-token, fp8
|
||||
per-block, and mxfp8 dynamic activation keys.
|
||||
"""
|
||||
per-block, and mxfp8 dynamic activation keys."""
|
||||
|
||||
def create_weights(self, layer, role, ctx, shapes, wl) -> None:
|
||||
if role is not ACT:
|
||||
|
||||
@@ -79,8 +79,7 @@ class Mxfp4Config(QuantizationConfig):
|
||||
|
||||
def _make_moe_method(self, moe: FusedMoEConfig) -> FusedMoEMethodBase:
|
||||
"""MoE method for RoutedExperts. Subclasses override to pick a
|
||||
checkpoint-specific kernel family.
|
||||
"""
|
||||
checkpoint-specific kernel family."""
|
||||
return Mxfp4MoEMethod(moe)
|
||||
|
||||
def get_quant_method(
|
||||
|
||||
@@ -139,8 +139,7 @@ def _find_matching_targets(
|
||||
|
||||
class OnlineQuantizationConfig(QuantizationConfig):
|
||||
"""Model-level config for online quantization (quantize fp16/bf16 weights
|
||||
during model loading, without requiring a pre-quantized checkpoint).
|
||||
"""
|
||||
during model loading, without requiring a pre-quantized checkpoint)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -118,8 +118,7 @@ def _is_tp_sharded(layer: Module, *, reduces_output_dim: bool = True) -> bool:
|
||||
|
||||
class OnlineLinearBase(LinearMethodBase):
|
||||
"""Shared base for online FP8 linear methods. Loads fp16/bf16 checkpoint
|
||||
weights onto meta device and materializes them just-in-time.
|
||||
"""
|
||||
weights onto meta device and materializes them just-in-time."""
|
||||
|
||||
uses_meta_device: bool = True
|
||||
|
||||
@@ -163,8 +162,7 @@ class OnlineLinearBase(LinearMethodBase):
|
||||
|
||||
class Fp8PerTensorOnlineLinearMethod(OnlineLinearBase):
|
||||
"""Online tensorwise FP8 linear quantization.
|
||||
Loads fp16/bf16 weights and quantizes them per-tensor during loading.
|
||||
"""
|
||||
Loads fp16/bf16 weights and quantizes them per-tensor during loading."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
@@ -265,8 +263,7 @@ class Fp8PerTensorOnlineLinearMethod(OnlineLinearBase):
|
||||
|
||||
class Fp8PerBlockOnlineLinearMethod(OnlineLinearBase):
|
||||
"""Online blockwise FP8 linear quantization.
|
||||
Loads fp16/bf16 weights and quantizes them per-block during loading.
|
||||
"""
|
||||
Loads fp16/bf16 weights and quantizes them per-block during loading."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
@@ -440,8 +437,7 @@ class Fp8PtpcOnlineLinearMethod(OnlineLinearBase):
|
||||
|
||||
class _Fp8OnlineMoEBase(OnlineMoEMethodBase):
|
||||
"""Shared base for online FP8 MoE methods. Loads fp16/bf16 checkpoint
|
||||
weights onto meta device and materializes them just-in-time.
|
||||
"""
|
||||
weights onto meta device and materializes them just-in-time."""
|
||||
|
||||
# Declared here for mypy; actual values are set in __init__.
|
||||
fp8_backend: "Fp8MoeBackend"
|
||||
@@ -562,8 +558,7 @@ class _Fp8OnlineMoEBase(OnlineMoEMethodBase):
|
||||
|
||||
class Fp8PerTensorOnlineMoEMethod(_Fp8OnlineMoEBase):
|
||||
"""Online tensorwise FP8 MoE quantization.
|
||||
Loads fp16/bf16 weights and quantizes them per-tensor during loading.
|
||||
"""
|
||||
Loads fp16/bf16 weights and quantizes them per-tensor during loading."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -620,8 +615,7 @@ class Fp8PerTensorOnlineMoEMethod(_Fp8OnlineMoEBase):
|
||||
|
||||
class Fp8PerBlockOnlineMoEMethod(_Fp8OnlineMoEBase):
|
||||
"""Online blockwise FP8 MoE quantization.
|
||||
Loads fp16/bf16 weights and quantizes them per-block during loading.
|
||||
"""
|
||||
Loads fp16/bf16 weights and quantizes them per-block during loading."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user