class MHAlayer(nn.Module): def __init__(self, n_heads, cat, input_dim, hidden_dim, attn_dropout=0.1, dropout=0): super(MHAlayer, self).__init__() self.n_heads = n_heads self.input_dim = input_dim self.hidden_dim = hidden_dim self.head_dim = self.hidden_dim / self.n_heads self.dropout = nn.Dropout(attn_dropout) self.dropout1 = nn.Dropout(dropout) self.norm = 1 / math.sqrt(self.head_dim) self.w = nn.Linear(input_dim * cat, hidden_dim, bias=False) self.k = nn.Linear(input_dim, hidden_dim, bias=False) self.v = nn.Linear(input_dim, hidden_dim, bias=False) self.fc = nn.Linear(hidden_dim, hidden_dim, bias=False) def forward(self, state_t, context, mask): ''' :param state_t: (batch_size,1,input_dim*3(GATembeding,fist_node,end_node)) :param context: (batch_size,n_nodes,input_dim) :param mask: selected nodes (batch_size,n_nodes) :return: ''' batch_size, n_nodes, input_dim = context.size() Q = self.w(state_t).view(batch_size, 1, self.n_heads, -1) K = self.k(context).view(batch_size, n_nodes, self.n_heads, -1) V = self.v(context).view(batch_size, n_nodes, self.n_heads, -1) Q, K, V = Q.transpose(1, 2), K.transpose(1, 2), V.transpose(1, 2) compatibility = self.norm * torch.matmul(Q, K.transpose(2, 3)) compatibility = compatibility.squeeze(2) mask = mask.unsqueeze(1).expand_as(compatibility) u_i = compatibility.masked_fill(mask.bool(), float("-inf")) scores = F.softmax(u_i, dim=-1) scores = scores.unsqueeze(2) out_put = torch.matmul(scores, V) out_put = out_put.squeeze(2).view(batch_size, self.hidden_dim) out_put = self.fc(out_put) return out_put
时间: 2024-04-27 17:19:37 浏览: 182
hobd-1.2.7.wince-standalone.zip_HOBD_hobd-1.1.1.wince_wince 导航
这是一个PyTorch的神经网络模型定义,其中定义了一个叫做MHAlayer的模块。这个模块实现了Multi-Head Attention机制,用于文本序列处理中的Attention机制。具体来说,这个模块输入了三个张量:state_t,context和mask,其中state_t是一个(batch_size,1,input_dim*3)的张量,context是一个(batch_size,n_nodes,input_dim)的张量,mask是一个(batch_size,n_nodes)的张量,表示需要进行Attention的节点。在模块中,首先用线性层将state_t和context分别映射到hidden_dim维的向量,并将输入的维度变为(batch_size, n_heads, hidden_dim),然后计算查询向量Q,键向量K和值向量V,并将它们都分成n_heads份。接下来,计算对应的Attention得分compatibility,并根据mask将需要Attention的节点的得分设置为负无穷。然后对得分进行softmax归一化,并加权求和得到Attention的输出。最后再通过一个线性层转换维度,并返回输出。
阅读全文