vllm.v1.metrics.perf
¶
Analytic flops/memory estimation module for transformer components, to help derive MFU (Model Flops Utilization) stats for a running model.
Classes:
-
AttentionDetectionParser–Prevents standard AttentionMetrics from being instantiated for MLA models.
-
AttentionMetrics– -
AttentionQuantizationConfigParser–Parses quantization configuration for attention layers.
-
BaseAttentionConfigParser–Parses attention-specific configuration.
-
BaseConfigParser–Parses base model configuration.
-
BaseFfnConfigParser–Parses FFN and MoE configuration.
-
ComponentMetrics–Each concrete ComponentMetrics class is associated with:
-
ExecutionContext–Represents an execution context for a batch of requests.
-
FfnMetrics– -
FfnParallelParser–Parses FFN parallelism configuration.
-
FfnQuantizationConfigParser–Parses quantization configuration for FFN layers.
-
InterleaveMoeLayerStepParser–Parses interleave_moe_layer_step field for models like Llama4.
-
InvalidComponent–Custom exception to indicate that a certain ComponentMetric is not
-
MLAAttentionMetrics–Performance metrics for Multi-Latent Attention (MLA) layers.
-
MLAConfigParser–Parses MLA-specific configuration fields.
-
MLADetectionParser–Validates that the model uses MLA attention.
-
ModelMetrics– -
MoeLayerFreqParser–Parses moe_layer_freq and first_k_dense_replace fields for models like Deepseek.
-
ParsedArgs–Syntactic sugar so that Parsers can use dot notations
-
Parser– -
ParserChain–Applies chain of parser in a sequential order.
-
PerfMetricsProm–Record performance metrics in Prometheus.
-
SlidingWindowAttentionParser–Parses sliding window attention configuration and layer breakdown.
-
UnembedMetrics–
Functions:
-
get_required–Get an attr from an object, or throw a InvalidComponentError if it's not set.
-
getattr_from_list–Try to get the first attr that exists in the object
AttentionDetectionParser
¶
Bases: Parser
Prevents standard AttentionMetrics from being instantiated for MLA models. MLA models should use MLAAttentionMetrics instead.
Methods:
-
parse–Raise InvalidComponent for MLA models so AttentionMetrics is skipped.
parse(args, vllm_config)
¶
Raise InvalidComponent for MLA models so AttentionMetrics is skipped.
AttentionMetrics
¶
Bases: ComponentMetrics
Methods:
-
component_type–Return the component registry key for standard (non-MLA) attention.
-
get_num_flops_breakdown–Compute FLOPs breakdown for attention layers.
-
get_parser–Return the parser chain for AttentionMetrics.
-
get_read_bytes_breakdown–Compute read-memory-traffic breakdown for attention layers.
-
get_write_bytes_breakdown–Calculate write memory traffic for attention layers.
_layer_counts(per_gpu)
¶
Return (L, L_full, L_swa), the layer counts to bill for.
Per-GPU counts divide each global count by pp_size independently.
Deriving the sublayer split after reducing L instead rounds a
minority sublayer away: a 6-layer model with 1 sliding-window layer at
pp_size=2 yields round(3 * 1 / 6) == 0, billing all three layers
as full attention. Dividing each count separately keeps
L_full + L_swa == L and keeps the per-GPU values summing back to the
whole model across stages.
The counts are fractional because these metrics are built from config
alone (see from_vllm_config); no pipeline rank is available, so a
per-GPU figure is the average stage rather than a specific one. A model
whose layers do not divide evenly across stages has no single integer
answer here.
component_type()
classmethod
¶
Return the component registry key for standard (non-MLA) attention.
get_num_flops_breakdown(ctx, per_gpu=True)
¶
Compute FLOPs breakdown for attention layers.
Accounts for hybrid models by splitting total layers into full-attention
(L_full) and sliding-window (L_swa) sublayers. See _layer_counts for
how those are scaled under pipeline parallelism.
Parameters:
-
(ctx¶ExecutionContext) –Execution context describing the current batch.
-
(per_gpu¶bool, default:True) –If True, scale counts down by tensor/pipeline parallelism.
Returns:
get_parser()
classmethod
¶
Return the parser chain for AttentionMetrics.
Parsers run in order: MLA detection guard, base model config, attention-specific config, sliding-window breakdown, quantization weight-size override.
get_read_bytes_breakdown(ctx, per_gpu=True)
¶
Compute read-memory-traffic breakdown for attention layers.
Splits layers into full-attention and sliding-window sublayers using the
same counts as get_num_flops_breakdown; see _layer_counts.
Parameters:
-
(ctx¶ExecutionContext) –Execution context describing the current batch.
-
(per_gpu¶bool, default:True) –If True, scale counts down by tensor/pipeline parallelism.
Returns:
get_write_bytes_breakdown(ctx, per_gpu=True)
¶
Calculate write memory traffic for attention layers.
Writes do not depend on the attention window, so only the total layer
count is needed; it comes from _layer_counts so all three breakdowns
bill the same number of layers.
AttentionQuantizationConfigParser
¶
BaseAttentionConfigParser
¶
BaseConfigParser
¶
Bases: Parser
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
Methods:
-
parse–Parse base model dimensions, dtype byte sizes, and parallelism config.
parse(args, vllm_config)
¶
Parse base model dimensions, dtype byte sizes, and parallelism config.
BaseFfnConfigParser
¶
Bases: Parser
Parses FFN and MoE configuration. Provides: intermediate_size, num_experts, num_experts_per_tok, moe_intermediate_size, num_shared_experts, num_moe_layers
ComponentMetrics
¶
Bases: BaseModel, ABC
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 - metric methods that derive flops/bytes for a given execution context
Methods:
-
component_type–Return the unique string key identifying this component in the registry.
-
from_vllm_config–Instantiate this class from VllmConfig.
-
get_num_flops_breakdown–Return per-operation FLOPs breakdown for this component.
-
get_parser–Return a ParserChain that provides values for all required fields.
-
get_read_bytes_breakdown–Return per-operation read-memory-traffic breakdown for this component.
-
get_write_bytes_breakdown–Return per-operation write-memory-traffic breakdown for this component.
component_type()
abstractmethod
classmethod
¶
Return the unique string key identifying this component in the registry.
from_vllm_config(vllm_config)
classmethod
¶
Instantiate this class from VllmConfig. Raises ValidationError if parsing fails.
get_num_flops_breakdown(ctx, per_gpu=True)
abstractmethod
¶
Return per-operation FLOPs breakdown for this component.
get_parser()
abstractmethod
classmethod
¶
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. See individual Parser docstrings for which args they provide, and field comments on ComponentMetrics subclasses for which parser provides each field.
get_read_bytes_breakdown(ctx, per_gpu=True)
abstractmethod
¶
Return per-operation read-memory-traffic breakdown for this component.
get_write_bytes_breakdown(ctx, per_gpu=True)
abstractmethod
¶
Return per-operation write-memory-traffic breakdown for this component.
ExecutionContext
dataclass
¶
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.
Example) - Batch with one full prefill (2048 tokens) and one decode (1 token, 8192 context): ctx = ExecutionContext() ctx.add(2048, 2048, is_prefill=True) ctx.add(1, 8192, is_prefill=False)
Methods:
-
add–Add a single request's statistics to this batch context.
-
decode_context_len_for_window–Sum of context_len for decode requests, clamped to sliding_window if set.
-
from_single_request–Create an ExecutionContext from a single request.
-
num_logits_tokens–Number of tokens that require logits computation (unembedding).
-
prefill_context_len_for_window–Sum of context_len for prefill requests, clamped to sliding_window if set.
-
total_num_tokens–Total number of tokens across all requests in the batch.
-
total_token_context_product–Total sum of (num_tokens * context_len) across all requests.
add(num_tokens, context_len, is_prefill)
¶
Add a single request's statistics to this batch context.
decode_context_len_for_window(sliding_window=None)
¶
Sum of context_len for decode requests, clamped to sliding_window if set.
from_single_request(num_tokens, context_len, is_prefill)
classmethod
¶
Create an ExecutionContext from a single request.
This is a convenience method primarily for testing.
num_logits_tokens()
¶
Number of tokens that require logits computation (unembedding).
For prefill, only the last token per request needs logits. For decode, all tokens need logits.
prefill_context_len_for_window(sliding_window=None)
¶
Sum of context_len for prefill requests, clamped to sliding_window if set.
total_num_tokens()
¶
Total number of tokens across all requests in the batch.
total_token_context_product(sliding_window=None)
¶
Total sum of (num_tokens * context_len) across all requests.
If sliding_window is provided, context length per request is clamped to sliding_window.
FfnMetrics
¶
Bases: ComponentMetrics
Methods:
-
component_type–Return the component registry key for FFN layers.
-
get_num_flops_breakdown–Calculate flops breakdown for FFN layers.
-
get_parser–Return the parser chain for FfnMetrics.
-
get_read_bytes_breakdown–Calculate read memory traffic for FFN layers.
-
get_write_bytes_breakdown–Calculate write memory traffic for FFN layers.
-
validate_moe_fields–Validate that MoE-related fields are properly set when num_moe_layers > 0.
component_type()
classmethod
¶
Return the component registry key for FFN layers.
get_num_flops_breakdown(ctx, per_gpu=True)
¶
Calculate flops breakdown for FFN layers.
get_parser()
classmethod
¶
Return the parser chain for FfnMetrics.
Parsers run in order: base model config, FFN parallelism, base FFN config, MoE interleave step, MoE layer frequency, quantization override.
get_read_bytes_breakdown(ctx, per_gpu=True)
¶
Calculate read memory traffic for FFN layers.
get_write_bytes_breakdown(ctx, per_gpu=True)
¶
Calculate write memory traffic for FFN layers.
validate_moe_fields()
¶
Validate that MoE-related fields are properly set when num_moe_layers > 0.
FfnParallelParser
¶
FfnQuantizationConfigParser
¶
InterleaveMoeLayerStepParser
¶
Bases: Parser
Parses interleave_moe_layer_step field for models like Llama4.
Overrides: num_moe_layers
InvalidComponent
¶
Bases: Exception
Custom exception to indicate that a certain ComponentMetric is not applicable to the given VllmConfig.
MLAAttentionMetrics
¶
Bases: ComponentMetrics
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 (kv_lora_rank + qk_rope_head_dim) per token per layer, instead of 2 * num_kv_heads * head_dim as in standard MHA/GQA. - Q path uses optional low-rank compression: h -> q_lora_rank -> num_heads * qk_head_dim - KV path: h -> (kv_lora_rank + qk_rope_head_dim), then kv_lora_rank -> num_heads * (qk_nope_head_dim + v_head_dim)
Used by DeepSeek-V2, DeepSeek-V3, DeepSeek-R1, and similar models.
Methods:
-
component_type–Return the component registry key for MLA attention.
-
get_num_flops_breakdown–Calculate flops breakdown for MLA attention layers.
-
get_parser–Return the parser chain for MLAAttentionMetrics.
-
get_read_bytes_breakdown–Calculate read memory traffic for MLA attention layers.
-
get_write_bytes_breakdown–Calculate write memory traffic for MLA attention layers.
component_type()
classmethod
¶
Return the component registry key for MLA attention.
get_num_flops_breakdown(ctx, per_gpu=True)
¶
Calculate flops breakdown for MLA attention layers.
MLA projection structure: - Q path: h -> q_lora_rank -> num_heads * qk_head_dim (or h -> num_heads * qk_head_dim if q_lora_rank is None) - KV path: h -> (kv_lora_rank + qk_rope_head_dim), then kv_lora_rank -> num_heads * (qk_nope_head_dim + v_head_dim) - Attention: Q @ K^T and attn @ V - Output: num_heads * v_head_dim -> h
get_parser()
classmethod
¶
Return the parser chain for MLAAttentionMetrics.
Parsers run in order: MLA detection guard, base model config, MLA-specific config, quantization weight-size override.
get_read_bytes_breakdown(ctx, per_gpu=True)
¶
Calculate read memory traffic for MLA attention layers.
get_write_bytes_breakdown(ctx, per_gpu=True)
¶
Calculate write memory traffic for MLA attention layers.
MLAConfigParser
¶
Bases: Parser
Parses MLA-specific configuration fields. Provides: kv_lora_rank, qk_nope_head_dim, qk_rope_head_dim, v_head_dim, q_lora_rank
Methods:
-
parse–Parse MLA-specific compression dimensions and KV-cache dtype byte size.
parse(args, vllm_config)
¶
Parse MLA-specific compression dimensions and KV-cache dtype byte size.
MLADetectionParser
¶
Bases: Parser
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.
Methods:
-
parse–Raise InvalidComponent if the model does not use MLA attention.
parse(args, vllm_config)
¶
Raise InvalidComponent if the model does not use MLA attention.
ModelMetrics
¶
Methods:
-
__init__–Parse vllm_config to instantiate metrics for each component.
-
get_step_perf_stats_per_gpu–Calculate perf stats for the current step based on scheduled tokens.
MoeLayerFreqParser
¶
Bases: Parser
Parses moe_layer_freq and first_k_dense_replace fields for models like Deepseek.
Overrides: num_moe_layers
ParsedArgs
¶
Syntactic sugar so that Parsers can use dot notations to access/update the parsed arguments.
e.g.) args = ParsedArgs() args.x = 3 args.y = args.x + 1
Parser
¶
ParserChain
¶
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.
Methods:
-
parse–Apply all parsers in sequence and return the accumulated ParsedArgs.
parse(vllm_config)
¶
Apply all parsers in sequence and return the accumulated ParsedArgs.
PerfMetricsProm
¶
Record performance metrics in Prometheus.
Average TFLOPS (tera floating-point operations per second) can be calculated using a PromQL query:
rate(vllm:estimated_flops_per_gpu_total[1m]) / 1e12
Average memory bandwidth in GB/s can be calculated using:
(rate(vllm:estimated_read_bytes_per_gpu_total[1m]) + rate(vllm:estimated_write_bytes_per_gpu_total[1m])) / 1e9
SlidingWindowAttentionParser
¶
Bases: Parser
Parses sliding window attention configuration and layer breakdown. Provides: sliding_window, num_swa_layers
Methods:
-
parse–Determine sliding_window size and count of SWA layers.
parse(args, vllm_config)
¶
Determine sliding_window size and count of SWA layers.
Detects per-layer type lists (e.g. Llama-4), Gemma 2 alternating pattern, and uniform SWA models (Mistral, Qwen2.5).
UnembedMetrics
¶
Bases: ComponentMetrics
Methods:
-
component_type–Return the component registry key for the unembedding (LM head) layer.
-
get_num_flops_breakdown–Calculate flops breakdown for unembedding layer.
-
get_parser–Return the parser chain for UnembedMetrics (base model config only).
-
get_read_bytes_breakdown–Calculate read memory traffic for unembedding layer.
-
get_write_bytes_breakdown–Calculate write memory traffic for unembedding layer.
component_type()
classmethod
¶
Return the component registry key for the unembedding (LM head) layer.
get_num_flops_breakdown(ctx, per_gpu=True)
¶
Calculate flops breakdown for unembedding layer.
get_parser()
classmethod
¶
Return the parser chain for UnembedMetrics (base model config only).
get_read_bytes_breakdown(ctx, per_gpu=True)
¶
Calculate read memory traffic for unembedding layer.
get_write_bytes_breakdown(ctx, per_gpu=True)
¶
Calculate write memory traffic for unembedding layer.
get_required(obj, attr)
¶
Get an attr from an object, or throw a InvalidComponentError if it's not set.
getattr_from_list(obj, attrs, default=None)
¶
Try to get the first attr that exists in the object from a list of attrs. Otherwise return None.