[Model][ROCm] Enable DeepSeek V4 Vision (#55107)
Signed-off-by: Andreas Karatzas <Andreas.Karatzas@amd.com> Signed-off-by: Andreas Karatzas <akaratza@amd.com> Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
co-authored by
OpenAI Codex
parent
127143e27f
commit
9dd969da09
@@ -79,6 +79,8 @@ from vllm.platforms import current_platform
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from ..common.mm_preprocess import IMAGE_SENTINEL_BASE_ID
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -549,6 +551,10 @@ class DeepseekV4MoE(nn.Module):
|
||||
|
||||
self.gate.e_score_correction_bias = None
|
||||
self.gate.tid2eid = None
|
||||
self.gate.bias_vl = None
|
||||
self.image_sentinel_lo = (
|
||||
IMAGE_SENTINEL_BASE_ID if getattr(config, "vision_n_layers", 0) > 0 else 0
|
||||
)
|
||||
is_hash_moe = extract_layer_index(prefix) < config.num_hash_layers
|
||||
self.hash_indices_dtype = torch.int32
|
||||
if is_hash_moe:
|
||||
@@ -564,12 +570,20 @@ class DeepseekV4MoE(nn.Module):
|
||||
),
|
||||
requires_grad=False,
|
||||
)
|
||||
elif getattr(config, "topk_method", None) == "noaux_tc":
|
||||
if getattr(config, "topk_method", None) == "noaux_tc" and (
|
||||
not is_hash_moe or getattr(config, "vision_n_layers", 0) > 0
|
||||
):
|
||||
self.gate.e_score_correction_bias = nn.Parameter(
|
||||
torch.empty(config.n_routed_experts, dtype=torch.float32),
|
||||
requires_grad=False,
|
||||
)
|
||||
|
||||
if getattr(config, "vision_n_layers", 0) > 0:
|
||||
self.gate.bias_vl = nn.Parameter(
|
||||
torch.empty(config.n_routed_experts, dtype=torch.float32),
|
||||
requires_grad=False,
|
||||
)
|
||||
|
||||
self.n_shared_experts = config.n_shared_experts
|
||||
|
||||
# TODO: Historically, only `VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS=1`
|
||||
@@ -638,6 +652,8 @@ class DeepseekV4MoE(nn.Module):
|
||||
routed_scaling_factor=self.routed_scaling_factor,
|
||||
e_score_correction_bias=self.gate.e_score_correction_bias,
|
||||
hash_indices_table=self.gate.tid2eid,
|
||||
bias_vl=self.gate.bias_vl,
|
||||
image_sentinel_lo=self.image_sentinel_lo,
|
||||
swiglu_limit=self.swiglu_limit,
|
||||
router_logits_dtype=torch.float32,
|
||||
routed_experts_cls=(
|
||||
@@ -660,6 +676,8 @@ class DeepseekV4MoE(nn.Module):
|
||||
) -> torch.Tensor:
|
||||
if self.gate.tid2eid is not None and input_ids is None:
|
||||
raise ValueError("DeepSeek V4 hash MoE routing requires input_ids.")
|
||||
if self.gate.bias_vl is not None and input_ids is None:
|
||||
raise ValueError("DeepSeek V4 vision MoE routing requires input_ids.")
|
||||
|
||||
org_shape = hidden_states.shape
|
||||
final_hidden_states = self.experts(
|
||||
@@ -1351,6 +1369,7 @@ def _make_deepseek_v4_weights_mapper(
|
||||
|
||||
class DeepseekV4ForCausalLM(nn.Module, SupportsPP, SupportsEagle3):
|
||||
model_cls = DeepseekV4Model
|
||||
finalizes_weights_during_load = False
|
||||
|
||||
# Default mapper assumes the original FP4-expert checkpoint layout.
|
||||
# Overridden per-instance in __init__ when expert_dtype != "fp4".
|
||||
@@ -1397,6 +1416,9 @@ class DeepseekV4ForCausalLM(nn.Module, SupportsPP, SupportsEagle3):
|
||||
logits = self.logits_processor(self.lm_head, hidden_states)
|
||||
return logits
|
||||
|
||||
def compute_logits_local(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return self.logits_processor(self.lm_head, hidden_states, skip_gather=True)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
|
||||
@@ -160,7 +160,7 @@ class DeepSeekV4MultiTokenPredictorLayer(nn.Module):
|
||||
inputs_embeds
|
||||
).unsqueeze(-2)
|
||||
hidden_states, residual, post_mix, res_mix = self.mtp_block(
|
||||
positions=positions, x=hidden_states, input_ids=None
|
||||
positions=positions, x=hidden_states, input_ids=input_ids
|
||||
)
|
||||
if self.mtp_block.use_fused_mhc:
|
||||
hidden_states = self.mtp_block.hc_post(
|
||||
|
||||
@@ -67,8 +67,13 @@ def weight_already_preshuffled(linear: torch.nn.Module) -> bool:
|
||||
The hand-shuffles below (fused_wqa_wkv, wo_b, gate_up_proj) must be skipped
|
||||
for those, since shuffle_weight is a permutation rather than an involution.
|
||||
"""
|
||||
kernel = getattr(getattr(linear, "quant_method", None), "fp8_linear", None)
|
||||
return bool(getattr(kernel, "preshuffles_weight", False))
|
||||
return any(
|
||||
getattr(getattr(method, "fp8_linear", None), "preshuffles_weight", False)
|
||||
for method in (
|
||||
getattr(linear, "quant_method", None),
|
||||
getattr(linear, "scheme", None),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def apply_pre_quantized_block_scaled_mm(
|
||||
@@ -116,13 +121,18 @@ def _combine_topk_swa_indices_kernel(
|
||||
query_start_loc_ptr,
|
||||
seq_lens_ptr,
|
||||
gather_lens_ptr,
|
||||
left_visible_ptr,
|
||||
right_visible_ptr,
|
||||
M,
|
||||
N,
|
||||
TOP_K: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
WINDOW_SIZE: tl.constexpr,
|
||||
SWA_WIDTH: tl.constexpr,
|
||||
TOPK_WIDTH: tl.constexpr,
|
||||
PADDED_TOP_K: tl.constexpr,
|
||||
PADDED_SWA_WIDTH: tl.constexpr,
|
||||
HAS_IMAGE: tl.constexpr,
|
||||
):
|
||||
batch_idx = tl.program_id(0)
|
||||
worker_id = tl.program_id(1)
|
||||
@@ -141,7 +151,20 @@ def _combine_topk_swa_indices_kernel(
|
||||
token_idx_in_query = token_idx - query_start
|
||||
pos = start_pos + token_idx_in_query
|
||||
topk_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K)
|
||||
swa_len = tl.minimum(pos + 1, WINDOW_SIZE)
|
||||
if HAS_IMAGE:
|
||||
left = tl.load(left_visible_ptr + token_idx)
|
||||
right = tl.load(right_visible_ptr + token_idx)
|
||||
else:
|
||||
left = 0
|
||||
right = 0
|
||||
left_add = tl.maximum(left - (WINDOW_SIZE - 1), 0)
|
||||
# Prefix caching can resume inside an image span. Do not generate
|
||||
# indices outside the SWA rows present in the gathered workspace.
|
||||
swa_start = tl.maximum(
|
||||
tl.maximum(pos - (WINDOW_SIZE - 1) - left_add, 0), gather_start
|
||||
)
|
||||
swa_end = tl.minimum(pos + right + 1, seq_len)
|
||||
swa_len = tl.maximum(swa_end - swa_start, 0)
|
||||
|
||||
topk_offset = tl.arange(0, PADDED_TOP_K)
|
||||
topk_mask = topk_offset < topk_len
|
||||
@@ -159,14 +182,14 @@ def _combine_topk_swa_indices_kernel(
|
||||
mask=topk_mask,
|
||||
)
|
||||
|
||||
swa_offset = tl.arange(0, WINDOW_SIZE)
|
||||
swa_offset = tl.arange(0, PADDED_SWA_WIDTH)
|
||||
tl.store(
|
||||
combined_indices_ptr
|
||||
+ token_idx * combined_indices_stride
|
||||
+ topk_len
|
||||
+ swa_offset,
|
||||
M * batch_idx + N + swa_offset + pos - swa_len + 1 - gather_start,
|
||||
mask=swa_offset < swa_len,
|
||||
M * batch_idx + N + swa_offset + swa_start - gather_start,
|
||||
mask=(swa_offset < swa_len) & (swa_offset < SWA_WIDTH),
|
||||
)
|
||||
|
||||
tl.store(combined_lens_ptr + token_idx, topk_len + swa_len)
|
||||
@@ -182,12 +205,21 @@ def combine_topk_swa_indices(
|
||||
topk: int,
|
||||
M: int,
|
||||
N: int,
|
||||
max_image_tokens: int = 0,
|
||||
left_visible: torch.Tensor | None = None,
|
||||
right_visible: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if (left_visible is None) != (right_visible is None):
|
||||
raise ValueError("left_visible and right_visible must be provided together")
|
||||
topk_indices = topk_indices.reshape(topk_indices.shape[0], -1).contiguous()
|
||||
num_tokens = topk_indices.shape[0]
|
||||
num_reqs = seq_lens.shape[0]
|
||||
has_image = left_visible is not None
|
||||
# Keep the row shape fixed for a vision model even when a particular batch
|
||||
# has no image.
|
||||
swa_width = window_size + max_image_tokens
|
||||
combined_topk = (
|
||||
(topk + window_size + _SPARSE_PREFILL_TOPK_ALIGNMENT - 1)
|
||||
(topk + swa_width + _SPARSE_PREFILL_TOPK_ALIGNMENT - 1)
|
||||
// _SPARSE_PREFILL_TOPK_ALIGNMENT
|
||||
* _SPARSE_PREFILL_TOPK_ALIGNMENT
|
||||
)
|
||||
@@ -211,13 +243,18 @@ def combine_topk_swa_indices(
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
gather_lens,
|
||||
left_visible if left_visible is not None else topk_indices,
|
||||
right_visible if right_visible is not None else topk_indices,
|
||||
M,
|
||||
N,
|
||||
TOP_K=topk,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
WINDOW_SIZE=window_size,
|
||||
SWA_WIDTH=swa_width,
|
||||
TOPK_WIDTH=topk_indices.shape[-1],
|
||||
PADDED_TOP_K=triton.next_power_of_2(topk_indices.shape[-1]),
|
||||
PADDED_SWA_WIDTH=triton.next_power_of_2(swa_width),
|
||||
HAS_IMAGE=has_image,
|
||||
)
|
||||
return combined_indices, combined_lens
|
||||
|
||||
@@ -948,6 +985,12 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
assert query_start_loc_cpu is not None
|
||||
assert query_start_loc is not None
|
||||
prefill_token_base = query_start_loc_cpu[num_decodes]
|
||||
left_visible = swa_metadata.prefill_left_visible
|
||||
right_visible = swa_metadata.prefill_right_visible
|
||||
if left_visible is not None:
|
||||
left_visible = left_visible[num_decode_tokens:]
|
||||
assert right_visible is not None
|
||||
right_visible = right_visible[num_decode_tokens:]
|
||||
|
||||
if not swa_only:
|
||||
if self.compress_ratio == 4:
|
||||
@@ -1026,6 +1069,17 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
top_k,
|
||||
M,
|
||||
N,
|
||||
max_image_tokens=self.max_image_tokens,
|
||||
left_visible=(
|
||||
left_visible[query_start:query_end]
|
||||
if left_visible is not None
|
||||
else None
|
||||
),
|
||||
right_visible=(
|
||||
right_visible[query_start:query_end]
|
||||
if right_visible is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
rocm_sparse_attn_prefill(
|
||||
q=q[query_start:query_end],
|
||||
|
||||
Reference in New Issue
Block a user