import torch
import torch.nn as nn
import numpy as np

class LayerNorm(nn.Module):
    def __init__(self, embed_dim):
        super().__init__()
        self.epsilon = 1e-5 # Prevents divide-by-zero errors.

        # These trainable parameters allow the model to scale and
        # shift this layers output beyond strict normalization if
        # that improves model performance.
        self.scale = nn.Parameter(torch.ones(embed_dim))
        self.shift = nn.Parameter(torch.zeros(embed_dim))

    def forward(self, X):
        mean = X.mean(dim=-1, keepdim=True)

        # We use a biased variance because in practice embedding
        # dimensions are so large that the difference is negligible,
        # plus this ensures compatibility with historical open-weight
        # GPT models.
        var = X.var(dim=-1, keepdim=True, unbiased=False)

        normed_X = (X - mean) / torch.sqrt(var + self.epsilon)
        normed_X = normed_X * self.scale + self.shift
        return normed_X

class GELU(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, X):
        sqrt_2_over_pi = torch.sqrt(torch.tensor(2 / torch.pi))
        result = 0.5 * X * (1 + torch.tanh(sqrt_2_over_pi * (X + 0.044715 * torch.pow(X,3))))
        return result

class FeedForward(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        embed_dim = cfg["emb_dim"]
        embed_dim_x4 = embed_dim * 4
        self.layers = nn.Sequential(
            nn.Linear(embed_dim, embed_dim_x4),
            GELU(),
            nn.Linear(embed_dim_x4, embed_dim)
        )

    def forward(self, X):
        result = self.layers(X)
        return result

class MultiHeadAttention(nn.Module):
    def __init__(self, input_dim, output_dim, context_length, dropout_pct, num_heads, use_bias=False):
        super().__init__()

        assert output_dim % num_heads == 0, "output_dim must be a multiple of num_heads"
        self.num_heads = num_heads
        self.head_dim = output_dim // num_heads
        self.output_dim = output_dim
        
        self.W_q = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.W_k = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.W_v = nn.Linear(input_dim, output_dim, bias=use_bias)
        self.output_proj = nn.Linear(output_dim, output_dim)
        
        self.dropout = torch.nn.Dropout(dropout_pct)
        ones = torch.ones(context_length, context_length)
        self.register_buffer("mask", torch.triu(ones, diagonal=1).bool())

    def forward(self, batch):
        num_samples, num_tokens, token_dim = batch.shape
        queries = self.W_q(batch)
        keys = self.W_k(batch)
        values = self.W_v(batch)

        queries = queries.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        keys = keys.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        values = values.view(num_samples, num_tokens, self.num_heads, self.head_dim).transpose(1, 2)
        
        attn_scores = queries @ keys.transpose(2, 3)
        attn_scores.masked_fill_(self.mask[:num_tokens, :num_tokens], -torch.inf)
        
        attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
        attn_weights = self.dropout(attn_weights)
        
        context_vectors = attn_weights @ values
        context_vectors = context_vectors.transpose(1, 2)
        context_vectors = context_vectors.contiguous().view(num_samples, num_tokens, self.output_dim)
        
        output = self.output_proj(context_vectors)
        return output

class TransformerBlock(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.attention = MultiHeadAttention(
            input_dim      = config["emb_dim"],
            output_dim     = config["emb_dim"],
            context_length = config["context_length"],
            num_heads      = config["n_heads"],
            dropout_pct    = config["drop_rate"],
            use_bias       = config["qkv_bias"]
        )
        self.feed_forward = FeedForward(config)
        self.norm1 = LayerNorm(config["emb_dim"])
        self.norm2 = LayerNorm(config["emb_dim"])
        self.dropout = nn.Dropout(config["drop_rate"])

    def forward(self, batch):
        shortcut = batch
        output = self.norm1(batch)
        output = self.attention(output)
        output = self.dropout(output)
        output = output + shortcut

        shortcut = output
        output = self.norm2(output)
        output = self.feed_forward(output)
        output = self.dropout(output)
        output = output + shortcut

        return output

class GPTModel(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
        self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
        self.dropout = nn.Dropout(cfg["drop_rate"])
        self.xform_blocks = nn.Sequential(
            *[TransformerBlock(cfg) for _ in range(cfg["n_layers"])]
        )
        self.final_norm = LayerNorm(cfg["emb_dim"])
        self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias = False)

    def forward(self, input_tokens):
        batch_size, num_tokens = input_tokens.shape

        token_embeds = self.tok_emb(input_tokens)
        pos_embeds = self.pos_emb(torch.arange(num_tokens, device=input_tokens.device))
        X = token_embeds + pos_embeds
        X = self.dropout(X)
        X = self.xform_blocks(X)
        X = self.final_norm(X)

        logits = self.out_head(X)
        return logits

# This is Raschka's function to assign data with a warning in the event of shape
# mismatches.
def assign(left, right):
    if left.shape != right.shape:
        raise ValueError(f"Shape mismatch. Left: {left.shape}, "
                          "Right: {right.shape}"
        )
    return torch.nn.Parameter(torch.tensor(right))

# And this is Raschka's function to read the gpt2 weights into our model,
# lightly adapted to suit the code which I authored.
# In his words it was a "lot of guesswork." So I'm just copy-pasting it.
# I would write it from scratch myself (as I've done with most of the rest
# of the code), but I don't think there's a pot of gold at the end of that
# particular rainbow.
def load_weights_into_gpt(gpt, params):
    gpt.pos_emb.weight = assign(gpt.pos_emb.weight, params['wpe'])
    gpt.tok_emb.weight = assign(gpt.tok_emb.weight, params['wte'])

    for b in range(len(params["blocks"])):
        q_w, k_w, v_w = np.split(
            (params["blocks"][b]["attn"]["c_attn"])["w"], 3, axis=-1)
        gpt.xform_blocks[b].attention.W_q.weight = assign(
            gpt.xform_blocks[b].attention.W_q.weight, q_w.T)
        gpt.xform_blocks[b].attention.W_k.weight = assign(
            gpt.xform_blocks[b].attention.W_k.weight, k_w.T)
        gpt.xform_blocks[b].attention.W_v.weight = assign(
            gpt.xform_blocks[b].attention.W_v.weight, v_w.T)

        q_b, k_b, v_b = np.split(
            (params["blocks"][b]["attn"]["c_attn"])["b"], 3, axis=-1)
        gpt.xform_blocks[b].attention.W_q.bias = assign(
            gpt.xform_blocks[b].attention.W_q.bias, q_b)
        gpt.xform_blocks[b].attention.W_k.bias = assign(
            gpt.xform_blocks[b].attention.W_k.bias, k_b)
        gpt.xform_blocks[b].attention.W_v.bias = assign(
            gpt.xform_blocks[b].attention.W_v.bias, v_b)

        gpt.xform_blocks[b].attention.output_proj.weight = assign(
            gpt.xform_blocks[b].attention.output_proj.weight, 
            params["blocks"][b]["attn"]["c_proj"]["w"].T)
        gpt.xform_blocks[b].attention.output_proj.bias = assign(
            gpt.xform_blocks[b].attention.output_proj.bias, 
            params["blocks"][b]["attn"]["c_proj"]["b"])

        gpt.xform_blocks[b].feed_forward.layers[0].weight = assign(
            gpt.xform_blocks[b].feed_forward.layers[0].weight, 
            params["blocks"][b]["mlp"]["c_fc"]["w"].T)
        gpt.xform_blocks[b].feed_forward.layers[0].bias = assign(
            gpt.xform_blocks[b].feed_forward.layers[0].bias, 
            params["blocks"][b]["mlp"]["c_fc"]["b"])
        gpt.xform_blocks[b].feed_forward.layers[2].weight = assign(
            gpt.xform_blocks[b].feed_forward.layers[2].weight, 
            params["blocks"][b]["mlp"]["c_proj"]["w"].T)
        gpt.xform_blocks[b].feed_forward.layers[2].bias = assign(
            gpt.xform_blocks[b].feed_forward.layers[2].bias, 
            params["blocks"][b]["mlp"]["c_proj"]["b"])

        gpt.xform_blocks[b].norm1.scale = assign(
            gpt.xform_blocks[b].norm1.scale, 
            params["blocks"][b]["ln_1"]["g"])
        gpt.xform_blocks[b].norm1.shift = assign(
            gpt.xform_blocks[b].norm1.shift, 
            params["blocks"][b]["ln_1"]["b"])
        gpt.xform_blocks[b].norm2.scale = assign(
            gpt.xform_blocks[b].norm2.scale, 
            params["blocks"][b]["ln_2"]["g"])
        gpt.xform_blocks[b].norm2.shift = assign(
            gpt.xform_blocks[b].norm2.shift, 
            params["blocks"][b]["ln_2"]["b"])

    gpt.final_norm.scale = assign(gpt.final_norm.scale, params["g"])
    gpt.final_norm.shift = assign(gpt.final_norm.shift, params["b"])
    gpt.out_head.weight = assign(gpt.out_head.weight, params["wte"])

def generate_text_simple(model, tokens, max_output_tokens, max_context_length):
    for _ in range(max_output_tokens):
        # Crop tokens to maximum context length and get logits.
        tokens_context = tokens[:, -max_context_length:]
        logits = model(tokens_context)

        # Go from [batch_size, num_tokens, embed_dim] to [batch_size, embed_dim],
        # only retaining the last token from each batch.
        logits = logits[:, -1, :]

        # Determine the next token and append it.
        probas = torch.softmax(logits, dim=-1)
        next_tokens = torch.argmax(probas, dim=-1, keepdim=True)
        tokens = torch.cat([tokens, next_tokens], dim=-1)

    return tokens

# This is a helper function for testing purposes. It takes
# some text and returns the tokens wrapped up within a
# batch. This makes it easy to use little bits of test
# text with functions that expect to receive a batch of
# tokenized samples.
def text_to_token_ids(text, tokenizer):
    encoded = tokenizer.encode(text, allowed_special={'<|endoftext|>'})
    
    # unsqueeze() wraps the tokens in a batch.
    encoded_tensor = torch.tensor(encoded).unsqueeze(0)
    return encoded_tensor

# This is the same idea as the preceding function, just
# in the other direction. It takes a batch of tokens
# and returns a string.
def token_ids_to_text(tokens, tokenizer):
     # squeeze() removes the first dimension which represents the batch.
    decoded_text = tokenizer.decode(tokens.squeeze(0).tolist())
    return decoded_text

