Standard scaled dot-product attention.
(Q: torch.Tensor, K: torch.Tensor, V: torch.Tensor, causal: bool = True, sm_scale: float = None)
| 30 | |
| 31 | # Flash Attention |
| 32 | def flash_attention_ref(Q: torch.Tensor, K: torch.Tensor, V: torch.Tensor, causal: bool = True, sm_scale: float = None) -> torch.Tensor: |
| 33 | """Standard scaled dot-product attention.""" |
| 34 | if sm_scale is None: |
| 35 | sm_scale = Q.shape[-1] ** -0.5 |
| 36 | attn = torch.matmul(Q, K.transpose(-2, -1)) * sm_scale |
| 37 | if causal: |
| 38 | seq_len_q, seq_len_k = Q.shape[-2], K.shape[-2] |
| 39 | mask = torch.triu(torch.ones(seq_len_q, seq_len_k, device=Q.device, dtype=torch.bool), diagonal=1) |
| 40 | attn = attn.masked_fill(mask, float('-inf')) |
| 41 | attn = F.softmax(attn, dim=-1) |
| 42 | return torch.matmul(attn, V) |
| 43 | |
| 44 | # Fused MLP (SwiGLU-style) |
| 45 | def fused_mlp_ref(x: torch.Tensor, w_gate: torch.Tensor, w_up: torch.Tensor, w_down: torch.Tensor, activation: str = "silu") -> torch.Tensor: |
nothing calls this directly
no outgoing calls
no test coverage detected