[Feat] DeepSeek V4 Rebased (#40860)
Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai> Signed-off-by: Woosuk Kwon <woosuk@inferact.ai> Signed-off-by: qizixi <zixi@inferact.ai> Signed-off-by: Jee Jee Li <pandaleefree@gmail.com> Signed-off-by: Yongye Zhu <zyy1102000@gmail.com> Co-authored-by: Yongye Zhu <zyy1102000@gmail.com> Co-authored-by: Yongye Zhu <yongye@inferact.ai> Co-authored-by: Simon Mo <simon@inferact.ai> Co-authored-by: Bugen Zhao <i@bugenzhao.com> Co-authored-by: Giancarlo Delfin <gdelfin@inferact.ai> Co-authored-by: Jee Jee Li <pandaleefree@gmail.com> Co-authored-by: Nick Hill <nickhill123@gmail.com> Co-authored-by: Roger Wang <hey@rogerw.io> Co-authored-by: Roy Wang <yasong.wang@inferact.ai> Co-authored-by: Woosuk Kwon <woosuk@inferact.ai> Co-authored-by: youkaichao <youkaichao@gmail.com> Co-authored-by: Zhewen Li <jerven.vllm@gmail.com> Co-authored-by: Zijing Liu <liuzijing2014@gmail.com> Co-authored-by: khluu <khluu000@gmail.com> Co-authored-by: qizixi <zixi@inferact.ai> Co-authored-by: Zhewen Li <zhewenli@inferact.ai>
This commit is contained in:
co-authored by
Yongye Zhu
Yongye Zhu
Simon Mo
Bugen Zhao
Giancarlo Delfin
Jee Jee Li
Nick Hill
Roger Wang
Roy Wang
Woosuk Kwon
youkaichao
Zhewen Li
Zijing Liu
khluu
qizixi
Zhewen Li
parent
32e45636e3
commit
4d51588e23
@@ -7,7 +7,10 @@ from typing import Any
|
||||
import torch
|
||||
|
||||
from .base import RotaryEmbedding
|
||||
from .deepseek_scaling_rope import DeepseekScalingRotaryEmbedding
|
||||
from .deepseek_scaling_rope import (
|
||||
DeepseekScalingRotaryEmbedding,
|
||||
DeepseekV4ScalingRotaryEmbedding,
|
||||
)
|
||||
from .dual_chunk_rope import DualChunkRotaryEmbedding
|
||||
from .dynamic_ntk_alpha_rope import DynamicNTKAlphaRotaryEmbedding
|
||||
from .dynamic_ntk_scaling_rope import DynamicNTKScalingRotaryEmbedding
|
||||
@@ -60,11 +63,13 @@ def get_rope(
|
||||
rope_parameters = rope_parameters or {}
|
||||
base = rope_parameters.get("rope_theta", 10000)
|
||||
scaling_type = rope_parameters.get("rope_type", "default")
|
||||
partial_rotary_factor = rope_parameters.get("partial_rotary_factor", 1.0)
|
||||
|
||||
if partial_rotary_factor <= 0.0 or partial_rotary_factor > 1.0:
|
||||
raise ValueError(f"{partial_rotary_factor=} must be between 0.0 and 1.0")
|
||||
rotary_dim = int(head_size * partial_rotary_factor)
|
||||
if rotary_dim := rope_parameters.get("rope_dim", None):
|
||||
pass
|
||||
else:
|
||||
partial_rotary_factor = rope_parameters.get("partial_rotary_factor", 1.0)
|
||||
if partial_rotary_factor <= 0.0 or partial_rotary_factor > 1.0:
|
||||
raise ValueError(f"{partial_rotary_factor=} must be between 0.0 and 1.0")
|
||||
rotary_dim = int(head_size * partial_rotary_factor)
|
||||
|
||||
key = (
|
||||
head_size,
|
||||
@@ -289,7 +294,11 @@ def get_rope(
|
||||
"mscale_all_dim",
|
||||
)
|
||||
}
|
||||
rotary_emb = DeepseekScalingRotaryEmbedding(
|
||||
if rope_parameters.get("is_deepseek_v4", False):
|
||||
cls = DeepseekV4ScalingRotaryEmbedding
|
||||
else:
|
||||
cls = DeepseekScalingRotaryEmbedding
|
||||
rotary_emb = cls(
|
||||
head_size,
|
||||
rotary_dim,
|
||||
original_max_position,
|
||||
|
||||
@@ -132,10 +132,8 @@ class DeepseekScalingRotaryEmbedding(RotaryEmbeddingBase):
|
||||
]
|
||||
cos, sin = cos_sin.chunk(2, dim=-1)
|
||||
if self.is_neox_style:
|
||||
# NOTE(woosuk): Here we assume that the positions tensor has the
|
||||
# shape [batch_size, seq_len].
|
||||
cos = cos.repeat(1, 1, 2).unsqueeze(-2)
|
||||
sin = sin.repeat(1, 1, 2).unsqueeze(-2)
|
||||
cos = torch.cat((cos, cos), dim=-1).unsqueeze(-2)
|
||||
sin = torch.cat((sin, sin), dim=-1).unsqueeze(-2)
|
||||
else:
|
||||
cos = cos.repeat_interleave(2, dim=-1).unsqueeze(-2)
|
||||
sin = sin.repeat_interleave(2, dim=-1).unsqueeze(-2)
|
||||
@@ -197,3 +195,118 @@ class DeepseekScalingRotaryEmbedding(RotaryEmbeddingBase):
|
||||
return query, key
|
||||
else:
|
||||
return self.forward_native(positions, query, key, offsets)
|
||||
|
||||
|
||||
class DeepseekV4ScalingRotaryEmbedding(DeepseekScalingRotaryEmbedding):
|
||||
"""RotaryEmbedding extended with YaRN method.
|
||||
|
||||
Credits to Peng et al. github.com/jquesnelle/yarn
|
||||
|
||||
Compared to DeepseekScalingRotaryEmbedding:
|
||||
- Applies RoPE to the last rotary_dim
|
||||
- The forward method requires an inverse parameter to indicate
|
||||
whether to negate the sin
|
||||
- Supports applying RoPE to query only (without key)
|
||||
- cos_sin_cache stored as fp32 for higher precision RoPE
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
cache_fp32 = self._compute_cos_sin_cache()
|
||||
self.register_buffer("cos_sin_cache", cache_fp32, persistent=False)
|
||||
|
||||
def _compute_cos_sin_cache(self) -> torch.Tensor:
|
||||
inv_freq = self._compute_inv_freq(self.scaling_factor)
|
||||
t = torch.arange(
|
||||
self.max_position_embeddings * self.scaling_factor,
|
||||
device=current_platform.device_type,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
freqs = torch.einsum("i,j -> ij", t, inv_freq)
|
||||
cos = freqs.cos() * self.mscale
|
||||
sin = freqs.sin() * self.mscale
|
||||
cache = torch.cat((cos, sin), dim=-1)
|
||||
return cache
|
||||
|
||||
def forward_native(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor | None = None,
|
||||
offsets: torch.Tensor | None = None,
|
||||
inverse: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
"""PyTorch-native implementation equivalent to forward()."""
|
||||
|
||||
head_size = query.size(-1)
|
||||
query_rot = query[..., -self.rotary_dim :]
|
||||
key_rot = key[..., -self.rotary_dim :] if key is not None else None
|
||||
|
||||
if self.rotary_dim < head_size:
|
||||
query_pass = query[..., : -self.rotary_dim]
|
||||
key_pass = key[..., : -self.rotary_dim] if key is not None else None
|
||||
|
||||
cos_sin = self.cos_sin_cache[
|
||||
torch.add(positions, offsets) if offsets is not None else positions
|
||||
]
|
||||
cos, sin = cos_sin.chunk(2, dim=-1)
|
||||
if self.is_neox_style:
|
||||
cos = torch.cat((cos, cos), dim=-1).unsqueeze(-2)
|
||||
sin = torch.cat((sin, sin), dim=-1).unsqueeze(-2)
|
||||
else:
|
||||
cos = cos.repeat_interleave(2, dim=-1).unsqueeze(-2)
|
||||
sin = sin.repeat_interleave(2, dim=-1).unsqueeze(-2)
|
||||
if inverse:
|
||||
sin = -sin
|
||||
rotate_fn = rotate_neox if self.is_neox_style else rotate_gptj
|
||||
orig_dtype = query.dtype
|
||||
query_rot = (query_rot * cos + rotate_fn(query_rot) * sin).to(orig_dtype)
|
||||
if key_rot is not None:
|
||||
key_rot = (key_rot * cos + rotate_fn(key_rot) * sin).to(orig_dtype)
|
||||
|
||||
if self.rotary_dim < head_size:
|
||||
query = torch.cat((query_pass, query_rot), dim=-1)
|
||||
key = torch.cat((key_pass, key_rot), dim=-1) if key is not None else None
|
||||
else:
|
||||
query = query_rot
|
||||
key = key_rot
|
||||
|
||||
return query, key
|
||||
|
||||
def forward_hip(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor | None = None,
|
||||
offsets: torch.Tensor | None = None,
|
||||
inverse: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
return self.forward_native(positions, query, key, offsets)
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
positions: torch.Tensor,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor | None = None,
|
||||
offsets: torch.Tensor | None = None,
|
||||
inverse: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
from vllm import _custom_ops as ops
|
||||
|
||||
# The indexer and attention have different head_dim,
|
||||
# we obtain the corresponding head_dim via the query.
|
||||
head_size = query.size(-1)
|
||||
rope_dim_offset = head_size - self.rotary_dim
|
||||
# ops.rotary_embedding() is an in-place operation
|
||||
# that updates the query and key tensors.
|
||||
ops.rotary_embedding(
|
||||
torch.add(positions, offsets) if offsets is not None else positions,
|
||||
query,
|
||||
key,
|
||||
head_size,
|
||||
self.cos_sin_cache,
|
||||
self.is_neox_style,
|
||||
rope_dim_offset=rope_dim_offset,
|
||||
inverse=inverse,
|
||||
)
|
||||
return query, key
|
||||
|
||||
Reference in New Issue
Block a user