|
1 | 1 | from .libllaisys import LIB_LLAISYS |
2 | 2 | from .tensor import Tensor |
3 | | -from ctypes import c_float, c_int |
| 3 | +from ctypes import c_float, c_int, c_bool |
4 | 4 |
|
5 | 5 |
|
6 | 6 | class Ops: |
@@ -53,3 +53,36 @@ def self_attention(attn_val: Tensor, q: Tensor, k: Tensor, v: Tensor, scale: flo |
53 | 53 | @staticmethod |
54 | 54 | def swiglu(out: Tensor, gate: Tensor, up: Tensor): |
55 | 55 | LIB_LLAISYS.llaisysSwiGLU(out.lib_tensor(), gate.lib_tensor(), up.lib_tensor()) |
| 56 | + |
| 57 | + @staticmethod |
| 58 | + def flash_attention( |
| 59 | + out: Tensor, |
| 60 | + q: Tensor, |
| 61 | + k: Tensor, |
| 62 | + v: Tensor, |
| 63 | + scale: float = 0.0, |
| 64 | + is_causal: bool = False, |
| 65 | + enable_gqa: bool = False |
| 66 | + ): |
| 67 | + """ |
| 68 | + Flash Attention with causal masking and GQA support. |
| 69 | + Behavior matches torch.nn.functional.scaled_dot_product_attention. |
| 70 | + |
| 71 | + Args: |
| 72 | + out: Output tensor [batch, seq_len, num_q_heads, head_dim] |
| 73 | + q: Query tensor [batch, seq_len, num_q_heads, head_dim] |
| 74 | + k: Key tensor [batch, kv_len, num_kv_heads, head_dim] |
| 75 | + v: Value tensor [batch, kv_len, num_kv_heads, head_dim] |
| 76 | + scale: Scale factor (default: 1/sqrt(head_dim)) |
| 77 | + is_causal: Enable causal masking |
| 78 | + enable_gqa: Enable Grouped Query Attention |
| 79 | + """ |
| 80 | + LIB_LLAISYS.llaisysFlashAttention( |
| 81 | + out.lib_tensor(), |
| 82 | + q.lib_tensor(), |
| 83 | + k.lib_tensor(), |
| 84 | + v.lib_tensor(), |
| 85 | + c_float(scale), |
| 86 | + c_bool(is_causal), |
| 87 | + c_bool(enable_gqa) |
| 88 | + ) |
0 commit comments