Stoopidity/HarryPotterLLM
0
1import torch2import torch.nn as nn3from torch.nn import functional as F4import gradio as gr5 6# hyperparameters7batch_size = 16 # how many independent sequences will we process in parallel?8block_size = 32 # what is the maximum context length for predictions?9max_iters = 500010eval_interval = 10011learning_rate = 1e-312device = 'cuda' if torch.cuda.is_available() else 'cpu'13eval_iters = 20014n_embd = 6415n_head = 416n_layer = 417dropout = 0.018# ------------19 20torch.manual_seed(1337)21 22# wget https://github.com/Cral-Cactus/HarryPotterLLM/raw/main/HarryPotter.txt23with open('HarryPotter.txt', 'r', encoding='utf-8') as f:24 text = f.read()25 26# here are all the unique characters that occur in this text27chars = sorted(list(set(text)))28vocab_size = len(chars)29# create a mapping from characters to integers30stoi = { ch:i for i,ch in enumerate(chars) }31itos = { i:ch for i,ch in enumerate(chars) }32encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers33decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string34 35# Train and test splits36data = torch.tensor(encode(text), dtype=torch.long)37n = int(0.9*len(data)) # first 90% will be train, rest val38train_data = data[:n]39val_data = data[n:]40 41# data loading42def get_batch(split):43 # generate a small batch of data of inputs x and targets y44 data = train_data if split == 'train' else val_data45 ix = torch.randint(len(data) - block_size, (batch_size,))46 x = torch.stack([data[i:i+block_size] for i in ix])47 y = torch.stack([data[i+1:i+block_size+1] for i in ix])48 x, y = x.to(device), y.to(device)49 return x, y50 51@torch.no_grad()52def estimate_loss():53 out = {}54 model.eval()55 for split in ['train', 'val']:56 losses = torch.zeros(eval_iters)57 for k in range(eval_iters):58 X, Y = get_batch(split)59 logits, loss = model(X, Y)60 losses[k] = loss.item()61 out[split] = losses.mean()62 model.train()63 return out64 65class Head(nn.Module):66 """ one head of self-attention """67 68 def __init__(self, head_size):69 super().__init__()70 self.key = nn.Linear(n_embd, head_size, bias=False)71 self.query = nn.Linear(n_embd, head_size, bias=False)72 self.value = nn.Linear(n_embd, head_size, bias=False)73 self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))74 75 self.dropout = nn.Dropout(dropout)76 77 def forward(self, x):78 B,T,C = x.shape79 k = self.key(x) # (B,T,C)80 q = self.query(x) # (B,T,C)81 # compute attention scores ("affinities")82 wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)83 wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)84 wei = F.softmax(wei, dim=-1) # (B, T, T)85 wei = self.dropout(wei)86 # perform the weighted aggregation of the values87 v = self.value(x) # (B,T,C)88 out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)89 return out90 91class MultiHeadAttention(nn.Module):92 """ multiple heads of self-attention in parallel """93 94 def __init__(self, num_heads, head_size):95 super().__init__()96 self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])97 self.proj = nn.Linear(n_embd, n_embd)98 self.dropout = nn.Dropout(dropout)99 100 def forward(self, x):101 out = torch.cat([h(x) for h in self.heads], dim=-1)102 out = self.dropout(self.proj(out))103 return out104 105class FeedFoward(nn.Module):106 """ a simple linear layer followed by a non-linearity """107 108 def __init__(self, n_embd):109 super().__init__()110 self.net = nn.Sequential(111 nn.Linear(n_embd, 4 * n_embd),112 nn.ReLU(),113 nn.Linear(4 * n_embd, n_embd),114 nn.Dropout(dropout),115 )116 117 def forward(self, x):118 return self.net(x)119 120class Block(nn.Module):121 """ Transformer block: communication followed by computation """122 123 def __init__(self, n_embd, n_head):124 # n_embd: embedding dimension, n_head: the number of heads we'd like125 super().__init__()126 head_size = n_embd // n_head127 self.sa = MultiHeadAttention(n_head, head_size)128 self.ffwd = FeedFoward(n_embd)129 self.ln1 = nn.LayerNorm(n_embd)130 self.ln2 = nn.LayerNorm(n_embd)131 132 def forward(self, x):133 x = x + self.sa(self.ln1(x))134 x = x + self.ffwd(self.ln2(x))135 return x136 137# super simple bigram model138class BigramLanguageModel(nn.Module):139 140 def __init__(self):141 super().__init__()142 # each token directly reads off the logits for the next token from a lookup table143 self.token_embedding_table = nn.Embedding(vocab_size, n_embd)144 self.position_embedding_table = nn.Embedding(block_size, n_embd)145 self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])146 self.ln_f = nn.LayerNorm(n_embd) # final layer norm147 self.lm_head = nn.Linear(n_embd, vocab_size)148 149 def forward(self, idx, targets=None):150 B, T = idx.shape151 152 # idx and targets are both (B,T) tensor of integers153 tok_emb = self.token_embedding_table(idx) # (B,T,C)154 pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)155 x = tok_emb + pos_emb # (B,T,C)156 x = self.blocks(x) # (B,T,C)157 x = self.ln_f(x) # (B,T,C)158 logits = self.lm_head(x) # (B,T,vocab_size)159 160 if targets is None:161 loss = None162 else:163 B, T, C = logits.shape164 logits = logits.view(B*T, C)165 targets = targets.view(B*T)166 loss = F.cross_entropy(logits, targets)167 168 return logits, loss169 170 def generate(self, idx, max_new_tokens):171 # idx is (B, T) array of indices in the current context172 for _ in range(max_new_tokens):173 # crop idx to the last block_size tokens174 idx_cond = idx[:, -block_size:]175 # get the predictions176 logits, loss = self(idx_cond)177 # focus only on the last time step178 logits = logits[:, -1, :] # becomes (B, C)179 # apply softmax to get probabilities180 probs = F.softmax(logits, dim=-1) # (B, C)181 # sample from the distribution182 idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)183 # append sampled index to the running sequence184 idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)185 return idx186 187model = BigramLanguageModel()188m = model.to(device)189m.load_state_dict(torch.load("state.txt",map_location = torch.device(device)))190 191def generate_text(context,mt):192 return decode(m.generate(torch.tensor([encode(context)]), max_new_tokens=mt)[0].tolist())193 194iface = gr.Interface(195 fn=generate_text,196 inputs=[197 gr.Textbox(label="Prompt", placeholder="Put something here!!!"),198 gr.Slider(minimum=1, maximum=1000, step=1, label="Number of characters to generate", value=100)199 ],200 outputs=gr.Textbox(label="Generated Text"),201 title="Name of your bot",202 description="Add a description here!"203)204 205# Launch the interface206if __name__ == "__main__":207 iface.launch()