Bigram Model with Linear layer & Token + Positional embeddings

Bigram Model with Linear layer & Token + Positional embeddings#

Open In Colab


  • Context window (block size) = 8

  • This model looks at 8 past tokens to predicts 1 future token

  • Two trainable embedding tables at input.

  • Token embedding table maps each token into a vector of size (32), giving a (8, 32) matrix

  • Position embedding table maps the positions 0-31 into a vector of size (32)

  • These are added together to informs the model of the positions of input tokens

import torch
import torch.nn as nn
from torch.nn import functional as F

Hyperparameters#

B = 32 # B (batch size): how many independent sequences will we process in parallel?
T = 1  # T (block size): what is the maximum context length for predictions?
C = 32 # C (channels)  : dimensionality, also called d
max_iters = 3000
eval_interval = 300
learning_rate = 1e-2
device = 'cuda' if torch.cuda.is_available() else 'cpu'
eval_iters = 200
torch.manual_seed(1337)
<torch._C.Generator at 0x7e71f812e250>

Dataset#

!wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
--2024-06-09 01:38:46--  https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.108.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1115394 (1.1M) [text/plain]
Saving to: ‘input.txt.4’


input.txt.4           0%[                    ]       0  --.-KB/s               
input.txt.4         100%[===================>]   1.06M  --.-KB/s    in 0.06s   

2024-06-09 01:38:46 (18.6 MB/s) - ‘input.txt.4’ saved [1115394/1115394]
with open('input.txt', 'r', encoding='utf-8') as f:
    text = f.read()

# here are all the unique characters that occur in this text
chars = sorted(list(set(text)))
vocab_size = len(chars)
# create a mapping from characters to integers
stoi = { ch:i for i,ch in enumerate(chars) }
itos = { i:ch for i,ch in enumerate(chars) }
encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string

chars_str = ''.join(chars)
print(f'vocab_size: {vocab_size}')
print(f'vocabulary: {chars_str}')

# Train and test splits
data = torch.tensor(encode(text), dtype=torch.long)
n = int(0.9*len(data)) # first 90% will be train, rest val
train_data = data[:n]
val_data = data[n:]


def get_batch(split):
    # generate a small batch of data of inputs x and targets y
    data = train_data if split == 'train' else val_data
    ix = torch.randint(len(data) - T, (T,))
    x = torch.stack([data[i:i+T] for i in ix])
    y = torch.stack([data[i+1:i+T+1] for i in ix])
    x, y = x.to(device), y.to(device)
    return x, y
vocab_size: 65
vocabulary: 
 !$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

Bigram Model with Linear layer & token/pos embeddings#

class BigramLanguageModel(nn.Module):

    def __init__(self, B, T ,C):
        super().__init__()
        self.B, self.T, self.C = B, T, C
        # each token directly reads off the logits for the next token from a lookup table
        self.token_embedding_table = nn.Embedding(vocab_size, C) # for every possible token, weights for next token
        self.position_embedding_table = nn.Embedding(B, C)
        self.lm_head = nn.Linear(C, vocab_size)

    def forward(self, idx, targets=None):

        tok_emb = self.token_embedding_table(idx)                                        # (B,T,C)
        pos_emb = self.position_embedding_table(torch.arange(self.T, device=device))     # (T,C): [0,1,2..T-1]

        '''
        B - batch               # of independant vectors processed
        T - time/block/context  # of tokens in a context
        C - channels            # of features
        '''

        x = tok_emb + pos_emb     # (B,T,C)
        logits = self.lm_head(x)  # (B,T,vocab_size)

        if targets is None:
            loss = None
        else:
            B, T, C = logits.shape
            logits = logits.view(B*T, C)
            targets = targets.view(B*T)
            loss = F.cross_entropy(logits, targets)

        return logits, loss

    def generate(self, idx, max_new_tokens):
        for _ in range(max_new_tokens):                        # idx is (B, T) array of indices in the current context
            idx_cond = idx[:, -self.B:]                             # crop the last block_size tokens for input
            logits, loss = self(idx_cond)                      # get the predictions
            logits = logits[:, -1, :]                          # (B,T,C) -> (B, C)
            probs = F.softmax(logits, dim=-1)                  # (B, C)
            idx_next = torch.multinomial(probs, num_samples=1) # sample from the distribution acc to prob (B, 1)
            idx = torch.cat((idx, idx_next), dim=1)            # New idx is concat (B, T+1)
        return idx

model = BigramLanguageModel(B, T ,C)
m = model.to(device)

Training#

@torch.no_grad()
def estimate_loss():
    out = {}
    model.eval()
    for split in ['train', 'val']:
        losses = torch.zeros(eval_iters)
        for k in range(eval_iters):
            X, Y = get_batch(split)
            logits, loss = model(X, Y)
            losses[k] = loss.item()
        out[split] = losses.mean()
    model.train()
    return out

optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)

for iter in range(max_iters):
    if iter % eval_interval == 0:   # every once in a while evaluate the loss on train and val sets
        losses = estimate_loss()
        print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")

    xb, yb = get_batch('train')     # sample a batch of data

    # evaluate the loss
    logits, loss = model(xb, yb)
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    optimizer.step()
step 0: train loss 4.3337, val loss 4.4599
step 300: train loss 3.2863, val loss 3.2765
step 600: train loss 3.2917, val loss 3.0822
step 900: train loss 3.1424, val loss 3.0526
step 1200: train loss 3.0914, val loss 3.0241
step 1500: train loss 3.2469, val loss 2.9623
step 1800: train loss 2.8173, val loss 2.8259
step 2100: train loss 2.8679, val loss 2.9978
step 2400: train loss 2.9930, val loss 3.0948
step 2700: train loss 2.9934, val loss 2.9553

Inference#

context = torch.ones((1, B), dtype=torch.long, device=device)  # start with '\n\n\n\n' as seed
out_ints = m.generate(context, max_new_tokens=500)[0].tolist() # output list of ints
print(decode(out_ints))
                                l ouerketisis ir alutor a magay per: d;
O ke he tugolouce, painllo b wer oououeeffor is
SBe t;
Su Ase llur iethe'ereerd'louce h, hous he eaver d'lofmoaousethe ghe b r w!owhaisoo us r impouooreldoug nes ce heaigubusuinisouer e he
O!oonere hedisor ?
Se.
Y,
Thed g aepthas dSisit y t bofon t ldour , hofos fofout ae out forveaayo hesoooouct touy mowigr DugheUWr we ouowther
HAs ce  wenowisoAt wer louthe ige he   , tout ce tt Mhe dldfowers
koubofouofain her cthiner towem se oferug 
S:
SThe t in he his