xuan-luo's picture
download
raw
17.4 kB
"""Common tiled attention over compact GQA/CLA/Concat/Residual caches.
No FlashAttention dependency. Residual history is reconstructed in on-chip
tiles, preserving BF16 rounding at every recurrence. Concat combines scores
before ONE online softmax. Query-head pairs share each loaded KV tile.
"""
import torch
import triton as tr
import triton.language as tl
@tr.jit
def _norm(X,W,Y,D:tl.constexpr,BLOCK:tl.constexpr):
row=tl.program_id(0)
d=tl.arange(0,BLOCK)
x=tl.load(X+row*D+d,d<D,0).to(tl.float32)
w=tl.load(W+d,d<D,0).to(tl.float32)
y=x*tl.rsqrt(tl.sum(x*x,0)/D+1.e-6)*w
tl.store(Y+row*D+d,y,d<D)
def norm(x,w):
x=x.contiguous()
out=torch.empty_like(x)
_norm[(x.numel()//x.shape[-1],)](x,w,out,x.shape[-1],tr.next_power_of_2(x.shape[-1]),num_warps=4)
return out
@tr.jit
def _swiglu(X,Y,F:tl.constexpr,N:tl.constexpr,BLOCK:tl.constexpr):
idx=tl.program_id(0)*BLOCK+tl.arange(0,BLOCK)
row=idx//F
col=idx%F
g=tl.load(X+row*2*F+col,idx<N,0).to(tl.float32)
u=tl.load(X+row*2*F+F+col,idx<N,0).to(tl.float32)
silu=(g/(1+tl.exp(-g))).to(Y.dtype.element_ty).to(tl.float32)
tl.store(Y+idx,silu*u,idx<N)
def swiglu(x):
f=x.shape[-1]//2
out=torch.empty((*x.shape[:-1],f),device=x.device,dtype=x.dtype)
_swiglu[(tr.cdiv(out.numel(),256),)](x,out,f,out.numel(),256)
return out
@tr.jit
def _rounded_rotate(x,other,c,s,neg):
first=(x.to(tl.float32)*c.to(tl.float32)).to(x.dtype)
second=(tl.where(neg,-other,other).to(tl.float32)*s.to(tl.float32)).to(x.dtype)
return (first.to(tl.float32)+second.to(tl.float32)).to(x.dtype)
@tr.jit
def _prepare(M,KV,BASE,DELTA,Q,COS,SIN,S:tl.constexpr,N:tl.constexpr,
START,CAP:tl.constexpr,MS:tl.constexpr,
KIND:tl.constexpr,ANCHOR:tl.constexpr,D:tl.constexpr,
RD:tl.constexpr,A:tl.constexpr,R:tl.constexpr,BD:tl.constexpr,BT:tl.constexpr,WIDE:tl.constexpr=False):
t=tl.program_id(0)*BT+tl.arange(0,BT)
h=tl.program_id(1)
g=h//2
b=t//S
if WIDE:
b=b.to(tl.int64)
pos=START+t%S
d=tl.arange(0,BD)
if KIND==0:
qo=g*4*D+(h%2)*D
else:
qo=h*D
x=tl.load(M+t[:,None]*MS+qo+d[None,:],(t[:,None]<N)&(d[None,:]<D),0)
if KIND==2:
# Alpha lanes do not rotate. Keep their speculative RoPE loads valid
# even when R is not a power of two (signed remainder can be negative).
rd=tl.maximum(d-A,0)
partner=A+(rd+R//2)%R
else:
partner=(d+D//2)%D
rd=d
other=tl.load(M+t[:,None]*MS+qo+partner[None,:],(t[:,None]<N)&(d[None,:]<D),0)
c=tl.load(COS+pos[:,None]*RD+rd[None,:],(t[:,None]<N)&(rd[None,:]<RD),0).to(x.dtype)
s=tl.load(SIN+pos[:,None]*RD+rd[None,:],(t[:,None]<N)&(rd[None,:]<RD),0).to(x.dtype)
rotated=_rounded_rotate(x,other,c,s,rd[None,:]<RD//2)
if KIND==2:
rotated=tl.where(d[None,:]<A,x,rotated)
tl.store(Q+(t[:,None]*8+h)*D+d[None,:],rotated,(t[:,None]<N)&(d[None,:]<D))
if h%2==0:
if KIND==0:
ko=g*4*D+2*D
kp=M
stride=MS
width=D
elif KIND==1:
ko=g*2*D
kp=KV
stride=8*D
width=D
elif KIND==2:
ko=8*D+g*2*R
kp=M
stride=MS
width=R
else:
if ANCHOR:
width=D
else:
width=R
ko=8*D+g*2*width
kp=M
stride=MS
if KIND!=1 or ANCHOR:
k=tl.load(kp+t[:,None]*stride+ko+d[None,:],(t[:,None]<N)&(d[None,:]<width),0)
v=tl.load(kp+t[:,None]*stride+ko+width+d[None,:],(t[:,None]<N)&(d[None,:]<width),0)
if KIND!=3:
kd=(d+width//2)%width
otherk=tl.load(kp+t[:,None]*stride+ko+kd[None,:],(t[:,None]<N)&(d[None,:]<width),0)
ck=tl.load(COS+pos[:,None]*RD+d[None,:],(t[:,None]<N)&(d[None,:]<width),0).to(k.dtype)
sk=tl.load(SIN+pos[:,None]*RD+d[None,:],(t[:,None]<N)&(d[None,:]<width),0).to(k.dtype)
k=_rounded_rotate(k,otherk,ck,sk,d[None,:]<width//2)
if KIND==2 or (KIND==3 and not ANCHOR):
dest=DELTA
else:
dest=BASE
out=((b[:,None]*CAP+pos[:,None])*4+g)*2*width+d[None,:]
tl.store(dest+out,k,(t[:,None]<N)&(d[None,:]<width))
tl.store(dest+out+width,v,(t[:,None]<N)&(d[None,:]<width))
if KIND==2 and ANCHOR:
bo=8*D+8*R+g*2*A
k=tl.load(M+t[:,None]*MS+bo+d[None,:],(t[:,None]<N)&(d[None,:]<A),0)
v=tl.load(M+t[:,None]*MS+bo+A+d[None,:],(t[:,None]<N)&(d[None,:]<A),0)
out=((b[:,None]*CAP+pos[:,None])*4+g)*2*A+d[None,:]
tl.store(BASE+out,k,(t[:,None]<N)&(d[None,:]<A))
tl.store(BASE+out+A,v,(t[:,None]<N)&(d[None,:]<A))
def prepare(mixed,kv,cache,name,layer,start,cos,sin,dim):
b,s,ms=mixed.shape
anchor=layer if name=='gqa' else layer//4*4
base=cache['base',anchor]
delta=cache.get(('delta',layer),base)
q=torch.empty((b,s,8,dim),device=mixed.device,dtype=mixed.dtype)
bt=1 if s==1 else 8
_prepare[(tr.cdiv(b*s,bt),8)](mixed,kv if kv is not None else mixed,base,delta,q,cos,sin,
s,b*s,start,base.shape[1],ms,dict(gqa=0,cla=1,concat=2,residual=3)[name],layer==anchor,
dim,delta.shape[-1] if name=='concat' else dim,base.shape[-1],delta.shape[-1],
tr.next_power_of_2(dim),bt,base.numel()>=2**31 or delta.numel()>=2**31,
num_warps=4,enable_fp_fusion=False)
return q
@tr.jit
def _attention(Q, BASE, DELTA, D1, D2, D3, U1, U2, U3, COS, SIN, PART, LSE,
S:tl.constexpr, START, END, CAP:tl.constexpr,
KIND:tl.constexpr, DEPTH:tl.constexpr, D:tl.constexpr, A:tl.constexpr, R:tl.constexpr,
NS:tl.constexpr, SPLIT:tl.constexpr, BM:tl.constexpr, BN:tl.constexpr,
BD:tl.constexpr, BA:tl.constexpr, BR:tl.constexpr,WIDE:tl.constexpr=False):
bg=tl.program_id(0)
qb=tl.program_id(1)
sp=tl.program_id(2)
b=bg//4
if WIDE:
b=b.to(tl.int64)
h=bg%4
m=tl.arange(0,BM)
qi=qb*(BM//2)+m//2
qh=h*2+m%2
d=tl.arange(0,BD)
a=tl.arange(0,BA)
r=tl.arange(0,BR)
q=tl.load(Q+((b*S+qi[:,None])*8+qh[:,None])*D+d[None,:],
(qi[:,None]<S)&(d[None,:]<D),0)
if KIND==1:
qa=tl.load(Q+((b*S+qi[:,None])*8+qh[:,None])*D+a[None,:],
(qi[:,None]<S)&(a[None,:]<A),0)
qr=tl.load(Q+((b*S+qi[:,None])*8+qh[:,None])*D+A+r[None,:],(qi[:,None]<S)&(r[None,:]<R),0)
acca=tl.full((BM,BA),0,tl.float32)
accr=tl.full((BM,BR),0,tl.float32)
else:
acc=tl.full((BM,BD),0,tl.float32)
maximum=tl.full((BM,),-1.e30,tl.float32)
denom=tl.full((BM,),0,tl.float32)
upper=tl.minimum(tl.minimum((sp+1)*SPLIT,END),START+(qb+1)*(BM//2))
for off in range(sp*SPLIT,upper,BN):
t=off+tl.arange(0,BN)
if KIND==1:
ka=tl.load(BASE+((b*CAP+t[:,None])*4+h)*2*A+a[None,:],
(t[:,None]<END)&(a[None,:]<A),0)
va=tl.load(BASE+((b*CAP+t[:,None])*4+h)*2*A+A+a[None,:],
(t[:,None]<END)&(a[None,:]<A),0)
kd=tl.load(DELTA+((b*CAP+t[:,None])*4+h)*2*R+r[None,:],(t[:,None]<END)&(r[None,:]<R),0)
vd=tl.load(DELTA+((b*CAP+t[:,None])*4+h)*2*R+R+r[None,:],(t[:,None]<END)&(r[None,:]<R),0)
score=tl.dot(qa,tl.trans(ka))+tl.dot(qr,tl.trans(kd))
else:
if KIND==3:
# Combine compact buffers on chip, not in an HBM temporary.
ap=BASE+((b*CAP+t[:,None])*4+h)*2*A+d[None,:]
rp=DELTA+((b*CAP+t[:,None])*4+h)*2*R+d[None,:]-A
k=tl.load(tl.where(d[None,:]<A,ap,rp),(t[:,None]<END)&(d[None,:]<D),0)
v=tl.load(tl.where(d[None,:]<A,ap+A,rp+R),(t[:,None]<END)&(d[None,:]<D),0)
else:
k=tl.load(BASE+((b*CAP+t[:,None])*4+h)*2*D+d[None,:],
(t[:,None]<END)&(d[None,:]<D),0)
v=tl.load(BASE+((b*CAP+t[:,None])*4+h)*2*D+D+d[None,:],
(t[:,None]<END)&(d[None,:]<D),0)
if KIND==2:
# Keep the recurrence as a loop: static unrolling hoists all
# up-projection matrices and causes large register spills.
for depth in range(DEPTH):
if depth==0:
dp=D1
up=U1
elif depth==1:
dp=D2
up=U2
else:
dp=D3
up=U3
dk=tl.load(dp+((b*CAP+t[:,None])*4+h)*2*R+r[None,:],(t[:,None]<END)&(r[None,:]<R),0)
dv=tl.load(dp+((b*CAP+t[:,None])*4+h)*2*R+R+r[None,:],(t[:,None]<END)&(r[None,:]<R),0)
uk=tl.load(up+(h*2*D+d[None,:])*R+r[:,None],(d[None,:]<D)&(r[:,None]<R),0)
uv=tl.load(up+((h*2+1)*D+d[None,:])*R+r[:,None],(d[None,:]<D)&(r[:,None]<R),0)
updatek=tl.dot(dk,uk).to(k.dtype)
updatev=tl.dot(dv,uv).to(v.dtype)
k=(k.to(tl.float32)+updatek.to(tl.float32)).to(k.dtype)
v=(v.to(tl.float32)+updatev.to(tl.float32)).to(v.dtype)
# Rotate after recurrence. Gather partner lanes from SRAM.
partner=(d+D//2)%D
other=tl.gather(k,tl.broadcast_to(partner[None,:],(BN,BD)),1)
c=tl.load(COS+t[:,None]*D+d[None,:],(t[:,None]<END)&(d[None,:]<D),0).to(k.dtype)
s=tl.load(SIN+t[:,None]*D+d[None,:],(t[:,None]<END)&(d[None,:]<D),0).to(k.dtype)
first=(k.to(tl.float32)*c.to(tl.float32)).to(k.dtype)
second=(tl.where(d[None,:]<D//2,-other,other).to(tl.float32)*s.to(tl.float32)).to(k.dtype)
k=(first.to(tl.float32)+second.to(tl.float32)).to(k.dtype)
score=tl.dot(q,tl.trans(k))
score=score*(D**-0.5)
score=tl.where((qi[:,None]<S)&(t[None,:]<END)&(t[None,:]<=START+qi[:,None]),score,-1.e30)
nm=tl.maximum(maximum,tl.max(score,1))
alpha=tl.exp(maximum-nm)
p=tl.exp(score-nm[:,None])
p=tl.where((qi[:,None]<S)&(t[None,:]<END)&(t[None,:]<=START+qi[:,None]),p,0.)
if KIND==1:
acca=acca*alpha[:,None]+tl.dot(p.to(va.dtype),va)
accr=accr*alpha[:,None]+tl.dot(p.to(vd.dtype),vd)
else:
acc=acc*alpha[:,None]+tl.dot(p.to(v.dtype),v)
denom=denom*alpha+tl.sum(p,1)
maximum=nm
offset=(((b*S+qi)*8+qh)*NS+sp)*D
if KIND==1:
tl.store(PART+offset[:,None]+a[None,:],acca/tl.maximum(denom[:,None],1.e-30),(qi[:,None]<S)&(a[None,:]<A))
tl.store(PART+offset[:,None]+A+r[None,:],accr/tl.maximum(denom[:,None],1.e-30),(qi[:,None]<S)&(r[None,:]<R))
else:
tl.store(PART+offset[:,None]+d[None,:],acc/tl.maximum(denom[:,None],1.e-30),(qi[:,None]<S)&(d[None,:]<D))
tl.store(LSE+((b*S+qi)*8+qh)*NS+sp,tl.where(denom>0,maximum+tl.log(denom),-float('inf')),qi<S)
@tr.jit
def _decode_pair(Q,BASE,DELTA,PART,LSE,END,CAP:tl.constexpr,D:tl.constexpr,
A:tl.constexpr,R:tl.constexpr,CONCAT:tl.constexpr,
NS:tl.constexpr,BS:tl.constexpr,BD:tl.constexpr,WIDE:tl.constexpr=False):
"""One compact history load for two queries; no 16-row Tensor Core padding."""
bg=tl.program_id(0)
sp=tl.program_id(1)
b=bg//4
if WIDE:
b=b.to(tl.int64)
h=bg%4
d=tl.arange(0,BD)
t=sp*BS+tl.arange(0,BS)
q0=tl.load(Q+(b*8+h*2)*D+d,d<D,0).to(tl.float32)
q1=tl.load(Q+(b*8+h*2+1)*D+d,d<D,0).to(tl.float32)
if CONCAT:
ap=BASE+((b*CAP+t[:,None])*4+h)*2*A+d[None,:]
rp=DELTA+((b*CAP+t[:,None])*4+h)*2*R+d[None,:]-A
k=tl.load(tl.where(d[None,:]<A,ap,rp),(t[:,None]<END)&(d[None,:]<D),0).to(tl.float32)
else:
k=tl.load(BASE+((b*CAP+t[:,None])*4+h)*2*D+d[None,:],
(t[:,None]<END)&(d[None,:]<D),0).to(tl.float32)
s0=tl.where(t<END,tl.sum(k*q0[None,:],1)*(D**-0.5),-1.e30)
s1=tl.where(t<END,tl.sum(k*q1[None,:],1)*(D**-0.5),-1.e30)
m0=tl.max(s0,0)
m1=tl.max(s1,0)
p0=tl.where(t<END,tl.exp(s0-m0),0.)
p1=tl.where(t<END,tl.exp(s1-m1),0.)
z0=tl.sum(p0,0)
z1=tl.sum(p1,0)
if CONCAT:
v=tl.load(tl.where(d[None,:]<A,ap+A,rp+R),(t[:,None]<END)&(d[None,:]<D),0)
else:
v=tl.load(BASE+((b*CAP+t[:,None])*4+h)*2*D+D+d[None,:],
(t[:,None]<END)&(d[None,:]<D),0)
o0=tl.sum(p0.to(v.dtype).to(tl.float32)[:,None]*v.to(tl.float32),0)/tl.maximum(z0,1.e-30)
o1=tl.sum(p1.to(v.dtype).to(tl.float32)[:,None]*v.to(tl.float32),0)/tl.maximum(z1,1.e-30)
i0=(b*8+h*2)*NS+sp
i1=(b*8+h*2+1)*NS+sp
tl.store(PART+i0*D+d,o0,d<D)
tl.store(PART+i1*D+d,o1,d<D)
tl.store(LSE+i0,tl.where(z0>0,m0+tl.log(z0),-float('inf')))
tl.store(LSE+i1,tl.where(z1>0,m1+tl.log(z1),-float('inf')))
def attention(q, cache, name, layer, start, cos, sin, weight,
prefill_bm=64,prefill_bn=None,decode_bn=None,decode_split=None,
warps=None,inspect_resources=False,concat_mode='auto',decode_mode='auto',num_stages=None):
from inference.kernels import _merge
q=q.contiguous()
b,s,heads,d=q.shape
anchor=layer if name=='gqa' else layer//4*4
base=cache['base',anchor]
automatic=(num_stages is None and decode_bn is None and decode_split is None
and warps is None and concat_mode=='auto' and decode_mode=='auto')
if num_stages is None:
num_stages=1
# Paired full-model measurements on A100: only enable in tested shapes.
# Explicit num_stages=1 retains the previous dispatch for controlled baselines.
if automatic and s==1 and b==8:
if name=='concat' and d==80 and base.shape[-1]==64 and start+1>=8192:
num_stages=2
elif name=='gqa' and d==64 and start+1>=32768:
num_stages=2
decode_bn,decode_split=128,1024
if concat_mode=='auto':
# Decode benefits from one score/PV operation; for prefill avoid
# doubling Tensor Core width when the two components pad more cheaply.
alpha_width=base.shape[-1]
rank_width=cache.get(('delta',layer),base).shape[-1]
cheap_fusion=tr.next_power_of_2(d)<=tr.next_power_of_2(alpha_width)+max(16,tr.next_power_of_2(rank_width))
concat_mode='fused' if d<=128 and (s==1 or cheap_fusion) else 'split'
if decode_mode=='auto':
decode_mode='pair' if b==1 and start+s<=4096 and d<=128 and name in ('gqa','cla','concat') else 'mma'
if prefill_bn is None:
prefill_bn=128 if name=='concat' and d<=128 and concat_mode=='split' else 64
if decode_bn is None:
decode_bn=64 if d<=128 and name in ('gqa','cla','concat') else 32
kind={'gqa':0,'cla':0,'concat':1,'residual':2}[name]
if name=='concat' and concat_mode=='fused':
kind=3
depth=layer-anchor if name=='residual' else 0
# Reconstruction carries more live matrices. Eight warps avoid the severe
# register spills observed at depth 2 with four warps (see tuning JSON).
if warps is None:
warps=8 if kind==2 and depth>0 else 4
if decode_split is None:
decode_split=128 if decode_mode=='pair' else 256 if kind==2 and depth>0 else 512
delta=cache.get(('delta',layer),base)
ds=[cache['delta',anchor+j] if j<=depth else base for j in range(1,4)]
us=[weight(anchor+j,'self_attention.delta_up_weight') if j<=depth else base for j in range(1,4)]
end=start+s
split=decode_split if s==1 else tr.next_power_of_2(end)
ns=tr.cdiv(end,split)
# Prefill has a single partition, so write its result directly in BF16.
part=torch.empty((b,s,8,ns,d),device=q.device,dtype=torch.float32 if ns>1 else q.dtype)
lse=torch.empty((b,s,8,ns),device=q.device,dtype=torch.float32)
bm=16 if s==1 else prefill_bm
bn=decode_bn if s==1 else prefill_bn
if kind==2 and s>1:
# Generic residual oracle path; production prefill uses transient
# dense states, whose common attention tile is 64x64.
bm,bn=32,16
rank=delta.shape[-1] if name=='concat' or depth>0 else 32
if s==1 and name in ('gqa','cla','concat') and decode_mode=='pair':
kernel=_decode_pair[(b*4,ns)](q,base,delta,part,lse,end,base.shape[1],d,
base.shape[-1],rank,name=='concat',ns,split,tr.next_power_of_2(d),
base.numel()>=2**31 or delta.numel()>=2**31,
num_warps=warps,enable_fp_fusion=False)
else:
kernel=_attention[(b*4,tr.cdiv(s,bm//2),ns)](q,base,delta,*ds,*us,cos,sin,part,lse,
s,start,end,base.shape[1],kind,depth,d,base.shape[-1],
rank,ns,split,bm,bn,
tr.next_power_of_2(d),tr.next_power_of_2(base.shape[-1]),max(16,tr.next_power_of_2(rank)),
base.numel()>=2**31 or delta.numel()>=2**31,num_warps=warps,
num_stages=num_stages,enable_fp_fusion=False)
if ns==1:
return part.squeeze(-2)
out=torch.empty_like(q)
_merge[(b*s*8,)](part,lse,out,ns,d,tr.next_power_of_2(ns),tr.next_power_of_2(d),num_warps=4)
if inspect_resources:
return out,dict(regs=kernel.n_regs,spills=kernel.n_spills,shared=kernel.metadata.shared)
return out

Xet Storage Details

Size:
17.4 kB
·
Xet hash:
55fd67bee1e92e3d30d4332cd1f2ae67ac39cde19648e3f515f796fcfda5824f

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