Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Deepseek-V2] Fused rope implementation #3105

Merged
merged 1 commit into from
Jan 24, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 25 additions & 19 deletions python/mlc_llm/model/deepseek_v2/deepseek_v2_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,38 +137,44 @@ def forward(
k: Tensor,
positions: Tensor,
):
def _rope(x: te.Tensor, positions: te.Tensor):
def _rope_fused(x: te.Tensor, positions: te.Tensor):
_, _, _, d_dim = x.shape
d_dim_half = d_dim // 2
dtype = x.dtype

def compute(b: tir.Var, s: tir.Var, h: tir.Var, d: tir.Var):
d1 = d // d_dim_half
d2 = d % d_dim_half

cos_freq, sin_freq, var_map = self.rope_fn(
positions[s], d, self.rotary_dim, self.theta, dtype
)
cos = cos_freq * x[b, s, h, d]
sin = sin_freq * tir.if_then_else(
cos = x[b, s, h, d2 * 2 + d1] * cos_freq

partner_d = tir.if_then_else(
d < self.rotary_dim // 2,
-x[b, s, h, d + self.rotary_dim // 2],
x[b, s, h, d - self.rotary_dim // 2],
d + self.rotary_dim // 2,
d - self.rotary_dim // 2,
)

partner_d1 = partner_d // d_dim_half
partner_d2 = partner_d % d_dim_half
sin = (
x[b, s, h, partner_d2 * 2 + partner_d1]
* sin_freq
* tir.if_then_else(
d < self.rotary_dim // 2, tir.const(-1, dtype), tir.const(1, dtype)
)
)
expr = cos + sin
for var, value in var_map.items():
expr = tir.Let(var, value, expr)
for var, val in var_map.items():
expr = tir.Let(var, val, expr)
return expr

return te.compute(x.shape, compute, name="yarn_rope")

b, s, h, d = q.shape
q = op.reshape(
op.permute_dims(op.reshape(q, (b, s, h, d // 2, 2)), [0, 1, 2, 4, 3]), (b, s, h, d)
)

b, s, h, d = k.shape
k = op.reshape(
op.permute_dims(op.reshape(k, (b, s, h, d // 2, 2)), [0, 1, 2, 4, 3]), (b, s, h, d)
)

q_embed = op.tensor_expr_op(_rope, "rope", [q, positions])
k_embed = op.tensor_expr_op(_rope, "rope", [k, positions])
q_embed = op.tensor_expr_op(_rope_fused, "rope", [q, positions])
k_embed = op.tensor_expr_op(_rope_fused, "rope", [k, positions])
return q_embed, k_embed


Expand Down
Loading