Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes
Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
@@ -179,6 +179,7 @@ class ServingDerender(BaseServing):
|
||||
usage=usage,
|
||||
prompt_logprobs=gen.prompt_logprobs,
|
||||
kv_transfer_params=gen.kv_transfer_params,
|
||||
metrics=gen.metrics,
|
||||
)
|
||||
|
||||
async def derender_completion_response(
|
||||
@@ -245,6 +246,9 @@ class ServingDerender(BaseServing):
|
||||
choices=choices,
|
||||
usage=usage,
|
||||
kv_transfer_params=kv_params,
|
||||
# Metrics describe one prompt. Parallel samples are already
|
||||
# suppressed by /generate; multi-prompt responses cannot be merged.
|
||||
metrics=first.metrics if len(request.generate_responses) == 1 else None,
|
||||
)
|
||||
|
||||
async def derender_chat_stream_response(
|
||||
|
||||
@@ -11,7 +11,11 @@ from pydantic import (
|
||||
)
|
||||
|
||||
from vllm.config import ModelConfig
|
||||
from vllm.entrypoints.generate.base.protocol import StreamOptions, validate_cache_salt
|
||||
from vllm.entrypoints.generate.base.protocol import (
|
||||
PerRequestMetrics,
|
||||
StreamOptions,
|
||||
validate_cache_salt,
|
||||
)
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionLogProbs,
|
||||
ChatCompletionRequest,
|
||||
@@ -360,6 +364,7 @@ class GenerateStreamResponse(BaseModel):
|
||||
usage: UsageInfo | None = Field(default=None)
|
||||
prompt_token_ids: list[int] | None = None
|
||||
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
|
||||
metrics: PerRequestMetrics | None = None
|
||||
|
||||
|
||||
class GenerateResponse(BaseModel):
|
||||
@@ -378,6 +383,7 @@ class GenerateResponse(BaseModel):
|
||||
prompt_logprobs: list[dict[int, Logprob] | None] | None = None
|
||||
prompt_token_ids: list[int] | None = None
|
||||
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
|
||||
metrics: PerRequestMetrics | None = None
|
||||
|
||||
kv_transfer_params: dict[str, Any] | None = Field(
|
||||
default=None,
|
||||
|
||||
@@ -12,9 +12,13 @@ from fastapi import Request
|
||||
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.chat_utils import AsyncMultiModalItemTracker
|
||||
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
|
||||
from vllm.entrypoints.generate.base.protocol import (
|
||||
PerRequestMetrics,
|
||||
RequestResponseMetadata,
|
||||
)
|
||||
from vllm.entrypoints.generate.base.serving import (
|
||||
GenerateBaseServing,
|
||||
build_spec_decoding_metrics,
|
||||
clamp_prompt_logprobs,
|
||||
)
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
@@ -373,6 +377,11 @@ class ServingTokens(GenerateBaseServing):
|
||||
|
||||
request_metadata.final_usage_info = usage
|
||||
|
||||
per_request_metrics = None
|
||||
if request.sampling_params.n == 1:
|
||||
spec_stats = build_spec_decoding_metrics(final_res)
|
||||
if spec_stats is not None:
|
||||
per_request_metrics = PerRequestMetrics(speculative_decoding=spec_stats)
|
||||
response = GenerateResponse(
|
||||
request_id=request_id,
|
||||
created=created_time,
|
||||
@@ -384,6 +393,7 @@ class ServingTokens(GenerateBaseServing):
|
||||
final_res.prompt_token_ids if request.return_token_ids else None
|
||||
),
|
||||
mm_placeholders=request._response_mm_placeholders,
|
||||
metrics=per_request_metrics,
|
||||
kv_transfer_params=final_res.kv_transfer_params,
|
||||
ec_transfer_params=final_res.ec_transfer_params,
|
||||
)
|
||||
@@ -423,6 +433,7 @@ class ServingTokens(GenerateBaseServing):
|
||||
prompt_token_ids: list[int] | None = None
|
||||
num_cached_tokens = None
|
||||
sampling_params: SamplingParams = request.sampling_params
|
||||
last_res: RequestOutput | None = None
|
||||
|
||||
include_usage, include_continuous_usage = should_include_usage(
|
||||
request.stream_options, False
|
||||
@@ -430,6 +441,7 @@ class ServingTokens(GenerateBaseServing):
|
||||
|
||||
try:
|
||||
async for res in result_generator:
|
||||
last_res = res
|
||||
if first_iteration:
|
||||
if res.prompt_token_ids is not None:
|
||||
num_prompt_tokens = len(res.prompt_token_ids)
|
||||
@@ -496,10 +508,10 @@ class ServingTokens(GenerateBaseServing):
|
||||
total_tokens=(num_prompt_tokens + num_generated_tokens[i]),
|
||||
)
|
||||
|
||||
# Omit absent prompt metadata (Rust skips None fields).
|
||||
# Omit fields that are absent from token-bearing chunks.
|
||||
exclude = {
|
||||
name
|
||||
for name in ("prompt_token_ids", "mm_placeholders")
|
||||
for name in ("prompt_token_ids", "mm_placeholders", "metrics")
|
||||
if getattr(chunk, name) is None
|
||||
}
|
||||
yield f"data: {chunk.model_dump_json(exclude=exclude)}\n\n"
|
||||
@@ -517,10 +529,18 @@ class ServingTokens(GenerateBaseServing):
|
||||
)
|
||||
|
||||
if include_usage:
|
||||
per_request_metrics = None
|
||||
if sampling_params.n == 1:
|
||||
spec_stats = build_spec_decoding_metrics(last_res)
|
||||
if spec_stats is not None:
|
||||
per_request_metrics = PerRequestMetrics(
|
||||
speculative_decoding=spec_stats
|
||||
)
|
||||
final_chunk = GenerateStreamResponse(
|
||||
request_id=request_id,
|
||||
choices=[],
|
||||
usage=final_usage_info,
|
||||
metrics=per_request_metrics,
|
||||
)
|
||||
yield f"data: {final_chunk.model_dump_json(exclude_none=True)}\n\n"
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||
apply_gptq_marlin_linear,
|
||||
marlin_act_int8_process_scales,
|
||||
marlin_make_empty,
|
||||
marlin_make_workspace_new,
|
||||
marlin_pad_dim,
|
||||
marlin_pad_qweight,
|
||||
marlin_pad_scales,
|
||||
@@ -91,11 +90,6 @@ class MarlinLinearKernel(MPLinearKernel):
|
||||
size_k, size_n = c.partition_weight_shape
|
||||
padded_n, padded_k = marlin_padded_nk(size_n, size_k, c.group_size)
|
||||
|
||||
# Allocate marlin workspace, reusing existing storage on reload.
|
||||
self.workspace = marlin_make_workspace_new(
|
||||
device, existing=getattr(self, "workspace", None)
|
||||
)
|
||||
|
||||
# Default name since marlin requires empty parameter for zp,
|
||||
# TODO: remove this requirement from marlin (allow optional tensors)
|
||||
if self.w_zp_name is None:
|
||||
@@ -197,7 +191,7 @@ class MarlinLinearKernel(MPLinearKernel):
|
||||
weight=w_q,
|
||||
weight_scale=w_s,
|
||||
weight_zp=w_zp, # type: ignore
|
||||
workspace=self.workspace,
|
||||
workspace=None,
|
||||
wtype=c.weight_type,
|
||||
input_size_per_partition=c.partition_weight_shape[0],
|
||||
output_size_per_partition=c.partition_weight_shape[1],
|
||||
|
||||
@@ -58,7 +58,7 @@ class MarlinMxFp4LinearKernel(MxFp4LinearKernel):
|
||||
weight=layer.weight,
|
||||
weight_scale=layer.weight_scale,
|
||||
weight_global_scale=None,
|
||||
workspace=layer.workspace,
|
||||
workspace=None,
|
||||
size_n=layer.output_size_per_partition,
|
||||
size_k=layer.input_size_per_partition,
|
||||
bias=bias,
|
||||
|
||||
@@ -46,7 +46,7 @@ class MarlinMxfp8LinearKernel(Mxfp8LinearKernel):
|
||||
input=x,
|
||||
weight=layer.weight,
|
||||
weight_scale=layer.weight_scale,
|
||||
workspace=layer.workspace,
|
||||
workspace=None,
|
||||
size_n=layer.output_size_per_partition,
|
||||
size_k=layer.input_size_per_partition,
|
||||
bias=bias,
|
||||
|
||||
@@ -50,7 +50,7 @@ class MarlinNvFp4LinearKernel(NvFp4LinearKernel):
|
||||
weight=layer.weight,
|
||||
weight_scale=layer.weight_scale,
|
||||
weight_global_scale=layer.weight_global_scale,
|
||||
workspace=layer.workspace,
|
||||
workspace=None,
|
||||
size_n=layer.output_size_per_partition,
|
||||
size_k=layer.input_size_per_partition,
|
||||
bias=bias,
|
||||
|
||||
@@ -93,7 +93,7 @@ class MarlinFP8ScaledMMLinearKernel(FP8ScaledMMLinearKernel):
|
||||
input=x,
|
||||
weight=layer.weight,
|
||||
weight_scale=weight_scale,
|
||||
workspace=layer.workspace,
|
||||
workspace=None,
|
||||
size_n=layer.output_size_per_partition,
|
||||
size_k=layer.input_size_per_partition,
|
||||
input_dtype=self.marlin_input_dtype,
|
||||
|
||||
@@ -27,6 +27,7 @@ from vllm.model_executor.layers.fused_moe.moe_align_block_size import (
|
||||
from vllm.model_executor.layers.fused_moe.moe_fused_mul_sum import moe_fused_mul_sum
|
||||
from vllm.model_executor.layers.fused_moe.moe_permute_unpermute import (
|
||||
MoEPermuteScratch,
|
||||
get_moe_permute_scratch,
|
||||
moe_permute,
|
||||
moe_permute_unpermute_supported,
|
||||
moe_unpermute,
|
||||
@@ -176,7 +177,6 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
max_num_tokens=max_num_tokens,
|
||||
num_dispatchers=num_dispatchers,
|
||||
)
|
||||
self._permute_scratch: dict[int, MoEPermuteScratch] = {}
|
||||
|
||||
def init_humming_moe(self):
|
||||
from vllm.utils.humming import get_heuristics_config
|
||||
@@ -259,24 +259,20 @@ class HummingExpertsBase(mk.FusedMoEExpertsModular):
|
||||
if not moe_permute_unpermute_supported():
|
||||
return None
|
||||
|
||||
scratch = self._permute_scratch.get(topk)
|
||||
if scratch is None:
|
||||
max_expanded_rows = (
|
||||
self.moe_config.max_num_tokens
|
||||
* self.moe_config.dp_size
|
||||
* self.moe_config.experts_per_token
|
||||
)
|
||||
scratch = MoEPermuteScratch(
|
||||
max_num_tokens=math.ceil(max_expanded_rows / topk),
|
||||
topk=topk,
|
||||
num_experts=self.moe_config.num_experts,
|
||||
num_local_experts=self.moe_config.num_local_experts,
|
||||
device=torch.device(self.moe_config.device),
|
||||
hidden_size=self.moe_config.hidden_dim,
|
||||
hidden_dtype=self.moe_config.in_dtype,
|
||||
)
|
||||
self._permute_scratch[topk] = scratch
|
||||
return scratch
|
||||
max_expanded_rows = (
|
||||
self.moe_config.max_num_tokens
|
||||
* self.moe_config.dp_size
|
||||
* self.moe_config.experts_per_token
|
||||
)
|
||||
return get_moe_permute_scratch(
|
||||
max_num_tokens=math.ceil(max_expanded_rows / topk),
|
||||
topk=topk,
|
||||
num_experts=self.moe_config.num_experts,
|
||||
num_local_experts=self.moe_config.num_local_experts,
|
||||
device=torch.device(self.moe_config.device),
|
||||
hidden_size=self.moe_config.hidden_dim,
|
||||
hidden_dtype=self.moe_config.in_dtype,
|
||||
)
|
||||
|
||||
def get_global_valid_shape_m(self, topk_ids: torch.Tensor):
|
||||
ctx = get_forward_context()
|
||||
|
||||
@@ -35,7 +35,7 @@ from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
|
||||
from vllm.model_executor.layers.fused_moe.utils import _resize_cache
|
||||
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||
get_marlin_input_dtype,
|
||||
marlin_make_workspace_new,
|
||||
get_marlin_workspace,
|
||||
marlin_moe_intermediate_size,
|
||||
marlin_quant_input,
|
||||
)
|
||||
@@ -95,7 +95,7 @@ def _fused_marlin_moe(
|
||||
N = marlin_moe_intermediate_size(w1, w2)
|
||||
w13_num_shards = 2 if activation.is_gated else 1
|
||||
if workspace is None:
|
||||
workspace = marlin_make_workspace_new(hidden_states.device, 4)
|
||||
workspace = get_marlin_workspace(hidden_states.device)
|
||||
|
||||
if intermediate_cache13 is None:
|
||||
intermediate_cache13 = torch.empty(
|
||||
|
||||
@@ -5,6 +5,11 @@ from dataclasses import dataclass, field
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.v1.worker.workspace import (
|
||||
current_workspace_manager,
|
||||
is_workspace_manager_initialized,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MoEPermuteScratch:
|
||||
@@ -102,6 +107,48 @@ class MoEPermuteScratch:
|
||||
return topk_ids_int32
|
||||
|
||||
|
||||
def get_moe_permute_scratch(
|
||||
*,
|
||||
max_num_tokens: int,
|
||||
topk: int,
|
||||
num_experts: int,
|
||||
num_local_experts: int,
|
||||
device: torch.device,
|
||||
hidden_size: int | None = None,
|
||||
hidden_dtype: torch.dtype | None = None,
|
||||
) -> MoEPermuteScratch:
|
||||
"""Share scratch across sequential layers in the current ubatch and lane.
|
||||
|
||||
Without a workspace manager, allocate new scratch for each call.
|
||||
"""
|
||||
|
||||
def create_scratch() -> MoEPermuteScratch:
|
||||
return MoEPermuteScratch(
|
||||
max_num_tokens=max_num_tokens,
|
||||
topk=topk,
|
||||
num_experts=num_experts,
|
||||
num_local_experts=num_local_experts,
|
||||
device=device,
|
||||
hidden_size=hidden_size,
|
||||
hidden_dtype=hidden_dtype,
|
||||
)
|
||||
|
||||
if not is_workspace_manager_initialized():
|
||||
return create_scratch()
|
||||
|
||||
key = (
|
||||
MoEPermuteScratch,
|
||||
max_num_tokens,
|
||||
topk,
|
||||
num_experts,
|
||||
num_local_experts,
|
||||
device,
|
||||
hidden_size,
|
||||
hidden_dtype,
|
||||
)
|
||||
return current_workspace_manager().get_persistent_resource(key, create_scratch)
|
||||
|
||||
|
||||
def moe_permute(
|
||||
hidden_states: torch.Tensor,
|
||||
a1q_scale: torch.Tensor | None,
|
||||
|
||||
@@ -14,6 +14,12 @@ from vllm.v1.worker.workspace import current_workspace_manager
|
||||
|
||||
RADIX_TOPK_WORKSPACE_SIZE = 1024 * 1024
|
||||
|
||||
# cooperative_topk's hard row limit: one cluster wave covers at most this many
|
||||
# rows. "auto" uses cooperative_topk for every batch within the limit and falls
|
||||
# back to persistent_topk past it; explicit ``cooperative`` requests are
|
||||
# validated against the same bound.
|
||||
AUTO_COOPERATIVE_MAX_ROWS = 64
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DeepSelect (vllm._deepselect_C)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -209,8 +215,13 @@ class SparseIndexerTopk(torch.nn.Module):
|
||||
def _resolve_auto(
|
||||
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."""
|
||||
"""The priority chain: cooperative -> persistent -> per_row.
|
||||
deep_select/flashinfer/torch are opt-in only.
|
||||
|
||||
cooperative_topk is preferred whenever it is applicable, i.e. within
|
||||
its AUTO_COOPERATIVE_MAX_ROWS row limit; larger batches go to
|
||||
persistent_topk.
|
||||
"""
|
||||
if not self._cooperative_constraints(logits, topk_tokens, num_rows):
|
||||
return "cooperative"
|
||||
if self._is_cuda and topk_tokens in (512, 1024, 2048):
|
||||
@@ -228,8 +239,10 @@ class SparseIndexerTopk(torch.nn.Module):
|
||||
failures.append(
|
||||
f"topk_tokens must be in (512, 1024, 2048), got {topk_tokens}"
|
||||
)
|
||||
if num_rows > 64:
|
||||
failures.append(f"num_rows must be <= 64, got {num_rows}")
|
||||
if num_rows > AUTO_COOPERATIVE_MAX_ROWS:
|
||||
failures.append(
|
||||
f"num_rows must be <= {AUTO_COOPERATIVE_MAX_ROWS}, got {num_rows}"
|
||||
)
|
||||
if logits.stride(0) % 4 != 0:
|
||||
failures.append(
|
||||
f"logits.stride(0) must be divisible by 4, got {logits.stride(0)}"
|
||||
@@ -293,13 +306,18 @@ class SparseIndexerTopk(torch.nn.Module):
|
||||
(topk_workspace,) = current_workspace_manager().get_simultaneous(
|
||||
((RADIX_TOPK_WORKSPACE_SIZE,), torch.uint8),
|
||||
)
|
||||
# persistent_topk's last argument is the host-side "max seq_len
|
||||
# across rows" bound (it gates the sampled_topk path and clamps
|
||||
# per-row lengths), not the padded row width: logits is sized to
|
||||
# max_model_len, so passing its width would incorrectly enable the
|
||||
# long-row kernels on short-context batches.
|
||||
torch.ops._C.persistent_topk(
|
||||
logits,
|
||||
seq_lens,
|
||||
topk_indices,
|
||||
topk_workspace,
|
||||
topk_tokens,
|
||||
logits.shape[1],
|
||||
max_seq_len,
|
||||
)
|
||||
elif backend == "flashinfer":
|
||||
# Deferred: importing flashinfer initializes CUDA at import time.
|
||||
|
||||
@@ -167,6 +167,8 @@ def _log_gdn_backend_decision(
|
||||
head_k_dim,
|
||||
)
|
||||
return
|
||||
elif current_platform.is_xpu():
|
||||
return
|
||||
|
||||
chosen = {
|
||||
"flashinfer": "FlashInfer",
|
||||
@@ -524,6 +526,8 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
|
||||
self.gdn_decode_kernel = "triton"
|
||||
elif current_platform.is_cpu():
|
||||
self.gdn_decode_kernel = "CPU"
|
||||
elif current_platform.is_xpu():
|
||||
self.gdn_decode_kernel = "XPU"
|
||||
|
||||
self.enable_fused_gdn_decode = self.gdn_decode_kernel == "cuda"
|
||||
logger.info_once("GDN decode kernel: %s", self.gdn_decode_kernel)
|
||||
|
||||
@@ -48,7 +48,6 @@ from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||
check_marlin_supports_layer,
|
||||
check_moe_marlin_supports_layer,
|
||||
get_marlin_input_dtype,
|
||||
marlin_make_workspace_new,
|
||||
verify_marlin_supported,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
@@ -642,9 +641,6 @@ class AutoAWQMoEMethod(FusedMoEMethodBase):
|
||||
layer.register_parameter("w2_qzeros", w2_qzeros)
|
||||
set_weight_attrs(w2_qzeros, extra_weight_attrs)
|
||||
|
||||
device = layer.w13_qweight.device
|
||||
layer.workspace = marlin_make_workspace_new(device, 4)
|
||||
|
||||
def process_weights_after_loading(self, layer: RoutedExperts) -> None:
|
||||
converted = convert_to_wna16_moe_kernel_format(
|
||||
backend=self.wna16_moe_backend,
|
||||
|
||||
@@ -16,7 +16,6 @@ from vllm.model_executor.kernels.linear import (
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe import (
|
||||
FusedMoEConfig,
|
||||
FusedMoEExpertsModular,
|
||||
FusedMoEMethodBase,
|
||||
FusedMoEQuantConfig,
|
||||
FusedMoeWeightScaleSupported,
|
||||
@@ -46,7 +45,6 @@ from vllm.model_executor.layers.quantization.utils.gptq_utils import (
|
||||
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||
check_moe_marlin_supports_layer,
|
||||
get_marlin_input_dtype,
|
||||
marlin_make_workspace_new,
|
||||
marlin_repeat_scales_on_all_ranks,
|
||||
verify_marlin_supported,
|
||||
)
|
||||
@@ -601,12 +599,6 @@ class AutoGPTQMoEMethod(FusedMoEMethodBase):
|
||||
layer.register_parameter("w2_bias", w2_bias)
|
||||
set_weight_attrs(w2_bias, extra_weight_attrs)
|
||||
|
||||
if self.experts_cls is not None and issubclass(
|
||||
self.experts_cls, FusedMoEExpertsModular
|
||||
):
|
||||
device = layer.w13_qweight.device
|
||||
layer.workspace = marlin_make_workspace_new(device, 4)
|
||||
|
||||
def process_weights_after_loading(self, layer: RoutedExperts) -> None:
|
||||
def replace_or_register(name: str, val: torch.Tensor | None):
|
||||
if val is None:
|
||||
|
||||
-14
@@ -11,7 +11,6 @@ from compressed_tensors.quantization import (
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe import (
|
||||
FusedMoEExpertsModular,
|
||||
RoutedExperts,
|
||||
SharedExperts,
|
||||
)
|
||||
@@ -36,7 +35,6 @@ from vllm.model_executor.layers.quantization.compressed_tensors.schemes.compress
|
||||
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||
check_moe_marlin_supports_config,
|
||||
get_marlin_input_dtype,
|
||||
marlin_make_workspace_new,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
GroupShape,
|
||||
@@ -466,18 +464,6 @@ class CompressedTensorsWNA16MoEMethod(CompressedTensorsMoEMethod):
|
||||
torch.nn.Parameter(w2_input_global_scale, requires_grad=False),
|
||||
)
|
||||
|
||||
# Marlin workspace — only needed for Marlin-family backends, not emulation.
|
||||
if (
|
||||
self.experts_cls is not None
|
||||
and issubclass(self.experts_cls, FusedMoEExpertsModular)
|
||||
and self.wna16_backend != WNA16MoEBackend.EMULATION
|
||||
):
|
||||
layer.workspace = marlin_make_workspace_new(
|
||||
layer.w13_weight_packed.device,
|
||||
4,
|
||||
existing=getattr(layer, "workspace", None),
|
||||
)
|
||||
|
||||
# Alias packed weights to w13_weight/w2_weight for the modular kernel interface
|
||||
layer.w13_weight = layer.w13_weight_packed
|
||||
layer.w2_weight = layer.w2_weight_packed
|
||||
|
||||
@@ -8,7 +8,6 @@ import numpy
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.distributed.utils import verify_group_size_divides_partition
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe import RoutedExperts
|
||||
@@ -23,6 +22,7 @@ from vllm.platforms import current_platform
|
||||
from vllm.scalar_type import ScalarType, scalar_types
|
||||
from vllm.utils.math_utils import round_up
|
||||
from vllm.utils.platform_utils import num_compute_units
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
from .quant_utils import pack_cols, unpack_cols
|
||||
|
||||
@@ -32,6 +32,7 @@ GPTQ_MARLIN_TILE = 16
|
||||
GPTQ_MARLIN_MIN_THREAD_N = 64
|
||||
GPTQ_MARLIN_MIN_THREAD_K = 128
|
||||
GPTQ_MARLIN_MAX_PARALLEL = 16
|
||||
MARLIN_MAX_BLOCKS_PER_SM = 4
|
||||
|
||||
MARLIN_SUPPORTED_GROUP_SIZES = [-1, 32, 64, 128]
|
||||
|
||||
@@ -407,29 +408,96 @@ def marlin_moe_intermediate_size(w1_packed: torch.Tensor, w2_packed: torch.Tenso
|
||||
def marlin_make_workspace_new(
|
||||
device: torch.device,
|
||||
max_blocks_per_sm: int = 1,
|
||||
existing: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
# In the new marlin kernel, we use the num of threadblocks as workspace
|
||||
# size. The num of threadblocks is sms_count * max_blocks_per_sm.
|
||||
sms = num_compute_units(device.index)
|
||||
size = sms * max_blocks_per_sm
|
||||
# On weight reload, reuse the existing storage so the workspace address
|
||||
# captured by CUDA graphs stays valid.
|
||||
if existing is not None:
|
||||
if (
|
||||
existing.device != device
|
||||
or existing.dtype != torch.int
|
||||
or existing.numel() != size
|
||||
):
|
||||
raise ValueError(
|
||||
f"Existing Marlin workspace is incompatible "
|
||||
f"(device={existing.device}, dtype={existing.dtype}, "
|
||||
f"numel={existing.numel()}; expected device={device}, "
|
||||
f"dtype={torch.int}, numel={size}). Reload must reuse the "
|
||||
f"workspace storage captured by CUDA graphs."
|
||||
)
|
||||
return existing.zero_()
|
||||
return torch.zeros(size, dtype=torch.int, device=device, requires_grad=False)
|
||||
return torch.zeros(sms * max_blocks_per_sm, dtype=torch.int, device=device)
|
||||
|
||||
|
||||
def get_marlin_workspace(device: torch.device) -> torch.Tensor:
|
||||
"""Get zero-initialized locks for the current stream, ubatch, and lane.
|
||||
|
||||
Marlin resets its locks after each call, so ordered calls can reuse them.
|
||||
"""
|
||||
from vllm.utils.torch_utils import current_stream
|
||||
from vllm.v1.worker.workspace import (
|
||||
current_workspace_manager,
|
||||
is_workspace_manager_initialized,
|
||||
)
|
||||
|
||||
if not is_workspace_manager_initialized():
|
||||
return marlin_make_workspace_new(device, MARLIN_MAX_BLOCKS_PER_SM)
|
||||
|
||||
return current_workspace_manager().get_persistent(
|
||||
("marlin_locks", current_stream()),
|
||||
(num_compute_units(device.index) * MARLIN_MAX_BLOCKS_PER_SM,),
|
||||
torch.int,
|
||||
zero_init=True,
|
||||
)
|
||||
|
||||
|
||||
def _marlin_gemm(
|
||||
a: torch.Tensor,
|
||||
b_q_weight: torch.Tensor,
|
||||
b_bias: torch.Tensor | None,
|
||||
b_scales: torch.Tensor,
|
||||
a_scales: torch.Tensor | None,
|
||||
global_scale: torch.Tensor | None,
|
||||
b_zeros: torch.Tensor | None,
|
||||
workspace: torch.Tensor | None,
|
||||
b_q_type_id: int,
|
||||
size_m: int,
|
||||
size_n: int,
|
||||
size_k: int,
|
||||
use_atomic_add: bool = False,
|
||||
use_fp32_reduce: bool = False,
|
||||
is_zp_float: bool = False,
|
||||
) -> torch.Tensor:
|
||||
if workspace is None:
|
||||
workspace = get_marlin_workspace(a.device)
|
||||
return torch.ops._C.marlin_gemm(
|
||||
a,
|
||||
None,
|
||||
b_q_weight,
|
||||
b_bias,
|
||||
b_scales,
|
||||
a_scales,
|
||||
global_scale,
|
||||
b_zeros,
|
||||
workspace,
|
||||
b_q_type_id,
|
||||
size_m,
|
||||
size_n,
|
||||
size_k,
|
||||
use_atomic_add,
|
||||
use_fp32_reduce,
|
||||
is_zp_float,
|
||||
)
|
||||
|
||||
|
||||
def _marlin_gemm_fake(
|
||||
a: torch.Tensor,
|
||||
b_q_weight: torch.Tensor,
|
||||
b_bias: torch.Tensor | None,
|
||||
b_scales: torch.Tensor,
|
||||
a_scales: torch.Tensor | None,
|
||||
global_scale: torch.Tensor | None,
|
||||
b_zeros: torch.Tensor | None,
|
||||
workspace: torch.Tensor | None,
|
||||
b_q_type_id: int,
|
||||
size_m: int,
|
||||
size_n: int,
|
||||
size_k: int,
|
||||
use_atomic_add: bool = False,
|
||||
use_fp32_reduce: bool = False,
|
||||
is_zp_float: bool = False,
|
||||
) -> torch.Tensor:
|
||||
dtype = a.dtype if a.dtype in (torch.float16, torch.bfloat16) else b_scales.dtype
|
||||
return torch.empty((size_m, size_n), device=a.device, dtype=dtype)
|
||||
|
||||
|
||||
direct_register_custom_op("marlin_gemm", _marlin_gemm, fake_impl=_marlin_gemm_fake)
|
||||
|
||||
|
||||
def marlin_repeat_scales_on_all_ranks(group_size: int, is_row_parallel: bool) -> bool:
|
||||
@@ -686,7 +754,7 @@ def apply_gptq_marlin_linear(
|
||||
weight: torch.Tensor,
|
||||
weight_scale: torch.Tensor,
|
||||
weight_zp: torch.Tensor,
|
||||
workspace: torch.Tensor,
|
||||
workspace: torch.Tensor | None,
|
||||
wtype: ScalarType,
|
||||
output_size_per_partition: int,
|
||||
input_size_per_partition: int,
|
||||
@@ -723,9 +791,8 @@ def apply_gptq_marlin_linear(
|
||||
|
||||
reshaped_x, a_scales = marlin_quant_input(reshaped_x, input_dtype)
|
||||
|
||||
output = ops.marlin_gemm(
|
||||
output = torch.ops.vllm.marlin_gemm(
|
||||
reshaped_x,
|
||||
None,
|
||||
weight,
|
||||
bias,
|
||||
weight_scale,
|
||||
@@ -733,7 +800,7 @@ def apply_gptq_marlin_linear(
|
||||
None,
|
||||
weight_zp,
|
||||
workspace,
|
||||
wtype,
|
||||
wtype.id,
|
||||
size_m=reshaped_x.shape[0],
|
||||
size_n=padded_n,
|
||||
size_k=padded_k,
|
||||
|
||||
@@ -10,7 +10,6 @@ from vllm.model_executor.layers.fused_moe.routed_experts import RoutedExperts
|
||||
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||
USE_FP32_REDUCE_DEFAULT,
|
||||
get_marlin_input_dtype,
|
||||
marlin_make_workspace_new,
|
||||
marlin_pad_dim,
|
||||
marlin_pad_qweight,
|
||||
marlin_pad_scales,
|
||||
@@ -161,7 +160,7 @@ def apply_fp4_marlin_linear(
|
||||
weight: torch.Tensor,
|
||||
weight_scale: torch.Tensor,
|
||||
weight_global_scale: torch.Tensor | None,
|
||||
workspace: torch.Tensor,
|
||||
workspace: torch.Tensor | None,
|
||||
size_n: int,
|
||||
size_k: int,
|
||||
bias: torch.Tensor | None = None,
|
||||
@@ -196,9 +195,8 @@ def apply_fp4_marlin_linear(
|
||||
|
||||
inputs, a_scales = marlin_quant_input(inputs, torch.float8_e4m3fn)
|
||||
|
||||
output = ops.marlin_gemm(
|
||||
output = torch.ops.vllm.marlin_gemm(
|
||||
a=inputs,
|
||||
c=None,
|
||||
b_q_weight=weight,
|
||||
b_bias=bias,
|
||||
b_scales=weight_scale,
|
||||
@@ -206,7 +204,7 @@ def apply_fp4_marlin_linear(
|
||||
global_scale=weight_global_scale,
|
||||
b_zeros=None,
|
||||
workspace=workspace,
|
||||
b_q_type=scalar_types.float4_e2m1f,
|
||||
b_q_type_id=scalar_types.float4_e2m1f.id,
|
||||
size_m=reshaped_x.size(0),
|
||||
size_n=padded_n,
|
||||
size_k=padded_k,
|
||||
@@ -237,13 +235,6 @@ def prepare_fp4_layer_for_marlin(
|
||||
|
||||
assert layer.weight.shape == (part_size_n, part_size_k // 2)
|
||||
|
||||
device = layer.weight.device
|
||||
|
||||
# WORKSPACE
|
||||
layer.workspace = marlin_make_workspace_new(
|
||||
device, existing=getattr(layer, "workspace", None)
|
||||
)
|
||||
|
||||
# WEIGHT
|
||||
# Repack weights to marlin format
|
||||
qweight = layer.weight.view(torch.int32).T.contiguous()
|
||||
@@ -389,15 +380,9 @@ def prepare_nvfp4_moe_layer_for_marlin(
|
||||
return x
|
||||
return torch.nn.functional.pad(x, (0, (padded_N - N) // packing))
|
||||
|
||||
device = w13.device
|
||||
param_dtype = layer.params_dtype
|
||||
is_a_8bit = input_dtype is not None and input_dtype.itemsize == 1
|
||||
|
||||
# WORKSPACE
|
||||
layer.workspace = marlin_make_workspace_new(
|
||||
device, 4, existing=getattr(layer, "workspace", None)
|
||||
)
|
||||
|
||||
# WEIGHT
|
||||
# Repack weights to marlin format
|
||||
def repack_weight(weight: torch.Tensor, name: str) -> torch.Tensor:
|
||||
@@ -481,12 +466,7 @@ def prepare_moe_fp4_layer_for_marlin(
|
||||
k = layer.moe_config.hidden_dim
|
||||
n = layer.moe_config.intermediate_size_per_partition
|
||||
|
||||
# WORKSPACE
|
||||
device = layer.w13_weight.device
|
||||
param_dtype = layer.params_dtype
|
||||
layer.workspace = marlin_make_workspace_new(
|
||||
device, 4, existing=getattr(layer, "workspace", None)
|
||||
)
|
||||
is_a_8bit = input_dtype is not None and input_dtype.itemsize == 1
|
||||
|
||||
# WEIGHT
|
||||
|
||||
@@ -9,7 +9,6 @@ from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.utils.marlin_utils import (
|
||||
USE_FP32_REDUCE_DEFAULT,
|
||||
get_marlin_input_dtype,
|
||||
marlin_make_workspace_new,
|
||||
marlin_moe_padded_intermediate,
|
||||
marlin_pad_dim,
|
||||
marlin_pad_qweight,
|
||||
@@ -50,7 +49,7 @@ def apply_fp8_marlin_linear(
|
||||
input: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
weight_scale: torch.Tensor,
|
||||
workspace: torch.Tensor,
|
||||
workspace: torch.Tensor | None,
|
||||
size_n: int,
|
||||
size_k: int,
|
||||
bias: torch.Tensor | None,
|
||||
@@ -80,9 +79,8 @@ def apply_fp8_marlin_linear(
|
||||
# inputs, a_scales = marlin_quant_input(inputs, torch.float8_e4m3fn)
|
||||
raise RuntimeError("Marlin W8A8 is not supported.")
|
||||
|
||||
output = ops.marlin_gemm(
|
||||
output = torch.ops.vllm.marlin_gemm(
|
||||
a=inputs,
|
||||
c=None,
|
||||
b_q_weight=weight,
|
||||
b_bias=bias,
|
||||
b_scales=weight_scale,
|
||||
@@ -90,7 +88,7 @@ def apply_fp8_marlin_linear(
|
||||
global_scale=None,
|
||||
b_zeros=None,
|
||||
workspace=workspace,
|
||||
b_q_type=scalar_types.float8_e4m3fn,
|
||||
b_q_type_id=scalar_types.float8_e4m3fn.id,
|
||||
size_m=reshaped_x.size(0),
|
||||
size_n=padded_n,
|
||||
size_k=padded_k,
|
||||
@@ -127,13 +125,6 @@ def prepare_fp8_layer_for_marlin(
|
||||
else:
|
||||
assert layer.weight.shape == (part_size_n, part_size_k)
|
||||
|
||||
device = layer.weight.device
|
||||
|
||||
# WORKSPACE
|
||||
layer.workspace = marlin_make_workspace_new(
|
||||
device, existing=getattr(layer, "workspace", None)
|
||||
)
|
||||
|
||||
# WEIGHT
|
||||
# Repack weights to marlin format
|
||||
qweight = pack_fp8_to_int32(layer.weight, size_k_first)
|
||||
@@ -241,12 +232,7 @@ def prepare_fp8_moe_layer_for_marlin(
|
||||
w13_weight_scale: torch.Tensor,
|
||||
w2_weight_scale: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Shuffle weights and scales into marlin format.
|
||||
|
||||
Note that this function has the side effect of adding a `workspace`
|
||||
attribute to the layer. This `workspace` does not need to be
|
||||
registered as a Parameter as it is not used during weight reloading.
|
||||
"""
|
||||
"""Shuffle weights and scales into marlin format."""
|
||||
logger.warning_once(
|
||||
"Your GPU does not have native support for FP8 computation but "
|
||||
"FP8 quantization is being used. Weight-only FP8 compression will "
|
||||
@@ -272,12 +258,6 @@ def prepare_fp8_moe_layer_for_marlin(
|
||||
w13_weight = _moe_pad_shard_rows(w13_weight, n, padded_n)
|
||||
w2_weight = _moe_pad_last(w2_weight, n, padded_n)
|
||||
|
||||
# WORKSPACE
|
||||
device = layer.w13_weight.device
|
||||
layer.workspace = marlin_make_workspace_new(
|
||||
device, 4, existing=getattr(layer, "workspace", None)
|
||||
)
|
||||
|
||||
# WEIGHT
|
||||
# Repack weights to marlin format
|
||||
def repack_weight(name: str, weight: torch.Tensor) -> torch.Tensor:
|
||||
@@ -396,7 +376,7 @@ def apply_mxfp8_marlin_linear(
|
||||
input: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
weight_scale: torch.Tensor,
|
||||
workspace: torch.Tensor,
|
||||
workspace: torch.Tensor | None,
|
||||
size_n: int,
|
||||
size_k: int,
|
||||
bias: torch.Tensor | None = None,
|
||||
@@ -416,9 +396,8 @@ def apply_mxfp8_marlin_linear(
|
||||
dtype=input.dtype,
|
||||
)
|
||||
|
||||
output = ops.marlin_gemm(
|
||||
output = torch.ops.vllm.marlin_gemm(
|
||||
a=reshaped_x,
|
||||
c=None,
|
||||
b_q_weight=weight,
|
||||
b_bias=bias,
|
||||
b_scales=weight_scale,
|
||||
@@ -426,7 +405,7 @@ def apply_mxfp8_marlin_linear(
|
||||
global_scale=None,
|
||||
b_zeros=None,
|
||||
workspace=workspace,
|
||||
b_q_type=scalar_types.float8_e4m3fn,
|
||||
b_q_type_id=scalar_types.float8_e4m3fn.id,
|
||||
size_m=reshaped_x.size(0),
|
||||
size_n=padded_n,
|
||||
size_k=padded_k,
|
||||
@@ -451,13 +430,6 @@ def prepare_mxfp8_layer_for_marlin(layer: torch.nn.Module) -> None:
|
||||
group_size = 32 # MX standard block size
|
||||
padded_n, padded_k = marlin_padded_nk(part_size_n, part_size_k, group_size)
|
||||
|
||||
device = layer.weight.device
|
||||
|
||||
# WORKSPACE
|
||||
layer.workspace = marlin_make_workspace_new(
|
||||
device, existing=getattr(layer, "workspace", None)
|
||||
)
|
||||
|
||||
# WEIGHT - repack FP8 weights to Marlin format
|
||||
qweight = pack_fp8_to_int32(layer.weight, size_k_first=False)
|
||||
qweight = qweight.T.contiguous()
|
||||
@@ -512,7 +484,7 @@ def prepare_mxfp8_moe_layer_for_marlin(
|
||||
"""Repack MXFP8 MoE weights and scales into Marlin kernel format.
|
||||
|
||||
Args:
|
||||
layer: MoE layer (used to read params_dtype and attach workspace).
|
||||
layer: MoE layer.
|
||||
w13: [E, 2*N, K] float8_e4m3fn weights.
|
||||
w2: [E, K, N] float8_e4m3fn weights.
|
||||
w13_scale: [E, 2*N, K//32] uint8 e8m0 scales.
|
||||
@@ -537,13 +509,8 @@ def prepare_mxfp8_moe_layer_for_marlin(
|
||||
n = padded_n
|
||||
w13_n = w13.shape[1]
|
||||
|
||||
device = w13.device
|
||||
param_dtype = torch.get_default_dtype()
|
||||
|
||||
layer.workspace = marlin_make_workspace_new(
|
||||
device, 4, existing=getattr(layer, "workspace", None)
|
||||
)
|
||||
|
||||
def repack_weight(weight: torch.Tensor, name: str) -> torch.Tensor:
|
||||
if "w13" in name:
|
||||
size_n, size_k = w13_n, k
|
||||
|
||||
@@ -543,7 +543,7 @@ def _compiled_sample_step(
|
||||
if tp_size > 1:
|
||||
soft_embeds = torch.ops.vllm.all_reduce(soft_embeds, group_name=tp_group_name)
|
||||
soft_embeds = soft_embeds * normalizer
|
||||
sc_embeds[decode_slots] = soft_embeds * sc_keep
|
||||
sc_embeds[decode_slots] = (soft_embeds * sc_keep).to(sc_embeds.dtype)
|
||||
|
||||
# Overwrite canvas with argmax for newly converged denoise requests
|
||||
newly_converged = (converged & is_denoise).unsqueeze(1)
|
||||
|
||||
@@ -27,6 +27,7 @@ from vllm.model_executor.layers.fused_moe import (
|
||||
FusedMoEFactory,
|
||||
fused_moe_make_expert_params_mapping,
|
||||
)
|
||||
from vllm.model_executor.layers.fused_moe.router.gate_linear import GateLinear
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import (
|
||||
MergedColumnParallelLinear,
|
||||
@@ -156,14 +157,16 @@ class MiMoV2MoE(nn.Module):
|
||||
|
||||
dtype = getattr(config, "moe_router_dtype", "float32")
|
||||
self.gate_dtype = str_dtype_to_torch_dtype(dtype)
|
||||
self.gate = nn.Linear(
|
||||
self.gate = GateLinear(
|
||||
config.hidden_size,
|
||||
config.n_routed_experts,
|
||||
bias=False,
|
||||
dtype=self.gate_dtype,
|
||||
params_dtype=self.gate_dtype,
|
||||
out_dtype=torch.float32,
|
||||
prefix=f"{prefix}.gate",
|
||||
)
|
||||
self.gate.e_score_correction_bias = nn.Parameter(
|
||||
torch.empty(config.n_routed_experts, dtype=self.gate_dtype)
|
||||
torch.empty(config.n_routed_experts, dtype=self.gate.out_dtype)
|
||||
)
|
||||
|
||||
self.experts = FusedMoEFactory(
|
||||
@@ -182,7 +185,7 @@ class MiMoV2MoE(nn.Module):
|
||||
num_expert_group=config.n_group,
|
||||
topk_group=config.topk_group,
|
||||
scoring_func="sigmoid",
|
||||
router_logits_dtype=self.gate_dtype,
|
||||
router_logits_dtype=self.gate.out_dtype,
|
||||
)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
@@ -198,7 +201,7 @@ class MiMoV2MoE(nn.Module):
|
||||
gate_input = hidden_states.to(self.gate_dtype)
|
||||
else:
|
||||
gate_input = hidden_states
|
||||
router_logits = self.gate(gate_input)
|
||||
router_logits, _ = self.gate(gate_input)
|
||||
final_hidden_states = self.experts(
|
||||
hidden_states=hidden_states, router_logits=router_logits
|
||||
)
|
||||
|
||||
@@ -52,6 +52,7 @@ from vllm.transformers_utils.processors.mimo_v2_omni import (
|
||||
|
||||
from .interfaces import (
|
||||
MultiModalEmbeddings,
|
||||
SupportsEagle3,
|
||||
SupportsMultiModal,
|
||||
SupportsPP,
|
||||
SupportsQuant,
|
||||
@@ -1209,7 +1210,9 @@ class MiMoV2OmniDummyInputsBuilder(BaseDummyInputsBuilder[MiMoV2OmniProcessingIn
|
||||
info=MiMoV2OmniProcessingInfo,
|
||||
dummy_inputs=MiMoV2OmniDummyInputsBuilder,
|
||||
)
|
||||
class MiMoV2OmniForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, SupportsQuant):
|
||||
class MiMoV2OmniForCausalLM(
|
||||
nn.Module, SupportsMultiModal, SupportsPP, SupportsQuant, SupportsEagle3
|
||||
):
|
||||
# To ensure correct weight loading and mapping.
|
||||
hf_to_vllm_mapper = WeightsMapper(
|
||||
orig_to_new_prefix={
|
||||
|
||||
@@ -168,6 +168,7 @@ class DFlashQwen3Attention(nn.Module):
|
||||
rms_norm_eps: float = 1e-06,
|
||||
attention_bias: bool = False,
|
||||
add_swa_attention_sink_bias: bool = False,
|
||||
v_scale: float | None = None,
|
||||
sliding_window: int | None = None,
|
||||
causal: bool = False,
|
||||
is_neox_style: bool = True,
|
||||
@@ -193,6 +194,7 @@ class DFlashQwen3Attention(nn.Module):
|
||||
self.q_size = self.num_heads * self.head_dim
|
||||
self.kv_size = self.num_kv_heads * self.head_dim
|
||||
self.scaling = self.head_dim**-0.5
|
||||
self.v_scale = v_scale
|
||||
|
||||
self.qkv_proj = QKVParallelLinear(
|
||||
hidden_size,
|
||||
@@ -264,6 +266,8 @@ class DFlashQwen3Attention(nn.Module):
|
||||
|
||||
q, k = self.rotary_emb(positions, q, k)
|
||||
|
||||
if self.v_scale is not None:
|
||||
v = v * self.v_scale
|
||||
attn_output = self.attn(q, k, v)
|
||||
output, _ = self.o_proj(attn_output)
|
||||
return output
|
||||
@@ -312,6 +316,7 @@ class DFlashQwen3DecoderLayer(nn.Module):
|
||||
rms_norm_eps=config.rms_norm_eps,
|
||||
attention_bias=getattr(config, "attention_bias", False),
|
||||
add_swa_attention_sink_bias=add_swa_attention_sink_bias,
|
||||
v_scale=dflash_config.get("attention_value_scale"),
|
||||
sliding_window=sliding_window,
|
||||
causal=causal,
|
||||
is_neox_style=is_neox_style,
|
||||
@@ -633,6 +638,10 @@ class DFlashQwen3Model(nn.Module):
|
||||
if context_slot_mapping is None:
|
||||
return
|
||||
|
||||
v_scale = getattr(self.layers[0].self_attn, "v_scale", None)
|
||||
if v_scale is not None:
|
||||
all_v.mul_(v_scale)
|
||||
|
||||
# --- Per-layer cache insert ---
|
||||
all_k_final = all_k_flat.view(L, num_ctx, nkv, hd)
|
||||
per_layer = isinstance(context_slot_mapping, (list, tuple))
|
||||
|
||||
@@ -8,6 +8,7 @@ import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.models.interfaces import SupportsLoRA
|
||||
from vllm.model_executor.models.qwen3 import Qwen3Model
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader, maybe_prefix
|
||||
from vllm.sequence import IntermediateTensors
|
||||
@@ -15,7 +16,7 @@ from vllm.sequence import IntermediateTensors
|
||||
WeightItem = tuple[str, torch.Tensor]
|
||||
|
||||
|
||||
class VoyageQwen3BidirectionalEmbedModel(nn.Module):
|
||||
class VoyageQwen3BidirectionalEmbedModel(nn.Module, SupportsLoRA):
|
||||
"""Qwen3Model + Voyage embedding head + bidirectional attention.
|
||||
|
||||
Checkpoint conventions (HF):
|
||||
@@ -30,6 +31,11 @@ class VoyageQwen3BidirectionalEmbedModel(nn.Module):
|
||||
- No "model." prefix
|
||||
"""
|
||||
|
||||
packed_modules_mapping = {
|
||||
"qkv_proj": ["q_proj", "k_proj", "v_proj"],
|
||||
"gate_up_proj": ["gate_proj", "up_proj"],
|
||||
}
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
self.config = vllm_config.model_config.hf_config
|
||||
|
||||
@@ -7,6 +7,7 @@ from typing import cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm import envs
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_world_size,
|
||||
tensor_model_parallel_all_reduce,
|
||||
@@ -42,6 +43,49 @@ from vllm.v1.worker.workspace import current_workspace_manager
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _wo_a_block_scale_to_e8m0(scale: torch.Tensor) -> torch.Tensor | None:
|
||||
"""Normalize checkpoint WO_A scales to raw OCP MX E8M0 bytes.
|
||||
|
||||
E8M0 is an unsigned exponent-only scale format with bias 127. A finite
|
||||
encoded byte ``b`` in ``[0, 254]`` represents ``2 ** (b - 127)``;
|
||||
``0xFF`` is reserved for NaN. This is the vendor-neutral OCP encoding used
|
||||
by AMD AITER/OPUS, not an NVIDIA-specific convention. Reference: OCP
|
||||
Microscaling Formats (MX) Specification, section 5.4.1:
|
||||
https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf
|
||||
|
||||
Loaders may preserve the encoded byte as ``float8_e8m0fnu``/``uint8``,
|
||||
or decode it to a floating-point power of two. Floating-point inputs are
|
||||
accepted only when the original E8M0 byte can be recovered losslessly.
|
||||
This function does not quantize or round arbitrary scales.
|
||||
"""
|
||||
if scale.dtype == torch.float8_e8m0fnu:
|
||||
# Reinterpret the native E8M0 storage. ``to(uint8)`` would perform a
|
||||
# numeric conversion instead of preserving the encoded exponent byte.
|
||||
return scale.view(torch.uint8).contiguous()
|
||||
if scale.dtype == torch.uint8:
|
||||
# The checkpoint loader already exposed the E8M0 wire representation.
|
||||
return scale.contiguous()
|
||||
if not scale.dtype.is_floating_point:
|
||||
return None
|
||||
|
||||
scale_f32 = scale.detach().float()
|
||||
if not bool(torch.isfinite(scale_f32).all()) or bool((scale_f32 <= 0).any()):
|
||||
return None
|
||||
|
||||
# With no mantissa, E8M0 can represent only exact powers of two. Rebuild
|
||||
# the value before encoding so this adapter never silently quantizes a
|
||||
# general floating-point checkpoint scale.
|
||||
exponent = torch.round(torch.log2(scale_f32))
|
||||
if not torch.equal(torch.exp2(exponent), scale_f32):
|
||||
return None
|
||||
|
||||
encoded = exponent.to(torch.int32) + 127
|
||||
# 0xFF is NaN in OCP E8M0, not a finite exponent.
|
||||
if int(encoded.min()) < 0 or int(encoded.max()) > 254:
|
||||
return None
|
||||
return encoded.to(torch.uint8).contiguous()
|
||||
|
||||
|
||||
def _trust_dsv4_extra_cache_nan_free(
|
||||
kv_cache_dtype: str,
|
||||
has_kv_transfer: bool,
|
||||
@@ -555,6 +599,10 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
# Block scale for the preshuffled weight; None = not preshuffled.
|
||||
self._wqa_wkv_scale: torch.Tensor | None = None
|
||||
self._wo_b_scale: torch.Tensor | None = None
|
||||
self._wo_a_fp8_weight: torch.Tensor | None = None
|
||||
self._wo_a_e8m0_scale: torch.Tensor | None = None
|
||||
self._wo_a_cos_cache: torch.Tensor | None = None
|
||||
self._wo_a_sin_cache: torch.Tensor | None = None
|
||||
self._fused_compressor_weight: torch.Tensor | None
|
||||
self.register_buffer("_fused_compressor_weight", None, persistent=False)
|
||||
self._fused_compressor_split_sizes: tuple[int, int] | None = None
|
||||
@@ -815,6 +863,93 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
|
||||
self._wqa_wkv_scale = _prep(self.fused_wqa_wkv)
|
||||
self._wo_b_scale = _prep(self.wo_b)
|
||||
if _ON_GFX950 and envs.VLLM_ROCM_USE_AITER_FP8BMM:
|
||||
self._prepare_fp8_wo_a()
|
||||
|
||||
def _prepare_fp8_wo_a(self) -> None:
|
||||
try:
|
||||
from aiter.ops.batched_gemm_op_a8w8 import (
|
||||
batched_gemm_a8w8_mxscale as mxscale_op,
|
||||
)
|
||||
from aiter.ops.inverse_rope_group_quant import (
|
||||
inverse_rope_group_quant as inverse_quant_op,
|
||||
)
|
||||
except ImportError:
|
||||
logger.warning_once(
|
||||
"The DeepSeek V4 FP8 WO_A path requires AITER >= 0.1.20; "
|
||||
"falling back to BF16 WO_A."
|
||||
)
|
||||
return
|
||||
del mxscale_op, inverse_quant_op
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
|
||||
get_fp8_block_weight_scale,
|
||||
is_fp8,
|
||||
)
|
||||
|
||||
weight = getattr(self.wo_a, "weight", None)
|
||||
scale = get_fp8_block_weight_scale(self.wo_a)
|
||||
if scale is None:
|
||||
# ModelOpt MXFP8 stores the multiplicative E8M0 scale without the
|
||||
# historical ``_inv`` suffix.
|
||||
scale = getattr(self.wo_a, "weight_scale", None)
|
||||
if weight is None or scale is None:
|
||||
logger.warning_once(
|
||||
"DeepSeek V4 FP8 WO_A needs a block-scaled FP8 wo_a weight; "
|
||||
"the layer exposes no weight/weight scale. Falling back to "
|
||||
"BF16 WO_A."
|
||||
)
|
||||
return
|
||||
if weight.dim() != 2 or scale.dim() != 2 or not is_fp8(weight.dtype):
|
||||
logger.warning_once(
|
||||
"DeepSeek V4 FP8 WO_A needs a 2-D FP8 wo_a weight with a 2-D "
|
||||
"block scale, got weight %s%s and scale %s. Falling back to "
|
||||
"BF16 WO_A.",
|
||||
weight.dtype,
|
||||
tuple(weight.shape),
|
||||
tuple(scale.shape),
|
||||
)
|
||||
return
|
||||
|
||||
groups = self.n_local_groups
|
||||
out_per_group = self.o_lora_rank
|
||||
out_features, in_features = weight.shape
|
||||
if (
|
||||
out_features != groups * out_per_group
|
||||
or out_per_group % 128 != 0
|
||||
or in_features % 128 != 0
|
||||
or scale.shape != (out_features // 128, in_features // 128)
|
||||
):
|
||||
logger.warning_once(
|
||||
"DeepSeek V4 FP8 WO_A needs group-128 blocks for %d groups of "
|
||||
"%d outputs, got weight %s and scale %s. Falling back to BF16 "
|
||||
"WO_A.",
|
||||
groups,
|
||||
out_per_group,
|
||||
tuple(weight.shape),
|
||||
tuple(scale.shape),
|
||||
)
|
||||
return
|
||||
|
||||
e8m0_scale = _wo_a_block_scale_to_e8m0(scale)
|
||||
if e8m0_scale is None:
|
||||
logger.warning_once(
|
||||
"DeepSeek V4 FP8 WO_A could not losslessly encode the %s wo_a "
|
||||
"block scale as OCP E8M0. Falling back to BF16 WO_A.",
|
||||
scale.dtype,
|
||||
)
|
||||
return
|
||||
|
||||
self._wo_a_fp8_weight = weight.view(groups, out_per_group, in_features)
|
||||
self._wo_a_e8m0_scale = e8m0_scale.view(
|
||||
groups, out_per_group // 128, in_features // 128
|
||||
)
|
||||
cache = getattr(self.rotary_emb, "cos_sin_cache_bf16", None)
|
||||
if cache is None:
|
||||
cache = self.rotary_emb.cos_sin_cache.to(dtype=torch.bfloat16)
|
||||
cos_cache, sin_cache = cache.chunk(2, dim=-1)
|
||||
self._wo_a_cos_cache = cos_cache.contiguous()
|
||||
self._wo_a_sin_cache = sin_cache.contiguous()
|
||||
|
||||
def prepare_compressor_gemm_fusion(self) -> bool:
|
||||
if self._fused_compressor_weight is not None:
|
||||
@@ -973,17 +1108,44 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
)
|
||||
|
||||
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
|
||||
# ROCm BF16 reference wo_a path (inverse RoPE + einsum) + wo_b.
|
||||
z = rocm_inv_rope_einsum(
|
||||
self.rotary_emb,
|
||||
o,
|
||||
positions,
|
||||
self.rope_head_dim,
|
||||
self.n_local_groups,
|
||||
self.o_lora_rank,
|
||||
self.wo_a,
|
||||
)
|
||||
zf = z.flatten(1)
|
||||
if self._wo_a_fp8_weight is not None:
|
||||
from aiter.ops.batched_gemm_op_a8w8 import (
|
||||
batched_gemm_a8w8_mxscale,
|
||||
)
|
||||
from aiter.ops.inverse_rope_group_quant import (
|
||||
inverse_rope_group_quant,
|
||||
)
|
||||
|
||||
assert self._wo_a_cos_cache is not None
|
||||
assert self._wo_a_sin_cache is not None
|
||||
o_fp8, o_scale = inverse_rope_group_quant(
|
||||
o.view(o.shape[0], self.n_local_heads, self.head_dim),
|
||||
positions.to(torch.int64),
|
||||
self._wo_a_cos_cache,
|
||||
self._wo_a_sin_cache,
|
||||
num_groups=self.n_local_groups,
|
||||
quant_group_size=128,
|
||||
)
|
||||
assert self._wo_a_e8m0_scale is not None
|
||||
zf = batched_gemm_a8w8_mxscale(
|
||||
o_fp8,
|
||||
self._wo_a_fp8_weight,
|
||||
o_scale,
|
||||
self._wo_a_e8m0_scale,
|
||||
dtype=o.dtype,
|
||||
).flatten(1)
|
||||
else:
|
||||
# ROCm BF16 reference wo_a path (inverse RoPE + einsum) + wo_b.
|
||||
z = rocm_inv_rope_einsum(
|
||||
self.rotary_emb,
|
||||
o,
|
||||
positions,
|
||||
self.rope_head_dim,
|
||||
self.n_local_groups,
|
||||
self.o_lora_rank,
|
||||
self.wo_a,
|
||||
)
|
||||
zf = z.flatten(1)
|
||||
if self._wo_b_scale is not None and zf.dim() == 2:
|
||||
return self._bpre_attn_gemm(self.wo_b.weight, self._wo_b_scale, zf, True)
|
||||
return self.wo_b(zf)
|
||||
|
||||
@@ -40,8 +40,7 @@ from vllm.model_executor.models.vision import (
|
||||
)
|
||||
|
||||
|
||||
@lru_cache(8)
|
||||
def get_vision_cos_sin(
|
||||
def _compute_vision_cos_sin(
|
||||
n_h: int, n_w: int, dim: int, theta: float
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
|
||||
@@ -52,6 +51,13 @@ def get_vision_cos_sin(
|
||||
return freqs.cos().unsqueeze(1), freqs.sin().unsqueeze(1)
|
||||
|
||||
|
||||
@lru_cache(8)
|
||||
def get_vision_cos_sin(
|
||||
n_h: int, n_w: int, dim: int, theta: float
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return _compute_vision_cos_sin(n_h, n_w, dim, theta)
|
||||
|
||||
|
||||
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
|
||||
dtype = x.dtype
|
||||
x1, x2 = x.float().chunk(2, dim=-1)
|
||||
@@ -123,15 +129,23 @@ class DeepseekV4VisionAttention(nn.Module):
|
||||
)
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
cu_seqlens: torch.Tensor | None = None,
|
||||
max_seqlen: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
n = x.size(0)
|
||||
qkv, _ = self.wqkv(x)
|
||||
q, k, v = (t.view(n, self.n_heads, self.head_dim) for t in qkv.chunk(3, -1))
|
||||
q = apply_rotary(q, cos, sin).unsqueeze(0) # (b=1, n, h, d)
|
||||
k = apply_rotary(k, cos, sin).unsqueeze(0)
|
||||
# One image per call: a dense batch, no varlen packing metadata.
|
||||
o = self.attn(q, k, v.unsqueeze(0))
|
||||
# Dense (cu_seqlens=None): one image per call. Varlen (cu_seqlens
|
||||
# set): packed multi-image batch for encoder CUDA graph replay.
|
||||
o = self.attn(
|
||||
q, k, v.unsqueeze(0), cu_seqlens=cu_seqlens, max_seqlen=max_seqlen
|
||||
)
|
||||
out, _ = self.wo(o.reshape(n, -1))
|
||||
return out
|
||||
|
||||
@@ -173,9 +187,14 @@ class DeepseekV4VisionBlock(nn.Module):
|
||||
self.mlp = DeepseekV4VisionMLP(config, prefix=f"{prefix}.mlp")
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
cu_seqlens: torch.Tensor | None = None,
|
||||
max_seqlen: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
x = x + self.attn(self.norm1(x), cos, sin)
|
||||
x = x + self.attn(self.norm1(x), cos, sin, cu_seqlens, max_seqlen)
|
||||
return x + self.mlp(self.norm2(x))
|
||||
|
||||
|
||||
@@ -206,6 +225,115 @@ class DeepseekV4ViT(nn.Module):
|
||||
x = block(x, cos, sin)
|
||||
return self.norm(x)
|
||||
|
||||
def forward_packed(
|
||||
self,
|
||||
patches: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
cu_seqlens: torch.Tensor,
|
||||
max_seqlen: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Varlen path for encoder CUDA graphs: multiple images packed along
|
||||
rows, per-image attention via ``cu_seqlens``, RoPE tables precomputed
|
||||
on device. Pure-tensor (no host reads, no H2D), safe to capture."""
|
||||
x = self.patch_embed(patches)
|
||||
for block in self.blocks:
|
||||
x = block(x, cos, sin, cu_seqlens, max_seqlen)
|
||||
return self.norm(x)
|
||||
|
||||
|
||||
def build_packed_vit_metadata(
|
||||
grids: list[list[int]] | list[tuple[int, int]],
|
||||
*,
|
||||
rope_dim: int,
|
||||
rope_theta: float,
|
||||
device: torch.device,
|
||||
max_seqlen_override: int | None = None,
|
||||
cached: bool = True,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
"""Precompute packed-batch ViT metadata for ``DeepseekV4ViT.forward_packed``.
|
||||
|
||||
Args:
|
||||
grids: ``[n_vit_h, n_vit_w]`` per image, in packing order.
|
||||
rope_dim: RoPE embedding dimension of the ViT.
|
||||
rope_theta: RoPE base frequency of the ViT.
|
||||
device: Device for the returned tensors (except ``max_seqlen``,
|
||||
which stays on the host).
|
||||
max_seqlen_override: Worst-case value baked in at CUDA graph capture
|
||||
(the attention wrapper reads ``max_seqlen`` on the host, so the
|
||||
capture-time value becomes a graph constant).
|
||||
cached: Use the shared ``lru_cache`` for RoPE tables. Capture-time
|
||||
dummy grids pass ``False`` to avoid evicting real entries.
|
||||
|
||||
"""
|
||||
cos_sin = get_vision_cos_sin if cached else _compute_vision_cos_sin
|
||||
cos_list: list[torch.Tensor] = []
|
||||
sin_list: list[torch.Tensor] = []
|
||||
cu_seqlens = [0]
|
||||
max_seqlen = 0
|
||||
for n_h, n_w in grids:
|
||||
cos, sin = cos_sin(n_h, n_w, rope_dim, rope_theta)
|
||||
cos_list.append(cos)
|
||||
sin_list.append(sin)
|
||||
n = n_h * n_w
|
||||
cu_seqlens.append(cu_seqlens[-1] + n)
|
||||
max_seqlen = max(max_seqlen, n)
|
||||
if cos_list:
|
||||
cos = torch.cat(cos_list).to(device)
|
||||
sin = torch.cat(sin_list).to(device)
|
||||
else:
|
||||
cos = torch.zeros((0, 1, rope_dim), dtype=torch.float32, device=device)
|
||||
sin = torch.zeros((0, 1, rope_dim), dtype=torch.float32, device=device)
|
||||
if max_seqlen_override is not None:
|
||||
max_seqlen = max_seqlen_override
|
||||
return {
|
||||
"vit_cos": cos,
|
||||
"vit_sin": sin,
|
||||
"cu_seqlens": torch.tensor(cu_seqlens, dtype=torch.int32, device=device),
|
||||
# Read on the host by the attention wrapper; keep on CPU.
|
||||
"max_seqlen": torch.tensor(max_seqlen, dtype=torch.int32),
|
||||
}
|
||||
|
||||
|
||||
def build_packed_merge_metadata(
|
||||
grids: list[list[int]] | list[tuple[int, int]],
|
||||
downsample_ratio: int,
|
||||
*,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
"""Gather indices/mask for ``DeepseekV4Aligner.forward_packed``.
|
||||
|
||||
For each aligner output row, the ``r x r`` source patch rows in the
|
||||
packed ViT output; positions past the image edge (the eager path pads
|
||||
them with zeros) get mask 0 and a clamped in-range index.
|
||||
"""
|
||||
r = downsample_ratio
|
||||
idx_list: list[torch.Tensor] = []
|
||||
mask_list: list[torch.Tensor] = []
|
||||
offset = 0
|
||||
for n_h, n_w in grids:
|
||||
rows = -(-n_h // r)
|
||||
cols = -(-n_w // r)
|
||||
bi = torch.arange(rows).repeat_interleave(cols)
|
||||
bj = torch.arange(cols).repeat(rows)
|
||||
di = torch.arange(r).repeat_interleave(r)
|
||||
dj = torch.arange(r).repeat(r)
|
||||
hi = bi[:, None] * r + di[None, :]
|
||||
wj = bj[:, None] * r + dj[None, :]
|
||||
valid = (hi < n_h) & (wj < n_w)
|
||||
idx = offset + hi.clamp(max=n_h - 1) * n_w + wj.clamp(max=n_w - 1)
|
||||
idx_list.append(idx)
|
||||
mask_list.append(valid)
|
||||
offset += n_h * n_w
|
||||
if idx_list:
|
||||
merge_idx = torch.cat(idx_list).to(device)
|
||||
merge_mask = torch.cat(mask_list).unsqueeze(-1).to(device=device, dtype=dtype)
|
||||
else:
|
||||
merge_idx = torch.zeros((0, r * r), dtype=torch.int64, device=device)
|
||||
merge_mask = torch.zeros((0, r * r, 1), dtype=dtype, device=device)
|
||||
return {"merge_idx": merge_idx, "merge_mask": merge_mask}
|
||||
|
||||
|
||||
class DeepseekV4Aligner(nn.Module):
|
||||
"""Spatial merge (downsample_ratio x downsample_ratio) + MLP projector."""
|
||||
@@ -240,6 +368,27 @@ class DeepseekV4Aligner(nn.Module):
|
||||
out, _ = self.w2(F.gelu(hidden))
|
||||
return out
|
||||
|
||||
def forward_packed(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
merge_idx: torch.Tensor,
|
||||
merge_mask: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Packed multi-image path for encoder CUDA graphs.
|
||||
|
||||
``merge_idx``/``merge_mask`` come from ``build_packed_merge_metadata``;
|
||||
gather+mask reproduces the eager ``F.pad`` + ``F.unfold`` merge
|
||||
exactly (unfold rows are channel-major, so the gathered patch rows
|
||||
are transposed before flattening).
|
||||
"""
|
||||
r2 = self.downsample_ratio**2
|
||||
m = merge_idx.shape[0]
|
||||
gathered = (x[merge_idx] * merge_mask).view(m, r2, -1)
|
||||
gathered = gathered.permute(0, 2, 1).reshape(m, -1)
|
||||
hidden, _ = self.w1(gathered)
|
||||
out, _ = self.w2(F.gelu(hidden))
|
||||
return out
|
||||
|
||||
|
||||
def run_dp_sharded_vision_tower(
|
||||
vision_model: DeepseekV4ViT,
|
||||
|
||||
@@ -13,7 +13,10 @@ from vllm.distributed import (
|
||||
)
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.logger import init_logger
|
||||
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
|
||||
from vllm.models.deepseek_v41.attention import (
|
||||
DeepseekV4Attention,
|
||||
_replace_layer_index,
|
||||
)
|
||||
from vllm.models.deepseek_v41.common.ops import dequantize_and_gather_k_cache
|
||||
from vllm.models.deepseek_v41.sparse_mla import (
|
||||
DeepseekV4FlashMLAMetadata,
|
||||
@@ -391,6 +394,10 @@ def _copy_ragged_to_graph_buffers(
|
||||
return ragged_out, indptr_out
|
||||
|
||||
|
||||
# (ragged_indices, ragged_indptr, lens) as consumed by rocm_sparse_attn_decode.
|
||||
_TopkRagged = tuple[torch.Tensor, torch.Tensor, torch.Tensor]
|
||||
|
||||
|
||||
@dataclass
|
||||
class DeepseekV4ROCMAiterSparseSWAMetadata(DeepseekSparseSWAMetadata):
|
||||
decode_swa_ragged_indices: torch.Tensor | None = None
|
||||
@@ -500,6 +507,23 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
self._fused_compressor_weight: torch.Tensor | None
|
||||
self.register_buffer("_fused_compressor_weight", None, persistent=False)
|
||||
self._fused_compressor_split_sizes: tuple[int, int] | None = None
|
||||
# Decode ragged topk metadata is a pure function of the indices its
|
||||
# index source published, so every consumer of a source rebuilds the
|
||||
# same thing. The source owns one cache per compress ratio, refreshed
|
||||
# when it runs; consumers below it read through.
|
||||
self._topk_ragged_cache: dict[int, _TopkRagged] = {}
|
||||
self._index_source_prefix: str | None = None
|
||||
if self.compress_ratio > 0:
|
||||
assert self.index_source_layer_id is not None
|
||||
self._index_source_prefix = _replace_layer_index(
|
||||
self.prefix, self.index_source_layer_id
|
||||
)
|
||||
if self._index_source_prefix not in self._static_forward_context:
|
||||
raise NotImplementedError(
|
||||
f"Index source {self._index_source_prefix} not found on "
|
||||
"this rank; PP splits inside a v4.1 index-sharing group "
|
||||
"are not supported."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_padded_num_q_heads(cls, num_heads: int) -> int:
|
||||
@@ -733,6 +757,42 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
output=output[:num_decode_tokens],
|
||||
)
|
||||
|
||||
def _decode_topk_ragged(
|
||||
self,
|
||||
swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata,
|
||||
attn_metadata: DeepseekV4FlashMLAMetadata | None,
|
||||
num_decodes: int,
|
||||
num_decode_tokens: int,
|
||||
) -> _TopkRagged:
|
||||
"""Ragged form of the topk indices this layer's index source published.
|
||||
|
||||
The packing depends only on the shared ``topk_indices_buffer`` and
|
||||
per-step metadata, apart from the layer's own compress ratio, so the
|
||||
source memoizes one result per ratio for all the layers below it.
|
||||
"""
|
||||
assert attn_metadata is not None
|
||||
assert swa_metadata.is_valid_token is not None
|
||||
assert self.topk_indices_buffer is not None
|
||||
assert self._index_source_prefix is not None
|
||||
|
||||
source = self._static_forward_context[self._index_source_prefix]
|
||||
if source is self:
|
||||
# Fresh indices as of this layer; drop what the last step cached.
|
||||
source._topk_ragged_cache = {}
|
||||
cached = source._topk_ragged_cache.get(self.compress_ratio)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
built = compute_global_topk_ragged_indices_and_indptr(
|
||||
self.topk_indices_buffer[:num_decode_tokens],
|
||||
swa_metadata.token_to_req_indices,
|
||||
attn_metadata.block_table[:num_decodes],
|
||||
attn_metadata.block_size // self.compress_ratio,
|
||||
swa_metadata.is_valid_token[:num_decode_tokens],
|
||||
)
|
||||
source._topk_ragged_cache[self.compress_ratio] = built
|
||||
return built
|
||||
|
||||
def _forward_decode(
|
||||
self,
|
||||
q: torch.Tensor,
|
||||
@@ -749,22 +809,15 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
topk_ragged_indices = None
|
||||
topk_ragged_indptr = None
|
||||
if not swa_only:
|
||||
# Local indices filled by the index-source layer's indexer.
|
||||
assert attn_metadata is not None
|
||||
assert swa_metadata.is_valid_token is not None
|
||||
assert self.topk_indices_buffer is not None
|
||||
block_size = attn_metadata.block_size // self.compress_ratio
|
||||
is_valid = swa_metadata.is_valid_token[:num_decode_tokens]
|
||||
(
|
||||
topk_ragged_indices,
|
||||
topk_ragged_indptr,
|
||||
topk_lens,
|
||||
) = compute_global_topk_ragged_indices_and_indptr(
|
||||
self.topk_indices_buffer[:num_decode_tokens],
|
||||
swa_metadata.token_to_req_indices,
|
||||
attn_metadata.block_table[:num_decodes],
|
||||
block_size,
|
||||
is_valid,
|
||||
) = self._decode_topk_ragged(
|
||||
swa_metadata=swa_metadata,
|
||||
attn_metadata=attn_metadata,
|
||||
num_decodes=num_decodes,
|
||||
num_decode_tokens=num_decode_tokens,
|
||||
)
|
||||
|
||||
rocm_sparse_attn_decode(
|
||||
|
||||
@@ -26,6 +26,7 @@ from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.model_executor.models.interfaces import (
|
||||
MultiModalEmbeddings,
|
||||
SupportsEagle3,
|
||||
SupportsEncoderCudaGraph,
|
||||
SupportsMultiModal,
|
||||
SupportsPP,
|
||||
)
|
||||
@@ -44,15 +45,12 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.utils.tensor_schema import TensorSchema, TensorShape
|
||||
|
||||
from ..common.mm_preprocess import (
|
||||
IMAGE,
|
||||
IMAGE_END,
|
||||
IMAGE_NEW_LINE,
|
||||
IMAGE_PLACEHOLDER,
|
||||
IMAGE_START,
|
||||
DeepseekV4VLDummyInputsBuilder,
|
||||
DeepseekV4VLMultiModalProcessor,
|
||||
DeepseekV4VLProcessingInfo,
|
||||
)
|
||||
from ..common.vl_cudagraph import DeepseekV4VLEncoderCudaGraphMixin
|
||||
from .model import (
|
||||
DeepseekV41LLMForCausalLM,
|
||||
_linear_scale_param_name,
|
||||
@@ -115,11 +113,20 @@ def _make_deepseek_v4_vl_weights_mapper(
|
||||
info=DeepseekV4VLProcessingInfo,
|
||||
dummy_inputs=DeepseekV4VLDummyInputsBuilder,
|
||||
)
|
||||
class DeepseekV41ForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, SupportsEagle3):
|
||||
class DeepseekV41ForCausalLM(
|
||||
nn.Module,
|
||||
DeepseekV4VLEncoderCudaGraphMixin,
|
||||
SupportsMultiModal,
|
||||
SupportsEncoderCudaGraph,
|
||||
SupportsPP,
|
||||
SupportsEagle3,
|
||||
):
|
||||
"""Multimodal entry point for DeepSeek-V4.1 checkpoints with a vision tower.
|
||||
|
||||
``SupportsEagle3`` (aux hidden-state plumbing for MTP/DSpark drafters)
|
||||
delegates through ``language_model`` via the protocol defaults.
|
||||
``SupportsEncoderCudaGraph`` (ViT CUDA graph capture/replay) is
|
||||
implemented by ``DeepseekV4VLEncoderCudaGraphMixin``.
|
||||
"""
|
||||
|
||||
supports_encoder_tp_data = True
|
||||
@@ -196,29 +203,6 @@ class DeepseekV41ForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, Supports
|
||||
resolve_bindings={"p": self.config.vision_patch_size},
|
||||
)
|
||||
|
||||
def _encode_image(
|
||||
self,
|
||||
patches: torch.Tensor,
|
||||
n_vit_h: int,
|
||||
n_vit_w: int,
|
||||
) -> torch.Tensor:
|
||||
# Aligner rows in reading order, one per IMAGE slot.
|
||||
return self.aligner(self.vision(patches, n_vit_h, n_vit_w), n_vit_h, n_vit_w)
|
||||
|
||||
def _build_image_span(
|
||||
self, image_embeds: torch.Tensor, types: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Full image span: aligner rows at IMAGE slots, the learned
|
||||
delimiter vectors at IMAGE_START/IMAGE_NEW_LINE/IMAGE_END."""
|
||||
types = types.to(image_embeds.device)
|
||||
span = image_embeds.new_empty(types.numel(), image_embeds.shape[-1])
|
||||
dtype = image_embeds.dtype
|
||||
span[types == IMAGE_START] = self.image_start.to(dtype)
|
||||
span[types == IMAGE_END] = self.image_end.to(dtype)
|
||||
span[types == IMAGE_NEW_LINE] = self.image_newline.to(dtype)
|
||||
span[types == IMAGE] = image_embeds
|
||||
return span
|
||||
|
||||
def _process_image_input(
|
||||
self,
|
||||
image_input: DeepseekV4VLImagePixelInputs,
|
||||
|
||||
@@ -0,0 +1,390 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Encoder CUDA graph support for the DeepSeek-V4.1 vision tower.
|
||||
|
||||
Mixin implementing the ``SupportsEncoderCudaGraph`` protocol
|
||||
(``vllm/model_executor/models/interfaces.py``) on top of the shared
|
||||
``DeepseekV4ViT``/``DeepseekV4Aligner``. The captured graph packs a whole
|
||||
batch of images into one varlen run: ViT blocks attend per image via
|
||||
``cu_seqlens``, and the aligner's spatial merge becomes a gather+mask
|
||||
against precomputed indices. Span assembly (IMAGE_START/IMAGE_NEW_LINE/
|
||||
IMAGE_END delimiters) stays eager in ``postprocess_encoder_output`` but is
|
||||
batched over all items of the packed batch.
|
||||
|
||||
Enabled via ``--compilation-config '{"cudagraph_mm_encoder": true}'``; the
|
||||
manager (``vllm/v1/worker/encoder_cudagraph.py``) handles budget packing, DP
|
||||
sharding and eager fallback.
|
||||
"""
|
||||
|
||||
from collections.abc import Hashable
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.models.deepseek_v4.common.vision import (
|
||||
build_packed_merge_metadata,
|
||||
build_packed_vit_metadata,
|
||||
)
|
||||
from vllm.v1.worker.encoder_cudagraph_defs import (
|
||||
EncoderCudaGraphCaptureInputs,
|
||||
EncoderCudaGraphConfig,
|
||||
EncoderCudaGraphReplayBuffers,
|
||||
EncoderItemSpec,
|
||||
)
|
||||
|
||||
from .mm_preprocess import IMAGE, IMAGE_END, IMAGE_NEW_LINE, IMAGE_START
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.multimodal import MultiModalConfig
|
||||
from vllm.models.deepseek_v4.common.vision import (
|
||||
DeepseekV4Aligner,
|
||||
DeepseekV4ViT,
|
||||
)
|
||||
from vllm.transformers_utils.configs.deepseek_v41 import DeepseekV41Config
|
||||
|
||||
|
||||
class DeepseekV4VLEncoderCudaGraphMixin:
|
||||
"""``SupportsEncoderCudaGraph`` for ``DeepseekV41ForCausalLM``.
|
||||
|
||||
Expects ``self.vision``/``self.aligner``/``self.config``/
|
||||
``self.multimodal_config`` and the ``image_start``/``image_newline``/
|
||||
``image_end`` parameters from the host model.
|
||||
"""
|
||||
|
||||
# Provided by the host model; declared here so mixin methods type-check.
|
||||
vision: "DeepseekV4ViT"
|
||||
aligner: "DeepseekV4Aligner"
|
||||
config: "DeepseekV41Config"
|
||||
multimodal_config: "MultiModalConfig | None"
|
||||
image_start: torch.nn.Parameter
|
||||
image_end: torch.nn.Parameter
|
||||
image_newline: torch.nn.Parameter
|
||||
|
||||
# -- helpers shared with the eager multimodal path --
|
||||
|
||||
def _encode_image(
|
||||
self,
|
||||
patches: torch.Tensor,
|
||||
n_vit_h: int,
|
||||
n_vit_w: int,
|
||||
) -> torch.Tensor:
|
||||
# Aligner rows in reading order, one per IMAGE slot.
|
||||
return self.aligner(self.vision(patches, n_vit_h, n_vit_w), n_vit_h, n_vit_w)
|
||||
|
||||
def _build_image_span(
|
||||
self, image_embeds: torch.Tensor, types: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Full image span: aligner rows at IMAGE slots, the learned
|
||||
delimiter vectors at IMAGE_START/IMAGE_NEW_LINE/IMAGE_END."""
|
||||
types = types.to(image_embeds.device)
|
||||
span = image_embeds.new_empty(types.numel(), image_embeds.shape[-1])
|
||||
dtype = image_embeds.dtype
|
||||
span[types == IMAGE_START] = self.image_start.to(dtype)
|
||||
span[types == IMAGE_END] = self.image_end.to(dtype)
|
||||
span[types == IMAGE_NEW_LINE] = self.image_newline.to(dtype)
|
||||
span[types == IMAGE] = image_embeds
|
||||
return span
|
||||
|
||||
@staticmethod
|
||||
def _get_grid_list(mm_kwargs: dict[str, Any], key: str) -> list[list[int]]:
|
||||
grid = mm_kwargs[key]
|
||||
if isinstance(grid, torch.Tensor):
|
||||
grid = grid.tolist()
|
||||
return [[int(v) for v in row] for row in grid]
|
||||
|
||||
_encoder_cg_pad_totals: dict[int, int] = {}
|
||||
|
||||
# -- SupportsEncoderCudaGraph protocol --
|
||||
|
||||
def get_encoder_cudagraph_config(self) -> EncoderCudaGraphConfig:
|
||||
mm_cfg = self.multimodal_config
|
||||
if (
|
||||
mm_cfg is not None
|
||||
and mm_cfg.mm_encoder_attn_dtype == "fp8"
|
||||
and mm_cfg.mm_encoder_fp8_scale_path is None
|
||||
):
|
||||
raise ValueError(
|
||||
"cudagraph_mm_encoder is incompatible with dynamic FP8 "
|
||||
"scaling for the vision encoder (the amax history is "
|
||||
"host-side state that cannot be captured). Provide a static "
|
||||
"scale file via --mm-encoder-fp8-scale-path or disable "
|
||||
"cudagraph_mm_encoder."
|
||||
)
|
||||
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
backend = self.vision.blocks[0].attn.attn.attn_backend
|
||||
# FlashInfer reads max_seqlen on the host and TORCH_SDPA calls
|
||||
# .tolist() on CUDA cu_seqlens; neither can be captured.
|
||||
if backend in (
|
||||
AttentionBackendEnum.FLASHINFER,
|
||||
AttentionBackendEnum.TORCH_SDPA,
|
||||
):
|
||||
raise ValueError(
|
||||
f"cudagraph_mm_encoder is not supported with the {backend.name} "
|
||||
"ViT attention backend for DeepSeek-V4.1. Set "
|
||||
"--mm-encoder-attn-backend FLASH_ATTN or disable "
|
||||
"cudagraph_mm_encoder."
|
||||
)
|
||||
|
||||
pad_totals = self._encoder_cg_pad_totals
|
||||
|
||||
def pad_cu_seqlens(dst: torch.Tensor, src: torch.Tensor) -> None:
|
||||
# Varlen attention requires cu_seqlens[-1] to equal the number of
|
||||
# rows actually passed in. The captured buffers are sized for the
|
||||
# full token budget, so a smaller real batch is completed with one
|
||||
# trailing padding sequence; declaring fewer rows than the buffer
|
||||
# holds is undefined behaviour and returns NaN on FlashAttn.
|
||||
total = pad_totals.get(dst.data_ptr())
|
||||
if total is None:
|
||||
raise RuntimeError(
|
||||
"cu_seqlens replay buffer was not registered at capture "
|
||||
"time; the manager must replay into the capture-time "
|
||||
"buffers."
|
||||
)
|
||||
n = min(src.shape[0], dst.shape[0])
|
||||
dst[:n].copy_(src[:n])
|
||||
dst[n:] = total
|
||||
|
||||
return EncoderCudaGraphConfig(
|
||||
modalities=["image"],
|
||||
buffer_keys=[
|
||||
"patches",
|
||||
"vit_cos",
|
||||
"vit_sin",
|
||||
"cu_seqlens",
|
||||
"max_seqlen",
|
||||
"merge_idx",
|
||||
"merge_mask",
|
||||
],
|
||||
out_hidden_size=self.config.hidden_size,
|
||||
padding_logics={"cu_seqlens": pad_cu_seqlens},
|
||||
)
|
||||
|
||||
def get_encoder_cudagraph_budget_range(
|
||||
self,
|
||||
vllm_config: "VllmConfig",
|
||||
) -> tuple[int, int]:
|
||||
# Min: comfortably above the smallest possible image span (4 tokens
|
||||
# for a 1x1 grid); also sets max_batch_size = 64 via the manager's
|
||||
# auto-inference (max_batch_size <= min_budget invariant).
|
||||
min_budget = 64
|
||||
max_budget = min(
|
||||
vllm_config.scheduler_config.max_num_batched_tokens,
|
||||
vllm_config.model_config.max_model_len,
|
||||
)
|
||||
return (min_budget, max_budget)
|
||||
|
||||
def get_encoder_cudagraph_item_specs(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
) -> list[EncoderItemSpec]:
|
||||
vit_grid = self._get_grid_list(mm_kwargs, "vit_grid")
|
||||
llm_grid = self._get_grid_list(mm_kwargs, "llm_grid")
|
||||
return [
|
||||
EncoderItemSpec(
|
||||
input_size=h * w,
|
||||
output_tokens=lh * (lw + 1) + 2,
|
||||
)
|
||||
for (h, w), (lh, lw) in zip(vit_grid, llm_grid, strict=True)
|
||||
]
|
||||
|
||||
def select_encoder_cudagraph_items(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
indices: list[int],
|
||||
) -> dict[str, Any]:
|
||||
vit_grid = self._get_grid_list(mm_kwargs, "vit_grid")
|
||||
llm_grid = self._get_grid_list(mm_kwargs, "llm_grid")
|
||||
patches = mm_kwargs["patches"]
|
||||
types = mm_kwargs["types"]
|
||||
|
||||
if len(indices) == 0:
|
||||
return {
|
||||
"patches": patches[:0],
|
||||
"vit_grid": torch.zeros((0, 2), dtype=torch.int64),
|
||||
"llm_grid": torch.zeros((0, 2), dtype=torch.int64),
|
||||
"types": types[:0],
|
||||
}
|
||||
|
||||
cum_patches = [0]
|
||||
for h, w in vit_grid:
|
||||
cum_patches.append(cum_patches[-1] + h * w)
|
||||
cum_spans = [0]
|
||||
for lh, lw in llm_grid:
|
||||
cum_spans.append(cum_spans[-1] + lh * (lw + 1) + 2)
|
||||
|
||||
return {
|
||||
"patches": torch.cat(
|
||||
[patches[cum_patches[i] : cum_patches[i + 1]] for i in indices]
|
||||
),
|
||||
"vit_grid": torch.tensor([vit_grid[i] for i in indices], dtype=torch.int64),
|
||||
"llm_grid": torch.tensor([llm_grid[i] for i in indices], dtype=torch.int64),
|
||||
"types": torch.cat(
|
||||
[types[cum_spans[i] : cum_spans[i + 1]] for i in indices]
|
||||
),
|
||||
}
|
||||
|
||||
def prepare_encoder_cudagraph_capture_inputs(
|
||||
self,
|
||||
token_budget: int,
|
||||
max_batch_size: int,
|
||||
max_frames_per_batch: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
path: str = "default",
|
||||
axis_keys: tuple[Hashable, ...] | None = None,
|
||||
) -> EncoderCudaGraphCaptureInputs:
|
||||
if (
|
||||
self.multimodal_config is not None
|
||||
and self.multimodal_config.get_limit_per_prompt("image") == 0
|
||||
):
|
||||
raise RuntimeError(
|
||||
"cudagraph_mm_encoder requires the vision tower, but it was "
|
||||
"stubbed out because the image limit is 0. Disable "
|
||||
"cudagraph_mm_encoder."
|
||||
)
|
||||
|
||||
config = self.config
|
||||
r = config.vision_downsample_ratio
|
||||
# Span rows per dummy item (ceiling so the buffers tile the budget).
|
||||
# Each dummy image is a single aligner row of per_item_out blocks:
|
||||
# r x (r * per_item_out) patches. One real image using the whole
|
||||
# budget needs at most r^2 * token_budget patches, which this fits.
|
||||
per_item_out = -(-token_budget // max_batch_size)
|
||||
grids = [[r, r * per_item_out]] * max_batch_size
|
||||
total_patches = r * r * per_item_out * max_batch_size
|
||||
|
||||
p = config.vision_patch_size
|
||||
patches = torch.zeros(total_patches, 3, p, p, device=device, dtype=dtype)
|
||||
|
||||
metadata = build_packed_vit_metadata(
|
||||
grids,
|
||||
rope_dim=self.vision.rope_dim,
|
||||
rope_theta=self.vision.rope_theta,
|
||||
device=device,
|
||||
max_seqlen_override=total_patches,
|
||||
cached=False,
|
||||
)
|
||||
# Spare cu_seqlens slots let replay append a padding sequence that
|
||||
# covers the rows a smaller real batch does not fill.
|
||||
real_cu = metadata.pop("cu_seqlens")
|
||||
cu_seqlens = torch.full(
|
||||
(max_batch_size + 2,), total_patches, dtype=torch.int32, device=device
|
||||
)
|
||||
cu_seqlens[: real_cu.numel()] = real_cu
|
||||
|
||||
merge = build_packed_merge_metadata(grids, r, device=device, dtype=dtype)
|
||||
|
||||
self._encoder_cg_pad_totals[cu_seqlens.data_ptr()] = total_patches
|
||||
|
||||
return EncoderCudaGraphCaptureInputs(
|
||||
values={
|
||||
"patches": patches,
|
||||
**metadata,
|
||||
"cu_seqlens": cu_seqlens,
|
||||
**merge,
|
||||
}
|
||||
)
|
||||
|
||||
def prepare_encoder_cudagraph_replay_buffers(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
max_batch_size: int,
|
||||
max_frames_per_batch: int,
|
||||
path: str = "default",
|
||||
) -> EncoderCudaGraphReplayBuffers:
|
||||
vit_grid = self._get_grid_list(mm_kwargs, "vit_grid")
|
||||
patches = mm_kwargs["patches"]
|
||||
dtype = self.aligner.w1.weight.dtype
|
||||
if patches.dtype != dtype:
|
||||
patches = patches.to(dtype)
|
||||
|
||||
# Unpadded: the manager zero-pads patches/cos/sin/merge buffers, and
|
||||
# pad_cu_seqlens appends the padding sequence covering the tail rows.
|
||||
metadata = build_packed_vit_metadata(
|
||||
vit_grid,
|
||||
rope_dim=self.vision.rope_dim,
|
||||
rope_theta=self.vision.rope_theta,
|
||||
device=patches.device,
|
||||
)
|
||||
merge = build_packed_merge_metadata(
|
||||
vit_grid,
|
||||
self.config.vision_downsample_ratio,
|
||||
device=patches.device,
|
||||
dtype=dtype,
|
||||
)
|
||||
return EncoderCudaGraphReplayBuffers(
|
||||
values={"patches": patches, **metadata, **merge}
|
||||
)
|
||||
|
||||
def encoder_cudagraph_forward(
|
||||
self,
|
||||
inputs: dict[str, torch.Tensor],
|
||||
path: str = "default",
|
||||
) -> torch.Tensor:
|
||||
vit_out = self.vision.forward_packed(
|
||||
inputs["patches"],
|
||||
inputs["vit_cos"],
|
||||
inputs["vit_sin"],
|
||||
inputs["cu_seqlens"],
|
||||
inputs["max_seqlen"],
|
||||
)
|
||||
return self.aligner.forward_packed(
|
||||
vit_out, inputs["merge_idx"], inputs["merge_mask"]
|
||||
)
|
||||
|
||||
def encoder_eager_forward(
|
||||
self,
|
||||
mm_kwargs: dict[str, Any],
|
||||
path: str = "default",
|
||||
) -> torch.Tensor:
|
||||
patches = mm_kwargs["patches"].to(self.aligner.w1.weight.dtype)
|
||||
vit_grid = self._get_grid_list(mm_kwargs, "vit_grid")
|
||||
outs: list[torch.Tensor] = []
|
||||
offset = 0
|
||||
for n_vit_h, n_vit_w in vit_grid:
|
||||
n_vit = n_vit_h * n_vit_w
|
||||
outs.append(
|
||||
self._encode_image(patches[offset : offset + n_vit], n_vit_h, n_vit_w)
|
||||
)
|
||||
offset += n_vit
|
||||
if not outs:
|
||||
return patches.new_zeros((0, self.config.hidden_size))
|
||||
return torch.cat(outs, dim=0)
|
||||
|
||||
def postprocess_encoder_output(
|
||||
self,
|
||||
outputs: dict[str, torch.Tensor],
|
||||
indices: list[int],
|
||||
per_item_out_tokens: list[int],
|
||||
dest: dict[int, torch.Tensor] | list[torch.Tensor | None],
|
||||
clone: bool = False,
|
||||
batch_mm_kwargs: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
if not indices:
|
||||
return
|
||||
assert batch_mm_kwargs is not None
|
||||
aligner_out = outputs["default"]
|
||||
r = self.config.vision_downsample_ratio
|
||||
vit_grid = self._get_grid_list(batch_mm_kwargs, "vit_grid")
|
||||
llm_grid = self._get_grid_list(batch_mm_kwargs, "llm_grid")
|
||||
types = batch_mm_kwargs["types"].to(aligner_out.device)
|
||||
|
||||
n_rows = sum(-(-h // r) * (-(-w // r)) for h, w in vit_grid)
|
||||
span_lens = [lh * (lw + 1) + 2 for lh, lw in llm_grid]
|
||||
|
||||
# Batched span assembly: one masked fill per role across all items.
|
||||
dtype = aligner_out.dtype
|
||||
span = aligner_out.new_empty(sum(span_lens), self.config.hidden_size)
|
||||
span[types == IMAGE] = aligner_out[:n_rows]
|
||||
span[types == IMAGE_START] = self.image_start.to(dtype)
|
||||
span[types == IMAGE_END] = self.image_end.to(dtype)
|
||||
span[types == IMAGE_NEW_LINE] = self.image_newline.to(dtype)
|
||||
|
||||
# Freshly allocated, so later replays cannot clobber the results.
|
||||
offset = 0
|
||||
for idx, span_len in zip(indices, span_lens):
|
||||
dest[idx] = span[offset : offset + span_len]
|
||||
offset += span_len
|
||||
@@ -26,6 +26,7 @@ from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.model_executor.models.interfaces import (
|
||||
MultiModalEmbeddings,
|
||||
SupportsEagle3,
|
||||
SupportsEncoderCudaGraph,
|
||||
SupportsMultiModal,
|
||||
SupportsPP,
|
||||
)
|
||||
@@ -44,15 +45,12 @@ from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.utils.tensor_schema import TensorSchema, TensorShape
|
||||
|
||||
from ..common.mm_preprocess import (
|
||||
IMAGE,
|
||||
IMAGE_END,
|
||||
IMAGE_NEW_LINE,
|
||||
IMAGE_PLACEHOLDER,
|
||||
IMAGE_START,
|
||||
DeepseekV4VLDummyInputsBuilder,
|
||||
DeepseekV4VLMultiModalProcessor,
|
||||
DeepseekV4VLProcessingInfo,
|
||||
)
|
||||
from ..common.vl_cudagraph import DeepseekV4VLEncoderCudaGraphMixin
|
||||
from .model import (
|
||||
DeepseekV41LLMForCausalLM,
|
||||
_linear_scale_param_name,
|
||||
@@ -115,11 +113,20 @@ def _make_deepseek_v4_vl_weights_mapper(
|
||||
info=DeepseekV4VLProcessingInfo,
|
||||
dummy_inputs=DeepseekV4VLDummyInputsBuilder,
|
||||
)
|
||||
class DeepseekV41ForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, SupportsEagle3):
|
||||
class DeepseekV41ForCausalLM(
|
||||
nn.Module,
|
||||
DeepseekV4VLEncoderCudaGraphMixin,
|
||||
SupportsMultiModal,
|
||||
SupportsEncoderCudaGraph,
|
||||
SupportsPP,
|
||||
SupportsEagle3,
|
||||
):
|
||||
"""Multimodal entry point for DeepSeek-V4.1 checkpoints with a vision tower.
|
||||
|
||||
``SupportsEagle3`` (aux hidden-state plumbing for MTP/DSpark drafters)
|
||||
delegates through ``language_model`` via the protocol defaults.
|
||||
``SupportsEncoderCudaGraph`` (ViT CUDA graph capture/replay) is
|
||||
implemented by ``DeepseekV4VLEncoderCudaGraphMixin``.
|
||||
"""
|
||||
|
||||
supports_encoder_tp_data = True
|
||||
@@ -196,29 +203,6 @@ class DeepseekV41ForCausalLM(nn.Module, SupportsMultiModal, SupportsPP, Supports
|
||||
resolve_bindings={"p": self.config.vision_patch_size},
|
||||
)
|
||||
|
||||
def _encode_image(
|
||||
self,
|
||||
patches: torch.Tensor,
|
||||
n_vit_h: int,
|
||||
n_vit_w: int,
|
||||
) -> torch.Tensor:
|
||||
# Aligner rows in reading order, one per IMAGE slot.
|
||||
return self.aligner(self.vision(patches, n_vit_h, n_vit_w), n_vit_h, n_vit_w)
|
||||
|
||||
def _build_image_span(
|
||||
self, image_embeds: torch.Tensor, types: torch.Tensor
|
||||
) -> torch.Tensor:
|
||||
"""Full image span: aligner rows at IMAGE slots, the learned
|
||||
delimiter vectors at IMAGE_START/IMAGE_NEW_LINE/IMAGE_END."""
|
||||
types = types.to(image_embeds.device)
|
||||
span = image_embeds.new_empty(types.numel(), image_embeds.shape[-1])
|
||||
dtype = image_embeds.dtype
|
||||
span[types == IMAGE_START] = self.image_start.to(dtype)
|
||||
span[types == IMAGE_END] = self.image_end.to(dtype)
|
||||
span[types == IMAGE_NEW_LINE] = self.image_newline.to(dtype)
|
||||
span[types == IMAGE] = image_embeds
|
||||
return span
|
||||
|
||||
def _process_image_input(
|
||||
self,
|
||||
image_input: DeepseekV4VLImagePixelInputs,
|
||||
|
||||
@@ -383,6 +383,8 @@ def _kpool_tail_seed_kernel(
|
||||
tslot_ptr,
|
||||
tail_ptr,
|
||||
n_tokens,
|
||||
TAIL_BLOCK_ELEMS: tl.constexpr,
|
||||
KPOOL_HEAD: tl.constexpr,
|
||||
HEAD_DIM: tl.constexpr,
|
||||
KPOOL: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
@@ -393,6 +395,11 @@ def _kpool_tail_seed_kernel(
|
||||
ahead belongs to a different tail block (or is past the batch / padding,
|
||||
slot < 0). ``tslot = block * KPOOL + pos % KPOOL``; the destination is
|
||||
``tail[block, {0:K, 1:score}, pos % KPOOL, :]``.
|
||||
|
||||
The tail cache aliases the indexer cache with the indexer's (padded) block
|
||||
stride, so blocks are addressed through ``TAIL_BLOCK_ELEMS`` /
|
||||
``KPOOL_HEAD`` (``tail.stride(0)`` / ``tail.stride(1)``), never as a dense
|
||||
``[num_blocks, 2, KPOOL, HEAD_DIM]`` array.
|
||||
"""
|
||||
i = tl.program_id(0)
|
||||
t = tl.load(tslot_ptr + i).to(tl.int64)
|
||||
@@ -409,11 +416,11 @@ def _kpool_tail_seed_kernel(
|
||||
return
|
||||
offs = tl.arange(0, BLOCK_D)
|
||||
m = offs < HEAD_DIM
|
||||
base = (blk * 2 * KPOOL + t % KPOOL) * HEAD_DIM
|
||||
base = blk * TAIL_BLOCK_ELEMS + (t % KPOOL) * HEAD_DIM
|
||||
k = tl.load(key_ptr + i * HEAD_DIM + offs, mask=m)
|
||||
s = tl.load(score_ptr + i * HEAD_DIM + offs, mask=m)
|
||||
tl.store(tail_ptr + base + offs, k, mask=m)
|
||||
tl.store(tail_ptr + base + KPOOL * HEAD_DIM + offs, s, mask=m)
|
||||
tl.store(tail_ptr + base + KPOOL_HEAD + offs, s, mask=m)
|
||||
|
||||
|
||||
def kpool_seed_tail_cache(
|
||||
@@ -426,6 +433,8 @@ def kpool_seed_tail_cache(
|
||||
) -> None:
|
||||
"""Seed the paged tail cache from a prefill batch (see the kernel)."""
|
||||
assert tail_kv_cache.dtype == torch.bfloat16
|
||||
assert tail_kv_cache.ndim == 4 and tail_kv_cache.shape[1] == 2
|
||||
assert tail_kv_cache.stride(3) == 1 and tail_kv_cache.stride(2) == head_dim
|
||||
assert key.dtype == torch.bfloat16
|
||||
n = tslot.shape[0]
|
||||
if n == 0:
|
||||
@@ -436,6 +445,8 @@ def kpool_seed_tail_cache(
|
||||
tslot,
|
||||
tail_kv_cache,
|
||||
n,
|
||||
TAIL_BLOCK_ELEMS=tail_kv_cache.stride(0),
|
||||
KPOOL_HEAD=tail_kv_cache.stride(1),
|
||||
HEAD_DIM=head_dim,
|
||||
KPOOL=kpool,
|
||||
BLOCK_D=triton.next_power_of_2(head_dim),
|
||||
|
||||
@@ -10,6 +10,7 @@ from vllm.config import get_current_vllm_config_or_none
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.custom_op import CustomOp
|
||||
from vllm.model_executor.layers.indexer_topk import get_indexer_topk
|
||||
from vllm.models.glm5next.common.sparse_indexer import (
|
||||
RADIX_TOPK_WORKSPACE_SIZE,
|
||||
_build_decode_scatter_indices,
|
||||
@@ -39,21 +40,6 @@ if current_platform.is_cuda_alike():
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _use_cooperative_topk(
|
||||
logits: torch.Tensor,
|
||||
select_k: int,
|
||||
num_rows: int,
|
||||
) -> bool:
|
||||
return (
|
||||
current_platform.is_cuda()
|
||||
and select_k in (512, 1024, 2048)
|
||||
and num_rows <= 64
|
||||
and logits.stride(0) % 4 == 0
|
||||
and current_platform.has_device_capability(90)
|
||||
and not current_platform.is_device_capability_family(120)
|
||||
)
|
||||
|
||||
|
||||
# kpool write helper: form pools from the current token batch and compress them
|
||||
# into the index K cache via the fused Triton kernel.
|
||||
|
||||
@@ -134,6 +120,7 @@ def sparse_attn_indexer_kpool(
|
||||
# path and when the tail cache is disabled.
|
||||
tail_kv_cache: torch.Tensor | None = None,
|
||||
tail_prefix: str | None = None,
|
||||
topk_backend: str = "auto",
|
||||
) -> torch.Tensor:
|
||||
# careful! this will be None in dummy run
|
||||
attn_metadata = get_forward_context().attn_metadata
|
||||
@@ -584,35 +571,18 @@ def sparse_attn_indexer_kpool(
|
||||
else:
|
||||
topk_dst = topk_indices_buffer[:num_padded_tokens, :topk_tokens]
|
||||
|
||||
if current_platform.is_cuda() and select_k in (512, 1024, 2048):
|
||||
workspace_manager = current_workspace_manager()
|
||||
(topk_workspace,) = workspace_manager.get_simultaneous(
|
||||
((RADIX_TOPK_WORKSPACE_SIZE,), torch.uint8),
|
||||
)
|
||||
topk_op = (
|
||||
torch.ops._C.cooperative_topk
|
||||
if _use_cooperative_topk(logits, select_k, num_rows)
|
||||
else torch.ops._C.persistent_topk
|
||||
)
|
||||
topk_op(
|
||||
logits,
|
||||
seq_lens,
|
||||
topk_dst,
|
||||
topk_workspace,
|
||||
select_k,
|
||||
attn_metadata_narrowed.max_seq_len,
|
||||
)
|
||||
else:
|
||||
torch.ops._C.top_k_per_row_decode(
|
||||
logits,
|
||||
next_n,
|
||||
seq_lens,
|
||||
topk_dst,
|
||||
num_rows,
|
||||
logits.stride(0),
|
||||
logits.stride(1),
|
||||
select_k,
|
||||
)
|
||||
# Shared dispatcher with the DSA sparse indexer, so the kpool select
|
||||
# honors kernel_config.sparse_indexer_topk_backend and picks between
|
||||
# cooperative/persistent by batch size instead of always taking the
|
||||
# same kernel.
|
||||
get_indexer_topk(topk_backend)(
|
||||
logits,
|
||||
seq_lens,
|
||||
next_n,
|
||||
topk_dst,
|
||||
select_k,
|
||||
attn_metadata_narrowed.max_seq_len,
|
||||
)
|
||||
|
||||
# Resolve to token-level indices in the output buffer.
|
||||
if index_kpool > 1:
|
||||
@@ -692,6 +662,11 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
"Sparse Attention Indexer CUDA op requires DeepGEMM to be installed."
|
||||
)
|
||||
_cfg = get_current_vllm_config_or_none()
|
||||
self.topk_backend = (
|
||||
_cfg.kernel_config.sparse_indexer_topk_backend
|
||||
if _cfg is not None
|
||||
else "auto"
|
||||
)
|
||||
_parallel = _cfg.parallel_config if _cfg is not None else None
|
||||
if (
|
||||
_parallel is not None
|
||||
@@ -766,4 +741,5 @@ class SparseAttnIndexerKpool(CustomOp):
|
||||
positions,
|
||||
self.tail_cache.kv_cache if self.tail_cache is not None else None,
|
||||
self.tail_cache.prefix if self.tail_cache is not None else None,
|
||||
self.topk_backend,
|
||||
)
|
||||
|
||||
+94
-8
@@ -7,11 +7,13 @@ from abc import ABC, abstractmethod
|
||||
from collections.abc import Mapping, Sequence
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import replace
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING, Any, Generic, overload
|
||||
|
||||
from typing_extensions import TypeVar
|
||||
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.inputs import (
|
||||
EmbedsInput,
|
||||
EmbedsPrompt,
|
||||
@@ -962,27 +964,103 @@ class BaseRenderer(ABC, Generic[_T]):
|
||||
|
||||
return engine_input
|
||||
|
||||
def _truncate_expanded_prompt(
|
||||
self,
|
||||
engine_input: TokensInput | MultiModalInput,
|
||||
params: TokenizeParams | None,
|
||||
) -> None:
|
||||
"""Re-apply `truncate_prompt_tokens` once placeholders are expanded.
|
||||
|
||||
`TokenizeParams.apply_post_tokenization` truncates the prompt before
|
||||
multimodal expansion, so a single placeholder token can expand into
|
||||
many and push the result back over the requested bound.
|
||||
|
||||
Multimodal spans are never cut: a request whose spans would not all
|
||||
survive intact is rejected, matching the post-expansion rejection in
|
||||
`vllm.v1.engine.input_processor._validate_model_input`.
|
||||
|
||||
Only multimodal inputs can grow after `apply_post_tokenization`, so
|
||||
everything else returns immediately.
|
||||
"""
|
||||
if engine_input["type"] != "multimodal":
|
||||
return
|
||||
|
||||
if params is None or params.truncate_prompt_tokens is None:
|
||||
return
|
||||
|
||||
prompt_token_ids = engine_input.get("prompt_token_ids")
|
||||
if prompt_token_ids is None:
|
||||
return
|
||||
|
||||
num_tokens = len(prompt_token_ids)
|
||||
truncation = params._truncation_slice(self.tokenizer, num_tokens)
|
||||
if truncation is None:
|
||||
return
|
||||
|
||||
start, stop, _ = truncation.indices(num_tokens)
|
||||
|
||||
mm_placeholders = engine_input["mm_placeholders"]
|
||||
for modality, positions in mm_placeholders.items():
|
||||
for position in positions:
|
||||
end = position.offset + position.length
|
||||
if position.offset >= start and end <= stop:
|
||||
continue
|
||||
raise VLLMValidationError(
|
||||
f"truncate_prompt_tokens={params.truncate_prompt_tokens} "
|
||||
f"would split or drop a(n) {modality} item, which spans "
|
||||
f"tokens {position.offset} to {end} of the "
|
||||
f"{num_tokens}-token prompt. Multimodal placeholders "
|
||||
f"expand after truncation is applied, so the limit must "
|
||||
f"leave every multimodal item intact. Please raise "
|
||||
f"truncate_prompt_tokens or shorten the multimodal input.",
|
||||
parameter="truncate_prompt_tokens",
|
||||
value=params.truncate_prompt_tokens,
|
||||
)
|
||||
|
||||
if start:
|
||||
engine_input["mm_placeholders"] = {
|
||||
modality: [
|
||||
replace(position, offset=position.offset - start)
|
||||
for position in positions
|
||||
]
|
||||
for modality, positions in mm_placeholders.items()
|
||||
}
|
||||
|
||||
engine_input["prompt_token_ids"] = prompt_token_ids[truncation]
|
||||
|
||||
def _process_singleton(
|
||||
self,
|
||||
prompt: SingletonTokPrompt,
|
||||
*,
|
||||
skip_mm_cache: bool = False,
|
||||
tok_params: TokenizeParams | None = None,
|
||||
) -> SingletonInput:
|
||||
if "prompt_embeds" in prompt:
|
||||
return self._process_embeds(prompt) # type: ignore[arg-type]
|
||||
|
||||
return self._process_tokens(prompt, skip_mm_cache=skip_mm_cache) # type: ignore[arg-type]
|
||||
engine_input = self._process_tokens( # type: ignore[arg-type]
|
||||
prompt, # type: ignore[arg-type]
|
||||
skip_mm_cache=skip_mm_cache,
|
||||
)
|
||||
self._truncate_expanded_prompt(engine_input, tok_params)
|
||||
return engine_input
|
||||
|
||||
async def _process_singleton_async(
|
||||
self,
|
||||
prompt: SingletonTokPrompt,
|
||||
*,
|
||||
skip_mm_cache: bool = False,
|
||||
tok_params: TokenizeParams | None = None,
|
||||
) -> SingletonInput:
|
||||
if "prompt_embeds" in prompt:
|
||||
return self._process_embeds(prompt) # type: ignore[arg-type]
|
||||
|
||||
return await self._process_tokens_async(prompt, skip_mm_cache=skip_mm_cache) # type: ignore[arg-type]
|
||||
engine_input = await self._process_tokens_async( # type: ignore[arg-type]
|
||||
prompt, # type: ignore[arg-type]
|
||||
skip_mm_cache=skip_mm_cache,
|
||||
)
|
||||
self._truncate_expanded_prompt(engine_input, tok_params)
|
||||
return engine_input
|
||||
|
||||
def _get_skip_decoder_start_token(self) -> bool:
|
||||
"""Whether the multimodal processor supplies a complete decoder prefix."""
|
||||
@@ -1048,12 +1126,15 @@ class BaseRenderer(ABC, Generic[_T]):
|
||||
arrival_time: float,
|
||||
*,
|
||||
skip_mm_cache: bool = False,
|
||||
tok_params: TokenizeParams | None = None,
|
||||
) -> EngineInput:
|
||||
engine_input: EngineInput
|
||||
if "encoder_prompt" in prompt:
|
||||
engine_input = self._process_enc_dec(prompt, skip_mm_cache=skip_mm_cache) # type: ignore[arg-type]
|
||||
else:
|
||||
engine_input = self._process_singleton(prompt, skip_mm_cache=skip_mm_cache)
|
||||
engine_input = self._process_singleton(
|
||||
prompt, skip_mm_cache=skip_mm_cache, tok_params=tok_params
|
||||
)
|
||||
|
||||
engine_input["arrival_time"] = arrival_time
|
||||
|
||||
@@ -1065,6 +1146,7 @@ class BaseRenderer(ABC, Generic[_T]):
|
||||
arrival_time: float,
|
||||
*,
|
||||
skip_mm_cache: bool = False,
|
||||
tok_params: TokenizeParams | None = None,
|
||||
) -> EngineInput:
|
||||
engine_input: EngineInput
|
||||
if "encoder_prompt" in prompt:
|
||||
@@ -1074,7 +1156,7 @@ class BaseRenderer(ABC, Generic[_T]):
|
||||
)
|
||||
else:
|
||||
engine_input = await self._process_singleton_async(
|
||||
prompt, skip_mm_cache=skip_mm_cache
|
||||
prompt, skip_mm_cache=skip_mm_cache, tok_params=tok_params
|
||||
)
|
||||
|
||||
engine_input["arrival_time"] = arrival_time
|
||||
@@ -1101,7 +1183,9 @@ class BaseRenderer(ABC, Generic[_T]):
|
||||
self._apply_prompt_extras(tok_prompts, prompt_extras)
|
||||
|
||||
return [
|
||||
self.process_for_engine(prompt, arrival_time, skip_mm_cache=skip_mm_cache)
|
||||
self.process_for_engine(
|
||||
prompt, arrival_time, skip_mm_cache=skip_mm_cache, tok_params=tok_params
|
||||
)
|
||||
for prompt in tok_prompts
|
||||
]
|
||||
|
||||
@@ -1126,7 +1210,7 @@ class BaseRenderer(ABC, Generic[_T]):
|
||||
return await asyncio.gather(
|
||||
*(
|
||||
self.process_for_engine_async(
|
||||
p, arrival_time, skip_mm_cache=skip_mm_cache
|
||||
p, arrival_time, skip_mm_cache=skip_mm_cache, tok_params=tok_params
|
||||
)
|
||||
for p in tok_prompts
|
||||
)
|
||||
@@ -1164,7 +1248,9 @@ class BaseRenderer(ABC, Generic[_T]):
|
||||
self._apply_prompt_extras(tok_prompts, prompt_extras)
|
||||
|
||||
eng_prompts = [
|
||||
self.process_for_engine(prompt, arrival_time, skip_mm_cache=skip_mm_cache)
|
||||
self.process_for_engine(
|
||||
prompt, arrival_time, skip_mm_cache=skip_mm_cache, tok_params=tok_params
|
||||
)
|
||||
for prompt in tok_prompts
|
||||
]
|
||||
|
||||
@@ -1204,7 +1290,7 @@ class BaseRenderer(ABC, Generic[_T]):
|
||||
eng_prompts = await asyncio.gather(
|
||||
*(
|
||||
self.process_for_engine_async(
|
||||
p, arrival_time, skip_mm_cache=skip_mm_cache
|
||||
p, arrival_time, skip_mm_cache=skip_mm_cache, tok_params=tok_params
|
||||
)
|
||||
for p in tok_prompts
|
||||
)
|
||||
|
||||
+25
-27
@@ -1194,22 +1194,20 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
|
||||
coordinate space, no offset shifting needed afterwards.
|
||||
"""
|
||||
prompt_embeds_info = cast(dict, prompt).pop("_prompt_embeds", None)
|
||||
if prompt_embeds_info is not None:
|
||||
tensors, placeholder_token_id = prompt_embeds_info
|
||||
mm_updates = _build_prompt_embeds_updates(tensors, placeholder_token_id)
|
||||
cast(dict, prompt)["prompt_token_ids"] = _expand_prompt_embeds_placeholders(
|
||||
list(prompt["prompt_token_ids"]), mm_updates
|
||||
)
|
||||
if prompt_embeds_info is None:
|
||||
return super()._process_tokens(prompt, skip_mm_cache=skip_mm_cache)
|
||||
|
||||
tensors, placeholder_token_id = prompt_embeds_info
|
||||
mm_updates = _build_prompt_embeds_updates(tensors, placeholder_token_id)
|
||||
cast(dict, prompt)["prompt_token_ids"] = _expand_prompt_embeds_placeholders(
|
||||
list(prompt["prompt_token_ids"]), mm_updates
|
||||
)
|
||||
engine_input = super()._process_tokens(prompt, skip_mm_cache=skip_mm_cache)
|
||||
|
||||
if prompt_embeds_info is not None:
|
||||
tensors, _ = prompt_embeds_info
|
||||
self._apply_prompt_embeds_to_engine_input(
|
||||
cast(MultiModalInput, engine_input),
|
||||
tensors,
|
||||
mm_updates,
|
||||
)
|
||||
self._apply_prompt_embeds_to_engine_input(
|
||||
cast(MultiModalInput, engine_input),
|
||||
tensors,
|
||||
mm_updates,
|
||||
)
|
||||
|
||||
return engine_input
|
||||
|
||||
@@ -1222,24 +1220,24 @@ class HfRenderer(BaseRenderer[HfTokenizer]):
|
||||
) -> TokensInput | MultiModalInput:
|
||||
"""Async equivalent of `_process_tokens`."""
|
||||
prompt_embeds_info = cast(dict, prompt).pop("_prompt_embeds", None)
|
||||
if prompt_embeds_info is not None:
|
||||
tensors, placeholder_token_id = prompt_embeds_info
|
||||
mm_updates = _build_prompt_embeds_updates(tensors, placeholder_token_id)
|
||||
cast(dict, prompt)["prompt_token_ids"] = _expand_prompt_embeds_placeholders(
|
||||
list(prompt["prompt_token_ids"]), mm_updates
|
||||
if prompt_embeds_info is None:
|
||||
return await super()._process_tokens_async(
|
||||
prompt, skip_mm_cache=skip_mm_cache
|
||||
)
|
||||
|
||||
tensors, placeholder_token_id = prompt_embeds_info
|
||||
mm_updates = _build_prompt_embeds_updates(tensors, placeholder_token_id)
|
||||
cast(dict, prompt)["prompt_token_ids"] = _expand_prompt_embeds_placeholders(
|
||||
list(prompt["prompt_token_ids"]), mm_updates
|
||||
)
|
||||
engine_input = await super()._process_tokens_async(
|
||||
prompt, skip_mm_cache=skip_mm_cache
|
||||
)
|
||||
|
||||
if prompt_embeds_info is not None:
|
||||
tensors, _ = prompt_embeds_info
|
||||
self._apply_prompt_embeds_to_engine_input(
|
||||
cast(MultiModalInput, engine_input),
|
||||
tensors,
|
||||
mm_updates,
|
||||
)
|
||||
self._apply_prompt_embeds_to_engine_input(
|
||||
cast(MultiModalInput, engine_input),
|
||||
tensors,
|
||||
mm_updates,
|
||||
)
|
||||
|
||||
return engine_input
|
||||
|
||||
|
||||
@@ -398,6 +398,7 @@ class OnlineDerenderer:
|
||||
model=model,
|
||||
choices=stream_choices,
|
||||
usage=usage,
|
||||
metrics=generate_chunk.metrics,
|
||||
)
|
||||
return chunk, updated_state
|
||||
|
||||
@@ -595,6 +596,7 @@ class OnlineDerenderer:
|
||||
model=model,
|
||||
choices=stream_choices,
|
||||
usage=usage,
|
||||
metrics=generate_chunk.metrics,
|
||||
)
|
||||
return chunk, updated_state
|
||||
|
||||
@@ -741,6 +743,7 @@ class OnlineDerenderer:
|
||||
model=model,
|
||||
choices=stream_choices,
|
||||
usage=usage,
|
||||
metrics=generate_chunk.metrics,
|
||||
)
|
||||
return chunk, updated_state
|
||||
|
||||
|
||||
@@ -512,11 +512,10 @@ def _get_attn_isa(
|
||||
)
|
||||
if supports_amx and dtype in (torch.bfloat16,) and block_size % 32 == 0:
|
||||
return "amx"
|
||||
elif supports_arm:
|
||||
return "neon"
|
||||
elif block_size % 32 == 0:
|
||||
if supports_arm:
|
||||
# support ARM NEON FMLA and BFMMLA (bf16) for block size 32
|
||||
return "neon"
|
||||
elif supports_riscv and _riscv_supports_rvv():
|
||||
if supports_riscv and _riscv_supports_rvv():
|
||||
return "rvv"
|
||||
elif supports_vxe:
|
||||
return "vxe"
|
||||
|
||||
@@ -634,6 +634,38 @@ class DeepseekV32IndexerMetadata:
|
||||
prefill: DeepseekV32IndexerPrefillMetadata | None = None
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_reqs", "num_actual_tokens", "num_tokens"])
|
||||
def _kpool_tail_slot_mapping_kernel(
|
||||
slot_mapping_ptr,
|
||||
block_table_ptr,
|
||||
block_table_stride,
|
||||
query_start_loc_ptr,
|
||||
positions_ptr,
|
||||
out_ptr,
|
||||
num_reqs,
|
||||
num_actual_tokens,
|
||||
num_tokens,
|
||||
kpool,
|
||||
BLOCK: tl.constexpr,
|
||||
):
|
||||
pid = tl.program_id(0)
|
||||
if pid < num_reqs:
|
||||
start = tl.load(query_start_loc_ptr + pid)
|
||||
# Tokens past the last request's boundary (if any) also map to it.
|
||||
end = tl.load(query_start_loc_ptr + pid + 1)
|
||||
end = tl.where(pid == num_reqs - 1, num_actual_tokens, end)
|
||||
own_block = tl.load(block_table_ptr + pid * block_table_stride).to(tl.int64)
|
||||
for i in range(start, end, BLOCK):
|
||||
offs = i + tl.arange(0, BLOCK)
|
||||
mask = offs < end
|
||||
pos = tl.load(positions_ptr + offs, mask=mask, other=0).to(tl.int64)
|
||||
tl.store(out_ptr + offs, own_block * kpool + pos % kpool, mask=mask)
|
||||
else:
|
||||
offs = num_actual_tokens + (pid - num_reqs) * BLOCK + tl.arange(0, BLOCK)
|
||||
mask = offs < num_tokens
|
||||
tl.store(out_ptr + offs, tl.load(slot_mapping_ptr + offs, mask=mask), mask=mask)
|
||||
|
||||
|
||||
def compute_kpool_tail_slot_mapping(
|
||||
slot_mapping: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
@@ -646,10 +678,33 @@ def compute_kpool_tail_slot_mapping(
|
||||
) -> torch.Tensor:
|
||||
"""Map every token to its request's one circular tail block."""
|
||||
if out is None:
|
||||
out = slot_mapping.clone()
|
||||
out = torch.empty_like(slot_mapping)
|
||||
else:
|
||||
assert out.shape == slot_mapping.shape
|
||||
out.copy_(slot_mapping)
|
||||
if slot_mapping.is_cuda and slot_mapping.dim() == 1 and num_reqs > 0:
|
||||
block = 256
|
||||
num_tokens = slot_mapping.shape[0]
|
||||
num_actual_tokens = min(num_actual_tokens, num_tokens)
|
||||
grid = (num_reqs + triton.cdiv(num_tokens - num_actual_tokens, block),)
|
||||
_kpool_tail_slot_mapping_kernel[grid](
|
||||
slot_mapping,
|
||||
block_table,
|
||||
block_table.stride(0),
|
||||
query_start_loc,
|
||||
positions,
|
||||
out,
|
||||
num_reqs,
|
||||
num_actual_tokens,
|
||||
num_tokens,
|
||||
kpool,
|
||||
BLOCK=block,
|
||||
num_warps=4,
|
||||
)
|
||||
return out
|
||||
# Torch fallback: CPU tensors (the CPU unit tests), non-1D or empty inputs.
|
||||
# Production always takes the Triton path above — spec-decode tokens arrive
|
||||
# flattened token-major, so slot_mapping is 1D there too.
|
||||
out.copy_(slot_mapping)
|
||||
if num_actual_tokens == 0:
|
||||
return out
|
||||
tokens = torch.arange(num_actual_tokens, device=slot_mapping.device)
|
||||
|
||||
@@ -165,6 +165,9 @@ class SimpleCPUOffloadScheduler:
|
||||
kv_cache_config, offload_capacity
|
||||
)
|
||||
self.num_cpu_blocks = self.cpu_kv_cache_config.num_blocks
|
||||
self.prefix_cacheable_group_ids = (
|
||||
self.cpu_kv_cache_config.prefix_cacheable_group_ids
|
||||
)
|
||||
self.kv_event_medium = MEDIUM_STORAGE if disk_capacity_bytes > 0 else MEDIUM_CPU
|
||||
# Find the full attention kv group for prefix cache matching.
|
||||
self.fa_gidx = -1
|
||||
@@ -297,7 +300,7 @@ class SimpleCPUOffloadScheduler:
|
||||
"""GPU blocks to keep available (free/offloaded) per step in lazy mode."""
|
||||
WATERMARK_RATIO = 1.0 # Reserve larger space to avoid running out of GPU blocks
|
||||
target = 0
|
||||
for g in kv_cache_config.kv_cache_groups:
|
||||
for g in kv_cache_config.prefix_cacheable_groups:
|
||||
spec = g.kv_cache_spec
|
||||
# Only full attention is sharded across DCP ranks; replicated specs
|
||||
# (mamba, sliding window, chunked-local) keep their own block size.
|
||||
@@ -442,6 +445,9 @@ class SimpleCPUOffloadScheduler:
|
||||
# the rest will be released along with the temp pin below.
|
||||
cpu_hit_blocks: list[list[KVCacheBlock]] = []
|
||||
for g in range(num_groups):
|
||||
if g not in self.prefix_cacheable_group_ids:
|
||||
cpu_hit_blocks.append([])
|
||||
continue
|
||||
g_block_size = self.group_block_sizes[g]
|
||||
n_take_g = cdiv(num_external_tokens, g_block_size)
|
||||
cpu_hit_blocks.append(cpu_hit_blocks_full[g][:n_take_g])
|
||||
@@ -828,6 +834,8 @@ class SimpleCPUOffloadScheduler:
|
||||
num_free = self.cpu_block_pool.get_num_free_blocks()
|
||||
|
||||
for g, group_gpu_ids in enumerate(block_ids_by_group):
|
||||
if g not in self.prefix_cacheable_group_ids:
|
||||
continue
|
||||
if len(gpu_block_ids) >= num_free:
|
||||
break
|
||||
group_manager = self.cpu_coordinator.single_type_managers[g]
|
||||
|
||||
@@ -662,6 +662,7 @@ class ModelCudaGraphManager(CudaGraphManager):
|
||||
model_inputs = {
|
||||
"input_ids": input_buffers.input_ids[:num_tokens],
|
||||
"positions": input_buffers.positions[:num_tokens],
|
||||
"intermediate_tensors": None,
|
||||
**model_state.prepare_dummy_inputs(num_reqs, num_tokens),
|
||||
}
|
||||
if not self.is_first_pp_rank:
|
||||
|
||||
@@ -1291,7 +1291,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
# Get the number of draft tokens for each request.
|
||||
draft_tokens = scheduler_output.scheduled_spec_decode_tokens
|
||||
num_draft_tokens_per_req = None
|
||||
if not draft_tokens:
|
||||
if not draft_tokens and self.model_state.num_new_sampled_tokens_per_step == 1:
|
||||
# No draft token scheduled (common case).
|
||||
total_num_draft_tokens = 0
|
||||
total_num_logits = num_reqs
|
||||
@@ -1322,9 +1322,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
np.cumsum(num_logits, out=cu_num_logits_np[1:])
|
||||
cu_num_logits = async_tensor_h2d(cu_num_logits_np, device=self.device)
|
||||
|
||||
adaptive_verification = (
|
||||
self.adaptive_verification if num_draft_tokens_per_req is not None else None
|
||||
)
|
||||
# The general branch also serves a no-draft batch with k != 1, and
|
||||
# compact_batch's budget is only primed when drafts are scheduled.
|
||||
adaptive_verification = self.adaptive_verification if draft_tokens else None
|
||||
num_scheduled_tokens_upper_bound = num_scheduled_tokens_np
|
||||
if adaptive_verification is not None:
|
||||
# num_scheduled_tokens represents the draft budget evenly distributed across
|
||||
@@ -1354,7 +1354,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
adaptive_verification.reallocate_drafts(req_ids, idx_mapping)
|
||||
)
|
||||
total_num_logits = num_reqs * num_bonus_tokens + total_num_draft_tokens
|
||||
if draft_tokens:
|
||||
if num_draft_tokens_per_req is not None:
|
||||
expanded_idx_mapping, expanded_local_pos = expand_idx_mapping(
|
||||
idx_mapping, total_num_logits, cu_num_logits, self.decode_query_len
|
||||
)
|
||||
@@ -1534,7 +1534,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
sample_hidden_states = hidden_states[input_batch.logits_indices]
|
||||
logits = self.model.compute_logits(sample_hidden_states)
|
||||
|
||||
if grammar_output is not None:
|
||||
# A diffusion prefill has no logit rows even when a bitmask row
|
||||
# arrived for it.
|
||||
if grammar_output is not None and logits.shape[0] > 0:
|
||||
# Apply grammar bitmask to the logits in-place.
|
||||
assert self.structured_outputs_worker is not None
|
||||
self.structured_outputs_worker.apply_grammar_bitmask(
|
||||
|
||||
+75
-21
@@ -3,11 +3,12 @@
|
||||
|
||||
import inspect
|
||||
import os
|
||||
from collections.abc import Iterator
|
||||
from collections.abc import Callable, Hashable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from itertools import accumulate
|
||||
from math import prod
|
||||
from typing import TypeVar, cast
|
||||
|
||||
import torch
|
||||
|
||||
@@ -17,6 +18,7 @@ from vllm.utils.math_utils import round_up
|
||||
from vllm.v1.worker.ubatching import dbo_current_ubatch_id
|
||||
|
||||
logger = init_logger(__name__)
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def _compute_bytes(shape: tuple[int, ...], dtype: torch.dtype) -> int:
|
||||
@@ -47,8 +49,8 @@ def use_workspace_lane(lane: int) -> Iterator[None]:
|
||||
class WorkspaceManager:
|
||||
"""Manager for workspace allocation.
|
||||
|
||||
Manages one workspace buffer per active ``(ubatch, lane)`` slot.
|
||||
Can be locked to prevent further growth during execution.
|
||||
Manages shared scratch and keyed persistent resources per ``(ubatch, lane)``.
|
||||
Can be locked to prevent growth or new resources during execution.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -66,6 +68,9 @@ class WorkspaceManager:
|
||||
self._current_workspaces: list[torch.Tensor | None] = [None] * (
|
||||
self._num_ubatches * self._num_lanes
|
||||
)
|
||||
self._persistent_resources: list[dict[Hashable, object]] = [
|
||||
{} for _ in self._current_workspaces
|
||||
]
|
||||
self._locked: bool = False
|
||||
|
||||
@staticmethod
|
||||
@@ -76,10 +81,10 @@ class WorkspaceManager:
|
||||
return workspace.numel() * workspace.element_size()
|
||||
|
||||
def lock(self) -> None:
|
||||
"""Lock the workspace to prevent further growth.
|
||||
"""Lock the workspace to prevent growth or new persistent resources.
|
||||
|
||||
After locking, any attempt to allocate a larger workspace will raise
|
||||
an assertion error. This ensures workspace size is fixed during execution.
|
||||
Larger scratch requests and new persistent resources raise an assertion
|
||||
error. Existing resources retain their storage throughout execution.
|
||||
"""
|
||||
self._locked = True
|
||||
if envs.VLLM_DEBUG_WORKSPACE:
|
||||
@@ -113,6 +118,63 @@ class WorkspaceManager:
|
||||
"""Check if workspace is locked."""
|
||||
return self._locked
|
||||
|
||||
def _get_workspace_id(self) -> int:
|
||||
lane = _workspace_lane.get()
|
||||
if lane >= self._num_lanes:
|
||||
raise RuntimeError(
|
||||
f"Workspace lane {lane} is not configured; manager has "
|
||||
f"{self._num_lanes} lane(s)."
|
||||
)
|
||||
return dbo_current_ubatch_id() * self._num_lanes + lane
|
||||
|
||||
def get_persistent_resource(self, key: Hashable, factory: Callable[[], T]) -> T:
|
||||
"""Return the resource cached for ``key`` in the current ubatch and lane.
|
||||
|
||||
The first request calls ``factory`` and stores its result for the lifetime
|
||||
of this manager. Later requests return the same object without calling
|
||||
the factory again. Each ubatch/lane pair has a separate cache. Once the
|
||||
manager is locked, requesting a key missing from that cache raises an
|
||||
AssertionError.
|
||||
|
||||
Keys must identify the resource type and configuration. Callers must not
|
||||
resize or replace tensor storage held by a cached resource. Uses of the
|
||||
same resource must not overlap; include the CUDA stream in the key when
|
||||
streams can execute concurrently.
|
||||
|
||||
With torch.compile, call this inside a runtime custom op so resource
|
||||
selection happens during execution.
|
||||
"""
|
||||
resources = self._persistent_resources[self._get_workspace_id()]
|
||||
if key not in resources:
|
||||
if self._locked:
|
||||
raise AssertionError(
|
||||
f"Workspace is locked but {key!r} was not allocated during "
|
||||
"warmup for the current ubatch and lane."
|
||||
)
|
||||
resources[key] = factory()
|
||||
return cast(T, resources[key])
|
||||
|
||||
def get_persistent(
|
||||
self,
|
||||
key: Hashable,
|
||||
shape: tuple[int, ...],
|
||||
dtype: torch.dtype,
|
||||
*,
|
||||
zero_init: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""Get a fixed-shape tensor, optionally zeroed on first allocation only."""
|
||||
factory = torch.zeros if zero_init else torch.empty
|
||||
workspace = self.get_persistent_resource(
|
||||
(torch.Tensor, key),
|
||||
lambda: factory(shape, dtype=dtype, device=self._device),
|
||||
)
|
||||
if workspace.shape != shape or workspace.dtype != dtype:
|
||||
raise ValueError(
|
||||
f"Persistent workspace {key!r} has shape={workspace.shape}, "
|
||||
f"dtype={workspace.dtype}; requested shape={shape}, dtype={dtype}."
|
||||
)
|
||||
return workspace
|
||||
|
||||
def get_simultaneous(
|
||||
self, *shapes_and_dtypes: tuple[tuple[int, ...], torch.dtype]
|
||||
) -> list[torch.Tensor]:
|
||||
@@ -151,14 +213,7 @@ class WorkspaceManager:
|
||||
The current workspace tensor.
|
||||
|
||||
"""
|
||||
ubatch_id = dbo_current_ubatch_id()
|
||||
lane = _workspace_lane.get()
|
||||
if lane >= self._num_lanes:
|
||||
raise RuntimeError(
|
||||
f"Workspace lane {lane} is not configured; manager has "
|
||||
f"{self._num_lanes} lane(s)."
|
||||
)
|
||||
workspace_id = ubatch_id * self._num_lanes + lane
|
||||
workspace_id = self._get_workspace_id()
|
||||
current_workspace = self._current_workspaces[workspace_id]
|
||||
current_size = self._workspace_size_bytes(current_workspace)
|
||||
|
||||
@@ -218,8 +273,8 @@ class WorkspaceManager:
|
||||
get_caller_info(),
|
||||
current_size / _MB,
|
||||
required_bytes / _MB,
|
||||
ubatch_id,
|
||||
lane,
|
||||
workspace_id // self._num_lanes,
|
||||
workspace_id % self._num_lanes,
|
||||
)
|
||||
|
||||
return current_workspace
|
||||
@@ -277,12 +332,11 @@ def init_workspace_manager(
|
||||
|
||||
|
||||
def lock_workspace() -> None:
|
||||
"""Lock the workspace to prevent further growth.
|
||||
"""Lock the workspace to prevent growth or new persistent resources.
|
||||
|
||||
After calling this function, any attempt to allocate a workspace larger
|
||||
than the current size will raise an AssertionError. This ensures that
|
||||
workspace size is fixed during execution and prevents unexpected memory
|
||||
allocations in the hot path.
|
||||
Larger scratch requests and new persistent resources raise an AssertionError.
|
||||
All required resources must be initialized in each execution slot during
|
||||
warmup, so their storage remains fixed during execution.
|
||||
|
||||
Example:
|
||||
# During initialization
|
||||
|
||||
Reference in New Issue
Block a user