[Model] Add Kimi K3 support: model files and kernels [1/N] (#50089)
Signed-off-by: zjy0516 <riverclouds.zhu@qq.com> Signed-off-by: Isotr0py <Isotr0py@outlook.com> Signed-off-by: Bugen Zhao <i@bugenzhao.com> Signed-off-by: Yongye Zhu <zyy1102000@gmail.com> Co-authored-by: Isotr0py <Isotr0py@outlook.com> Co-authored-by: Thien Tran <gau.nernst@yahoo.com.sg> Co-authored-by: Bugen Zhao <i@bugenzhao.com> Co-authored-by: Yongye Zhu <zyy1102000@gmail.com> Co-authored-by: Ziming Huang <zelda.huanghuang@gmail.com> Co-authored-by: Roger Wang <hey@rogerw.io> Co-authored-by: Isotr0py <mozf@inferact.ai> Co-authored-by: aoshen02 <aoshen02@users.noreply.github.com> Co-authored-by: Woosuk Kwon <woosuk@inferact.ai> Co-authored-by: Jee Jee Li <jeejeelee@inferact.ai> Co-authored-by: aoshen02 <aoshen@inferact.ai> Co-authored-by: Summer Yang <girasoleyang@gmail.com> Co-authored-by: Kevin H. Luu <khluu000@gmail.com> Co-authored-by: Bowen Wang <abmfy@icloud.com> Co-authored-by: gnovack <novackgm@gmail.com> Co-authored-by: Nick Hill <nickhill123@gmail.com> Co-authored-by: Yifan Qiao <yifanqiao@inferact.ai> Co-authored-by: xiaozhoupy <peiyuanzhou1994@gmail.com> Co-authored-by: Roy Wang <yasong.wang@inferact.ai> Co-authored-by: Jeff (Junze) Ma <93145857+majunze2001@users.noreply.github.com> Co-authored-by: Codex <codex@openai.com>
This commit is contained in:
co-authored by
Isotr0py
Thien Tran
Bugen Zhao
Yongye Zhu
Ziming Huang
Roger Wang
Isotr0py
aoshen02
Woosuk Kwon
Jee Jee Li
aoshen02
Summer Yang
Kevin H. Luu
Bowen Wang
gnovack
Nick Hill
Yifan Qiao
xiaozhoupy
Roy Wang
Jeff Ma
Codex
parent
6f00a1ae3b
commit
7c6729b769
@@ -0,0 +1,412 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Songlin Yang, Yu Zhang
|
||||
#
|
||||
# This file contains code copied from the flash-linear-attention project.
|
||||
# The original source was licensed under the MIT license.
|
||||
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
||||
# ruff: noqa: E501
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.model_executor.custom_op import CustomOp
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.math_utils import cdiv, next_power_of_2
|
||||
|
||||
@triton.heuristics(
|
||||
{
|
||||
"STORE_RESIDUAL_OUT": lambda args: args["residual_out"] is not None,
|
||||
"HAS_RESIDUAL": lambda args: args["residual"] is not None,
|
||||
"HAS_WEIGHT": lambda args: args["w"] is not None,
|
||||
"HAS_BIAS": lambda args: args["b"] is not None,
|
||||
}
|
||||
)
|
||||
@triton.jit
|
||||
def layer_norm_gated_fwd_kernel(
|
||||
x, # pointer to the input
|
||||
g, # pointer to the gate
|
||||
y, # pointer to the output
|
||||
w, # pointer to the weights
|
||||
b, # pointer to the biases
|
||||
residual, # pointer to the residual
|
||||
residual_out, # pointer to the residual
|
||||
mean, # pointer to the mean
|
||||
rstd, # pointer to the 1/std
|
||||
eps, # epsilon to avoid division by zero
|
||||
T, # number of rows in x
|
||||
H: tl.constexpr, # number of heads
|
||||
g_stride_n,
|
||||
D: tl.constexpr, # number of columns in x
|
||||
BT: tl.constexpr,
|
||||
BD: tl.constexpr,
|
||||
ACTIVATION: tl.constexpr,
|
||||
IS_RMS_NORM: tl.constexpr,
|
||||
STORE_RESIDUAL_OUT: tl.constexpr,
|
||||
HAS_RESIDUAL: tl.constexpr,
|
||||
HAS_WEIGHT: tl.constexpr,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
):
|
||||
i_t = tl.program_id(0)
|
||||
|
||||
o_d = tl.arange(0, BD)
|
||||
m_d = o_d < D
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
p_x = tl.make_block_ptr(x, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
|
||||
b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32)
|
||||
if HAS_RESIDUAL:
|
||||
p_res = tl.make_block_ptr(
|
||||
residual, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0)
|
||||
)
|
||||
b_x += tl.load(p_res, boundary_check=(0, 1)).to(tl.float32)
|
||||
if STORE_RESIDUAL_OUT:
|
||||
p_res_out = tl.make_block_ptr(
|
||||
residual_out, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0)
|
||||
)
|
||||
tl.store(p_res_out, b_x.to(p_res_out.dtype.element_ty), boundary_check=(0, 1))
|
||||
if not IS_RMS_NORM:
|
||||
b_mean = tl.sum(b_x, axis=1) / D
|
||||
p_mean = tl.make_block_ptr(mean, (T,), (1,), (i_t * BT,), (BT,), (0,))
|
||||
tl.store(p_mean, b_mean.to(p_mean.dtype.element_ty), boundary_check=(0,))
|
||||
b_xbar = tl.where(m_d[None, :], b_x - b_mean[:, None], 0.0)
|
||||
b_var = tl.sum(b_xbar * b_xbar, axis=1) / D
|
||||
else:
|
||||
b_xbar = tl.where(m_d[None, :], b_x, 0.0)
|
||||
b_var = tl.sum(b_xbar * b_xbar, axis=1) / D
|
||||
b_rstd = 1 / tl.sqrt(b_var + eps)
|
||||
|
||||
p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t * BT,), (BT,), (0,))
|
||||
tl.store(p_rstd, b_rstd.to(p_rstd.dtype.element_ty), boundary_check=(0,))
|
||||
|
||||
if HAS_WEIGHT:
|
||||
b_w = tl.load(w + o_d, mask=m_d).to(tl.float32)
|
||||
if HAS_BIAS:
|
||||
b_b = tl.load(b + o_d, mask=m_d).to(tl.float32)
|
||||
b_x_hat = (
|
||||
(b_x - b_mean[:, None]) * b_rstd[:, None]
|
||||
if not IS_RMS_NORM
|
||||
else b_x * b_rstd[:, None]
|
||||
)
|
||||
b_y = b_x_hat * b_w[None, :] if HAS_WEIGHT else b_x_hat
|
||||
if HAS_BIAS:
|
||||
b_y = b_y + b_b[None, :]
|
||||
|
||||
# swish/sigmoid output gate
|
||||
o_t = i_t * BT + tl.arange(0, BT)
|
||||
o_g = (o_t // H) * g_stride_n + (o_t % H) * D
|
||||
b_g = tl.load(
|
||||
g + o_g[:, None] + o_d[None, :],
|
||||
mask=(o_t[:, None] < T) & m_d[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
if ACTIVATION == "swish" or ACTIVATION == "silu":
|
||||
b_y = b_y * b_g * tl.sigmoid(b_g)
|
||||
elif ACTIVATION == "sigmoid":
|
||||
b_y = b_y * tl.sigmoid(b_g)
|
||||
|
||||
# Write output
|
||||
p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
|
||||
tl.store(p_y, b_y.to(p_y.dtype.element_ty), boundary_check=(0, 1))
|
||||
|
||||
|
||||
@triton.heuristics(
|
||||
{
|
||||
"STORE_RESIDUAL_OUT": lambda args: args["residual_out"] is not None,
|
||||
"HAS_RESIDUAL": lambda args: args["residual"] is not None,
|
||||
"HAS_WEIGHT": lambda args: args["w"] is not None,
|
||||
"HAS_BIAS": lambda args: args["b"] is not None,
|
||||
}
|
||||
)
|
||||
@triton.jit
|
||||
def layer_norm_gated_fwd_kernel1(
|
||||
x, # pointer to the input
|
||||
g, # pointer to the gate
|
||||
y, # pointer to the output
|
||||
w, # pointer to the weights
|
||||
b, # pointer to the biases
|
||||
residual, # pointer to the residual
|
||||
residual_out, # pointer to the residual
|
||||
mean, # pointer to the mean
|
||||
rstd, # pointer to the 1/std
|
||||
eps, # epsilon to avoid division by zero
|
||||
D: tl.constexpr, # number of columns in x
|
||||
BD: tl.constexpr,
|
||||
ACTIVATION: tl.constexpr,
|
||||
IS_RMS_NORM: tl.constexpr,
|
||||
STORE_RESIDUAL_OUT: tl.constexpr,
|
||||
HAS_RESIDUAL: tl.constexpr,
|
||||
HAS_WEIGHT: tl.constexpr,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
):
|
||||
i_t = tl.program_id(0)
|
||||
x += i_t * D
|
||||
y += i_t * D
|
||||
g += i_t * D
|
||||
if HAS_RESIDUAL:
|
||||
residual += i_t * D
|
||||
if STORE_RESIDUAL_OUT:
|
||||
residual_out += i_t * D
|
||||
|
||||
if launch_pdl:
|
||||
tl.extra.cuda.gdc_wait()
|
||||
tl.extra.cuda.gdc_launch_dependents()
|
||||
|
||||
o_d = tl.arange(0, BD)
|
||||
m_d = o_d < D
|
||||
b_x = tl.load(x + o_d, mask=m_d, other=0.0).to(tl.float32)
|
||||
if HAS_RESIDUAL:
|
||||
b_x += tl.load(residual + o_d, mask=m_d, other=0.0).to(tl.float32)
|
||||
if STORE_RESIDUAL_OUT:
|
||||
tl.store(residual_out + o_d, b_x, mask=m_d)
|
||||
if not IS_RMS_NORM:
|
||||
b_mean = tl.sum(b_x, axis=0) / D
|
||||
tl.store(mean + i_t, b_mean)
|
||||
b_xbar = tl.where(m_d, b_x - b_mean, 0.0)
|
||||
b_var = tl.sum(b_xbar * b_xbar, axis=0) / D
|
||||
else:
|
||||
b_xbar = tl.where(m_d, b_x, 0.0)
|
||||
b_var = tl.sum(b_xbar * b_xbar, axis=0) / D
|
||||
b_rstd = 1 / tl.sqrt(b_var + eps)
|
||||
tl.store(rstd + i_t, b_rstd)
|
||||
|
||||
if HAS_WEIGHT:
|
||||
b_w = tl.load(w + o_d, mask=m_d).to(tl.float32)
|
||||
if HAS_BIAS:
|
||||
b_b = tl.load(b + o_d, mask=m_d).to(tl.float32)
|
||||
b_x_hat = (b_x - b_mean) * b_rstd if not IS_RMS_NORM else b_x * b_rstd
|
||||
b_y = b_x_hat * b_w if HAS_WEIGHT else b_x_hat
|
||||
if HAS_BIAS:
|
||||
b_y = b_y + b_b
|
||||
|
||||
# swish/sigmoid output gate
|
||||
b_g = tl.load(g + o_d, mask=m_d, other=0.0).to(tl.float32)
|
||||
if ACTIVATION == "swish" or ACTIVATION == "silu":
|
||||
b_y = b_y * b_g * tl.sigmoid(b_g)
|
||||
elif ACTIVATION == "sigmoid":
|
||||
b_y = b_y * tl.sigmoid(b_g)
|
||||
|
||||
# Write output
|
||||
tl.store(y + o_d, b_y, mask=m_d)
|
||||
|
||||
|
||||
def layer_norm_gated_fwd(
|
||||
x: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor,
|
||||
activation: str = "swish",
|
||||
eps: float = 1e-5,
|
||||
residual: torch.Tensor = None,
|
||||
out_dtype: torch.dtype = None,
|
||||
residual_dtype: torch.dtype = None,
|
||||
is_rms_norm: bool = False,
|
||||
H: int = 1,
|
||||
g_stride_n: int | None = None,
|
||||
):
|
||||
if residual is not None:
|
||||
residual_dtype = residual.dtype
|
||||
T, D = x.shape
|
||||
if g_stride_n is None:
|
||||
g_stride_n = D
|
||||
assert T % H == 0
|
||||
if residual is not None:
|
||||
assert residual.shape == (T, D)
|
||||
if weight is not None:
|
||||
assert weight.shape == (D,)
|
||||
if bias is not None:
|
||||
assert bias.shape == (D,)
|
||||
# allocate output
|
||||
y = x if out_dtype is None else torch.empty_like(x, dtype=out_dtype)
|
||||
if residual is not None or (
|
||||
residual_dtype is not None and residual_dtype != x.dtype
|
||||
):
|
||||
residual_out = torch.empty(T, D, device=x.device, dtype=residual_dtype)
|
||||
else:
|
||||
residual_out = None
|
||||
mean = (
|
||||
torch.empty((T,), dtype=torch.float, device=x.device)
|
||||
if not is_rms_norm
|
||||
else None
|
||||
)
|
||||
rstd = torch.empty((T,), dtype=torch.float, device=x.device)
|
||||
# Less than 64KB per feature: enqueue fused kernel
|
||||
MAX_FUSED_SIZE = 65536 // x.element_size()
|
||||
BD = min(MAX_FUSED_SIZE, next_power_of_2(D))
|
||||
if D > BD:
|
||||
raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
|
||||
if D <= 512:
|
||||
BT = 16
|
||||
layer_norm_gated_fwd_kernel[(cdiv(T, BT),)](
|
||||
x=x,
|
||||
g=g,
|
||||
y=y,
|
||||
w=weight,
|
||||
b=bias,
|
||||
residual=residual,
|
||||
residual_out=residual_out,
|
||||
mean=mean,
|
||||
rstd=rstd,
|
||||
eps=eps,
|
||||
T=T,
|
||||
H=H,
|
||||
g_stride_n=g_stride_n,
|
||||
D=D,
|
||||
BD=BD,
|
||||
BT=BT,
|
||||
ACTIVATION=activation,
|
||||
IS_RMS_NORM=is_rms_norm,
|
||||
num_warps=8,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
else:
|
||||
layer_norm_gated_fwd_kernel1[(T,)](
|
||||
x=x,
|
||||
g=g,
|
||||
y=y,
|
||||
w=weight,
|
||||
b=bias,
|
||||
residual=residual,
|
||||
residual_out=residual_out,
|
||||
mean=mean,
|
||||
rstd=rstd,
|
||||
eps=eps,
|
||||
D=D,
|
||||
BD=BD,
|
||||
ACTIVATION=activation,
|
||||
IS_RMS_NORM=is_rms_norm,
|
||||
num_warps=4,
|
||||
launch_pdl=current_platform.is_arch_support_pdl(),
|
||||
)
|
||||
# residual_out is None if residual is None and residual_dtype == input_dtype
|
||||
return y, mean, rstd, residual_out if residual_out is not None else x
|
||||
|
||||
|
||||
def rms_norm_gated(
|
||||
x: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor,
|
||||
activation: str = "swish",
|
||||
residual: torch.Tensor | None = None,
|
||||
prenorm: bool = False,
|
||||
residual_in_fp32: bool = False,
|
||||
eps: float = 1e-6,
|
||||
):
|
||||
x_shape_og = x.shape
|
||||
# reshape input data into 2D tensor
|
||||
x = x.contiguous().reshape(-1, x.shape[-1])
|
||||
D = x.shape[-1]
|
||||
# The tiled kernel supports row-strided gates; kernel1 does not.
|
||||
if D <= 512:
|
||||
H = 1 if g.ndim == 2 else g.shape[-2]
|
||||
g = g.view(-1, H, D)
|
||||
g_stride_n = g.stride(0)
|
||||
else:
|
||||
g = g.contiguous()
|
||||
H = 1
|
||||
g_stride_n = D
|
||||
if residual is not None:
|
||||
assert residual.shape == x_shape_og
|
||||
residual = residual.contiguous().reshape(-1, residual.shape[-1])
|
||||
residual_dtype = (
|
||||
residual.dtype
|
||||
if residual is not None
|
||||
else (torch.float if residual_in_fp32 else None)
|
||||
)
|
||||
y, _, _, residual_out = layer_norm_gated_fwd(
|
||||
x=x,
|
||||
g=g,
|
||||
weight=weight,
|
||||
bias=bias,
|
||||
activation=activation,
|
||||
eps=eps,
|
||||
residual=residual,
|
||||
residual_dtype=residual_dtype,
|
||||
is_rms_norm=True,
|
||||
H=H,
|
||||
g_stride_n=g_stride_n,
|
||||
)
|
||||
y = y.reshape(x_shape_og)
|
||||
return y if not prenorm else (y, residual_out.reshape(x_shape_og))
|
||||
|
||||
|
||||
@CustomOp.register("fused_rms_norm_gated")
|
||||
class FusedRMSNormGated(CustomOp):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
elementwise_affine: bool = True,
|
||||
eps: float = 1e-5,
|
||||
activation: str = "swish",
|
||||
device: torch.device | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
) -> None:
|
||||
factory_kwargs = {"device": device, "dtype": dtype}
|
||||
super().__init__()
|
||||
|
||||
self.hidden_size = hidden_size
|
||||
self.elementwise_affine = elementwise_affine
|
||||
self.eps = eps
|
||||
self.activation = activation
|
||||
|
||||
if self.activation not in ["swish", "silu", "sigmoid"]:
|
||||
raise ValueError(f"Unsupported activation: {self.activation}")
|
||||
|
||||
if elementwise_affine:
|
||||
self.weight = nn.Parameter(torch.empty(hidden_size, **factory_kwargs))
|
||||
else:
|
||||
self.register_parameter("weight", None)
|
||||
self.register_parameter("bias", None)
|
||||
|
||||
def forward_native(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
residual: torch.Tensor | None = None,
|
||||
prenorm: bool = False,
|
||||
residual_in_fp32: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""Decomposed PyTorch ops for torch.compile/inductor fusion."""
|
||||
# TODO(https://github.com/vllm-project/vllm/issues/36175): implement
|
||||
# native residual/prenorm path and unify with RMSNormGated.
|
||||
# For now, fall back to the triton kernel.
|
||||
if residual is not None or prenorm:
|
||||
return self.forward_cuda(x, g, residual, prenorm, residual_in_fp32)
|
||||
x_float = x.float()
|
||||
variance = x_float.pow(2).mean(dim=-1, keepdim=True)
|
||||
x_normed = x_float * torch.rsqrt(variance + self.eps)
|
||||
if self.weight is not None:
|
||||
x_normed = x_normed * self.weight.float()
|
||||
g_float = g.float()
|
||||
if self.activation in ("swish", "silu"):
|
||||
out = x_normed * g_float * torch.sigmoid(g_float)
|
||||
else: # sigmoid
|
||||
out = x_normed * torch.sigmoid(g_float)
|
||||
return out.to(x.dtype)
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
residual: torch.Tensor | None = None,
|
||||
prenorm: bool = False,
|
||||
residual_in_fp32: bool = False,
|
||||
) -> torch.Tensor:
|
||||
return rms_norm_gated(
|
||||
x,
|
||||
g,
|
||||
self.weight,
|
||||
self.bias,
|
||||
self.activation,
|
||||
residual=residual,
|
||||
eps=self.eps,
|
||||
prenorm=prenorm,
|
||||
residual_in_fp32=residual_in_fp32,
|
||||
)
|
||||
+63
-25
@@ -166,6 +166,8 @@ def layer_norm_gated_fwd_kernel(
|
||||
rstd, # pointer to the 1/std
|
||||
eps, # epsilon to avoid division by zero
|
||||
T, # number of rows in x
|
||||
H: tl.constexpr, # number of heads
|
||||
g_stride_n: tl.constexpr,
|
||||
D: tl.constexpr, # number of columns in x
|
||||
BT: tl.constexpr,
|
||||
BD: tl.constexpr,
|
||||
@@ -221,8 +223,13 @@ def layer_norm_gated_fwd_kernel(
|
||||
b_y = b_y + b_b[None, :]
|
||||
|
||||
# swish/sigmoid output gate
|
||||
p_g = tl.make_block_ptr(g, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
|
||||
b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
|
||||
o_t = i_t * BT + tl.arange(0, BT)
|
||||
o_g = (o_t // H) * g_stride_n + (o_t % H) * D
|
||||
b_g = tl.load(
|
||||
g + o_g[:, None] + o_d[None, :],
|
||||
mask=(o_t[:, None] < T) & m_d[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
if ACTIVATION == "swish" or ACTIVATION == "silu":
|
||||
b_y = b_y * b_g * tl.sigmoid(b_g)
|
||||
elif ACTIVATION == "sigmoid":
|
||||
@@ -320,10 +327,15 @@ def layer_norm_gated_fwd(
|
||||
out_dtype: torch.dtype = None,
|
||||
residual_dtype: torch.dtype = None,
|
||||
is_rms_norm: bool = False,
|
||||
H: int = 1,
|
||||
g_stride_n: int | None = None,
|
||||
):
|
||||
if residual is not None:
|
||||
residual_dtype = residual.dtype
|
||||
T, D = x.shape
|
||||
if g_stride_n is None:
|
||||
g_stride_n = D
|
||||
assert T % H == 0
|
||||
if residual is not None:
|
||||
assert residual.shape == (T, D)
|
||||
if weight is not None:
|
||||
@@ -349,10 +361,8 @@ def layer_norm_gated_fwd(
|
||||
BD = min(MAX_FUSED_SIZE, next_power_of_2(D))
|
||||
if D > BD:
|
||||
raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
|
||||
# heuristics for number of warps
|
||||
|
||||
if D <= 512:
|
||||
BT = 32
|
||||
BT = 16
|
||||
layer_norm_gated_fwd_kernel[(cdiv(T, BT),)](
|
||||
x=x,
|
||||
g=g,
|
||||
@@ -365,12 +375,14 @@ def layer_norm_gated_fwd(
|
||||
rstd=rstd,
|
||||
eps=eps,
|
||||
T=T,
|
||||
H=H,
|
||||
g_stride_n=g_stride_n,
|
||||
D=D,
|
||||
BD=BD,
|
||||
BT=BT,
|
||||
ACTIVATION=activation,
|
||||
IS_RMS_NORM=is_rms_norm,
|
||||
num_warps=4,
|
||||
num_warps=8,
|
||||
)
|
||||
else:
|
||||
layer_norm_gated_fwd_kernel1[(T,)](
|
||||
@@ -408,7 +420,16 @@ def rms_norm_gated(
|
||||
x_shape_og = x.shape
|
||||
# reshape input data into 2D tensor
|
||||
x = x.contiguous().reshape(-1, x.shape[-1])
|
||||
g = g.contiguous().reshape(-1, g.shape[-1])
|
||||
D = x.shape[-1]
|
||||
# The tiled kernel supports row-strided gates; kernel1 does not.
|
||||
if D <= 512:
|
||||
H = 1 if g.ndim == 2 else g.shape[-2]
|
||||
g = g.view(-1, H, D)
|
||||
g_stride_n = g.stride(0)
|
||||
else:
|
||||
g = g.contiguous()
|
||||
H = 1
|
||||
g_stride_n = D
|
||||
if residual is not None:
|
||||
assert residual.shape == x_shape_og
|
||||
residual = residual.contiguous().reshape(-1, residual.shape[-1])
|
||||
@@ -427,6 +448,8 @@ def rms_norm_gated(
|
||||
residual=residual,
|
||||
residual_dtype=residual_dtype,
|
||||
is_rms_norm=True,
|
||||
H=H,
|
||||
g_stride_n=g_stride_n,
|
||||
)
|
||||
y = y.reshape(x_shape_og)
|
||||
return y if not prenorm else (y, residual_out.reshape(x_shape_og))
|
||||
@@ -1187,6 +1210,7 @@ def kda_gate_cumsum_fwd_kernel(
|
||||
cu_seqlens,
|
||||
chunk_indices,
|
||||
cumsum_scale,
|
||||
lower_bound,
|
||||
beta,
|
||||
threshold,
|
||||
T,
|
||||
@@ -1196,6 +1220,7 @@ def kda_gate_cumsum_fwd_kernel(
|
||||
BD: tl.constexpr,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
IS_VARLEN: tl.constexpr,
|
||||
USE_LOWER_BOUND: tl.constexpr,
|
||||
):
|
||||
i_d, i_t, i_bh = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
||||
i_b, i_h = i_bh // H, i_bh % H
|
||||
@@ -1235,14 +1260,17 @@ def kda_gate_cumsum_fwd_kernel(
|
||||
b_bias = tl.load(g_bias + i_h * D + o_d, mask=o_d < D, other=0.0).to(tl.float32)
|
||||
b_g = b_g + b_bias[None, :]
|
||||
|
||||
b_a = -tl.exp(tl.load(A + i_h).to(tl.float32))
|
||||
b_g_scaled = b_g * beta
|
||||
b_softplus = tl.where(
|
||||
b_g_scaled > threshold,
|
||||
b_g,
|
||||
(1.0 / beta) * log(1.0 + tl.exp(b_g_scaled)),
|
||||
)
|
||||
b_gate = b_a * b_softplus
|
||||
b_a = tl.exp(tl.load(A + i_h).to(tl.float32))
|
||||
if USE_LOWER_BOUND:
|
||||
b_gate = lower_bound * tl.sigmoid(b_a * b_g)
|
||||
else:
|
||||
b_g_scaled = b_g * beta
|
||||
b_softplus = tl.where(
|
||||
b_g_scaled > threshold,
|
||||
b_g,
|
||||
(1.0 / beta) * log(1.0 + tl.exp(b_g_scaled)),
|
||||
)
|
||||
b_gate = -b_a * b_softplus
|
||||
|
||||
# Out-of-bounds rows (load returns 0, but softplus/bias can still make
|
||||
# b_gate non-zero) participate in the dot product. They only contribute to
|
||||
@@ -1260,6 +1288,7 @@ def fused_kda_gate_chunk_cumsum(
|
||||
g_bias: torch.Tensor | None = None,
|
||||
beta: float = 1.0,
|
||||
threshold: float = 20.0,
|
||||
lower_bound: float | None = None,
|
||||
cu_seqlens: torch.Tensor | None = None,
|
||||
chunk_indices: torch.Tensor | None = None,
|
||||
chunk_size: int = FLA_CHUNK_SIZE,
|
||||
@@ -1293,16 +1322,17 @@ def fused_kda_gate_chunk_cumsum(
|
||||
# exp2-based kernels reproduce exp(g). Keep this in sync with the
|
||||
# `use_exp2=True` path in `_chunk_kda_fwd_with_cumulative_g`.
|
||||
cumsum_scale=RCP_LN2,
|
||||
lower_bound=lower_bound or 0.0,
|
||||
beta=beta,
|
||||
threshold=threshold,
|
||||
T=T,
|
||||
H=H,
|
||||
D=D,
|
||||
BT=chunk_size,
|
||||
USE_LOWER_BOUND=lower_bound is not None,
|
||||
)
|
||||
return y
|
||||
|
||||
|
||||
def _chunk_kda_fwd_with_cumulative_g(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
@@ -1424,6 +1454,7 @@ def chunk_kda_with_fused_gate_fwd(
|
||||
scale: float,
|
||||
initial_state: torch.Tensor,
|
||||
output_final_state: bool,
|
||||
lower_bound: float | None = None,
|
||||
cu_seqlens: torch.Tensor | None = None,
|
||||
):
|
||||
chunk_size = FLA_CHUNK_SIZE
|
||||
@@ -1439,6 +1470,7 @@ def chunk_kda_with_fused_gate_fwd(
|
||||
cu_seqlens=cu_seqlens,
|
||||
chunk_indices=chunk_indices,
|
||||
chunk_size=chunk_size,
|
||||
lower_bound=lower_bound,
|
||||
)
|
||||
return _chunk_kda_fwd_with_cumulative_g(
|
||||
q=q,
|
||||
@@ -1500,6 +1532,7 @@ def chunk_kda_with_fused_gate(
|
||||
scale: float | None = None,
|
||||
initial_state: torch.Tensor | None = None,
|
||||
output_final_state: bool = False,
|
||||
lower_bound: float | None = None,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
cu_seqlens: torch.Tensor | None = None,
|
||||
**kwargs,
|
||||
@@ -1523,6 +1556,7 @@ def chunk_kda_with_fused_gate(
|
||||
scale=scale,
|
||||
initial_state=initial_state.contiguous() if initial_state is not None else None,
|
||||
output_final_state=output_final_state,
|
||||
lower_bound=lower_bound,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
return o, final_state
|
||||
@@ -1543,6 +1577,7 @@ def kda_gate_fwd_kernel(
|
||||
A,
|
||||
y,
|
||||
g_bias,
|
||||
lower_bound,
|
||||
beta: tl.constexpr,
|
||||
threshold: tl.constexpr,
|
||||
T,
|
||||
@@ -1551,12 +1586,12 @@ def kda_gate_fwd_kernel(
|
||||
BT: tl.constexpr,
|
||||
BD: tl.constexpr,
|
||||
HAS_BIAS: tl.constexpr,
|
||||
USE_LOWER_BOUND: tl.constexpr,
|
||||
):
|
||||
i_t, i_h = tl.program_id(0), tl.program_id(1)
|
||||
n_t = i_t * BT
|
||||
|
||||
b_a = tl.load(A + i_h).to(tl.float32)
|
||||
b_a = -tl.exp(b_a)
|
||||
b_a = tl.exp(tl.load(A + i_h).to(tl.float32))
|
||||
|
||||
stride_row = H * D
|
||||
stride_col = 1
|
||||
@@ -1589,13 +1624,13 @@ def kda_gate_fwd_kernel(
|
||||
)
|
||||
b_g = b_g + b_bias[None, :]
|
||||
|
||||
# softplus(x, beta) = (1/beta) * log(1 + exp(beta * x))
|
||||
# When beta * x > threshold, use linear approximation x
|
||||
# Use threshold to switch to linear when beta*x > threshold
|
||||
g_scaled = b_g * beta
|
||||
use_linear = g_scaled > threshold
|
||||
sp = tl.where(use_linear, b_g, (1.0 / beta) * log(1.0 + tl.exp(g_scaled)))
|
||||
b_y = b_a * sp
|
||||
if USE_LOWER_BOUND:
|
||||
b_y = lower_bound * tl.sigmoid(b_a * b_g)
|
||||
else:
|
||||
g_scaled = b_g * beta
|
||||
use_linear = g_scaled > threshold
|
||||
sp = tl.where(use_linear, b_g, (1.0 / beta) * log(1.0 + tl.exp(g_scaled)))
|
||||
b_y = -b_a * sp
|
||||
|
||||
tl.store(y_ptr, b_y.to(y.dtype.element_ty), boundary_check=(0, 1))
|
||||
|
||||
@@ -1607,6 +1642,7 @@ def fused_kda_gate(
|
||||
g_bias: torch.Tensor | None = None,
|
||||
beta: float = 1.0,
|
||||
threshold: float = 20.0,
|
||||
lower_bound: float | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Forward pass for KDA gate:
|
||||
@@ -1634,6 +1670,7 @@ def fused_kda_gate(
|
||||
A,
|
||||
y,
|
||||
g_bias,
|
||||
lower_bound or 0.0,
|
||||
beta,
|
||||
threshold,
|
||||
T,
|
||||
@@ -1641,6 +1678,7 @@ def fused_kda_gate(
|
||||
head_k_dim,
|
||||
BD=next_power_of_2(head_k_dim),
|
||||
HAS_BIAS=g_bias is not None,
|
||||
USE_LOWER_BOUND=lower_bound is not None,
|
||||
)
|
||||
|
||||
y = y.view(*orig_shape, H, head_k_dim)
|
||||
|
||||
Reference in New Issue
Block a user