"""Week 3: toy tokenizers, causal attention, and an untrained decoder block.
Requires torch. Keep this file beside week04.py for the training lab.
"""
import argparse
import math
import torch
from torch import nn


class TinyDecoder(nn.Module):
    def __init__(self, vocabulary_size, width=24, max_length=32, heads=2):
        super().__init__()
        self.max_length = max_length
        self.token_embedding = nn.Embedding(vocabulary_size, width)
        self.position_embedding = nn.Embedding(max_length, width)
        self.norm1 = nn.LayerNorm(width)
        self.attention = nn.MultiheadAttention(width, heads, dropout=0.0, batch_first=True)
        self.norm2 = nn.LayerNorm(width)
        self.feedforward = nn.Sequential(nn.Linear(width, width * 2), nn.ReLU(),
                                         nn.Linear(width * 2, width))
        self.final_norm = nn.LayerNorm(width)
        self.output = nn.Linear(width, vocabulary_size)

    def forward(self, identifiers):
        batch, length = identifiers.shape
        if length > self.max_length:
            raise ValueError('Input exceeds the learned position table')
        positions = torch.arange(length, device=identifiers.device)
        hidden = self.token_embedding(identifiers) + self.position_embedding(positions)
        # nn.MultiheadAttention bool mask: True means blocked.
        mask = torch.triu(torch.ones(length, length, dtype=torch.bool,
                                     device=identifiers.device), diagonal=1)
        normalized = self.norm1(hidden)
        mixed, _ = self.attention(normalized, normalized, normalized,
                                  attn_mask=mask, need_weights=False)
        hidden = hidden + mixed
        hidden = hidden + self.feedforward(self.norm2(hidden))
        return self.output(self.final_norm(hidden))

    @torch.no_grad()
    def generate(self, prefix, count=12, temperature=1.0, top_p=1.0):
        if temperature < 0 or not 0 < top_p <= 1:
            raise ValueError('temperature must be nonnegative; 0 < top_p <= 1')
        self.eval()
        result = prefix.clone()
        for _ in range(count):
            context = result[:, -self.max_length:]
            logits = self(context)[:, -1, :]
            if temperature == 0:
                next_token = logits.argmax(dim=-1, keepdim=True)
            else:
                probabilities = torch.softmax(logits / temperature, dim=-1)
                if top_p < 1:
                    ordered, indices = probabilities.sort(descending=True, dim=-1)
                    # Retain the token crossing p as well as the preceding mass.
                    keep = (ordered.cumsum(dim=-1) - ordered) < top_p
                    ordered = ordered * keep
                    ordered /= ordered.sum(dim=-1, keepdim=True)
                    sampled = torch.multinomial(ordered, 1)
                    next_token = indices.gather(-1, sampled)
                else:
                    next_token = torch.multinomial(probabilities, 1)
            result = torch.cat([result, next_token], dim=1)
        return result


def lesson1():
    text = 'a  café a'
    vocabulary = sorted(set(text))
    encode = {character: index for index, character in enumerate(vocabulary)}
    decode = {index: character for character, index in encode.items()}
    identifiers = [encode[character] for character in text]
    assert ''.join(decode[index] for index in identifiers) == text
    words = text.split()
    assert ' '.join(words) != text  # Repeated spaces were lost.
    table = nn.Embedding(len(vocabulary), 4)
    vectors = table(torch.tensor([identifiers]))
    assert tuple(vectors.shape) == (1, len(text), 4)
    assert torch.equal(vectors[0, 0], vectors[0, -1])
    positions = nn.Embedding(len(text), 4)(torch.arange(len(text)))
    combined = vectors + positions
    assert combined.shape == vectors.shape
    assert torch.allclose(combined[0, 0] - vectors[0, 0], positions[0], atol=1e-6)
    print('Text:', repr(text), '; character identifiers:', identifiers)
    print('Characters:', len(text), '; UTF-8 bytes:', len(text.encode('utf-8')),
          '; whitespace pieces:', len(words))
    print('Embedding output shape:', tuple(vectors.shape))
    print('PASS: exact character roundtrip; whitespace reconstruction loss is explicit.')


def lesson2():
    scores = torch.zeros(3, 3)
    future = torch.triu(torch.ones(3, 3, dtype=torch.bool), diagonal=1)
    weights = torch.softmax(scores.masked_fill(future, float('-inf')), dim=-1)
    expected = torch.tensor([[1., 0., 0.], [0.5, 0.5, 0.], [1/3, 1/3, 1/3]])
    assert torch.allclose(weights, expected)
    assert torch.allclose(weights.sum(dim=-1), torch.ones(3))
    assert torch.all(weights[future] == 0)
    broken = torch.softmax(scores.masked_fill(future, 0.), dim=-1)
    assert torch.any(broken[future] > 0)
    values = torch.tensor([[2., 0.], [0., 4.]])
    assert torch.allclose(torch.tensor([[0.5, 0.5]]) @ values,
                          torch.tensor([[1., 2.]]))
    torch.manual_seed(7)
    model = TinyDecoder(8).eval()
    before = torch.tensor([[1, 2, 3, 4]])
    after = torch.tensor([[1, 2, 3, 7]])
    with torch.no_grad():
        assert torch.allclose(model(before)[:, :3], model(after)[:, :3], atol=1e-6)
    print('Correct causal weights:', weights.tolist())
    print('Broken future mass:', broken[future].tolist())
    print('PASS: row normalization, blocked future weights, value mixture and perturbation.')


def lesson3():
    torch.manual_seed(7)
    torch.set_num_threads(1)
    model = TinyDecoder(8).eval()
    sequence = torch.tensor([[1, 2, 3, 4]])
    inputs, targets = sequence[:, :-1], sequence[:, 1:]
    logits = model(inputs)
    assert tuple(logits.shape) == (1, 3, 8)
    changed = inputs.clone()
    changed[:, -1] = 7
    with torch.no_grad():
        assert torch.allclose(model(inputs)[:, :-1], model(changed)[:, :-1], atol=1e-6)
    loss = nn.functional.cross_entropy(logits.reshape(-1, 8), targets.reshape(-1))
    assert torch.isfinite(loss)
    hand_mean = sum(-math.log(p) for p in [0.5, 0.25, 0.5]) / 3
    assert math.isclose(hand_mean, 0.9241962407465937)
    sample = model.generate(torch.tensor([[1]]), count=5, temperature=0)
    assert tuple(sample.shape) == (1, 6)
    print('Shifted input:', inputs.tolist(), '; targets:', targets.tolist())
    print('Untrained model loss:', loss.item(), '; hand example loss:', hand_mean)
    print('Untrained generated identifiers:', sample.tolist())
    print('PASS: decoder shapes, shifted target loss, bounded generation; no language-quality claim.')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--lesson', choices=['1', '2', '3', 'all'], default='all')
    args = parser.parse_args()
    torch.set_num_threads(1)
    for number, function in [('1', lesson1), ('2', lesson2), ('3', lesson3)]:
        if args.lesson in (number, 'all'):
            function()
