import math import torch import torch.nn as nn import torch.nn.functional as F class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout=0.1, max_len=600): super().__init__() self.dropout = nn.Dropout(p=dropout) # vanilla sinusoidal encoding pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0) self.register_buffer('pe', pe) def forward(self, x): x = x + self.pe[:, x.shape[1], :] return self.dropout(x) def enc_dec_mask(T, S, frame_width=2, expansion=0, device='cuda'): mask = torch.ones(T, S) for i in range(T): mask[i, max(0, (i - expansion) * frame_width):(i + expansion + 1) * frame_width] = 0 return (mask == 1).to(device=device)