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):