MCPcopy Create free account
hub / github.com/Navidfoumani/ConvTran / AbsolutePositionalEncoding

Class AbsolutePositionalEncoding

Models/AbsolutePositionalEncoding.py:47–83  ·  view source on GitHub ↗

r"""Inject some information about the relative or absolute position of the tokens in the sequence. The positional encodings have the same dimension as the embeddings, so that the two can be summed. Here, we use sine and cosine functions of different frequencies. .. math::

Source from the content-addressed store, hash-verified

45
46
47class AbsolutePositionalEncoding(nn.Module):
48 r"""Inject some information about the relative or absolute position of the tokens
49 in the sequence. The positional encodings have the same dimension as
50 the embeddings, so that the two can be summed. Here, we use sine and cosine
51 functions of different frequencies.
52 .. math::
53 \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))
54 \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))
55 \text{where pos is the word position and i is the embed idx)
56 Args:
57 d_model: the embed dim (required).
58 dropout: the dropout value (default=0.1).
59 max_len: the max. length of the incoming sequence (default=1024).
60 """
61
62 def __init__(self, d_model, dropout=0.1, max_len=1024, scale_factor=1.0):
63 super(AbsolutePositionalEncoding, self).__init__()
64 self.dropout = nn.Dropout(p=dropout)
65 pe = torch.zeros(max_len, d_model) # positional encoding
66 position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
67 div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
68
69 pe[:, 0::2] = torch.sin(position * div_term)
70 pe[:, 1::2] = torch.cos(position * div_term)
71 pe = scale_factor * pe.unsqueeze(0)
72 self.register_buffer('pe', pe) # this stores the variable in the state_dict (used for non-trainable variables)
73
74 def forward(self, x):
75 r"""Inputs of forward function
76 Args:
77 x: the sequence fed to the positional encoder model (required).
78 Shape:
79 x: [sequence length, batch size, embed dim]
80 output: [sequence length, batch size, embed dim]
81 """
82 x = x + self.pe
83 return self.dropout(x)
84
85class LearnablePositionalEncoding(nn.Module):
86

Callers 1

__init__Method · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected