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!/usr/bin/env python3
|
| 2 |
+
"""End-to-end training benchmark: Dense vs PyLoop vs Triton sparse backward."""
|
| 3 |
+
|
| 4 |
+
import math, os, time, urllib.request
|
| 5 |
+
import torch, torch.nn as nn, torch.nn.functional as F
|
| 6 |
+
import tiktoken
|
| 7 |
+
|
| 8 |
+
# Import our Triton kernels from the module
|
| 9 |
+
from triton_sparse import (
|
| 10 |
+
TritonChunkedSparseLinear, PythonLoopSparseLinear,
|
| 11 |
+
sparse_bwd_dW, sparse_bwd_dX, sparse_bwd_dbias
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
device = 'cuda'
|
| 15 |
+
BS, BLK = 8, 256
|
| 16 |
+
|
| 17 |
+
# Data
|
| 18 |
+
if not os.path.exists('input.txt'):
|
| 19 |
+
urllib.request.urlretrieve('https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt', 'input.txt')
|
| 20 |
+
enc = tiktoken.get_encoding('gpt2')
|
| 21 |
+
tokens = torch.tensor(enc.encode(open('input.txt').read()), dtype=torch.long)
|
| 22 |
+
train_data = tokens[:int(0.9*len(tokens))]
|
| 23 |
+
val_data = tokens[int(0.9*len(tokens)):]
|
| 24 |
+
V = enc.n_vocab
|
| 25 |
+
|
| 26 |
+
def get_batch(data, gen=None):
|
| 27 |
+
ix = torch.randint(len(data)-BLK-1, (BS,), generator=gen)
|
| 28 |
+
return (torch.stack([data[i:i+BLK] for i in ix]).to(device),
|
| 29 |
+
torch.stack([data[i+1:i+BLK+1] for i in ix]).to(device))
|
| 30 |
+
|
| 31 |
+
# Model
|
| 32 |
+
class SparseFFN(nn.Module):
|
| 33 |
+
def __init__(self, d, cs=64):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.fc = nn.Linear(d, 4*d)
|
| 36 |
+
self.proj = nn.Linear(4*d, d)
|
| 37 |
+
self.do = nn.Dropout(0.1)
|
| 38 |
+
self.cs = cs
|
| 39 |
+
self.mode = 'dense'
|
| 40 |
+
self.active_chunks = None
|
| 41 |
+
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
h = F.gelu(self.fc(x))
|
| 44 |
+
if self.mode == 'dense' or self.active_chunks is None:
|
| 45 |
+
return self.do(self.proj(h))
|
| 46 |
+
elif self.mode == 'pyloop':
|
| 47 |
+
return self.do(PythonLoopSparseLinear.apply(
|
| 48 |
+
h, self.proj.weight, self.proj.bias, self.active_chunks, self.cs, False))
|
| 49 |
+
else: # triton
|
| 50 |
+
return self.do(TritonChunkedSparseLinear.apply(
|
| 51 |
+
h, self.proj.weight, self.proj.bias, self.active_chunks, self.cs, False))
|
| 52 |
+
|
| 53 |
+
class Attn(nn.Module):
|
| 54 |
+
def __init__(self, d, nh, bs):
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.nh, self.hd = nh, d//nh
|
| 57 |
+
self.qkv = nn.Linear(d, 3*d)
|
| 58 |
+
self.proj = nn.Linear(d, d)
|
| 59 |
+
self.do = nn.Dropout(0.1)
|
| 60 |
+
self.register_buffer('mask', torch.tril(torch.ones(bs,bs)).view(1,1,bs,bs))
|
| 61 |
+
|
| 62 |
+
def forward(self, x):
|
| 63 |
+
B,T,C = x.shape
|
| 64 |
+
q,k,v = self.qkv(x).split(C,2)
|
| 65 |
+
q = q.view(B,T,self.nh,self.hd).transpose(1,2)
|
| 66 |
+
k = k.view(B,T,self.nh,self.hd).transpose(1,2)
|
| 67 |
+
v = v.view(B,T,self.nh,self.hd).transpose(1,2)
|
| 68 |
+
att = (q @ k.transpose(-2,-1)) / math.sqrt(self.hd)
|
| 69 |
+
att = att.masked_fill(self.mask[:,:,:T,:T]==0, float('-inf'))
|
| 70 |
+
att = self.do(F.softmax(att, dim=-1))
|
| 71 |
+
return self.proj((att @ v).transpose(1,2).contiguous().view(B,T,C))
|
| 72 |
+
|
| 73 |
+
class Block(nn.Module):
|
| 74 |
+
def __init__(self, d, nh, bs):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.ln1=nn.LayerNorm(d); self.attn=Attn(d,nh,bs)
|
| 77 |
+
self.ln2=nn.LayerNorm(d); self.mlp=SparseFFN(d)
|
| 78 |
+
def forward(self, x):
|
| 79 |
+
x = x + self.attn(self.ln1(x))
|
| 80 |
+
return x + self.mlp(self.ln2(x))
|
| 81 |
+
|
| 82 |
+
class GPT(nn.Module):
|
| 83 |
+
def __init__(self, d, nl, nh, bs):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.te=nn.Embedding(V,d); self.pe=nn.Embedding(bs,d)
|
| 86 |
+
self.blocks=nn.ModuleList([Block(d,nh,bs) for _ in range(nl)])
|
| 87 |
+
self.ln=nn.LayerNorm(d); self.head=nn.Linear(d,V)
|
| 88 |
+
|
| 89 |
+
def forward(self, idx, tgt=None):
|
| 90 |
+
x = self.te(idx)+self.pe(torch.arange(idx.shape[1],device=idx.device))[None]
|
| 91 |
+
for b in self.blocks: x = b(x)
|
| 92 |
+
lo = self.head(self.ln(x))
|
| 93 |
+
loss = F.cross_entropy(lo.view(-1,lo.size(-1)), tgt.view(-1)) if tgt is not None else None
|
| 94 |
+
return lo, loss
|
| 95 |
+
|
| 96 |
+
def get_ffns(self):
|
| 97 |
+
return [b.mlp for b in self.blocks]
|
| 98 |
+
|
| 99 |
+
# Run
|
| 100 |
+
STEPS = 100
|
| 101 |
+
af = 0.10
|
| 102 |
+
cs = 64
|
| 103 |
+
|
| 104 |
+
print(f"End-to-end training: {STEPS} steps, B={BS}, T={BLK}, active_frac={af}")
|
| 105 |
+
print(f"{'d_model':>7} | {'Mode':>8} | {'ms/step':>10} | {'vs Dense':>10} | {'val_loss':>10}")
|
| 106 |
+
print("-"*60)
|
| 107 |
+
|
| 108 |
+
for d in [512, 1024, 2048]:
|
| 109 |
+
nh = 8; nl = 6
|
| 110 |
+
results = {}
|
| 111 |
+
|
| 112 |
+
for mode in ['dense', 'pyloop', 'triton']:
|
| 113 |
+
torch.manual_seed(42)
|
| 114 |
+
model = GPT(d, nl, nh, BLK).to(device)
|
| 115 |
+
opt = torch.optim.AdamW(model.parameters(), lr=5e-4)
|
| 116 |
+
ffns = model.get_ffns()
|
| 117 |
+
|
| 118 |
+
torch.cuda.synchronize()
|
| 119 |
+
t0 = time.perf_counter()
|
| 120 |
+
|
| 121 |
+
for step in range(STEPS):
|
| 122 |
+
if mode != 'dense':
|
| 123 |
+
for ffn in ffns:
|
| 124 |
+
ffn.mode = mode
|
| 125 |
+
# proj: Linear(4d, d) -> weight shape (d, 4d), out_features=d
|
| 126 |
+
nc = ffn.proj.out_features // cs
|
| 127 |
+
k = max(1, int(af * nc))
|
| 128 |
+
ffn.active_chunks = torch.randperm(nc, device=device)[:k].sort().values
|
| 129 |
+
else:
|
| 130 |
+
for ffn in ffns:
|
| 131 |
+
ffn.mode = 'dense'; ffn.active_chunks = None
|
| 132 |
+
|
| 133 |
+
x, y = get_batch(train_data, torch.Generator().manual_seed(step))
|
| 134 |
+
opt.zero_grad()
|
| 135 |
+
_, loss = model(x, y)
|
| 136 |
+
loss.backward()
|
| 137 |
+
opt.step()
|
| 138 |
+
|
| 139 |
+
torch.cuda.synchronize()
|
| 140 |
+
ms = 1000 * (time.perf_counter() - t0) / STEPS
|
| 141 |
+
|
| 142 |
+
# Eval
|
| 143 |
+
model.eval()
|
| 144 |
+
for ffn in ffns: ffn.mode = 'dense'; ffn.active_chunks = None
|
| 145 |
+
with torch.no_grad():
|
| 146 |
+
vl = sum(model(*get_batch(val_data, torch.Generator().manual_seed(9999+i)))[1].item() for i in range(20))/20
|
| 147 |
+
|
| 148 |
+
results[mode] = (ms, vl)
|
| 149 |
+
del model; torch.cuda.empty_cache()
|
| 150 |
+
|
| 151 |
+
d_ms = results['dense'][0]
|
| 152 |
+
for mode in ['dense', 'pyloop', 'triton']:
|
| 153 |
+
ms, vl = results[mode]
|
| 154 |
+
sp = d_ms / ms
|
| 155 |
+
print(f"{d:>7} | {mode:>8} | {ms:>9.1f}ms | {sp:>9.2f}x | {vl:>9.4f}")
|
| 156 |
+
print()
|