;
`,f=b=>`
${b.registerUniform("reduceSize","u32").declareVariables(p,d)}
${_}
fn DIV_CEIL(a : u32, b : u32) -> u32 {
return ((a - 1u) / b + 1u);
}
${b.mainStart(u)}
let outputIndex = global_idx / ${u};
let offset = outputIndex * uniforms.reduceSize;
var bestValue = f32(${xp[s]});
let Length = uniforms.reduceSize;
for (var k = local_idx; k < Length; k = k + ${u}) {
let candidate = f32(${p.getByOffset("offset + k")});
bestValue = ${yp[s]};
}
aBestValues[local_idx] = bestValue;
workgroupBarrier();
var reduceSize = min(Length, ${u}u);
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
currentSize = reduceSize / 2u) {
let interval = DIV_CEIL(reduceSize, 2u);
if (local_idx < currentSize) {
let candidate = aBestValues[local_idx + interval];
bestValue = ${vp[s]};
aBestValues[local_idx] = bestValue;
}
reduceSize = interval;
workgroupBarrier();
}
if (local_idx == 0u) {
${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${Tp[s]})`}`)};
}
}`;return{name:e,shaderCache:{hint:`${r};${u}`,inputDependencies:["type"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:c}]})}},vs=(e,r,t,s)=>{let o=e.inputs.length===1?t:_l(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((_,f)=>f));let a=Pe.normalizeAxes(n,e.inputs[0].dims.length),i=a,l=e.inputs[0],c=$p(i,e.inputs[0].dims.length);c.length>0&&(l=e.compute(rs(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],i=Ep(i.length,l.dims.length));let[p,d]=Pp(l.dims,i),u=p;o.keepDims&&(u=Cp(p,a)),e.compute(Ap(r,o.cacheKey,[l],s,e.inputs[0].dataType,u,d),{inputs:[l]})},kp=(e,r)=>{vs(e,"ReduceMeanShared",r,"mean")},Ip=(e,r)=>{vs(e,"ReduceL1Shared",r,"l1")},Fp=(e,r)=>{vs(e,"ReduceL2Shared",r,"l2")},Op=(e,r)=>{vs(e,"ReduceLogSumExpShared",r,"logSumExp")},Dp=(e,r)=>{vs(e,"ReduceMaxShared",r,"max")},Lp=(e,r)=>{vs(e,"ReduceMinShared",r,"min")},zp=(e,r)=>{vs(e,"ReduceProdShared",r,"prod")},Rp=(e,r)=>{vs(e,"ReduceSumShared",r,"sum")},Bp=(e,r)=>{vs(e,"ReduceSumSquareShared",r,"sumSquare")},Np=(e,r)=>{vs(e,"ReduceLogSumShared",r,"logSum")}}),xs,jp,ha,_l,Ts,Vp,Up,Wp,Gp,Hp,Kp,qp,Qp,Xp,Jp,Es,Yp,Zp,eh,th,rh,sh,nh,oh,ah,ih,gl=Ue(()=>{Mt(),Pt(),ur(),Ct(),qx(),xs=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},jp=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ha=(e,r,t,s,o,n,a=!1,i=!1)=>{let l=[],c=t[0].dims,p=c.length,d=Pe.normalizeAxes(o,p),u=!i&&d.length===0;c.forEach((b,A)=>{u||d.indexOf(A)>=0?a&&l.push(1):l.push(b)});let _=l.length,f=Pe.size(l);return{name:e,shaderCache:r,getShaderSource:b=>{let A=[],g=Oe("_A",t[0].dataType,p),y=at("output",n,_),C=s(g,y,d),x=C[2];for(let M=0,T=0;M=0?(a&&T++,x=`for(var j${M}: u32 = 0; j${M} < ${c[M]}; j${M}++) {
${C[2].includes("last_index")?`let last_index = j${M};`:""}
${g.indicesSet("input_indices",M,`j${M}`)}
${x}
}`):(A.push(`${g.indicesSet("input_indices",M,y.indicesGet("output_indices",T))};`),T++);return`
${b.registerUniform("output_size","u32").declareVariables(g,y)}
${b.mainStart()}
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
var input_indices: ${g.type.indices};
let output_indices = ${y.offsetToIndices("global_idx")};
${A.join(`
`)}
${C[0]} // init ops for reduce max/min
${C[1]}
${x}
${C[3]}
${C.length===4?y.setByOffset("global_idx","value"):C.slice(4).join(`
`)}
}`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...lt(c,l)]})}},_l=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),jt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},Ts=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:_l(o,t);e.compute(ha(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?jp:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},Vp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Up=(e,r)=>{xs(e.inputs),Ts(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Wp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Gp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},Hp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let a=0;a=0||o.length===0)&&n.push(t.indicesSet("input_indices",a,0));return[`${n.join(`
`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Kp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let a=0;a=0||o.length===0)&&(n*=e.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},qp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let a=0;a=0||o.length===0)&&n.push(`input_indices[${a}] = 0;`);return[`${n.join(`
`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Qp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},Xp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Jp=(e,r)=>{xs(e.inputs),Ts(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},Es=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},Yp=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Kp(e,r):kp(e,r)},Zp=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Up(e,r):Ip(e,r)},eh=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Wp(e,r):Fp(e,r)},th=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Gp(e,r):Op(e,r)},rh=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Hp(e,r):Dp(e,r)},sh=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?qp(e,r):Lp(e,r)},nh=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Qp(e,r):zp(e,r)},oh=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Xp(e,r):Rp(e,r)},ah=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Jp(e,r):Bp(e,r)},ih=(e,r)=>{Es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Vp(e,r):Np(e,r)}}),wl,lh,uh,Ml,Qx=Ue(()=>{Mt(),ur(),gl(),wl=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},lh=(e,r)=>{wl(e.inputs);let t=(s,o,n)=>{let a=[];for(let i=0;i=0||n.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(`
`)}`,`var value = ${s.getByIndices("input_indices")};
var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) {
value = ${s.getByIndices("input_indices")};
best_index = i32(last_index);
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(ha("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},uh=(e,r)=>{wl(e.inputs);let t=(s,o,n)=>{let a=[];for(let i=0;i=0||n.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(`
`)}`,`var value = ${s.getByIndices("input_indices")};
var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) {
value = ${s.getByIndices("input_indices")};
best_index = i32(last_index);
}`,"",o.setByOffset("global_idx","best_index")]};e.compute(ha("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Ml=e=>jt(e)}),ch,ma,dh,ph,hh,wo,mh,fh,bl=Ue(()=>{Mt(),Pt(),ul(),Ct(),ch=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],a=e[4],i=e[5];if(a&&i)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],c=t.dims[1],p=t.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=o.dims[0]/3,u=d,_=u;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let C of r.qkvHiddenSizes)if(C%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],u=r.qkvHiddenSizes[1],_=r.qkvHiddenSizes[2]}let f=c;if(d!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==d+u+_)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let b=0;if(a){if(u!==_)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==u/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(b=a.dims[3])}let A=f+b,g=-1,y=0;if(n)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(i){if(i.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(i.dims[0]!==l||i.dims[1]!==r.numHeads||i.dims[2]!==c||i.dims[3]!==A)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:c,pastSequenceLength:b,kvSequenceLength:f,totalSequenceLength:A,maxSequenceLength:g,inputHiddenSize:p,hiddenSize:d,vHiddenSize:_,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(_/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ma=(e,r,t)=>r&&e?`
let total_sequence_length_input = u32(${r.getByOffset("0")});
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;
total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1;
var past_sequence_length: u32 = 0;
if (is_first_prompt == false) {
past_sequence_length = total_sequence_length - sequence_length;
}
`:`
${t?"let past_sequence_length = uniforms.past_sequence_length":""};
let present_sequence_length = total_sequence_length;
`,dh=(e,r,t,s,o,n,a,i)=>{let l=or(a?1:n),c=64,p=n/l;p{let y=at("x",e.dataType,e.dims,l),C=[y],x=a?Oe("seq_lens",a.dataType,a.dims):void 0;x&&C.push(x);let M=i?Oe("total_sequence_length_input",i.dataType,i.dims):void 0;M&&C.push(M);let T=jr(e.dataType),v=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`
var thread_max: array;
var thread_sum: array;
${g.registerUniforms(v).declareVariables(...C)}
${g.mainStart([c,1,1])}
let batchIdx = workgroup_id.z / uniforms.num_heads;
let headIdx = workgroup_id.z % uniforms.num_heads;
let sequence_length = uniforms.sequence_length;
var total_sequence_length = uniforms.total_sequence_length;
${ma(x,M,!1)}
let local_offset = local_idx * uniforms.elements_per_thread;
let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset;
let seq_causal_length = ${a?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};
var thread_max_vector = ${f}(-3.402823e+38f);
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
thread_max_vector = max(${f}(x[offset + i]), thread_max_vector);
}
thread_max[local_idx] = ${(()=>{switch(l){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${l}`)}})()};
workgroupBarrier();
var max_value = f32(-3.402823e+38f);
for (var i = 0u; i < ${c}; i++) {
max_value = max(thread_max[i], max_value);
}
var sum_vector = ${f}(0);
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
sum_vector += exp(${f}(x[offset + i]) - max_value);
}
thread_sum[local_idx] = ${(()=>{switch(l){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${l}`)}})()};
workgroupBarrier();
var sum: f32 = 0;
for (var i = 0u; i < ${c}; i++) {
sum += thread_sum[i];
}
if (sum == 0) {
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
x[offset + i] = ${y.type.value}(${T}(1.0) / ${T}(seq_causal_length));
}
} else {
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
var f32input = ${f}(x[offset + i]);
x[offset + i] = ${y.type.value}(exp(f32input - max_value) / sum);
}
}
${a?`
for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
x[offset + total_seq_id] = ${y.type.value}(${T}(0));
}`:""};
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${_};${l}`,inputDependencies:b},getShaderSource:A,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:u})}},ph=(e,r,t,s,o,n,a,i,l)=>{let c=a+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,c],d=e>1&&s,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,_=d?[n.batchSize,u,c,n.headSize]:void 0,f=n.nReps?n.nReps:1,b=n.scale===0?1/Math.sqrt(n.headSize):n.scale,A=or(n.headSize),g=n.headSize/A,y=12,C={x:Math.ceil(c/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},x=[{type:12,data:n.sequenceLength},{type:12,data:g},{type:12,data:c},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:b},{type:12,data:a},{type:12,data:n.kvSequenceLength},{type:12,data:f}],M=d&&s&&Pe.size(s.dims)>0,T=["type","type"];M&&T.push("type"),o&&T.push("type"),i&&T.push("type"),l&&T.push("type");let v=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&v.push({dims:_,dataType:r.dataType,gpuDataType:0});let P=F=>{let D=Oe("q",r.dataType,r.dims,A),K=Oe("key",t.dataType,t.dims,A),U=[D,K];if(M){let he=Oe("past_key",s.dataType,s.dims,A);U.push(he)}o&&U.push(Oe("attention_bias",o.dataType,o.dims));let j=i?Oe("seq_lens",i.dataType,i.dims):void 0;j&&U.push(j);let ne=l?Oe("total_sequence_length_input",l.dataType,l.dims):void 0;ne&&U.push(ne);let q=at("output",r.dataType,p),te=[q];d&&te.push(at("present_key",r.dataType,_,A));let Z=jr(1,A),ae=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
const TILE_SIZE = ${y}u;
var tileQ: array<${D.type.storage}, ${y*y}>;
var tileK: array<${D.type.storage}, ${y*y}>;
${F.registerUniforms(ae).declareVariables(...U,...te)}
${F.mainStart([y,y,1])}
// x holds the N and y holds the M
let headIdx = workgroup_id.z % uniforms.num_heads;
let kvHeadIdx = ${f===1?"headIdx":"headIdx / uniforms.n_reps"};
let kv_num_heads = ${f===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
let batchIdx = workgroup_id.z / uniforms.num_heads;
let m = workgroup_id.y * TILE_SIZE;
let n = workgroup_id.x * TILE_SIZE;
let sequence_length = uniforms.M;
var total_sequence_length = uniforms.N;
${ma(j,ne,!0)}
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
${M&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};
let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;
${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}
var value = ${Z}(0);
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {
tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];
}
if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {
var idx = TILE_SIZE * local_id.y + local_id.x;
${M&&d?`
if (n + local_id.y < past_sequence_length) {
tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
} else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];
}`:`
if (n + local_id.y < uniforms.kv_sequence_length) {
tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
}`}
${d?`if (n + local_id.y < present_sequence_length) {
present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];
}`:""}
}
workgroupBarrier();
for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {
value += ${Z}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);
}
workgroupBarrier();
}
if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {
let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
var sum: f32 = ${(()=>{switch(A){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${A}`)}})()};
output[outputIdx] = ${q.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"};
}
}`};return{name:"AttentionProbs",shaderCache:{hint:`${A};${o!==void 0};${s!==void 0};${e}`,inputDependencies:T},getRunData:()=>({outputs:v,dispatchGroup:C,programUniforms:x}),getShaderSource:P}},hh=(e,r,t,s,o,n,a=void 0,i=void 0)=>{let l=n+o.kvSequenceLength,c=o.nReps?o.nReps:1,p=o.vHiddenSize*c,d=e>1&&s,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=d?[o.batchSize,u,l,o.headSize]:void 0,f=[o.batchSize,o.sequenceLength,p],b=12,A={x:Math.ceil(o.vHeadSize/b),y:Math.ceil(o.sequenceLength/b),z:o.batchSize*o.numHeads},g=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:c}],y=d&&s&&Pe.size(s.dims)>0,C=["type","type"];y&&C.push("type"),a&&C.push("type"),i&&C.push("type");let x=[{dims:f,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:_,dataType:r.dataType,gpuDataType:0});let M=T=>{let v=Oe("probs",r.dataType,r.dims),P=Oe("v",t.dataType,t.dims),F=[v,P];y&&F.push(Oe("past_value",s.dataType,s.dims));let D=a?Oe("seq_lens",a.dataType,a.dims):void 0;a&&F.push(D);let K=i?Oe("total_sequence_length_input",i.dataType,i.dims):void 0;i&&F.push(K);let U=[at("output",r.dataType,f)];d&&U.push(at("present_value",r.dataType,_));let j=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
const TILE_SIZE = ${b}u;
var tileQ: array<${v.type.value}, ${b*b}>;
var tileV: array<${v.type.value}, ${b*b}>;
${T.registerUniforms(j).declareVariables(...F,...U)}
${T.mainStart([b,b,1])}
let headIdx = workgroup_id.z % uniforms.num_heads;
let batchIdx = workgroup_id.z / uniforms.num_heads;
let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"};
let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
let m = global_id.y;
let n = global_id.x;
let sequence_length = uniforms.M;
var total_sequence_length = uniforms.K;
${ma(D,K,!0)}
let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
${y&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};
let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;
${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}
var value = ${v.type.storage}(0);
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
if (m < uniforms.M && w + local_id.x < uniforms.K) {
tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];
}
if (n < uniforms.N && w + local_id.y < uniforms.K) {
var idx = TILE_SIZE * local_id.y + local_id.x;
${y&&d?`
if (w + local_id.y < past_sequence_length) {
tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];
} else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];
}
`:`
if (w + local_id.y < uniforms.kv_sequence_length) {
tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];
}`}
${d?`
if (w + local_id.y < present_sequence_length) {
present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];
}`:""}
}
workgroupBarrier();
for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {
value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];
}
workgroupBarrier();
}
// we need to transpose output from BNSH_v to BSND_v
if (m < uniforms.M && n < uniforms.N) {
let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size
+ headIdx * uniforms.N + n;
output[outputIdx] = value;
}
}`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:C},getRunData:()=>({outputs:x,dispatchGroup:A,programUniforms:g}),getShaderSource:M}},wo=(e,r,t,s,o,n,a,i,l,c,p=void 0,d=void 0)=>{let u=Math.min(e.outputCount,1+(a?1:0)+(i?1:0)),_=u>1?c.pastSequenceLength:0,f=_+c.kvSequenceLength,b=l&&Pe.size(l.dims)>0?l:void 0,A=[r,t];u>1&&a&&Pe.size(a.dims)>0&&A.push(a),b&&A.push(b),p&&A.push(p),d&&A.push(d);let g=e.compute(ph(u,r,t,a,b,c,_,p,d),{inputs:A,outputs:u>1?[-1,1]:[-1]})[0];e.compute(dh(g,c.batchSize,c.numHeads,_,c.sequenceLength,f,p,d),{inputs:p&&d?[g,p,d]:[g],outputs:[]});let y=[g,s];u>1&&i&&Pe.size(i.dims)>0&&y.push(i),p&&y.push(p),d&&y.push(d),e.compute(hh(u,g,s,i,c,_,p,d),{inputs:y,outputs:u>1?[0,2]:[0]})},mh=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,a=12,i={x:Math.ceil(r.headSize/a),y:Math.ceil(r.sequenceLength/a),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:s},{type:12,data:o},{type:12,data:n},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=d=>{let u=at("output_q",l[0].dataType,t),_=at("output_k",l[0].dataType,t),f=at("output_v",l[0].dataType,t),b=Oe("input",l[0].dataType,l[0].dims),A=Oe("weight",l[1].dataType,l[1].dims),g=Oe("bias",l[2].dataType,l[2].dims),y=b.type.storage,C=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`
const TILE_SIZE = ${a}u;
var tileInput: array<${y}, ${a*a}>;
var tileWeightQ: array<${y}, ${a*a}>;
var tileWeightK: array<${y}, ${a*a}>;
var tileWeightV: array<${y}, ${a*a}>;
${d.registerUniforms(C).declareVariables(b,A,g,u,_,f)}
${d.mainStart([a,a,1])}
let batchIndex = workgroup_id.z / uniforms.num_heads;
let headNumber = workgroup_id.z % uniforms.num_heads;
let m = global_id.y;
let n = global_id.x;
let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;
let biasOffsetQ = headNumber * uniforms.head_size;
let biasOffsetK = uniforms.hidden_size + biasOffsetQ;
let biasOffsetV = uniforms.hidden_size + biasOffsetK;
var valueQ = ${y}(0);
var valueK = ${y}(0);
var valueV = ${y}(0);
for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {
if (m < uniforms.M && w + local_id.x < uniforms.K) {
tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];
}
if (n < uniforms.N && w + local_id.y < uniforms.K) {
let offset = n + (w + local_id.y) * uniforms.ldb;
tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];
tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];
tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];
}
workgroupBarrier();
for (var k: u32 = 0u; k({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:i,programUniforms:c}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},fh=(e,r)=>{let t=ch(e.inputs,r),[s,o,n]=mh(e,t);return wo(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),_h,gh,wh,Mh,Xx=Ue(()=>{bs(),Mt(),Pt(),ur(),Ct(),_h=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let a=o.length;if(a!==s.length)throw new Error(`${n}: num dimensions != ${a}`);o.forEach((i,l)=>{if(i!==s[l])throw new Error(`${n}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},gh=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,a=s?or(n[n.length-1]):1,i=o==="NHWC"&&n.length>1?a:1,l=Pe.size(n)/a,c=s,p=c?n.length:n,d=Oe("x",e[0].dataType,e[0].dims,a),u=Oe("scale",e[1].dataType,e[1].dims,i),_=Oe("bias",e[2].dataType,e[2].dims,i),f=Oe("inputMean",e[3].dataType,e[3].dims,i),b=Oe("inputVar",e[4].dataType,e[4].dims,i),A=at("y",e[0].dataType,p,a),g=()=>{let C="";if(s)C=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${a}`:"outputIndices[1]"};`;else if(o==="NCHW")C=`
${A.indicesSet("outputIndices","0","0")}
let cOffset = ${A.indicesToOffset("outputIndices")};`;else{C=`var cIndices = ${u.type.indices}(0);
cIndices[0] = outputIndices[${n.length-1}];`;for(let x=1;x`
const epsilon = ${t};
${C.registerUniform("outputSize","u32").declareVariables(d,u,_,f,b,A)}
${C.mainStart()}
${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
var outputIndices = ${A.offsetToIndices(`global_idx * ${a}`)};
${g()}
let scale = ${u.getByOffset("cOffset")};
let bias = ${_.getByOffset("cOffset")};
let inputMean = ${f.getByOffset("cOffset")};
let inputVar = ${b.getByOffset("cOffset")};
let x = ${d.getByOffset("global_idx")};
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
${A.setByOffset("global_idx","value")}
}`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${a}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c?[{type:12,data:l},...lt(n)]:[{type:12,data:l}]})}},wh=e=>jt(e),Mh=(e,r)=>{let{inputs:t,outputCount:s}=e,o=wh({...r,outputCount:s});if(Jt.webgpu.validateInputContent&&_h(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(gh(t,o))}}),bh,yh,vh,Jx=Ue(()=>{Pt(),Ct(),bh=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},yh=e=>{let r=e[0].dims,t=e[0].dims[2],s=Pe.size(r)/4,o=e[0].dataType,n=Oe("input",o,r,4),a=Oe("bias",o,[t],4),i=Oe("residual",o,r,4),l=at("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:c=>`
const channels = ${t}u / 4;
${c.declareVariables(n,a,i,l)}
${c.mainStart()}
${c.guardAgainstOutOfBoundsWorkgroupSizes(s)}
let value = ${n.getByOffset("global_idx")}
+ ${a.getByOffset("global_idx % channels")} + ${i.getByOffset("global_idx")};
${l.setByOffset("global_idx","value")}
}`}},vh=e=>{bh(e.inputs),e.compute(yh(e.inputs))}}),xh,Bt,Th,Eh,Ph,Ch,Sh,$h,Ah,kh,Ih,Fh,Oh,Dh,Lh,zh,Mo,Rh,fa,Bh,Nh,jh,Vh,Uh,Wh,Gh,Hh,Kh,qh,Qh,Xh,Jh,Yh,Zh,em,yl,tm,vl,xl,rm,sm,nm,om,am,im,Tl=Ue(()=>{Mt(),Pt(),ur(),Ct(),xh=(e,r,t,s,o,n,a)=>{let i=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let c=Oe("inputData",t,[i],4),p=at("outputData",s,[i],4),d=[{name:"vec_size",type:"u32"}];return a&&d.push(...a),`
${e.registerUniforms(d).declareVariables(c,p)}
${n??""}
${e.mainStart()}
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
let a = ${c.getByOffset("global_idx")};
${p.setByOffset("global_idx",l)}
}`},Bt=(e,r,t,s,o,n=e.dataType,a,i)=>{let l=[{type:12,data:Math.ceil(Pe.size(e.dims)/4)}];return a&&l.push(...a),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:c=>xh(c,Pe.size(e.dims),e.dataType,n,t,s,i),getRunData:c=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(Pe.size(c[0].dims)/64/4)},programUniforms:l})}},Th=e=>{e.compute(Bt(e.inputs[0],"Abs","abs"))},Eh=e=>{e.compute(Bt(e.inputs[0],"Acos","acos"))},Ph=e=>{e.compute(Bt(e.inputs[0],"Acosh","acosh"))},Ch=e=>{e.compute(Bt(e.inputs[0],"Asin","asin"))},Sh=e=>{e.compute(Bt(e.inputs[0],"Asinh","asinh"))},$h=e=>{e.compute(Bt(e.inputs[0],"Atan","atan"))},Ah=e=>{e.compute(Bt(e.inputs[0],"Atanh","atanh"))},kh=e=>jt(e),Ih=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${r.to}`)}e.compute(Bt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},Fh=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return jt({min:r,max:t})},Oh=(e,r)=>{let t=r||Fh(e.inputs),s=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},Dh=e=>{e.compute(Bt(e.inputs[0],"Ceil","ceil"))},Lh=e=>{e.compute(Bt(e.inputs[0],"Cos","cos"))},zh=e=>{e.compute(Bt(e.inputs[0],"Cosh","cosh"))},Mo=e=>jt(e),Rh=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,`
const elu_alpha_ = ${t}(${r.alpha});
fn elu_f32(a: ${t}) -> ${t} {
return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);
}
fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> {
return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
}`,r.cacheKey))},fa=(e="f32")=>`
const r0: ${e} = 0.3275911;
const r1: ${e} = 0.254829592;
const r2: ${e} = -0.284496736;
const r3: ${e} = 1.421413741;
const r4: ${e} = -1.453152027;
const r5: ${e} = 1.061405429;
fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {
let absv = abs(v);
let x = 1.0 / (1.0 + r0 * absv);
return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
}`,Bh=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,fa(r)))},Nh=e=>{e.compute(Bt(e.inputs[0],"Exp","exp"))},jh=e=>{e.compute(Bt(e.inputs[0],"Floor","floor"))},Vh=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,fa(r)))},Uh=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},Wh=e=>{e.compute(Bt(e.inputs[0],"Not",r=>`!${r}`))},Gh=e=>{e.compute(Bt(e.inputs[0],"Neg",r=>`-${r}`))},Hh=e=>{e.compute(Bt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},Kh=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},qh=e=>{e.compute(Bt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},Qh=e=>jt(e),Xh=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},Jh=e=>{e.compute(Bt(e.inputs[0],"Sin","sin"))},Yh=e=>{e.compute(Bt(e.inputs[0],"Sinh","sinh"))},Zh=e=>{e.compute(Bt(e.inputs[0],"Sqrt","sqrt"))},em=e=>{e.compute(Bt(e.inputs[0],"Tan","tan"))},yl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,tm=e=>{e.compute(Bt(e.inputs[0],"Tanh",yl))},vl=(e="f32")=>`
const fast_gelu_a: ${e} = 0.5;
const fast_gelu_b: ${e} = 0.7978845608028654;
const fast_gelu_c: ${e} = 0.035677408136300125;
fn tanh_v(v: vec4<${e}>) -> vec4<${e}> {
return ${yl("v")};
}
`,xl=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,rm=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"FastGelu",xl,vl(r),void 0,e.inputs[0].dataType))},sm=(e,r)=>{let t=jr(e.inputs[0].dataType);return e.compute(Bt(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},nm=e=>{e.compute(Bt(e.inputs[0],"Log","log"))},om=(e,r)=>`
const alpha = vec4<${e}>(${r});
const one = ${e}(1.0);
const zero = ${e}(0.0);
fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {
let v = x *alpha;
var x1 : vec4<${e}>;
for (var i = 0; i < 4; i = i + 1) {
if (v[i] >= zero) {
x1[i] = one / (one + exp(-v[i]));
} else {
x1[i] = one - one / (one + exp(v[i]));
}
}
return x * x1;
}
`,am=e=>`quick_gelu_impl(${e})`,im=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"QuickGelu",am,om(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),lm,um,cm,Yx=Ue(()=>{Pt(),Ct(),Tl(),lm=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},um=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Oe("input",e[0].dataType,e[0].dims,4),s=Oe("bias",e[0].dataType,[e[0].dims[2]],4),o=at("output",e[0].dataType,r,4),n=Pe.size(r)/4,a=Sr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:i=>`
const M_SQRT2 = sqrt(2.0);
const halfChannels = ${e[0].dims[2]/4/2}u;
${i.declareVariables(t,s,o)}
${fa(a)}
${i.mainStart()}
${i.guardAgainstOutOfBoundsWorkgroupSizes(n)}
let biasIdx = global_idx % halfChannels;
let batchIndex = global_idx / halfChannels;
let inputOffset = biasIdx + batchIndex * halfChannels * 2;
let valueLeft = input[inputOffset] + bias[biasIdx];
let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];
let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);
${o.setByOffset("global_idx","valueLeft * geluRight")}
}`}},cm=e=>{lm(e.inputs),e.compute(um(e.inputs))}}),dm,pm,Ps,hm,mm,fm,_m,gm,wm,Mm,bm,ym,vm,Zx=Ue(()=>{Mt(),Pt(),Ct(),dm=(e,r,t,s,o,n,a,i,l,c,p,d)=>{let u,_;typeof i=="string"?u=_=(y,C)=>`${i}((${y}),(${C}))`:typeof i=="function"?u=_=i:(u=i.scalar,_=i.vector);let f=at("outputData",p,s.length,4),b=Oe("aData",l,r.length,4),A=Oe("bData",c,t.length,4),g;if(o)if(n){let y=Pe.size(r)===1,C=Pe.size(t)===1,x=r.length>0&&r[r.length-1]%4===0,M=t.length>0&&t[t.length-1]%4===0;y||C?g=f.setByOffset("global_idx",_(y?`${b.type.value}(${b.getByOffset("0")}.x)`:b.getByOffset("global_idx"),C?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):g=`
let outputIndices = ${f.offsetToIndices("global_idx * 4u")};
let offsetA = ${b.broadcastedIndicesToOffset("outputIndices",f)};
let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",f)};
${f.setByOffset("global_idx",_(a||x?b.getByOffset("offsetA / 4u"):`${b.type.value}(${b.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||M?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
`}else g=f.setByOffset("global_idx",_(b.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let y=(C,x,M="")=>{let T=`aData[indexA${x}][componentA${x}]`,v=`bData[indexB${x}][componentB${x}]`;return`
let outputIndices${x} = ${f.offsetToIndices(`global_idx * 4u + ${x}u`)};
let offsetA${x} = ${b.broadcastedIndicesToOffset(`outputIndices${x}`,f)};
let offsetB${x} = ${A.broadcastedIndicesToOffset(`outputIndices${x}`,f)};
let indexA${x} = offsetA${x} / 4u;
let indexB${x} = offsetB${x} / 4u;
let componentA${x} = offsetA${x} % 4u;
let componentB${x} = offsetB${x} % 4u;
${C}[${x}] = ${M}(${u(T,v)});
`};p===9?g=`
var data = vec4(0);
${y("data",0,"u32")}
${y("data",1,"u32")}
${y("data",2,"u32")}
${y("data",3,"u32")}
outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:g=`
${y("outputData[global_idx]",0)}
${y("outputData[global_idx]",1)}
${y("outputData[global_idx]",2)}
${y("outputData[global_idx]",3)}
`}return`
${e.registerUniform("vec_size","u32").declareVariables(b,A,f)}
${d??""}
${e.mainStart()}
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
${g}
}`},pm=(e,r,t,s,o,n,a=t.dataType)=>{let i=t.dims.map(b=>Number(b)??1),l=s.dims.map(b=>Number(b)??1),c=!Pe.areEqual(i,l),p=i,d=Pe.size(i),u=!1,_=!1,f=[c];if(c){let b=Gn.calcShape(i,l,!1);if(!b)throw new Error("Can't perform binary op on the given tensors");p=b.slice(),d=Pe.size(p);let A=Pe.size(i)===1,g=Pe.size(l)===1,y=i.length>0&&i[i.length-1]%4===0,C=l.length>0&&l[l.length-1]%4===0;f.push(A),f.push(g),f.push(y),f.push(C);let x=1;for(let M=1;Mb.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:b=>dm(b,i,l,p,u,c,_,o,t.dataType,s.dataType,a,n),getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(Pe.size(p)/4)},...lt(i,l,p)]})}},Ps=(e,r,t,s,o,n)=>{e.compute(pm(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},hm=e=>{Ps(e,"Add",(r,t)=>`${r}+${t}`)},mm=e=>{Ps(e,"Div",(r,t)=>`${r}/${t}`)},fm=e=>{Ps(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},_m=e=>{Ps(e,"Mul",(r,t)=>`${r}*${t}`)},gm=e=>{let r=Oe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Ps(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},`
fn pow_custom(a : ${r}, b : ${r}) -> ${r} {
if (b == ${r}(0.0)) {
return ${r}(1.0);
} else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) {
return ${r}(pow(f32(a), f32(b))); // NaN
}
return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));
}
fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> {
// TODO: implement vectorized pow
return vec4<${r}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));
}
`)},wm=e=>{Ps(e,"Sub",(r,t)=>`${r}-${t}`)},Mm=e=>{Ps(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},bm=e=>{Ps(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},ym=e=>{Ps(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},vm=e=>{Ps(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),xm,Tm,Em,Pm,Cm,Sm,eT=Ue(()=>{Mt(),Pt(),ur(),Ct(),xm=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((a,i)=>{if(i!==t){if(a.dataType!==o)throw new Error("input tensors should be one type");if(a.dims.length!==n)throw new Error("input tensors should have the same shape");a.dims.forEach((l,c)=>{if(c!==r&&l!==s.dims[c])throw new Error("non concat dimensions must match")})}})},Tm=(e,r)=>`
fn calculateInputIndex(index: u32) -> u32 {
let sizeInConcatAxis = array(${r});
for (var i: u32 = 0u; i < ${e}; i += 1u ) {
if (index < sizeInConcatAxis[i]) {
return i;
}
}
return ${e}u;
}`,Em=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=Pe.size(t),n=new Array(e.length),a=new Array(e.length),i=0,l=[],c=[],p=[{type:12,data:o}];for(let b=0;b`uniforms.sizeInConcatAxis${b}`).join(","),f=b=>`
${(()=>{b.registerUniform("outputSize","u32");for(let A=0;A(${_});
${u} -= sizeInConcatAxis[inputIndex - 1u];
}
${Em(a,d)}
}`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:f}},Cm=(e,r)=>{let t=e.inputs,s=t[0].dims,o=Pe.normalizeAxis(r.axis,s.length);xm(t,o);let n=s.slice();n[o]=t.reduce((i,l)=>i+(l.dims.length>o?l.dims[o]:0),0);let a=t.filter(i=>Pe.size(i.dims)>0);e.compute(Pm(a,o,n,t[0].dataType),{inputs:a})},Sm=e=>jt({axis:e.axis})}),_n,gn,wn,El,Mn=Ue(()=>{Mt(),Pt(),_n=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value));
value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},gn=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},wn=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},El=e=>{let r=(e==null?void 0:e.activation)||"";if(r==="HardSigmoid"){let[t,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=(e==null?void 0:e.activation_params)||[Jd,Yd];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=(e==null?void 0:e.activation_params)||[.01];return{activation:r,alpha:t}}return{activation:r}}}),zr,$m,Pl=Ue(()=>{zr=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},$m=e=>`
${e?"value = value + getBiasByOutputCoords(coords);":""}
`}),Am,tT=Ue(()=>{Am=e=>`
fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {
return dot(coords, vec4(
shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));
}
fn getOutputIndexFromCoords(coords : vec4) -> i32 {
return dot(coords, vec4(
i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));
}
`}),bo,Cl,Sl=Ue(()=>{Mt(),Pt(),Ct(),Mn(),bo=(e,r,t,s,o)=>{let n=s-t;return`
${Array.from({length:t}).map((a,i)=>`
if (${it(r.shape,i,r.rank)} != 1) {
${r.indicesSet(e,i,it(o,i+n,s))}
} else {
${r.indicesSet(e,i,0)}
}`).join("")}
`},Cl=(e,r,t,s,o=!1,n)=>{let a=e[0].dims,i=e[1].dims,l=a[a.length-2],c=i[i.length-1],p=a[a.length-1],d=or(c),u=or(p),_=or(l),f=Pe.size(t)/d/_,b=e.length>2,A=s?s.slice(0,-2):t.slice(0,-2),g=[Pe.size(A),l,c],y=[{type:12,data:f},{type:12,data:l},{type:12,data:c},{type:12,data:p}];gn(r,y),y.push(...lt(A,a,i)),b&&y.push(...lt(e[2].dims)),y.push(...lt(g));let C=x=>{let M=ml("batch_dims",e[0].dataType,A.length),T=Oe("a",e[0].dataType,a.length,u),v=Oe("b",e[1].dataType,i.length,d),P=at("output",e[0].dataType,g.length,d),F=Sr(P.type.tensor),D=_n(r,P.type.value,F),K=[T,v],U="";if(b){let q=o?d:1;K.push(Oe("bias",e[2].dataType,e[2].dims.length,q)),U=`${o?`value += bias[col / ${q}];`:`value += ${P.type.value}(bias[row + i]);`}`}let j=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];wn(r,j);let ne=()=>{let q=`var a_data: ${T.type.value};`;for(let te=0;te;
for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) {
${ne()}
}
for (var i = 0u; i < ${_}u; i++) {
var value = values[i];
${U}
${D}
let cur_indices = ${P.type.indices}(batch, row + i, col);
let offset = ${P.indicesToOffset("cur_indices")};
${P.setByOffset(`offset / ${d}`,"value")};
}
}
`};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${u};${_};${o}`,inputDependencies:b?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:y}),getShaderSource:C}}}),km,Im,$l,Al,Fm,kl,Om,_a,Il=Ue(()=>{Mt(),Pt(),Ct(),Mn(),Sl(),Pl(),km=(e,r)=>e?`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
kStart + inputRow,
globalRowStart / innerElementSize + inputCol${r?", batchIndices":""});
`:`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
globalRow + innerRow,
kStart / innerElementSize + inputCol${r?", batchIndices":""});
`,Im=(e,r)=>e?`
let ACached0 = mm_Asub[k * innerElementSize][localRow];
let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];
let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];
${r===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}
for (var i = 0; i < rowPerThread; i = i + 1) {
acc[i] = BCached0 * ACached0[i] + acc[i];
acc[i] = BCached1 * ACached1[i] + acc[i];
acc[i] = BCached2 * ACached2[i] + acc[i];
${r===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}
}`:`
for (var i = 0; i < rowPerThread; i = i + 1) {
let ACached = mm_Asub[tileRow + i][k];
acc[i] = BCached0 * ACached.x + acc[i];
acc[i] = BCached1 * ACached.y + acc[i];
acc[i] = BCached2 * ACached.z + acc[i];
${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}
}`,$l=(e,r,t="f32",s,o=!1,n=32,a=!1,i=32)=>{let l=r[1]*e[1],c=r[0]*e[0],p=o?l:n,d=o?n:l,u=p/r[0],_=n/r[1];if(!((o&&u===4&&e[1]===4||!o&&(u===3||u===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4.
Otherwise, innerElementSize ${u} must be 3 or 4.
tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${n} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return`
var mm_Asub: array, ${p/u}>, ${d}>;
var mm_Bsub: array, ${c/e[0]}>, ${n}>;
const rowPerThread = ${e[1]};
const colPerThread = ${e[0]};
const innerElementSize = ${u};
const tileInner = ${n};
@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]})
fn main(@builtin(local_invocation_id) localId : vec3,
@builtin(global_invocation_id) globalId : vec3,
@builtin(workgroup_id) workgroupId : vec3) {
let localRow = i32(localId.y);
let tileRow = localRow * rowPerThread;
let tileCol = i32(localId.x);
let globalRow =i32(globalId.y) * rowPerThread;
let globalCol = i32(globalId.x);
let batch = ${a?"0":"i32(globalId.z)"};
${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""}
let globalRowStart = i32(workgroupId.y) * ${l};
let num_tiles = ${a?`${Math.ceil(i/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
var kStart = ${a?`i32(globalId.z) * ${i}`:"0"};
var acc: array, rowPerThread>;
// Loop over shared dimension.
let tileRowB = localRow * ${_};
for (var t = 0; t < num_tiles; t = t + 1) {
// Load one tile of A into local memory.
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
let inputRow = tileRow + innerRow;
let inputCol = tileCol;
${km(o,s)}
}
// Load one tile of B into local memory.
for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {
let inputRow = tileRowB + innerRow;
let inputCol = tileCol;
mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""});
}
kStart = kStart + tileInner;
workgroupBarrier();
// Compute acc values for a single thread.
for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {
let BCached0 = mm_Bsub[k * innerElementSize][tileCol];
let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];
let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];
${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}
${Im(o,u)}
}
workgroupBarrier();
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
}
}`},Al=(e,r)=>e?`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
kStart + inputRow,
globalRowStart + inputCol${r?", batchIndices":""});
`:`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
globalRowStart + inputRow,
kStart + inputCol${r?", batchIndices":""});
`,Fm=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",kl=(e,r,t="f32",s,o=!1,n=32,a=!1,i=32,l=!1)=>{let c=e[1]*r[1],p=e[0]*r[0],d=o?c:n,u=o?n:c;if(!(u%r[1]===0&&d%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let _=u/r[1],f=d/r[0],b=n/r[1],A=l?`
let localRow = i32(localId.y);
let localCol = i32(localId.x);
let globalRowStart = i32(workgroupId.y) * ${c};
let globalColStart = i32(workgroupId.x) * ${p};
// Loop over shared dimension.
for (var t = 0; t < num_tiles; t = t + 1) {
// Load one tile of A into local memory.
for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${r[1]}) {
for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) {
${Al(o,s)}
}
}
// Load one tile of B into local memory.
for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) {
for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) {
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
kStart + inputRow,
globalColStart + inputCol${s?", batchIndices":""});
}
}
kStart = kStart + tileInner;
workgroupBarrier();
// Compute acc values for a single thread.
var BCached : array<${t}, colPerThread>;
for (var k = 0; k < tileInner; k = k + 1) {
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
BCached[inner] = mm_Bsub[k][localCol + inner * ${r[0]}];
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`}
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
acc[innerRow][innerCol] = acc[innerRow][innerCol] +
ACached * BCached[innerCol];
}
}
}
workgroupBarrier();
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
let gRow = globalRowStart + localRow + innerRow * ${r[1]};
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
let gCol = globalColStart + localCol + innerCol * ${r[0]};
mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);
}
}
`:`
let tileRow = i32(localId.y) * rowPerThread;
let tileCol = i32(localId.x) * colPerThread;
let globalRow = i32(globalId.y) * rowPerThread;
let globalCol = i32(globalId.x) * colPerThread;
let globalRowStart = i32(workgroupId.y) * ${c};
let tileRowA = i32(localId.y) * ${_};
let tileColA = i32(localId.x) * ${f};
let tileRowB = i32(localId.y) * ${b};
// Loop over shared dimension.
for (var t = 0; t < num_tiles; t = t + 1) {
// Load one tile of A into local memory.
for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) {
let inputRow = tileRowA + innerRow;
let inputCol = tileColA + innerCol;
${Al(o,s)}
}
}
// Load one tile of B into local memory.
for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
let inputRow = tileRowB + innerRow;
let inputCol = tileCol + innerCol;
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
kStart + inputRow,
globalCol + innerCol${s?", batchIndices":""});
}
}
kStart = kStart + tileInner;
workgroupBarrier();
// Compute acc values for a single thread.
var BCached : array<${t}, colPerThread>;
for (var k = 0; k < tileInner; k = k + 1) {
for (var inner = 0; inner < colPerThread; inner = inner + 1) {
BCached[inner] = mm_Bsub[k][tileCol + inner];
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
${Fm(o)}
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
}
}
}
workgroupBarrier();
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
mm_write(batch, globalRow + innerRow, globalCol + innerCol,
acc[innerRow][innerCol]);
}
}
`;return`
var mm_Asub : array, ${u}>;
var mm_Bsub : array, ${n}>;
const rowPerThread = ${e[1]};
const colPerThread = ${e[0]};
const tileInner = ${n};
@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]})
fn main(@builtin(local_invocation_id) localId : vec3,
@builtin(global_invocation_id) globalId : vec3,
@builtin(workgroup_id) workgroupId : vec3) {
let batch = ${a?"0":"i32(globalId.z)"};
${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""}
let num_tiles = ${a?`${Math.ceil(i/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
var kStart = ${a?`i32(globalId.z) * ${i}`:"0"};
var acc : array, rowPerThread>;
${A}
}
`},Om=(e,r,t,s,o=!1)=>{let[n,a,i,l]=s,c=Sr(s[0].type.tensor);return`
fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${zr(e,c)} {
var value = ${zr(e,c)}(0.0);
let col = colIn * ${e};
if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)
{
var aIndices: ${a.type.indices};
${bo("aIndices",a,a.rank-2,n.rank,"batchIndices")}
${a.indicesSet("aIndices",a.rank-2,"u32(row)")}
${a.indicesSet("aIndices",a.rank-1,"u32(colIn)")}
value = ${a.getByIndices("aIndices")};
}
return value;
}
fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${zr(e,c)} {
var value = ${zr(e,c)}(0.0);
let col = colIn * ${e};
if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)
{
var bIndices: ${i.type.indices};
${bo("bIndices",i,i.rank-2,n.rank,"batchIndices")}
${i.indicesSet("bIndices",i.rank-2,"u32(row)")}
${i.indicesSet("bIndices",i.rank-1,"u32(colIn)")}
value = ${i.getByIndices("bIndices")};
}
return value;
}
fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${zr(e,c)}) {
let col = colIn * ${e};
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {
var value = valueIn;
let coords = vec3(batch, row, colIn);
${r?`value = value + ${o?"bias[colIn]":`${zr(e,c)}(bias[row])`};`:""}
${t}
${l.setByIndices("vec3(coords)","value")}
}
}
`},_a=(e,r,t,s,o=!1,n)=>{let a=e[0].dims,i=e[1].dims,l=a.slice(0,-2),c=i.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=Pe.size(p),u=a[a.length-2],_=a[a.length-1],f=i[i.length-1],b=_%4===0&&f%4===0,A=u<=8?[4,1,1]:[4,4,1],g=[8,8,1],y=[Math.ceil(f/g[0]/A[0]),Math.ceil(u/g[1]/A[1]),Math.ceil(d/g[2]/A[2])],C=b?4:1,x=[...l,u,_/C],M=x.length,T=[...c,_,f/C],v=T.length,P=[d,u,f/C],F=[{type:6,data:u},{type:6,data:f},{type:6,data:_}];gn(r,F),F.push(...lt(p,x,T));let D=["rank","rank"],K=e.length>2;K&&(F.push(...lt(e[2].dims)),D.push("rank")),F.push(...lt(P));let U=j=>{let ne=p.length,q=ml("batchDims",e[0].dataType,ne,1),te=Sr(e[0].dataType),Z=Oe("a",e[0].dataType,M,C),ae=Oe("b",e[1].dataType,v,C),he=at("result",e[0].dataType,P.length,C),Q=[Z,ae];if(K){let J=o?C:1;Q.push(Oe("bias",e[2].dataType,e[2].dims.length,J))}let B=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];wn(r,B);let O=Sr(he.type.tensor),W=_n(r,he.type.value,O),N=Om(C,K,W,[q,Z,ae,he],o);return`
${j.registerUniforms(B).registerInternalVariables(q).declareVariables(...Q,he)}
${N}
${b?$l(A,g,te,q):kl(A,g,te,q)}
`};return{name:"MatMul",shaderCache:{hint:`${A};${r.activation};${b};${o}`,inputDependencies:D},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:F}),getShaderSource:U}}}),Dm,Lm,rT=Ue(()=>{Mt(),js(),Ct(),Mn(),Pl(),tT(),Il(),Dm=(e,r,t,s,o=!1,n,a=4,i=4,l=4,c="f32")=>{let p=F=>{switch(F){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${F} is not supported.`)}},d=F=>{switch(F){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${F} is not supported.`)}},u=e?`
let coord = vec4(batch, xRow, xCol, xCh);
`:`
let coord = vec4(batch, xCh, xRow, xCol);
`,_=e?`
let coords = vec4(
batch,
row / outWidth,
row % outWidth,
col);
`:`
let coords = vec4(
batch,
row,
col / outWidth,
col % outWidth);
`,f=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",b=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=e?"row":"col",g=e?"col":"row",y=`
let inChannels = i32(uniforms.w_shape[2]);
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
let outRow = ${A} / outWidth;
let outCol = ${A} % outWidth;
let WRow = ${g} / (i32(uniforms.w_shape[1]) * inChannels);
let WCol = ${g} / inChannels % i32(uniforms.w_shape[1]);
let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];
let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];
let xCh = ${g} % inChannels;
var resData = ${zr(a,c)}(0.0);
// The bounds checking is always needed since we use it to pad zero for
// the 'same' padding type.
if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${b}) {
${u}
let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));
${p(a)}
}
return resData;`,C=e?r&&s?`
let col = colIn * ${a};
${y}`:`
let col = colIn * ${a};
if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {
${y}
}
return ${zr(a,c)}(0.0);`:s&&t?`
let col = colIn * ${a};
${y}`:`
let col = colIn * ${a};
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
${y}
}
return ${zr(a,c)}(0.0);`,x=e?s&&t?d(i):`
let col = colIn * ${i};
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
${d(i)}
}
return ${zr(i,c)}(0.0);`:`
let col = colIn * ${i};
if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
${d(i)}
}
return ${zr(i,c)}(0.0);`,M=zr(l,c),T=zr(e?a:i,c),v=zr(e?i:a,c),P=_n(n,M,c);return`
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${T} {
${e?C:x}
}
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${v} {
${e?x:C}
}
fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${M}) {
let col = colIn * ${l};
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)
{
var value = valueIn;
let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
${_}
${$m(o)}
${P}
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}`},Lm=(e,r,t,s,o,n,a,i,l)=>{let c=r.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],d=t[0],u=c?t[2]:t[3],_=c?t[1]:t[2],f=c?t[3]:t[1],b=c&&(p%4===0||p%3===0)&&f%4===0,A=c?f:u*_,g=c?u*_:f,y=[8,8,1],C=s<=8?[4,1,1]:[4,4,1],x=[Math.ceil(A/y[0]/C[0]),Math.ceil(g/y[1]/C[1]),Math.ceil(d/y[2]/C[2])];Dt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${x}`);let M=b?c&&p%4!==0?3:4:1,T=y[1]*C[1],v=y[0]*C[0],P=Math.max(y[0]*M,y[1]),F=s%T===0,D=o%v===0,K=n%P===0,U=b?[M,4,4]:[1,1,1],j=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];gn(r,j),j.push(...lt(e[0].dims,e[1].dims));let ne=["rank","rank"];a&&(j.push(...lt(e[2].dims)),ne.push("rank")),j.push(...lt(t));let q=te=>{let Z=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];wn(r,Z);let ae=b?4:1,he=Sr(e[0].dataType),Q=`
fn setOutputAtIndex(flatIndex : i32, value : ${b?`vec4<${he}>`:he}) {
result[flatIndex] = ${b?`vec4<${he}>`:he}(value);
}
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${b?`vec4<${he}>`:he}) {
let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));
setOutputAtIndex(flatIndex ${b?"/ 4":""}, value);
}`,B=Oe("x",e[0].dataType,e[0].dims.length,M===3?1:M),O=Oe("w",e[1].dataType,e[1].dims.length,ae),W=[B,O],N=at("result",e[0].dataType,t.length,ae);if(a){let J=Oe("bias",e[2].dataType,e[2].dims.length,ae);W.push(J),Q+=`
fn getBiasByOutputCoords(coords : vec4) -> ${b?`vec4<${he}>`:he} {
return bias[coords.${c?"w":"y"}${b?"/ 4":""}];
}`}return`
${Am("uniforms.result_strides")}
//struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,
// outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,
// dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };
${te.registerUniforms(Z).declareVariables(...W,N)}
${Q}
${Dm(c,F,D,K,a,r,U[0],U[1],U[2],he)}
${b?$l(C,y,he,void 0,!c,P):kl(C,y,he,void 0,!c,P,!1,void 0,i)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${M};${b};${F};${D};${K};${T};${v};${P}`,inputDependencies:ne},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:x[0],y:x[1],z:x[2]},programUniforms:j}),getShaderSource:q}}}),zm,Fl,yo,Rm,Ol,Bm,Nm,jm,sT=Ue(()=>{Mt(),js(),Pt(),Ct(),Mn(),Pl(),zm=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,yo=(e,r)=>r<=1?e:e+(e-1)*(r-1),Rm=(e,r,t,s=1)=>{let o=yo(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},Ol=(e,r,t,s,o)=>{o==null&&(o=Rm(e,r[0],s[0]));let n=[0,0,0,t];for(let a=0;a<3;a++)e[a]+2*o>=r[a]&&(n[a]=Math.trunc((e[a]-r[a]+2*o)/s[a]+1));return n},Bm=(e,r,t,s,o,n,a,i,l,c)=>{let p,d,u,_;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=Ol([r,t,s,1],[i,l,c],1,[o,n,a],e);d=f[0],u=f[1],_=f[2]}else if(Array.isArray(e)){if(!e.every((b,A,g)=>b===g[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let f=Ol([r,t,s,1],[i,l,c],1,[o,n,a],e[0]);d=f[0],u=f[1],_=f[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/o),u=Math.ceil(t/n),_=Math.ceil(s/a);let f=(d-1)*o+i-r,b=(u-1)*n+l-t,A=(_-1)*a+c-s,g=Math.floor(f/2),y=f-g,C=Math.floor(b/2),x=b-C,M=Math.floor(A/2),T=A-M;p={top:C,bottom:x,left:M,right:T,front:g,back:y}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:u,outWidth:_}},Nm=(e,r,t,s,o,n=!1,a="channelsLast")=>{let i,l,c,p,d;if(a==="channelsLast")[i,l,c,p,d]=e;else if(a==="channelsFirst")[i,d,l,c,p]=e;else throw new Error(`Unknown dataFormat ${a}`);let[u,,_,f,b]=r,[A,g,y]=Fl(t),[C,x,M]=Fl(s),T=yo(_,C),v=yo(f,x),P=yo(b,M),{padInfo:F,outDepth:D,outHeight:K,outWidth:U}=Bm(o,l,c,p,A,g,y,T,v,P),j=n?u*d:u,ne=[0,0,0,0,0];return a==="channelsFirst"?ne=[i,j,D,K,U]:a==="channelsLast"&&(ne=[i,D,K,U,j]),{batchSize:i,dataFormat:a,inDepth:l,inHeight:c,inWidth:p,inChannels:d,outDepth:D,outHeight:K,outWidth:U,outChannels:j,padInfo:F,strideDepth:A,strideHeight:g,strideWidth:y,filterDepth:_,filterHeight:f,filterWidth:b,effectiveFilterDepth:T,effectiveFilterHeight:v,effectiveFilterWidth:P,dilationDepth:C,dilationHeight:x,dilationWidth:M,inShape:e,outShape:ne,filterShape:r}},jm=(e,r,t,s,o,n)=>{let a=n==="channelsLast";a?e[0].dims[3]:e[0].dims[1];let i=[64,1,1],l={x:t.map((A,g)=>g)},c=[Math.ceil(zm(l.x.map(A=>t[A]))/i[0]),1,1];Dt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,d=Pe.size(t),u=[{type:12,data:d},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];gn(r,u),u.push(...lt(e[0].dims,e[1].dims));let _=["rank","rank"],f=e.length===3;f&&(u.push(...lt(e[2].dims)),_.push("rank")),u.push(...lt(t));let b=A=>{let g=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];wn(r,g);let y=1,C=Sr(e[0].dataType),x=Oe("x",e[0].dataType,e[0].dims.length,p),M=Oe("W",e[1].dataType,e[1].dims.length,y),T=[x,M],v=at("result",e[0].dataType,t.length,y),P="";if(f){let K=Oe("bias",e[2].dataType,e[2].dims.length,y);T.push(K),P+=`
fn getBiasByOutputCoords(coords : array) -> ${C} {
return bias[${a?it("coords",4,5):it("coords",1,5)}];
}`}let F=zr(p,C),D=_n(r,F,C);return`
${P}
fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
let aIndices = array(d0, d1, d2, d3, d4);
return ${x.getByIndices("aIndices")};
}
fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
let aIndices = array(d0, d1, d2, d3, d4);
return ${M.getByIndices("aIndices")};
}
${A.registerUniforms(g).declareVariables(...T,v)}
${A.mainStart()}
${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let coords = ${v.offsetToIndices("global_idx")};
let batch = ${it("coords",0,x.rank)};
let d2 = ${a?it("coords",x.rank-1,x.rank):it("coords",1,x.rank)};
let xFRCCorner = vec3(${a?it("coords",1,x.rank):it("coords",2,x.rank)},
${a?it("coords",2,x.rank):it("coords",3,x.rank)},
${a?it("coords",3,x.rank):it("coords",4,x.rank)}) * uniforms.strides - uniforms.pads;
let xFCorner = xFRCCorner.x;
let xRCorner = xFRCCorner.y;
let xCCorner = xFRCCorner.z;
let xShapeY = ${a?it("uniforms.x_shape",1,x.rank):it("uniforms.x_shape",2,x.rank)};
let xShapeZ = ${a?it("uniforms.x_shape",2,x.rank):it("uniforms.x_shape",3,x.rank)};
let xShapeW = ${a?it("uniforms.x_shape",3,x.rank):it("uniforms.x_shape",4,x.rank)};
let xShapeU = ${a?it("uniforms.x_shape",4,x.rank):it("uniforms.x_shape",1,x.rank)};
let inputDepthNearestVec4 = (xShapeU / 4) * 4;
let inputDepthVec4Remainder = xShapeU % 4;
var value = 0.0;
for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {
let xF = xFCorner + wF * uniforms.dilations[0];
if (xF < 0 || xF >= xShapeY) {
continue;
}
for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {
let xR = xRCorner + wR * uniforms.dilations[1];
if (xR < 0 || xR >= xShapeZ) {
continue;
}
for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {
let xC = xCCorner + wC * uniforms.dilations[2];
if (xC < 0 || xC >= xShapeW) {
continue;
}
for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {
${a?`let xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3));
`:`let xValues = vec4(
getX(batch, d1, xF, xR, xC),
getX(batch, d1 + 1, xF, xR, xC),
getX(batch, d1 + 2, xF, xR, xC),
getX(batch, d1 + 3, xF, xR, xC));
`}
let wValues = vec4(
getW(d2, d1, wF, wR, wC),
getW(d2, d1 + 1, wF, wR, wC),
getW(d2, d1 + 2, wF, wR, wC),
getW(d2, d1 + 3, wF, wR, wC));
value += dot(xValues, wValues);
}
if (inputDepthVec4Remainder == 1) {
${a?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4)
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC)
* getW(d2, inputDepthNearestVec4, wF, wR, wC);`}
} else if (inputDepthVec4Remainder == 2) {
${a?`let xValues = vec2(
getX(batch, xF, xR, xC, inputDepthNearestVec4),
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));
`:`let xValues = vec2(
getX(batch, inputDepthNearestVec4, xF, xR, xC),
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));
`}
let wValues = vec2(
getW(d2, inputDepthNearestVec4, wF, wR, wC),
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));
value += dot(xValues, wValues);
} else if (inputDepthVec4Remainder == 3) {
${a?`let xValues = vec3(
getX(batch, xF, xR, xC, inputDepthNearestVec4),
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),
getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));
`:`let xValues = vec3(
getX(batch, inputDepthNearestVec4, xF, xR, xC),
getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),
getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));
`}
let wValues = vec3(
getW(d2, inputDepthNearestVec4, wF, wR, wC),
getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),
getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));
value += dot(xValues, wValues);
}
}
}
}
${f?"value = value + getBiasByOutputCoords(coords)":""};
${D}
result[global_idx] = f32(value);
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${a};${p};${f}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:u}),getShaderSource:b}}}),Vm,Um,nT=Ue(()=>{Mt(),Pt(),Ct(),Mn(),Vm=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",a=e[0].dims,i=e[1].dims,l=r.format==="NHWC",c=l?t[3]:t[1],p=c/r.group,d=l&&p>=4?or(c):1,u=Pe.size(t)/d,_=[{type:12,data:u},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];gn(r,_),_.push(...lt(a,[i[0],i[1],i[2],i[3]/d]));let f=o?["rank","rank","rank"]:["rank","rank"];_.push(...lt([t[0],t[1],t[2],t[3]/d]));let b=A=>{let g=at("output",e[0].dataType,t.length,d),y=Sr(g.type.tensor),C=_n(r,g.type.value,y),x=Oe("x",e[0].dataType,a.length),M=Oe("w",e[1].dataType,i.length,d),T=[x,M];o&&T.push(Oe("b",e[2].dataType,e[2].dims,d));let v=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];wn(r,v);let P=l?`
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {
continue;
}
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {
continue;
}
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {
let input_channel = in_channel_offset + wInChannel;
let xVal = ${x.get("batch","xHeight","xWidth","input_channel")};
let wVal = ${M.get("wHeight","wWidth","wInChannel","output_channel")};
value += xVal * wVal;
}
}
}
`:`
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {
let input_channel = in_channel_offset + wInChannel;
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {
continue;
}
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {
continue;
}
let xVal = ${x.get("batch","input_channel","xHeight","xWidth")};
let wVal = ${M.get("output_channel","wInChannel","wHeight","wWidth")};
value += xVal * wVal;
}
}
}
`;return`
${A.registerUniforms(v).declareVariables(...T,g)}
${A.mainStart()}
${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let outputIndices = ${g.offsetToIndices("global_idx")};
let batch: u32 = outputIndices[0];
let output_channel: u32 = outputIndices[${l?3:1}];
let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads;
let group_id: u32 = output_channel * ${d} / uniforms.output_channels_per_group;
var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}];
var value: ${g.type.value} = ${g.type.value}(0);
${P}
${n}
${C}
${g.setByOffset("global_idx","value")}
}`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:_}),getShaderSource:b}},Um=(e,r,t,s)=>{let o=e.length>2,n=or(t[3]),a=or(t[2]),i=Pe.size(t)/n/a,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[t[0],t[1],t[2],t[3]/n],d=[{type:12,data:i},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];gn(r,d),d.push(...lt(l,c,p));let u=(a-1)*r.strides[1]+c[1],_=f=>{let b=at("output",e[0].dataType,p.length,n),A=Sr(b.type.tensor),g=_n(r,b.type.value,A),y=Oe("x",e[0].dataType,l.length,n),C=Oe("w",e[1].dataType,c.length,n),x=[y,C];o&&x.push(Oe("b",e[2].dataType,e[2].dims,n));let M=o?"value += b[output_channel];":"",T=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return wn(r,T),`
${f.registerUniforms(T).declareVariables(...x,b)}
${f.mainStart()}
${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let width0 = uniforms.output_shape[3];
let output_channel = global_idx % width0;
var index1 = global_idx / width0;
let width1 = uniforms.output_shape[2] / ${a}u;
let col = (index1 % width1) * ${a}u;
index1 = index1 / width1;
let row = index1 % uniforms.output_shape[1];
let batch = index1 / uniforms.output_shape[1];
let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;
var x_vals: array<${y.type.value}, ${u}>;
var values: array<${b.type.value}, ${a}>;
let input_channel = output_channel;
// Use constant instead of uniform can give better performance for w's height/width.
for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) {
let x_height = x_corner.x + i32(w_height);
if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {
for (var i = 0; i < ${u}; i++) {
let x_width = x_corner.y + i;
if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {
x_vals[i] = ${y.get("batch","u32(x_height)","u32(x_width)","input_channel")};
} else {
x_vals[i] = ${y.type.value}(0);
}
}
for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) {
let w_val = ${C.get("w_height","w_width","0","output_channel")};
for (var i = 0u; i < ${a}u; i++) {
values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);
}
}
}
}
for (var i = 0u; i < ${a}u; i++) {
var value = values[i];
${M}
${g}
${b.set("batch","row","col + i","output_channel","value")};
}
}`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${a};${u};${c[0]};${c[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d}),getShaderSource:_}}}),Wm,ga,Gm,wa,Dl,Ll,Hm,Km,zl,oT=Ue(()=>{Pt(),rT(),sT(),Il(),nT(),Mn(),Sl(),Ys(),Wm=(e,r,t,s,o,n)=>{let a=e[0],i=e.slice(n?1:2,n?3:4),l=i.length,c=r[0],p=r.slice(2).map((u,_)=>u+(u-1)*(t[_]-1)),d=i.map((u,_)=>u+s[_]+s[_+l]).map((u,_)=>Math.floor((u-p[_]+o[_])/o[_]));return d.splice(0,0,a),d.splice(n?3:1,0,c),d},ga=[2,3,1,0],Gm=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},wa=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=El(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,a=e.kernel_shape,i=e.pads,l=e.strides,c=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:a,pads:i,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Ll=(e,r,t,s)=>{let o=t.format==="NHWC",n=Wm(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let T=[r[0]];if(o){let v=e.kernelCustomData.wT??e.compute(rs(r[1],ga),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=v),T.push(v)}else T.push(r[1]);r.length===3&&T.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(Um(T,t,n,s),{inputs:T}):e.compute(Vm(T,t,n,s),{inputs:T});return}let a=r.length===3,i=r[0].dims[o?1:2],l=r[0].dims[o?2:3],c=r[0].dims[o?3:1],p=r[1].dims[2],d=r[1].dims[3],u=n[o?1:2],_=n[o?2:3],f=n[o?3:1],b=o&&p===i&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(b||p===1&&d===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let T=n[0],v,P,F,D=[];if(o){let j=e.kernelCustomData.wT??e.compute(rs(r[1],ga),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=j),b){let ne=i*l*c;v=r[0].reshape([1,T,ne]),P=j.reshape([1,ne,f]),F=[1,T,f]}else v=r[0].reshape([T,i*l,c]),P=j.reshape([1,c,f]),F=[T,u*_,f];D.push(v),D.push(P)}else v=r[0].reshape([T,c,i*l]),P=r[1].reshape([1,f,c]),F=[T,f,u*_],D.push(P),D.push(v);a&&D.push(r[2]);let K=F[2],U=D[0].dims[D[0].dims.length-1];K<8&&U<8?e.compute(Cl(D,t,n,F,o,s),{inputs:D}):e.compute(_a(D,t,n,F,o,s),{inputs:D});return}let A=!0,g=e.kernelCustomData.wT??e.compute(rs(r[1],ga),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let y=[r[0],g];a&&y.push(r[2]);let C=o?u*_:f,x=o?f:u*_,M=p*d*c;e.compute(Lm(y,t,n,C,x,M,a,A,s),{inputs:y})},Hm=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),a=[1].concat(r.dilations),i=[1].concat(r.kernelShape),l=wa({...r,pads:o,strides:n,dilations:a,kernelShape:i},s);Ll(e,s,l,c=>t?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},Km=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=wa(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,a=Nm(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(jm(r,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],s))},zl=(e,r)=>{if(Gm(e.inputs,r),e.inputs[0].dims.length===3)Hm(e,r);else if(e.inputs[0].dims.length===5)Km(e,e.inputs,r);else{let t=wa(r,e.inputs);Ll(e,e.inputs,t)}}}),qm,aT=Ue(()=>{Mt(),js(),Pt(),Ct(),qm=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",a=r.group,i=e[1].dims,l=i[2]/a,c=i[3],p=n?or(l):1,d=n&&c===1&&l>=4,u=d?Math.floor(l/4)*4:Math.floor(l/p)*p,_=l-u,f=n?or(c):1,b=n?c===1?p:f:1,A=Pe.size(o)/f,g=[Math.ceil(A/64),1,1];Dt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${g}`);let y=["rank","rank"],C=[r.strides[0],r.strides[1]],x=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],M=[r.dilations[0],r.dilations[1]],T=[x[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),x[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],v=[T[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),T[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],P=[{type:12,data:A},{type:12,data:C},{type:12,data:x},{type:12,data:M},{type:12,data:T},{type:6,data:v},{type:12,data:u},{type:12,data:l},{type:12,data:c},...lt(e[0].dims,e[1].dims)];s&&(P.push(...lt(e[2].dims)),y.push("rank")),P.push(...lt(o));let F=D=>{let K=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:C.length},{name:"filter_dims",type:"u32",length:x.length},{name:"dilations",type:"u32",length:x.length},{name:"effective_filter_dims",type:"u32",length:T.length},{name:"pads",type:"i32",length:v.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],U=Sr(e[0].dataType),j=n?1:2,ne=n?2:3,q=n?3:1,te=Oe("W",e[1].dataType,e[1].dims.length,b),Z=Oe("Dy",e[0].dataType,e[0].dims.length,p),ae=[Z,te];s&&ae.push(Oe("bias",e[2].dataType,[o[q]].length,f));let he=at("result",e[0].dataType,o.length,f),Q=()=>{let W="";if(d)p===4?W+=`
let xValue = ${Z.getByOffset("x_offset")};
let wValue = ${te.getByOffset("w_offset")};
dotProd = dotProd + dot(xValue, wValue);
x_offset += 1u;
w_offset += 1u;`:p===2?W+=`
dotProd = dotProd + dot(vec4<${U}>(${Z.getByOffset("x_offset")}, ${Z.getByOffset("x_offset + 1u")}), vec4<${U}>(${te.getByOffset("w_offset")}, ${te.getByOffset("w_offset + 1u")}));
x_offset += 2u;
w_offset += 2u;`:p===1&&(W+=`
dotProd = dotProd + dot(vec4<${U}>(${Z.getByOffset("x_offset")}, ${Z.getByOffset("x_offset + 1u")}, ${Z.getByOffset("x_offset + 2u")}, ${Z.getByOffset("x_offset + 3u")}), vec4<${U}>(${te.getByOffset("w_offset")}, ${te.getByOffset("w_offset + 1u")}, ${te.getByOffset("w_offset + 2u")}, ${te.getByOffset("w_offset + 3u")}));
x_offset += 4u;
w_offset += 4u;`);else if(W+=`
let xValue = ${n?Z.getByOffset(`${Z.indicesToOffset(`${Z.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):Z.get("batch","inputChannel","idyR","idyC")};
`,p===1)W+=`
let w_offset = ${te.indicesToOffset(`${te.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
let wValue = ${te.getByOffset(`w_offset / ${b}`)};
dotProd = dotProd + xValue * wValue;`;else for(let N=0;N{if(_===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let W="";if(p===1){W+="dotProd = dotProd";for(let N=0;N<_;N++)W+=`
+ ${Z.getByOffset(`x_offset + ${N}`)} * ${te.getByOffset(`w_offset + ${N}`)}`;W+=";"}else if(p===2){if(_!==2)throw new Error(`Invalid inputChannelsRemainder ${_}.`);W+=`
let xValue = ${Z.getByOffset("x_offset")};
let wValue = ${te.getByOffset("w_offset")};
dotProd = dotProd + dot(xValue, wValue);`}return W},O=`
let outputIndices = ${he.offsetToIndices(`global_idx * ${f}`)};
let batch = ${he.indicesGet("outputIndices",0)};
let d1 = ${he.indicesGet("outputIndices",q)};
let r = ${he.indicesGet("outputIndices",j)};
let c = ${he.indicesGet("outputIndices",ne)};
let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;
let dyRCorner = dyCorner.x;
let dyCCorner = dyCorner.y;
let groupId = d1 / uniforms.output_channels_per_group;
let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
var dotProd = ${he.type.value}(0.0);
var wR: u32 = 0;
if (uniforms.dilations.x == 1) {
// Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0
wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);
}
for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {
if (wR % uniforms.dilations.x != 0) {
continue;
}
let dyR = (${U}(dyRCorner) + ${U}(wR)) / ${U}(uniforms.strides[0]);
let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;
if (dyR < 0.0 || dyR >= ${U}(uniforms.Dy_shape[${j}]) || fract(dyR) > 0.0 ||
wRPerm < 0) {
continue;
}
let idyR: u32 = u32(dyR);
var wC: u32 = 0;
if (uniforms.dilations.y == 1) {
// Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0
wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);
}
for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {
if (wC % uniforms.dilations.y != 0) {
continue;
}
let dyC = (${U}(dyCCorner) + ${U}(wC)) / ${U}(uniforms.strides.y);
let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
if (dyC < 0.0 || dyC >= ${U}(uniforms.Dy_shape[${ne}]) ||
fract(dyC) > 0.0 || wCPerm < 0) {
continue;
}
let idyC: u32 = u32(dyC);
var inputChannel = groupId * uniforms.input_channels_per_group;
${d?`
var x_offset = ${Z.indicesToOffset(`${Z.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p};
var w_offset = ${te.indicesToOffset(`${te.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${b};
`:""}
for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) {
${Q()}
inputChannel = inputChannel + ${d?4:p};
}
${B()}
wC = wC + uniforms.strides.y - 1;
}
wR = wR + uniforms.strides[0] - 1;
}
let value = dotProd${s?` + bias[d1 / ${f}]`:""};
${he.setByOffset("global_idx","value")};
`;return`
${D.registerUniforms(K).declareVariables(...ae,he)}
${D.mainStart()}
${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
${O}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${b}${f}${d}${_}`,inputDependencies:y},getRunData:()=>({dispatchGroup:{x:g[0],y:g[1],z:g[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:P}),getShaderSource:F}}}),Qm,Xm,Jm,Rl,Ym,Zm,Bl,ef,tf,iT=Ue(()=>{aT(),Mn(),Ys(),Qm=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,Xm=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},Jm=(e,r,t,s,o,n,a,i,l,c)=>{let p=e.length-2,d=c.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,u)=>d*u,1)===0){t.length=0;for(let d=2;dd+u,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let c=e.strides.slice();if(c.reduce((d,u)=>d+u,0)===0){let d=r[0].dims.length-2;c=new Array(d).fill(1)}Jm(i,t,l,e.autoPad,e.group,o,c,s,a,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:a,outputShape:n,dilations:l,strides:c}),p},Ym=e=>{let r=El(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,a=e.kernelShape,i=e.pads,l=e.strides,c=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:a,outputPadding:p,outputShape:d,pads:i,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Zm=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((a,i)=>a+i,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((a,i)=>a+i,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((a,i)=>a+i,0)>0&&r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.outputPadding.length!==n&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(r.kernelShape.reduce((a,i)=>a+i,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Bl=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(rs(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(qm(n,t,s),{inputs:n})},ef=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let a=r.strides;(a.length===0||a[0]===0)&&(a=[1]);let i=r.pads;i.length===0&&(i=[0,0]),i=[0,i[0],0,i[1]],a=[1].concat(a),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let c=Rl({...r,pads:i,strides:a,dilations:n,kernelShape:o,outputPadding:l},s);Bl(e,s,c,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},tf=(e,r)=>{if(Zm(e.inputs,r),e.inputs[0].dims.length===3)ef(e,r);else{let t=Rl(r,e.inputs);Bl(e,e.inputs,t)}}}),rf,sf,nf,lT=Ue(()=>{Mt(),Pt(),ur(),Ct(),rf=(e,r,t,s)=>{let o=Pe.size(r),n=r.length,a=Oe("input",e,n),i=at("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=Pe.normalizeAxis(l,n),p=d=>{let u=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,_=it("uniforms.input_shape","uniforms.axis",n),f=s.reverse?u+(s.exclusive?" + 1":""):"0",b=s.reverse?_:u+(s.exclusive?"":" + 1");return`
${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,i)}
${d.mainStart()}
${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
var inputIndices = ${i.offsetToIndices("global_idx")};
var sum = ${i.type.value}(0);
let first : i32 = ${f};
let last : i32 = ${b};
for (var i : i32 = first; i < last; i++) {
${a.indicesSet("inputIndices","uniforms.axis","u32(i)")};
sum = sum + ${a.getByIndices("inputIndices")};
}
${i.setByOffset("global_idx","sum")};
}`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:c},...lt(r,r)]}),getShaderSource:p}},sf=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(rf(s,t,o,r),{inputs:[0]})},nf=e=>{let r=e.exclusive===1,t=e.reverse===1;return jt({exclusive:r,reverse:t})}}),of,af,lf,uf,cf,uT=Ue(()=>{Mt(),Pt(),ur(),Ct(),of=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},af=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} {
var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,a,i,l=r.format==="NHWC",c=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,a=p?[t,s,o,c,c,n/c**2]:[t,s,o,n/c**2,c,c],i=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=p?[t,c,c,n/c**2,s,o]:[t,n/c**2,c,c,s,o],i=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(a),u=d.dims.length,_=e.dataType,f=Oe("a",_,u),b=at("output",_,u),A=g=>`
${g.registerUniform("output_size","u32").declareVariables(f,b)}
${af(i,u,f,b)}
${g.mainStart()}
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let indices = ${b.offsetToIndices("global_idx")};
let aIndices = perm(indices);
${b.setByOffset("global_idx",f.getByIndices("aIndices"))}
}`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:g=>{let y=l?[t,s*c,o*c,n/c**2]:[t,n/c**2,s*c,o*c],C=Pe.size(y),x=d.dims,M=Pe.sortBasedOnPerm(x,i);return{outputs:[{dims:y,dataType:g[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...lt(x,M)]}},getShaderSource:A}},uf=(e,r)=>{of(e.inputs),e.compute(lf(e.inputs[0],r))},cf=e=>jt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ma,vo,Nl,df,pf,hf,mf,jl,ff,_f,gf,cT=Ue(()=>{Mt(),Pt(),ur(),Ct(),Ma="[a-zA-Z]|\\.\\.\\.",vo="("+Ma+")+",Nl="^"+vo+"$",df="("+vo+",)*"+vo,pf="^"+df+"$",hf=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},mf=class{constructor(e,r){var o;this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(pf)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,a)=>{let i=e[a].dims.slice();if(!n.match(RegExp(Nl)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,i,a);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,a])=>a.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(vo)))throw new Error("Invalid RHS");(o=s.match(RegExp(Ma,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(n);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let o=t.length,n=!1,a=[],i=0;if(!e.match(RegExp(Nl))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(Ma,"g")),c=new hf(s);return l==null||l.forEach((p,d)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let u=o-l.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(a=t.slice(i,i+u),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=a;else throw new Error("Ellipsis must be specified in the LHS");for(let _=0;_e+"_max",ff=(e,r,t,s)=>{let o=e.map(c=>c.length).map((c,p)=>Oe(`input${p}`,r,c)),n=Pe.size(s),a=at("output",r,s.length),i=[...t.symbolToInfo.keys()].filter(c=>!t.rhs.symbolToIndices.has(c)),l=c=>{let p=[],d="var prod = 1.0;",u="var sum = 0.0;",_="sum += prod;",f=[],b=[],A=[],g=[],y=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((x,M)=>{var T;if(t.rhs.symbolToIndices.has(M)){let v=(T=t.rhs.symbolToIndices.get(M))==null?void 0:T[0];v!==void 0&&t.lhs.forEach((P,F)=>{if(x.inputIndices.includes(F)){let D=P.symbolToIndices.get(M);if(D===void 0)throw new Error("Invalid symbol error");D.forEach(K=>{p.push(`${o[F].indicesSet(`input${F}Indices`,K,a.indicesGet("outputIndices",v))}`)})}})}else t.lhs.forEach((v,P)=>{if(x.inputIndices.includes(P)){let F=v.symbolToIndices.get(M);if(F===void 0)throw new Error("Invalid symbol error");F.forEach(D=>{f.push(`${o[P].indicesSet(`input${P}Indices`,D,`${M}`)}`)}),g.push(`prod *= ${o[P].getByIndices(`input${P}Indices`)};`)}}),b.push(`for(var ${M}: u32 = 0; ${M} < uniforms.${jl(M)}; ${M}++) {`),A.push("}")});let C=y?[...p,`let sum = ${o.map((x,M)=>x.getByIndices(`input${M}Indices`)).join(" * ")};`]:[...p,u,...b,...f,d,...g,_,...A];return`
${c.registerUniforms(i.map(x=>({name:`${jl(x)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,a)}
${c.mainStart()}
${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
var outputIndices = ${a.offsetToIndices("global_idx")};
${o.map((x,M)=>`var input${M}Indices: ${o[M].type.indices};`).join(`
`)}
${C.join(`
`)};
${a.setByOffset("global_idx","sum")};
}`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=i.filter(d=>t.symbolToInfo.has(d)).map(d=>{var u;return{type:12,data:((u=t.symbolToInfo.get(d))==null?void 0:u.dimValue)||0}});c.push({type:12,data:n});let p=e.map((d,u)=>[...lt(d)]).reduce((d,u)=>d.concat(u),c);return p.push(...lt(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},_f=(e,r)=>{let t=new mf(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,a)=>n.dims);e.compute(ff(o,e.inputs[0].dataType,t,s))},gf=e=>{let r=e.equation.replace(/\s+/g,"");return jt({equation:r})}}),wf,Vl,Mf,bf,yf,dT=Ue(()=>{Mt(),Pt(),Ct(),wf=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let o=0;oe.length>r.length?Vl(e,r):Vl(r,e),bf=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Mf(r,t),o=e[0].dataType,n=o===9||Pe.size(r)===1,a=o===9||r.length>0&&r[r.length-1]%4===0?4:1,i=n||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(Pe.size(s)/i),c=d=>{let u=Oe("input",o,r.length,a),_=at("output",o,s.length,i),f;if(o===9){let b=(A,g,y="")=>`
let outputIndices${g} = ${_.offsetToIndices(`outputOffset + ${g}u`)};
let offset${g} = ${u.broadcastedIndicesToOffset(`outputIndices${g}`,_)};
let index${g} = offset${g} / 4u;
let component${g} = offset${g} % 4u;
${A}[${g}] = ${y}(${u.getByOffset(`index${g}`)}[component${g}]);
`;f=`
let outputOffset = global_idx * ${i};
var data = vec4(0);
${b("data",0,"u32")}
${b("data",1,"u32")}
${b("data",2,"u32")}
${b("data",3,"u32")}
${_.setByOffset("global_idx","data")}
}`}else f=`
let outputIndices = ${_.offsetToIndices(`global_idx * ${i}`)};
let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",_)};
let data = ${_.type.value}(${u.getByOffset(`inputOffset / ${a}`)});
${_.setByOffset("global_idx","data")}
}`;return`
${d.registerUniform("vec_size","u32").declareVariables(u,_)}
${d.mainStart()}
${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
${f}`},p=[{type:12,data:l},...lt(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${a}${i}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},yf=e=>{wf(e.inputs),e.compute(bf(e.inputs),{inputs:[0]})}}),vf,xf,pT=Ue(()=>{Mt(),Pt(),Ct(),Tl(),vf=e=>{let r=e[0].dataType,t=Pe.size(e[0].dims),s=Pe.size(e[1].dims),o=s%4===0,n=a=>{let i=Oe("x",r,[1],4),l=Oe("bias",r,[1],4),c=at("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=_=>`
let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;
let bias${_} = ${l.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,u=o?`
let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)}
let bias = ${i.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(p).declareVariables(i,l,c)}
${vl(jr(r))}
${a.mainStart(Hn)}
${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
let x = ${i.getByOffset("global_idx")};
${u}
let x_in = x + bias;
${c.setByOffset("global_idx",xl("x_in"))}
}`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/Hn/4)}})}},xf=e=>{e.inputs.length<2||Pe.size(e.inputs[1].dims)===0?rm(e):e.compute(vf(e.inputs))}}),Tf,Ef,Pf,Cf,hT=Ue(()=>{Mt(),Pt(),ur(),Ct(),Tf=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ef=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Pe.normalizeAxis(r.axis,o),a=t.slice(0);a.splice(n,1,...s);let i=t[n],l=e[0].dataType===9?4:1,c=Math.ceil(Pe.size(a)/l),p=[{type:12,data:c},{type:6,data:i},{type:12,data:n},...lt(e[0].dims,e[1].dims,a)],d=u=>{let _=Oe("data",e[0].dataType,e[0].dims.length,l),f=Oe("inputIndices",e[1].dataType,e[1].dims.length),b=at("output",e[0].dataType,a.length,l),A=y=>{let C=s.length,x=`var indicesIndices${y} = ${f.type.indices}(0);`;for(let M=0;M1?`indicesIndices${y}[${M}]`:`indicesIndices${y}`} = ${a.length>1?`outputIndices${y}[uniforms.axis + ${M}]`:`outputIndices${y}`};`;x+=`
var idx${y} = ${f.getByIndices(`indicesIndices${y}`)};
if (idx${y} < 0) {
idx${y} = idx${y} + uniforms.axisDimLimit;
}
var dataIndices${y} : ${_.type.indices};
`;for(let M=0,T=0;M1?`dataIndices${y}[${M}]`:`dataIndices${y}`} = u32(idx${y});`,T+=C):(x+=`${o>1?`dataIndices${y}[${M}]`:`dataIndices${y}`} = ${a.length>1?`outputIndices${y}[${T}]`:`outputIndices${y}`};`,T++);return x},g;if(e[0].dataType===9){let y=(C,x,M="")=>`
let outputIndices${x} = ${b.offsetToIndices(`outputOffset + ${x}u`)};
${A(x)};
let offset${x} = ${_.indicesToOffset(`dataIndices${x}`)};
let index${x} = offset${x} / 4u;
let component${x} = offset${x} % 4u;
${C}[${x}] = ${M}(${_.getByOffset(`index${x}`)}[component${x}]);
`;g=`
let outputOffset = global_idx * ${l};
var value = vec4(0);
${y("value",0,"u32")}
${y("value",1,"u32")}
${y("value",2,"u32")}
${y("value",3,"u32")}
${b.setByOffset("global_idx","value")}
`}else g=`
let outputIndices = ${b.offsetToIndices("global_idx")};
${A("")};
let value = ${_.getByIndices("dataIndices")};
${b.setByOffset("global_idx","value")};
`;return`
${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,f,b)}
${u.mainStart()}
${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
${g}
}`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:d}},Pf=e=>jt({axis:e.axis}),Cf=(e,r)=>{let t=e.inputs;Tf(t),e.compute(Ef(e.inputs,r))}}),Sf,$f,Af,mT=Ue(()=>{Mt(),Pt(),Ct(),Sf=(e,r,t,s,o,n,a,i,l)=>{let c=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:a},{type:12,data:i},{type:12,data:l}],p=[n];c.push(...lt(r.dims,p));let d=u=>{let _=Oe("indices_data",r.dataType,r.dims.length),f=at("input_slice_offsets_data",12,1,1),b=[_,f],A=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`
${u.registerUniforms(A).declareVariables(...b)}
${u.mainStart()}
${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let batch_idx = global_idx / uniforms.num_slices_per_batch;
let base_offset = batch_idx * uniforms.input_batch_stride;
let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;
var relative_slice_offset = 0;
for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {
var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);
let input_dim_idx = uniforms.batch_dims + dim_idx;
if (index < 0) {
${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"}
}
${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"}
}
input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
}`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:c}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},$f=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,a=n[n.length-1],i=Pe.sizeToDimension(n,n.length-1),l=Pe.sizeFromDimension(s,r.batchDims+a),c=Pe.sizeToDimension(s,r.batchDims),p=Pe.sizeFromDimension(s,r.batchDims),d=i/c,u=new Array(a),_=l;for(let x=0;xs.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let A=n.slice(0,-1).concat(s.slice(b)),g=Pe.size(A),y=[{type:12,data:g},{type:12,data:l},...lt(t[0].dims,f.dims,A)],C=x=>{let M=Oe("data",t[0].dataType,t[0].dims.length),T=Oe("slice_offsets",12,f.dims.length),v=at("output",t[0].dataType,A.length);return`
${x.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(M,T,v)}
${x.mainStart()}
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];
}`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:A,dataType:o}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:y}),getShaderSource:C},{inputs:[t[0],f]})},Af=e=>({batchDims:e.batch_dims,cacheKey:""})}),kf,If,Ff,Of,fT=Ue(()=>{Mt(),Pt(),ur(),Ct(),kf=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=Pe.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],a=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.dims.map((i,l)=>l===t?Math.ceil(i/s)===n.dims[l]:i===n.dims[l]).reduce((i,l)=>i&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==n.dims.length||!a.dims.map((i,l)=>i===n.dims[l]).reduce((i,l)=>i&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},If=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Pe.normalizeAxis(r.gatherAxis,o),a=Pe.normalizeAxis(r.quantizeAxis,o),i=t.slice(0);i.splice(n,1,...s);let l=Pe.size(i),c=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:a},{type:12,data:n},{type:12,data:r.blockSize},...lt(...e.map((_,f)=>_.dims),i)],u=_=>{let f=Oe("data",e[0].dataType,e[0].dims.length),b=Oe("inputIndices",e[1].dataType,e[1].dims.length),A=Oe("scales",e[2].dataType,e[2].dims.length),g=e.length>3?Oe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,y=at("output",c,i.length),C=[f,b,A];g&&C.push(g);let x=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return`
${_.registerUniforms(x).declareVariables(...C,y)}
${_.mainStart()}
let output_indices = ${y.offsetToIndices("global_idx")};
var indices_indices = ${b.type.indices}(0);
${s.length>1?`
for (var i: u32 = 0; i < ${s.length}; i++) {
let index = ${y.indicesGet("output_indices","uniforms.gather_axis + i")};
${b.indicesSet("indices_indices","i","index")};
}`:`indices_indices = ${y.indicesGet("output_indices","uniforms.gather_axis")};`};
var data_indices = ${f.type.indices}(0);
for (var i: u32 = 0; i < uniforms.gather_axis; i++) {
let index = ${y.indicesGet("output_indices","i")};
${f.indicesSet("data_indices","i","index")};
}
var index_from_indices = ${b.getByIndices("indices_indices")};
if (index_from_indices < 0) {
index_from_indices += ${t[n]};
}
${f.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};
for (var i = uniforms.gather_axis + 1; i < ${i.length}; i++) {
let index = ${y.indicesGet("output_indices",`i + ${s.length} - 1`)};
${f.indicesSet("data_indices","i","index")};
}
let data_offset = ${f.indicesToOffset("data_indices")};
let data_index = data_offset % 8;
// Convert 4-bit packed data to 8-bit packed data.
let packed_4bit_quantized_data = ${f.getByOffset("data_offset / 8")};
let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;
let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));
let quantized_data = quantized_data_vec[data_index / 2];
var scale_indices = data_indices;
let quantize_axis_index = ${A.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;
${A.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};
var scale = ${A.getByIndices("scale_indices")};
${g?`
let zero_point_indices = scale_indices;
let zero_point_offset = ${g.indicesToOffset("zero_point_indices")};
let zero_point_index = zero_point_offset % 8;
let packed_4bit_zero_points = ${g.getByOffset("zero_point_offset / 8")};
let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
let dequantized_data = ${jr(c)}(quantized_data - zero_point) * scale;
${y.setByOffset("global_idx","dequantized_data")};
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((_,f)=>f!==1).map(_=>_.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(_,f)=>"rank")},getRunData:()=>({outputs:[{dims:i,dataType:c}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},Ff=(e,r)=>{let t=e.inputs;kf(t,r),e.compute(If(e.inputs,r))},Of=e=>jt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Df,Lf,zf,Rf,_T=Ue(()=>{Mt(),Pt(),ur(),Ct(),Df=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and
indices input tensors be of same rank.`)},Lf=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,a=e[1].dataType,i=Pe.normalizeAxis(r.axis,o),l=t[i],c=n.slice(0),p=Pe.size(c),d=Oe("input",s,o),u=Oe("indicesInput",a,n.length),_=at("output",s,c.length),f=[{type:12,data:p},{type:6,data:l},{type:12,data:i}];return f.push(...lt(t,n,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:b=>`
${b.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,u,_)}
${b.mainStart()}
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
let outputIndices = ${_.offsetToIndices("global_idx")};
var idx = ${u.getByOffset("global_idx")};
if (idx < 0) {
idx = idx + uniforms.axisDimLimit;
}
var inputIndices = ${d.type.indices}(outputIndices);
${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")};
let value = ${d.getByIndices("inputIndices")};
${_.setByOffset("global_idx","value")};
}`}},zf=e=>jt({axis:e.axis}),Rf=(e,r)=>{let t=e.inputs;Df(t),e.compute(Lf(e.inputs,r))}}),Bf,Nf,jf,Vf,gT=Ue(()=>{Mt(),Pt(),Ct(),Bf=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Nf=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,a]=Xd.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),i=[o,n];if(!i)throw new Error("Can't use gemm on the given tensors");let l=16,c=Math.ceil(n/l),p=Math.ceil(o/l),d=!0,u=Pe.size(i),_=[{type:12,data:d?c:u},{type:12,data:o},{type:12,data:n},{type:12,data:a},{type:1,data:r.alpha},{type:1,data:r.beta}],f=["type","type"];e.length===3&&(_.push(...lt(e[2].dims)),f.push("rank")),_.push(...lt(i));let b=g=>{let y="";r.transA&&r.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let C=r.alpha===1?"":"value *= uniforms.alpha;",x=Oe("a",e[0].dataType,e[0].dims),M=Oe("b",e[1].dataType,e[1].dims),T=x.type.value,v=null,P=[x,M];e.length===3&&(v=Oe("c",e[2].dataType,e[2].dims.length),P.push(v));let F=at("output",e[0].dataType,i.length);P.push(F);let D=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return`
${g.registerUniforms(D).declareVariables(...P)}
${g.mainStart()}
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let m = global_idx / uniforms.N;
let n = global_idx % uniforms.N;
var value = ${T}(0);
for (var k: u32 = 0u; k < uniforms.K; k++) {
${y}
}
${C}
${v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",F)}; value += ${T}(uniforms.beta) * ${v.getByOffset("cOffset")};`:""}
output[global_idx] = value;
}`},A=g=>{let y=Oe("a",e[0].dataType,e[0].dims),C=Oe("b",e[1].dataType,e[1].dims),x=null,M=[y,C];e.length===3&&(x=Oe("c",e[2].dataType,e[2].dims.length),M.push(x));let T=at("output",e[0].dataType,i.length);M.push(T);let v=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],P="",F="";r.transA&&r.transB?(F=`
var col = tile_row_start + local_id.x;
var row = k_start + local_id.y;
if (col < uniforms.M && row < uniforms.K) {
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
} else {
tile_a[local_id.y][local_id.x] = ${y.type.value}(0);
}
col = k_start + local_id.x;
row = tile_col_start + local_id.y;
if (col < uniforms.K && row < uniforms.N) {
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
} else {
tile_b[local_id.y][local_id.x] = ${C.type.value}(0);
}
`,P="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(F=`
var col = tile_row_start + local_id.x;
var row = k_start + local_id.y;
if (col < uniforms.M && row < uniforms.K) {
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
} else {
tile_a[local_id.y][local_id.x] = ${y.type.value}(0);
}
col = tile_col_start + local_id.x;
row = k_start + local_id.y;
if (col < uniforms.N && row < uniforms.K) {
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
} else {
tile_b[local_id.y][local_id.x] = ${C.type.value}(0);
}
`,P="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(F=`
var col = k_start + local_id.x;
var row = tile_row_start + local_id.y;
if (col < uniforms.K && row < uniforms.M) {
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
} else {
tile_a[local_id.y][local_id.x] = ${y.type.value}(0);
}
col = k_start + local_id.x;
row = tile_col_start + local_id.y;
if (col < uniforms.K && row < uniforms.N) {
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
} else {
tile_b[local_id.y][local_id.x] = ${C.type.value}(0);
}
`,P="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(F=`
var col = k_start + local_id.x;
var row = tile_row_start + local_id.y;
if (col < uniforms.K && row < uniforms.M) {
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
} else {
tile_a[local_id.y][local_id.x] = ${y.type.value}(0);
}
col = tile_col_start + local_id.x;
row = k_start + local_id.y;
if (col < uniforms.N && row < uniforms.K) {
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
} else {
tile_b[local_id.y][local_id.x] = ${C.type.value}(0);
}
`,P="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let D=r.alpha===1?"":"value *= uniforms.alpha;";return`
${g.registerUniforms(v).declareVariables(...M)}
var tile_a: array, ${l}>;
var tile_b: array, ${l}>;
${g.mainStart([l,l,1])}
let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${l};
let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${l};
let num_tiles = (uniforms.K - 1) / ${l} + 1;
var k_start = 0u;
var value = ${T.type.value}(0);
for (var t: u32 = 0u; t < num_tiles; t++) {
${F}
k_start = k_start + ${l};
workgroupBarrier();
for (var k: u32 = 0u; k < ${l}; k++) {
${P}
}
workgroupBarrier();
}
${D}
let m = tile_row_start + local_id.y;
let n = tile_col_start + local_id.x;
${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",T)}; value += ${T.type.value}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""}
if (m < uniforms.M && n < uniforms.N) {
output[m * uniforms.N + n] = value;
}
}`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:_}),getShaderSource:A}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:_}),getShaderSource:b}},jf=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Vf=(e,r)=>{Bf(e.inputs),e.compute(Nf(e.inputs,r))}}),Fs,Vs,bn,yn,Uf,Wf,Gf,Hf,Kf,qf,Qf,Xf,Jf,Yf,wT=Ue(()=>{Mt(),Pt(),ur(),Ct(),[Fs,Vs,bn,yn]=[0,1,2,3],Uf=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},Wf=`
fn gs_get_cubic_coeffs(x: f32) -> vec4 {
let cubic_alpha = -0.75f;
let x_abs = abs(x);
var coeffs: vec4;
coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);
coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);
coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);
coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);
return coeffs;
}
`,Gf=e=>`
fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {
var v: vec4;
var coeffs = gs_get_cubic_coeffs(x);
for (var i = 0; i < 4; i++) {
v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];
}
coeffs = gs_get_cubic_coeffs(y);
let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);
return pixel;
}
`,Hf=e=>`
fn gs_denormalize(n: f32, length: i32) -> f32 {
${e.alignCorners===0?`
// alignCorners: false => [-1, 1] to [-0.5, length - 0.5]
return ((n + 1.0) * f32(length) - 1.0) / 2.0;
`:`
// alignCorners: true => [-1, 1] to [0, length - 1]
return (n + 1.0) / 2.0 * (f32(length - 1));
`}
}
`,Kf=e=>`
${e.paddingMode==="reflection"?`
fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {
var dx = 0.0;
var fx = f32(x);
let range = x_max - x_min;
if (fx < x_min) {
dx = x_min - fx;
let n = u32(dx / range);
let r = dx - f32(n) * range;
if (n % 2 == 0) {
fx = x_min + r;
} else {
fx = x_max - r;
}
} else if (fx > x_max) {
dx = fx - x_max;
let n = u32(dx / range);
let r = dx - f32(n) * range;
if (n % 2 == 0) {
fx = x_max - r;
} else {
fx = x_min + r;
}
}
return u32(fx);
}`:""}
`,qf=(e,r,t)=>`
fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${r} {
var pixel = ${r}(0);
var indices = vec4(0);
indices[${Fs}] = batch;
indices[${Vs}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return`
if (r >= 0 && r < H && c >=0 && c < W) {
indices[${bn}] = u32(r);
indices[${yn}] = u32(c);
} else {
return ${r}(0);
}
`;case"border":return`
indices[${bn}] = u32(clamp(r, 0, H - 1));
indices[${yn}] = u32(clamp(c, 0, W - 1));
`;case"reflection":return`
indices[${bn}] = gs_reflect(r, border[1], border[3]);
indices[${yn}] = gs_reflect(c, border[0], border[2]);
`;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+`
return ${e.getByIndices("indices")};
}
`,Qf=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return`
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Fs}], indices[${Vs}], border);
`;case"bilinear":return`
let x1 = i32(floor(x));
let y1 = i32(floor(y));
let x2 = x1 + 1;
let y2 = y1 + 1;
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Fs}], indices[${Vs}], border);
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Fs}], indices[${Vs}], border);
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Fs}], indices[${Vs}], border);
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Fs}], indices[${Vs}], border);
let dx2 = ${r}(f32(x2) - x);
let dx1 = ${r}(x - f32(x1));
let dy2 = ${r}(f32(y2) - y);
let dy1 = ${r}(y - f32(y1));
let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);
`;case"bicubic":return`
let x0 = i32(floor(x)) - 1;
let y0 = i32(floor(y)) - 1;
var p: mat4x4<${r}>;
for (var h = 0; h < 4; h++) {
for (var w = 0; w < 4; w++) {
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Fs}], indices[${Vs}], border);
}
}
let dx = x - f32(x0 + 1);
let dy = y - f32(y0 + 1);
let result = gs_bicubic_interpolate(p, dx, dy);
`;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Xf=(e,r)=>{let t=Oe("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Oe("grid",e[1].dataType,s.length,2),n=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(n=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Fs,Vs,bn,yn]=[0,3,1,2]);let a=at("output",e[0].dataType,n.length),i=t.type.value,l=Pe.size(n),c=[{type:12,data:l},...lt(e[0].dims,s,n)],p=d=>`
${d.registerUniform("output_size","u32").declareVariables(t,o,a)}
${Wf}
${Gf(i)}
${Hf(r)}
${Kf(r)}
${qf(t,i,r)}
${d.mainStart()}
${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let H_in = i32(uniforms.x_shape[${bn}]);
let W_in = i32(uniforms.x_shape[${yn}]);
${r.alignCorners===0?`
let x_min = -0.5;
let x_max = f32(W_in) - 0.5;
let y_min = -0.5;
let y_max = f32(H_in) - 0.5;
`:`
let x_min = 0.0;
let x_max = f32(W_in) - 1.0;
let y_min = 0.0;
let y_max = f32(H_in) - 1.0;
`};
let border = vec4(x_min, y_min, x_max, y_max);
let indices = ${a.offsetToIndices("global_idx")};
var grid_indices = vec3(indices[${Fs}], indices[${bn}], indices[${yn}]);
let nxy = ${o.getByIndices("grid_indices")};
var x = gs_denormalize(f32(nxy[0]), W_in);
var y = gs_denormalize(f32(nxy[1]), H_in);
${Qf(a,i,r)}
}`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let u=Pe.size(n);return{outputs:[{dims:n,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}},getShaderSource:p}},Jf=(e,r)=>{Uf(e.inputs),e.compute(Xf(e.inputs,r))},Yf=e=>jt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Kr,Zf,e_,Ul,t_,xo,r_,s_=Ue(()=>{Mt(),Pt(),ur(),ul(),bl(),Ct(),Ys(),Kr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,Zf=(e,r)=>{let t=e[0],s=Kr(e,1),o=Kr(e,2),n=Kr(e,3),a=Kr(e,4),i=Kr(e,5),l=Kr(e,6),c=Kr(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],d=t.dims[1],u=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],_=d,f=0,b=0,A=Math.floor(u/r.numHeads);if(l&&c&&Pe.size(l.dims)&&Pe.size(c.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==A)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==p||c.dims[1]!==r.numHeads||c.dims[3]!==A)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],b=l.dims[2]}else if(l&&Pe.size(l.dims)||c&&Pe.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g;if(s&&Pe.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');g=2,_=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==A)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');g=5,_=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==A)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');g=0,_=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');g=3}if(n&&Pe.size(n.dims)>0){if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let y=f+_,C=0;if(a&&Pe.size(a.dims)>0){C=8;let v=a.dims;throw v.length===1?v[0]===p?C=1:v[0]===3*p+2&&(C=3):v.length===2&&v[0]===p&&v[1]===y&&(C=5),C===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let x=!1,M=u;if(o&&Pe.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');M=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');M=o.dims[1]*o.dims[3],x=!0}}let T=!1;if(a&&Pe.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(i&&Pe.size(i.dims)>0){if(i.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(i.dims[0]!==p||i.dims[1]!==r.numHeads||i.dims[2]!==d||i.dims[3]!==y)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:f,kvSequenceLength:_,totalSequenceLength:y,maxSequenceLength:b,inputHiddenSize:0,hiddenSize:u,vHiddenSize:M,headSize:A,vHeadSize:Math.floor(M/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:C,scale:r.scale,broadcastResPosBias:T,passPastInKv:x,qkvFormat:g}},e_=e=>jt({...e}),Ul=jt({perm:[0,2,1,3]}),t_=(e,r,t,s,o,n,a)=>{let i=[s,o,n],l=Pe.size(i),c=[{type:12,data:l},{type:12,data:a},{type:12,data:n}],p=d=>{let u=at("qkv_with_bias",r.dataType,i),_=Oe("qkv",r.dataType,i),f=Oe("bias",t.dataType,i),b=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
${d.registerUniforms(b).declareVariables(_,f,u)}
${d.mainStart()}
${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
}`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:i,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},xo=(e,r,t,s,o,n,a,i)=>{let l=n;if(a&&Pe.size(a.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=t_(e,n,a,r,s,t*o,i),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(rs(l,Ul.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(rs(l,Ul.perm),{inputs:[l],outputs:[-1]})[0]},r_=(e,r)=>{let t=Zf(e.inputs,r),s=e.inputs[0],o=Kr(e.inputs,1),n=Kr(e.inputs,2),a=Kr(e.inputs,3),i=Kr(e.inputs,4),l=Kr(e.inputs,5),c=Kr(e.inputs,6),p=Kr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let d=o&&n&&o.dims.length===4&&n.dims.length===4,u=xo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,a,0);if(d)return wo(e,u,o,n,i,void 0,c,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let _=xo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,a,t.hiddenSize),f=xo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,a,2*t.hiddenSize);wo(e,u,_,f,i,void 0,c,p,l,t)}}),n_,o_,a_,i_,Wl,l_,u_,c_=Ue(()=>{Mt(),Pt(),ur(),Ct(),n_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},o_=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>t.push(Number(o))),s=t.length),jt({numOutputs:s,axis:r.axis,splitSizes:t})},a_=e=>`
fn calculateOutputIndex(index: u32) -> u32 {
for (var i: u32 = 0u; i < ${e}u; i += 1u ) {
if (index < ${it("uniforms.size_in_split_axis","i",e)}) {
return i;
}
}
return ${e}u;
}`,i_=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=Pe.size(t),o=e[0].dataType,n=Pe.normalizeAxis(r.axis,t.length),a=new Array(r.numOutputs),i=Oe("input",o,t.length),l=new Array(r.numOutputs),c=[],p=[],d=0,u=[{type:12,data:s}];for(let f=0;f`
${f.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(i,...a)}
${a_(l.length)}
${i_(a)}
${f.mainStart()}
${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}
var indices = ${i.offsetToIndices("global_idx")};
var index = ${i.indicesGet("indices",n)};
let output_number = calculateOutputIndex(index);
if (output_number != 0) {
index -= ${it("uniforms.size_in_split_axis","output_number - 1u",l.length)};
${i.indicesSet("indices",n,"index")};
}
writeBufferData(output_number, indices, global_idx);
}`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},l_=(e,r)=>{n_(e.inputs);let t=e.inputs.length===1?r:o_(e.inputs,r);e.compute(Wl(e.inputs,t),{inputs:[0]})},u_=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return jt({axis:r,numOutputs:s,splitSizes:t})}}),d_,ba,p_,h_=Ue(()=>{Mt(),Pt(),ur(),Ct(),d_=(e,r)=>{let[t,s,o,n]=e,{numHeads:a,rotaryEmbeddingDim:i}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!Pe.areEqual(s.dims,[])&&!Pe.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!Pe.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(i>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],c=t.dims[t.dims.length-2],p=o.dims[0],d=Pe.sizeFromDimension(t.dims,1)/c,u=i===0?o.dims[1]*2:d/a;if(i>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(c!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(u/2!==o.dims[1]&&i/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(c>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},ba=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,a=e[0].dims[0],i=Pe.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],c=i/l,p=e[2].dims[1],d=o===0?p*2:c/s,u=new Array(a,l,c/d,d-p),_=Pe.computeStrides(u),f=[{type:1,data:n},{type:12,data:u},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[i,c,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[i,d,l*d,1]}):[],...lt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],b=A=>{let g=Oe("input",e[0].dataType,e[0].dims.length),y=Oe("position_ids",e[1].dataType,e[1].dims.length),C=Oe("cos_cache",e[2].dataType,e[2].dims.length),x=Oe("sin_cache",e[3].dataType,e[3].dims.length),M=at("output",e[0].dataType,e[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),`
${A.declareVariables(g,y,C,x,M)}
${A.mainStart(Hn)}
let half_rotary_emb_dim = uniforms.${C.name}_shape[1];
let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;
let size = uniforms.global_shape[0] * uniforms.global_strides[0];
${A.guardAgainstOutOfBoundsWorkgroupSizes("size")}
if (bsnh[3] < half_rotary_emb_dim) {
let position_ids_idx =
${y.broadcastedIndicesToOffset("bsnh.xy",at("",y.type.tensor,2))};
let position_id =
u32(${y.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);
let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t});
let j = i + select(half_rotary_emb_dim, 1, ${t});
let re = ${g.getByOffset("i")} * ${C.get("position_id","bsnh[3]")} -
${g.getByOffset("j")} * ${x.get("position_id","bsnh[3]")};
${M.setByOffset("i","re")}
let im = ${g.getByOffset("i")} * ${x.get("position_id","bsnh[3]")} +
${g.getByOffset("j")} * ${C.get("position_id","bsnh[3]")};
${M.setByOffset("j","im")}
} else {
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
${M.setByOffset("k",g.getByOffset("k"))}
}
}`};return{name:"RotaryEmbedding",shaderCache:{hint:jt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Pe.size(u)/Hn)},programUniforms:f})}},p_=(e,r)=>{d_(e.inputs,r),e.compute(ba(e.inputs,r))}}),m_,f_,Gl,__,g_,MT=Ue(()=>{ur(),Mt(),bl(),s_(),c_(),Ys(),h_(),Ct(),m_=(e,r)=>{if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],o=e[2],n=e[3],a=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let i=!1,l=t.dims[0],c=t.dims[1],p=t.dims.length===3?i?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=c,u=0,_=!s||s.dims.length===0,f=Math.floor(_?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);_&&(p=f*r.numHeads);let b=n&&n.dims.length!==0,A=a&&a.dims.length!==0;if(b&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===f)throw new Error("BSNH pastKey/pastValue is not supported");if(b&&A){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=n.dims[2]}else if(b||A)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==f)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');d=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==f)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');g=3}let y=0,C=!1,x=r.kvNumHeads?f*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(d!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');x=o.dims[2]}else{if(d!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');x=o.dims[1]*o.dims[3],C=!0}}let M=e.length>4?e[5]:void 0;if(M&&M.dims.length!==1&&M.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:c,pastSequenceLength:u,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:x,headSize:f,vHeadSize:Math.floor(x/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:C,qkvFormat:g}},f_=jt({perm:[0,2,1,3]}),Gl=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(rs(s,f_.perm),{inputs:[s],outputs:[-1]})[0]),s},__=(e,r,t,s)=>{let o=7,n=["type","type"],a=[e*r],i=e*r,l=[{type:12,data:i},{type:12,data:r},{type:12,data:e}],c=p=>{let d=Oe("seq_lens",t.dataType,t.dims),u=Oe("total_seq_lens",s.dataType,s.dims),_=at("pos_ids",o,a),f=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
${p.registerUniforms(f).declareVariables(d,u,_)}
${p.mainStart()}
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let total_sequence_length = u32(${u.getByOffset("0")});
let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length;
let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length;
let batch_idx = global_idx / uniforms.sequence_length;
let sequence_idx = i32(global_idx % uniforms.sequence_length);
var pos_id: i32 = 0;
let seqlen = ${d.getByOffset("batch_idx")};
let total_seqlen = seqlen + 1;
if (is_first_prompt) {
if (sequence_idx < total_seqlen) {
pos_id = sequence_idx;
} else {
pos_id = 1;
}
${_.setByOffset("global_idx","pos_id")}
} else if (is_subsequent_prompt) {
let past_seqlen = total_seqlen - i32(uniforms.sequence_length);
if (past_seqlen + sequence_idx < total_seqlen) {
pos_id = past_seqlen + sequence_idx;
} else {
pos_id = 1;
}
${_.setByOffset("global_idx","pos_id")}
} else if (global_idx < uniforms.batch_size) {
${_.setByOffset("global_idx","seqlen")}
};
}
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:l}),getShaderSource:c}},g_=(e,r)=>{var x;let t=m_(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((x=e.inputs[1])==null?void 0:x.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,n=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,i=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=jt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[u,_,f]=!o&&!n?e.compute(Wl([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],b,A;if(r.doRotary){let M=e.compute(__(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],T=e.inputs[7],v=e.inputs[8],P=jt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),F=[u,M,T,v],D=[-1];b=e.compute(ba(F,P),{inputs:F,outputs:D})[0],F.splice(0,1,_);let K=jt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});A=e.compute(ba(F,K),{inputs:F,outputs:D})[0]}let g=xo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?b:u,void 0,0),y=Gl(e,r.doRotary?A:_,t),C=Gl(e,f,t);wo(e,g,y,C,void 0,void 0,a,i,void 0,t,l,c)}}),Hl,w_,M_,b_,bT=Ue(()=>{Mt(),Pt(),Ys(),Ct(),Hl=(e,r,t,s,o,n,a,i)=>{let l=or(n),c=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=o*a,u=64;d===1&&(u=256);let _=[o,a,n/l],f=[o,a,2],b=["rank","type","type"],A=[];A.push(...lt(_,f));let g=y=>{let C=Oe("x",r.dataType,3,l),x=Oe("scale",t.dataType,t.dims),M=Oe("bias",s.dataType,s.dims),T=at("output",1,3,2),v=[C,x,M,T];return`
var workgroup_shared : array<${p}, ${u}>;
const workgroup_size = ${u}u;
${y.declareVariables(...v)}
${y.mainStart(u)}
let batch = workgroup_index / uniforms.x_shape[1];
let channel = workgroup_index % uniforms.x_shape[1];
let hight = uniforms.x_shape[2];
// initialize workgroup memory
var sum = ${c}(0);
var squared_sum = ${c}(0);
for (var h = local_idx; h < hight; h += workgroup_size) {
let value = ${c}(${C.get("batch","channel","h")});
sum += value;
squared_sum += value * value;
}
workgroup_shared[local_idx] = ${p}(sum, squared_sum);
workgroupBarrier();
for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {
if (local_idx < currSize) {
workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];
}
workgroupBarrier();
}
if (local_idx == 0) {
let sum_final = ${Js("workgroup_shared[0][0]",l)} / f32(hight * ${l});
let squared_sum_final = ${Js("workgroup_shared[0][1]",l)} / f32(hight * ${l});
let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${i}));
let channel_scale = inv_std_dev * f32(scale[channel]);
let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
output[workgroup_index] = vec2f(channel_scale, channel_shift);
}
}`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${i};${u}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:d},programUniforms:A}),getShaderSource:g},{inputs:[r,t,s],outputs:[-1]})[0]},w_=(e,r,t)=>{let s=r[0].dims,o=s,n=2,a=s[0],i=s[1],l=Pe.sizeFromDimension(s,n),c=or(l),p=Pe.size(o)/c,d=Hl(e,r[0],r[1],r[2],a,l,i,t.epsilon),u=[a,i,l/c],_=[a,i],f=["type","none"],b=A=>{let g=Oe("x",r[0].dataType,u.length,c),y=Oe("scale_shift",1,_.length,2),C=at("output",r[0].dataType,u.length,c),x=[g,y,C];return`
${A.registerUniform("output_size","u32").declareVariables(...x)}
${A.mainStart()}
${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let outputIndices = ${C.offsetToIndices("global_idx")};
let batch = outputIndices[0];
let channel = outputIndices[1];
let scale_shift = ${y.getByIndices("vec2(batch, channel)")};
let value = ${g.getByOffset("global_idx")} * ${C.type.value}(scale_shift.x) + ${C.type.value}(scale_shift.y);
${C.setByOffset("global_idx","value")};
}`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...lt(u,_,u)]}),getShaderSource:b},{inputs:[r[0],d]})},M_=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],a=s[s.length-1],i=Pe.sizeFromDimension(s,1)/a,l=or(a),c=Pe.size(o)/l,p=[{type:12,data:i},{type:12,data:Math.floor(a/l)}],d=["type","type"],u=!1,_=[0,s.length-1];for(let g=0;gs[_[y]])),b=Hl(e,f,r[1],r[2],n,i,a,t.epsilon),A=g=>{let y=Sr(r[0].dataType),C=l===1?"vec2f":`mat${l}x2f`,x=v=>{let P=v===0?"x":"y",F=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${y}(${F}(scale.${P}))`;case 2:return`vec2<${y}>(${F}(scale[0].${P}, scale[1].${P}))`;case 4:return`vec4<${y}>(${F}(scale[0].${P}, scale[1].${P}, scale[2].${P}, scale[3].${P}))`;default:throw new Error(`Not supported compoents ${l}`)}},M=Oe("input",r[0].dataType,r[0].dims,l),T=at("output",r[0].dataType,o,l);return`
@group(0) @binding(0) var input : array<${M.type.storage}>;
@group(0) @binding(1) var scale_input : array<${C}>;
@group(0) @binding(2) var output : array<${T.type.storage}>;
struct Uniforms {H: u32, C : u32};
@group(0) @binding(3) var uniforms: Uniforms;
${g.mainStart()}
let current_image_number = global_idx / (uniforms.C * uniforms.H);
let current_channel_number = global_idx % uniforms.C;
let scale_offset = current_image_number * uniforms.C + current_channel_number;
let scale = scale_input[scale_offset];
output[global_idx] = fma(input[global_idx], ${x(0)}, ${x(1)});
}`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:A},{inputs:[r[0],b]})},b_=(e,r)=>{r.format==="NHWC"?M_(e,e.inputs,r):w_(e,e.inputs,r)}}),y_,v_,x_,yT=Ue(()=>{Mt(),Pt(),Ct(),y_=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},v_=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],a=!s&&e[2],i=o,l=Pe.normalizeAxis(r.axis,o.length),c=Pe.sizeToDimension(o,l),p=Pe.sizeFromDimension(o,l),d=Pe.size(n.dims),u=a?Pe.size(a.dims):0;if(d!==p||a&&u!==p)throw new Error(`Size of X.shape()[axis:] == ${p}.
Size of scale and bias (if provided) must match this.
Got scale size of ${d} and bias size of ${u}`);let _=[];for(let M=0;M1,y=t>2,C=M=>{let T=Sr(e[0].dataType),v=[Oe("x",e[0].dataType,e[0].dims,f),Oe("scale",n.dataType,n.dims,f)];a&&v.push(Oe("bias",a.dataType,a.dims,f)),v.push(at("output",e[0].dataType,i,f)),g&&v.push(at("mean_data_output",1,_)),y&&v.push(at("inv_std_output",1,_));let P=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`
${M.registerUniforms(P).declareVariables(...v)}
${M.mainStart()}
${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
let offset = global_idx * uniforms.norm_size_vectorized;
var mean_vector = ${hl("f32",f)};
var mean_square_vector = ${hl("f32",f)};
for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
let value = ${Kn(T,f,"x[h + offset]")};
mean_vector += value;
mean_square_vector += value * value;
}
let mean = ${Js("mean_vector",f)} / uniforms.norm_size;
let inv_std_dev = inverseSqrt(${Js("mean_square_vector",f)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon);
for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
let f32input = ${Kn(T,f,"x[j + offset]")};
let f32scale = ${Kn(T,f,"scale[j]")};
output[j + offset] = ${v[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale
${a?`+ ${Kn(T,f,"bias[j]")}`:""}
);
}
${g?"mean_data_output[global_idx] = mean":""};
${y?"inv_std_output[global_idx] = inv_std_dev":""};
}`},x=[{dims:i,dataType:e[0].dataType}];return g&&x.push({dims:_,dataType:1}),y&&x.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${t};${s}`,inputDependencies:b},getRunData:()=>({outputs:x,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:A}),getShaderSource:C}},x_=(e,r)=>{y_(e.inputs),e.compute(v_(e.inputs,r,e.outputCount))}}),T_,E_,vT=Ue(()=>{Pt(),Sl(),Il(),T_=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},E_=e=>{T_(e.inputs);let r=Gn.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(Cl(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=Pe.size(e.inputs[0].dims.slice(0,-2)),a=Pe.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&a===1){let i=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),c=[1,n,t],p=[i,l];e.compute(_a(p,{activation:""},r,c),{inputs:p})}else e.compute(_a(e.inputs,{activation:""},r))}}}),P_,C_,S_,$_,A_,xT=Ue(()=>{Mt(),Pt(),ur(),Ct(),P_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,a=e[1];if(!Pe.areEqual(a.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let i=e[2].dims;if(Pe.size(i)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,c=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(Pe.size(l)!==c)throw new Error("zeroPoints input size error.")}},C_=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,a=r.n,i=t.slice(0,s-2),l=Pe.size(i),c=e[1].dims[2]/4,p=e[0].dataType,d=or(r.k),u=or(c),_=or(a),f=i.concat([o,a]),b=o>1&&a/_%2===0?2:1,A=Pe.size(f)/_/b,g=64,y=[],C=[l,o,n/d],x=Pe.convertShape(e[1].dims).slice();x.splice(-1,1,c/u),y.push(...lt(C)),y.push(...lt(x)),y.push(...lt(e[2].dims)),e.length===4&&y.push(...lt(Pe.convertShape(e[3].dims)));let M=[l,o,a/_];y.push(...lt(M));let T=v=>{let P=C.length,F=Oe("a",e[0].dataType,P,d),D=Oe("b",12,x.length,u),K=Oe("scales",e[2].dataType,e[2].dims.length),U=[F,D,K],j=e.length===4?Oe("zero_points",12,e[3].dims.length):void 0;j&&U.push(j);let ne=M.length,q=at("output",e[0].dataType,ne,_),te=Sr(e[0].dataType),Z=(()=>{switch(d){case 1:return`array<${te}, 8>`;case 2:return`mat4x2<${te}>`;case 4:return`mat2x4<${te}>`;default:throw new Error(`${d}-component is not supported.`)}})(),ae=()=>{let B=`
// reuse a data
var input_offset = ${F.indicesToOffset(`${F.type.indices}(batch, row, word_offset)`)};
var a_data: ${Z};
for (var j: u32 = 0; j < ${8/d}; j++) {
a_data[j] = ${F.getByOffset("input_offset")};
input_offset++;
}
`;for(let O=0;O<_*b;O++)B+=`
b_value = ${u===1?`b${O}_data`:`b${O}_data[i]`};
b_value_lower = unpack4xU8(b_value & b_mask);
b_value_upper = unpack4xU8((b_value >> 4) & b_mask);
b_quantized_values = ${Z}(${Array.from({length:4},(W,N)=>`${te}(b_value_lower[${N}]), ${te}(b_value_upper[${N}])`).join(", ")});
b_dequantized_values = ${d===1?`${Z}(${Array.from({length:8},(W,N)=>`(b_quantized_values[${N}] - ${j?`zero_point${O}`:"zero_point"}) * scale${O}`).join(", ")});`:`(b_quantized_values - ${Z}(${Array(8).fill(`${j?`zero_point${O}`:"zero_point"}`).join(",")})) * scale${O};`};
workgroup_shared[local_id.x * ${b} + ${Math.floor(O/_)}]${_>1?`[${O%_}]`:""} += ${Array.from({length:8/d},(W,N)=>`${d===1?`a_data[${N}] * b_dequantized_values[${N}]`:`dot(a_data[${N}], b_dequantized_values[${N}])`}`).join(" + ")};
`;return B},he=()=>{let B=`
var col_index = col * ${_};
${j?`
let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;
var zero_point_byte_count: u32;
var zero_point_word_index: u32;
var zero_point_byte_offset: u32;
let zero_point_nibble_offset: u32 = block & 0x1u;
var zero_point_bits_offset: u32;
var zero_point_word: u32;`:`
// The default zero point is 8 for unsigned 4-bit quantization.
let zero_point = ${te}(8);`}
`;for(let O=0;O<_*b;O++)B+=`
let scale${O} = ${K.getByOffset("col_index * nBlocksPerCol + block")};
${j?`
zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u);
zero_point_word_index = zero_point_byte_count >> 0x2u;
zero_point_byte_offset = zero_point_byte_count & 0x3u;
zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);
zero_point_word = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
let zero_point${O} = ${te}((zero_point_word) & 0xFu);`:""}
col_index += 1;`;return B},Q=()=>{let B=`col_index = col * ${_};`;for(let O=0;O<_*b;O++)B+=`
let b${O}_data = ${D.getByIndices(`${D.type.indices}(col_index, block, word)`)};
col_index += 1;`;return B+=`
var b_value: u32;
let b_mask: u32 = 0x0F0F0F0Fu;
var b_value_lower: vec4;
var b_value_upper: vec4;
var b_quantized_values: ${Z};
var b_dequantized_values: ${Z};`,B};return`
var workgroup_shared: array<${q.type.value}, ${b*g}>;
${v.declareVariables(...U,q)}
${v.mainStart([g,1,1])}
let output_indices = ${q.offsetToIndices(`(global_idx / ${g}) * ${b}`)};
let col = output_indices[2];
let row = output_indices[1];
let batch = output_indices[0];
let nBlocksPerCol = uniforms.b_shape[1];
for (var block = local_id.x; block < nBlocksPerCol; block += ${g}) {
//process one block
var word_offset: u32 = block * ${r.blockSize/d};
${he()}
for (var word: u32 = 0; word < ${c}; word += ${u}) {
${Q()}
for (var i: u32 = 0; i < ${u}; i++) {
${ae()}
word_offset += ${8/d};
}
}
}
workgroupBarrier();
if (local_id.x < ${b}) {
var output_value: ${q.type.value} = ${q.type.value}(0);
var workgroup_shared_offset: u32 = local_id.x;
for (var b: u32 = 0u; b < ${g}u; b++) {
output_value += workgroup_shared[workgroup_shared_offset];
workgroup_shared_offset += ${b};
}
${q.setByIndices(`${q.type.indices}(batch, row, col + local_id.x)`,"output_value")};
}
}`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${u};${_};${b};${g}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:A},programUniforms:y}),getShaderSource:T}},S_=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,a=r.n,i=t.slice(0,s-2),l=Pe.size(i),c=e[1].dims[2]/4,p=e[0].dataType,d=or(r.k),u=or(c),_=i.concat([o,a]),f=128,b=a%8===0?8:a%4===0?4:1,A=f/b,g=A*u*8,y=g/d,C=g/r.blockSize,x=Pe.size(_)/b,M=[],T=[l,o,n/d],v=Pe.convertShape(e[1].dims).slice();v.splice(-1,1,c/u),M.push(...lt(T)),M.push(...lt(v)),M.push(...lt(e[2].dims)),e.length===4&&M.push(...lt(Pe.convertShape(e[3].dims)));let P=[l,o,a];M.push(...lt(P));let F=D=>{let K=T.length,U=Oe("a",e[0].dataType,K,d),j=Oe("b",12,v.length,u),ne=Oe("scales",e[2].dataType,e[2].dims.length),q=[U,j,ne],te=e.length===4?Oe("zero_points",12,e[3].dims.length):void 0;te&&q.push(te);let Z=P.length,ae=at("output",e[0].dataType,Z),he=Sr(e[0].dataType),Q=()=>{switch(d){case 1:return`
let a_data0 = vec4<${he}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
let a_data1 = vec4<${he}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`
let a_data0 = vec4<${he}>(sub_a[word_offset], sub_a[word_offset + 1]);
let a_data1 = vec4<${he}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`
let a_data0 = sub_a[word_offset];
let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return`
var sub_a: array<${U.type.value}, ${y}>;
var inter_results: array, ${b}>;
${D.declareVariables(...q,ae)}
${D.mainStart([A,b,1])}
let output_indices = ${ae.offsetToIndices(`workgroup_index * ${b}`)};
let col = output_indices[2];
let row = output_indices[1];
let batch = output_indices[0];
let n_blocks_per_col = uniforms.b_shape[1];
let num_tiles = (n_blocks_per_col - 1) / ${C} + 1;
// Loop over shared dimension.
for (var tile: u32 = 0; tile < num_tiles; tile += 1) {
let a_col_start = tile * ${y};
// load one tile A data into shared memory.
for (var a_offset = local_idx; a_offset < ${y}; a_offset += ${f})
{
let a_col = a_col_start + a_offset;
if (a_col < uniforms.a_shape[2])
{
sub_a[a_offset] = ${U.getByIndices(`${U.type.indices}(batch, row, a_col)`)};
} else {
sub_a[a_offset] = ${U.type.value}(0);
}
}
workgroupBarrier();
// each thread process one block
let b_row = col + local_id.y;
let block = tile * ${C} + local_id.x;
${te?`
let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;
let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);
let zero_point_word_index = zero_point_byte_count >> 0x2u;
let zero_point_byte_offset = zero_point_byte_count & 0x3u;
let zero_point_nibble_offset: u32 = block & 0x1u;
let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);
let zero_point_word = ${te.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
let zero_point = ${he}((zero_point_word) & 0xFu);`:`
// The default zero point is 8 for unsigned 4-bit quantization.
let zero_point = ${he}(8);`}
let scale = ${ne.getByOffset("b_row * n_blocks_per_col + block")};
let b_data = ${j.getByIndices(`${j.type.indices}(b_row, block, 0)`)};
var word_offset = local_id.x * ${r.blockSize/d};
for (var i: u32 = 0; i < ${u}; i++) {
${Q()}
let b_value = ${u===1?"b_data":"b_data[i]"};
let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);
let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);
let b_quantized_values = mat2x4<${he}>(${Array.from({length:4},(B,O)=>`${he}(b_value_lower[${O}]), ${he}(b_value_upper[${O}])`).join(", ")});
let b_dequantized_values = (b_quantized_values - mat2x4<${he}>(${Array(8).fill("zero_point").join(",")})) * scale;
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(B,O)=>`${`dot(a_data${O}, b_dequantized_values[${O}])`}`).join(" + ")};
word_offset += ${8/d};
}
workgroupBarrier();
}
if (local_idx < ${b}) {
var output_value: ${ae.type.value} = ${ae.type.value}(0);
for (var b = 0u; b < ${A}; b++) {
output_value += inter_results[local_idx][b];
}
if (col + local_idx < uniforms.output_shape[2])
{
${ae.setByIndices(`${ae.type.indices}(batch, row, col + local_idx)`,"output_value")}
}
}
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${u};${A};${b}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x},programUniforms:M}),getShaderSource:F}},$_=(e,r)=>{P_(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(S_(e.inputs,r)):e.compute(C_(e.inputs,r))},A_=e=>jt(e)}),k_,I_,F_,O_,D_,L_,z_,R_,B_,TT=Ue(()=>{Mt(),Pt(),Ct(),k_=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},I_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=`
k = i32(${e.indicesGet("indices",o)}) - ${it("uniforms.pads",o,t)};
if (k < 0) {
break;
}
if (k >= i32(${it("uniforms.x_shape",o,r)})) {
break;
}
offset += k * i32(${it("uniforms.x_strides",o,r)});
`;return`
value = ${e.type.value}(uniforms.constant_value);
for (var i = 0; i < 1; i++) {
var offset = 0;
var k = 0;
${s}
value = x[offset];
}
`},F_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=`
k = i32(${e.indicesGet("indices",o)}) - ${it("uniforms.pads",o,t)};
if (k < 0) {
k = -k;
}
{
let _2n_1 = 2 * (i32(${it("uniforms.x_shape",o,r)}) - 1);
k = k % _2n_1;
if(k >= i32(${it("uniforms.x_shape",o,r)})) {
k = _2n_1 - k;
}
}
offset += k * i32(${it("uniforms.x_strides",o,r)});
`;return`
var offset = 0;
var k = 0;
${s}
value = x[offset];
`},O_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=`
k = i32(${e.indicesGet("indices",o)}) - ${it("uniforms.pads",o,t)};
if (k < 0) {
k = 0;
}
if (k >= i32(${it("uniforms.x_shape",o,r)})) {
k = i32(${it("uniforms.x_shape",o,r)}) - 1;
}
offset += k * i32(${it("uniforms.x_strides",o,r)});
`;return`
var offset = 0;
var k = 0;
${s}
value = x[offset];
`},D_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=`
k = i32(${e.indicesGet("indices",o)}) - ${it("uniforms.pads",o,t)};
if (k < 0) {
k += i32(${it("uniforms.x_shape",o,r)}]);
}
if (k >= i32(${it("uniforms.x_shape",o,r)})) {
k -= i32(${it("uniforms.x_shape",o,r)});
}
offset += k * i32(${it("uniforms.x_strides",o,r)});
`;return`
var offset = 0;
var k = 0;
${s}
value = x[offset];
`},L_=(e,r,t)=>{switch(t.mode){case 0:return I_(e,r,t.pads.length);case 1:return F_(e,r,t.pads.length);case 2:return O_(e,r,t.pads.length);case 3:return D_(e,r,t.pads.length);default:throw new Error("Invalid mode")}},z_=(e,r)=>{let t=Pe.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=Pe.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],a=e.length>=3&&e[2].data;r.mode===0&&n.push({type:a?e[2].dataType:1,data:r.value}),n.push(...lt(e[0].dims,t));let i=["rank"],l=c=>{let p=at("output",e[0].dataType,t.length),d=Oe("x",e[0].dataType,s.length),u=d.type.value,_=L_(p,s.length,r),f=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&f.push({name:"constant_value",type:a?u:"f32"}),`
${c.registerUniforms(f).declareVariables(d,p)}
${c.mainStart()}
${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let indices = ${p.offsetToIndices("global_idx")};
var value = ${u}(0);
${_}
output[global_idx] = value;
}`};return{name:"Pad",shaderCache:{hint:`${r.mode}${a}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Pe.size(t)/64)},programUniforms:n}),getShaderSource:l}},R_=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let i=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(i));let a=[];return n.forEach(i=>a.push(i)),{mode:r.mode,value:s,pads:a}}else return r},B_=(e,r)=>{k_(e.inputs);let t=R_(e.inputs,r);e.compute(z_(e.inputs,t),{inputs:[0]})}}),To,Kl,ql,Ql,Xl,N_,j_,Jl,Yl,V_,U_,Zl,W_,G_,eu,H_,K_,q_,Q_,ET=Ue(()=>{bs(),Mt(),Pt(),Ct(),To=e=>{if(Jt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Kl=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),a=r.kernelShape.slice(),i=r.strides.slice(),l=n?r.dilations.slice():[],c=r.pads.slice();la.adjustPoolAttributes(t,o,a,i,l,c);let p=la.computePoolOutputShape(t,o,i,l,a,c,r.autoPad),d=Object.assign({},r);n?Object.assign(d,{kernelShape:a,strides:i,pads:c,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:a,strides:i,pads:c,cacheKey:r.cacheKey});let u=p.slice();return u.push(u.splice(1,1)[0]),[d,s?u:p]},ql=(e,r)=>{let t=r.format==="NHWC",s=Pe.size(e),o=Pe.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let i=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],c=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(c+p);n.push({type:12,data:i},{type:12,data:l},{type:12,data:c},{type:12,data:p}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(r.kernelShape.length===2){let _=r.kernelShape[r.kernelShape.length-2],f=r.strides[r.strides.length-2],b=r.pads[r.pads.length/2-2],A=r.pads[r.pads.length-2];u=!!(b+A),n.push({type:12,data:_},{type:12,data:f},{type:12,data:b},{type:12,data:A}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,a,!0,d,u]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let i=Pe.computeStrides(r.kernelShape);n.push({type:12,data:i},{type:12,data:r.pads},{type:12,data:r.strides}),a.push({name:"kernelStrides",type:"u32",length:i.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((c,p)=>c+p);return[n,a,!!l,!1,!1]}},Ql=(e,r,t,s,o,n,a,i,l,c,p,d)=>{let u=o.format==="NHWC",_=r.type.value,f=at("output",r.type.tensor,s);if(o.kernelShape.length<=2){let b="",A="",g="",y=t-(u?2:1);if(p?b=`
for (var i: u32 = 0u; i < uniforms.kw; i++) {
xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i;
if (xIndices[${y}] < 0 || xIndices[${y}]
>= uniforms.x_shape[${y}]) {
pad++;
continue;
}
let x_val = x[${r.indicesToOffset("xIndices")}];
${n}
}`:b=`
for (var i: u32 = 0u; i < uniforms.kw; i++) {
xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i;
let x_val = x[${r.indicesToOffset("xIndices")}];
${n}
}`,o.kernelShape.length===2){let C=t-(u?3:2);d?A=`
for (var j: u32 = 0u; j < uniforms.kh; j++) {
xIndices[${C}] = indices[${C}] * uniforms.sh - uniforms.phStart + j;
if (xIndices[${C}] < 0 || xIndices[${C}] >= uniforms.x_shape[${C}]) {
pad += i32(uniforms.kw);
continue;
}
`:A=`
for (var j: u32 = 0u; j < uniforms.kh; j++) {
xIndices[${C}] = indices[${C}] * uniforms.sh - uniforms.phStart + j;
`,g=`
}
`}return`
${e.registerUniforms(l).declareVariables(r,f)}
${e.mainStart()}
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
let indices = ${f.offsetToIndices("global_idx")};
var xIndices = ${f.offsetToIndices("global_idx")};
var value = ${_}(${i});
var pad = 0;
${A}
${b}
${g}
${a}
output[global_idx] = value;
}`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let b=o.kernelShape.length,A=o.pads.length,g="";return c?g=`
if (xIndices[j] >= uniforms.x_shape[j]) {
pad++;
isPad = true;
break;
}
}
if (!isPad) {
let x_val = x[${r.indicesToOffset("xIndices")}];
${n}
}`:g=`
}
let x_val = x[${r.indicesToOffset("xIndices")}];
${n}
`,`
${e.registerUniforms(l).declareVariables(r,f)}
${e.mainStart()}
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
let indices = ${f.offsetToIndices("global_idx")};
var xIndices = ${f.offsetToIndices("global_idx")};
var offsets: array;
var value = ${_}(${i});
var pad = 0;
var isPad = false;
for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {
var offset = i;
for (var j = 0u; j < ${b-1}u; j++) {
offsets[j] = offset / ${it("uniforms.kernelStrides","j",b)};
offset -= offsets[j] * ${it("uniforms.kernelStrides","j",b)};
}
offsets[${b-1}] = offset;
isPad = false;
for (var j = ${t-b}u; j < ${t}u; j++) {
xIndices[j] = indices[j] * ${it("uniforms.strides",`j - ${t-b}u`,b)}
+ offsets[j - ${t-b}u] - ${it("uniforms.pads","j - 2u",A)};
${g}
}
${a}
output[global_idx] = value;
}`}},Xl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,N_=e=>`${Xl(e)};${e.countIncludePad}`,j_=e=>`${Xl(e)};${e.storageOrder};${e.dilations}`,Jl=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Yl=(e,r,t,s)=>{let[o,n]=Kl(r,s,t),a=Oe("x",r.dataType,r.dims.length),i=a.type.value,l="value += x_val;",c="";o.countIncludePad?c+=`value /= ${i}(uniforms.kernelSize);`:c+=`value /= ${i}(i32(uniforms.kernelSize) - pad);`;let[p,d,u,_,f]=ql(n,o);p.push(...lt(r.dims,n));let b=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${u};${_};${f}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Pe.size(n)/64)},programUniforms:p}),getShaderSource:A=>Ql(A,a,r.dims.length,n.length,o,l,c,0,d,u,_,f)}},V_=e=>{let r=e.count_include_pad!==0,t=Jl(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:N_(s)}},U_=(e,r)=>{To(e.inputs),e.compute(Yl("AveragePool",e.inputs[0],!1,r))},Zl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},W_=e=>{let r=e.format;return{format:r,...Zl,cacheKey:r}},G_=(e,r)=>{To(e.inputs),e.compute(Yl("GlobalAveragePool",e.inputs[0],!0,r))},eu=(e,r,t,s)=>{let[o,n]=Kl(r,s,t),a=`
value = max(x_val, value);
`,i="",l=Oe("x",r.dataType,r.dims.length),c=["rank"],[p,d,u,_,f]=ql(n,o);return p.push(...lt(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${u};${_};${f}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Pe.size(n)/64)},programUniforms:p}),getShaderSource:b=>Ql(b,l,r.dims.length,n.length,o,a,i,r.dataType===10?-65504:-1e5,d,u,_,f)}},H_=(e,r)=>{To(e.inputs),e.compute(eu("MaxPool",e.inputs[0],!1,r))},K_=e=>{let r=e.storage_order,t=e.dilations,s=Jl(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:j_(o)}},q_=e=>{let r=e.format;return{format:r,...Zl,cacheKey:r}},Q_=(e,r)=>{To(e.inputs),e.compute(eu("GlobalMaxPool",e.inputs[0],!0,r))}}),X_,J_,Y_,Z_,PT=Ue(()=>{Mt(),Pt(),ur(),Ct(),X_=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&n,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},J_=(e,r)=>{let t=Pe.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,a=e[1].dataType,i=Pe.size(n),l=s===3||s===2,c=l?[Math.ceil(Pe.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,u=d?l?[Math.ceil(Pe.size(d.dims)/4)]:d.dims:void 0,_=p.length===0||p.length===1&&p[0]===1,f=_===!1&&p.length===1,b=or(i),A=_&&(!l||b===4),g=A?b:1,y=A&&!l?b:1,C=Oe("input",l?12:s,c.length,y),x=Oe("scale",a,p.length),M=d?Oe("zero_point",l?12:s,u.length):void 0,T=at("output",a,n.length,g),v=[C,x];M&&v.push(M);let P=[c,p];d&&P.push(u);let F=[{type:12,data:i/g},{type:12,data:t},{type:12,data:r.blockSize},...lt(...P,n)],D=K=>{let U=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
${K.registerUniforms(U).declareVariables(...v,T)}
${K.mainStart()}
${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let output_indices = ${T.offsetToIndices("global_idx")};
// Set input x
${l?`
let input = ${C.getByOffset("global_idx / 4")};
let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"};
let x_value = ${g===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${C.getByOffset("global_idx")};`};
// Set scale input
${_?`let scale_value= ${x.getByOffset("0")}`:f?`
let scale_index = ${T.indicesGet("output_indices","uniforms.axis")};
let scale_value= ${x.getByOffset("scale_index")};`:`
var scale_indices: ${x.type.indices} = output_indices;
let index = ${x.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;
${x.indicesSet("scale_indices","uniforms.axis","index")};
let scale_value= ${x.getByIndices("scale_indices")};`};
// Set zero-point input
${M?_?l?`
let zero_point_input = ${M.getByOffset("0")};
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${M.getByOffset("0")}`:f?l?`
let zero_point_index = ${T.indicesGet("output_indices","uniforms.axis")};
let zero_point_input = ${M.getByOffset("zero_point_index / 4")};
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
let zero_point_value = zero_point_vec[zero_point_index % 4]`:`
let zero_point_index = ${T.indicesGet("output_indices","uniforms.axis")};
let zero_point_value = ${M.getByOffset("zero_point_index")};`:l?`
let zero_point_offset = ${x.indicesToOffset("scale_indices")};
let zero_point_input = ${M.getByOffset("zero_point_offset / 4")};
let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${M.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":C.type.value}(0);`};
// Compute and write output
${T.setByOffset("global_idx",`${T.type.value}(x_value - zero_point_value) * scale_value`)};
}`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:M?["rank","rank","rank"]:["rank","rank"]},getShaderSource:D,getRunData:()=>({outputs:[{dims:n,dataType:a}],dispatchGroup:{x:Math.ceil(i/g/64),y:1,z:1},programUniforms:F})}},Y_=(e,r)=>{X_(e.inputs,r),e.compute(J_(e.inputs,r))},Z_=e=>jt({axis:e.axis,blockSize:e.blockSize})}),eg,tg,rg,CT=Ue(()=>{bs(),Mt(),Ct(),eg=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},tg=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],a=o,i=[{type:12,data:a},{type:s,data:e},{type:s,data:t},...lt(n)],l=c=>{let p=at("output",s,n.length),d=p.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return`
${c.registerUniforms(u).declareVariables(p)}
${c.mainStart()}
${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta;
}`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:i})}},rg=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Jt.webgpu.validateInputContent&&eg(r,t,s),e.compute(tg(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),sg,tu,ru,ng,og,ag,ST=Ue(()=>{Mt(),Pt(),ur(),Ct(),sg=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let o=`{
var oldValue = 0;
loop {
let newValueF32 =`,n=`;
let newValue = bitcast(newValueF32);
let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue);
if res.exchanged {
break;
}
oldValue = res.old_value;
}
}`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:`
${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:`
${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},tu=(e,r)=>`${e===1?`
let element_count_dim = uniforms.output_strides;
let dim_value = uniforms.output_shape;`:`
let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}];
let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`}
if (index >= 0) {
if (index >= i32(dim_value)) {
index = i32(dim_value - 1);
}
} else {
if (index < -i32(dim_value)) {
index = 0;
} else {
index += i32(dim_value);
}
}
data_offset += u32((u32(index) * element_count_dim));`,ru=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) {
let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i];
${sg(e.reduction,"output[data_offset + i]","value",r)}
}`,ng=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,a=Math.ceil(Pe.size(s)/n),i=s[s.length-1],l=Pe.sizeFromDimension(t,i),c=Pe.sizeFromDimension(s,0)/i,p=[{type:12,data:a},{type:12,data:i},{type:12,data:l},...lt(e[1].dims,e[2].dims,o)],d=u=>{let _=Oe("indices",e[1].dataType,e[1].dims.length),f=Oe("updates",e[2].dataType,e[2].dims.length,n),b=r.reduction!=="none"&&r.reduction!==""?dp("output",e[0].dataType,o.length):at("output",e[0].dataType,o.length,n);return`
${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(_,f,b)}
${u.mainStart()}
${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
var hasDuplicates = false;
if (${r.reduction==="none"}) {
for (var i = 0; i < ${c}; i = i + 1) {
for (var j = i + 1; j < ${c}; j = j + 1) {
var index_i = i32(indices[i].x);
var index_j = i32(indices[j].x);
if (index_i == index_j) {
hasDuplicates = true;
break;
}
}
if (hasDuplicates) {
break;
}
}
}
if (${r.reduction==="none"} && hasDuplicates) {
if (global_idx != 0u) {
return;
}
// Process each index-update pair individually when duplicates exist
for (var idx = 0u; idx < ${c}u; idx++) {
var data_offset = 0u;
for (var i = 0u; i < uniforms.last_index_dimension; i++) {
var index = i32(indices[idx * uniforms.last_index_dimension + i].x);
${tu(t.length,!1)}
}
${ru(r,b.type.value,!1)}
}
return;
}
var data_offset = 0u;
var indices_start = uniforms.last_index_dimension * global_idx;
var indices_end = indices_start + uniforms.last_index_dimension;
for (var i = indices_start; i < indices_end; i++) {
var index = i32(indices[i].x);
${tu(t.length,!0)}
}
${ru(r,b.type.value,!0)}
}`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:d}},og=e=>jt({reduction:e.reduction}),ag=(e,r)=>{e.compute(ng(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),ig,lg,ug,su,cg,dg,pg,hg,mg,fg,_g,gg,nu,wg,Mg,bg,yg,vg,xg,Tg,$T=Ue(()=>{Mt(),Pt(),ur(),Ct(),ig=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(r.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},lg=(e,r,t)=>{r.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((o,n)=>s[o]=e[n]),s},ug=(e,r,t,s,o,n)=>{let[a,i,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(p=>n.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(i>0&&e.length>i&&e[i].dims.length===1&&e[i].dims[0]>0){if(e[i].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==c&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");ig(s,r),r.axes.length>0&&lg(s,r.axes,c).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==c&&t>=18&&o.length!==r.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof o<"u"&&s.length>0&&o.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},su=(e,r,t,s)=>`
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
// offset-by-one error later in floor().
let big = (${e}) * (${r});
let whole = ${s}(big / (${t}));
let fract = ${s}(big % (${t})) / ${s}(${t});
return whole + fract;
`,cg=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return`
if (xScale < 1.0 || floor(xScale) != xScale) {
return ${r}(xResized) / ${r}(xScale);
} else {
${su("xResized","lengthOriginal","lengthResized",r)}
}
`;case"pytorch_half_pixel":return`if (lengthResized > 1) {
return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5;
} else {
return 0.0;
}`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) {
return 0.0;
} else {
${su("xResized","lengthOriginal - 1","lengthResized - 1",r)}
}`;case"tf_crop_and_resize":return`if (lengthResized > 1) {
return ${r}(roiStart) * ${r}(lengthOriginal - 1) +
(${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) /
${r}(lengthResized - 1);
} else {
return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1);
}`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized);
const adjustment = ${r}(lengthResized) / outputWidth;
const center = ${r}(lengthOriginal) / 2;
const offset = center * (1 - adjustment);
return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",dg=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",pg=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,a)=>{s[n]=o[a],s[a+t]=o[r.length+a]}),s):o},hg=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,a)=>o[n]=t[a])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,a)=>Math.round(n*r[a]))}return o},mg=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(n=>r[n]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(n=>r[n]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,a)=>o[a]=Math.round(n*r[a]))),o},fg=(e,r,t,s,o)=>`
fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> {
var original_indices: array<${e.type.value}, ${t.length}>;
for (var i:u32 = 0; i < ${t.length}; i++) {
var output_index = ${e.indicesGet("output_indices","i")};
var scale = ${it("uniforms.scales","i",s)};
var roi_low = ${it("uniforms.roi","i",o)};
var roi_hi = ${it("uniforms.roi",`i + ${r.length}`,o)};
if (scale == 1.0) {
original_indices[i] = ${e.type.value}(output_index);
} else {
var input_shape_i = ${it("uniforms.input_shape","i",r.length)};
var output_shape_i = ${it("uniforms.output_shape","i",t.length)};
original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
input_shape_i, roi_low, roi_hi);
}
}
return original_indices;
}`,_g=(e,r,t,s,o,n,a)=>`
fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} {
var input_indices: ${e.type.indices};
for (var i:u32 = 0; i < ${s.length}; i++) {
var output_index = ${r.indicesGet("output_indices","i")};
var input_index: u32;
var scale = ${it("uniforms.scales","i",o)};
if (scale == 1.0) {
input_index = output_index;
} else {
var roi_low = ${it("uniforms.roi","i",n)};
var roi_hi = ${it("uniforms.roi",`i + ${t.length}`,n)};
var input_shape_i = ${it("uniforms.input_shape","i",t.length)};
var output_shape_i = ${it("uniforms.output_shape","i",s.length)};
var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
input_shape_i, roi_low, roi_hi);
if (!${a} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) {
if (original_idx < 0) {
input_index = 0;
} else if (original_idx > ${r.type.value}(input_shape_i - 1)) {
input_index = input_shape_i - 1;
} else {
input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));
}
} else {
input_index = u32(original_idx);
}
}
${e.indicesSet("input_indices","i","input_index")}
}
return input_indices;
}`,gg=(e,r)=>`
fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {
for (var i:u32 = 0; i < ${r.length}; i++) {
var input_index = ${e.indicesGet("input_indices","i")};
if (input_index < 0 || input_index >= ${it("uniforms.input_shape","i",r.length)}) {
return false;
}
}
return true;
}`,nu=(e,r,t,s)=>e.rank>s?`
${e.indicesSet("input_indices",r,"channel")};
${e.indicesSet("input_indices",t,"batch")};
`:"",wg=(e,r,t,s,o)=>{let[n,a,i,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return`
fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} {
var input_indices: ${e.type.indices};
${e.indicesSet("input_indices",a,`max(0, min(row, ${t[a]} - 1))`)};
${e.indicesSet("input_indices",i,`max(0, min(col, ${t[i]} - 1))`)};
${nu(e,l,n,2)}
return ${e.getByIndices("input_indices")};
}
fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${c} {
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
var row:${c} = originalIndices[${a}];
var col:${c} = originalIndices[${i}];
${s?`if (row < 0 || row > (${t[a]} - 1) || col < 0 || col > (${t[i]} - 1)) {
return ${o};
}`:""};
row = max(0, min(row, ${t[a]} - 1));
col = max(0, min(col, ${t[i]} - 1));
var row1: u32 = u32(row);
var col1: u32 = u32(col);
var row2: u32 = u32(row + 1);
var col2: u32 = u32(col + 1);
var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"};
var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"};
var x11: ${c} = getInputValue(batch, channel, row1, col1);
var x12: ${c} = getInputValue(batch, channel, row1, col2);
var x21: ${c} = getInputValue(batch, channel, row2, col1);
var x22: ${c} = getInputValue(batch, channel, row2, col2);
var dx1: ${c} = abs(row - ${c}(row1));
var dx2: ${c} = abs(${c}(row2) - row);
var dy1: ${c} = abs(col - ${c}(col1));
var dy2: ${c} = abs(${c}(col2) - col);
if (row1 == row2) {
dx1 = 0.5;
dx2 = 0.5;
}
if (col1 == col2) {
dy1 = 0.5;
dy2 = 0.5;
}
return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);
}`},Mg=(e,r,t,s,o,n,a,i,l,c)=>{let p=t.length===2,[d,u]=p?[0,1]:[2,3],_=e.type.value,f=b=>{let A=b===d?"row":"col";return`
fn ${A}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${_} {
var output_index = ${r.indicesGet("output_indices",b)};
var originalIdx: ${_} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[b]},
${s[b]}, ${t[b]}, ${n[b]}, ${n[b]} + ${t.length});
var fractOriginalIdx: ${_} = originalIdx - floor(originalIdx);
var coefs = getCubicInterpolationCoefs(fractOriginalIdx);
if (${i} && (originalIdx < 0 || originalIdx > (${t[b]} - 1))) {
return ${l};
}
var data: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0);
for (var i: i32 = -1; i < 3; i++) {
var ${A}: ${_} = originalIdx + ${_}(i);
if (${A} < 0 || ${A} >= ${t[b]}) {
${c?`coefs[i + 1] = 0.0;
continue;`:i?`return ${l};`:`${A} = max(0, min(${A}, ${t[b]} - 1));`};
}
var input_indices_copy: ${e.type.indices} = input_indices;
${e.indicesSet("input_indices_copy",b,`u32(${A})`)};
data[i + 1] = ${b===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};
}
return cubicInterpolation1D(data, coefs);
}`};return`
${f(d)};
${f(u)};
fn getCubicInterpolationCoefs(s: ${_}) -> array<${_}, 4> {
var absS = abs(s);
var coeffs: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0);
var oneMinusAbsS: ${_} = 1.0 - absS;
var twoMinusAbsS: ${_} = 2.0 - absS;
var onePlusAbsS: ${_} = 1.0 + absS;
coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};
coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;
coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;
coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};
return coeffs;
}
fn cubicInterpolation1D(x: array<${_}, 4>, coefs: array<${_}, 4>) -> ${_} {
var coefsSum: ${_} = coefs[0] + coefs[1] + coefs[2] + coefs[3];
return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;
}
fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${_} {
var input_indices: ${e.type.indices} = output_indices;
return colCubicInterpolation(input_indices, output_indices);
}
`},bg=(e,r,t,s,o)=>{let[n,a,i,l,c]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return`
fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} {
var input_indices: ${e.type.indices};
${e.indicesSet("input_indices",a,`max(0, min(depth, ${t[a]} - 1))`)};
${e.indicesSet("input_indices",i,`max(0, min(height, ${t[i]} - 1))`)};
${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)};
${nu(e,c,n,3)}
return ${e.getByIndices("input_indices")};
}
fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} {
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
var depth:${p} = originalIndices[${a}];
var height:${p} = originalIndices[${i}];
var width:${p} = originalIndices[${l}];
${s?`if (depth < 0 || depth > (${t[a]} - 1) || height < 0 || height > (${t[i]} - 1) || width < 0 || (width > ${t[l]} - 1)) {
return ${o};
}`:""};
depth = max(0, min(depth, ${t[a]} - 1));
height = max(0, min(height, ${t[i]} - 1));
width = max(0, min(width, ${t[l]} - 1));
var depth1: u32 = u32(depth);
var height1: u32 = u32(height);
var width1: u32 = u32(width);
var depth2: u32 = u32(depth + 1);
var height2: u32 = u32(height + 1);
var width2: u32 = u32(width + 1);
var channel: u32 = ${t.length>3?`u32(originalIndices[${c}])`:"0"};
var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"};
var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1);
var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2);
var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1);
var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2);
var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1);
var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2);
var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1);
var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2);
var dx1: ${p} = abs(depth - ${p}(depth1));
var dx2: ${p} = abs(${p}(depth2) - depth);
var dy1: ${p} = abs(height - ${p}(height1));
var dy2: ${p} = abs(${p}(height2) - height);
var dz1: ${p} = abs(width - ${p}(width1));
var dz2: ${p} = abs(${p}(width2) - width);
if (depth1 == depth2) {
dx1 = 0.5;
dx2 = 0.5;
}
if (height1 == height2) {
dy1 = 0.5;
dy2 = 0.5;
}
if (width1 == width2) {
dz1 = 0.5;
dz2 = 0.5;
}
return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
}`},yg=(e,r,t,s,o,n)=>{let a=e.dims,i=pg(n,r.axes,a.length),l=hg(a,s,o,r.axes),c=s.slice();s.length===0&&(c=a.map((y,C)=>y===0?1:l[C]/y),r.keepAspectRatioPolicy!=="stretch"&&(l=mg(a,c,r)));let p=at("output",e.dataType,l.length),d=Oe("input",e.dataType,a.length),u=Pe.size(l),_=a.length===l.length&&a.every((y,C)=>y===l[C]),f=r.coordinateTransformMode==="tf_crop_and_resize",b=r.extrapolationValue,A=d.type.value,g=y=>`
${_?"":`
${cg(r.coordinateTransformMode,A)};
${(()=>{switch(r.mode){case"nearest":return`
${gg(d,a)};
${dg(r.nearestMode,t,A)};
${_g(d,p,a,l,c.length,i.length,f)};
`;case"linear":return`
${fg(p,a,l,c.length,i.length)};
${(()=>{if(a.length===2||a.length===4)return`${wg(d,p,a,f,b)}`;if(a.length===3||a.length===5)return`${bg(d,p,a,f,b)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};
`;case"cubic":return`
${(()=>{if(a.length===2||a.length===4)return`${Mg(d,p,a,l,c,i,r.cubicCoeffA,f,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};
`;default:throw Error("Invalid resize mode")}})()};
`}
${y.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",i.length).declareVariables(d,p)}
${y.mainStart()}
${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
${_?"output[global_idx] = input[global_idx];":`
let output_indices = ${p.offsetToIndices("global_idx")};
var input_indices: ${d.type.indices};
${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);
if (checkInputIndices(input_indices)) {
output[global_idx] = ${d.getByIndices("input_indices")};
} else {
output[global_idx] = ${r.extrapolationValue};
}`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()};
`}
}`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${c.length>0?r.mode==="cubic"?c:c.length:""}|${o.length>0?o:""}|${i.length>0?i:""}|${_}|${r.mode==="nearest"?a.length:a}`,inputDependencies:["rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:c},{type:1,data:i},...lt(a,l)]})}},vg=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},xg=(e,r)=>{let t=[],s=[],o=[],n=vg(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");ug(e.inputs,r,n,t,s,o),e.compute(yg(e.inputs[0],r,n,t,s,o),{inputs:[0]})},Tg=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,a=e.extrapolationValue,i=e.keepAspectRatioPolicy,l=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return jt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:a,keepAspectRatioPolicy:i,mode:l,nearestMode:c})}}),Eg,Pg,Cg,AT=Ue(()=>{Mt(),Pt(),Ct(),Eg=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==n)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Pg=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,a=Pe.size(n),i=n,l=a,c=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],d=!o&&e.length>3,u=e.length>4,_=s&&t>1,f=s&&t>2,b=t>3,A=64,g=or(c),y=[{type:12,data:l},{type:12,data:g},{type:12,data:c},{type:1,data:r.epsilon}],C=M=>{let T=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],v=[Oe("x",e[0].dataType,e[0].dims,g),Oe("skip",e[1].dataType,e[1].dims,g),Oe("gamma",e[2].dataType,e[2].dims,g)];d&&v.push(Oe("beta",e[3].dataType,e[3].dims,g)),u&&v.push(Oe("bias",e[4].dataType,e[4].dims,g)),v.push(at("output",e[0].dataType,i,g)),_&&v.push(at("mean_output",1,p)),f&&v.push(at("inv_std_output",1,p)),b&&v.push(at("input_skip_bias_sum",e[0].dataType,i,g));let P=Sr(e[0].dataType),F=Sr(1,g);return`
${M.registerUniforms(T).declareVariables(...v)}
var sum_shared : array<${F}, ${A}>;
var sum_squared_shared : array<${F}, ${A}>;
${M.mainStart([A,1,1])}
let ix = local_id.x;
let iy = global_id.x / ${A};
let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;
var stride = hidden_size_vectorized / ${A};
let offset = ix * stride + iy * hidden_size_vectorized;
let offset1d = stride * ix;
if (ix == ${A-1}) {
stride = hidden_size_vectorized - stride * ix;
}
for (var i: u32 = 0; i < stride; i++) {
let skip_value = skip[offset + i];
let bias_value = ${u?"bias[offset1d + i]":P+"(0.0)"};
let input_value = x[offset + i];
let value = input_value + skip_value + bias_value;
${b?"input_skip_bias_sum[offset + i] = value;":""}
output[offset + i] = value;
let f32_value = ${Kn(P,g,"value")};
sum_shared[ix] += f32_value;
sum_squared_shared[ix] += f32_value * f32_value;
}
workgroupBarrier();
var reduce_size : u32 = ${A};
for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {
reduce_size = curr_size + (reduce_size & 1);
if (ix < curr_size) {
sum_shared[ix] += sum_shared[ix + reduce_size];
sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];
}
workgroupBarrier();
}
let sum = sum_shared[0];
let square_sum = sum_squared_shared[0];
let mean = ${Js("sum",g)} / f32(uniforms.hidden_size);
let inv_std_dev = inverseSqrt(${Js("square_sum",g)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon);
${_?"mean_output[global_idx] = mean;":""}
${f?"inv_std_output[global_idx] = inv_std_dev;":""}
for (var i: u32 = 0; i < stride; i++) {
output[offset + i] = (output[offset + i] ${o?"":`- ${P}(mean)`}) *
${P}(inv_std_dev) * gamma[offset1d + i]
${d?"+ beta[offset1d + i]":""};
}
}`},x=[{dims:i,dataType:e[0].dataType}];return t>1&&x.push({dims:p,dataType:1}),t>2&&x.push({dims:p,dataType:1}),t>3&&x.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${g};${_};${f};${b}`,inputDependencies:e.map((M,T)=>"type")},getShaderSource:C,getRunData:()=>({outputs:x,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:y})}},Cg=(e,r)=>{Eg(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(Pg(e.inputs,r,e.outputCount,!1),{outputs:t})}}),Sg,Eo,$g,ou,Ag,kg,Ig,Fg,kT=Ue(()=>{Mt(),Pt(),ur(),Ct(),Sg=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},Eo=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},$g=(e,r)=>{if(e.length>1){let t=Eo(e,1),s=Eo(e,2),o=Eo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),jt({starts:t,ends:s,axes:o})}else return r},ou=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},Ag=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} {
var input_indices: ${e.type.indices};
var carry = 0u;
for (var i = ${t.length}; i >= 0; i--) {
let input_shape_i = ${it("uniforms.input_shape","i",t.length)};
let steps_i = ${it("uniforms.steps","i",t.length)};
let signs_i = ${it("uniforms.signs","i",t.length)};
let starts_i = ${it("uniforms.starts","i",t.length)};
var output_index = ${r.indicesGet("output_indices","i")};
var input_index = output_index * steps_i + starts_i + carry;
carry = input_index / input_shape_i;
input_index = input_index % input_shape_i;
if (signs_i < 0) {
input_index = input_shape_i - input_index - 1u + starts_i;
}
${e.indicesSet("input_indices","i","input_index")};
}
return input_indices;
}`,kg=(e,r)=>{let t=e[0].dims,s=Pe.size(t),o=r.axes.length>0?Pe.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=Eo(e,4);n.forEach(g=>g!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let a=r.starts.map((g,y)=>ou(g,y,t,o,n)),i=r.ends.map((g,y)=>ou(g,y,t,o,n));if(o.length!==a.length||o.length!==i.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let g=0;gMath.sign(g));n.forEach((g,y,C)=>{if(g<0){let x=(i[y]-a[y])/g,M=a[y],T=M+x*n[y];a[y]=T,i[y]=M,C[y]=-g}});let c=t.slice(0);o.forEach((g,y)=>{c[g]=Math.ceil((i[g]-a[g])/n[g])});let p={dims:c,dataType:e[0].dataType},d=at("output",e[0].dataType,c.length),u=Oe("input",e[0].dataType,e[0].dims.length),_=Pe.size(c),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],b=[{type:12,data:_},{type:12,data:a},{type:6,data:l},{type:12,data:n},...lt(e[0].dims,c)],A=g=>`
${g.registerUniforms(f).declareVariables(u,d)}
${Ag(u,d,t)}
${g.mainStart()}
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
let output_indices = ${d.offsetToIndices("global_idx")};
let input_indices = calculateInputIndices(output_indices);
${d.setByOffset("global_idx",u.getByIndices("input_indices"))}
}`;return{name:"Slice",shaderCache:{hint:`${l.length}_${a.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:b})}},Ig=(e,r)=>{Sg(e.inputs,r);let t=$g(e.inputs,r);e.compute(kg(e.inputs,t),{inputs:[0]})},Fg=e=>{let r=e.starts,t=e.ends,s=e.axes;return jt({starts:r,ends:t,axes:s})}}),Og,Dg,Lg,zg,IT=Ue(()=>{Mt(),Pt(),ur(),Ys(),Ct(),Og=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Dg=(e,r)=>{let t=e.inputs[0],s=t.dims,o=Pe.size(s),n=s.length,a=Pe.normalizeAxis(r.axis,n),i=aP),c[a]=n-1,c[n-1]=a,l=e.compute(rs(t,c),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[n-1],u=o/d,_=or(d),f=d/_,b=64;u===1&&(b=256);let A=(v,P)=>P===4?`max(max(${v}.x, ${v}.y), max(${v}.z, ${v}.w))`:P===2?`max(${v}.x, ${v}.y)`:P===3?`max(max(${v}.x, ${v}.y), ${v}.z)`:v,g=Oe("x",l.dataType,l.dims,_),y=at("result",l.dataType,l.dims,_),C=g.type.value,x=Sr(l.dataType)==="f32"?`var threadMax = ${C}(-3.402823e+38f);`:`var threadMax = ${C}(-65504.0h);`,M=v=>`
var rowMaxShared : ${C};
var rowSumShared : ${C};
var threadShared : array<${C}, ${b}>;
fn getValue(row: i32, col: i32, row_stride: i32) -> ${C} {
let index = row * row_stride + col;
return x[index];
}
fn setValue(row: i32, col: i32, row_stride: i32, value: ${C}) {
let index = row * row_stride + col;
result[index] = value;
}
${v.registerUniform("packedCols","i32").declareVariables(g,y)}
${v.mainStart(b)}
let gindex = i32(global_idx);
let lindex = i32(local_idx);
const wg = ${b};
let row = gindex / wg;
let cols = uniforms.packedCols;
let row_stride : i32 = uniforms.packedCols;
// find the rows max
${x}
for (var col = lindex; col < cols; col += wg) {
let value = getValue(row, col, row_stride);
threadMax = max(threadMax, value);
}
if (lindex < cols) {
threadShared[lindex] = threadMax;
}
workgroupBarrier();
var reduceSize = min(cols, wg);
for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {
reduceSize = currSize + (reduceSize & 1);
if (lindex < currSize) {
threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);
}
workgroupBarrier();
}
if (lindex == 0) {
rowMaxShared = ${C}(${A("threadShared[0]",_)});
}
workgroupBarrier();
// find the rows sum
var threadSum = ${C}(0.0);
for (var col = lindex; col < cols; col += wg) {
let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);
threadSum += subExp;
}
threadShared[lindex] = threadSum;
workgroupBarrier();
for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {
if (lindex < currSize) {
threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];
}
workgroupBarrier();
}
if (lindex == 0) {
rowSumShared = ${C}(${Js("threadShared[0]",_)});
}
workgroupBarrier();
// calculate final value for each element in the row
for (var col = lindex; col < cols; col += wg) {
let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;
setValue(row, col, row_stride, value);
}
}`,T=e.compute({name:"Softmax",shaderCache:{hint:`${_};${b}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:f}]}),getShaderSource:M},{inputs:[l],outputs:[i?-1:0]})[0];i&&e.compute(rs(T,c),{inputs:[T]})},Lg=(e,r)=>{Og(e.inputs),Dg(e,r)},zg=e=>jt({axis:e.axis})}),au,Rg,Bg,Ng,jg,FT=Ue(()=>{Mt(),Pt(),Ct(),au=e=>Array.from(e.getBigInt64Array(),Number),Rg=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(au(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Bg=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??au(e[1]),o=Bg(t,s),n=Pe.size(o),a=e[0].dataType,i=Oe("input",a,t.length),l=at("output",a,o.length),c=p=>`
const inputShape = ${i.indices(...t)};
${p.registerUniform("output_size","u32").declareVariables(i,l)}
${p.mainStart()}
${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let output_indices = ${l.offsetToIndices("global_idx")};
var input_indices: ${i.type.indices};
for (var i = 0; i < ${t.length}; i++) {
let input_dim_i = ${i.indicesGet("uniforms.input_shape","i")};
let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i;
${i.indicesSet("input_indices","i","input_dim_value")}
}
${l.setByOffset("global_idx",i.getByIndices("input_indices"))}
}`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...lt(e[0].dims,o)]}),getShaderSource:c}},jg=e=>{Rg(e.inputs),e.compute(Ng(e.inputs),{inputs:[0]})}}),Vg,Ug,Wg,OT=Ue(()=>{Mt(),Pt(),Ct(),Vg=(e,r,t,s,o)=>{let n=at("output_data",o,t.length,4),a=Oe("a_data",r[1].dataType,r[1].dims.length,4),i=Oe("b_data",r[2].dataType,r[2].dims.length,4),l=Oe("c_data",r[0].dataType,r[0].dims.length,4),c,p=(d,u,_)=>`select(${u}, ${d}, ${_})`;if(!s)c=n.setByOffset("global_idx",p(a.getByOffset("global_idx"),i.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(u,_,f="")=>{let b=`a_data[index_a${_}][component_a${_}]`,A=`b_data[index_b${_}][component_b${_}]`,g=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`
let output_indices${_} = ${n.offsetToIndices(`global_idx * 4u + ${_}u`)};
let offset_a${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,n)};
let offset_b${_} = ${i.broadcastedIndicesToOffset(`output_indices${_}`,n)};
let offset_c${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,n)};
let index_a${_} = offset_a${_} / 4u;
let index_b${_} = offset_b${_} / 4u;
let index_c${_} = offset_c${_} / 4u;
let component_a${_} = offset_a${_} % 4u;
let component_b${_} = offset_b${_} % 4u;
let component_c${_} = offset_c${_} % 4u;
${u}[${_}] = ${f}(${p(b,A,g)});
`};o===9?c=`
var data = vec4(0);
${d("data",0,"u32")}
${d("data",1,"u32")}
${d("data",2,"u32")}
${d("data",3,"u32")}
output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=`
${d("output_data[global_idx]",0)}
${d("output_data[global_idx]",1)}
${d("output_data[global_idx]",2)}
${d("output_data[global_idx]",3)}
`}return`
${e.registerUniform("vec_size","u32").declareVariables(l,a,i,n)}
${e.mainStart()}
${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
${c}
}`},Ug=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(Pe.areEqual(r,t)&&Pe.areEqual(t,s)),a=r,i=Pe.size(r);if(n){let c=Gn.calcShape(Gn.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,i=Pe.size(a)}let l=Math.ceil(i/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Vg(c,e,a,n,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(i/64/4)},programUniforms:[{type:12,data:l},...lt(s,r,t,a)]})}},Wg=e=>{e.compute(Ug(e.inputs))}}),Gg,DT=Ue(()=>{Qx(),bl(),Xx(),Jx(),Yx(),Zx(),eT(),oT(),iT(),lT(),uT(),cT(),dT(),pT(),hT(),mT(),fT(),_T(),gT(),wT(),MT(),bT(),yT(),vT(),xT(),s_(),TT(),ET(),PT(),CT(),ST(),gl(),$T(),h_(),AT(),kT(),IT(),c_(),FT(),Ys(),Tl(),OT(),Gg=new Map([["Abs",[Th]],["Acos",[Eh]],["Acosh",[Ph]],["Add",[hm]],["ArgMax",[uh,Ml]],["ArgMin",[lh,Ml]],["Asin",[Ch]],["Asinh",[Sh]],["Atan",[$h]],["Atanh",[Ah]],["Attention",[fh]],["AveragePool",[U_,V_]],["BatchNormalization",[Mh]],["BiasAdd",[vh]],["BiasSplitGelu",[cm]],["Cast",[Ih,kh]],["Ceil",[Dh]],["Clip",[Oh]],["Concat",[Cm,Sm]],["Conv",[zl,Dl]],["ConvTranspose",[tf,Ym]],["Cos",[Lh]],["Cosh",[zh]],["CumSum",[sf,nf]],["DepthToSpace",[uf,cf]],["DequantizeLinear",[Y_,Z_]],["Div",[mm]],["Einsum",[_f,gf]],["Elu",[Rh,Mo]],["Equal",[fm]],["Erf",[Bh]],["Exp",[Nh]],["Expand",[yf]],["FastGelu",[xf]],["Floor",[jh]],["FusedConv",[zl,Dl]],["Gather",[Cf,Pf]],["GatherElements",[Rf,zf]],["GatherBlockQuantized",[Ff,Of]],["GatherND",[$f,Af]],["Gelu",[Vh]],["Gemm",[Vf,jf]],["GlobalAveragePool",[G_,W_]],["GlobalMaxPool",[Q_,q_]],["Greater",[Mm]],["GreaterOrEqual",[ym]],["GridSample",[Jf,Yf]],["GroupQueryAttention",[g_]],["HardSigmoid",[Xh,Qh]],["InstanceNormalization",[b_]],["LayerNormalization",[x_]],["LeakyRelu",[Uh,Mo]],["Less",[bm]],["LessOrEqual",[vm]],["Log",[nm]],["MatMul",[E_]],["MatMulNBits",[$_,A_]],["MaxPool",[H_,K_]],["Mul",[_m]],["MultiHeadAttention",[r_,e_]],["Neg",[Gh]],["Not",[Wh]],["Pad",[B_]],["Pow",[gm]],["QuickGelu",[im,Mo]],["Range",[rg]],["Reciprocal",[Hh]],["ReduceMin",[sh]],["ReduceMean",[Yp]],["ReduceMax",[rh]],["ReduceSum",[oh]],["ReduceProd",[nh]],["ReduceL1",[Zp]],["ReduceL2",[eh]],["ReduceLogSum",[ih]],["ReduceLogSumExp",[th]],["ReduceSumSquare",[ah]],["Relu",[Kh]],["Resize",[xg,Tg]],["RotaryEmbedding",[p_]],["ScatterND",[ag,og]],["Sigmoid",[qh]],["Sin",[Jh]],["Sinh",[Yh]],["Slice",[Ig,Fg]],["SkipLayerNormalization",[Cg]],["Split",[l_,u_]],["Sqrt",[Zh]],["Softmax",[Lg,zg]],["Sub",[wm]],["Tan",[em]],["Tanh",[tm]],["ThresholdedRelu",[sm,Mo]],["Tile",[jg]],["Transpose",[Mp,bp]],["Where",[Wg]]])}),Hg,LT=Ue(()=>{bs(),js(),Ct(),Hg=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,o){Ms(e.programInfo.name);let n=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let i=[];for(let c of r)i.push({binding:i.length,resource:{buffer:c.buffer}});for(let c of t)i.push({binding:i.length,resource:{buffer:c.buffer}});o&&i.push({binding:i.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:i,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}a.setPipeline(e.computePipeline),a.setBindGroup(0,l),a.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),us(e.programInfo.name)}dispose(){}build(e,r){Ms(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&s.push(`enable ${c.extension};`)});let o=hp(r,this.backend.device.limits),n=e.getShaderSource(o),a=`${s.join(`
`)}
${o.additionalImplementations}
${n}`,i=t.createShaderModule({code:a,label:e.name});Dt("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:i,entryPoint:"main"},layout:"auto",label:e.name});return us(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,a=Math.ceil(Math.sqrt(n));if(a>o){if(a=Math.ceil(Math.cbrt(n)),a>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),Kg={};Un(Kg,{WebGpuBackend:()=>Jg});var qg,Qg,Xg,Jg,zT=Ue(()=>{bs(),Mt(),js(),Zd(),Kx(),DT(),LT(),qg=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{var o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${qg(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},Xg=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Jg=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Xg(r.info||await r.requestAdapterInfo()),this.gpuDataManager=up(this),this.programManager=new Hg(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,tl(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ms(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=_);let b=Number(_-this.queryTimeBase),A=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(b)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(g=>({dims:g.dims,dataType:Ns(g.dataType)})),outputsMetadata:u.map(g=>({dims:g.dims,dataType:Ns(g.dataType)})),kernelId:a,kernelType:l,kernelName:c,programName:p,startTime:b,endTime:A});else{let g="";d.forEach((C,x)=>{g+=`input[${x}]: [${C.dims}] | ${Ns(C.dataType)}, `});let y="";u.forEach((C,x)=>{y+=`output[${x}]: [${C.dims}] | ${Ns(C.dataType)}, `}),console.log(`[profiling] kernel "${a}|${l}|${c}|${p}" ${g}${y}execution time: ${A-b} ns`)}mo("GPU",`${p}::${_}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),us()}run(e,r,t,s,o,n){Ms(e.name);let a=[];for(let y=0;yC):t;if(p.length!==i.length)throw new Error(`Output size ${p.length} must be equal to ${i.length}.`);let d=[],u=[];for(let y=0;y=n)throw new Error(`Invalid output index: ${p[y]}`);if(p[y]===-3)continue;let C=p[y]===-1,x=p[y]===-2,M=C||x?o(i[y].dataType,i[y].dims):s(p[y],i[y].dataType,i[y].dims);if(d.push(M),M.data===0)continue;let T=this.gpuDataManager.get(M.data);if(!T)throw new Error(`no GPU data for output: ${M.data}`);if(C&&this.temporaryData.push(T),x){let v=this.kernelPersistentData.get(this.currentKernelId);v||(v=[],this.kernelPersistentData.set(this.currentKernelId,v)),v.push(T)}u.push(T)}if(a.length!==r.length||u.length!==d.length){if(u.length===0)return us(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(c){let y=0,C=[];c.forEach(v=>{let P=typeof v.data=="number"?[v.data]:v.data;if(P.length===0)return;let F=v.type===10?2:4,D,K;v.type===10?(K=P.length>4?16:P.length>2?8:P.length*F,D=P.length>4?16:F*P.length):(K=P.length<=2?P.length*F:16,D=16),y=Math.ceil(y/K)*K,C.push(y);let U=v.type===10?8:4;y+=P.length>4?Math.ceil(P.length/U)*D:P.length*F});let x=16;y=Math.ceil(y/x)*x;let M=new ArrayBuffer(y);c.forEach((v,P)=>{let F=C[P],D=typeof v.data=="number"?[v.data]:v.data;if(v.type===6)new Int32Array(M,F,D.length).set(D);else if(v.type===12)new Uint32Array(M,F,D.length).set(D);else if(v.type===10)new Uint16Array(M,F,D.length).set(D);else if(v.type===1)new Float32Array(M,F,D.length).set(D);else throw new Error(`Unsupported uniform type: ${Ns(v.type)}`)});let T=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(T.buffer,0,M,0,y),this.gpuDataManager.release(T.id),_={offset:0,size:y,buffer:T.buffer}}let f=this.programManager.normalizeDispatchGroupSize(l),b=f[1]===1&&f[2]===1,A=Qg(e,r,b),g=this.programManager.getArtifact(A);if(g||(g=this.programManager.build(e,f),this.programManager.setArtifact(A,g),Dt("info",()=>`[artifact] key: ${A}, programName: ${e.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${A}) with ${f[0]}x${f[1]}x${f[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(g,a,u,f,_),us(e.name),d}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let o=Gg.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[1],t]};this.kernels.set(r,n)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let o=s.kernelType,n=s.kernelName,a=s.kernelEntry,i=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,i[0]&&(i[1]=i[0](i[1]),i[0]=void 0),Dt("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(r,i[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${o}] ${n}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),a=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[a,t]),a}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await pl(this,e,r);return rl(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Dt("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Dt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Dt("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Yg={};Un(Yg,{init:()=>ew});var ya,Zg,ew,RT=Ue(()=>{Mt(),js(),Pt(),Hx(),ya=class ix{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=Pe.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=Pe.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=Pe.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=Pe.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(Pe.size(r)!==Pe.size(this.dims))throw new Error("Invalid new shape");return new ix(this.module,this.dataType,this.data,r)}},Zg=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let a=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let i=[];for(let l=0;l