from __future__ import absolute_import, division, print_function, unicode_literals

import torch
import torch.nn as nn
import math


class PositionalEmbedding(nn.Module):
    def __init__(self, d_model, max_len=512):
        super().__init__()

        # Compute the positional encodings once in log space.
        pe = torch.zeros(max_len, d_model).float()
        pe.require_grad = False

        position = torch.arange(0, max_len).float().unsqueeze(1)
        div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()

        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):
        return self.pe[:, :x.size(1)]
    
    
class TokenEmbedding(nn.Module):
    def __init__(self, vocab_size, d_model, pad_id):
        super(TokenEmbedding, self).__init__()
        self.token_embedding = nn.Embedding(vocab_size, d_model, padding_idx=pad_id)

    def forward(self, x):
        x_embed = self.token_embedding(x)
        return x_embed
    
    
class Embeddings(nn.Module):
    def __init__(self, config):
        super(Embeddings, self).__init__()
        self.token_embedding = TokenEmbedding(vocab_size=config.vocab_size, d_model=config.d_model, pad_id=config.pad_idx)
        self.pos_embedding = PositionalEmbedding(d_model = config.d_model, max_len=config.maxlen)

    def forward(self, x):
        token_embed = self.token_embedding(x)
        pos_embed = self.pos_embedding(x)
        return token_embed + pos_embed