MCPcopy Create free account
hub / github.com/pytorch/examples / PositionalEncoding

Class PositionalEncoding

word_language_model/model.py:65–105  ·  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

63
64# Temporarily leave PositionalEncoding module here. Will be moved somewhere else.
65class PositionalEncoding(nn.Module):
66 r"""Inject some information about the relative or absolute position of the tokens in the sequence.
67 The positional encodings have the same dimension as the embeddings, so that the two can be summed.
68 Here, we use sine and cosine functions of different frequencies.
69 .. math:
70 \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))
71 \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))
72 \text{where pos is the word position and i is the embed idx)
73 Args:
74 d_model: the embed dim (required).
75 dropout: the dropout value (default=0.1).
76 max_len: the max. length of the incoming sequence (default=5000).
77 Examples:
78 >>> pos_encoder = PositionalEncoding(d_model)
79 """
80
81 def __init__(self, d_model, dropout=0.1, max_len=5000):
82 super(PositionalEncoding, self).__init__()
83 self.dropout = nn.Dropout(p=dropout)
84
85 pe = torch.zeros(max_len, d_model)
86 position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
87 div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
88 pe[:, 0::2] = torch.sin(position * div_term)
89 pe[:, 1::2] = torch.cos(position * div_term)
90 pe = pe.unsqueeze(0).transpose(0, 1)
91 self.register_buffer('pe', pe)
92
93 def forward(self, x):
94 r"""Inputs of forward function
95 Args:
96 x: the sequence fed to the positional encoder model (required).
97 Shape:
98 x: [sequence length, batch size, embed dim]
99 output: [sequence length, batch size, embed dim]
100 Examples:
101 >>> output = pos_encoder(x)
102 """
103
104 x = x + self.pe[:x.size(0), :]
105 return self.dropout(x)
106
107class TransformerModel(nn.Transformer):
108 """Container module with an encoder, a recurrent or transformer module, and a decoder."""

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected