import torch
import torch.nn as nn
import math
import numpy as np
class CausalSelfAttention(nn.Module):
def __init__(self, hidden_dim, n_heads, dropout=0.0):
super().__init__()
self.hidden_dim = hidden_dim
self.n_heads = n_heads
self.head_dim = hidden_dim // n_heads
assert hidden_dim % n_heads == 0, "hidden_dim 必须能被 n_heads 整除"
self.query = nn.Linear(hidden_dim, hidden_dim)
self.key = nn.Linear(hidden_dim, hidden_dim)
self.value = nn.Linear(hidden_dim, hidden_dim)
self.output = nn.Linear(hidden_dim, hidden_dim)
self.dropout = nn.Dropout(p=dropout)
def forward(self, x, mask=None):
q = self.query(x)
k = self.key(x)
v = self.value(x)
return self.get_attention_scores(q, k, v, mask=mask)
def get_attention_scores(self, q, k, v, mask=None):
B, L, H = q.shape
# 重塑张量以适应多头注意力
q = q.view(B, L, self.n_heads,
因果注意力(or 掩码注意力)代码实现
最新推荐文章于 2025-11-24 15:28:47 发布

最低0.47元/天 解锁文章
343

被折叠的 条评论
为什么被折叠?



