"""G14: single-head scaled dot-product attention, not a trained transformer."""importmathdefsoftmax(scores,allowed=None):s=list(scores)mask=[True]*len(s)ifallowedisNoneelselist(allowed)ifnotsorlen(mask)!=len(s)orany(type(x)isnotboolforxinmask)ornotany(mask):raiseValueError("nonempty row with at least one allowed position required")ifany(notmath.isfinite(x)forxins):raiseValueError("finite pre-mask scores required")top=max(vforv,okinzip(s,mask)ifok)e=[math.exp(v-top)ifokelse0.forv,okinzip(s,mask)]total=math.fsum(e)return[v/totalforvine]defattention(Q,K,V,causal=False):n,m=len(Q),len(K)d=len(Q[0])ifnelse0dv=len(V[0])ifVelse0if(type(causal)isnotboolornot1<=n<=256ornot1<=m<=256ornot1<=d<=128ornot1<=dv<=128orlen(V)!=m):raiseValueError("bounded nonempty matching matrices required")ifcausalandn!=m:raiseValueError("this causal lab requires equal query/key lengths")formatrix,widthin((Q,d),(K,d),(V,dv)):ifany(len(row)!=widthorany(notmath.isfinite(x)forxinrow)forrowinmatrix):raiseValueError("ragged or nonfinite matrix")out,weights=[],[]fori,qinenumerate(Q):scores=[math.fsum(a*bfora,binzip(q,k))/math.sqrt(d)forkinK]p=softmax(scores,[j<=iforjinrange(m)]ifcausalelseNone)weights.append(p)out.append([math.fsum(p[j]*V[j][v]forjinrange(m))forvinrange(dv)])returnout,weightsif__name__=="__main__":print(attention([[0.],[0.]],[[1.],[2.]],[[2.],[8.]],causal=True))