Running LLMs on cpus by Rust
2024/07/21
First attempt by Python
Reference: https://github.com/karpathy/llm.c/blob/master/train_gpt2.py
Environment
from dataclassess import dataclass import math import torch import torch.nn as nn from torch.nn import functional as F @dataclass class GPTConfig: block_size: int = 1024 vocab_size: int = 50257 n_layer: int = 12 n_head: int = 12 n_embed: int = 768 class NewGELU(nn.Module): def forward(self, input): return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0))))
Blocks
class Block(nn.Module): def __init__(self, config: GPTConfig): super().__init__() self.ln_1 = nn.LayerNorm(config.n_embed) self.attn = CausalSelfAttention(config) self.ln_2 = nn.LayerNorm(config.n_embed) self.mlp = MLP(config) def forward(self, x): x = x + self.attn(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x
MLP
class MLP(nn.Module): def __init__(self, config: GPTConfig): super().__init__() self.c_fc = nn.Linear(config.n_embed, 4 * config.n_embed) self.gelu = NewGELU() self.c_proj = nn.Linear(4 * config.n_embed, config.n_embed) def forward(self, x): x = self.c_fc(x) x = self.gelu(x) x = self.c_proj(x) return x
Attention
class CausalSelfAttention(nn.Module): def __init__(self, config: GPTConfig): super().__init__() assert config.n_embed % config.n_head == 0 self.c_attn = nn.Linear(config.n_embed, 3 * config.n_embed) self.c_proj = nn.Linear(config.n_embed, config.n_embed) self.n_head = config.n_head self.n_embed = config.n_embed # it's actually a mask self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size)) def forward(self, x): B, T, C = x.size() # batch size, input length, embed dim qkv = self.c_attn(x) # projection to Q, K, V q, k, v = qkv.split(self.n_embed, dim=2) k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) attn = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) attn = attn.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf')) attn = F.softmax(attn, dim=-1) y = attn @ v y = y.transpose(1, 2).contiguous().view(B, T, C) y = self.c_proj(y) return y