1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import torch import torch.nn as nn
def self_attention(q,k,v,mask=None): d_k=q.size(-1) scores=torch.matmul(q,k.transpose(-2,-1)/torch.sqrt(d_k,dtype=torch.float32)) if mask is not None: scores=scores.masked_fill(mask==0,-1e9) attn_weights=F.softmax(scores,dim=-1) output=torch.matmul(attn_weights,v) return output,attn_weights
Batch_size=2 Seq_len=5 Dim=64
q=torch.randn(Batch_size,Seq_len,Dim) k=torch.randn(Batch_size,Seq_len,Dim) v=torch.randn(Batch_size,Seq_len,Dim)
attn_output,attn_weights=self.attention(q,k,v)
|