请用 Python 实现一个高精度自注意力算子,并给出理论时间复杂度。
思考过程 · 16 秒
已完成算子实现。对于序列长度为 N、嵌入维度为 D 的输入,计算复杂度为 O(N² · D)。
import torch
import torch.nn as nn
class ScaledDotProductAttention(nn.Module):
def __init__(self, d_k):
super().__init__()
self.scale = 1.0 / (d_k ** 0.5)
def forward(self, q, k, v):
scores = torch.matmul(q, k.transpose(-2, -1)) * self.scale
attn = torch.softmax(scores, dim=-1)
return torch.matmul(attn, v)