-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathembeddings.py
More file actions
56 lines (42 loc) · 1.72 KB
/
Copy pathembeddings.py
File metadata and controls
56 lines (42 loc) · 1.72 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""
embeddings.py
Handles converting token IDs into embeddings, and adding positional
information to those embeddings so the model knows token order.
"""
import torch
import torch.nn as nn
import math
class PositionalEncoding(nn.Module):
"""
Adds sinusoidal positional information to token embeddings.
Attention has no built-in sense of sequence order (unlike RNNs),
so we inject position information directly into the embeddings.
"""
def __init__(self, embed_dim: int, max_len: int = 5000):
super().__init__()
pe = torch.zeros(max_len, embed_dim)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(
torch.arange(0, embed_dim, 2).float() * (-math.log(10000.0) / embed_dim)
)
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0) # shape: (1, max_len, embed_dim)
self.register_buffer("pe", pe)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Add positional encoding to the input embeddings."""
seq_len = x.size(1)
return x + self.pe[:, :seq_len, :]
class TokenEmbedding(nn.Module):
"""
Wraps a standard embedding layer plus positional encoding
into a single reusable component.
"""
def __init__(self, vocab_size: int, embed_dim: int, max_len: int = 5000):
super().__init__()
self.token_embedding = nn.Embedding(vocab_size, embed_dim)
self.positional_encoding = PositionalEncoding(embed_dim, max_len)
def forward(self, token_ids: torch.Tensor) -> torch.Tensor:
x = self.token_embedding(token_ids)
x = self.positional_encoding(x)
return x