Skip to content
Open
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
54 changes: 42 additions & 12 deletions lightx2v_platform/ops/attn/cambricon_mlu/sage_attn.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,47 @@
tmo = None


@torch.library.custom_op(
"lightx2v::mlu_sage_attention",
mutates_args=(),
device_types="mlu",
)
def _mlu_sage_attention(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
max_seqlen_q: int,
max_seqlen_kv: int,
softmax_scale: float,
causal: bool,
) -> torch.Tensor:
return tmo.sage_attn(
q=q,
k=k,
v=v,
cu_seq_lens_q=None,
cu_seq_lens_kv=None,
max_seq_len_q=max_seqlen_q,
max_seq_len_kv=max_seqlen_kv,
softmax_scale=softmax_scale,
is_causal=causal,
compute_dtype=torch.bfloat16,
)


@_mlu_sage_attention.register_fake
def _mlu_sage_attention_fake(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
max_seqlen_q: int,
max_seqlen_kv: int,
softmax_scale: float,
causal: bool,
) -> torch.Tensor:
return v.new_empty((*q.shape[:-1], v.shape[-1]))


@PLATFORM_ATTN_WEIGHT_REGISTER("mlu_sage_attn")
class MluSageAttnWeight(AttnWeightTemplate):
def __init__(self):
Expand All @@ -27,17 +68,6 @@ def apply(self, q, k, v, cu_seqlens_q=None, cu_seqlens_kv=None, max_seqlen_q=Non
if softmax_scale is None:
softmax_scale = 1 / math.sqrt(q.shape[-1])
causal = kwds.get("causal", False)
x = tmo.sage_attn(
q=q,
k=k,
v=v,
cu_seq_lens_q=None,
cu_seq_lens_kv=None,
max_seq_len_kv=max_seqlen_kv,
max_seq_len_q=max_seqlen_q,
is_causal=causal,
compute_dtype=torch.bfloat16,
softmax_scale=softmax_scale,
)
x = _mlu_sage_attention(q, k, v, max_seqlen_q, max_seqlen_kv, softmax_scale, causal)
x = x.reshape(bs * max_seqlen_q, -1)
return x
Loading