|
12 | 12 |
|
13 | 13 | import einops |
14 | 14 | import torch |
| 15 | +import torch.nn.functional as F |
15 | 16 |
|
16 | 17 | from aphrodite.utils.torch_utils import direct_register_custom_op |
17 | 18 |
|
@@ -113,3 +114,53 @@ def vit_flash_attn_wrapper( |
113 | 114 | return torch.ops.aphrodite.flash_attn_maxseqlen_wrapper( |
114 | 115 | q, k, v, cu_seqlens, max_seqlen, batch_size, is_rocm_aiter, use_upstream_fa |
115 | 116 | ) |
| 117 | + |
| 118 | + |
| 119 | +# TODO: Once we have a torch 2.10, we can use tensor slices |
| 120 | +# so we won't need to wrap this in custom ops |
| 121 | +def torch_sdpa_wrapper( |
| 122 | + q: torch.Tensor, |
| 123 | + k: torch.Tensor, |
| 124 | + v: torch.Tensor, |
| 125 | + cu_seqlens: torch.Tensor, |
| 126 | +) -> torch.Tensor: |
| 127 | + outputs = [] |
| 128 | + for i in range(1, len(cu_seqlens)): |
| 129 | + start_idx = cu_seqlens[i - 1] |
| 130 | + end_idx = cu_seqlens[i] |
| 131 | + q_i = q[:, start_idx:end_idx] |
| 132 | + k_i = k[:, start_idx:end_idx] |
| 133 | + v_i = v[:, start_idx:end_idx] |
| 134 | + q_i, k_i, v_i = (einops.rearrange(x, "b s h d -> b h s d") for x in [q_i, k_i, v_i]) |
| 135 | + output_i = F.scaled_dot_product_attention(q_i, k_i, v_i, dropout_p=0.0) |
| 136 | + output_i = einops.rearrange(output_i, "b h s d -> b s h d ") |
| 137 | + outputs.append(output_i) |
| 138 | + context_layer = torch.cat(outputs, dim=1) |
| 139 | + context_layer = einops.rearrange(context_layer, "b s h d -> s b (h d)").contiguous() |
| 140 | + return context_layer |
| 141 | + |
| 142 | + |
| 143 | +def torch_sdpa_wrapper_fake( |
| 144 | + q: torch.Tensor, |
| 145 | + k: torch.Tensor, |
| 146 | + v: torch.Tensor, |
| 147 | + cu_seqlens: torch.Tensor, |
| 148 | +) -> torch.Tensor: |
| 149 | + b, s, h, d = q.shape |
| 150 | + return torch.empty((s, b, h * d), dtype=q.dtype, device=q.device) |
| 151 | + |
| 152 | + |
| 153 | +direct_register_custom_op( |
| 154 | + op_name="torch_sdpa_wrapper", |
| 155 | + op_func=torch_sdpa_wrapper, |
| 156 | + fake_impl=torch_sdpa_wrapper_fake, |
| 157 | +) |
| 158 | + |
| 159 | + |
| 160 | +def vit_torch_sdpa_wrapper( |
| 161 | + q: torch.Tensor, |
| 162 | + k: torch.Tensor, |
| 163 | + v: torch.Tensor, |
| 164 | + cu_seqlens: torch.Tensor, |
| 165 | +) -> torch.Tensor: |
| 166 | + return torch.ops.aphrodite.torch_sdpa_wrapper(q, k, v, cu_seqlens) |
0 commit comments