xuan-luo's picture
download
raw
19.9 kB
"""Checkpoint-backed, common eager FlashAttention inference comparison.
Compact static caches; concat materializes K/V per layer, residual reconstructs
history recursively. These are reference implementations, not tuned kernels.
"""
from __future__ import annotations
import argparse
import gc
import hashlib
import json
import random
import statistics
import sys
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
import torch.distributed.checkpoint as dcp
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0,str(ROOT))
CHECKPOINTS = {
'gqa': 'arxiv/gqa/gqa_ctx32k_stage1b_step0001908/checkpoints/iter_0001908',
'cla': 'arxiv/cla/cla_ctx32k_stage1b_step0002180/checkpoints/iter_0002180',
'concat': 'arxiv/kvpath/kvpath_ctx32k_stage1b_step0001908/checkpoints/iter_0001908',
'residual': 'training/kvpath_delta/overall_delta/train_32k/checkpoints/iter_0001908',
}
class Model:
def __init__(self, name, backend='flash'):
self.name = name
if backend not in ('flash', 'triton', 'eager'):
raise ValueError(backend)
self.backend = backend
self.dim = dict(gqa=64, cla=256, concat=160, residual=160)[name]
self.alpha_dim = 128
self.delta_dim = 32
reader = dcp.FileSystemReader(ROOT / CHECKPOINTS[name])
meta = reader.read_metadata().state_dict_metadata
state = {k: torch.empty(tuple(v.size), dtype=v.properties.dtype)
for k, v in meta.items() if hasattr(v, 'size')
and k.startswith(('embedding.', 'decoder.', 'output_layer.'))}
dcp.load(state, storage_reader=reader)
self.params = sum(v.numel() for v in state.values())
assert self.params == 98710016, (name, self.params)
self.w = {k: v.to('cuda', torch.bfloat16) for k, v in state.items()}
self.init_rope()
def init_rope(self):
self.rope_dim = self.delta_dim if self.name == 'concat' else self.dim
inv = 1 / (1e6 ** (torch.arange(0, self.rope_dim, 2, device='cuda').float() / self.rope_dim))
phase = torch.outer(torch.arange(40960, device='cuda').float(), inv)
phase = torch.cat((phase, phase), dim=-1)
self.cos, self.sin = phase.cos()[None, :, None], phase.sin()[None, :, None]
def weight(self, i, suffix):
key = f'decoder.layers.{i}.{suffix}'
if key in self.w:
return self.w[key]
return self.w[f'decoder.layers.{suffix}'][i]
def norm(self, x, weight):
if self.backend == 'triton':
from inference.compact_triton import norm
return norm(x,weight)
# Megatron RMSNorm reduces in float32 and returns model dtype.
return (x.float() * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + 1e-6)
* weight.float()).to(x.dtype)
def rope(self, x, start=0):
# Match Megatron: cast cos/sin to BF16 before the multiply/add.
c = self.cos[:, start:start+x.shape[1]].to(x.dtype)
s = self.sin[:, start:start+x.shape[1]].to(x.dtype)
a, b = x.chunk(2, -1)
return x * c + torch.cat((-b, a), -1) * s
def cache(self, batch, capacity):
cache = {}
def alloc(key, dim):
cache[key] = torch.empty(batch, capacity, 4, 2, dim, device='cuda', dtype=torch.bfloat16)
for i in range(12):
if self.name == 'gqa':
alloc(('base', i), self.dim)
elif self.name == 'cla':
if i % 4 == 0:
alloc(('base', i), self.dim)
elif self.name == 'concat':
if i % 4 == 0:
alloc(('base', i), self.alpha_dim)
alloc(('delta', i), self.delta_dim)
elif i % 4 == 0:
alloc(('base', i), self.dim)
else:
alloc(('delta', i), self.delta_dim)
assert sum(v.numel() for v in cache.values()) == batch * capacity * self.cache_elements_per_token
return cache
@property
def cache_elements_per_token(self):
widths = dict(gqa=12*self.dim, cla=3*self.dim,
concat=3*self.alpha_dim+12*self.delta_dim,
residual=3*self.dim+9*self.delta_dim)
return 4*2*widths[self.name]
@torch.inference_mode()
def forward(self, ids, cache, start=0, all_logits=False):
batch, seq = ids.shape
end = start + seq
if start and seq != 1:
raise ValueError('Only full prefill or single-token decode is supported')
x = F.embedding(ids, self.w['embedding.word_embeddings.weight'])
previous = None
for i in range(12):
anchor = i // 4 * 4
if self.name == 'gqa':
nw = self.weight(i, 'self_attention.linear_qkv.layer_norm_weight')
else:
nw = self.weight(i, 'input_layernorm.weight')
h = self.norm(x, nw)
def linear(suffix, value=h):
return F.linear(value, self.weight(i, suffix))
if self.backend == 'triton':
from inference.compact_triton import prepare
kv = None
if self.name == 'gqa':
mixed = linear('self_attention.linear_qkv.weight')
elif self.name == 'cla':
mixed = linear('self_attention.linear_q.weight')
if i == anchor:
kv = linear('self_attention.linear_kv.weight')
else:
if self.name == 'concat':
suffix = 'linear_q_delta_base' if i == anchor else 'linear_q_delta'
else:
suffix = 'linear_q_kv' if i == anchor else 'linear_q_delta'
mixed = linear(f'self_attention.{suffix}.weight')
q = prepare(mixed,kv,cache,self.name,i,start,self.cos,self.sin,self.dim)
elif self.name == 'gqa':
mixed = linear('self_attention.linear_qkv.weight').view(batch, seq, 4, 4, 64)
q = mixed[..., :2, :].reshape(batch, seq, 8, 64)
kv = mixed[..., 2:, :]
current = torch.stack((self.rope(kv[..., 0, :], start), kv[..., 1, :]), -2)
cache['base', i][:, start:end].copy_(current)
history = cache['base', i][:, :end]
k, v = history[..., 0, :], history[..., 1, :]
q = self.rope(q, start)
elif self.name == 'cla':
q = self.rope(linear('self_attention.linear_q.weight').view(batch, seq, 8, 256), start)
if i == anchor:
kv = linear('self_attention.linear_kv.weight').view(batch, seq, 4, 2, 256)
cache['base', i][:, start:end].copy_(torch.stack((self.rope(kv[..., 0, :], start), kv[..., 1, :]), -2))
history = cache['base', anchor][:, :end]
k, v = history[..., 0, :], history[..., 1, :]
elif self.name == 'concat':
suffix = 'linear_q_delta_base' if i == anchor else 'linear_q_delta'
mixed = linear(f'self_attention.{suffix}.weight')
q_end = 8*self.dim
delta_end = q_end+8*self.delta_dim
q = mixed[..., :q_end].view(batch, seq, 8, self.dim)
q = torch.cat((q[..., :self.alpha_dim], self.rope(q[..., self.alpha_dim:], start)), -1)
delta = mixed[..., q_end:delta_end].view(batch, seq, 4, 2, self.delta_dim)
cache['delta', i][:, start:end].copy_(torch.stack((self.rope(delta[..., 0, :], start), delta[..., 1, :]), -2))
if i == anchor:
cache['base', i][:, start:end].copy_(mixed[..., delta_end:].view(batch, seq, 4, 2, self.alpha_dim))
if self.backend != 'triton':
base, delta = cache['base', anchor][:, :end], cache['delta', i][:, :end]
k = torch.cat((base[..., 0, :], delta[..., 0, :]), -1)
v = torch.cat((base[..., 1, :], delta[..., 1, :]), -1)
else:
suffix = 'linear_q_kv' if i == anchor else 'linear_q_delta'
mixed = linear(f'self_attention.{suffix}.weight')
q_end = 8*self.dim
q = self.rope(mixed[..., :q_end].view(batch, seq, 8, self.dim), start)
if i == anchor:
cache['base', i][:, start:end].copy_(mixed[..., q_end:].view(batch, seq, 4, 2, self.dim))
previous = cache['base', i][:, :end]
else:
cache['delta', i][:, start:end].copy_(mixed[..., q_end:].view(batch, seq, 4, 2, self.delta_dim))
if self.backend != 'triton':
update = torch.einsum('bshvr,hvdr->bshvd', cache['delta', i][:, :end],
self.weight(i, 'self_attention.delta_up_weight'))
previous = previous + update
if self.backend != 'triton':
k, v = self.rope(previous[..., 0, :]), previous[..., 1, :]
if self.backend == 'triton':
from inference.compact_triton import attention
if seq == 1 and getattr(self, 'decode_attention', None) is not None:
# Opt-in decode backend; preparation/projections/MLP stay common.
out = self.decode_attention(q, cache, i, end)
elif self.name == 'residual' and seq > 1:
# Prefill reuses the full current-sequence state across
# depth; do not recompute it for every query tile.
if i == anchor:
previous = cache['base',i][:,:end]
else:
update = torch.einsum('bshvr,hvdr->bshvd',cache['delta',i][:,:end],
self.weight(i,'self_attention.delta_up_weight'))
previous = previous + update
dense = torch.stack((self.rope(previous[...,0,:]),previous[...,1,:]),-2)
out = attention(q,{('base',i):dense},'gqa',i,start,self.cos,self.sin,self.weight)
else:
out = attention(q,cache,self.name,i,start,self.cos,self.sin,self.weight)
elif self.backend == 'eager_grouped':
from inference.benchmark_eager_grouped import grouped_attention
out = grouped_attention(q, k, v, start)
elif self.backend == 'eager':
# Explicit FP32 QK/softmax/PV oracle; only for small correctness tests.
kk, vv = k.repeat_interleave(2,2).float(), v.repeat_interleave(2,2).float()
scores = torch.einsum('bshd,bthd->bhst',q.float(),kk)*self.dim**-0.5
mask = torch.arange(end,device=x.device)[None,:] > (start+torch.arange(seq,device=x.device))[:,None]
scores.masked_fill_(mask,-float('inf'))
out = torch.einsum('bhst,bthd->bshd',scores.softmax(-1),vv).to(q.dtype)
else:
from flash_attn import flash_attn_func
out = flash_attn_func(q, k, v,
dropout_p=0, softmax_scale=self.dim**-0.5, causal=True)
x = x + linear('self_attention.linear_proj.weight', out.reshape(batch, seq, -1))
norm_suffix = ('pre_mlp_layernorm.weight' if self.name == 'cla'
else 'mlp.linear_fc1.layer_norm_weight')
h = self.norm(x, self.weight(i, norm_suffix))
fc1 = linear('mlp.linear_fc1.weight', h)
if self.backend == 'triton':
from inference.compact_triton import swiglu
activated = swiglu(fc1)
else:
gate, up = fc1.chunk(2,-1)
activated = F.silu(gate)*up
x = x + linear('mlp.linear_fc2.weight', activated)
x = self.norm(x if all_logits else x[:, -1:], self.w['decoder.final_layernorm.weight'])
return F.linear(x, self.w['output_layer.weight'])
def elapsed(call):
torch.cuda.synchronize()
begin, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
wall = time.perf_counter()
begin.record()
result = call()
end.record()
torch.cuda.synchronize()
return result, begin.elapsed_time(end), (time.perf_counter() - wall) * 1000
def parity(model):
torch.manual_seed(5000)
ids = torch.randint(0, 50257, (2, 33), device='cuda')
cache = model.cache(2, 33)
full = model.forward(ids, cache).float()
model.forward(ids[:, :29], cache)
for pos in range(29, 33):
step = model.forward(ids[:, pos:pos+1], cache, pos).float()
diff = full-step
relative = float(diff.norm() / full.norm())
assert relative < .025, (model.name, relative)
return {'relative_l2': relative, 'max_abs': float(diff.abs().max()),
'argmax_match': bool(torch.equal(full.argmax(-1), step.argmax(-1)))}
def run_case(model, ids, context, batch, steps, repeats, graph_mode=False, warmup_replays=0):
gc.collect()
torch.cuda.empty_cache()
torch.cuda.synchronize()
weights_alloc = torch.cuda.memory_allocated()
cache = model.cache(batch, context+steps)
cache_bytes = sum(v.numel()*v.element_size() for v in cache.values())
prompt = ids[:batch, :context]
# Warm both phases, including shape-specific kernels.
model.forward(prompt, cache)
for j in range(2):
model.forward(ids[:batch, context:context+1], cache, context)
torch.cuda.synchronize()
def generate():
for j in range(steps):
out = model.forward(ids[:batch, context+j:context+j+1], cache, context+j)
return out
graph = None
graph_parity = None
graph_capture_peak = 0
graph_reserved = 0
if graph_mode:
stream = torch.cuda.Stream()
stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(stream):
reference_logits = generate().clone()
torch.cuda.current_stream().wait_stream(stream)
reference_logits = reference_logits.cpu()
graph = torch.cuda.CUDAGraph()
torch.cuda.reset_peak_memory_stats()
with torch.cuda.graph(graph, stream=stream):
graph_logits = generate()
torch.cuda.synchronize()
graph_capture_peak = torch.cuda.max_memory_allocated()
graph_reserved = torch.cuda.memory_reserved()
graph.replay()
torch.cuda.synchronize()
graph_parity = float((reference_logits.float()-graph_logits.cpu().float()).norm()
/ reference_logits.float().norm())
assert graph_parity < .001, graph_parity
del reference_logits
def replay():
graph.replay()
return graph_logits
# Stabilize the GPU after shape-specific compilation, outside measured rounds.
for _ in range(warmup_replays):
(replay if graph_mode else generate)()
torch.cuda.synchronize()
prefill, decode, prefill_wall, decode_wall = [], [], [], []
prefill_peaks, decode_peaks = [], []
decode_reserved = []
for _ in range(repeats):
torch.cuda.reset_peak_memory_stats()
logits, gpu, wall = elapsed(lambda: model.forward(prompt, cache))
prefill.append(gpu)
prefill_wall.append(wall)
prefill_peaks.append(torch.cuda.max_memory_allocated())
del logits
torch.cuda.reset_peak_memory_stats()
logits, gpu, wall = elapsed(replay if graph_mode else generate)
decode.append(gpu/steps)
decode_wall.append(wall/steps)
decode_peaks.append(torch.cuda.max_memory_allocated())
decode_reserved.append(torch.cuda.memory_reserved())
del logits
return {'model': model.name, 'context': context, 'batch': batch, 'decode_graph': graph_mode,
'graph_relative_l2': graph_parity,
'graph_capture_peak_alloc_bytes': graph_capture_peak,
'post_capture_reserved_bytes': graph_reserved,
'params': model.params, 'cache_bytes': cache_bytes,
'live_prompt_cache_bytes': batch*context*model.cache_elements_per_token*2,
'weights_runtime_alloc_bytes': weights_alloc,
'prefill_ms_samples': prefill, 'decode_ms_per_step_samples': decode,
'prefill_wall_ms_samples': prefill_wall, 'decode_wall_ms_per_step_samples': decode_wall,
'prefill_ms': statistics.median(prefill),
'decode_ms_per_step': statistics.median(decode),
'decode_tokens_per_sec': batch*1000/statistics.median(decode),
'prefill_peak_alloc_bytes': max(prefill_peaks),
'decode_replay_peak_alloc_bytes': max(decode_peaks),
'decode_peak_alloc_bytes': max([graph_capture_peak, *decode_peaks]),
'decode_reserved_bytes': max(decode_reserved)}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--contexts', type=int, nargs='+', default=[2048,8192,32768])
parser.add_argument('--batches', type=int, nargs='+', default=[1,8])
parser.add_argument('--models', nargs='+', default=list(CHECKPOINTS))
parser.add_argument('--steps', type=int, default=32)
parser.add_argument('--repeats', type=int, default=5)
parser.add_argument('--smoke', action='store_true')
parser.add_argument('--graph', action='store_true', help='Capture the full growing 32-step decode sequence for all models')
parser.add_argument('--backend',choices=['flash','triton','eager'],default='flash')
args = parser.parse_args()
torch.set_num_threads(4)
torch.backends.cuda.matmul.allow_tf32 = False
import triton
report = {'protocol': 'common backend; BF16; static compact cache; actual final32k weights; teacher-forced growing decode; ungraphed prefill',
'backend':args.backend, 'triton':triton.__version__,
'source_sha256': {f:hashlib.sha256((ROOT/f).read_bytes()).hexdigest()
for f in ['inference/four_way.py','inference/compact_triton.py','inference/kernels.py']},
'decode_graph': args.graph,
'torch': torch.__version__,
'gpu': torch.cuda.get_device_name(), 'steps': args.steps, 'repeats': args.repeats,
'checkpoints': CHECKPOINTS, 'parity': {}, 'results': []}
if args.backend == 'flash':
from importlib.metadata import version
report['flash_attn'] = version('flash_attn')
raw = np.fromfile(ROOT/'ppl-evals/datasets/c4_10m.bin', dtype=np.uint16,
count=max(args.batches)*(max(args.contexts)+args.steps))
ids = torch.tensor(raw.astype(np.int64), device='cuda').reshape(max(args.batches), -1)
order = args.models.copy()
random.Random(5000).shuffle(order)
for name in order:
print(f'Loading {name}', flush=True)
model = Model(name, backend=args.backend)
report['parity'][name] = parity(model)
print('PARITY', name, report['parity'][name], flush=True)
if not args.smoke:
for context in args.contexts:
for batch in args.batches:
row = run_case(model, ids, context, batch, args.steps, args.repeats, args.graph)
report['results'].append(row)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2)+'\n')
print(json.dumps(row), flush=True)
del model
gc.collect()
torch.cuda.empty_cache()
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, indent=2)+'\n')
if __name__ == '__main__':
main()

Xet Storage Details

Size:
19.9 kB
·
Xet hash:
e96e466f83afdd8dd8ca07718c45ed61f61336bb266ad0eeeb6ce6ec41987ac8

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