载入中...
搜索中...
未找到
KernelGenResize.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cctype>
3#include <cmath>
4#include <map>
5#include <sstream>
6#include "common/Exception.h"
7#include "tensor/CpuKernels.h"
10#include "tensor/Quant.h"
11
12// KernelGenResize.cpp
14void genResize2d(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
15 const GraphNode &rn = g.node(grp.outputNode);
16 const GraphNode &X = g.node(rn.in0);
17 const int H = X.dims[2], W = X.dims[3];
18 const int OH = rn.dims[2], OW = rn.dims[3];
19 const bool nearest = rn.i0 == 0;
20 std::ostringstream os;
21 os << header(kLocalSize);
22 os << bufferDecl(0, "in_");
23 os << bufferDecl(1, "o");
24 os << pushConstant();
25 os << "void main() {\n";
26 os << " uint i_ = gl_GlobalInvocationID.x;\n";
27 os << " if (i_ >= " << rn.size << "u) return;\n";
28 os << " uint ow = i_ % " << OW << "u;\n";
29 os << " uint rem = i_ / " << OW << "u;\n";
30 os << " uint oh = rem % " << OH << "u;\n";
31 os << " uint rem2 = rem / " << OH << "u;\n";
32 os << " uint c = rem2 % " << X.dims[1] << "u;\n";
33 os << " uint n_ = rem2 / " << X.dims[1] << "u;\n";
34 os << " uint base = (n_ * " << X.dims[1] << "u + c) * " << H << "u * " << W << "u;\n";
35 if (nearest) {
36 os << " uint ih = uint(float(oh) * " << scalarStr(float(H) / OH) << ") ;\n";
37 os << " uint iw = uint(float(ow) * " << scalarStr(float(W) / OW) << ") ;\n";
38 os << " ih = min(ih, " << H - 1 << "u); iw = min(iw, " << W - 1 << "u);\n";
39 os << " o[i_] = in_[base + ih * " << W << "u + iw];\n";
40 } else {
41 os << " float fx = (float(ow) + 0.5) * " << scalarStr(float(W) / OW) << " - 0.5;\n";
42 os << " float fy = (float(oh) + 0.5) * " << scalarStr(float(H) / OH) << " - 0.5;\n";
43 os << " fx = clamp(fx, 0.0, " << scalarStr(float(W - 1)) << ");\n";
44 os << " fy = clamp(fy, 0.0, " << scalarStr(float(H - 1)) << ");\n";
45 os << " uint x0 = uint(floor(fx)); uint y0 = uint(floor(fy));\n";
46 os << " uint x1 = min(x0 + 1u, " << W - 1 << "u); uint y1 = min(y0 + 1u, " << H - 1 << "u);\n";
47 os << " float w00 = in_[base + y0 * " << W << "u + x0];\n";
48 os << " float w10 = in_[base + y0 * " << W << "u + x1];\n";
49 os << " float w01 = in_[base + y1 * " << W << "u + x0];\n";
50 os << " float w11 = in_[base + y1 * " << W << "u + x1];\n";
51 os << " float top = w00 + (w10 - w00) * (fx - float(x0));\n";
52 os << " float bot = w01 + (w11 - w01) * (fx - float(x0));\n";
53 os << " o[i_] = top + (bot - top) * (fy - float(y0));\n";
54 }
55 os << "}\n";
56 out.pass1.clear();
57 out.pass2 = os.str();
58 out.groupsX2 = groupsFor(rn.size);
59 out.inputCount = 1;
60 return;
61}
62
63
64} // namespace eve::tensor::glsl_detail
65
66// KernelGenWgsl.cpp
67namespace eve::tensor {
68namespace wgsl_detail {
69
70
71std::string header(int localX, int localY) {
72 return "const workgroupX = " + std::to_string(localX) + "u;\nconst workgroupY = " + std::to_string(localY) + "u;\n";
73}
74std::string bufferDecl(int binding, const char *name) {
75 return "@group(0) @binding(" + std::to_string(binding) + ") var<storage, read_write> " + name + ": array<f32>;\n";
76}
77std::string bufferDeclUint(int binding, const char *name) {
78 return "@group(0) @binding(" + std::to_string(binding) + ") var<storage, read_write> " + name + ": array<u32>;\n";
79}
80
86std::string emitQuantizedBVal(DType dt, int group, const char *bufName = "b") {
87 std::ostringstream os;
88 const int g = group > 0 ? group : 1;
89 switch (dt) {
90 case DType::Int8:
91 os << "fn bval(idx: u32) -> f32 {\n"
92 << " var word: u32 = " << bufName << "[idx >> 2u];\n"
93 << " var byte: u32 = (word >> ((idx & 3u) * 8u)) & 0xFFu;\n"
94 << " var v: i32 = i32(byte);\n"
95 << " if (v >= 128) { v -= 256; }\n"
96 << " return f32(v) * bs[idx / " << g << "u];\n"
97 << "}\n";
98 break;
99 case DType::Int4:
100 os << "fn bval(idx: u32) -> f32 {\n"
101 << " var word: u32 = " << bufName << "[idx >> 3u];\n"
102 << " var byte: u32 = (word >> (((idx >> 1u) & 3u) * 8u)) & 0xFFu;\n"
103 << " var nib: u32 = select(byte >> 4u, byte & 0xFu, (idx & 1u) == 0u);\n"
104 << " var v: i32 = i32(nib);\n"
105 << " if (v >= 8) { v -= 16; }\n"
106 << " return f32(v) * bs[idx / " << g << "u];\n"
107 << "}\n";
108 break;
109 case DType::Fp16:
110 os << "fn bval(idx: u32) -> f32 {\n"
111 << " var word: u32 = " << bufName << "[idx >> 1u];\n"
112 << " var hb: u32 = (word >> ((idx & 1u) * 16u)) & 0xFFFFu;\n"
113 << " return unpack2x16float(hb).x;\n"
114 << "}\n";
115 break;
116 case DType::Fp8E4M3:
117 os << "fn bval(idx: u32) -> f32 {\n"
118 << " var word: u32 = " << bufName << "[idx >> 2u];\n"
119 << " var byte: u32 = (word >> ((idx & 3u) * 8u)) & 0xFFu;\n"
120 << " var s: i32 = select(1, -1, (byte & 0x80u) != 0u);\n"
121 << " var e: i32 = i32((byte >> 3u) & 0xFu);\n"
122 << " var m: i32 = i32(byte & 0x7u);\n"
123 << " var v: f32 = select(exp2(f32(e - 7)) * (1.0 + f32(m) / 8.0),\n"
124 << " exp2(-6.0) * f32(m) / 8.0, e == 0);\n"
125 << " return f32(s) * v * bs[idx / " << g << "u];\n"
126 << "}\n";
127 break;
128 case DType::Fp4E2M1:
129 os << "fn bval(idx: u32) -> f32 {\n"
130 << " var word: u32 = " << bufName << "[idx >> 3u];\n"
131 << " var byte: u32 = (word >> (((idx >> 1u) & 3u) * 8u)) & 0xFFu;\n"
132 << " var nib: u32 = select(byte >> 4u, byte & 0xFu, (idx & 1u) == 0u);\n"
133 << " var s: i32 = select(1, -1, (nib & 8u) != 0u);\n"
134 << " var e: i32 = i32((nib >> 1u) & 3u);\n"
135 << " var m: i32 = i32(nib & 1u);\n"
136 << " var v: f32 = select(exp2(f32(e - 1)) * (1.0 + 0.5 * f32(m)),\n"
137 << " 0.5 * f32(m), e == 0);\n"
138 << " return f32(s) * v * bs[idx / " << g << "u];\n"
139 << "}\n";
140 break;
141 default: break;
142 }
143 return os.str();
144}
145
146std::string pushConstant() { return ""; }
147
148int groupsFor(int count) { return (count + kLocalSize - 1) / kLocalSize; }
149
150std::string scalarStr(float v) {
151 if (v == int(v) && std::fabs(v) < 1e9f) return std::to_string(int(v)) + ".0";
152 std::ostringstream os;
153 os << v << "f";
154 return os.str();
155}
156
163 const Graph &graph;
165 const std::vector<std::string> &indexExprs; // per group input
166 std::string rootVar;
167 std::ostringstream &os;
168 int temp = 0;
169 std::string biasIndexExpr; // e.g. "jj" (matmul) / "f" (conv), empty = none
170
171 std::string operand(int nodeId) {
172 if (nodeId == group.biasNode && !biasIndexExpr.empty()) return "bias[" + biasIndexExpr + "]";
173 const auto it = std::find(group.inputs.begin(), group.inputs.end(), nodeId);
174 if (it != group.inputs.end()) {
175 const size_t idx = static_cast<size_t>(it - group.inputs.begin());
176 return "a" + std::to_string(idx) + "[" + indexExprs[idx] + "]";
177 }
178 return vars[static_cast<size_t>(nodeId)];
179 }
180
181 std::vector<std::string> vars;
182
183 std::string emit(int nodeId) {
184 const GraphNode &nd = graph.node(nodeId);
185 const std::string x =
186 (nd.in0 == group.nodes.front() && rootVar != "") ? rootVar : (nd.in0 >= 0 ? operand(nd.in0) : rootVar);
187 std::string expr;
188 switch (nd.type) {
189 case OpType::Add: expr = "(" + x + " + " + operand(nd.in1) + ")"; break;
190 case OpType::Sub: expr = "(" + x + " - " + operand(nd.in1) + ")"; break;
191 case OpType::Multiply: expr = "(" + x + " * " + operand(nd.in1) + ")"; break;
192 case OpType::Divide: expr = "(" + x + " / " + operand(nd.in1) + ")"; break;
193 case OpType::AddScalar: expr = "(" + x + " + " + scalarStr(nd.s0) + ")"; break;
194 case OpType::SubScalar: expr = "(" + x + " - " + scalarStr(nd.s0) + ")"; break;
195 case OpType::MulScalar: expr = "(" + x + " * " + scalarStr(nd.s0) + ")"; break;
196 case OpType::DivScalar: expr = "(" + x + " / " + scalarStr(nd.s0) + ")"; break;
197 case OpType::PowScalar: expr = "pow(" + x + ", " + scalarStr(nd.s0) + ")"; break;
198 case OpType::Neg: expr = "(-" + x + ")"; break;
199 case OpType::Abs: expr = "abs(" + x + ")"; break;
200 case OpType::Sqrt: expr = "sqrt(" + x + ")"; break;
201 case OpType::Exp: expr = "exp(" + x + ")"; break;
202 case OpType::Log: expr = "log(" + x + ")"; break;
203 case OpType::Sin: expr = "sin(" + x + ")"; break;
204 case OpType::Cos: expr = "cos(" + x + ")"; break;
205 case OpType::Tanh: expr = "tanh(" + x + ")"; break;
206 case OpType::Relu: expr = "max(" + x + ", 0.0)"; break;
207 case OpType::Sigmoid: expr = "(1.0 / (1.0 + exp(-" + x + ")))"; break;
208 case OpType::Gelu:
209 expr = "(0.5 * " + x + " * (1.0 + tanh(0.7978845608028654 * (" + x + " + 0.044715 * " + x + " * " + x +
210 " * " + x + "))))";
211 break;
212 case OpType::Silu: expr = "(" + x + " / (1.0 + exp(-" + x + ")))"; break;
213 case OpType::Clamp: {
214 float lo = nd.s0, hi = nd.s1;
215 if (lo > hi) std::swap(lo, hi);
216 expr = "clamp(" + x + ", " + scalarStr(lo) + ", " + scalarStr(hi) + ")";
217 break;
218 }
219 case OpType::MaximumScalar: expr = "max(" + x + ", " + scalarStr(nd.s0) + ")"; break;
220 case OpType::MinimumScalar: expr = "min(" + x + ", " + scalarStr(nd.s0) + ")"; break;
221 case OpType::Where:
222 expr = "select(" + operand(nd.in2) + ", " + operand(nd.in1) + ", " + operand(nd.in0) + " > 0.5)";
223 break;
224 default: return "";
225 }
226 const std::string var = "t" + std::to_string(temp++);
227 os << " var " << var << ": f32 = " << expr << ";\n";
228 if (vars.size() <= static_cast<size_t>(nodeId)) vars.resize(static_cast<size_t>(nodeId) + 1);
229 vars[static_cast<size_t>(nodeId)] = var;
230 return var;
231 }
232};
233
239void emitInputIndexExprs(std::ostringstream &os, const Graph &g, const FusedGroup &grp,
240 std::vector<std::string> &indexExprs) {
241 const GraphNode &on = g.node(grp.outputNode);
242 const int rank = on.rank;
243 std::vector<int> S(static_cast<size_t>(rank), 1);
244 if (rank > 0) {
245 S[static_cast<size_t>(rank - 1)] = 1;
246 for (int k = rank - 2; k >= 0; --k) S[static_cast<size_t>(k)] = S[static_cast<size_t>(k + 1)] * on.dims[k + 1];
247 }
248 indexExprs.resize(grp.inputs.size());
249 for (size_t k = 0; k < grp.inputs.size(); ++k) {
250 const GraphNode &inN = g.node(grp.inputs[k]);
251 bool identical = inN.rank == rank;
252 if (identical) {
253 for (int d = 0; d < rank; ++d)
254 if (inN.dims[d] != on.dims[d]) {
255 identical = false;
256 break;
257 }
258 }
259 if (identical) {
260 indexExprs[k] = "i_";
261 continue;
262 }
263 const int pad = rank - inN.rank;
264 std::vector<int> stride(static_cast<size_t>(rank), 0);
265 for (int d = 0; d < rank; ++d) {
266 const int dim = d < pad ? 1 : inN.dims[d - pad];
267 if (dim == 1) continue;
268 int s = 1;
269 for (int t = d + 1; t < rank; ++t) {
270 const int dt = t < pad ? 1 : inN.dims[t - pad];
271 if (dt != 1) s *= dt;
272 }
273 stride[static_cast<size_t>(d)] = s;
274 }
275 const std::string var = "idx" + std::to_string(k);
276 os << " var " << var << ": u32 = 0u;\n";
277 for (int d = 0; d < rank; ++d) {
278 if (stride[static_cast<size_t>(d)] == 0) continue;
279 os << " " << var << " += ((i_ / " << S[static_cast<size_t>(d)] << "u) % " << on.dims[d] << "u) * "
280 << stride[static_cast<size_t>(d)] << "u;\n";
281 }
282 indexExprs[k] = var;
283 }
284}
285
286void genElementwise(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
287 if (grp.inputs.size() > size_t(kMaxKernelBindings - 1))
288 throw eve::Exception("Tensor WGSL: unsupported kernel variant or binding count");
289 const GraphNode &on = g.node(grp.outputNode);
290 std::ostringstream os;
291 os << header(kLocalSize);
292 for (size_t k = 0; k < grp.inputs.size(); ++k) os << bufferDecl(int(k), ("a" + std::to_string(k)).c_str());
293 os << bufferDecl(int(grp.inputs.size()), "o");
294 os << pushConstant();
295 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
296 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
297 os << " var i_: u32 = globalId.x;\n";
298 os << " if (i_ >= " << on.size << "u) { return; }\n";
299 std::vector<std::string> indexExprs;
300 emitInputIndexExprs(os, g, grp, indexExprs);
301 ChainContext ctx{g, grp, indexExprs, "", os, 0, ""};
302 for (int u : grp.nodes) ctx.emit(u);
303 os << " o[i_] = " << ctx.vars[static_cast<size_t>(grp.outputNode)] << ";\n";
304 os << "}\n";
305 out.pass1.clear();
306 out.pass2 = os.str();
307 out.groupsX2 = groupsFor(on.size);
308 out.inputCount = int(grp.inputs.size());
309 return;
310}
311
313void genMatMul(const Graph &g, const FusedGroup &grp, bool tiled, KernelSpec &out) {
314 const GraphNode &mm = g.node(grp.nodes.front());
315 const GraphNode &A = g.node(mm.in0);
316 const GraphNode &B = g.node(mm.in1);
317 const bool batched = mm.rank == 3;
318 const int batch = batched ? A.dims[0] : 1;
319 const int m = A.dims[batched ? 1 : 0];
320 const int k = A.dims[batched ? 2 : 1];
321 const int n = B.dims[batched ? 2 : 1];
322 const bool hasBias = grp.biasNode >= 0;
323 const bool bQuant = q::isQuantDType(static_cast<DType>(B.dtype)) && !B.constBytes.empty();
324 if (bQuant && tiled)
325 throw eve::Exception("Tensor WGSL: unsupported kernel variant or binding count"); // quantized weights use the
326 // naive variant only
327 const int scalesBinding = hasBias ? 3 : 2;
328 const int bindingOut = bQuant ? (hasBias ? 4 : 3) : (hasBias ? 3 : 2);
329
330 std::ostringstream os;
331 if (!tiled) {
332 os << header(kLocalSize);
333 } else {
334 os << header(16, 16);
335 }
336 os << bufferDecl(0, "a");
337 if (bQuant)
338 os << bufferDeclUint(1, "b");
339 else
340 os << bufferDecl(1, "b");
341 if (hasBias) os << bufferDecl(2, "bias");
342 if (bQuant && B.dtype != static_cast<int>(DType::Fp16)) os << bufferDecl(scalesBinding, "bs");
343 os << bufferDecl(bindingOut, "o");
344 os << pushConstant();
345 if (bQuant) os << emitQuantizedBVal(static_cast<DType>(B.dtype), B.qGroup);
346
347 std::vector<std::string> indexExprs(grp.inputs.size(), "i_");
348 ChainContext ctx{g, grp, indexExprs, "r", os, 0, ""};
349 ctx.biasIndexExpr = "jj";
350
351 if (!tiled) {
352 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
353 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) "
354 "{\n";
355 os << " var i_: u32 = globalId.x;\n";
356 os << " if (i_ >= " << batch * m * n << "u) { return; }\n";
357 if (batched) {
358 os << " var bb: u32 = i_ / " << m * n << "u;\n";
359 os << " var rem: u32 = i_ % " << m * n << "u;\n";
360 os << " var ii: u32 = rem / " << n << "u;\n";
361 os << " var jj: u32 = rem % " << n << "u;\n";
362 } else {
363 os << " var ii: u32 = i_ / " << n << "u;\n";
364 os << " var jj: u32 = i_ % " << n << "u;\n";
365 }
366 os << " var r: f32 = 0.0;\n";
367 os << " for (var t: u32 = 0u; t < " << k << "u; t++) {\n";
368 if (batched) {
369 os << " r += a[bb * " << m * k << "u + ii * " << k << "u + t] * "
370 << (bQuant ? "bval(bb * " + std::to_string(k * n) + "u + t * " + std::to_string(n) + "u + jj)"
371 : "b[bb * " + std::to_string(k * n) + "u + t * " + std::to_string(n) + "u + jj]")
372 << ";\n";
373 } else {
374 os << " r += a[ii * " << k << "u + t] * "
375 << (bQuant ? "bval(t * " + std::to_string(n) + "u + jj)" : "b[t * " + std::to_string(n) + "u + jj]")
376 << ";\n";
377 }
378 os << " }\n";
379 for (int u : grp.epilogue) ctx.emit(u);
380 const std::string finalExpr =
381 grp.epilogue.empty() ? std::string("r") : ctx.vars[static_cast<size_t>(grp.outputNode)];
382 os << " o[i_] = " << finalExpr << ";\n";
383 os << "}\n";
384 out.groupsX2 = groupsFor(batch * m * n);
385 } else {
386 ctx.biasIndexExpr = "col";
387 const int gx = (n + 15) / 16;
388 const int gy = (m + 15) / 16;
389 os << "var<workgroup> As: array<array<f32, 17>, 16>;\n";
390 os << "var<workgroup> Bs: array<array<f32, 17>, 16>;\n";
391 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
392 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) "
393 "{\n";
394 os << " var tx: u32 = localId.x;\n";
395 os << " var ty: u32 = localId.y;\n";
396 os << " var row: u32 = globalId.y;\n";
397 os << " var col: u32 = globalId.x;\n";
398 os << " var acc: f32 = 0.0;\n";
399 os << " for (var tile: u32 = 0u; tile < " << (k + 15) / 16 << "u; tile++) {\n";
400 os << " var aCol: u32 = tile * 16u + tx;\n";
401 os << " var bRow: u32 = tile * 16u + ty;\n";
402 os << " As[ty][tx] = 0.0; Bs[ty][tx] = 0.0;\n";
403 os << " if (aCol < " << k << "u && row < " << m << "u) { As[ty][tx] = a[row * " << k << "u + aCol]; }\n";
404 os << " if (bRow < " << k << "u && col < " << n << "u) { Bs[ty][tx] = b[bRow * " << n << "u + col]; }\n";
405 os << " workgroupBarrier();\n";
406 os << " for (var t: u32 = 0u; t < 16u; t++) { acc += As[ty][t] * Bs[t][tx]; }\n";
407 os << " workgroupBarrier();\n";
408 os << " }\n";
409 os << " if (row >= " << m << "u || col >= " << n << "u) { return; }\n";
410 os << " var i_: u32 = row * " << n << "u + col;\n";
411 os << " var r: f32 = acc;\n";
412 for (int u : grp.epilogue) ctx.emit(u);
413 const std::string finalExpr =
414 grp.epilogue.empty() ? std::string("r") : ctx.vars[static_cast<size_t>(grp.outputNode)];
415 os << " o[i_] = " << finalExpr << ";\n}\n";
416 out.groupsX2 = gx;
417 out.groupsY2 = gy;
418 }
419 out.pass1.clear();
420 out.pass2 = os.str();
421 out.inputCount = hasBias ? 3 : 2;
422 out.qDtype = bQuant ? B.dtype : 0;
423 out.qGroup = B.qGroup;
424 out.scalesBinding = bQuant && B.dtype != static_cast<int>(DType::Fp16) ? scalesBinding : -1;
425 out.outputBinding = bQuant ? bindingOut : -1;
426 if (tiled && batched)
427 throw eve::Exception(
428 "Tensor WGSL: unsupported kernel variant or binding count"); // batched matmul uses the naive variant
429 return;
430}
431
432void genConv(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
433 const GraphNode &cn = g.node(grp.nodes.front());
434 const GraphNode &X = g.node(cn.in0);
435 const GraphNode &Wt = g.node(cn.in1);
436 const bool is1d = cn.type == OpType::Conv1d;
437 const int stride = cn.i0, pad = cn.i1;
438 const bool hasBias = grp.biasNode >= 0;
439 const bool hasConvBias = cn.in2 >= 0;
440 const int bindingOut = 2 + int(hasConvBias) + int(hasBias);
441
442 std::ostringstream os;
443 os << header(kLocalSize);
444 os << bufferDecl(0, "x");
445 os << bufferDecl(1, "w");
446 if (hasConvBias) os << bufferDecl(2, "convBias");
447 if (hasBias) os << bufferDecl(hasConvBias ? 3 : 2, "bias");
448 os << bufferDecl(bindingOut, "o");
449 os << pushConstant();
450 std::vector<std::string> indexExprs(grp.inputs.size(), "i_");
451 ChainContext ctx{g, grp, indexExprs, "r", os, 0, ""};
452 ctx.biasIndexExpr = is1d ? "ol" : "ow";
453
454 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
455 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
456 os << " var i_: u32 = globalId.x;\n";
457 os << " if (i_ >= " << g.node(grp.outputNode).size << "u) { return; }\n";
458 if (is1d) {
459 const int C = X.dims[1], L = X.dims[2];
460 const int F = Wt.dims[0], K = Wt.dims[2];
461 os << " var n_: u32 = i_ / (" << F << "u * " << cn.dims[2] << "u);\n";
462 os << " var rem: u32 = i_ % (" << F << "u * " << cn.dims[2] << "u);\n";
463 os << " var f: u32 = rem / " << cn.dims[2] << "u;\n";
464 os << " var ol: u32 = rem % " << cn.dims[2] << "u;\n";
465 os << " var r: f32 = " << (hasConvBias ? "convBias[f]" : "0.0") << ";\n";
466 os << " for (var c: u32 = 0u; c < " << C << "u; c++) {\n";
467 os << " for (var kk: u32 = 0u; kk < " << K << "u; kk++) {\n";
468 os << " var il: i32 = i32(ol) * " << stride << " + i32(kk) - " << pad << ";\n";
469 os << " if (il < 0 || il >= " << L << ") { continue; }\n";
470 os << " r += x[(n_ * " << C << "u + c) * " << L << "u + u32(il)] * w[(f * " << C << "u + c) * " << K
471 << "u + kk];\n";
472 os << " }\n";
473 os << " }\n";
474 } else {
475 const int C = X.dims[1], H = X.dims[2], W = X.dims[3];
476 const int F = Wt.dims[0], KH = Wt.dims[2], KW = Wt.dims[3];
477 os << " var n_: u32 = i_ / (" << F << "u * " << cn.dims[2] << "u * " << cn.dims[3] << "u);\n";
478 os << " var rem: u32 = i_ % (" << F << "u * " << cn.dims[2] << "u * " << cn.dims[3] << "u);\n";
479 os << " var f: u32 = rem / (" << cn.dims[2] << "u * " << cn.dims[3] << "u);\n";
480 os << " var rem2: u32 = rem % (" << cn.dims[2] << "u * " << cn.dims[3] << "u);\n";
481 os << " var oh: u32 = rem2 / " << cn.dims[3] << "u;\n";
482 os << " var ow: u32 = rem2 % " << cn.dims[3] << "u;\n";
483 os << " var r: f32 = " << (hasConvBias ? "convBias[f]" : "0.0") << ";\n";
484 os << " for (var c: u32 = 0u; c < " << C << "u; c++) {\n";
485 os << " for (var kh: u32 = 0u; kh < " << KH << "u; kh++) {\n";
486 os << " var ih: i32 = i32(oh) * " << stride << " + i32(kh) - " << pad << ";\n";
487 os << " if (ih < 0 || ih >= " << H << ") { continue; }\n";
488 os << " for (var kw: u32 = 0u; kw < " << KW << "u; kw++) {\n";
489 os << " var iw: i32 = i32(ow) * " << stride << " + i32(kw) - " << pad << ";\n";
490 os << " if (iw < 0 || iw >= " << W << ") { continue; }\n";
491 os << " r += x[((n_ * " << C << "u + c) * " << H << "u + u32(ih)) * " << W << "u + u32(iw)] * w[((f * "
492 << C << "u + c) * " << KH << "u + kh) * " << KW << "u + kw];\n";
493 os << " }\n";
494 os << " }\n";
495 os << " }\n";
496 }
497 for (int u : grp.epilogue) ctx.emit(u);
498 const std::string finalExpr =
499 grp.epilogue.empty() ? std::string("r") : ctx.vars[static_cast<size_t>(grp.outputNode)];
500 os << " o[i_] = " << finalExpr << ";\n";
501 os << "}\n";
502 out.pass1.clear();
503 out.pass2 = os.str();
504 out.groupsX2 = groupsFor(g.node(grp.outputNode).size);
505 out.inputCount = 2 + int(hasConvBias) + int(hasBias);
506 return;
507}
508
509void genPool(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
510 const GraphNode &pn = g.node(grp.outputNode);
511 const GraphNode &X = g.node(pn.in0);
512 const int ksize = pn.i0, stride = pn.i1, pad = pn.i2;
513 const int C = X.dims[1], H = X.dims[2], W = X.dims[3];
514 const int OH = pn.dims[2], OW = pn.dims[3];
515 const bool maxPool = pn.type == OpType::MaxPool2d;
516 std::ostringstream os;
517 os << header(kLocalSize);
518 os << bufferDecl(0, "in_");
519 os << bufferDecl(1, "o");
520 os << pushConstant();
521 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
522 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
523 os << " var i_: u32 = globalId.x;\n";
524 os << " if (i_ >= " << pn.size << "u) { return; }\n";
525 os << " var n_: u32 = i_ / (" << C << "u * " << OH << "u * " << OW << "u);\n";
526 os << " var rem: u32 = i_ % (" << C << "u * " << OH << "u * " << OW << "u);\n";
527 os << " var c: u32 = rem / (" << OH << "u * " << OW << "u);\n";
528 os << " var rem2: u32 = rem % (" << OH << "u * " << OW << "u);\n";
529 os << " var oh: u32 = rem2 / " << OW << "u;\n";
530 os << " var ow: u32 = rem2 % " << OW << "u;\n";
531 os << " var acc: f32 = " << (maxPool ? "-3.402823e38" : "0.0") << ";\n";
532 os << " var valid: i32 = 0;\n";
533 os << " for (var kh: i32 = 0; kh < " << ksize << "; kh++) {\n";
534 os << " var ih: i32 = i32(oh) * " << stride << " + kh - " << pad << ";\n";
535 os << " if (ih < 0 || ih >= " << H << ") { continue; }\n";
536 os << " for (var kw: i32 = 0; kw < " << ksize << "; kw++) {\n";
537 os << " var iw: i32 = i32(ow) * " << stride << " + kw - " << pad << ";\n";
538 os << " if (iw < 0 || iw >= " << W << ") { continue; }\n";
539 os << " var v: f32 = in_[((n_ * " << C << "u + c) * " << H << "u + u32(ih)) * " << W << "u + u32(iw)];\n";
540 if (maxPool) {
541 os << " acc = max(acc, v);\n";
542 } else {
543 os << " acc += v; valid++;\n";
544 }
545 os << " }\n";
546 os << " }\n";
547 if (!maxPool) os << " if (valid > 0) { acc /= f32(valid); }\n";
548 os << " o[i_] = acc;\n";
549 os << "}\n";
550 out.pass1.clear();
551 out.pass2 = os.str();
552 out.groupsX2 = groupsFor(pn.size);
553 out.inputCount = 1;
554 return;
555}
556
557} // namespace wgsl_detail
558
560 using namespace wgsl_detail;
561 out = KernelSpec{};
562 switch (group.kind) {
563 case GroupKind::Elementwise: return genElementwise(graph, group, out);
565 // naive variant first; the runtime autotunes between naive and tiled
566 return genMatMul(graph, group, false, out);
568 case GroupKind::Conv2d: return genConv(graph, group, out);
570 case GroupKind::AvgPool2d: return genPool(graph, group, out);
571 case GroupKind::Softmax: return genSoftmax(graph, group, out);
572 case GroupKind::LayerNorm: return genNorm(graph, group, false, out);
573 case GroupKind::RMSNorm: return genNorm(graph, group, true, out);
575 case GroupKind::ArgMax: return genReduceOrArgmax(graph, group, group.kind == GroupKind::ArgMax, out);
576 case GroupKind::Embedding: return genEmbedding(graph, group, out);
577 case GroupKind::Concat: return genConcat(graph, group, out);
578 case GroupKind::Slice: return genSlice(graph, group, out);
579 case GroupKind::Permute: return genPermute(graph, group, out);
580 case GroupKind::Resize2d: return genResize2d(graph, group, out);
581 case GroupKind::Sdpa: return genSdpa(graph, group, out);
582 case GroupKind::Alias: return; // no kernel; pure buffer alias
583 }
584 throw eve::Exception("Tensor WGSL: unsupported kernel variant or binding count");
585}
586
588 try {
591 if (group.kind != GroupKind::MatMul)
593 DiagnosticCode::Unsupported, "Tiled WGSL requires a matrix product", "tensor.kernel"));
595 } else {
597 }
599 return Result<KernelSpec>::success(std::move(out));
600 } catch (const std::exception &error) {
602 Diagnostic::error(DiagnosticCode::Unsupported, error.what(), "tensor.kernel"));
603 }
604}
605
606} // namespace eve::tensor
607
608// KernelGenWgslBindings.cpp
609namespace eve::tensor::wgsl_detail {
610namespace {
611int storageNode(const Graph &graph, int id) {
612 const auto &node = graph.node(id);
613 switch (node.type) {
614 case OpType::Reshape:
615 case OpType::Flatten:
616 case OpType::Cast: return storageNode(graph, node.in0);
617 default: return id;
618 }
619}
620
621// Specialize only our generated declarations and identifier tokens, never arbitrary user shaders.
622void specializeSource(std::string &source, const std::vector<int> &representatives, int inputCount) {
623 std::vector<std::string> names(static_cast<size_t>(inputCount));
624 std::map<std::string, std::string> aliases;
625 for (int i = 0; i < inputCount; ++i) {
626 const std::string prefix = "@group(0) @binding(" + std::to_string(i) + ") var<storage, read_write> ";
627 const auto begin = source.find(prefix);
628 if (begin == std::string::npos) throw eve::Exception("Tensor WGSL: missing input declaration");
629 const auto nameBegin = begin + prefix.size();
630 const auto nameEnd = source.find(':', nameBegin);
631 names[static_cast<size_t>(i)] = source.substr(nameBegin, nameEnd - nameBegin);
632 if (representatives[static_cast<size_t>(i)] == i) continue;
633 aliases.emplace(names[static_cast<size_t>(i)],
634 names[static_cast<size_t>(representatives[static_cast<size_t>(i)])]);
635 source.erase(begin, source.find('\n', nameEnd) + 1 - begin);
636 }
637 if (aliases.empty()) return;
638 std::string renamed;
639 for (size_t i = 0; i < source.size();) {
640 const unsigned char ch = static_cast<unsigned char>(source[i]);
641 if (std::isalpha(ch) || ch == '_') {
642 const auto begin = i++;
643 while (i < source.size() && (std::isalnum(static_cast<unsigned char>(source[i])) || source[i] == '_')) ++i;
644 const std::string word = source.substr(begin, i - begin);
645 const auto found = aliases.find(word);
646 renamed += found == aliases.end() ? word : found->second;
647 } else {
648 renamed += source[i++];
649 }
650 }
651 source = std::move(renamed);
652}
653} // namespace
654
656 std::map<int, int> first;
657 for (int i = 0; i < spec.inputCount; ++i) {
658 const auto [it, inserted] = first.emplace(storageNode(graph, group.inputs[static_cast<size_t>(i)]), i);
659 (void)inserted;
660 spec.inputRepresentatives.push_back(it->second);
661 }
662 if (spec.twoPass) specializeSource(spec.pass1, spec.inputRepresentatives, spec.inputsReadPass1);
663 if (!spec.pass2.empty()) specializeSource(spec.pass2, spec.inputRepresentatives, spec.inputCount);
664}
665} // namespace eve::tensor::wgsl_detail
666
667// KernelGenWgslIndex.cpp
668namespace eve::tensor::wgsl_detail {
669void genEmbedding(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
670 const GraphNode &en = g.node(grp.outputNode);
671 const GraphNode &T = g.node(en.in0);
672 const bool tQuant = q::isQuantDType(static_cast<DType>(T.dtype)) && !T.constBytes.empty();
673 const bool tInt = T.dtype != static_cast<int>(DType::Fp16);
674 const int vocab = T.dims[0], dim = T.dims[1];
675 std::ostringstream os;
676 os << header(kLocalSize);
677 if (tQuant)
678 os << bufferDeclUint(0, "table");
679 else
680 os << bufferDecl(0, "table");
681 os << bufferDecl(1, "idx");
682 if (tQuant && tInt) os << bufferDecl(2, "bs");
683 os << bufferDecl(tQuant ? 3 : 2, "o");
684 os << pushConstant();
685 if (tQuant) os << emitQuantizedBVal(static_cast<DType>(T.dtype), T.qGroup, "table");
686 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
687 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
688 os << " var i_: u32 = globalId.x;\n";
689 os << " if (i_ >= " << en.size << "u) { return; }\n";
690 os << " var r: u32 = i_ / " << dim << "u;\n";
691 os << " var d: u32 = i_ % " << dim << "u;\n";
692 os << " var ii: i32 = i32(idx[r]);\n";
693 os << " ii = clamp(ii, 0, " << (vocab - 1) << ");\n";
694 os << " o[i_] = "
695 << (tQuant ? "bval(u32(ii) * " + std::to_string(dim) + "u + d)"
696 : "table[u32(ii) * " + std::to_string(dim) + "u + d]")
697 << ";\n";
698 os << "}\n";
699 out.pass1.clear();
700 out.pass2 = os.str();
701 out.groupsX2 = groupsFor(en.size);
702 out.inputCount = 2;
703 out.qDtype = tQuant ? T.dtype : 0;
704 out.qGroup = T.qGroup;
705 out.scalesBinding = tQuant && tInt ? 2 : -1;
706 out.outputBinding = tQuant ? 3 : -1;
707 return;
708}
709
710void genConcat(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
711 const GraphNode &cn = g.node(grp.outputNode);
712 const int axis = cn.i0;
713 const int n = int(grp.inputs.size());
714 if (n < 2 || n > 4) throw eve::Exception("Tensor WGSL: unsupported kernel variant or binding count");
715 int starts[4] = {};
716 int axisTotal = 0;
717 for (int k = 0; k < n; ++k) {
718 starts[k] = axisTotal;
719 axisTotal += g.node(grp.inputs[static_cast<size_t>(k)]).dims[axis];
720 }
721 int inner = 1;
722 for (int k = axis + 1; k < cn.rank; ++k) inner *= cn.dims[k];
723 std::ostringstream os;
724 os << header(kLocalSize);
725 for (int k = 0; k < n; ++k) os << bufferDecl(k, ("a" + std::to_string(k)).c_str());
726 os << bufferDecl(n, "o");
727 os << pushConstant();
728 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
729 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
730 os << " var i_: u32 = globalId.x;\n";
731 os << " if (i_ >= " << cn.size << "u) { return; }\n";
732 os << " var ax: u32 = (i_ / " << inner << "u) % " << axisTotal << "u;\n";
733 os << " var op: u32 = i_ / (" << axisTotal << "u * " << inner << "u);\n";
734 os << " var ip: u32 = i_ % " << inner << "u;\n";
735 os << " var v: f32 = 0.0;\n";
736 for (int k = 0; k < n; ++k) {
737 const int sz = g.node(grp.inputs[static_cast<size_t>(k)]).dims[axis];
738 const char *cond = k == 0 ? "if" : "else if";
739 os << " " << cond << " (ax >= " << starts[k] << "u && ax < " << starts[k] + sz << "u) {\n";
740 os << " v = a" << k << "[op * " << sz << "u * " << inner << "u + (ax - " << starts[k] << "u) * " << inner
741 << "u + ip];\n";
742 os << " }\n";
743 }
744 os << " o[i_] = v;\n";
745 os << "}\n";
746 out.pass1.clear();
747 out.pass2 = os.str();
748 out.groupsX2 = groupsFor(cn.size);
749 out.inputCount = n;
750 return;
751}
752
753void genSlice(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
754 const GraphNode &sn = g.node(grp.outputNode);
755 const GraphNode &X = g.node(sn.in0);
756 const int axis = sn.i0, begin = sn.i1, end = sn.i2;
757 const int axisSize = end - begin;
758 int inner = 1;
759 for (int k = axis + 1; k < sn.rank; ++k) inner *= sn.dims[k];
760 std::ostringstream os;
761 os << header(kLocalSize);
762 os << bufferDecl(0, "in_");
763 os << bufferDecl(1, "o");
764 os << pushConstant();
765 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
766 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
767 os << " var i_: u32 = globalId.x;\n";
768 os << " if (i_ >= " << sn.size << "u) { return; }\n";
769 os << " var ax: u32 = (i_ / " << inner << "u) % " << axisSize << "u;\n";
770 os << " var op: u32 = i_ / (" << axisSize << "u * " << inner << "u);\n";
771 os << " var ip: u32 = i_ % " << inner << "u;\n";
772 os << " o[i_] = in_[op * " << X.dims[axis] << "u * " << inner << "u + (ax + " << begin << "u) * " << inner
773 << "u + ip];\n";
774 os << "}\n";
775 out.pass1.clear();
776 out.pass2 = os.str();
777 out.groupsX2 = groupsFor(sn.size);
778 out.inputCount = 1;
779 return;
780}
781
782void genPermute(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
783 const GraphNode &pn = g.node(grp.outputNode);
784 const GraphNode &X = g.node(pn.in0);
785 const int rank = pn.rank;
786 int S[Tensor::kMaxRank] = {};
787 S[rank - 1] = 1;
788 for (int k = rank - 2; k >= 0; --k) S[k] = S[k + 1] * pn.dims[k + 1];
789 int inStride[Tensor::kMaxRank] = {};
790 inStride[rank - 1] = 1;
791 for (int k = rank - 2; k >= 0; --k) inStride[k] = inStride[k + 1] * X.dims[k + 1];
792 std::ostringstream os;
793 os << header(kLocalSize);
794 os << bufferDecl(0, "in_");
795 os << bufferDecl(1, "o");
796 os << pushConstant();
797 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
798 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
799 os << " var i_: u32 = globalId.x;\n";
800 os << " if (i_ >= " << pn.size << "u) { return; }\n";
801 os << " var idx: u32 = 0u;\n";
802 for (int k = 0; k < rank; ++k) {
803 const int inAxis = pn.perm[k];
804 os << " idx += ((i_ / " << S[k] << "u) % " << pn.dims[k] << "u) * " << inStride[inAxis] << "u;\n";
805 }
806 os << " o[i_] = in_[idx];\n";
807 os << "}\n";
808 out.pass1.clear();
809 out.pass2 = os.str();
810 out.groupsX2 = groupsFor(pn.size);
811 out.inputCount = 1;
812 return;
813}
814
815void genResize2d(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
816 const GraphNode &rn = g.node(grp.outputNode);
817 const GraphNode &X = g.node(rn.in0);
818 const int H = X.dims[2], W = X.dims[3];
819 const int OH = rn.dims[2], OW = rn.dims[3];
820 const bool nearest = rn.i0 == 0;
821 std::ostringstream os;
822 os << header(kLocalSize);
823 os << bufferDecl(0, "in_");
824 os << bufferDecl(1, "o");
825 os << pushConstant();
826 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
827 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
828 os << " var i_: u32 = globalId.x;\n";
829 os << " if (i_ >= " << rn.size << "u) { return; }\n";
830 os << " var ow: u32 = i_ % " << OW << "u;\n";
831 os << " var rem: u32 = i_ / " << OW << "u;\n";
832 os << " var oh: u32 = rem % " << OH << "u;\n";
833 os << " var rem2: u32 = rem / " << OH << "u;\n";
834 os << " var c: u32 = rem2 % " << X.dims[1] << "u;\n";
835 os << " var n_: u32 = rem2 / " << X.dims[1] << "u;\n";
836 os << " var base: u32 = (n_ * " << X.dims[1] << "u + c) * " << H << "u * " << W << "u;\n";
837 if (nearest) {
838 os << " var ih: u32 = u32(f32(oh) * " << scalarStr(float(H) / OH) << ") ;\n";
839 os << " var iw: u32 = u32(f32(ow) * " << scalarStr(float(W) / OW) << ") ;\n";
840 os << " ih = min(ih, " << H - 1 << "u); iw = min(iw, " << W - 1 << "u);\n";
841 os << " o[i_] = in_[base + ih * " << W << "u + iw];\n";
842 } else {
843 os << " var fx: f32 = (f32(ow) + 0.5) * " << scalarStr(float(W) / OW) << " - 0.5;\n";
844 os << " var fy: f32 = (f32(oh) + 0.5) * " << scalarStr(float(H) / OH) << " - 0.5;\n";
845 os << " fx = clamp(fx, 0.0, " << scalarStr(float(W - 1)) << ");\n";
846 os << " fy = clamp(fy, 0.0, " << scalarStr(float(H - 1)) << ");\n";
847 os << " var x0: u32 = u32(floor(fx)); var y0: u32 = u32(floor(fy));\n";
848 os << " var x1: u32 = min(x0 + 1u, " << W - 1 << "u); var y1: u32 = min(y0 + 1u, " << H - 1 << "u);\n";
849 os << " var w00: f32 = in_[base + y0 * " << W << "u + x0];\n";
850 os << " var w10: f32 = in_[base + y0 * " << W << "u + x1];\n";
851 os << " var w01: f32 = in_[base + y1 * " << W << "u + x0];\n";
852 os << " var w11: f32 = in_[base + y1 * " << W << "u + x1];\n";
853 os << " var top: f32 = w00 + (w10 - w00) * (fx - f32(x0));\n";
854 os << " var bot: f32 = w01 + (w11 - w01) * (fx - f32(x0));\n";
855 os << " o[i_] = top + (bot - top) * (fy - f32(y0));\n";
856 }
857 os << "}\n";
858 out.pass1.clear();
859 out.pass2 = os.str();
860 out.groupsX2 = groupsFor(rn.size);
861 out.inputCount = 1;
862 return;
863}
864
865void genSdpa(const Graph &g, const FusedGroup &grp, KernelSpec &out) {
866 const GraphNode &qn = g.node(grp.outputNode);
867 const GraphNode &Q = g.node(qn.in0);
868 const GraphNode &K = g.node(qn.in1);
869 const int B = Q.dims[0], H = Q.dims[1], T = Q.dims[2], D = Q.dims[3];
870 const int S = K.dims[2];
871 if (S > 2048 || D > 512)
872 throw eve::Exception(
873 "Tensor WGSL: unsupported kernel variant or binding count"); // shared-memory limits -> CPU fallback
874 const float scale = qn.s0;
875 const bool masked = grp.masked;
876 const int bindingOut = masked ? 4 : 3;
877 std::ostringstream os;
878 os << header(128);
879 os << bufferDecl(0, "q");
880 os << bufferDecl(1, "k");
881 os << bufferDecl(2, "v");
882 if (masked) os << bufferDecl(3, "mask");
883 os << bufferDecl(bindingOut, "o");
884 os << "var<workgroup> scores: array<f32, " << S << ">;\n";
885 os << "var<workgroup> maxv: f32;\n";
886 os << "var<workgroup> sumv: f32;\n";
887 os << pushConstant();
888 os << "@compute @workgroup_size(workgroupX, workgroupY)\nfn main(@builtin(global_invocation_id) globalId: "
889 "vec3<u32>, @builtin(local_invocation_id) localId: vec3<u32>, @builtin(workgroup_id) groupId: vec3<u32>) {\n";
890 os << " var tid: u32 = localId.x;\n";
891 os << " var bh: u32 = groupId.x;\n";
892 os << " var t: u32 = groupId.y;\n";
893 os << " var b: u32 = bh / " << H << "u;\n";
894 os << " var h: u32 = bh % " << H << "u;\n";
895 os << " var qbase: u32 = (b * " << H << "u + h) * " << T << "u * " << D << "u + t * " << D << "u;\n";
896 os << " var kbase: u32 = (b * " << H << "u + h) * " << S << "u * " << D << "u;\n";
897 os << " var vbase: u32 = kbase;\n";
898 os << " for (var s: u32 = tid; s < " << S << "u; s += 128u) {\n";
899 os << " var acc: f32 = 0.0;\n";
900 os << " for (var d: u32 = 0u; d < " << D << "u; d++) { acc += q[qbase + d] * k[kbase + s * " << D
901 << "u + d]; }\n";
902 os << " acc *= " << scalarStr(scale) << ";\n";
903 if (masked) {
904 os << " acc += mask[(b * " << H << "u + h) * " << T << "u * " << S << "u + t * " << S << "u + s];\n";
905 }
906 os << " scores[s] = acc;\n";
907 os << " }\n";
908 os << " workgroupBarrier();\n";
909 os << " if (tid == 0u) {\n";
910 os << " var m: f32 = -3.402823e38;\n";
911 os << " for (var s: u32 = 0u; s < " << S << "u; s++) { m = max(m, scores[s]); }\n";
912 os << " var sm: f32 = 0.0;\n";
913 os << " for (var s: u32 = 0u; s < " << S << "u; s++) { sm += exp(scores[s] - m); }\n";
914 os << " maxv = m; sumv = sm;\n";
915 os << " }\n";
916 os << " workgroupBarrier();\n";
917 os << " for (var d: u32 = tid; d < " << D << "u; d += 128u) {\n";
918 os << " var acc: f32 = 0.0;\n";
919 os << " for (var s: u32 = 0u; s < " << S << "u; s++) { acc += exp(scores[s] - maxv) * v[vbase + s * " << D
920 << "u + d]; }\n";
921 os << " o[qbase + d] = acc / sumv;\n";
922 os << " }\n";
923 os << "}\n";
924 out.pass1.clear();
925 out.pass2 = os.str();
926 out.groupsX2 = B * H;
927 out.groupsY2 = T;
928 out.inputCount = masked ? 4 : 3;
929 return;
930}
931
932
933} // namespace eve::tensor::wgsl_detail
double m[16]
double x
const std::string & s
std::string variant
std::string nodeId
std::string name
Definition ECS.cpp:154
tensor::Graph g
Definition GpuGraph.cpp:7
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
float v
std::int32_t first
JointPoint2D axis
std::array< float, 3 > scale
std::string id
double dt
std::string error
Definition Package.cpp:174
std::map< std::string, std::vector< std::string > > graph
Definition Package.cpp:173
eve::action::ActionVfxBinding binding
int idx
float d
float t
const RoadNode * node
bool found
ScriptStructure out
std::string_view source
size_t begin
size_t end
int count
AbilityActivationGroup group
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
EVENGINE_API_DOMAINS public API.
Definition Graph.h:111
const GraphNode & node(int id) const
Node.
Definition Graph.h:116
static constexpr int kMaxRank
Definition Tensor.h:50
std::string word
std::string header(int localX, int localY)
Header.
Definition KernelGen.cpp:13
std::string bufferDecl(int binding, const char *name)
Buffer decl.
Definition KernelGen.cpp:22
int groupsFor(int count)
Groups for.
std::string scalarStr(float v)
Scalar str.
void genResize2d(const Graph &, const FusedGroup &, KernelSpec &)
Gen resize 2 d.
std::string pushConstant()
Pushes constant.
bool isQuantDType(DType dt)
True when quant d type.
Definition Quant.h:17
std::string scalarStr(float v)
Scalar str.
void genSlice(const Graph &g, const FusedGroup &grp, KernelSpec &out)
Gen slice.
void genConcat(const Graph &g, const FusedGroup &grp, KernelSpec &out)
Gen concat.
std::string emitQuantizedBVal(DType dt, int group, const char *bufName="b")
Emit quantized b val.
void genResize2d(const Graph &g, const FusedGroup &grp, KernelSpec &out)
Gen resize 2 d.
std::string bufferDeclUint(int binding, const char *name)
Buffer decl uint.
void genPermute(const Graph &g, const FusedGroup &grp, KernelSpec &out)
Gen permute.
void genConv(const Graph &g, const FusedGroup &grp, KernelSpec &out)
void specializeInputBindings(const Graph &graph, const FusedGroup &group, KernelSpec &spec)
Specialize input bindings.
void genEmbedding(const Graph &g, const FusedGroup &grp, KernelSpec &out)
Gen embedding.
void genElementwise(const Graph &g, const FusedGroup &grp, KernelSpec &out)
std::string bufferDecl(int binding, const char *name)
Buffer decl.
std::string pushConstant()
Pushes constant.
int groupsFor(int count)
Groups for.
void genPool(const Graph &g, const FusedGroup &grp, KernelSpec &out)
void genSdpa(const Graph &g, const FusedGroup &grp, KernelSpec &out)
Gen sdpa.
void emitInputIndexExprs(std::ostringstream &os, const Graph &g, const FusedGroup &grp, std::vector< std::string > &indexExprs)
std::string header(int localX, int localY)
Header.
void genMatMul(const Graph &g, const FusedGroup &grp, bool tiled, KernelSpec &out)
DType
Tensor element types.
Definition Tensor.h:24
KernelVariant
Internal choice of generated matrix multiplication implementation.
void generateKernelWgslImpl(const Graph &graph, const FusedGroup &group, KernelSpec &out)
constexpr int kMaxKernelBindings
Definition KernelGen.h:69
Result< KernelSpec > generateWgslKernel(const Graph &graph, const FusedGroup &group, KernelVariant variant)
Lower an optimizer-produced group directly to owning WGSL source and dispatch metadata.
FusedGroup public API.
Definition Optimizer.h:46
std::vector< int > epilogue
Definition Optimizer.h:65
std::vector< int > nodes
Definition Optimizer.h:51
std::vector< int > inputs
Definition Optimizer.h:53
GraphNode public API.
Definition Graph.h:80
int perm[Tensor::kMaxRank]
Definition Graph.h:99
int dims[Tensor::kMaxRank]
Definition Graph.h:82
std::vector< uint8_t > constBytes
Definition Graph.h:105
KernelSpec public API.
Definition KernelGen.h:27
std::vector< int > inputRepresentatives
Input slot to representative slot; empty means identity. WGSL aliases repeated read inputs to one dec...
Definition KernelGen.h:34
const std::vector< std::string > & indexExprs
uint32_t pad[2]