xuan-luo's picture
download
raw
26.9 kB
"""Equal-memory decode capacity benchmark for GQA and head64 rolling variants.
Synthetic exact-shape weights; compact raw rolling banks and fixed local rings.
Includes all projections, 12 layers, FFN and vocabulary head. Excludes prefill.
"""
from __future__ import annotations
import argparse
import json
import os
import statistics
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT), str(ROOT / 'inference')]
import torch
import torch.nn.functional as F
import triton as tr
import triton.language as tl
from benchmark_cache375 import BudgetModel
from inference.compact_triton import norm, swiglu, _rounded_rotate
from inference.kernels import _merge
from benchmark_decode_batches import check_exclusive
@tr.jit
def prepare(M, K, V, LK, LV, Q, C, S, B, CAP: tl.constexpr,
POS, I, R: tl.constexpr, LOCAL: tl.constexpr, FIRST: tl.constexpr):
b, h = tl.program_id(0).to(tl.int64), tl.program_id(1)
slots: tl.constexpr = 64 // R
new: tl.constexpr = slots if FIRST else 1
width: tl.constexpr = 1024 if LOCAL else 512 + new * 8 * R
d = tl.arange(0, 64)
x = tl.load(M + b * width + h * 64 + d)
other = tl.load(M + b * width + h * 64 + (d + 32) % 64)
c = tl.load(C + POS * 64 + d).to(x.dtype)
s = tl.load(S + POS * 64 + d).to(x.dtype)
tl.store(Q + (b * 8 + h) * 64 + d, _rounded_rotate(x, other, c, s, d < 32))
if h < 4:
r = tl.arange(0, R)
for j in range(new):
state = j if FIRST else I + slots - 1
if LOCAL:
coord = j * R + r if FIRST else 64 - R + r
k = tl.load(M + b * width + 512 + h * 64 + coord)
v = tl.load(M + b * width + 768 + h * 64 + coord)
else:
k = tl.load(M + b * width + 512 + j * 8 * R + h * 2 * R + r)
v = tl.load(M + b * width + 512 + j * 8 * R + h * 2 * R + R + r)
off = (((state * B + b) * 4 + h) * CAP + POS) * R + r
tl.store(K + off, k)
tl.store(V + off, v)
if LOCAL:
off = (((I * B + b) * 4 + h) * 128 + POS % 128) * 64 + d
tl.store(LK + off, tl.load(M + b * width + 512 + h * 64 + d))
tl.store(LV + off, tl.load(M + b * width + 768 + h * 64 + d))
@tr.jit
def attend(Q, K, V, LK, LV, C, S, P, L, B, CAP: tl.constexpr,
END, I, R: tl.constexpr, LOCAL: tl.constexpr,
GATHER_PARTNER: tl.constexpr, TOKEN_MAJOR: tl.constexpr,
NS: tl.constexpr, SPLIT: tl.constexpr):
bg, part = tl.program_id(0), tl.program_id(1)
b, g = (bg // 4).to(tl.int64), bg % 4
h, d = tl.arange(0, 16), tl.arange(0, 64)
head = b * 8 + g * 2 + h
q = tl.load(Q + head[:, None] * 64 + d[None, :], h[:, None] < 2, 0)
acc = tl.full((16, 64), 0, tl.float32)
maximum = tl.full((16,), -float('inf'), tl.float32)
denom = tl.full((16,), 0, tl.float32)
for begin in range(part * SPLIT, tl.minimum((part + 1) * SPLIT, END), 64):
t = begin + tl.arange(0, 64)
state = I + d // R
koord = (d + 32) % 64
near = (t >= END - 128) & (t < END)
if TOKEN_MAJOR:
# Load one [context, head_dim] tile so each raw 16-d state chunk
# is contiguous in memory. QK consumes its transpose.
off = (((state[None, :] * B + b) * 4 + g) * CAP + t[:, None]) * R + d[None, :] % R
off_other = ((((I + koord[None, :] // R) * B + b) * 4 + g) * CAP + t[:, None]) * R + koord[None, :] % R
valid = t[:, None] < END
k = tl.load(K + off, valid, 0)
if GATHER_PARTNER:
gather_index = tl.broadcast_to(koord[None, :], (64, 64))
ko = tl.gather(k, gather_index, axis=1)
else:
ko = tl.load(K + off_other, valid, 0)
if LOCAL:
loff = (((I * B + b) * 4 + g) * 128 + t[:, None] % 128) * 64
lk = tl.load(LK + loff + d[None, :], near[:, None], 0)
lko = tl.load(LK + loff + koord[None, :], near[:, None], 0)
k, ko = tl.where(near[:, None], lk, k), tl.where(near[:, None], lko, ko)
c = tl.load(C + t[:, None] * 64 + d[None, :], valid, 0).to(k.dtype)
s = tl.load(S + t[:, None] * 64 + d[None, :], valid, 0).to(k.dtype)
k = _rounded_rotate(k, ko, c, s, d[None, :] < 32)
score = tl.dot(q, tl.trans(k)) * 0.125
else:
off = (((state[:, None] * B + b) * 4 + g) * CAP + t[None, :]) * R + d[:, None] % R
off_other = ((((I + koord[:, None] // R) * B + b) * 4 + g) * CAP + t[None, :]) * R + koord[:, None] % R
k = tl.load(K + off, t[None, :] < END, 0)
if GATHER_PARTNER:
gather_index = tl.broadcast_to(koord[:, None], (64, 64))
ko = tl.gather(k, gather_index, axis=0)
else:
ko = tl.load(K + off_other, t[None, :] < END, 0)
if LOCAL:
loff = (((I * B + b) * 4 + g) * 128 + t[None, :] % 128) * 64
lk = tl.load(LK + loff + d[:, None], near[None, :], 0)
lko = tl.load(LK + loff + koord[:, None], near[None, :], 0)
k, ko = tl.where(near[None, :], lk, k), tl.where(near[None, :], lko, ko)
c = tl.load(C + t[None, :] * 64 + d[:, None], t[None, :] < END, 0).to(k.dtype)
s = tl.load(S + t[None, :] * 64 + d[:, None], t[None, :] < END, 0).to(k.dtype)
k = _rounded_rotate(k, ko, c, s, d[:, None] < 32)
score = tl.dot(q, k) * 0.125
score = tl.where(t[None, :] < END, score, -float('inf'))
nm = tl.maximum(maximum, tl.max(score, 1))
alpha = tl.exp(maximum - nm)
probability = tl.exp(score - nm[:, None])
voff = (((state[None, :] * B + b) * 4 + g) * CAP + t[:, None]) * R + d[None, :] % R
value = tl.load(V + voff, t[:, None] < END, 0)
if LOCAL:
lv = tl.load(LV + (((I * B + b) * 4 + g) * 128 + t[:, None] % 128) * 64 + d[None, :], near[:, None], 0)
value = tl.where(near[:, None], lv, value)
acc = acc * alpha[:, None] + tl.dot(probability.to(value.dtype), value)
denom = denom * alpha + tl.sum(probability, 1)
maximum = nm
tl.store(P + (head[:, None] * NS + part) * 64 + d[None, :], acc / denom[:, None], h[:, None] < 2)
tl.store(L + head * NS + part, maximum + tl.log(denom), h < 2)
@tr.jit
def attend_pair(Q, K, V, LK, LV, C, S, P, L, B, CAP: tl.constexpr,
END, I, R: tl.constexpr, LOCAL: tl.constexpr,
GATHER_PARTNER: tl.constexpr, TOKEN_MAJOR: tl.constexpr,
NS: tl.constexpr, SPLIT: tl.constexpr):
bg, part = tl.program_id(0), tl.program_id(1)
b, g = (bg // 4).to(tl.int64), bg % 4
d = tl.arange(0, 64)
t = part * SPLIT + tl.arange(0, SPLIT)
q0 = tl.load(Q + (b*8+g*2)*64+d).to(tl.float32)
q1 = tl.load(Q + (b*8+g*2+1)*64+d).to(tl.float32)
other = (d+32) % 64
off = ((((I+d[None, :]//R)*B+b)*4+g)*CAP+t[:, None])*R+d[None, :] % R
oo = ((((I+other[None, :]//R)*B+b)*4+g)*CAP+t[:, None])*R+other[None, :] % R
k = tl.load(K+off, t[:, None]<END, 0)
ko = tl.load(K+oo, t[:, None]<END, 0)
if LOCAL:
near = (t>=END-128)&(t<END)
lo = (((I*B+b)*4+g)*128+t[:, None] % 128)*64
lk = tl.load(LK+lo+d[None, :], near[:, None], 0)
lko = tl.load(LK+lo+other[None, :], near[:, None], 0)
k = tl.where(near[:, None], lk, k)
ko = tl.where(near[:, None], lko, ko)
c = tl.load(C+t[:, None]*64+d[None, :], t[:, None]<END, 0).to(k.dtype)
s = tl.load(S+t[:, None]*64+d[None, :], t[:, None]<END, 0).to(k.dtype)
k = _rounded_rotate(k, ko, c, s, d[None, :]<32).to(tl.float32)
score0 = tl.where(t<END, tl.sum(k*q0[None, :], 1)*.125, -1.e30)
score1 = tl.where(t<END, tl.sum(k*q1[None, :], 1)*.125, -1.e30)
m0, m1 = tl.max(score0, 0), tl.max(score1, 0)
p0 = tl.where(t<END, tl.exp(score0-m0), 0.)
p1 = tl.where(t<END, tl.exp(score1-m1), 0.)
z0, z1 = tl.sum(p0, 0), tl.sum(p1, 0)
value = tl.load(V+off, t[:, None]<END, 0)
if LOCAL:
lv = tl.load(LV+lo+d[None, :], near[:, None], 0)
value = tl.where(near[:, None], lv, value)
out0 = tl.sum(p0.to(value.dtype).to(tl.float32)[:, None]*value.to(tl.float32), 0)/tl.maximum(z0, 1.e-30)
out1 = tl.sum(p1.to(value.dtype).to(tl.float32)[:, None]*value.to(tl.float32), 0)/tl.maximum(z1, 1.e-30)
h0, h1 = (b*8+g*2)*NS+part, (b*8+g*2+1)*NS+part
tl.store(P+h0*64+d, out0)
tl.store(P+h1*64+d, out1)
tl.store(L+h0, tl.where(z0>0, m0+tl.log(z0), -float('inf')))
tl.store(L+h1, tl.where(z1>0, m1+tl.log(z1), -float('inf')))
@tr.jit
def attend_relative_pair(Q, K, V, LK, LV, C, S, P, L, B, CAP: tl.constexpr,
END, I, R: tl.constexpr, LOCAL: tl.constexpr,
NS: tl.constexpr, SPLIT: tl.constexpr):
"""Two-query decode using direct pairwise RoPE arithmetic.
For each history token, load the two 32-d halves once, rotate them in
registers, and reduce scores for the two real query heads. This avoids a
second global K load for the RoPE partner and avoids padded MMA rows.
"""
bg, part = tl.program_id(0), tl.program_id(1)
b, g = (bg // 4).to(tl.int64), bg % 4
t = part * SPLIT + tl.arange(0, SPLIT)
half = tl.arange(0, 32)
d = tl.arange(0, 64)
head0 = b * 8 + g * 2
head1 = head0 + 1
q0a = tl.load(Q + head0 * 64 + half).to(tl.float32)
q0b = tl.load(Q + head0 * 64 + half + 32).to(tl.float32)
q1a = tl.load(Q + head1 * 64 + half).to(tl.float32)
q1b = tl.load(Q + head1 * 64 + half + 32).to(tl.float32)
sa = I + half // R
sb = I + (half + 32) // R
offa = (((sa[None, :] * B + b) * 4 + g) * CAP + t[:, None]) * R + half[None, :] % R
offb = (((sb[None, :] * B + b) * 4 + g) * CAP + t[:, None]) * R + (half[None, :] + 32) % R
valid = t[:, None] < END
ka = tl.load(K + offa, valid, 0)
kb = tl.load(K + offb, valid, 0)
near = (t >= END - 128) & (t < END)
if LOCAL:
local_base = ((I * B + b) * 4 + g) * 128
local_a = (local_base + t[:, None] % 128) * 64 + half[None, :]
local_b = (local_base + t[:, None] % 128) * 64 + half[None, :] + 32
lka = tl.load(LK + local_a, near[:, None], 0)
lkb = tl.load(LK + local_b, near[:, None], 0)
ka, kb = tl.where(near[:, None], lka, ka), tl.where(near[:, None], lkb, kb)
c = tl.load(C + t[:, None] * 64 + half[None, :], valid, 0).to(ka.dtype)
s = tl.load(S + t[:, None] * 64 + half[None, :], valid, 0).to(ka.dtype)
# Match the existing BF16 RoPE rounding: round each multiply, then add.
ra0 = (ka.to(tl.float32) * c.to(tl.float32)).to(ka.dtype)
ra1 = (-kb.to(tl.float32) * s.to(tl.float32)).to(ka.dtype)
rb0 = (kb.to(tl.float32) * c.to(tl.float32)).to(kb.dtype)
rb1 = (ka.to(tl.float32) * s.to(tl.float32)).to(ka.dtype)
kra = (ra0.to(tl.float32) + ra1.to(tl.float32)).to(ka.dtype)
krb = (rb0.to(tl.float32) + rb1.to(tl.float32)).to(kb.dtype)
score0 = tl.sum(q0a[None, :] * kra.to(tl.float32)
+ q0b[None, :] * krb.to(tl.float32), 1) * 0.125
score1 = tl.sum(q1a[None, :] * kra.to(tl.float32)
+ q1b[None, :] * krb.to(tl.float32), 1) * 0.125
score0 = tl.where(t < END, score0, -1.e30)
score1 = tl.where(t < END, score1, -1.e30)
m0, m1 = tl.max(score0, 0), tl.max(score1, 0)
p0 = tl.where(t < END, tl.exp(score0 - m0), 0.)
p1 = tl.where(t < END, tl.exp(score1 - m1), 0.)
z0, z1 = tl.sum(p0, 0), tl.sum(p1, 0)
state = I + d // R
voff = ((((state[None, :] * B + b) * 4 + g) * CAP + t[:, None]) * R
+ d[None, :] % R)
value = tl.load(V + voff, t[:, None] < END, 0)
if LOCAL:
local_v = (((I * B + b) * 4 + g) * 128 + t[:, None] % 128) * 64 + d[None, :]
lv = tl.load(LV + local_v, near[:, None], 0)
value = tl.where(near[:, None], lv, value)
vf = value.to(tl.float32)
out0 = tl.sum(p0.to(value.dtype).to(tl.float32)[:, None] * vf, 0) / tl.maximum(z0, 1.e-30)
out1 = tl.sum(p1.to(value.dtype).to(tl.float32)[:, None] * vf, 0) / tl.maximum(z1, 1.e-30)
i0, i1 = head0 * NS + part, head1 * NS + part
tl.store(P + i0 * 64 + d, out0)
tl.store(P + i1 * 64 + d, out1)
tl.store(L + i0, tl.where(z0 > 0, m0 + tl.log(z0), -float('inf')))
tl.store(L + i1, tl.where(z1 > 0, m1 + tl.log(z1), -float('inf')))
class RollingModel(BudgetModel):
def __init__(self, rank, local):
self.name, self.dim, self.backend = 'rolling_window', 64, 'triton'
self.rank, self.local, self.split = rank, local, 512
self.w = {}
torch.manual_seed(5000)
def add(key, shape, scale=False):
x = torch.empty(shape, device='cuda', dtype=torch.bfloat16)
self.w[key] = x.fill_(1) if scale else x.normal_(std=.02)
add('embedding.word_embeddings.weight', (50304, 512))
add('output_layer.weight', (50304, 512))
add('decoder.final_layernorm.weight', (512,), True)
for i in range(12):
def put(key, shape, scale=False):
add(f'decoder.layers.{i}.{key}', shape, scale)
put('input_layernorm.weight', (512,), True)
width = 1024 if local or i == 0 else 512 + 8 * rank
put('self_attention.projection.weight', (width, 512))
put('self_attention.linear_proj.weight', (512, 512))
put('mlp.linear_fc1.layer_norm_weight', (512,), True)
ffn = 2166 if i < 4 else 2165
put('mlp.linear_fc1.weight', (2 * ffn, 512))
put('mlp.linear_fc2.weight', (512, ffn))
self.params = sum(v.numel() for v in self.w.values())
assert self.params == (100872704 if local else 98710016 if rank == 16 else 99430912)
self.init_rope()
def cache(self, batch, capacity):
states = 12 + 64 // self.rank - 1
result = {k: torch.empty((states, batch, 4, capacity, self.rank), device='cuda', dtype=torch.bfloat16) for k in ('k', 'v')}
if self.local:
result.update({k: torch.empty((12, batch, 4, 128, 64), device='cuda', dtype=torch.bfloat16) for k in ('lk', 'lv')})
return result
def attention(self, q, cache, i, start):
b, cap, end = q.shape[0], cache['k'].shape[3], start + 1
lk, lv = cache.get('lk', cache['k']), cache.get('lv', cache['v'])
ns = tr.cdiv(end, self.split)
partial = torch.empty((b * 8, ns, 64), device='cuda', dtype=torch.float32)
lse = torch.empty((b * 8, ns), device='cuda', dtype=torch.float32)
out = torch.empty_like(q)
mode = getattr(self, 'kernel', 'mma')
if mode == 'relative':
self.last_attention_kernel = attend_relative_pair[(b * 4, ns)](
q, cache['k'], cache['v'], lk, lv, self.cos, self.sin, partial, lse,
b, cap, end, i, self.rank, self.local, ns, self.split,
num_warps=getattr(self, 'warps', 4), num_stages=1, enable_fp_fusion=False)
else:
kernel = attend_pair if mode == 'pair' else attend
self.last_attention_kernel = kernel[(b * 4, ns)](
q, cache['k'], cache['v'], lk, lv, self.cos, self.sin, partial, lse,
b, cap, end, i, self.rank, self.local,
getattr(self, 'gather_partner', False), getattr(self, 'token_major', False), ns, self.split,
num_warps=getattr(self, 'warps', 4), num_stages=1, enable_fp_fusion=False)
_merge[(b * 8,)](partial, lse, out, ns, 64, tr.next_power_of_2(ns), 64, num_warps=4)
return out
@torch.inference_mode()
def forward(self, ids, cache, start=0):
b, cap = ids.shape[0], cache['k'].shape[3]
x = F.embedding(ids, self.w['embedding.word_embeddings.weight'])
for i in range(12):
mixed = F.linear(norm(x, self.weight(i, 'input_layernorm.weight')), self.weight(i, 'self_attention.projection.weight'))
if self.backend == 'eager':
mixed = mixed.reshape(b, -1)
q = self.rope(mixed[:, :512].view(b, 1, 8, 64), start)
slots = 64 // self.rank
count = slots if i == 0 else 1
if self.local:
fresh_k = mixed[:, 512:768].view(b, 4, 64)
fresh_v = mixed[:, 768:].view(b, 4, 64)
cache['lk'][i, :, :, start % 128] = fresh_k
cache['lv'][i, :, :, start % 128] = fresh_v
states = [(fresh_k[..., j*self.rank:(j+1)*self.rank], fresh_v[..., j*self.rank:(j+1)*self.rank])
for j in range(slots)] if i == 0 else [(fresh_k[..., -self.rank:], fresh_v[..., -self.rank:])]
else:
fresh = mixed[:, 512:].view(b, count, 4, 2, self.rank)
states = [(fresh[:, j, :, 0], fresh[:, j, :, 1]) for j in range(count)]
for j, (key, value) in enumerate(states):
state = j if i == 0 else i + slots - 1
cache['k'][state, :, :, start] = key
cache['v'][state, :, :, start] = value
k = torch.cat([cache['k'][j, :, :, :start+1].transpose(1, 2) for j in range(i, i+slots)], -1)
v = torch.cat([cache['v'][j, :, :, :start+1].transpose(1, 2) for j in range(i, i+slots)], -1)
if self.local:
t = torch.arange(max(0, start-127), start+1, device='cuda')
k[:, t] = cache['lk'][i, :, :, t % 128].transpose(1, 2)
v[:, t] = cache['lv'][i, :, :, t % 128].transpose(1, 2)
scores = torch.einsum('bqhd,bthd->bhqt', q.float(), self.rope(k).repeat_interleave(2, 2).float()) * .125
out = torch.einsum('bhqt,bthd->bqhd', scores.softmax(-1), v.repeat_interleave(2, 2).float()).to(x.dtype)
else:
q = torch.empty((b, 1, 8, 64), device='cuda', dtype=torch.bfloat16)
prepare[(b, 8)](mixed, cache['k'], cache['v'], cache.get('lk', cache['k']), cache.get('lv', cache['v']),
q, self.cos, self.sin, b, cap, start, i, self.rank, self.local, i == 0, enable_fp_fusion=False)
out = self.attention(q, cache, i, start)
x = x + F.linear(out.reshape(b, 1, 512), self.weight(i, 'self_attention.linear_proj.weight'))
h = norm(x, self.weight(i, 'mlp.linear_fc1.layer_norm_weight'))
x = x + F.linear(swiglu(F.linear(h, self.weight(i, 'mlp.linear_fc1.weight'))), self.weight(i, 'mlp.linear_fc2.weight'))
return F.linear(norm(x, self.w['decoder.final_layernorm.weight']), self.w['output_layer.weight'])
def build(variant):
return BudgetModel('gqa') if variant == 'gqa' else RollingModel(16 if '16' in variant else 32, 'w128' in variant)
@torch.inference_mode()
def validate():
rows = []
for rank in (16, 32):
for local in (False, True):
model = RollingModel(rank, local)
for start in (0, 127, 128, 129, 512, 32768):
b = 2
cache = model.cache(b, start + 2)
for value in cache.values():
value.normal_(std=.2)
mixed = torch.randn((b, 1024 if local else 512 + 8 * rank), device='cuda', dtype=torch.bfloat16)
i = 3
q = torch.empty((b, 1, 8, 64), device='cuda', dtype=torch.bfloat16)
prepare[(b, 8)](mixed, cache['k'], cache['v'], cache.get('lk', cache['k']), cache.get('lv', cache['v']),
q, model.cos, model.sin, b, start + 2, start, i, rank, local, i == 0, enable_fp_fusion=False)
rawq = mixed[:, :512].view(b, 1, 8, 64)
torch.testing.assert_close(q, model.rope(rawq, start), rtol=.02, atol=.01)
k = torch.cat([cache['k'][j, :, :, :start + 1].transpose(1, 2) for j in range(i, i + 64 // rank)], -1)
v = torch.cat([cache['v'][j, :, :, :start + 1].transpose(1, 2) for j in range(i, i + 64 // rank)], -1)
if local:
t = torch.arange(max(0, start - 127), start + 1, device='cuda')
k[:, t] = cache['lk'][i, :, :, t % 128].transpose(1, 2)
v[:, t] = cache['lv'][i, :, :, t % 128].transpose(1, 2)
k = model.rope(k)
scores = torch.einsum('bqhd,bthd->bhqt', q.float(), k.repeat_interleave(2, 2).float()) * .125
ref = torch.einsum('bhqt,bthd->bqhd', scores.softmax(-1), v.repeat_interleave(2, 2).float())
actual = model.attention(q, cache, i, start).float()
rel = float((actual - ref).norm() / ref.norm())
assert rel < .02, (rank, local, start, rel)
rows.append(dict(rank=rank, local=local, position=start, relative_l2=rel))
for start in (126, 512):
fast_cache = model.cache(2, start + 4)
for value in fast_cache.values():
value.normal_(std=.2)
ref_cache = {k: v.clone() for k, v in fast_cache.items()}
for step in range(4):
ids = torch.randint(0, 50304, (2, 1), device='cuda')
model.backend = 'triton'
actual = model.forward(ids, fast_cache, start + step).float()
model.backend = 'eager'
reference = model.forward(ids, ref_cache, start + step).float()
rel = float((actual - reference).norm() / reference.norm())
assert rel < .05, (rank, local, start, step, rel)
rows.append(dict(kind='full_model_logits', rank=rank, local=local, position=start+step, relative_l2=rel))
model.backend = 'triton'
return rows
@torch.inference_mode()
def trial(args):
check_exclusive()
torch.set_num_threads(4)
budget = int(args.budget_gib * 1024**3)
torch.cuda.set_per_process_memory_fraction(budget / torch.cuda.get_device_properties(0).total_memory)
row = dict(variant=args.variant, context=args.context, batch=args.batch, budget_bytes=budget)
try:
model = build(args.variant)
if hasattr(model, 'split'):
model.split = args.split
model.kernel = args.kernel
cache = model.cache(args.batch, args.context + 8)
for value in cache.values():
value.normal_(std=.2)
ids = torch.randint(0, 50304, (args.batch, 8), device='cuda')
def run():
# Fixed-context decode: rewriting the SAME next-token slot preserves
# the historical ring across warmups/replays. An eight-token block
# replay would overwrite seven historical ring entries before the
# next replay begins, changing its inputs.
return model.forward(ids[:, :1], cache, args.context)
for _ in range(2):
run()
reference = run().clone()
torch.cuda.empty_cache()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
out = run()
graph.replay()
torch.cuda.synchronize()
rel = float((out.float() - reference.float()).norm() / reference.float().norm())
assert rel < .001, rel
for _ in range(3):
graph.replay()
samples = []
for _ in range(5):
a, z = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
a.record()
graph.replay()
z.record()
z.synchronize()
samples.append(a.elapsed_time(z))
ms = statistics.median(samples)
return dict(row, status='ok', ms=ms, tokens_s=args.batch*1000/ms,
params=model.params, cache_bytes=sum(v.numel()*v.element_size() for v in cache.values()),
peak_reserved=torch.cuda.max_memory_reserved(), samples_ms=samples, graph_relative_l2=rel)
except torch.cuda.OutOfMemoryError as exc:
return dict(row, status='oom', reason=str(exc))
def main():
p = argparse.ArgumentParser()
p.add_argument('--variant', choices=['gqa', 'roll16', 'roll32', 'roll16_w128', 'roll32_w128'])
p.add_argument('--context', type=int, default=32768)
p.add_argument('--batch', type=int)
p.add_argument('--split', type=int, default=512)
p.add_argument('--kernel', choices=['mma', 'pair'], default='mma')
p.add_argument('--budget-gib', type=float, default=38)
p.add_argument('--validate', action='store_true')
p.add_argument('--output', required=True)
args = p.parse_args()
if args.validate:
result = dict(status='PASS', checks=validate())
elif args.batch is not None:
result = trial(args)
else:
output = Path(args.output)
folder = output.parent / (output.stem + '_trials')
folder.mkdir(parents=True, exist_ok=True)
trials = []
def run(b, tag):
dest = folder / f'b{b}_{tag}.json'
command = [sys.executable, __file__, '--variant', args.variant, '--context', str(args.context),
'--batch', str(b), '--budget-gib', str(args.budget_gib), '--split', str(args.split), '--kernel', args.kernel, '--output', str(dest)]
proc = subprocess.run(command, capture_output=True, text=True)
if proc.returncode:
raise RuntimeError(proc.stderr[-6000:])
row = json.loads(dest.read_text())
trials.append(row)
print(json.dumps(row), flush=True)
return row
elements = 6144 if args.variant == 'gqa' else 1920 if '16' in args.variant else 3328
extra = 1572864 if 'w128' in args.variant else 0
upper = int(args.budget_gib * 1024**3 // ((args.context + 8) * elements * 2 + extra)) + 1
low, high = 0, upper
while low + 1 < high:
mid = (low + high) // 2
if run(mid, 'search')['status'] == 'ok':
low = mid
else:
high = mid
assert low > 0
confirmed = run(low, 'confirm')
assert confirmed['status'] == 'ok'
result = dict(status='PASS', variant=args.variant, context=args.context, max_batch=low,
first_infeasible_batch=high, confirmed=confirmed, trials=trials,
protocol='A100 40GiB, common 38GiB allocator cap, BF16 synthetic exact architecture, compact cache with 8 output slots reserved, CUDA graph fixed-context single-token full-model decode, 5 timing rounds; excludes prefill/sampling')
dest = Path(args.output)
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(json.dumps(result, indent=2) + '\n')
print(json.dumps(result), flush=True)
if __name__ == '__main__':
main()

Xet Storage Details

Size:
26.9 kB
·
Xet hash:
84df48579759d8ea5041b33b57faf63d213c038c31112f164ae58a9b9aa1721e

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.