Buckets:
| """Exact-budget GQA / Concat80+20 / Rolling128 decode benchmark. | |
| Synthetic weights with actual training architectures. Static compact caches, | |
| shared fused norm/SwiGLU, cuBLAS projections, fused history attention and graphs. | |
| Rolling retains raw keys: only the rightmost slot is rotated inside attention. | |
| """ | |
| import argparse | |
| import gc | |
| import hashlib | |
| import json | |
| import statistics | |
| import torch | |
| import torch.nn.functional as F | |
| import triton as tr | |
| import triton.language as tl | |
| from four_way import Model, ROOT, elapsed | |
| from inference.compact_triton import norm, swiglu, _rounded_rotate | |
| from inference.kernels import _merge | |
| def rolling_prepare(M, K, V, Q, C, S, B:tl.constexpr, CAP:tl.constexpr, | |
| POS, LAYER, NEW:tl.constexpr): | |
| b,h=tl.program_id(0).to(tl.int64),tl.program_id(1) | |
| d=tl.arange(0,128) | |
| stride=1024+NEW*256 | |
| x=tl.load(M+b*stride+h*128+d) | |
| r=tl.maximum(d-96,0) | |
| other=tl.load(M+b*stride+h*128+96+(r+16)%32) | |
| c=tl.load(C+POS*32+r).to(x.dtype) | |
| s=tl.load(S+POS*32+r).to(x.dtype) | |
| y=_rounded_rotate(x,other,c,s,r<16) | |
| tl.store(Q+(b*8+h)*128+d,tl.where(d<96,x,y)) | |
| if h<4: | |
| for j in range(NEW): | |
| state=tl.where(LAYER==0,j,LAYER+3) | |
| k=tl.load(M+b*stride+1024+j*256+h*64+d,d<32,0) | |
| v=tl.load(M+b*stride+1024+j*256+h*64+32+d,d<32,0) | |
| offset=(((state*B+b)*4+h)*CAP+POS)*32+d | |
| tl.store(K+offset,k,d<32) | |
| tl.store(V+offset,v,d<32) | |
| def rolling_attention(Q,K,V,C,S,P,L,B:tl.constexpr,CAP:tl.constexpr, | |
| END,LAYER,NS:tl.constexpr, | |
| SPLIT:tl.constexpr): | |
| bg,part=tl.program_id(0),tl.program_id(1) | |
| batch=(bg//4).to(tl.int64) | |
| group=bg%4 | |
| h=tl.arange(0,16) | |
| head=bg//4*8+bg%4*2+h | |
| d=tl.arange(0,128) | |
| slot,r=d//32,d%32 | |
| q=tl.load(Q+head[:,None]*128+d[None,:],h[:,None]<2,0) | |
| acc=tl.full((16,128),0,tl.float32) | |
| m=tl.full((16,),-float('inf'),tl.float32) | |
| z=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) | |
| off=((((slot[:,None]+LAYER)*B+batch)*4+group)*CAP+t[None,:])*32+r[:,None] | |
| k=tl.load(K+off,t[None,:]<END,0) | |
| ko=tl.load(K+off-r[:,None]+(r[:,None]+16)%32, | |
| (t[None,:]<END)&(slot[:,None]==3),0) | |
| c=tl.load(C+t[None,:]*32+r[:,None],t[None,:]<END,0).to(k.dtype) | |
| s=tl.load(S+t[None,:]*32+r[:,None],t[None,:]<END,0).to(k.dtype) | |
| kr=_rounded_rotate(k,ko,c,s,r[:,None]<16) | |
| k=tl.where(slot[:,None]==3,kr,k) | |
| score=tl.dot(q,k)*128**-.5 | |
| score=tl.where(t[None,:]<END,score,-float('inf')) | |
| nm=tl.maximum(m,tl.max(score,1)) | |
| a=tl.exp(m-nm) | |
| p=tl.exp(score-nm[:,None]) | |
| voff=((((slot[None,:]+LAYER)*B+batch)*4+group)*CAP+t[:,None])*32+r[None,:] | |
| v=tl.load(V+voff,t[:,None]<END,0) | |
| acc=acc*a[:,None]+tl.dot(p.to(v.dtype),v) | |
| z=z*a+tl.sum(p,1) | |
| m=nm | |
| tl.store(P+(head[:,None]*NS+part)*128+d[None,:],acc/z[:,None],h[:,None]<2) | |
| tl.store(L+head*NS+part,m+tl.log(z),h<2) | |
| class BudgetModel(Model): | |
| def __init__(self,variant): | |
| self.name=variant | |
| self.backend='triton' | |
| self.alpha_dim,self.delta_dim=80,20 | |
| self.dim={'gqa':64,'concat':100,'rolling':128}[variant] | |
| self.w={} | |
| torch.manual_seed(5000) | |
| def add(key,shape,isnorm=False): | |
| v=torch.empty(shape,device='cuda',dtype=torch.bfloat16) | |
| self.w[key]=v.fill_(1) if isnorm else v.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(s,shape,n=False):add(f'decoder.layers.{i}.{s}',shape,n) | |
| put('self_attention.linear_qkv.layer_norm_weight' if variant=='gqa' | |
| else 'input_layernorm.weight',(512,),True) | |
| if variant=='gqa': | |
| put('self_attention.linear_qkv.weight',(1024,512)) | |
| elif variant=='concat': | |
| s='linear_q_delta_base' if i%4==0 else 'linear_q_delta' | |
| put('self_attention.'+s+'.weight',(960+(640 if i%4==0 else 0),512)) | |
| else: | |
| put('self_attention.linear_q_state.weight',(1024+(1024 if i==0 else 256),512)) | |
| put('self_attention.linear_proj.weight',(512,8*self.dim)) | |
| put('mlp.linear_fc1.layer_norm_weight',(512,),True) | |
| f=2048 if variant=='gqa' else 1920 if variant=='concat' else 1771 if i<8 else 1770 | |
| put('mlp.linear_fc1.weight',(2*f,512)) | |
| put('mlp.linear_fc2.weight',(512,f)) | |
| self.params=sum(v.numel() for v in self.w.values()) | |
| assert self.params==98710016,(variant,self.params) | |
| if variant=='rolling': | |
| self.rope_dim=32 | |
| freq=1e6**(-torch.arange(0,32,2,device='cuda').float()/32) | |
| p=torch.outer(torch.arange(40960,device='cuda').float(),freq) | |
| p=torch.cat((p,p),-1) | |
| self.cos,self.sin=p.cos()[None,:,None],p.sin()[None,:,None] | |
| else:self.init_rope() | |
| def cache_elements_per_token(self):return 6144 if self.name=='gqa' else 3840 | |
| def cache(self,batch,capacity): | |
| if self.name!='rolling':return super().cache(batch,capacity) | |
| return {k:torch.empty((15,batch,4,capacity,32),device='cuda',dtype=torch.bfloat16) | |
| for k in ('k','v')} | |
| def forward(self,ids,cache,start=0,all_logits=False): | |
| if self.name!='rolling':return super().forward(ids,cache,start,all_logits) | |
| assert ids.shape[1]==1 | |
| b=ids.shape[0]; cap=cache['k'].shape[3]; end=start+1 | |
| x=F.embedding(ids,self.w['embedding.word_embeddings.weight']) | |
| for i in range(12): | |
| h=norm(x,self.weight(i,'input_layernorm.weight')) | |
| mixed=F.linear(h,self.weight(i,'self_attention.linear_q_state.weight')) | |
| q=torch.empty((b,1,8,128),device=x.device,dtype=x.dtype) | |
| if self.backend=='triton': | |
| rolling_prepare[(b,8)](mixed,cache['k'],cache['v'],q,self.cos,self.sin, | |
| b,cap,start,i,4 if i==0 else 1,enable_fp_fusion=False) | |
| split=getattr(self,'split',512); ns=tr.cdiv(end,split) | |
| p=torch.empty((b*8,ns,128),device=x.device,dtype=torch.float32) | |
| l=torch.empty((b*8,ns),device=x.device,dtype=torch.float32) | |
| out=torch.empty_like(q) | |
| rolling_attention[(b*4,ns)](q,cache['k'],cache['v'],self.cos,self.sin,p,l, | |
| b,cap,end,i,ns,split,num_warps=4,num_stages=getattr(self,'stages',1),enable_fp_fusion=False) | |
| _merge[(b*8,)](p,l,out,ns,128,tr.next_power_of_2(ns),128,num_warps=4) | |
| else: | |
| raw=mixed[...,:1024].view(b,1,8,128) | |
| q=torch.cat((raw[...,:96],self.rope(raw[...,96:],start)),-1) | |
| new=mixed[...,1024:].view(b,4 if i==0 else 1,4,2,32) | |
| for j in range(new.shape[1]): | |
| state=j if i==0 else i+3 | |
| cache['k'][state,:,:,start]=new[:,j,:,0] | |
| cache['v'][state,:,:,start]=new[:,j,:,1] | |
| ks=[cache['k'][j,:,:,:end].transpose(1,2) for j in range(i,i+4)] | |
| vs=[cache['v'][j,:,:,:end].transpose(1,2) for j in range(i,i+4)] | |
| ks[-1]=self.rope(ks[-1]) | |
| k,v=torch.cat(ks,-1),torch.cat(vs,-1) | |
| score=torch.einsum('bshd,bthd->bhst',q.float(),k.repeat_interleave(2,2).float())*128**-.5 | |
| out=torch.einsum('bhst,bthd->bshd',score.softmax(-1),v.repeat_interleave(2,2).float()).to(x.dtype) | |
| x=x+F.linear(out.reshape(b,1,1024),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 validate(model): | |
| checks=[] | |
| for b,t in ((2,0),(2,129),(1,513),(1,8192),(1,32768)): | |
| torch.manual_seed(17) | |
| cache=model.cache(b,t+4) | |
| for v in cache.values():v.normal_(std=.2) | |
| ref={k:v.clone() for k,v in cache.items()} | |
| ids=torch.randint(0,50304,(b,4),device='cuda') | |
| for step in range(4): | |
| model.backend='triton'; a=model.forward(ids[:,step:step+1],cache,t+step).float() | |
| model.backend='eager'; e=model.forward(ids[:,step:step+1],ref,t+step).float() | |
| error=float((a-e).norm()/e.norm()) | |
| # Synthetic 12-layer BF16 logits amplify reduction differences; | |
| # report the errors, and separately check the new attention core. | |
| assert error<.05,(model.name,b,t,step,error) | |
| # New KV in later layers inherits BF16 attention differences. | |
| # Existing history must remain bitwise unchanged. | |
| for k in cache: | |
| prefix=(slice(None),slice(None),slice(None),slice(0,t)) if model.name=='rolling' else (slice(None),slice(0,t)) | |
| torch.testing.assert_close(cache[k][prefix],ref[k][prefix],atol=0,rtol=0) | |
| checks.append(dict(batch=b,position=t+step,relative_l2=error)) | |
| model.backend='triton' | |
| if model.name=='rolling': | |
| for t in (1,129,513,8193,32769): | |
| b=2 if t<1000 else 1 | |
| cache=model.cache(b,t+3) | |
| for v in cache.values():v.normal_(std=.2) | |
| q=torch.randn(b,1,8,128,device='cuda',dtype=torch.bfloat16)*.2 | |
| for layer in (0,3,11): | |
| ns=tr.cdiv(t,512) | |
| p=torch.empty((b*8,ns,128),device='cuda',dtype=torch.float32) | |
| l=torch.empty((b*8,ns),device='cuda',dtype=torch.float32) | |
| out=torch.empty_like(q) | |
| rolling_attention[(b*4,ns)](q,cache['k'],cache['v'],model.cos,model.sin,p,l, | |
| b,t+3,t,layer,ns,512,num_warps=4,num_stages=1,enable_fp_fusion=False) | |
| _merge[(b*8,)](p,l,out,ns,128,tr.next_power_of_2(ns),128,num_warps=4) | |
| ks=[cache['k'][j,:,:,:t].transpose(1,2) for j in range(layer,layer+4)] | |
| ks[-1]=model.rope(ks[-1]) | |
| k=torch.cat(ks,-1).repeat_interleave(2,2).float() | |
| v=torch.cat([cache['v'][j,:,:,:t].transpose(1,2) for j in range(layer,layer+4)],-1).repeat_interleave(2,2).float() | |
| score=torch.einsum('bshd,bthd->bhst',q.float(),k)*128**-.5 | |
| ref=torch.einsum('bhst,bthd->bshd',score.softmax(-1),v) | |
| error=float((out.float()-ref).norm()/ref.norm()) | |
| assert error<.01,('rolling_core',t,layer,error) | |
| checks.append(dict(kind='independent_attention',length=t,layer=layer,relative_l2=error)) | |
| return checks | |
| def main(): | |
| parser=argparse.ArgumentParser() | |
| parser.add_argument('--output',default='inference/results/cache375_matched.json') | |
| parser.add_argument('--batches',type=int,nargs='+',default=[1,8,32]) | |
| parser.add_argument('--contexts',type=int,nargs='+',default=[2048,8192,32768]) | |
| parser.add_argument('--equal-cache',action='store_true') | |
| args=parser.parse_args() | |
| torch.set_num_threads(4) | |
| torch.backends.cuda.matmul.allow_tf32=False | |
| report=dict(gpu=torch.cuda.get_device_name(),torch=torch.__version__,triton=tr.__version__, | |
| weights='synthetic seed5000; exact parameter-matched training architectures; no new PPL measurement', | |
| protocol='same process/device BF16; compact static KV; fused norm/SwiGLU/append/attention; cuBLAS GEMMs; 8 growing steps; 10 interleaved warmups; 7 alternating rounds x 3 replays; synthetic history initialization and graph capture excluded; all layers and vocabulary projection included', | |
| comparison='equal persistent KV capacity' if args.equal_cache else 'equal batch', | |
| correctness={},results=[],source_sha256={}) | |
| for f in ['inference/benchmark_cache375.py','inference/compact_triton.py','inference/four_way.py','inference/kernels.py']: | |
| report['source_sha256'][f]=hashlib.sha256((ROOT/f).read_bytes()).hexdigest() | |
| path=ROOT/args.output | |
| def save():path.write_text(json.dumps(report,indent=2)+'\n') | |
| for name in ('gqa','concat','rolling'): | |
| model=BudgetModel(name) | |
| report['correctness'][name]=validate(model) | |
| print('PASS',name,flush=True);save() | |
| del model;gc.collect();torch.cuda.empty_cache() | |
| for b in args.batches: | |
| for t in args.contexts: | |
| models={n:BudgetModel(n) for n in ('gqa','concat','rolling')} | |
| graphs={}; outputs={}; caches={}; samples={n:[] for n in models} | |
| torch.manual_seed(99) | |
| if args.equal_cache:assert b%5==0 | |
| batch_sizes={n:(b if n=='gqa' or not args.equal_cache else b*8//5) for n in models} | |
| ids=torch.randint(0,50304,(max(batch_sizes.values()),8),device='cuda') | |
| for name,model in models.items(): | |
| mb=batch_sizes[name] | |
| cache=model.cache(mb,t+8);caches[name]=cache | |
| for v in cache.values():v.normal_(std=.2) | |
| def run(): | |
| for j in range(8):out=model.forward(ids[:mb,j:j+1],cache,t+j) | |
| return out | |
| for _ in range(3):eager=run() | |
| reference=eager.clone() | |
| graph=torch.cuda.CUDAGraph() | |
| with torch.cuda.graph(graph):outputs[name]=run() | |
| graphs[name]=graph | |
| graph.replay();torch.cuda.synchronize() | |
| torch.testing.assert_close(outputs[name],reference,atol=0,rtol=0) | |
| names=list(models) | |
| for rep in range(10): | |
| for n in names[::1 if rep%2==0 else -1]:graphs[n].replay() | |
| for rep in range(7): | |
| for n in names[::1 if rep%2==0 else -1]: | |
| def replay(): | |
| for _ in range(3):graphs[n].replay() | |
| samples[n].append(elapsed(replay)[1]/24) | |
| for name,model in models.items(): | |
| ms=statistics.median(samples[name]) | |
| mb=batch_sizes[name] | |
| row=dict(model=name,batch=mb,gqa_batch=b,context=t,ms=ms,tokens_s=mb*1000/ms, | |
| samples=samples[name],params=model.params,cache_elements_per_token=model.cache_elements_per_token, | |
| cache_bytes=sum(v.numel()*v.element_size() for v in caches[name].values())) | |
| report['results'].append(row);print(json.dumps(row),flush=True) | |
| save() | |
| del graphs,outputs,caches,models,cache,model,graph,eager,reference,run,replay | |
| gc.collect();torch.cuda.empty_cache() | |
| report['status']='PASS';save() | |
| if __name__=='__main__':main() | |
Xet Storage Details
- Size:
- 14.9 kB
- Xet hash:
- c4ad6d38c3edcfdd8ef13e2d54365186956f4afb8b086411ff8cc46338ac85f3
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.