Add pydocstyle to the ruff rules (#52136)
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com> Signed-off-by: Harry Mellor <hej.mellor@gmail.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
804e5377aa
commit
8c1557a79c
@@ -177,6 +177,7 @@ def build_buckets(mantissa_lst: list[int], max_value: int) -> list[float]:
|
||||
|
||||
Returns:
|
||||
Bucket values in increasing order, capped at `max_value`.
|
||||
|
||||
"""
|
||||
exponent = 0
|
||||
buckets: list[float] = []
|
||||
@@ -196,6 +197,7 @@ def build_1_2_5_buckets(max_value: int) -> list[float]:
|
||||
Example:
|
||||
>>> build_1_2_5_buckets(100)
|
||||
[1, 2, 5, 10, 20, 50, 100]
|
||||
|
||||
"""
|
||||
return build_buckets([1, 2, 5], max_value)
|
||||
|
||||
@@ -218,6 +220,7 @@ def histogram_buckets(
|
||||
Raises:
|
||||
ValueError: If `family` is `request_tokens` and `max_model_len`
|
||||
is None.
|
||||
|
||||
"""
|
||||
if family == "request_tokens":
|
||||
if max_model_len is None:
|
||||
|
||||
+10
-10
@@ -91,7 +91,8 @@ 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]): ...
|
||||
@@ -1202,16 +1203,15 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
|
||||
|
||||
|
||||
class StatLoggerManager:
|
||||
"""
|
||||
StatLoggerManager:
|
||||
Logging happens at the level of the EngineCore (per scheduler).
|
||||
* DP: >1 EngineCore per AsyncLLM - loggers for each EngineCore.
|
||||
* With Local Logger, just make N copies for N EngineCores.
|
||||
* With Prometheus, we need a single logger with N "labels"
|
||||
"""StatLoggerManager:
|
||||
Logging happens at the level of the EngineCore (per scheduler).
|
||||
* DP: >1 EngineCore per AsyncLLM - loggers for each EngineCore.
|
||||
* With Local Logger, just make N copies for N EngineCores.
|
||||
* With Prometheus, we need a single logger with N "labels"
|
||||
|
||||
This class abstracts away this implementation detail from
|
||||
the AsyncLLM, allowing the AsyncLLM to just call .record()
|
||||
and .log() to a simple interface.
|
||||
This class abstracts away this implementation detail from
|
||||
the AsyncLLM, allowing the AsyncLLM to just call .record()
|
||||
and .log() to a simple interface.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
+28
-53
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Analytic flops/memory estimation module for transformer components,
|
||||
"""Analytic flops/memory estimation module for transformer components,
|
||||
to help derive MFU (Model Flops Utilization) stats for a running model.
|
||||
"""
|
||||
|
||||
@@ -33,8 +32,7 @@ logger = init_logger(__name__)
|
||||
|
||||
|
||||
class InvalidComponent(Exception):
|
||||
"""
|
||||
Custom exception to indicate that a certain ComponentMetric is not
|
||||
"""Custom exception to indicate that a certain ComponentMetric is not
|
||||
applicable to the given VllmConfig.
|
||||
"""
|
||||
|
||||
@@ -99,8 +97,7 @@ class PerfStats:
|
||||
|
||||
@dataclass
|
||||
class ExecutionContext:
|
||||
"""
|
||||
Represents an execution context for a batch of requests.
|
||||
"""Represents an execution context for a batch of requests.
|
||||
|
||||
This class aggregates statistics across multiple requests in a batch,
|
||||
separately tracking prefill and decode phases.
|
||||
@@ -202,8 +199,7 @@ class ExecutionContext:
|
||||
|
||||
|
||||
class ParsedArgs:
|
||||
"""
|
||||
Syntactic sugar so that Parsers can use dot notations
|
||||
"""Syntactic sugar so that Parsers can use dot notations
|
||||
to access/update the parsed arguments.
|
||||
|
||||
e.g.)
|
||||
@@ -227,16 +223,14 @@ class ParsedArgs:
|
||||
|
||||
class Parser(Protocol):
|
||||
def parse(self, args: ParsedArgs, vllm_config: VllmConfig) -> ParsedArgs:
|
||||
"""
|
||||
Parse the vllm config and update the current ParsedArgs and pass it on.
|
||||
"""Parse the vllm config and update the current ParsedArgs and pass it on.
|
||||
If the parser isn't applicable to the vllm_config, it will do nothing.
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class ParserChain:
|
||||
"""
|
||||
Applies chain of parser in a sequential order.
|
||||
"""Applies chain of parser in a sequential order.
|
||||
Later parsers might overwrite results from previous parsers,
|
||||
so parsers should be chained in the appropriate order if they
|
||||
are not mutually exclusive.
|
||||
@@ -260,8 +254,7 @@ _COMPONENT_METRICS_REGISTRY: dict[str, type["ComponentMetrics"]] = {}
|
||||
|
||||
|
||||
class ComponentMetrics(BaseModel, ABC):
|
||||
"""
|
||||
Each concrete ComponentMetrics class is associated with:
|
||||
"""Each concrete ComponentMetrics class is associated with:
|
||||
- fields that are required for metric derivation
|
||||
(fields are specified/validated through pydantic model)
|
||||
- parser to parse VllmConfig into fields
|
||||
@@ -277,8 +270,7 @@ class ComponentMetrics(BaseModel, ABC):
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def get_parser(cls) -> ParserChain:
|
||||
"""
|
||||
Return a ParserChain that provides values for all required fields.
|
||||
"""Return a ParserChain that provides values for all required fields.
|
||||
The returned parser chain must populate ParsedArgs with values for every
|
||||
field defined on this ComponentMetrics class. Missing fields will cause
|
||||
a ValidationError when from_vllm_config() is called.
|
||||
@@ -292,11 +284,9 @@ class ComponentMetrics(BaseModel, ABC):
|
||||
|
||||
@classmethod
|
||||
def from_vllm_config(cls, vllm_config: VllmConfig) -> Self:
|
||||
"""
|
||||
Instantiate this class from VllmConfig.
|
||||
"""Instantiate this class from VllmConfig.
|
||||
Raises ValidationError if parsing fails.
|
||||
"""
|
||||
|
||||
parser = cls.get_parser()
|
||||
parsed_args = parser.parse(vllm_config)
|
||||
try:
|
||||
@@ -343,8 +333,7 @@ class ComponentMetrics(BaseModel, ABC):
|
||||
|
||||
|
||||
class BaseConfigParser(Parser):
|
||||
"""
|
||||
Parses base model configuration.
|
||||
"""Parses base model configuration.
|
||||
Provides: vocab_size, hidden_size, num_attention_heads, num_hidden_layers,
|
||||
weight_byte_size, activation_byte_size, dp_size, tp_size, pp_size, enable_ep
|
||||
"""
|
||||
@@ -396,8 +385,7 @@ class BaseConfigParser(Parser):
|
||||
|
||||
|
||||
class BaseAttentionConfigParser(Parser):
|
||||
"""
|
||||
Parses attention-specific configuration.
|
||||
"""Parses attention-specific configuration.
|
||||
Provides: num_key_value_heads, head_dim, cache_byte_size
|
||||
"""
|
||||
|
||||
@@ -418,8 +406,7 @@ class BaseAttentionConfigParser(Parser):
|
||||
|
||||
|
||||
class SlidingWindowAttentionParser(Parser):
|
||||
"""
|
||||
Parses sliding window attention configuration and layer breakdown.
|
||||
"""Parses sliding window attention configuration and layer breakdown.
|
||||
Provides: sliding_window, num_swa_layers
|
||||
"""
|
||||
|
||||
@@ -466,8 +453,7 @@ class SlidingWindowAttentionParser(Parser):
|
||||
|
||||
|
||||
class AttentionQuantizationConfigParser(Parser):
|
||||
"""
|
||||
Parses quantization configuration for attention layers.
|
||||
"""Parses quantization configuration for attention layers.
|
||||
Overrides: weight_byte_size
|
||||
"""
|
||||
|
||||
@@ -490,8 +476,7 @@ class AttentionQuantizationConfigParser(Parser):
|
||||
|
||||
|
||||
class AttentionDetectionParser(Parser):
|
||||
"""
|
||||
Prevents standard AttentionMetrics from being instantiated for MLA models.
|
||||
"""Prevents standard AttentionMetrics from being instantiated for MLA models.
|
||||
MLA models should use MLAAttentionMetrics instead.
|
||||
"""
|
||||
|
||||
@@ -589,6 +574,7 @@ class AttentionMetrics(ComponentMetrics):
|
||||
|
||||
Returns:
|
||||
Dict with keys: qkv_proj, out_proj, attn_qk, attn_av.
|
||||
|
||||
"""
|
||||
D, q, kv, d = (
|
||||
self.hidden_size,
|
||||
@@ -642,6 +628,7 @@ class AttentionMetrics(ComponentMetrics):
|
||||
Returns:
|
||||
Dict with keys: qkv_input, qkv_weight, attn_input (conditional),
|
||||
out_input, out_weight.
|
||||
|
||||
"""
|
||||
D, q, kv, d = (
|
||||
self.hidden_size,
|
||||
@@ -747,8 +734,7 @@ class AttentionMetrics(ComponentMetrics):
|
||||
|
||||
|
||||
class MLADetectionParser(Parser):
|
||||
"""
|
||||
Validates that the model uses MLA attention.
|
||||
"""Validates that the model uses MLA attention.
|
||||
Raises InvalidComponent if the model does not use MLA,
|
||||
so MLAAttentionMetrics is silently skipped for non-MLA models.
|
||||
"""
|
||||
@@ -761,8 +747,7 @@ class MLADetectionParser(Parser):
|
||||
|
||||
|
||||
class MLAConfigParser(Parser):
|
||||
"""
|
||||
Parses MLA-specific configuration fields.
|
||||
"""Parses MLA-specific configuration fields.
|
||||
Provides: kv_lora_rank, qk_nope_head_dim, qk_rope_head_dim,
|
||||
v_head_dim, q_lora_rank
|
||||
"""
|
||||
@@ -787,8 +772,7 @@ class MLAConfigParser(Parser):
|
||||
|
||||
|
||||
class MLAAttentionMetrics(ComponentMetrics):
|
||||
"""
|
||||
Performance metrics for Multi-Latent Attention (MLA) layers.
|
||||
"""Performance metrics for Multi-Latent Attention (MLA) layers.
|
||||
|
||||
MLA uses a compressed latent representation for KV cache:
|
||||
- KV cache stores a single compressed vector of size
|
||||
@@ -1025,8 +1009,7 @@ class MLAAttentionMetrics(ComponentMetrics):
|
||||
|
||||
|
||||
class BaseFfnConfigParser(Parser):
|
||||
"""
|
||||
Parses FFN and MoE configuration.
|
||||
"""Parses FFN and MoE configuration.
|
||||
Provides: intermediate_size, num_experts, num_experts_per_tok,
|
||||
moe_intermediate_size, num_shared_experts, num_moe_layers
|
||||
"""
|
||||
@@ -1056,8 +1039,7 @@ class BaseFfnConfigParser(Parser):
|
||||
|
||||
|
||||
class FfnParallelParser(Parser):
|
||||
"""
|
||||
Parses FFN parallelism configuration.
|
||||
"""Parses FFN parallelism configuration.
|
||||
|
||||
Provides: ffn_tp_size, ffn_ep_size
|
||||
"""
|
||||
@@ -1077,8 +1059,7 @@ class FfnParallelParser(Parser):
|
||||
|
||||
|
||||
class InterleaveMoeLayerStepParser(Parser):
|
||||
"""
|
||||
Parses interleave_moe_layer_step field for models like Llama4.
|
||||
"""Parses interleave_moe_layer_step field for models like Llama4.
|
||||
|
||||
Overrides: num_moe_layers
|
||||
"""
|
||||
@@ -1104,8 +1085,7 @@ class InterleaveMoeLayerStepParser(Parser):
|
||||
|
||||
|
||||
class MoeLayerFreqParser(Parser):
|
||||
"""
|
||||
Parses moe_layer_freq and first_k_dense_replace fields for models like Deepseek.
|
||||
"""Parses moe_layer_freq and first_k_dense_replace fields for models like Deepseek.
|
||||
|
||||
Overrides: num_moe_layers
|
||||
"""
|
||||
@@ -1129,8 +1109,7 @@ class MoeLayerFreqParser(Parser):
|
||||
|
||||
|
||||
class FfnQuantizationConfigParser(Parser):
|
||||
"""
|
||||
Parses quantization configuration for FFN layers.
|
||||
"""Parses quantization configuration for FFN layers.
|
||||
|
||||
Overrides: weight_byte_size
|
||||
"""
|
||||
@@ -1486,11 +1465,9 @@ class UnembedMetrics(ComponentMetrics):
|
||||
|
||||
class ModelMetrics:
|
||||
def __init__(self, vllm_config: VllmConfig) -> None:
|
||||
"""
|
||||
Parse vllm_config to instantiate metrics for each component.
|
||||
"""Parse vllm_config to instantiate metrics for each component.
|
||||
is_enabled() will return False if no component metrics could be instantiated.
|
||||
"""
|
||||
|
||||
self.vllm_config = vllm_config
|
||||
|
||||
self.metrics: list[ComponentMetrics] = []
|
||||
@@ -1558,10 +1535,7 @@ class ModelMetrics:
|
||||
def get_step_perf_stats_per_gpu(
|
||||
self, scheduler_output: SchedulerOutput
|
||||
) -> PerfStats:
|
||||
"""
|
||||
Calculate perf stats for the current step based on scheduled tokens.
|
||||
"""
|
||||
|
||||
"""Calculate perf stats for the current step based on scheduled tokens."""
|
||||
t0 = time.monotonic()
|
||||
|
||||
# Build a single batch context
|
||||
@@ -1846,7 +1820,8 @@ 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)
|
||||
|
||||
@@ -42,6 +42,7 @@ def get_prometheus_registry() -> CollectorRegistry:
|
||||
|
||||
Returns:
|
||||
Registry: A prometheus registry
|
||||
|
||||
"""
|
||||
if os.getenv("PROMETHEUS_MULTIPROC_DIR") is not None:
|
||||
logger.debug("Using multiprocess registry for prometheus metrics")
|
||||
@@ -70,7 +71,6 @@ def unregister_vllm_metrics():
|
||||
|
||||
def shutdown_prometheus():
|
||||
"""Shutdown prometheus metrics."""
|
||||
|
||||
path = _prometheus_multiproc_dir
|
||||
if path is None:
|
||||
return
|
||||
|
||||
@@ -68,8 +68,7 @@ class RayPrometheusMetric:
|
||||
|
||||
@staticmethod
|
||||
def _get_sanitized_opentelemetry_name(name: str) -> str:
|
||||
"""
|
||||
For compatibility with Ray + OpenTelemetry, the metric name must be
|
||||
"""For compatibility with Ray + OpenTelemetry, the metric name must be
|
||||
sanitized. In particular, this replaces disallowed character (e.g., ':')
|
||||
with '_' in the metric name.
|
||||
Allowed characters: a-z, A-Z, 0-9, _
|
||||
@@ -78,13 +77,13 @@ class RayPrometheusMetric:
|
||||
Ref: https://github.com/open-telemetry/opentelemetry-cpp/blob/main/sdk/src/metrics/instrument_metadata_validator.cc#L22-L23
|
||||
Ref: https://github.com/ray-project/ray/blob/master/src/ray/stats/metric.cc#L107
|
||||
"""
|
||||
|
||||
return re.sub(r"[^a-zA-Z0-9_]", "_", name)
|
||||
|
||||
|
||||
class RayGaugeWrapper(RayPrometheusMetric):
|
||||
"""Wraps around ray.util.metrics.Gauge to provide same API as
|
||||
prometheus_client.Gauge"""
|
||||
prometheus_client.Gauge
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -118,7 +117,8 @@ 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,7 +143,8 @@ 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,
|
||||
@@ -169,8 +170,7 @@ class RayHistogramWrapper(RayPrometheusMetric):
|
||||
|
||||
|
||||
class RaySpecDecodingProm(SpecDecodingProm):
|
||||
"""
|
||||
RaySpecDecodingProm is used by RayMetrics to log to Ray metrics.
|
||||
"""RaySpecDecodingProm is used by RayMetrics to log to Ray metrics.
|
||||
Provides the same metrics as SpecDecodingProm but uses Ray's
|
||||
util.metrics library.
|
||||
"""
|
||||
@@ -179,8 +179,7 @@ class RaySpecDecodingProm(SpecDecodingProm):
|
||||
|
||||
|
||||
class RayKVConnectorProm(KVConnectorProm):
|
||||
"""
|
||||
RayKVConnectorProm is used by RayMetrics to log Ray
|
||||
"""RayKVConnectorProm is used by RayMetrics to log Ray
|
||||
metrics. Provides the same metrics as KV connectors but
|
||||
uses Ray's util.metrics library.
|
||||
"""
|
||||
@@ -191,8 +190,7 @@ class RayKVConnectorProm(KVConnectorProm):
|
||||
|
||||
|
||||
class RayPerfMetricsProm(PerfMetricsProm):
|
||||
"""
|
||||
RayPerfMetricsProm is used by RayMetrics to log Ray
|
||||
"""RayPerfMetricsProm is used by RayMetrics to log Ray
|
||||
metrics. Provides the same MFU metrics as PerfMetricsProm
|
||||
uses Ray's util.metrics library.
|
||||
"""
|
||||
|
||||
@@ -82,6 +82,7 @@ def get_metrics_snapshot() -> list[Metric]:
|
||||
... print(f" count = {metric.count}")
|
||||
... for bucket_le, value in metrics.buckets.items():
|
||||
... print(f" {bucket_le} = {value}")
|
||||
|
||||
"""
|
||||
collected: list[Metric] = []
|
||||
for metric in REGISTRY.collect():
|
||||
|
||||
@@ -34,9 +34,10 @@ class BaseCacheStats:
|
||||
|
||||
class CachingMetrics:
|
||||
"""Metrics for caching with a hit rate of the most recent N requests.
|
||||
|
||||
Args:
|
||||
interval: The number of the most recent requests to aggregate.
|
||||
Defaults to 1000.
|
||||
max_recent_requests: The number of the most recent requests to aggregate.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, max_recent_requests: int = 1000) -> None:
|
||||
@@ -62,6 +63,7 @@ class CachingMetrics:
|
||||
|
||||
Args:
|
||||
stats: The prefix cache stats.
|
||||
|
||||
"""
|
||||
# reset_prefix_cache was invoked before the current update.
|
||||
# Reset the metrics before aggregating the current stats.
|
||||
@@ -113,8 +115,7 @@ class CachingMetrics:
|
||||
|
||||
@dataclass
|
||||
class PrefixCacheStats(BaseCacheStats):
|
||||
"""
|
||||
Stores prefix cache hit statistics.
|
||||
"""Stores prefix cache hit statistics.
|
||||
- `reset`: Whether `reset_prefix_cache` was invoked.
|
||||
- `queries`: Refers to the number of tokens that were queried.
|
||||
"""
|
||||
@@ -144,8 +145,7 @@ class PrefixCacheStats(BaseCacheStats):
|
||||
|
||||
@dataclass
|
||||
class MultiModalCacheStats(BaseCacheStats):
|
||||
"""
|
||||
Stores multi-modal cache hit statistics.
|
||||
"""Stores multi-modal cache hit statistics.
|
||||
- `reset`: Whether `reset_mm_cache` was invoked.
|
||||
- `queries`: Refers to the number of multi-modal data items
|
||||
that were queried.
|
||||
|
||||
Reference in New Issue
Block a user