@genai-fi/nanogpt 1.6.1 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (427) hide show
  1. package/dist/{binary_op_util-WY9YIl0q.js → Reshape-CqftURg0.js} +75 -60
  2. package/dist/TeachableLLM.d.ts +12 -12
  3. package/dist/api/beamer.d.ts +4 -4
  4. package/dist/api/responses.d.ts +4 -4
  5. package/dist/api/training.d.ts +10 -10
  6. package/dist/backend.d.ts +1 -1
  7. package/dist/backend_util-DZIc6pyV.js +1081 -0
  8. package/dist/checks/index.d.ts +11 -11
  9. package/dist/checks/weights.d.ts +1 -1
  10. package/dist/data/docx.d.ts +1 -1
  11. package/dist/data/pdf.d.ts +1 -1
  12. package/dist/data/stream.d.ts +1 -1
  13. package/dist/data/textLoader.d.ts +1 -1
  14. package/dist/data.d.ts +3 -3
  15. package/dist/device-CZPGtQBU.js +9 -0
  16. package/dist/device.d.ts +2 -0
  17. package/dist/{dist-DeVH1nGn.js → dist-DiszGjH-.js} +1833 -1844
  18. package/dist/{dist-CMMLi-qO.js → dist-JOPw9zTN.js} +69 -11
  19. package/dist/inference/Beamer.d.ts +3 -3
  20. package/dist/inference/Generator.d.ts +4 -4
  21. package/dist/inference/tokenisePrompt.d.ts +2 -2
  22. package/dist/inference/types.d.ts +1 -1
  23. package/dist/inference/utilities.d.ts +1 -1
  24. package/dist/layers/BaseLayer.d.ts +5 -4
  25. package/dist/layers/GQA.d.ts +24 -26
  26. package/dist/layers/HeadLayer.d.ts +2 -2
  27. package/dist/layers/LoRA.d.ts +1 -1
  28. package/dist/layers/MHA.d.ts +3 -4
  29. package/dist/layers/MLP.d.ts +2 -2
  30. package/dist/layers/PositionEmbedding.d.ts +3 -3
  31. package/dist/layers/RMSNorm.d.ts +2 -2
  32. package/dist/layers/RoPECache.d.ts +2 -1
  33. package/dist/layers/TiedEmbedding.d.ts +2 -2
  34. package/dist/layers/TransformerBlock.d.ts +9 -6
  35. package/dist/layers.d.ts +4 -4
  36. package/dist/loader/load.d.ts +1 -1
  37. package/dist/loader/loadHF.d.ts +3 -3
  38. package/dist/loader/loadTransformers.d.ts +2 -2
  39. package/dist/loader/loadZipMeta.d.ts +2 -2
  40. package/dist/loader/newZipLoad.d.ts +2 -2
  41. package/dist/loader/oldZipLoad.d.ts +4 -4
  42. package/dist/loader/save.d.ts +5 -5
  43. package/dist/loader/types.d.ts +23 -10
  44. package/dist/main.d.ts +40 -24
  45. package/dist/matMul16-CiMKJM8v.js +2610 -0
  46. package/dist/models/Llama.d.ts +2 -2
  47. package/dist/models/LoopNano.d.ts +16 -0
  48. package/dist/models/NanoGPTV1.d.ts +2 -2
  49. package/dist/models/NanoGPTV2.d.ts +2 -2
  50. package/dist/models/Qwen3.d.ts +2 -2
  51. package/dist/models/config.d.ts +11 -1
  52. package/dist/models/factory.d.ts +2 -2
  53. package/dist/models/model.d.ts +6 -6
  54. package/dist/models.d.ts +4 -4
  55. package/dist/nanogpt.js +37052 -0
  56. package/dist/ops/adamAdjust.d.ts +2 -0
  57. package/dist/ops/adamMoments.d.ts +2 -0
  58. package/dist/ops/adamW.d.ts +2 -0
  59. package/dist/ops/add16.d.ts +1 -0
  60. package/dist/ops/appendCache.d.ts +2 -0
  61. package/dist/ops/attentionMask.d.ts +11 -1
  62. package/dist/ops/dropout16.d.ts +2 -0
  63. package/dist/ops/gatherSub.d.ts +2 -0
  64. package/dist/ops/gelu.d.ts +3 -0
  65. package/dist/ops/log.d.ts +1 -0
  66. package/dist/ops/matMul16.d.ts +4 -0
  67. package/dist/ops/matMulGelu.d.ts +3 -0
  68. package/dist/ops/matMulMul.d.ts +2 -0
  69. package/dist/ops/mul16.d.ts +1 -0
  70. package/dist/ops/mulDrop.d.ts +2 -0
  71. package/dist/ops/normRMS.d.ts +3 -0
  72. package/dist/ops/pack16.d.ts +1 -0
  73. package/dist/ops/qkv.d.ts +13 -1
  74. package/dist/ops/rope.d.ts +4 -1
  75. package/dist/ops/scatterSub.d.ts +4 -1
  76. package/dist/ops/silu.d.ts +1 -0
  77. package/dist/ops/softmax16.d.ts +1 -0
  78. package/dist/ops/sparseCrossEntropy.d.ts +15 -0
  79. package/dist/ops/unpack16.d.ts +1 -0
  80. package/dist/ops/webgl/sparseCrossEntropy.d.ts +1 -0
  81. package/dist/ops/webgpu/adamW.d.ts +1 -0
  82. package/dist/ops/webgpu/concat16.d.ts +16 -0
  83. package/dist/ops/webgpu/index.d.ts +29 -0
  84. package/dist/ops/webgpu/normRMS16_program.d.ts +2 -2
  85. package/dist/ops/webgpu/normRMS32_program.d.ts +2 -2
  86. package/dist/ops/webgpu/pack16_program.d.ts +1 -1
  87. package/dist/ops/webgpu/softmax16_program.d.ts +16 -0
  88. package/dist/ops/webgpu/sparseCrossEntropy.d.ts +1 -0
  89. package/dist/ops/webgpu/utils/binary_op.d.ts +16 -0
  90. package/dist/ops/webgpu/utils/deviceInfo.d.ts +1 -1
  91. package/dist/ops/webgpu/utils/reductions.d.ts +1 -1
  92. package/dist/patches/webgpu_backend.d.ts +2 -1
  93. package/dist/patches/webgpu_base.d.ts +0 -1
  94. package/dist/patches/webgpu_program.d.ts +21 -0
  95. package/dist/{shared-BIDMUBCs.js → shared-BARkvvG4.js} +587 -505
  96. package/dist/tokenise.d.ts +4 -4
  97. package/dist/tokeniser/BaseTokeniser.d.ts +3 -3
  98. package/dist/tokeniser/CharTokeniser.d.ts +2 -2
  99. package/dist/tokeniser/bpe.d.ts +2 -2
  100. package/dist/tokeniser/type.d.ts +2 -2
  101. package/dist/training/AdamW.d.ts +19 -2
  102. package/dist/training/BasicTrainer.d.ts +5 -5
  103. package/dist/training/DatasetBuilder.d.ts +16 -9
  104. package/dist/training/Evaluator.d.ts +1 -1
  105. package/dist/training/LRScheduler.d.ts +1 -1
  106. package/dist/training/PreTrainer.d.ts +6 -6
  107. package/dist/training/SFTTrainer.d.ts +6 -6
  108. package/dist/training/configure.d.ts +2 -2
  109. package/dist/training/factory.d.ts +6 -5
  110. package/dist/training/prepareData.d.ts +7 -7
  111. package/dist/training/tasks/TokenStore.d.ts +4 -4
  112. package/dist/training/tasks/tokenStream.d.ts +3 -3
  113. package/dist/training/types.d.ts +8 -7
  114. package/dist/training/validateOptions.d.ts +1 -1
  115. package/dist/training/validation.d.ts +5 -5
  116. package/dist/utilities/datasetID.d.ts +1 -1
  117. package/dist/utilities/dummy.d.ts +1 -1
  118. package/dist/utilities/packed.d.ts +1 -1
  119. package/dist/utilities/parameters.d.ts +1 -1
  120. package/dist/utilities/sentences.d.ts +1 -1
  121. package/dist/utilities/waitForModel.d.ts +1 -1
  122. package/dist/webgpu-D4syGmzo.js +3221 -0
  123. package/dist/webgpu-wUCQopBN.js +1007 -0
  124. package/dist/{webgpu_program-DvkFqRlR.js → webgpu_backend-CzY9TzvA.js} +174 -223
  125. package/dist/{patches/webgpu_base.js → webgpu_base-Bjg7okYf.js} +6 -9
  126. package/package.json +12 -9
  127. package/dist/DatasetBuilder-DRDW8tcM.js +0 -731
  128. package/dist/Generator-8IK28IWR.js +0 -316
  129. package/dist/RealDiv-Cl8k3YTx.js +0 -354
  130. package/dist/Reshape-CKxKPKqi.js +0 -91
  131. package/dist/Reshape-H5zZRgr9.js +0 -16
  132. package/dist/RoPECache-dYscFINl.js +0 -722
  133. package/dist/TeachableLLM.js +0 -220
  134. package/dist/api/beamer.js +0 -61
  135. package/dist/api/responses.js +0 -177
  136. package/dist/api/training.js +0 -215
  137. package/dist/axis_util-rF9RnwKE.js +0 -37
  138. package/dist/backend.js +0 -12
  139. package/dist/backend_util-Cpp0Gwlp.js +0 -394
  140. package/dist/broadcast_to-CGvLNiQ0.js +0 -20
  141. package/dist/checks/appendCache.js +0 -55
  142. package/dist/checks/attentionMask.js +0 -57
  143. package/dist/checks/check.js +0 -31
  144. package/dist/checks/gelu.js +0 -46
  145. package/dist/checks/index.js +0 -27
  146. package/dist/checks/matMulGelu.js +0 -84
  147. package/dist/checks/normRMS.js +0 -30
  148. package/dist/checks/normRMSGrad.js +0 -23
  149. package/dist/checks/packUnpack.js +0 -46
  150. package/dist/checks/qkv.js +0 -1
  151. package/dist/checks/rope.js +0 -30
  152. package/dist/checks/weights.js +0 -26
  153. package/dist/clip_by_value-D-UX9am5.js +0 -13
  154. package/dist/complex-Cl904TqN.js +0 -13
  155. package/dist/complex_util-BBlPAm-s.js +0 -59
  156. package/dist/concat-Oip5acVY.js +0 -14
  157. package/dist/concat_util-CY45Hf4F.js +0 -18
  158. package/dist/data/docx.js +0 -17
  159. package/dist/data/pdf.js +0 -14
  160. package/dist/data/stream.js +0 -1
  161. package/dist/data/textLoader.js +0 -575
  162. package/dist/data-CV_i_H6B.js +0 -11
  163. package/dist/data.js +0 -5
  164. package/dist/dist-DyL7qSLJ.js +0 -7809
  165. package/dist/dropout16-CA31Ud5a.js +0 -20
  166. package/dist/dropout_util-SiFMbFXz.js +0 -22
  167. package/dist/eventemitter3-wmfmOP_f.js +0 -90
  168. package/dist/expand_dims-Dh3Fulyn.js +0 -10
  169. package/dist/floor-BwjmUb7X.js +0 -8
  170. package/dist/gather-B5Z1RFt5.js +0 -14
  171. package/dist/gatherSub-CRUfUzBa.js +0 -22
  172. package/dist/gelu-Xx9-ohH9.js +0 -25
  173. package/dist/gpgpu_math-48m8q3jI.js +0 -1591
  174. package/dist/inference/Beamer.js +0 -215
  175. package/dist/inference/Generator.js +0 -1
  176. package/dist/inference/tokenisePrompt.js +0 -17
  177. package/dist/inference/types.js +0 -0
  178. package/dist/inference/utilities.js +0 -31
  179. package/dist/jszip.min-Btv48m44.js +0 -3037
  180. package/dist/kernel_funcs_utils-BYRpSfV_.js +0 -229
  181. package/dist/layers/BaseLayer.js +0 -75
  182. package/dist/layers/GQA.js +0 -102
  183. package/dist/layers/HeadLayer.js +0 -28
  184. package/dist/layers/LoRA.js +0 -45
  185. package/dist/layers/MHA.js +0 -102
  186. package/dist/layers/MLP.js +0 -47
  187. package/dist/layers/PositionEmbedding.js +0 -28
  188. package/dist/layers/RMSNorm.js +0 -25
  189. package/dist/layers/RoPECache.js +0 -1
  190. package/dist/layers/TiedEmbedding.js +0 -33
  191. package/dist/layers/TransformerBlock.js +0 -50
  192. package/dist/layers/WeightStore.js +0 -68
  193. package/dist/layers-CFqEip3s.js +0 -13
  194. package/dist/layers.js +0 -6
  195. package/dist/loader/load.js +0 -63
  196. package/dist/loader/loadHF.js +0 -17
  197. package/dist/loader/loadTransformers.js +0 -61
  198. package/dist/loader/loadZipMeta.js +0 -15
  199. package/dist/loader/newZipLoad.js +0 -24
  200. package/dist/loader/oldZipLoad.js +0 -36
  201. package/dist/loader/save.js +0 -89
  202. package/dist/loader/types.js +0 -0
  203. package/dist/main.js +0 -12145
  204. package/dist/matMul16-tE26fnhf.js +0 -87
  205. package/dist/matMulGelu-ASUWlKqu.js +0 -162
  206. package/dist/mat_mul-R9_DWmIT.js +0 -16
  207. package/dist/models/Llama.js +0 -88
  208. package/dist/models/NanoGPTV1.js +0 -94
  209. package/dist/models/NanoGPTV2.js +0 -85
  210. package/dist/models/Qwen3.js +0 -88
  211. package/dist/models/config.js +0 -32
  212. package/dist/models/factory.js +0 -16
  213. package/dist/models/model.js +0 -75
  214. package/dist/models-DyBpJJwM.js +0 -13
  215. package/dist/models.js +0 -6
  216. package/dist/mul16-C7sqgqik.js +0 -41
  217. package/dist/non_max_suppression_impl-B0H318rb.js +0 -72
  218. package/dist/not_equal-Bu3O8rh_.js +0 -67
  219. package/dist/one_hot-TEMPumJj.js +0 -14
  220. package/dist/ones-DpPXWa6A.js +0 -13
  221. package/dist/ops/adamAdjust.js +0 -17
  222. package/dist/ops/adamMoments.js +0 -15
  223. package/dist/ops/add16.js +0 -11
  224. package/dist/ops/appendCache.js +0 -26
  225. package/dist/ops/attentionMask.js +0 -19
  226. package/dist/ops/concat16.js +0 -8
  227. package/dist/ops/cpu/adamAdjust.js +0 -15
  228. package/dist/ops/cpu/adamMoments.js +0 -16
  229. package/dist/ops/cpu/appendCache.js +0 -65
  230. package/dist/ops/cpu/attentionMask.js +0 -20
  231. package/dist/ops/cpu/fusedSoftmax.js +0 -22
  232. package/dist/ops/cpu/gatherSub.js +0 -1
  233. package/dist/ops/cpu/gelu.js +0 -35
  234. package/dist/ops/cpu/matMul16.js +0 -14
  235. package/dist/ops/cpu/matMulGelu.js +0 -44
  236. package/dist/ops/cpu/matMulMul.js +0 -19
  237. package/dist/ops/cpu/mulDropout.js +0 -19
  238. package/dist/ops/cpu/normRMS.js +0 -34
  239. package/dist/ops/cpu/qkv.js +0 -74
  240. package/dist/ops/cpu/rope.js +0 -84
  241. package/dist/ops/cpu/scatterSub.js +0 -1
  242. package/dist/ops/dot16.js +0 -28
  243. package/dist/ops/dropout.js +0 -12
  244. package/dist/ops/dropout16.js +0 -1
  245. package/dist/ops/gatherSub.js +0 -12
  246. package/dist/ops/gelu.js +0 -1
  247. package/dist/ops/globalNorm.js +0 -19
  248. package/dist/ops/grads/add16.js +0 -26
  249. package/dist/ops/grads/attentionMask.js +0 -25
  250. package/dist/ops/grads/dropout16.js +0 -1
  251. package/dist/ops/grads/gelu.js +0 -1
  252. package/dist/ops/grads/matMul16.js +0 -1
  253. package/dist/ops/grads/matMulGelu.js +0 -21
  254. package/dist/ops/grads/mul16.js +0 -1
  255. package/dist/ops/grads/normRMS.js +0 -36
  256. package/dist/ops/grads/pack16.js +0 -1
  257. package/dist/ops/grads/qkv.js +0 -46
  258. package/dist/ops/grads/rope.js +0 -1
  259. package/dist/ops/grads/silu.js +0 -1
  260. package/dist/ops/grads/softmax16.js +0 -22
  261. package/dist/ops/grads/unpack16.js +0 -1
  262. package/dist/ops/grads/utils.js +0 -11
  263. package/dist/ops/log.js +0 -1
  264. package/dist/ops/matMul16.js +0 -1
  265. package/dist/ops/matMulGelu.js +0 -19
  266. package/dist/ops/matMulMul.js +0 -15
  267. package/dist/ops/mul16.js +0 -1
  268. package/dist/ops/mulDrop.js +0 -14
  269. package/dist/ops/normRMS.js +0 -21
  270. package/dist/ops/pack16.js +0 -1
  271. package/dist/ops/qkv.js +0 -15
  272. package/dist/ops/reshape16.js +0 -33
  273. package/dist/ops/rope.js +0 -1
  274. package/dist/ops/scatterSub.js +0 -12
  275. package/dist/ops/silu.js +0 -1
  276. package/dist/ops/slice16.js +0 -11
  277. package/dist/ops/softmax16.js +0 -8
  278. package/dist/ops/sub16.js +0 -10
  279. package/dist/ops/sum16.js +0 -13
  280. package/dist/ops/transpose16.js +0 -33
  281. package/dist/ops/unpack16.js +0 -1
  282. package/dist/ops/webgl/adamAdjust.js +0 -81
  283. package/dist/ops/webgl/adamMoments.js +0 -43
  284. package/dist/ops/webgl/appendCache.js +0 -52
  285. package/dist/ops/webgl/attentionMask.js +0 -63
  286. package/dist/ops/webgl/dropout16.js +0 -11
  287. package/dist/ops/webgl/fusedSoftmax.js +0 -70
  288. package/dist/ops/webgl/gatherSub.js +0 -27
  289. package/dist/ops/webgl/gelu.js +0 -47
  290. package/dist/ops/webgl/log.js +0 -14
  291. package/dist/ops/webgl/matMul16.js +0 -48
  292. package/dist/ops/webgl/matMulGelu.js +0 -1
  293. package/dist/ops/webgl/matMulMul.js +0 -23
  294. package/dist/ops/webgl/mulDropout.js +0 -31
  295. package/dist/ops/webgl/normRMS.js +0 -115
  296. package/dist/ops/webgl/qkv.js +0 -53
  297. package/dist/ops/webgl/rope.js +0 -73
  298. package/dist/ops/webgl/scatterSub.js +0 -27
  299. package/dist/ops/webgpu/adamAdjust.js +0 -76
  300. package/dist/ops/webgpu/adamMoments.js +0 -75
  301. package/dist/ops/webgpu/add16.js +0 -13
  302. package/dist/ops/webgpu/appendCache.js +0 -129
  303. package/dist/ops/webgpu/attentionMask.js +0 -41
  304. package/dist/ops/webgpu/attentionMask32_program.js +0 -61
  305. package/dist/ops/webgpu/clipScale.js +0 -44
  306. package/dist/ops/webgpu/concat16.js +0 -110
  307. package/dist/ops/webgpu/dropout16.js +0 -58
  308. package/dist/ops/webgpu/gatherSub.js +0 -51
  309. package/dist/ops/webgpu/gelu.js +0 -146
  310. package/dist/ops/webgpu/index.js +0 -27
  311. package/dist/ops/webgpu/matMul16.js +0 -91
  312. package/dist/ops/webgpu/matMul16_program.js +0 -311
  313. package/dist/ops/webgpu/mul16.js +0 -13
  314. package/dist/ops/webgpu/norm2.js +0 -45
  315. package/dist/ops/webgpu/normRMS.js +0 -25
  316. package/dist/ops/webgpu/normRMS16_program.js +0 -28
  317. package/dist/ops/webgpu/normRMS32_program.js +0 -28
  318. package/dist/ops/webgpu/normRMSGrad.js +0 -225
  319. package/dist/ops/webgpu/pack16.js +0 -20
  320. package/dist/ops/webgpu/pack16_program.js +0 -92
  321. package/dist/ops/webgpu/qkv.js +0 -63
  322. package/dist/ops/webgpu/rope.js +0 -227
  323. package/dist/ops/webgpu/scatterSub.js +0 -52
  324. package/dist/ops/webgpu/silu.js +0 -117
  325. package/dist/ops/webgpu/slice16.js +0 -73
  326. package/dist/ops/webgpu/softmax16.js +0 -18
  327. package/dist/ops/webgpu/softmax16_program.js +0 -88
  328. package/dist/ops/webgpu/softmax16_subgroup_program.js +0 -69
  329. package/dist/ops/webgpu/softmax16grad.js +0 -30
  330. package/dist/ops/webgpu/sub16.js +0 -13
  331. package/dist/ops/webgpu/sum16.js +0 -30
  332. package/dist/ops/webgpu/transpose16.js +0 -38
  333. package/dist/ops/webgpu/transpose16_program.js +0 -50
  334. package/dist/ops/webgpu/transpose16_shared_program.js +0 -78
  335. package/dist/ops/webgpu/unpack16.js +0 -59
  336. package/dist/ops/webgpu/utils/binary_op.js +0 -140
  337. package/dist/ops/webgpu/utils/deviceInfo.js +0 -10
  338. package/dist/ops/webgpu/utils/reductions.js +0 -264
  339. package/dist/ops-Be5ACU5R.js +0 -13
  340. package/dist/ops-C1UpdEYM.js +0 -509
  341. package/dist/pack16-BHO4t1-M.js +0 -36
  342. package/dist/pad-Dy-1IP3A.js +0 -13
  343. package/dist/patches/webgpu_backend.js +0 -42
  344. package/dist/patches/webgpu_program.js +0 -292
  345. package/dist/picomatch--TW6gyBJ.js +0 -999
  346. package/dist/qkv-BQfNPucX.js +0 -42
  347. package/dist/rand_util-_vCY93Uw.js +0 -44
  348. package/dist/random_normal-DUIT8kyC.js +0 -11
  349. package/dist/range-CYvQC3fW.js +0 -13
  350. package/dist/relu-C4XULT8A.js +0 -8
  351. package/dist/reshape-DJb1jgMt.js +0 -8
  352. package/dist/resize_nearest_neighbor-DAqcTYUe.js +0 -188
  353. package/dist/rope-JjBVufF_.js +0 -24
  354. package/dist/scatterSub-BOnqk-uY.js +0 -27
  355. package/dist/scatter_nd_util-BepMCpLY.js +0 -34
  356. package/dist/seedrandom-SHEGFK6H.js +0 -282
  357. package/dist/selu_util-DeOTf-sc.js +0 -27
  358. package/dist/shared-CX_iPI5K.js +0 -4
  359. package/dist/silu-DsAE2cJ5.js +0 -23
  360. package/dist/slice-Dlb1FlzG.js +0 -13
  361. package/dist/slice_util-BVgPRoij.js +0 -207
  362. package/dist/softmax-Dpav_dWw.js +0 -10
  363. package/dist/split-DYnT8chz.js +0 -11
  364. package/dist/squeeze-B3XYGAlg.js +0 -9
  365. package/dist/stack-Dbbt9mIk.js +0 -10
  366. package/dist/step-DA-5DNu9.js +0 -348
  367. package/dist/stream-BBe2apn4.js +0 -2280
  368. package/dist/sum-C8qNbFNp.js +0 -13
  369. package/dist/tensor-ALxWZfmz.js +0 -7
  370. package/dist/tensor1d-BHgkkhTE.js +0 -9
  371. package/dist/tensor2d-ARItvqVn.js +0 -10
  372. package/dist/tensor4d-D1zRBipJ.js +0 -10
  373. package/dist/tfjs_backend-CsXOum0h.js +0 -685
  374. package/dist/tile-DfyQ0KX-.js +0 -10
  375. package/dist/tokenise-DbS2Ea-T.js +0 -14
  376. package/dist/tokenise.js +0 -6
  377. package/dist/tokeniser/BaseTokeniser.js +0 -137
  378. package/dist/tokeniser/CharTokeniser.js +0 -85
  379. package/dist/tokeniser/bpe.js +0 -156
  380. package/dist/tokeniser/messages.js +0 -0
  381. package/dist/tokeniser/type.js +0 -0
  382. package/dist/topk-BrU2pkrR.js +0 -19
  383. package/dist/training/AdamW.js +0 -132
  384. package/dist/training/BasicTrainer.js +0 -274
  385. package/dist/training/DatasetBuilder.js +0 -1
  386. package/dist/training/Evaluator.js +0 -51
  387. package/dist/training/LRScheduler.js +0 -37
  388. package/dist/training/PreTrainer.js +0 -21
  389. package/dist/training/SFTTrainer.js +0 -23
  390. package/dist/training/configure.js +0 -33
  391. package/dist/training/factory.js +0 -7
  392. package/dist/training/loss.js +0 -18
  393. package/dist/training/orthoGrad.js +0 -9
  394. package/dist/training/prepareData.js +0 -51
  395. package/dist/training/sparseCrossEntropy.js +0 -53
  396. package/dist/training/tasks/TokenStore.js +0 -217
  397. package/dist/training/tasks/tokenStream.js +0 -45
  398. package/dist/training/types.js +0 -0
  399. package/dist/training/validateOptions.js +0 -18
  400. package/dist/training/validation.js +0 -30
  401. package/dist/transpose-BC-M_OoT.js +0 -34
  402. package/dist/unsorted_segment_sum-BelC7R-q.js +0 -408
  403. package/dist/utilities/arrayClose.js +0 -29
  404. package/dist/utilities/arrayShape.js +0 -7
  405. package/dist/utilities/datasetID.js +0 -17
  406. package/dist/utilities/dummy.js +0 -36
  407. package/dist/utilities/float16.js +0 -46
  408. package/dist/utilities/maxHeap.js +0 -54
  409. package/dist/utilities/multinomialCPU.js +0 -7
  410. package/dist/utilities/naming.js +0 -0
  411. package/dist/utilities/packed.js +0 -12
  412. package/dist/utilities/parameters.js +0 -53
  413. package/dist/utilities/performance.js +0 -15
  414. package/dist/utilities/profile.js +0 -32
  415. package/dist/utilities/random.js +0 -18
  416. package/dist/utilities/safetensors.js +0 -63
  417. package/dist/utilities/sentences.js +0 -35
  418. package/dist/utilities/tokenParse.js +0 -16
  419. package/dist/utilities/tokens.js +0 -39
  420. package/dist/utilities/topP.js +0 -25
  421. package/dist/utilities/waitForModel.js +0 -11
  422. package/dist/utilities/weights.js +0 -40
  423. package/dist/utilities/yielder.js +0 -6
  424. package/dist/v4-YCkfo8OR.js +0 -27
  425. package/dist/webgpu-BHX-uBym.js +0 -518
  426. package/dist/webgpu_util-5QTyovaf.js +0 -105
  427. package/dist/zeros-hxKGkRfl.js +0 -12
@@ -0,0 +1,3221 @@
1
+ import { Ai as e, Di as t, E as n, I as r, O as i, Ui as a, X as o, Zi as s, j as c, kt as l, ta as u } from "./dist-JOPw9zTN.js";
2
+ import { G as d, K as f, Z as p, ct as m, ft as h, gt as g, mt as _, q as v, ut as y, xt as b } from "./backend_util-DZIc6pyV.js";
3
+ import { Jt as x, Wt as S, Yt as C, a as ee, c as te, d as w, f as ne, i as T, o as re, p as E, r as D, t as O, u as k } from "./matMul16-CiMKJM8v.js";
4
+ import { c as A, f as j, h as M, i as N, m as P } from "./webgpu-wUCQopBN.js";
5
+ import { t as F } from "./webgpu_backend-CzY9TzvA.js";
6
+ import { i as I, r as L, t as R } from "./Reshape-CqftURg0.js";
7
+ // lib/ops/webgpu/attentionMask32_program.ts
8
+ var z = class {
9
+ variableNames = ["q", "k"];
10
+ outputShape;
11
+ shaderKey = "AttentionMask";
12
+ dispatchLayout;
13
+ dispatch;
14
+ uniforms = "divisor: f32, pastLen: i32, inf: f32, queryLen: i32";
15
+ workgroupSize = [
16
+ 64,
17
+ 1,
18
+ 1
19
+ ];
20
+ size = !0;
21
+ hs;
22
+ nh;
23
+ T1;
24
+ T2;
25
+ constructor(e, t, n, r, i) {
26
+ if (this.shaderKey = `AttentionMask_${i}`, this.outputShape = [
27
+ e,
28
+ t,
29
+ n,
30
+ r
31
+ ], this.hs = i, this.nh = t, this.T1 = n, this.T2 = r, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize), i % 4 != 0) throw Error("Head size must be a multiple of 4 for AttentionMaskProgram");
32
+ }
33
+ getUserCode() {
34
+ return `
35
+ ${M("index")} {
36
+
37
+ let coords = getCoordsFromIndex(index);
38
+ let b = coords[0];
39
+ let h = coords[1];
40
+ let t1 = coords[2];
41
+ let t2 = coords[3];
42
+
43
+ if (index < uniforms.size) {
44
+ // Rows may hold several query heads of a GQA group
45
+ if (t2 > (t1 % uniforms.queryLen) + uniforms.pastLen) {
46
+ setOutputAtIndex(index, uniforms.inf);
47
+ return;
48
+ }
49
+
50
+ let q0 = getIndexFromCoords4D(vec4<i32>(b, h, t1, 0), uniforms.qShape);
51
+ let k0 = getIndexFromCoords4D(vec4<i32>(b, h, t2, 0), uniforms.kShape);
52
+
53
+ var sum: f32 = 0.0;
54
+ for (var i: i32 = 0; i < ${this.hs}; i = i + 4) {
55
+ let qv = vec4<f32>(q[q0 + i], q[q0 + i + 1], q[q0 + i + 2], q[q0 + i + 3]);
56
+ let kv = vec4<f32>(k[k0 + i], k[k0 + i + 1], k[k0 + i + 2], k[k0 + i + 3]);
57
+ sum = sum + dot(qv, kv);
58
+ }
59
+ let scaled = sum * uniforms.divisor;
60
+ setOutputAtIndex(index, scaled);
61
+ }
62
+ }
63
+ `;
64
+ }
65
+ };
66
+ // lib/ops/webgpu/attentionMask.ts
67
+ function B(t) {
68
+ let { q: n, k: r, mask: i } = t.inputs, { divisor: a, pastLen: o, groupSize: s = 1 } = t.attrs, c = t.backend, l = E(n) && E(r), u = n.shape[2] / s;
69
+ if (l) return O(n, r, !1, !0, {
70
+ causalMask: !0,
71
+ pastLen: o,
72
+ scale: a,
73
+ causalPeriod: u
74
+ }, i);
75
+ let d = n.shape[0], f = n.shape[2], p = r.shape[2], m = n.shape[1], h = n.shape[3];
76
+ if (e(r.shape, [
77
+ d,
78
+ m,
79
+ p,
80
+ h
81
+ ], "Error in AttentionMask: "), a === 0) throw Error("Divisor must be non-zero in AttentionMask");
82
+ if (o < 0) throw Error("pastLen must be non-negative in AttentionMask");
83
+ let g = new z(d, m, f, p, h), _ = [
84
+ {
85
+ type: "float32",
86
+ data: [a]
87
+ },
88
+ {
89
+ type: "int32",
90
+ data: [o]
91
+ },
92
+ {
93
+ type: "float32",
94
+ data: [-Infinity]
95
+ },
96
+ {
97
+ type: "int32",
98
+ data: [u]
99
+ }
100
+ ], v = n.dtype;
101
+ return c.runWebGPUProgram(g, [n, r], v, _);
102
+ }
103
+ l({
104
+ kernelName: "AttentionMask",
105
+ backendName: "webgpu",
106
+ kernelFunc: B
107
+ });
108
+ // lib/ops/webgpu/utils/reductions.ts
109
+ function V(e, t, n, r, i) {
110
+ return e && !t ? "\n bestValue = subgroupAdd(bestValue);\n " : e ? `
111
+ bestValue = subgroupAdd(bestValue);
112
+ let lane = localId.x % subgroupSize;
113
+ if (lane == 0) {
114
+ bestValues[localId.x / subgroupSize] = bestValue;
115
+ }
116
+ workgroupBarrier();
117
+ let numSubgroups = ${i ? `(${n}u + subgroupSize - 1u) / subgroupSize` : `${n} / subgroupSize`};
118
+ bestValue = select(${r ? "vec2<f32>(0.0f)" : "0.0f"}, bestValues[lane], lane < numSubgroups);
119
+ bestValue = subgroupAdd(bestValue);
120
+ ` : `
121
+ bestValues[localId.x] = bestValue;
122
+ workgroupBarrier();
123
+
124
+ var reduceSize = min(u32(Length), ${n}u);
125
+ for (var currentSize = reduceSize / 2u; reduceSize > 1u;
126
+ currentSize = reduceSize / 2u) {
127
+ let interval = DIV_CEIL(reduceSize, 2u);
128
+ if (localId.x < currentSize) {
129
+ let candidate = bestValues[localId.x + interval];
130
+ bestValue = bestValue + candidate;
131
+ bestValues[localId.x] = bestValue;
132
+ }
133
+ reduceSize = interval;
134
+ workgroupBarrier();
135
+ }
136
+
137
+ bestValue = bestValues[0];
138
+ `;
139
+ }
140
+ function H(e) {
141
+ let t = `${e.workgroupSizeX}`, n = e.subgroups && !e.variableSubgroups ? "" : `
142
+ var<workgroup> bestValues : array<f32, ${e.workgroupSizeX}>;
143
+ `, r = V(e.subgroups, e.variableSubgroups, e.workgroupSizeX, !1, e.partialSubgroup);
144
+ return `
145
+ fn DIV_CEIL(a : u32, b : u32) -> u32 {
146
+ return ((a - 1u) / b + 1u);
147
+ }
148
+
149
+ fn readInput(index: i32) -> vec2<f32> {
150
+ ${e.inputReadSnippet ? e.inputReadSnippet : "\n let packed = u32(x[index]);\n return unpack2x16float(packed);\n "}
151
+ }
152
+
153
+ ${n}
154
+ ${e.utilityFunctions ?? ""}
155
+
156
+ ${M("index")} {
157
+ let outputIndex = index / ${t};
158
+ let offset = outputIndex * uniforms.reduceSize;
159
+ var bestValue = 0.0f;
160
+ let Length = uniforms.reduceSize;
161
+ let tid = i32(localId.x);
162
+
163
+ for (var k = tid; k < Length;
164
+ k = k + ${t}) {
165
+ var candidate = readInput(offset + k);
166
+ ${e.inputSnippet}
167
+ bestValue = bestValue + candidate.x + candidate.y;
168
+ }
169
+
170
+ ${r}
171
+ bestValue = bestValue ${e.reductionOp === "mean" ? "/ f32(uniforms.reduceSize * 2i)" : ""};
172
+
173
+ ${e.reducedSnippet ? e.reducedSnippet : ""}
174
+
175
+ for (var k = tid; k < Length;
176
+ k = k + ${t}) {
177
+ ${e.outputSnippet}
178
+ }
179
+ }
180
+ `;
181
+ }
182
+ function U(e) {
183
+ let t = `${e.workgroupSizeX}`, n = e.subgroups && !e.variableSubgroups ? "" : `
184
+ var<workgroup> bestValues : array<vec2<f32>, ${e.workgroupSizeX}>;
185
+ `, r = V(e.subgroups, e.variableSubgroups, e.workgroupSizeX, !0, e.partialSubgroup);
186
+ return `
187
+ fn DIV_CEIL(a : u32, b : u32) -> u32 {
188
+ return ((a - 1u) / b + 1u);
189
+ }
190
+
191
+ fn readInput(index: i32) -> vec2<f32> {
192
+ ${e.inputReadSnippet ? e.inputReadSnippet : "\n let packed = u32(x[index]);\n return unpack2x16float(packed);\n "}
193
+ }
194
+
195
+ ${n}
196
+ ${e.utilityFunctions ?? ""}
197
+
198
+ ${M("index")} {
199
+ let outputIndex = index / ${t};
200
+ let offset1 = outputIndex * 2 * uniforms.reduceSize;
201
+ let offset2 = offset1 + uniforms.reduceSize;
202
+ var bestValue = vec2<f32>(0.0f, 0.0f);
203
+ let Length = uniforms.reduceSize;
204
+ let tid = i32(localId.x);
205
+
206
+ for (var k = tid; k < Length;
207
+ k = k + ${t}) {
208
+ var candidate = readInput(offset1 + k);
209
+ ${e.inputSnippet}
210
+ let bv1 = candidate.x + candidate.y;
211
+
212
+ candidate = readInput(offset2 + k);
213
+ ${e.inputSnippet}
214
+ let bv2 = candidate.x + candidate.y;
215
+
216
+ bestValue = bestValue + vec2<f32>(bv1, bv2);
217
+ }
218
+ ${r}
219
+ bestValue = bestValue ${e.reductionOp === "mean" ? "/ f32(uniforms.reduceSize * 2i)" : ""};
220
+
221
+ ${e.reducedSnippet ?? ""}
222
+ ${e.outputSnippet}
223
+ }
224
+ `;
225
+ }
226
+ function W(e) {
227
+ return e.elementwise ? H(e) : U(e);
228
+ }
229
+ function ie(e) {
230
+ let t = `${e.workgroupSizeX}`, n = e.subgroups && !e.variableSubgroups ? "" : `
231
+ var<workgroup> bestValues : array<f32, ${e.workgroupSizeX}>;
232
+ `, r = V(e.subgroups, e.variableSubgroups, e.workgroupSizeX, !1, e.partialSubgroup);
233
+ return `
234
+ fn DIV_CEIL(a : u32, b : u32) -> u32 {
235
+ return ((a - 1u) / b + 1u);
236
+ }
237
+
238
+ fn readInput(index: i32) -> f32 {
239
+ ${e.inputReadSnippet ? e.inputReadSnippet : "\n return x[index];\n "}
240
+ }
241
+
242
+ ${n}
243
+ ${e.utilityFunctions ?? ""}
244
+
245
+ ${M("index")} {
246
+ let outputIndex = index / ${e.workgroupSizeX};
247
+ let offset = outputIndex * uniforms.reduceSize;
248
+ var bestValue = 0.0f;
249
+ let Length = uniforms.reduceSize;
250
+ let tid = i32(localId.x);
251
+
252
+ for (var k = tid; k < Length;
253
+ k = k + ${e.workgroupSizeX}) {
254
+ var candidate = readInput(offset + k);
255
+ ${e.inputSnippet}
256
+ bestValue = bestValue + candidate;
257
+ }
258
+ ${r}
259
+
260
+ bestValue = bestValue ${e.reductionOp === "mean" ? "/ f32(uniforms.reduceSize)" : ""};
261
+
262
+ ${e.reducedSnippet}
263
+
264
+ ${e.elementwise ? `for (var k = tid; k < Length;
265
+ k = k + ${t}) {
266
+ ${e.outputSnippet}
267
+ }` : `${e.outputSnippet}`}
268
+ }
269
+ `;
270
+ }
271
+ function G(e, t) {
272
+ let n = e[0], r = s(t, n.shape), [, i] = _(n.shape, r), a = u(i), o = u(n.shape) / a;
273
+ return {
274
+ windowSize: a,
275
+ inSize: a,
276
+ batchSize: o,
277
+ outSize: o
278
+ };
279
+ }
280
+ var K = class {
281
+ atomic = !1;
282
+ outputShape;
283
+ shaderKey = "reduce16";
284
+ dispatchLayout;
285
+ dispatch;
286
+ workgroupSize = [
287
+ 64,
288
+ 1,
289
+ 1
290
+ ];
291
+ variableNames = ["x"];
292
+ uniforms = "reduceSize : i32,";
293
+ inputShape;
294
+ size = !1;
295
+ packed = !0;
296
+ outputComponent;
297
+ variableComponents;
298
+ elementwise;
299
+ subgroups = !1;
300
+ subgroupBuiltins = !1;
301
+ deviceInfo;
302
+ params;
303
+ utilityFunctions;
304
+ constructor(e, t, n, r) {
305
+ this.params = n, this.inputShape = [t.batchSize, t.inSize], this.deviceInfo = e, this.packed = r;
306
+ let i = n.forceWorkgroupSize ? n.forceWorkgroupSize : t.inSize % 64 == 0 ? 64 : 32;
307
+ e.subgroupsSupported && !n.forceWorkgroupSize ? (this.workgroupSize = [
308
+ Math.min(i, e.subgroupMaxSize),
309
+ 1,
310
+ 1
311
+ ], this.subgroups = !0, e.variableSubgroups && (this.subgroupBuiltins = !0)) : this.workgroupSize[0] = i, this.outputShape = n.elementwise ? [t.batchSize, t.inSize] : r ? [t.outSize / 2] : [t.outSize], this.dispatchLayout = A(this.outputShape), this.dispatch = [
312
+ n.elementwise ? t.batchSize : r ? t.batchSize / 2 : t.batchSize,
313
+ 1,
314
+ 1
315
+ ], this.outputComponent = 1, this.variableComponents = [1], this.elementwise = n.elementwise === !0;
316
+ }
317
+ getWriteSnippet() {
318
+ return this.packed ? "result[outputIndex] = i32(pack2x16float(bestValue));" : "result[outputIndex] = bestValue;";
319
+ }
320
+ getPreprocessSnippet() {
321
+ return "";
322
+ }
323
+ getPostprocessSnippet() {
324
+ return "";
325
+ }
326
+ getReadSnippet() {
327
+ return this.packed ? "\n let packed = u32(x[index]);\n return unpack2x16float(packed);\n " : "return f32(x[index]);";
328
+ }
329
+ getUserCode() {
330
+ let e = this.workgroupSize[0], t = this.subgroups && this.deviceInfo.variableSubgroups && e < this.deviceInfo.subgroupMaxSize;
331
+ return this.packed ? W({
332
+ ...this.params,
333
+ workgroupSizeX: e,
334
+ subgroups: this.subgroups,
335
+ variableSubgroups: this.deviceInfo.variableSubgroups,
336
+ partialSubgroup: t,
337
+ inputReadSnippet: this.getReadSnippet(),
338
+ inputSnippet: this.getPreprocessSnippet(),
339
+ outputSnippet: this.getWriteSnippet(),
340
+ reducedSnippet: this.getPostprocessSnippet(),
341
+ utilityFunctions: this.utilityFunctions
342
+ }) : ie({
343
+ ...this.params,
344
+ workgroupSizeX: e,
345
+ subgroups: this.subgroups,
346
+ variableSubgroups: this.deviceInfo.variableSubgroups,
347
+ partialSubgroup: t,
348
+ inputReadSnippet: this.getReadSnippet(),
349
+ inputSnippet: this.getPreprocessSnippet(),
350
+ outputSnippet: this.getWriteSnippet(),
351
+ reducedSnippet: this.getPostprocessSnippet(),
352
+ utilityFunctions: this.utilityFunctions
353
+ });
354
+ }
355
+ };
356
+ function q(e, t, n, r, i) {
357
+ let a = t[0], s = [{
358
+ type: "int32",
359
+ data: [e.inputShape[e.inputShape.length - 1]]
360
+ }, ...r ?? []], c = i;
361
+ !i && e.atomic && (c = y(e.outputShape, "int32"));
362
+ let l = n.runWebGPUProgram(e, t, e.packed ? "packedF16" : e.atomic ? "int32" : "float32", s, c), u = o().makeTensorFromTensorInfo(l);
363
+ if (e.outputShape.length === 1 && e.outputShape[0] <= 2) return u;
364
+ let d = w(u, e.elementwise ? a.shape : e.packed ? [...a.shape.slice(0, -2), a.shape[a.shape.length - 2] / 2] : [...a.shape.slice(0, -2), a.shape[a.shape.length - 2]]);
365
+ return u.dispose(), d;
366
+ }
367
+ // lib/ops/webgpu/normRMS16_program.ts
368
+ var ae = class extends K {
369
+ epsilon;
370
+ hasGamma;
371
+ constructor(e, t, n = !1, r = 1e-8) {
372
+ super(e, t, {
373
+ reductionOp: "mean",
374
+ elementwise: !0
375
+ }, !0), this.epsilon = r, this.shaderKey = `RMSNorm16_${n ? "Gamma" : "NoGamma"}_${this.epsilon}`, n && this.variableNames.push("gamma"), this.variableComponents = [1, 1], this.hasGamma = n;
376
+ }
377
+ getPreprocessSnippet() {
378
+ return "candidate = candidate * candidate;";
379
+ }
380
+ getPostprocessSnippet() {
381
+ return `bestValue = inverseSqrt(bestValue + ${this.epsilon});`;
382
+ }
383
+ getWriteSnippet() {
384
+ return `
385
+ let X = unpack2x16float(u32(x[offset + k]));
386
+ ${this.hasGamma ? "let gamma = unpack2x16float(u32(gamma[k]));" : ""}
387
+ let normalized = X * bestValue;
388
+ let outVal = normalized ${this.hasGamma ? " * gamma" : ""};
389
+ result[offset + k] = i32(pack2x16float(outVal));
390
+ `;
391
+ }
392
+ }, oe = class extends K {
393
+ epsilon;
394
+ hasGamma;
395
+ constructor(e, t, n = !1, r = 1e-8) {
396
+ super(e, t, {
397
+ reductionOp: "mean",
398
+ elementwise: !0
399
+ }, !1), this.epsilon = r, this.shaderKey = `RMSNorm32_${n ? "Gamma" : "NoGamma"}_${this.epsilon}`, n && this.variableNames.push("gamma"), this.variableComponents = [1, 1], this.hasGamma = n;
400
+ }
401
+ getPreprocessSnippet() {
402
+ return "candidate = candidate * candidate;";
403
+ }
404
+ getPostprocessSnippet() {
405
+ return `bestValue = inverseSqrt(bestValue + ${this.epsilon});`;
406
+ }
407
+ getWriteSnippet() {
408
+ return `
409
+ let X = f32(x[offset + k]);
410
+ ${this.hasGamma ? "let gamma = gamma[k];" : ""}
411
+ let normalized = X * bestValue;
412
+ let outVal = normalized ${this.hasGamma ? " * gamma" : ""};
413
+ result[offset + k] = f32(outVal);
414
+ `;
415
+ }
416
+ };
417
+ // lib/ops/webgpu/utils/deviceInfo.ts
418
+ function J(e) {
419
+ let t = e.device.features.has("subgroups");
420
+ return {
421
+ subgroupsSupported: t,
422
+ subgroupMaxSize: e.subgroupMaxSize,
423
+ variableSubgroups: e.subgroupMinSize !== e.subgroupMaxSize && t
424
+ };
425
+ }
426
+ // lib/ops/webgpu/normRMS.ts
427
+ function se(t) {
428
+ let { x: n, gamma: r } = t.inputs, i = t.backend, a = t.attrs?.epsilon ?? 1e-8, o = J(i), s = E(n), c = r ? E(r) : !1, l = s || c, u = !l || s ? n : D(n), d = r && (!l || c ? r : D(r)), f = d ? [u, d] : [u], p = G(f, -1), m = l ? new ae(o, p, !!r, a) : new oe(o, p, !!r, a);
429
+ if (d && e(d.shape, [u.shape[u.shape.length - 1]], "Error in RMSNorm: "), n.shape.length !== 3) throw Error(`rmsNormGPU: input rank ${n.shape.length} not supported, only rank 3 is supported`);
430
+ if (p.inSize !== u.shape[u.shape.length - 1]) throw Error(`rmsNormGPU: reduction size ${p.inSize} does not match expected size ${u.shape[u.shape.length - 1]}`);
431
+ if (p.batchSize !== n.shape[0] * n.shape[1]) throw Error(`rmsNormGPU: batch size ${p.batchSize} does not match expected size ${n.shape[0] * n.shape[1]}`);
432
+ let h = q(m, f, i);
433
+ return l && !s && u.dispose(), l && !c && d && d.dispose(), h;
434
+ }
435
+ l({
436
+ kernelName: "RMSNorm",
437
+ backendName: "webgpu",
438
+ kernelFunc: se
439
+ }), l({
440
+ kernelName: "RMSNormNoGamma",
441
+ backendName: "webgpu",
442
+ kernelFunc: se
443
+ });
444
+ // lib/ops/slice16.ts
445
+ function Y(e, t, n) {
446
+ return E(e) ? o().runKernel("Slice16", { x: e }, {
447
+ begin: t,
448
+ size: n
449
+ }) : x(e, t, n);
450
+ }
451
+ // lib/ops/webgpu/normRMSGrad.ts
452
+ var ce = class {
453
+ outputShape;
454
+ shaderKey = "RMSNormGrad";
455
+ dispatchLayout;
456
+ dispatch;
457
+ workgroupSize = [
458
+ 64,
459
+ 1,
460
+ 1
461
+ ];
462
+ variableNames = [
463
+ "x",
464
+ "gamma",
465
+ "dy"
466
+ ];
467
+ uniforms = "reduceSize : i32, batchSize: i32";
468
+ inputShape;
469
+ size = !1;
470
+ rowsPerWorkgroup;
471
+ packed = !1;
472
+ outputComponent;
473
+ epsilon;
474
+ constructor(e, t = 4, n = !1, r = 1e-8) {
475
+ if (this.packed = n, this.epsilon = r, this.shaderKey = `RMSNormGrad_${t}_${r}`, this.rowsPerWorkgroup = t, this.inputShape = [e.batchSize, e.inSize], this.outputShape = [e.batchSize + e.batchSize / this.rowsPerWorkgroup, e.inSize], this.dispatchLayout = A(this.outputShape), this.dispatch = [
476
+ e.batchSize / this.rowsPerWorkgroup,
477
+ 1,
478
+ 1
479
+ ], e.batchSize % this.rowsPerWorkgroup !== 0) throw Error(`RMSNormGradProgram: batch size ${e.batchSize} must be divisible by rowsPerWorkgroup ${this.rowsPerWorkgroup}`);
480
+ if (e.inSize > 1024) throw Error(`RMSNormGradProgram: inSize ${e.inSize} exceeds max of 1024`);
481
+ }
482
+ getUserCode() {
483
+ let e = this.workgroupSize[0], t = this.rowsPerWorkgroup, n = `
484
+ var<workgroup> partials : array<vec2<f32>, ${e}>;
485
+ var<workgroup> accumulation: array<${this.packed ? "vec2<f32>" : "f32"}, 1024>;
486
+ `, r = this.packed ? "\n let X = unpack2x16float(u32(x[offset + k]));\n let DY = unpack2x16float(u32(dy[offset + k]));\n let G = unpack2x16float(u32(gamma[k]));\n sum_x2 = fma(X.x, X.x, sum_x2);\n sum_x2 = fma(X.y, X.y, sum_x2);\n sum_dygx = fma(DY.x * G.x, X.x, sum_dygx);\n sum_dygx = fma(DY.y * G.y, X.y, sum_dygx);\n " : "\n let X = f32(x[offset + k]);\n let DY = f32(dy[offset + k]);\n let G = f32(gamma[k]);\n sum_x2 = fma(X, X, sum_x2);\n sum_dygx = fma(DY * G, X, sum_dygx);\n ", i = this.packed ? "\n let X = unpack2x16float(u32(x[offset + k]));\n let DY = unpack2x16float(u32(dy[offset + k]));\n let G = unpack2x16float(u32(gamma[k]));\n\n let dyGamma = DY * G;\n let dx = vec2<f32>(\n fma(dyGamma.x, invRMS, -X.x * scale),\n fma(dyGamma.y, invRMS, -X.y * scale)\n );\n\n result[offset + k] = i32(pack2x16float(dx));\n\n // dGamma\n accumulation[k] = fma(DY, X * invRMS, accumulation[k]);\n " : "\n let X = f32(x[offset + k]);\n let DY = f32(dy[offset + k]);\n let G = f32(gamma[k]);\n\n let dyGamma = DY * G;\n let dx = fma(dyGamma, invRMS, -X * scale);\n\n result[offset + k] = dx;\n\n // dGamma\n accumulation[k] = fma(DY, X * invRMS, accumulation[k]);\n ", a = this.packed ? "\n result[outDgBase + k] = i32(pack2x16float(accumulation[k]));\n " : "\n result[outDgBase + k] = accumulation[k];\n ";
487
+ return `
488
+ fn DIV_CEIL(a : u32, b : u32) -> u32 {
489
+ return ((a - 1u) / b + 1u);
490
+ }
491
+
492
+ ${n}
493
+
494
+ ${M("index")} {
495
+ // One workgroup per row (batch).
496
+ let Length = uniforms.reduceSize;
497
+ let BatchSize = uniforms.batchSize;
498
+ for (var k = i32(localId.x); k < Length; k = k + ${e}) {
499
+ accumulation[k] = ${this.packed ? "vec2<f32>(0.0f)" : "0.0f"};
500
+ }
501
+
502
+ for (var rowOff = 0; rowOff < ${t}; rowOff = rowOff + 1) {
503
+ let row = i32(workgroupId.x) * ${t} + rowOff;
504
+ let offset = row * Length;
505
+
506
+ var sum_x2 = 0.0f;
507
+ var sum_dygx = 0.0f;
508
+
509
+ for (var k = i32(localId.x); k < Length; k = k + ${e}) {
510
+ ${r}
511
+ }
512
+
513
+ partials[localId.x] = vec2<f32>(sum_x2, sum_dygx);
514
+ workgroupBarrier();
515
+
516
+ var reduceSize = min(u32(Length), ${e}u);
517
+ for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) {
518
+ let interval = DIV_CEIL(reduceSize, 2u);
519
+ if (localId.x < currentSize) {
520
+ partials[localId.x] = partials[localId.x] + partials[localId.x + interval];
521
+ }
522
+ reduceSize = interval;
523
+ workgroupBarrier();
524
+ }
525
+
526
+ let invN = 1.0f / f32(${this.packed ? "Length * 2" : "Length"});
527
+ let mean_x2 = fma(partials[0].x, invN, ${this.epsilon.toExponential()});
528
+ let mean_dygx = partials[0].y * invN;
529
+
530
+ let invRMS = inverseSqrt(mean_x2);
531
+ let scale = (mean_dygx / (mean_x2)) * invRMS;
532
+
533
+ // write dx and dGamma.
534
+ for (var k = i32(localId.x); k < Length; k = k + ${e}) {
535
+ ${i}
536
+ }
537
+
538
+ workgroupBarrier();
539
+ }
540
+
541
+ // Write out the partially accumulated dGamma
542
+ let outDgBase = BatchSize * Length + i32(workgroupId.x) * Length;
543
+ for (var k = i32(localId.x); k < Length; k = k + ${e}) {
544
+ ${a}
545
+ }
546
+ }
547
+ `;
548
+ }
549
+ }, le = class {
550
+ outputShape;
551
+ shaderKey = "RMSNormGrad";
552
+ dispatchLayout;
553
+ dispatch;
554
+ workgroupSize = [
555
+ 64,
556
+ 1,
557
+ 1
558
+ ];
559
+ variableNames = ["x", "dy"];
560
+ uniforms = "reduceSize : i32, batchSize: i32";
561
+ inputShape;
562
+ size = !1;
563
+ packed = !1;
564
+ outputComponent;
565
+ epsilon;
566
+ constructor(e, t = !1, n = 1e-8) {
567
+ this.packed = t, this.epsilon = n, this.shaderKey = `RMSNormGrad_NoGamma_${n}`, this.inputShape = [e.batchSize, e.inSize], this.outputShape = [e.batchSize, e.inSize], this.dispatchLayout = A(this.outputShape), this.dispatch = [
568
+ e.batchSize,
569
+ 1,
570
+ 1
571
+ ];
572
+ }
573
+ getUserCode() {
574
+ let e = this.workgroupSize[0], t = `
575
+ var<workgroup> partials : array<vec2<f32>, ${e}>;
576
+ `, n = this.packed ? "\n let X = unpack2x16float(u32(x[offset + k]));\n let DY = unpack2x16float(u32(dy[offset + k]));\n sum_x2 = fma(X.x, X.x, sum_x2);\n sum_x2 = fma(X.y, X.y, sum_x2);\n sum_dygx = fma(DY.x, X.x, sum_dygx);\n sum_dygx = fma(DY.y, X.y, sum_dygx);\n " : "\n let X = f32(x[offset + k]);\n let DY = f32(dy[offset + k]);\n sum_x2 = fma(X, X, sum_x2);\n sum_dygx = fma(DY, X, sum_dygx);\n ", r = this.packed ? "\n let X = unpack2x16float(u32(x[offset + k]));\n let DY = unpack2x16float(u32(dy[offset + k]));\n\n let dx = vec2<f32>(\n fma(DY.x, invRMS, -X.x * scale),\n fma(DY.y, invRMS, -X.y * scale)\n );\n\n result[offset + k] = i32(pack2x16float(dx));\n " : "\n let X = f32(x[offset + k]);\n let DY = f32(dy[offset + k]);\n\n let dx = fma(DY, invRMS, -X * scale);\n\n result[offset + k] = dx;\n ";
577
+ return `
578
+ fn DIV_CEIL(a : u32, b : u32) -> u32 {
579
+ return ((a - 1u) / b + 1u);
580
+ }
581
+
582
+ ${t}
583
+
584
+ ${M("index")} {
585
+ // One workgroup per row (batch).
586
+ let Length = uniforms.reduceSize;
587
+ let BatchSize = uniforms.batchSize;
588
+
589
+ let row = i32(workgroupId.x);
590
+ let offset = row * Length;
591
+
592
+ var sum_x2 = 0.0f;
593
+ var sum_dygx = 0.0f;
594
+
595
+ for (var k = i32(localId.x); k < Length; k = k + ${e}) {
596
+ ${n}
597
+ }
598
+
599
+ partials[localId.x] = vec2<f32>(sum_x2, sum_dygx);
600
+ workgroupBarrier();
601
+
602
+ var reduceSize = min(u32(Length), ${e}u);
603
+ for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) {
604
+ let interval = DIV_CEIL(reduceSize, 2u);
605
+ if (localId.x < currentSize) {
606
+ partials[localId.x] = partials[localId.x] + partials[localId.x + interval];
607
+ }
608
+ reduceSize = interval;
609
+ workgroupBarrier();
610
+ }
611
+
612
+ let invN = 1.0f / f32(${this.packed ? "Length * 2" : "Length"});
613
+ let mean_x2 = fma(partials[0].x, invN, ${this.epsilon.toExponential()});
614
+ let mean_dygx = partials[0].y * invN;
615
+
616
+ let invRMS = inverseSqrt(mean_x2);
617
+ let scale = (mean_dygx / (mean_x2)) * invRMS;
618
+
619
+ // write dx and dGamma.
620
+ for (var k = i32(localId.x); k < Length; k = k + ${e}) {
621
+ ${r}
622
+ }
623
+ }
624
+ `;
625
+ }
626
+ };
627
+ function ue(t) {
628
+ let { dy: n, x: r, gamma: i } = t.inputs, a = t.attrs?.epsilon ?? 1e-8;
629
+ e(r.shape, n.shape, "Error in RMSNormGrad dy: ");
630
+ let s = E(r), c = i ? E(i) : !1, l = E(n), u = s || c || l, d = !u || s ? r : D(r), f = !u || c || !i ? i : D(i), p = !u || l ? n : D(n);
631
+ f && e(f.shape, [d.shape[d.shape.length - 1]], "Error in RMSNormGrad gamma: ");
632
+ let m = t.backend, h = G(f ? [
633
+ d,
634
+ f,
635
+ p
636
+ ] : [d, p], -1), g = i ? new ce(h, 4, u, a) : new le(h, u, a), _ = [{
637
+ type: "int32",
638
+ data: [g.inputShape[1]]
639
+ }, {
640
+ type: "int32",
641
+ data: [g.inputShape[0]]
642
+ }];
643
+ if (h.inSize > 1024) throw Error(`rmsNormGradGPU: inSize ${h.inSize} exceeds max of 1024`);
644
+ let v = m.runWebGPUProgram(g, f ? [
645
+ d,
646
+ f,
647
+ p
648
+ ] : [d, p], u ? "packedF16" : "float32", _);
649
+ u && !s && d.dispose(), u && !c && f && f.dispose(), u && !l && p.dispose();
650
+ let y = o().makeTensorFromTensorInfo(v);
651
+ if (i) {
652
+ let e = Y(y, [0, 0], [h.batchSize, h.inSize]), t = Y(y, [h.batchSize, 0], [h.batchSize / 4, h.inSize]);
653
+ y.dispose();
654
+ let n = w(e, r.shape);
655
+ e.dispose();
656
+ let i = k(t, [0]);
657
+ return t.dispose(), [n, !u || c ? i : T(i)];
658
+ }
659
+ {
660
+ let e = w(y, r.shape);
661
+ return y.dispose(), [e];
662
+ }
663
+ }
664
+ l({
665
+ kernelName: "RMSNormGrad",
666
+ backendName: "webgpu",
667
+ kernelFunc: ue
668
+ });
669
+ // lib/ops/webgpu/rope.ts
670
+ var de = class {
671
+ variableNames = [
672
+ "x",
673
+ "sin",
674
+ "cos"
675
+ ];
676
+ outputShape;
677
+ shaderKey = "Rope";
678
+ dispatchLayout;
679
+ dispatch;
680
+ workgroupSize = [
681
+ 64,
682
+ 1,
683
+ 1
684
+ ];
685
+ size = !0;
686
+ uniforms = "pastLen: i32";
687
+ interleaved;
688
+ constructor(e, t, n, r, i = !0) {
689
+ this.shaderKey = `Rope_${r}_${i ? "interleaved" : "split"}`, this.outputShape = [
690
+ e,
691
+ t,
692
+ n,
693
+ r
694
+ ], this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize), this.interleaved = i;
695
+ }
696
+ getUserCode() {
697
+ let e = this.outputShape[3];
698
+ return `
699
+ ${M("index")} {
700
+ if (index < uniforms.size) {
701
+ let coords = getCoordsFromIndex(index); // [b, h, t, d]
702
+ let b = coords[0];
703
+ let h = coords[1];
704
+ let t = coords[2];
705
+ let d = coords[3];
706
+
707
+ let rotaryDim = ${e};
708
+
709
+ var outVal = 0.0;
710
+
711
+ let xIdx = b * uniforms.outShapeStrides[0] +
712
+ h * uniforms.outShapeStrides[1] +
713
+ t * uniforms.outShapeStrides[2] +
714
+ d;
715
+
716
+ if (d < rotaryDim) {
717
+ let half = rotaryDim / 2;
718
+ let idx = (t + uniforms.pastLen + b) * uniforms.cosShape[1] +
719
+ ${this.interleaved ? "d / 2" : "d % half"};
720
+ let cos = cos[idx];
721
+ let sin = sin[idx];
722
+
723
+ let ownX = x[xIdx] * cos;
724
+ var evenOdd = 0.0;
725
+
726
+ if (${this.interleaved ? "d % 2 == 0" : "d < half"}) {
727
+ evenOdd = -x[${this.interleaved ? "xIdx + 1" : "xIdx + half"}];
728
+ } else {
729
+ evenOdd = x[${this.interleaved ? "xIdx - 1" : "xIdx - half"}];
730
+ }
731
+
732
+ outVal = fma(evenOdd, sin, ownX);
733
+ } else {
734
+ // pass through for non-rotary dims
735
+ outVal = x[xIdx];
736
+ }
737
+
738
+ setOutputAtIndex(index, outVal);
739
+ }
740
+ }
741
+ `;
742
+ }
743
+ }, fe = class {
744
+ variableNames = [
745
+ "x",
746
+ "sin",
747
+ "cos"
748
+ ];
749
+ outputShape;
750
+ shaderKey = "Rope";
751
+ dispatchLayout;
752
+ dispatch;
753
+ workgroupSize = [
754
+ 64,
755
+ 1,
756
+ 1
757
+ ];
758
+ size = !0;
759
+ uniforms = "pastLen: i32";
760
+ constructor(e, t, n, r) {
761
+ this.shaderKey = `Rope_${r}_interleaved_packed`, this.outputShape = [
762
+ e,
763
+ t,
764
+ n,
765
+ r / 2
766
+ ], this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
767
+ }
768
+ getUserCode() {
769
+ return `
770
+ ${M("index")} {
771
+ if (index < uniforms.size) {
772
+ let coords = getCoordsFromIndex(index); // [b, h, t, d]
773
+ let b = coords[0];
774
+ let h = coords[1];
775
+ let t = coords[2];
776
+ let d = coords[3];
777
+
778
+ var outVal = vec2<f32>(0.0, 0.0);
779
+
780
+ let xIdx = b * uniforms.outShapeStrides[0] +
781
+ h * uniforms.outShapeStrides[1] +
782
+ t * uniforms.outShapeStrides[2] +
783
+ d;
784
+
785
+ let xPair = unpack2x16float(u32(x[xIdx]));
786
+ let idx = (t + uniforms.pastLen + b) * uniforms.cosShape[1] + d;
787
+ let cosVal = cos[idx];
788
+ let sinVal = sin[idx];
789
+
790
+ outVal = vec2<f32>(
791
+ fma(-xPair.y, sinVal, xPair.x * cosVal),
792
+ fma(xPair.x, sinVal, xPair.y * cosVal)
793
+ );
794
+
795
+ result[index] = i32(pack2x16float(outVal));
796
+ }
797
+ }
798
+ `;
799
+ }
800
+ }, pe = class {
801
+ variableNames = [
802
+ "x",
803
+ "sin",
804
+ "cos"
805
+ ];
806
+ outputShape;
807
+ shaderKey = "Rope";
808
+ dispatchLayout;
809
+ dispatch;
810
+ workPerThread = 2;
811
+ workgroupSize = [
812
+ 64,
813
+ 1,
814
+ 1
815
+ ];
816
+ size = !0;
817
+ uniforms = "pastLen: i32";
818
+ constructor(e, t, n, r) {
819
+ this.shaderKey = `Rope_${r}_split_packed`, this.outputShape = [
820
+ e,
821
+ t,
822
+ n,
823
+ r / 2
824
+ ], this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
825
+ this.workPerThread,
826
+ 1,
827
+ 1
828
+ ]);
829
+ }
830
+ getUserCode() {
831
+ return `
832
+ ${M("index")} {
833
+ let halfPacked = uniforms.outShape[3] / 2;
834
+ for (var i = 0; i < ${this.workPerThread}; i = i + 1) {
835
+ let flatIndex = index * ${this.workPerThread} + i;
836
+ if (flatIndex < uniforms.size) {
837
+ let coords = getCoordsFromIndex(flatIndex); // [b, h, t, dPacked]
838
+ let d = coords[3];
839
+
840
+ if (d < halfPacked) {
841
+ let t = coords[2];
842
+ let xLow = unpack2x16float(u32(x[flatIndex]));
843
+ let xHigh = unpack2x16float(u32(x[flatIndex + halfPacked]));
844
+
845
+ let scalar0 = d * 2;
846
+ let scalar1 = scalar0 + 1;
847
+ let cacheOffset = (t + uniforms.pastLen + coords[0]) * uniforms.cosShape[1];
848
+
849
+ let cos0 = cos[cacheOffset + scalar0];
850
+ let sin0 = sin[cacheOffset + scalar0];
851
+ let cos1 = cos[cacheOffset + scalar1];
852
+ let sin1 = sin[cacheOffset + scalar1];
853
+
854
+ let outLow = vec2<f32>(
855
+ fma(-xHigh.x, sin0, xLow.x * cos0),
856
+ fma(-xHigh.y, sin1, xLow.y * cos1)
857
+ );
858
+ let outHigh = vec2<f32>(
859
+ fma(xLow.x, sin0, xHigh.x * cos0),
860
+ fma(xLow.y, sin1, xHigh.y * cos1)
861
+ );
862
+
863
+ result[flatIndex] = i32(pack2x16float(outLow));
864
+ result[flatIndex + halfPacked] = i32(pack2x16float(outHigh));
865
+ }
866
+ }
867
+ }
868
+ }
869
+ `;
870
+ }
871
+ };
872
+ function me(t) {
873
+ let { x: n } = t.inputs, { pastLen: r, negSin: i, ropeCache: a, interleaved: o } = t.attrs, s = t.backend, c = E(n), l = n.shape[0], u = n.shape[1], d = n.shape[2], f = c ? n.shape[3] * 2 : n.shape[3], p = i ? a.getNegSin() : a.getSin(), m = a.getCos();
874
+ if (e(p.shape, m.shape, "Error in Rope: "), p.shape[0] < d + r) throw Error(`Sin tensor shape ${p.shape} is not compatible with seqLength ${d} and pastLen ${r}.`);
875
+ if (p.shape[1] * 2 < f) throw Error(`Sin tensor shape ${p.shape} is not compatible with feature dimension ${f}.`);
876
+ if (p.shape.length !== 3) throw Error(`Sin tensor must be 3-dimensional, but got shape ${p.shape}.`);
877
+ let h = c ? o ? new fe(l, u, d, f) : new pe(l, u, d, f) : new de(l, u, d, f, o), g = [{
878
+ type: "int32",
879
+ data: [r]
880
+ }], _ = c ? "packedF16" : n.dtype;
881
+ return s.runWebGPUProgram(h, [
882
+ n,
883
+ p,
884
+ m
885
+ ], _, g);
886
+ }
887
+ l({
888
+ kernelName: "Rope",
889
+ backendName: "webgpu",
890
+ kernelFunc: me
891
+ });
892
+ // lib/ops/webgpu/appendCache.ts
893
+ var he = class {
894
+ variableNames = ["cache", "item"];
895
+ outputShape;
896
+ shaderKey = "AppendCache";
897
+ dispatchLayout;
898
+ dispatch;
899
+ workgroupSize = [
900
+ 64,
901
+ 1,
902
+ 1
903
+ ];
904
+ size = !0;
905
+ uniforms = "cacheT: i32";
906
+ constructor(e, t, n, r, i) {
907
+ let a = Math.min(n + 1, i);
908
+ this.shaderKey = `AppendCache_${a}`, this.outputShape = [
909
+ e,
910
+ t,
911
+ a,
912
+ r
913
+ ], this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
914
+ }
915
+ getUserCode() {
916
+ let e = this.outputShape[2];
917
+ return `
918
+ ${M("index")} {
919
+ if (index < uniforms.size) {
920
+ let coords = getCoordsFromIndex(index); // [b, h, t, d]
921
+ let b = coords[0];
922
+ let h = coords[1];
923
+ let t = coords[2];
924
+ let d = coords[3];
925
+
926
+ let itemT = 1;
927
+ let maxSize = ${e};
928
+ let totalT = uniforms.cacheT + itemT;
929
+ let start = select(0, 1, totalT >= maxSize);
930
+
931
+ let srcT = t + start;
932
+ var val = 0.0;
933
+ if (srcT < uniforms.cacheT) {
934
+ val = getCache(b, h, srcT, d);
935
+ }
936
+ if (srcT == uniforms.cacheT) {
937
+ val = getItem(b, h, 0, d);
938
+ }
939
+
940
+ setOutputAtIndex(index, val);
941
+ }
942
+ }
943
+ `;
944
+ }
945
+ }, ge = class {
946
+ variableNames = ["cache", "item"];
947
+ outputShape;
948
+ shaderKey = "AppendCache";
949
+ dispatchLayout;
950
+ dispatch;
951
+ workgroupSize = [
952
+ 64,
953
+ 1,
954
+ 1
955
+ ];
956
+ size = !0;
957
+ uniforms = "cacheT: i32";
958
+ constructor(e, t, n, r, i) {
959
+ let a = Math.min(n + 1, i);
960
+ this.shaderKey = `AppendCache_${a}`, this.outputShape = [
961
+ e,
962
+ t,
963
+ a,
964
+ r
965
+ ], this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
966
+ }
967
+ getUserCode() {
968
+ let e = this.outputShape[2];
969
+ return `
970
+ ${M("index")} {
971
+ if (index < uniforms.size) {
972
+ let coords = getCoordsFromIndex(index); // [b, h, t, d]
973
+ let b = coords[0];
974
+ let h = coords[1];
975
+ let t = coords[2];
976
+ let d = coords[3];
977
+
978
+ let itemT = 1;
979
+ let maxSize = ${e};
980
+ let totalT = uniforms.cacheT + itemT;
981
+ let start = select(0, 1, totalT >= maxSize);
982
+
983
+ let srcT = t + start;
984
+ var val: i32 = 0i;
985
+ if (srcT < uniforms.cacheT) {
986
+ val = cache[getIndexFromCoords4D(vec4<i32>(b, h, srcT, d), uniforms.cacheShape)];
987
+ }
988
+ if (srcT == uniforms.cacheT) {
989
+ val = item[getIndexFromCoords4D(vec4<i32>(b, h, 0, d), uniforms.itemShape)];
990
+ }
991
+
992
+ result[index] = val;
993
+ }
994
+ }
995
+ `;
996
+ }
997
+ };
998
+ function _e(t) {
999
+ let { cache: n, item: r } = t.inputs, { maxSize: i, pastLen: a } = t.attrs, o = t.backend, s = E(n), c = n.shape[0], l = n.shape[2], u = n.shape[1];
1000
+ if (e(r.shape, [
1001
+ c,
1002
+ u,
1003
+ 1,
1004
+ r.shape[3]
1005
+ ], "Error in AppendCache: "), a < 0 || a > i) throw Error(`Invalid pastLen value: ${a}. Must be in the range [0, ${i}].`);
1006
+ let d = s ? new ge(c, u, l, r.shape[3], i) : new he(c, u, l, r.shape[3], i), f = [{
1007
+ type: "int32",
1008
+ data: [a]
1009
+ }], p = s ? "packedF16" : n.dtype;
1010
+ return o.runWebGPUProgram(d, [n, r], p, f);
1011
+ }
1012
+ l({
1013
+ kernelName: "AppendCache",
1014
+ backendName: "webgpu",
1015
+ kernelFunc: _e
1016
+ });
1017
+ // lib/ops/webgpu/scatterSub.ts
1018
+ var ve = class {
1019
+ variableNames = [
1020
+ "labels",
1021
+ "softmaxProbs",
1022
+ "dy"
1023
+ ];
1024
+ outputShape;
1025
+ shaderKey = "ScatterSub";
1026
+ dispatchLayout;
1027
+ dispatch;
1028
+ workgroupSize = [
1029
+ 64,
1030
+ 1,
1031
+ 1
1032
+ ];
1033
+ size = !0;
1034
+ uniforms = "targetWeight: f32";
1035
+ constructor(e, t) {
1036
+ this.outputShape = [e, t], this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
1037
+ }
1038
+ getUserCode() {
1039
+ return `
1040
+ ${M("index")} {
1041
+ if (index < uniforms.size) {
1042
+ let coords = getCoordsFromIndex(index); // [batch, depth]
1043
+ let idx = i32(labels[coords[0]]);
1044
+ let prob = softmaxProbs[index];
1045
+ let dy = dy[coords[0]];
1046
+ setOutputAtIndex(index, select(prob, prob - uniforms.targetWeight, idx == coords[1]) * dy);
1047
+ }
1048
+ }
1049
+ `;
1050
+ }
1051
+ };
1052
+ function ye(t) {
1053
+ let { logits: n, labels: r, dy: i } = t.inputs, a = t.attrs?.targetWeight ?? 1, o = t.backend, s = r.shape[0], c = n.shape[1];
1054
+ e(i.shape, [s], "Error in EfficientScatterSub dy: "), e(n.shape, [s, c], "Error in EfficientScatterSub logits: "), e(r.shape, [s], "Error in EfficientScatterSub labels: ");
1055
+ let l = new ve(s, c);
1056
+ return o.runWebGPUProgram(l, [
1057
+ r,
1058
+ n,
1059
+ i
1060
+ ], "float32", [{
1061
+ type: "float32",
1062
+ data: [a]
1063
+ }]);
1064
+ }
1065
+ l({
1066
+ kernelName: "EfficientScatterSub",
1067
+ backendName: "webgpu",
1068
+ kernelFunc: ye
1069
+ });
1070
+ // lib/ops/webgpu/gatherSub.ts
1071
+ var be = class {
1072
+ variableNames = [
1073
+ "labels",
1074
+ "logits",
1075
+ "values"
1076
+ ];
1077
+ outputShape;
1078
+ shaderKey = "GatherSub";
1079
+ dispatchLayout;
1080
+ dispatch;
1081
+ workgroupSize = [
1082
+ 64,
1083
+ 1,
1084
+ 1
1085
+ ];
1086
+ size = !0;
1087
+ constructor(e) {
1088
+ this.outputShape = [e], this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
1089
+ }
1090
+ getUserCode() {
1091
+ return `
1092
+ ${M("index")} {
1093
+ if (index < uniforms.size) {
1094
+ let idx = i32(labels[index]);
1095
+ let val = values[index];
1096
+ let logit = logits[index * uniforms.logitsShape[1] + idx];
1097
+ setOutputAtIndex(index, val - logit);
1098
+ }
1099
+ }
1100
+ `;
1101
+ }
1102
+ };
1103
+ function xe(t) {
1104
+ let { logits: n, labels: r, values: i } = t.inputs, a = t.backend, o = r.shape[0];
1105
+ e(i.shape, [o], "Error in EfficientGatherSub: "), e(r.shape, [o], "Error in EfficientGatherSub: ");
1106
+ let s = new be(o);
1107
+ return a.runWebGPUProgram(s, [
1108
+ r,
1109
+ n,
1110
+ i
1111
+ ], "float32");
1112
+ }
1113
+ l({
1114
+ kernelName: "EfficientGatherSub",
1115
+ backendName: "webgpu",
1116
+ kernelFunc: xe
1117
+ });
1118
+ // lib/ops/webgpu/qkv.ts
1119
+ function Se(e) {
1120
+ let { x: t, kernel: n } = e.inputs, { heads: r } = e.attrs, i = e.attrs?.kvHeads ?? r, a = t.shape[0], o = t.shape[1], s = t.shape[2], c = E(t), l = r + 2 * i;
1121
+ if (n.shape[0] !== (c ? s * 2 : s)) throw Error(`Error in QKV: kernel rows ${n.shape[0]} do not match input channels.`);
1122
+ let u = n.shape[1];
1123
+ if (u % l !== 0) throw Error(`QKV kernel width ${u} must be divisible by ${l} heads.`);
1124
+ let d = u / l, f = O(t, n, !1, !1, {
1125
+ forceOutputShape: [
1126
+ a,
1127
+ o,
1128
+ l,
1129
+ d
1130
+ ],
1131
+ perm: [
1132
+ 0,
1133
+ 2,
1134
+ 1,
1135
+ 3
1136
+ ]
1137
+ }), p = [
1138
+ Y(f, [
1139
+ 0,
1140
+ 0,
1141
+ 0,
1142
+ 0
1143
+ ], [
1144
+ a,
1145
+ r,
1146
+ o,
1147
+ d
1148
+ ]),
1149
+ Y(f, [
1150
+ 0,
1151
+ r,
1152
+ 0,
1153
+ 0
1154
+ ], [
1155
+ a,
1156
+ i,
1157
+ o,
1158
+ d
1159
+ ]),
1160
+ Y(f, [
1161
+ 0,
1162
+ r + i,
1163
+ 0,
1164
+ 0
1165
+ ], [
1166
+ a,
1167
+ i,
1168
+ o,
1169
+ d
1170
+ ])
1171
+ ];
1172
+ return f.dispose(), p;
1173
+ }
1174
+ l({
1175
+ kernelName: "QKV",
1176
+ backendName: "webgpu",
1177
+ kernelFunc: Se
1178
+ });
1179
+ // lib/ops/webgpu/gelu.ts
1180
+ var X = .7978845608028654, Z = .044715, Ce = class {
1181
+ outputShape;
1182
+ shaderKey;
1183
+ dispatchLayout;
1184
+ dispatch;
1185
+ variableNames = ["A"];
1186
+ workgroupSize;
1187
+ size = !0;
1188
+ constructor(e) {
1189
+ this.workgroupSize = [
1190
+ 128,
1191
+ 1,
1192
+ 1
1193
+ ], this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "unary_gelu";
1194
+ }
1195
+ getUserCode() {
1196
+ return `
1197
+ // TODO: revisit after https://github.com/gpuweb/gpuweb/issues/4458 is resolved
1198
+ fn tanhComplete(x: f32) -> f32 {
1199
+ return select(tanh(x), sign(x), abs(x) > 15.0);
1200
+ }
1201
+ fn unaryOperation(x : f32) -> f32 {
1202
+ let x3 = x * x * x;
1203
+ var inner = fma(${Z}, x3, x);
1204
+ inner = ${X} * inner;
1205
+ inner = tanhComplete(inner);
1206
+ inner = 0.5 * (1.0 + inner);
1207
+ return x * inner;
1208
+ }
1209
+ ${M("index")} {
1210
+ if (index < uniforms.size) {
1211
+ let a = getAByOutputIndex(index);
1212
+ setOutputAtIndex(index, unaryOperation(a));
1213
+ }
1214
+ }
1215
+ `;
1216
+ }
1217
+ };
1218
+ function we(e) {
1219
+ let { x: t } = e.inputs, n = e.backend, r = new Ce(t.shape);
1220
+ return n.runWebGPUProgram(r, [t], "float32");
1221
+ }
1222
+ l({
1223
+ kernelName: "Gelu",
1224
+ backendName: "webgpu",
1225
+ kernelFunc: we
1226
+ });
1227
+ var Te = class {
1228
+ variableNames = ["dy", "x"];
1229
+ outputShape;
1230
+ shaderKey = "GeluGrad";
1231
+ dispatchLayout;
1232
+ dispatch;
1233
+ workgroupSize = [
1234
+ 128,
1235
+ 1,
1236
+ 1
1237
+ ];
1238
+ size = !0;
1239
+ constructor(e) {
1240
+ this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
1241
+ }
1242
+ getUserCode() {
1243
+ return `
1244
+ // TODO: revisit after https://github.com/gpuweb/gpuweb/issues/4458 is resolved
1245
+ fn tanhComplete(x: f32) -> f32 {
1246
+ return select(tanh(x), sign(x), abs(x) > 15.0);
1247
+ }
1248
+ fn activationGrad(dy: f32, X: f32) -> f32 {
1249
+ let x2 = X * X;
1250
+ let x3 = x2 * X;
1251
+ let u = ${X} * (X + ${Z} * x3);
1252
+ let t = tanhComplete(u);
1253
+ let sech2 = 1.0 - t * t;
1254
+ let du_dx = ${X} * (1.0 + 3.0 * ${Z} * x2);
1255
+ let dgelu = 0.5 * (1.0 + t) + 0.5 * X * sech2 * du_dx;
1256
+ return dy *dgelu;
1257
+ }
1258
+ ${M("index")} {
1259
+ if (index < uniforms.size) {
1260
+ let X = unpack2x16float(u32(x[index]));
1261
+ let DY = unpack2x16float(u32(dy[index]));
1262
+ let dgelu = vec2<f32>(
1263
+ activationGrad(DY.x, X.x),
1264
+ activationGrad(DY.y, X.y)
1265
+ );
1266
+ result[index] = i32(pack2x16float(dgelu));
1267
+ }
1268
+ }`;
1269
+ }
1270
+ }, Ee = class {
1271
+ variableNames = ["dy", "x"];
1272
+ outputShape;
1273
+ shaderKey = "GeluGrad";
1274
+ dispatchLayout;
1275
+ dispatch;
1276
+ workgroupSize = [
1277
+ 128,
1278
+ 1,
1279
+ 1
1280
+ ];
1281
+ size = !0;
1282
+ constructor(e) {
1283
+ this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
1284
+ }
1285
+ getUserCode() {
1286
+ return `
1287
+ // TODO: revisit after https://github.com/gpuweb/gpuweb/issues/4458 is resolved
1288
+ fn tanhComplete(x: f32) -> f32 {
1289
+ return select(tanh(x), sign(x), abs(x) > 15.0);
1290
+ }
1291
+ fn activationGrad(dy: f32, X: f32) -> f32 {
1292
+ let x2 = X * X;
1293
+ let x3 = x2 * X;
1294
+ let u = ${X} * (X + ${Z} * x3);
1295
+ let t = tanhComplete(u);
1296
+ let sech2 = 1.0 - t * t;
1297
+ let du_dx = ${X} * (1.0 + 3.0 * ${Z} * x2);
1298
+ let dgelu = 0.5 * (1.0 + t) + 0.5 * X * sech2 * du_dx;
1299
+ return dy *dgelu;
1300
+ }
1301
+ ${M("index")} {
1302
+ if (index < uniforms.size) {
1303
+ let X = getXByOutputIndex(index);
1304
+ let DY = getDyByOutputIndex(index);
1305
+ let dgelu = activationGrad(DY, X);
1306
+ setOutputAtIndex(index, dgelu);
1307
+ }
1308
+ }`;
1309
+ }
1310
+ };
1311
+ function De(e) {
1312
+ let { dy: t, x: n } = e.inputs, r = e.backend, i = E(t), a = i ? new Te(n.shape) : new Ee(n.shape);
1313
+ return r.runWebGPUProgram(a, [t, n], i ? "packedF16" : "float32");
1314
+ }
1315
+ l({
1316
+ kernelName: "GeluGrad",
1317
+ backendName: "webgpu",
1318
+ kernelFunc: De
1319
+ });
1320
+ // lib/ops/webgpu/adamMoments.ts
1321
+ var Oe = class {
1322
+ variableNames = [
1323
+ "moments",
1324
+ "gradient",
1325
+ "scaling"
1326
+ ];
1327
+ outputShape;
1328
+ shaderKey = "AdamMoments";
1329
+ dispatchLayout;
1330
+ dispatch;
1331
+ workgroupSize = [
1332
+ 64,
1333
+ 1,
1334
+ 1
1335
+ ];
1336
+ size = !0;
1337
+ uniforms = "beta1: f32, beta2: f32";
1338
+ outputComponent = 2;
1339
+ variableComponents = [
1340
+ 2,
1341
+ 1,
1342
+ 1
1343
+ ];
1344
+ constructor(e) {
1345
+ this.outputShape = e, this.dispatchLayout = A(this.outputShape.slice(0, -1)), this.dispatch = N(this.dispatchLayout, this.outputShape.slice(0, -1), this.workgroupSize, [
1346
+ 1,
1347
+ 1,
1348
+ 1
1349
+ ]);
1350
+ }
1351
+ getUserCode() {
1352
+ return `
1353
+ ${M("index")} {
1354
+ if (index < uniforms.size) {
1355
+ let m: vec2<f32> = moments[index];
1356
+
1357
+ // Loss and clip scaling.
1358
+ let g: f32 = gradient[index] * scaling[0];
1359
+
1360
+ let newM1 = fma(m.x, uniforms.beta1, g * (1.0 - uniforms.beta1));
1361
+ let newM2 = fma(m.y, uniforms.beta2, g * g * (1.0 - uniforms.beta2));
1362
+
1363
+ setOutputAtIndex(index, vec2<f32>(newM1, newM2));
1364
+ }
1365
+ }
1366
+ `;
1367
+ }
1368
+ };
1369
+ function ke(t) {
1370
+ let { moments: n, gradient: r, scaling: i } = t.inputs, { beta1: a, beta2: o } = t.attrs, s = t.backend;
1371
+ if (r.dtype !== "float32") throw Error(`Gradient must be float32, but got ${r.dtype}`);
1372
+ if (e(n.shape, [...r.shape, 2], "Error in AdamMoments: "), a < 0 || a >= 1) throw Error(`Invalid beta1 value: ${a}. Must be in the range [0, 1).`);
1373
+ if (o < 0 || o >= 1) throw Error(`Invalid beta2 value: ${o}. Must be in the range [0, 1).`);
1374
+ let c = new Oe(n.shape), l = [{
1375
+ type: "float32",
1376
+ data: [a]
1377
+ }, {
1378
+ type: "float32",
1379
+ data: [o]
1380
+ }];
1381
+ return s.runWebGPUProgram(c, [
1382
+ n,
1383
+ r,
1384
+ i
1385
+ ], "float32", l);
1386
+ }
1387
+ l({
1388
+ kernelName: "AdamMoments",
1389
+ backendName: "webgpu",
1390
+ kernelFunc: ke
1391
+ });
1392
+ // lib/ops/webgpu/adamAdjust.ts
1393
+ var Ae = class {
1394
+ variableNames = ["moments", "value"];
1395
+ outputShape;
1396
+ shaderKey = "AdamAdjust";
1397
+ dispatchLayout;
1398
+ dispatch;
1399
+ workgroupSize = [
1400
+ 64,
1401
+ 1,
1402
+ 1
1403
+ ];
1404
+ size = !0;
1405
+ uniforms = "invbeta1: f32, invbeta2: f32, learningRate: f32, epsilon: f32";
1406
+ outputComponent = 1;
1407
+ variableComponents = [2, 1];
1408
+ useWeightDecay;
1409
+ constructor(e, t) {
1410
+ this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize), this.useWeightDecay = t, t && (this.uniforms += ", weightDecay: f32");
1411
+ }
1412
+ getUserCode() {
1413
+ return `
1414
+ ${M("index")} {
1415
+ if (index < uniforms.size) {
1416
+ let moments: vec2<f32> = moments[index];
1417
+ let value: f32 = value[index];
1418
+
1419
+ let m1Hat = moments.x * uniforms.invbeta1;
1420
+ let m2Hat = moments.y * uniforms.invbeta2;
1421
+
1422
+ let invSqrt = inverseSqrt(max(m2Hat, 1e-30));
1423
+ let invDenom = invSqrt / fma(uniforms.epsilon, invSqrt, 1.0);
1424
+ var adjustedValue = fma(-uniforms.learningRate * m1Hat, invDenom, value);
1425
+
1426
+ ${this.useWeightDecay ? "adjustedValue = adjustedValue - uniforms.learningRate * uniforms.weightDecay * value;" : ""}
1427
+
1428
+ setOutputAtIndex(index, adjustedValue);
1429
+ }
1430
+ }
1431
+ `;
1432
+ }
1433
+ };
1434
+ function je(t) {
1435
+ let { moments: n, value: r } = t.inputs, { beta1: i, beta2: a, learningRate: o, epsilon: s, weightDecay: c } = t.attrs, l = t.backend;
1436
+ e(n.shape, [...r.shape, 2], "Error in AdamAdjust: ");
1437
+ let u = new Ae(r.shape, c > 0), d = [
1438
+ {
1439
+ type: "float32",
1440
+ data: [1 / i]
1441
+ },
1442
+ {
1443
+ type: "float32",
1444
+ data: [1 / a]
1445
+ },
1446
+ {
1447
+ type: "float32",
1448
+ data: [o]
1449
+ },
1450
+ {
1451
+ type: "float32",
1452
+ data: [s]
1453
+ }
1454
+ ];
1455
+ return c > 0 && d.push({
1456
+ type: "float32",
1457
+ data: [c]
1458
+ }), l.runWebGPUProgram(u, [n, r], "float32", d);
1459
+ }
1460
+ l({
1461
+ kernelName: "AdamAdjust",
1462
+ backendName: "webgpu",
1463
+ kernelFunc: je
1464
+ });
1465
+ // lib/ops/webgpu/adamW.ts
1466
+ var Me = class {
1467
+ outputShape;
1468
+ variableNames = [
1469
+ "moments",
1470
+ "gradient",
1471
+ "value",
1472
+ "scaling",
1473
+ "newMoments"
1474
+ ];
1475
+ auxiliaryOutputs;
1476
+ shaderKey = "AdamW";
1477
+ dispatchLayout;
1478
+ dispatch;
1479
+ workgroupSize = [
1480
+ 64,
1481
+ 1,
1482
+ 1
1483
+ ];
1484
+ size = !0;
1485
+ outputComponent = 1;
1486
+ variableComponents = [
1487
+ 2,
1488
+ 1,
1489
+ 1,
1490
+ 1,
1491
+ 2
1492
+ ];
1493
+ uniforms = "beta1: f32, beta2: f32, invbeta1: f32, invbeta2: f32, learningRate: f32, epsilon: f32, weightDecay: f32";
1494
+ constructor(e) {
1495
+ this.outputShape = e, this.auxiliaryOutputs = [{
1496
+ name: "newMoments",
1497
+ shape: [...e, 2],
1498
+ dtype: "float32"
1499
+ }], this.dispatchLayout = A(e), this.dispatch = N(this.dispatchLayout, e, this.workgroupSize);
1500
+ }
1501
+ getUserCode() {
1502
+ return `
1503
+ ${M("index")} {
1504
+ if (index < uniforms.size) {
1505
+ let m = moments[index];
1506
+ let g = gradient[index] * scaling[0];
1507
+ let newM1 = fma(m.x, uniforms.beta1, g * (1.0 - uniforms.beta1));
1508
+ let newM2 = fma(m.y, uniforms.beta2, g * g * (1.0 - uniforms.beta2));
1509
+ let oldValue = value[index];
1510
+ let m1Hat = newM1 * uniforms.invbeta1;
1511
+ let m2Hat = newM2 * uniforms.invbeta2;
1512
+ let invSqrt = inverseSqrt(max(m2Hat, 1e-30));
1513
+ let invDenom = invSqrt / fma(uniforms.epsilon, invSqrt, 1.0);
1514
+ var adjustedValue = fma(-uniforms.learningRate * m1Hat, invDenom, oldValue);
1515
+ if (uniforms.weightDecay > 0.0) {
1516
+ adjustedValue = adjustedValue - uniforms.learningRate * uniforms.weightDecay * oldValue;
1517
+ }
1518
+ newMoments[index] = vec2<f32>(newM1, newM2);
1519
+ setOutputAtIndex(index, adjustedValue);
1520
+ }
1521
+ }`;
1522
+ }
1523
+ };
1524
+ function Ne(t) {
1525
+ let { moments: n, gradient: r, value: i, scaling: a } = t.inputs;
1526
+ if (!n || !r || !i || !a) throw Error("AdamW requires moments, gradient, value and scaling inputs.");
1527
+ let { beta1: o, beta2: s, oneMinusAccBeta1: c, oneMinusAccBeta2: l, epsilon: d, learningRate: f, weightDecay: p } = t.attrs;
1528
+ if (!(t.backend instanceof F)) throw Error("AdamW requires the patched WebGPU backend.");
1529
+ for (let [e, t] of Object.entries({
1530
+ moments: n,
1531
+ gradient: r,
1532
+ value: i,
1533
+ scaling: a
1534
+ })) if (t.dtype !== "float32") throw Error(`AdamW ${e} must be float32, but got ${t.dtype}`);
1535
+ if (e(i.shape, r.shape, "Error in AdamW: "), e(n.shape, [...i.shape, 2], "Error in AdamW: "), u(a.shape) < 1) throw Error("AdamW scaling must contain at least one value.");
1536
+ for (let [e, t] of [["beta1", o], ["beta2", s]]) if (!Number.isFinite(t) || t < 0 || t >= 1) throw Error(`Invalid ${e} value: ${t}. Must be in the range [0, 1).`);
1537
+ for (let e of [c, l]) if (!Number.isFinite(e) || e <= 0 || e > 1) throw Error(`Invalid AdamW bias correction: ${e}. Must be in the range (0, 1].`);
1538
+ return t.backend.runWebGPUProgramWithOutputs(new Me(i.shape), [
1539
+ n,
1540
+ r,
1541
+ i,
1542
+ a
1543
+ ], "float32", [
1544
+ o,
1545
+ s,
1546
+ 1 / c,
1547
+ 1 / l,
1548
+ f,
1549
+ d,
1550
+ p
1551
+ ].map((e) => ({
1552
+ type: "float32",
1553
+ data: [e]
1554
+ })));
1555
+ }
1556
+ l({
1557
+ kernelName: "AdamW",
1558
+ backendName: "webgpu",
1559
+ kernelFunc: Ne
1560
+ });
1561
+ // lib/ops/webgpu/pack16_program.ts
1562
+ var Pe = class {
1563
+ outputShape;
1564
+ shaderKey = "Pack16";
1565
+ dispatchLayout;
1566
+ dispatch;
1567
+ workgroupSize = [
1568
+ 64,
1569
+ 1,
1570
+ 1
1571
+ ];
1572
+ variableNames = ["x"];
1573
+ uniforms;
1574
+ size = !0;
1575
+ outputComponent = 4;
1576
+ scaling = !1;
1577
+ padding = 0;
1578
+ constructor(e, t = 0) {
1579
+ if (e[e.length - 1] % 2 != 0 && t === 0) throw Error("Last dimension of output shape must be even to use Pack16.");
1580
+ if (t % 4 != 0) throw Error("Padding must be a multiple of 4 to use Pack16.");
1581
+ if (this.outputShape = [...e.slice(0, -1), e[e.length - 1]], t > 0) {
1582
+ this.shaderKey += `_Padded${t}`, this.padding = t;
1583
+ for (let e = this.outputShape.length - 2; e < this.outputShape.length; e++) this.outputShape[e] % this.padding !== 0 && (this.outputShape[e] += this.padding - this.outputShape[e] % this.padding);
1584
+ this.outputComponent = 1;
1585
+ }
1586
+ this.outputShape[this.outputShape.length - 1] /= 2, this.outputShape[this.outputShape.length - 1] % this.outputComponent !== 0 && (this.outputComponent = 1), this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
1587
+ this.outputComponent,
1588
+ 1,
1589
+ 1
1590
+ ]);
1591
+ }
1592
+ useScaling() {
1593
+ this.shaderKey += "_Scaled", this.uniforms = "scaling : f32,", this.scaling = !0;
1594
+ }
1595
+ getUserCode() {
1596
+ if (this.padding > 0 && this.outputComponent === 1) {
1597
+ let e = this.outputShape.length;
1598
+ return `
1599
+ ${M("index")} {
1600
+ if (index < uniforms.size) {
1601
+ var coords = getCoordsFromIndex(index);
1602
+ coords[${e} - 1] = coords[${e} - 1] * 2;
1603
+ let row = coords[${e} - 2];
1604
+ let col = coords[${e} - 1];
1605
+ let width = uniforms.xShape[${e} - 1];
1606
+ let height = uniforms.xShape[${e} - 2];
1607
+
1608
+ var value1 = 0.0f;
1609
+ if (col < width && row < height) {
1610
+ let baseInputIndex = getIndexFromCoords${e}D(coords, uniforms.xShape);
1611
+ value1 = x[baseInputIndex] ${this.scaling ? "* uniforms.scaling" : ""};
1612
+ }
1613
+ var value2 = 0.0f;
1614
+ if (col + 1 < width && row < height) {
1615
+ coords[${e} - 1] = coords[${e} - 1] + 1;
1616
+ let baseInputIndex = getIndexFromCoords${e}D(coords, uniforms.xShape);
1617
+ value2 = x[baseInputIndex] ${this.scaling ? "* uniforms.scaling" : ""};
1618
+ }
1619
+ let packed = i32(pack2x16float(vec2<f32>(value1, value2)));
1620
+ result[index] = packed;
1621
+ }
1622
+ }`;
1623
+ }
1624
+ return this.outputComponent === 1 ? `
1625
+ ${M("index")} {
1626
+ if (index < uniforms.size) {
1627
+ let baseInputIndex = index * 2;
1628
+ let x1 = x[baseInputIndex] ${this.scaling ? "* uniforms.scaling" : ""};
1629
+ let x2 = x[baseInputIndex + 1] ${this.scaling ? "* uniforms.scaling" : ""};
1630
+ let packed = i32(pack2x16float(vec2<f32>(x1, x2)));
1631
+ result[index] = packed;
1632
+ }
1633
+ }` : `
1634
+ ${M("index")} {
1635
+ if (index < uniforms.size) {
1636
+ let baseInputIndex = index * 2;
1637
+ let x1 = x[baseInputIndex] ${this.scaling ? "* uniforms.scaling" : ""};
1638
+ let x2 = x[baseInputIndex + 1] ${this.scaling ? "* uniforms.scaling" : ""};
1639
+ let packed = vec4<i32>(
1640
+ i32(pack2x16float(vec2<f32>(x1.x, x1.y))),
1641
+ i32(pack2x16float(vec2<f32>(x1.z, x1.w))),
1642
+ i32(pack2x16float(vec2<f32>(x2.x, x2.y))),
1643
+ i32(pack2x16float(vec2<f32>(x2.z, x2.w)))
1644
+ );
1645
+ result[index] = packed;
1646
+ }
1647
+ }`;
1648
+ }
1649
+ };
1650
+ // lib/ops/webgpu/pack16.ts
1651
+ function Fe(e) {
1652
+ let { x: t } = e.inputs, { scaling: n, padding: r } = e.attrs, i = e.backend;
1653
+ if (t.shape[t.shape.length - 1] % 2 != 0) throw Error("Last dimension of input tensor must be even to use Pack16.");
1654
+ e.attrs && (e.attrs.originalShape = t.shape);
1655
+ let a = new Pe(t.shape, r), o = n !== 1;
1656
+ o && a.useScaling();
1657
+ let s = [{
1658
+ type: "float32",
1659
+ data: [n]
1660
+ }];
1661
+ return i.runWebGPUProgram(a, [t], "packedF16", o ? s : void 0);
1662
+ }
1663
+ l({
1664
+ kernelName: "Pack16",
1665
+ backendName: "webgpu",
1666
+ kernelFunc: Fe
1667
+ });
1668
+ // lib/ops/webgpu/unpack16.ts
1669
+ var Ie = class {
1670
+ outputShape;
1671
+ shaderKey = "Unpack16";
1672
+ dispatchLayout;
1673
+ dispatch;
1674
+ workgroupSize = [
1675
+ 64,
1676
+ 1,
1677
+ 1
1678
+ ];
1679
+ variableNames = ["x"];
1680
+ size = !0;
1681
+ uniforms;
1682
+ outputComponent = 4;
1683
+ variableComponents = [2];
1684
+ scaling = !1;
1685
+ constructor(e) {
1686
+ this.outputShape = [...e.slice(0, -1), e[e.length - 1] * 2], this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
1687
+ 4,
1688
+ 1,
1689
+ 1
1690
+ ]);
1691
+ }
1692
+ useScaling() {
1693
+ this.shaderKey += "_Scaled", this.uniforms = "scaling : f32,", this.scaling = !0;
1694
+ }
1695
+ getUserCode() {
1696
+ return `
1697
+ ${M("index")} {
1698
+ let outIndex = index;
1699
+ if (outIndex < uniforms.size) {
1700
+ let xvec2 = x[index];
1701
+ let v1 = vec4<f32>(
1702
+ unpack2x16float(u32(xvec2.x)),
1703
+ unpack2x16float(u32(xvec2.y))
1704
+ ) ${this.scaling ? "* uniforms.scaling" : ""};
1705
+ result[outIndex] = v1;
1706
+ }
1707
+ }`;
1708
+ }
1709
+ };
1710
+ function Le(e) {
1711
+ let { x: t } = e.inputs, { scaling: n } = e.attrs, r = e.backend, i = new Ie(t.shape), a = n !== 1;
1712
+ a && i.useScaling();
1713
+ let o = [{
1714
+ type: "float32",
1715
+ data: [1 / n]
1716
+ }];
1717
+ return r.runWebGPUProgram(i, [t], "float32", a ? o : void 0);
1718
+ }
1719
+ l({
1720
+ kernelName: "Unpack16",
1721
+ backendName: "webgpu",
1722
+ kernelFunc: Le
1723
+ });
1724
+ // lib/ops/webgpu/softmax16_program.ts
1725
+ var Re = class {
1726
+ variableNames = ["logits"];
1727
+ outputShape;
1728
+ shaderKey;
1729
+ dispatchLayout;
1730
+ dispatch;
1731
+ workgroupSize;
1732
+ constructor(e) {
1733
+ this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = [
1734
+ this.outputShape[0],
1735
+ 1,
1736
+ 1
1737
+ ], this.workgroupSize = this.outputShape[1] >= 4096 ? [
1738
+ 256,
1739
+ 1,
1740
+ 1
1741
+ ] : this.outputShape[1] < 64 ? [
1742
+ 32,
1743
+ 1,
1744
+ 1
1745
+ ] : [
1746
+ 64,
1747
+ 1,
1748
+ 1
1749
+ ], this.shaderKey = "softmax16";
1750
+ }
1751
+ getUserCode() {
1752
+ return `
1753
+ var<workgroup> buf : array<f32, ${this.workgroupSize[0]}>;
1754
+ const blockSize = ${this.workgroupSize[0]};
1755
+ ${M("index")} {
1756
+ let row = index / blockSize;
1757
+ let tid = i32(localId.x);
1758
+ let cols = uniforms.outShape[1];
1759
+ let rowIdx = row * cols;
1760
+
1761
+ var threadMax = -3.402823e+38f;
1762
+ for (var col = tid; col < cols; col += blockSize) {
1763
+ let value = unpack2x16float(u32(logits[rowIdx + col]));
1764
+ threadMax = max(threadMax, max(value.x, value.y));
1765
+ }
1766
+ buf[tid] = threadMax;
1767
+ workgroupBarrier();
1768
+
1769
+ for (var currSize = blockSize >> 1; currSize > 0; currSize = currSize >> 1) {
1770
+ if (tid < currSize) {
1771
+ buf[tid] = max(buf[tid], buf[tid + currSize]);
1772
+ }
1773
+ workgroupBarrier();
1774
+ }
1775
+
1776
+ let rowMaxShared: f32 = buf[0];
1777
+ workgroupBarrier();
1778
+
1779
+ var threadSum = 0.0f;
1780
+ for (var col = tid; col < cols; col += blockSize) {
1781
+ let value = unpack2x16float(u32(logits[rowIdx + col]));
1782
+ let subExp = exp(value.x - rowMaxShared);
1783
+ threadSum += subExp;
1784
+ let subExpY = exp(value.y - rowMaxShared);
1785
+ threadSum += subExpY;
1786
+ }
1787
+ buf[tid] = threadSum;
1788
+ workgroupBarrier();
1789
+
1790
+ for (var currSize = blockSize >> 1; currSize > 0; currSize = currSize >> 1) {
1791
+ if (tid < currSize) {
1792
+ buf[tid] = buf[tid] + buf[tid + currSize];
1793
+ }
1794
+ workgroupBarrier();
1795
+ }
1796
+
1797
+ let rowSumShared: f32 = buf[0];
1798
+
1799
+ for (var col = tid; col < cols; col += blockSize) {
1800
+ let value = unpack2x16float(u32(logits[rowIdx + col]));
1801
+ let value1: f32 = exp(value.x - rowMaxShared) / rowSumShared;
1802
+ let value2: f32 = exp(value.y - rowMaxShared) / rowSumShared;
1803
+ result[rowIdx + col] = i32(pack2x16float(vec2<f32>(value1, value2)));
1804
+ }
1805
+ }
1806
+ `;
1807
+ }
1808
+ }, ze = class {
1809
+ variableNames = ["logits"];
1810
+ outputShape;
1811
+ shaderKey;
1812
+ dispatchLayout;
1813
+ dispatch;
1814
+ workgroupSize;
1815
+ minSubgroupSize;
1816
+ maxSubgroupSize;
1817
+ subgroups = !0;
1818
+ subgroupBuiltins = !1;
1819
+ constructor(e, t, n) {
1820
+ this.minSubgroupSize = t, this.maxSubgroupSize = n, this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = [
1821
+ this.outputShape[0],
1822
+ 1,
1823
+ 1
1824
+ ], this.workgroupSize = [
1825
+ Math.min(64, n),
1826
+ 1,
1827
+ 1
1828
+ ], t !== n && (this.subgroupBuiltins = !0, this.workgroupSize = [
1829
+ 64,
1830
+ 1,
1831
+ 1
1832
+ ]), this.shaderKey = "softmax16subgroup";
1833
+ }
1834
+ getUserCode() {
1835
+ let e = this.maxSubgroupSize !== this.minSubgroupSize;
1836
+ return `
1837
+ ${e ? `var<workgroup> bestValues : array<f32, ${this.workgroupSize[0]}>;` : ""}
1838
+ const blockSize = ${this.workgroupSize[0]};
1839
+ ${M("index")} {
1840
+ let row = index / blockSize;
1841
+ let tid = i32(localId.x);
1842
+ let cols = uniforms.outShape[1];
1843
+ let rowIdx = row * cols;
1844
+
1845
+ var threadMax = -3.402823e+38f;
1846
+ for (var col = tid; col < cols; col += blockSize) {
1847
+ let value = unpack2x16float(u32(logits[rowIdx + col]));
1848
+ threadMax = max(threadMax, max(value.x, value.y));
1849
+ }
1850
+
1851
+ threadMax = subgroupMax(threadMax);
1852
+ ${e ? "\n let lane = localId.x % subgroupSize;\n if (lane == 0) {\n bestValues[localId.x / subgroupSize] = threadMax;\n }\n workgroupBarrier();\n let numSubgroups = blockSize / subgroupSize;\n threadMax = select(-3.402823e+38f, bestValues[lane], lane < numSubgroups);\n threadMax = subgroupMax(threadMax);\n workgroupBarrier(); \n " : ""}
1853
+
1854
+ var threadSum = 0.0f;
1855
+ for (var col = tid; col < cols; col += blockSize) {
1856
+ let value = unpack2x16float(u32(logits[rowIdx + col]));
1857
+ let subExp = exp(value - threadMax);
1858
+ threadSum += subExp.x + subExp.y;
1859
+ }
1860
+
1861
+ threadSum = subgroupAdd(threadSum);
1862
+ ${e ? "\n if (lane == 0) {\n bestValues[localId.x / subgroupSize] = threadSum;\n }\n workgroupBarrier();\n threadSum = select(0.0f, bestValues[lane], lane < numSubgroups);\n threadSum = subgroupAdd(threadSum); \n " : ""}
1863
+
1864
+ for (var col = tid; col < cols; col += ${e ? "i32(subgroupSize)" : "blockSize"}) {
1865
+ let value = unpack2x16float(u32(logits[rowIdx + col]));
1866
+ let valuePair: vec2<f32> = exp(value - threadMax) / threadSum;
1867
+ result[rowIdx + col] = i32(pack2x16float(valuePair));
1868
+ }
1869
+ }
1870
+ `;
1871
+ }
1872
+ };
1873
+ // lib/ops/webgpu/softmax16.ts
1874
+ function Be(e) {
1875
+ let { inputs: t, backend: n, attrs: r } = e, { logits: i } = t, { dim: a } = r, s = n.subgroupMinSize, c = n.subgroupMaxSize, l = J(n).subgroupsSupported, d = b(i, [u(i.shape) / i.shape[a], i.shape[a]]), f = l ? new ze(d.shape, s, c) : new Re(d.shape), p = n.runWebGPUProgram(f, [d], "packedF16");
1876
+ d.dispose();
1877
+ let m = o().makeTensorFromTensorInfo(p), h = w(m, i.shape);
1878
+ return m.dispose(), h;
1879
+ }
1880
+ l({
1881
+ kernelName: "Softmax16",
1882
+ backendName: "webgpu",
1883
+ kernelFunc: Be
1884
+ });
1885
+ // lib/ops/webgpu/matMul16_program.ts
1886
+ var Ve = class {
1887
+ variableNames = ["A", "B"];
1888
+ outputShape;
1889
+ shaderKey = "MatMul16TB";
1890
+ dispatchLayout;
1891
+ dispatch;
1892
+ workgroupSize = [
1893
+ 8,
1894
+ 8,
1895
+ 1
1896
+ ];
1897
+ dimInner;
1898
+ transposeA = !1;
1899
+ transposeB = !0;
1900
+ broadcastBatch = !0;
1901
+ tileInner = 32;
1902
+ uniforms;
1903
+ scale = !1;
1904
+ scaleA = !1;
1905
+ scaleB = !1;
1906
+ activation;
1907
+ causalMask = !1;
1908
+ hasMask = !1;
1909
+ outputComponent;
1910
+ variableComponents;
1911
+ outputIndexSnippet;
1912
+ outputStrideSnippet;
1913
+ constructor(e, t, n, r, i, a = !1, o = !1, s = !1) {
1914
+ if (this.hasMask = s, this.transposeA = a, this.transposeB = o, this.variableComponents = [2, 2], this.outputComponent = 2, this.shaderKey = `MatMul16TB_${t}_${n}_${r}_${i}_${a ? "TA" : ""}${o ? "TB" : ""}${s ? "HM" : ""}`, a) {
1915
+ if (this.outputShape = [
1916
+ e,
1917
+ r,
1918
+ i / 2
1919
+ ], this.dimInner = t, t !== n) throw Error("Inner dimensions of A and B must match for MatMul16 transposeA");
1920
+ } else if (o) {
1921
+ if (this.outputShape = [
1922
+ e,
1923
+ t,
1924
+ n / 2
1925
+ ], this.dimInner = i, i !== r) throw Error("Inner dimensions of A and B must match for MatMul16 transposeB");
1926
+ } else if (this.outputShape = [
1927
+ e,
1928
+ t,
1929
+ i / 2
1930
+ ], this.dimInner = r, r !== n) throw Error("Inner dimensions of A and B must match for MatMul16");
1931
+ if (this.dimInner % this.tileInner !== 0) throw Error(`Inner dimension ${this.dimInner} must be multiple of ${this.tileInner}`);
1932
+ if (this.dispatchLayout = {
1933
+ x: [2],
1934
+ y: [1],
1935
+ z: [0]
1936
+ }, this.dispatch = [
1937
+ Math.ceil(this.outputShape[2] / (this.workgroupSize[0] * 2)),
1938
+ Math.ceil(this.outputShape[1] / (this.workgroupSize[1] * 4)),
1939
+ this.outputShape[0]
1940
+ ], i % 32 != 0 || r % 32 != 0) throw Error("Head size must be even for MatMul16 transposeB");
1941
+ if (t % 32 != 0 || n % 32 != 0) throw Error("Sequence length must be multiple of 32 for MatMul16 transposeB");
1942
+ this.outputIndexSnippet = "var idx0 = getOutputIndexFromCoords(vec3<i32>(batch, gRow, gColPacked));", this.outputStrideSnippet = "idx0 = idx0 + uniforms.outShapeStrides[1]; // Next row", this.hasMask && (this.variableComponents.push(1), this.variableNames.push("mask"));
1943
+ }
1944
+ addUniform(e) {
1945
+ this.uniforms ? this.uniforms += `, ${e}` : this.uniforms = e;
1946
+ }
1947
+ setOutputShape(e, t) {
1948
+ let n = u(e), r = u(this.outputShape);
1949
+ if (n !== r) throw Error(`New shape size ${n} must match current size ${r}`);
1950
+ function i(e, t) {
1951
+ return [`${e} / ${t}`, `${e} % ${t}`];
1952
+ }
1953
+ let a = this.outputShape, o = [];
1954
+ if (e.length === a.length + 1) {
1955
+ if (e[0] * e[1] === a[0]) o = [
1956
+ ...i("batch", e[1]),
1957
+ "gRow",
1958
+ "gColPacked"
1959
+ ], this.shaderKey += `_batchSplit_${e[1]}`;
1960
+ else if (e[e.length - 2] * e[e.length - 1] === a[a.length - 1]) o = [
1961
+ "batch",
1962
+ "gRow",
1963
+ ...i("gColPacked", e[e.length - 1])
1964
+ ], this.shaderKey += `_colSplit_${e[e.length - 1]}`;
1965
+ else throw Error("Unsupported output shape split");
1966
+ } else if (e.length === a.length) o = [
1967
+ "batch",
1968
+ "gRow",
1969
+ "gColPacked"
1970
+ ];
1971
+ else if (e.length === 2 && a[0] === 1) o = ["gRow", "gColPacked"], this.shaderKey += "_batchRemoved";
1972
+ else throw Error(`Unsupported output shape rank change: ${a.length} -> ${e.length}}`);
1973
+ let s;
1974
+ if (t) {
1975
+ if (t.length !== e.length) throw Error("Permutation length must match output rank");
1976
+ s = t.map((e) => o[e]), this.shaderKey += `_perm_${t.join("")}`;
1977
+ } else s = o;
1978
+ let c = s.findIndex((e) => e === "gRow"), l = `vec${e.length}<i32>(${s.join(", ")})`;
1979
+ this.outputIndexSnippet = `var idx0: i32 = getOutputIndexFromCoords(${l});`, this.outputStrideSnippet = `idx0 = idx0 + uniforms.outShapeStrides${c === 0 ? "" : `[${c}]`}; `, this.outputShape = t ? t.map((t) => e[t]) : e;
1980
+ }
1981
+ useScale() {
1982
+ this.addUniform("scale: f32"), this.scale = !0, this.shaderKey += "_scaled";
1983
+ }
1984
+ useScaleA() {
1985
+ this.addUniform("scaleA: f32"), this.scaleA = !0, this.shaderKey += "_scaledA";
1986
+ }
1987
+ useScaleB() {
1988
+ this.addUniform("scaleB: f32"), this.scaleB = !0, this.shaderKey += "_scaledB";
1989
+ }
1990
+ useActivation(e) {
1991
+ this.activation = e, this.shaderKey += `_${e}`;
1992
+ }
1993
+ useCausalMask() {
1994
+ this.causalMask = !0, this.addUniform("pastLen: i32, causalPeriod: i32"), this.shaderKey += "_causalMask";
1995
+ }
1996
+ activationSnippet() {
1997
+ return this.activation === "gelu" ? "\n // TODO: revisit after https://github.com/gpuweb/gpuweb/issues/4458 is resolved\n fn tanhComplete(x: vec4<f32>) -> vec4<f32> {\n return vec4<f32>(\n select(tanh(x.x), sign(x.x), abs(x.x) > 15.0f),\n select(tanh(x.y), sign(x.y), abs(x.y) > 15.0f),\n select(tanh(x.z), sign(x.z), abs(x.z) > 15.0f),\n select(tanh(x.w), sign(x.w), abs(x.w) > 15.0f),\n );\n }\n fn activation(x : vec4<f32>) -> vec4<f32> {\n let x3 = x * x * x;\n var inner = fma(vec4<f32>(0.044715f), x3, x);\n inner = 0.7978845608028654f * inner;\n inner = tanhComplete(inner);\n inner = 0.5f * (1.0f + inner);\n return x * inner;\n }\n " : this.activation === "relu2" ? "\n fn activation(x : vec4<f32>) -> vec4<f32> {\n let y = max(x, vec4<f32>(0.0));\n return y * y;\n }\n " : this.activation === "relu" ? "\n fn activation(x : vec4<f32>) -> vec4<f32> {\n return max(x, vec4<f32>(0.0));\n }\n " : this.activation === "silu" ? "\n fn activation(x : vec4<f32>) -> vec4<f32> {\n return x * (1.0 / (1.0 + exp(-x)));\n }\n " : "";
1998
+ }
1999
+ readASnippet() {
2000
+ let e = `
2001
+ var col = i32(localId.x);
2002
+ var row = i32(localId.y) * 4;
2003
+ var packedA: vec2<i32> = A[offsetA + row * strideA + col];
2004
+ var Arow1 = vec4<f32>(
2005
+ unpack2x16float(u32(packedA.x)),
2006
+ unpack2x16float(u32(packedA.y))
2007
+ );
2008
+ packedA = A[offsetA + (row + 1) * strideA + col];
2009
+ var Arow2 = vec4<f32>(
2010
+ unpack2x16float(u32(packedA.x)),
2011
+ unpack2x16float(u32(packedA.y))
2012
+ );
2013
+ packedA = A[offsetA + (row + 2) * strideA + col];
2014
+ var Arow3 = vec4<f32>(
2015
+ unpack2x16float(u32(packedA.x)),
2016
+ unpack2x16float(u32(packedA.y))
2017
+ );
2018
+ packedA = A[offsetA + (row + 3) * strideA + col];
2019
+ var Arow4 = vec4<f32>(
2020
+ unpack2x16float(u32(packedA.x)),
2021
+ unpack2x16float(u32(packedA.y))
2022
+ );
2023
+
2024
+ ${this.scaleA ? "Arow1 = Arow1 * uniforms.scaleA;" : ""}
2025
+ ${this.scaleA ? "Arow2 = Arow2 * uniforms.scaleA;" : ""}
2026
+ ${this.scaleA ? "Arow3 = Arow3 * uniforms.scaleA;" : ""}
2027
+ ${this.scaleA ? "Arow4 = Arow4 * uniforms.scaleA;" : ""}
2028
+ `;
2029
+ return this.transposeA ? `{
2030
+ ${e}
2031
+ mm_Asub[row][col] = Arow1;
2032
+ mm_Asub[row + 1][col] = Arow2;
2033
+ mm_Asub[row + 2][col] = Arow3;
2034
+ mm_Asub[row + 3][col] = Arow4;
2035
+ }` : `{
2036
+ ${e}
2037
+
2038
+ col = i32(localId.x) * 4;
2039
+ row = i32(localId.y);
2040
+
2041
+ mm_Asub[col][row] = vec4<f32>(Arow1.x, Arow2.x, Arow3.x, Arow4.x);
2042
+ mm_Asub[col + 1][row] = vec4<f32>(Arow1.y, Arow2.y, Arow3.y, Arow4.y);
2043
+ mm_Asub[col + 2][row] = vec4<f32>(Arow1.z, Arow2.z, Arow3.z, Arow4.z);
2044
+ mm_Asub[col + 3][row] = vec4<f32>(Arow1.w, Arow2.w, Arow3.w, Arow4.w);
2045
+ }`;
2046
+ }
2047
+ readBSnippet() {
2048
+ let e = `
2049
+ var col = i32(localId.x);
2050
+ var row = i32(localId.y) * 4;
2051
+ var packedB: vec2<i32> = B[offsetB + row * strideB + col];
2052
+ var Brow1 = vec4<f32>(
2053
+ unpack2x16float(u32(packedB.x)),
2054
+ unpack2x16float(u32(packedB.y))
2055
+ );
2056
+ packedB = B[offsetB + (row + 1) * strideB + col];
2057
+ var Brow2 = vec4<f32>(
2058
+ unpack2x16float(u32(packedB.x)),
2059
+ unpack2x16float(u32(packedB.y))
2060
+ );
2061
+ packedB = B[offsetB + (row + 2) * strideB + col];
2062
+ var Brow3 = vec4<f32>(
2063
+ unpack2x16float(u32(packedB.x)),
2064
+ unpack2x16float(u32(packedB.y))
2065
+ );
2066
+ packedB = B[offsetB + (row + 3) * strideB + col];
2067
+ var Brow4 = vec4<f32>(
2068
+ unpack2x16float(u32(packedB.x)),
2069
+ unpack2x16float(u32(packedB.y))
2070
+ );
2071
+
2072
+ ${this.scaleB ? "Brow1 = Brow1 * uniforms.scaleB;" : ""}
2073
+ ${this.scaleB ? "Brow2 = Brow2 * uniforms.scaleB;" : ""}
2074
+ ${this.scaleB ? "Brow3 = Brow3 * uniforms.scaleB;" : ""}
2075
+ ${this.scaleB ? "Brow4 = Brow4 * uniforms.scaleB;" : ""}
2076
+ `;
2077
+ return this.transposeB ? `{
2078
+ ${e}
2079
+
2080
+ col = i32(localId.x) * 4;
2081
+ row = i32(localId.y);
2082
+
2083
+ mm_Bsub[col][row] = vec4<f32>(Brow1.x, Brow2.x, Brow3.x, Brow4.x);
2084
+ mm_Bsub[col + 1][row] = vec4<f32>(Brow1.y, Brow2.y, Brow3.y, Brow4.y);
2085
+ mm_Bsub[col + 2][row] = vec4<f32>(Brow1.z, Brow2.z, Brow3.z, Brow4.z);
2086
+ mm_Bsub[col + 3][row] = vec4<f32>(Brow1.w, Brow2.w, Brow3.w, Brow4.w);
2087
+ }` : `{
2088
+ ${e}
2089
+ mm_Bsub[row][col] = Brow1;
2090
+ mm_Bsub[row + 1][col] = Brow2;
2091
+ mm_Bsub[row + 2][col] = Brow3;
2092
+ mm_Bsub[row + 3][col] = Brow4;
2093
+ }`;
2094
+ }
2095
+ baseIndexSnippets() {
2096
+ let e;
2097
+ e = this.transposeB ? "let baseB = getIndexFromCoords3D(vec3<i32>(batchB, globalColStart, 0), vec3<i32>(uniforms.bShape.x, uniforms.bShape.y, strideB));" : "let baseB = getIndexFromCoords3D(vec3<i32>(batchB, 0, globalColStart / 4), vec3<i32>(uniforms.bShape.x, uniforms.bShape.y, strideB));";
2098
+ let t;
2099
+ return t = this.transposeA ? "let baseA = getIndexFromCoords3D(vec3<i32>(batchA, 0, globalRowStart / 4), vec3<i32>(uniforms.aShape.x, uniforms.aShape.y, strideA));" : "let baseA = getIndexFromCoords3D(vec3<i32>(batchA, globalRowStart, 0), vec3<i32>(uniforms.aShape.x, uniforms.aShape.y, strideA));", `
2100
+
2101
+ let strideA = uniforms.aShape.z / 2;
2102
+ let strideB = uniforms.bShape.z / 2;
2103
+
2104
+ ${t}
2105
+ ${e}
2106
+ `;
2107
+ }
2108
+ offsetSnippets() {
2109
+ let e;
2110
+ e = this.transposeA ? "let offsetA = baseA + kStart * strideA;" : "let offsetA = baseA + kStart / 4;";
2111
+ let t;
2112
+ return t = this.transposeB ? "let offsetB = baseB + kStart / 4;" : "let offsetB = baseB + kStart * strideB;", `
2113
+ ${e}
2114
+ ${t}
2115
+ `;
2116
+ }
2117
+ getUserCode() {
2118
+ let e = this.transposeA, t = this.tileInner, n = this.workgroupSize[1] * 4, r = this.workgroupSize[0] * 4, i = e ? n : t, a = e ? t : n, o = this.dimInner, s = Math.ceil(o / t);
2119
+ return `
2120
+ var<workgroup> mm_Asub : array<array<vec4<f32>, ${i / 4 + +!this.transposeA}>, ${a}>;
2121
+ var<workgroup> mm_Bsub : array<array<vec4<f32>, ${r / 4 + +!!this.transposeB}>, ${t}>;
2122
+
2123
+ ${this.activation ? this.activationSnippet() : ""}
2124
+
2125
+ ${M()} {
2126
+ let batch = i32(globalId.z);
2127
+ let batchA = ${this.broadcastBatch ? "batch % uniforms.aShape[0]" : "batch"};
2128
+ let batchB = ${this.broadcastBatch ? "batch % uniforms.bShape[0]" : "batch"};
2129
+ var kStart = 0;
2130
+ let localRow = i32(localId.y);
2131
+ let localCol = i32(localId.x);
2132
+ let globalRowStart = i32(workgroupId.y) * ${n};
2133
+ let globalColStart = i32(workgroupId.x) * ${r};
2134
+
2135
+ // 4 rows x 4 cols accumulator
2136
+ // acc[i] holds row i (4 cols)
2137
+ var acc = array<vec4<f32>, 4>(
2138
+ vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0)
2139
+ );
2140
+
2141
+ ${this.baseIndexSnippets()}
2142
+
2143
+ for (var t = 0; t < ${s}; t++) {
2144
+ ${this.offsetSnippets()}
2145
+
2146
+ ${this.readASnippet()}
2147
+ ${this.readBSnippet()}
2148
+
2149
+ kStart = kStart + ${t};
2150
+ workgroupBarrier();
2151
+
2152
+ for (var k = 0; k < ${t}; k++) {
2153
+ // Load 4 columns of B as a vec4
2154
+ let bVec = mm_Bsub[k][localCol];
2155
+ let aVec = mm_Asub[k][localRow];
2156
+
2157
+ // Compute 4 rows
2158
+ for (var r = 0; r < 4; r = r + 1) {
2159
+ acc[r] = fma(vec4<f32>(aVec[r]), bVec, acc[r]);
2160
+ }
2161
+ }
2162
+ workgroupBarrier();
2163
+ }
2164
+
2165
+ // Write out 4 rows x 2 packed cols (4 unpacked cols)
2166
+ let gRow = globalRowStart + localRow * 4;
2167
+ let gColPacked = i32(workgroupId.x) * ${this.workgroupSize[0] * 2} + localCol * 2;
2168
+
2169
+ ${this.outputIndexSnippet}
2170
+ for (var i = 0; i < 4; i = i + 1) {
2171
+ ${this.causalMask ? `
2172
+ // Causal Masking: mask if col > row + pastLen
2173
+ // Rows wrap every causalPeriod so folded GQA query heads share the same mask
2174
+ let r = (gRow + i) % uniforms.causalPeriod;
2175
+ let cBase = gColPacked * 2;
2176
+ let cVec = vec4<i32>(cBase, cBase + 1, cBase + 2, cBase + 3);
2177
+ let positionMask = cVec > vec4<i32>(r + uniforms.pastLen);
2178
+ ${this.hasMask ? "\n let additionalMask = vec4<bool>(\n positionMask.x || mask[cVec.x] == 1,\n positionMask.y || mask[cVec.y] == 1,\n positionMask.z || mask[cVec.z] == 1,\n positionMask.w || mask[cVec.w] == 1\n );\n acc[i] = select(acc[i], vec4<f32>(-uniforms.INFINITY), additionalMask);\n " : "\n acc[i] = select(acc[i], vec4<f32>(-uniforms.INFINITY), positionMask);\n "}
2179
+ ` : ""}
2180
+
2181
+ ${this.activation ? "acc[i] = activation(acc[i]);" : ""}
2182
+ ${this.scale ? "acc[i] = acc[i] * uniforms.scale;" : ""}
2183
+ result[idx0 / 2] = vec2<i32>(
2184
+ i32(pack2x16float(acc[i].xy)),
2185
+ i32(pack2x16float(acc[i].zw))
2186
+ );
2187
+
2188
+ ${this.outputStrideSnippet}
2189
+ }
2190
+ }
2191
+ `;
2192
+ }
2193
+ };
2194
+ // lib/ops/webgpu/matMul16.ts
2195
+ function He(e) {
2196
+ let { A: t, B: a, mask: o } = e.inputs, { transposeA: s, transposeB: l, scale: d, activation: f, scaleA: p, scaleB: h, forceOutputShape: g, perm: _, causalMask: v, pastLen: y, causalPeriod: x } = e.attrs, ne = e.backend, T = !E(t), D = !E(a);
2197
+ if (T && D) {
2198
+ let e = p === void 0 ? t : r(t, i(p)), o = h === void 0 ? a : r(a, i(h));
2199
+ if (v) throw Error("Causal mask is not supported for unpacked MatMul16.");
2200
+ let c;
2201
+ if (f === "gelu") c = ee(e, o);
2202
+ else if (f === "relu2") {
2203
+ let t = C(e, o, s, l), r = m(t);
2204
+ t.dispose(), c = n(r), r.dispose();
2205
+ } else if (f === "relu") {
2206
+ if (c = m(C(e, o, s, l)), d !== void 0) {
2207
+ let e = r(c, i(d));
2208
+ c.dispose(), c = e;
2209
+ }
2210
+ } else if (f === "silu") {
2211
+ if (c = te(C(e, o, s, l)), d !== void 0) {
2212
+ let e = r(c, i(d));
2213
+ c.dispose(), c = e;
2214
+ }
2215
+ } else c = d === void 0 ? C(e, o, s, l) : re(e, o, i(d), s, l);
2216
+ if (_) {
2217
+ if (g) {
2218
+ let e = b(c, g);
2219
+ c.dispose();
2220
+ let t = S(e, _);
2221
+ return e.dispose(), t;
2222
+ }
2223
+ {
2224
+ let e = S(c, _);
2225
+ return c.dispose(), e;
2226
+ }
2227
+ }
2228
+ if (g) {
2229
+ let e = b(c, g);
2230
+ return c.dispose(), e;
2231
+ }
2232
+ return c;
2233
+ }
2234
+ if (T && !D) throw Error("When using mixed precision, A must be packed if B is packed.");
2235
+ if (!T && D) throw Error("When using mixed precision, B must be packed if A is packed.");
2236
+ let O = t.shape.length, k = a.shape.length, A = t.shape.slice(0, -2), j = a.shape.slice(0, -2), M = u(A), N = u(j), P = c(t.shape.slice(0, -2), a.shape.slice(0, -2)), F = Math.max(M, N), I = t.shape[O - 2], L = a.shape[k - 2], R = t.shape[O - 1] * 2, z = a.shape[k - 1] * 2, B = w(t, [
2237
+ M,
2238
+ t.shape[O - 2],
2239
+ t.shape[O - 1]
2240
+ ]), V = w(a, [
2241
+ N,
2242
+ a.shape[k - 2],
2243
+ a.shape[k - 1]
2244
+ ]), H = new Ve(F, I, L, R, z, s, l, !!o), U = [];
2245
+ d !== void 0 && (H.useScale(), U.push({
2246
+ type: "float32",
2247
+ data: [d]
2248
+ })), p !== void 0 && (H.useScaleA(), U.push({
2249
+ type: "float32",
2250
+ data: [p]
2251
+ })), h !== void 0 && (H.useScaleB(), U.push({
2252
+ type: "float32",
2253
+ data: [h]
2254
+ })), f !== void 0 && H.useActivation(f), v && (H.useCausalMask(), U.push({
2255
+ type: "int32",
2256
+ data: [y || 0]
2257
+ }), U.push({
2258
+ type: "int32",
2259
+ data: [x || H.outputShape[1]]
2260
+ }));
2261
+ let W = H.outputShape.length;
2262
+ g && (e.attrs.originalShape = H.outputShape);
2263
+ let ie = g ?? P.concat([H.outputShape[W - 2], H.outputShape[W - 1]]);
2264
+ H.setOutputShape(ie, _);
2265
+ let G = ne.runWebGPUProgram(H, o ? [
2266
+ B,
2267
+ V,
2268
+ o
2269
+ ] : [B, V], "packedF16", U.length > 0 ? U : void 0);
2270
+ return B.dispose(), V.dispose(), G;
2271
+ }
2272
+ l({
2273
+ kernelName: "MatMul16",
2274
+ backendName: "webgpu",
2275
+ kernelFunc: He
2276
+ });
2277
+ // lib/ops/webgpu/transpose16_shared_program.ts
2278
+ var Ue = class {
2279
+ variableNames = ["A"];
2280
+ outputShape;
2281
+ shaderKey;
2282
+ dispatchLayout;
2283
+ dispatch;
2284
+ workgroupSize = [
2285
+ 8,
2286
+ 8,
2287
+ 1
2288
+ ];
2289
+ constructor(e, t) {
2290
+ let n = e.length, r = Array(n), i = e.slice();
2291
+ i[i.length - 1] *= 2;
2292
+ for (let e = 0; e < r.length; e++) r[e] = i[t[e]];
2293
+ r[r.length - 1] /= 2, this.outputShape = r, this.dispatchLayout = n === 2 ? {
2294
+ x: [0],
2295
+ y: [1]
2296
+ } : {
2297
+ x: [1],
2298
+ y: [2],
2299
+ z: [0]
2300
+ }, this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
2301
+ 2,
2302
+ 1,
2303
+ 1
2304
+ ]), this.shaderKey = `transposeShared16_${n}`;
2305
+ }
2306
+ getUserCode() {
2307
+ let e = this.outputShape.length;
2308
+ t(this.workgroupSize[0] === this.workgroupSize[1], () => `Must be a square tile, current tile shape is ${this.workgroupSize[0]} x ${this.workgroupSize[1]}`);
2309
+ let n = this.workgroupSize[0] * 2;
2310
+ return `
2311
+ var<workgroup> tile : array<array<f32, ${n + 1}>, ${n}>;
2312
+ ${M()} {
2313
+ var x = i32(workgroupId.x) * ${n / 2} + i32(localId.x);
2314
+ var y = i32(workgroupId.y) * ${n} + i32(localId.y);
2315
+ let batch = ${e === 3 ? "i32(workgroupId.z)" : "0"};
2316
+ let batchOffsetA = ${e === 3 ? "batch * uniforms.aShapeStrides[0]" : "0"};
2317
+ let batchOffsetOut = ${e === 3 ? "batch * uniforms.outShapeStrides[0]" : "0"};
2318
+
2319
+ let inputWidth = uniforms.outShape[${e === 3 ? "1" : "0"}] / 2; // Output height
2320
+ let inputHeight = uniforms.outShape[${e === 3 ? "2" : "1"}] * 2; // Output width
2321
+ if (x < inputWidth && y < inputHeight) {
2322
+ let unpackedA = unpack2x16float(u32(A[batchOffsetA + y * inputWidth + x]));
2323
+ tile[localId.y][localId.x * 2] = unpackedA.x;
2324
+ tile[localId.y][localId.x * 2 + 1] = unpackedA.y;
2325
+ }
2326
+ // Second load to cover the tile
2327
+ y = y + ${this.workgroupSize[0]};
2328
+ if (x < inputWidth && y < inputHeight) {
2329
+ let unpackedA = unpack2x16float(u32(A[batchOffsetA + y * inputWidth + x]));
2330
+ tile[localId.y + ${this.workgroupSize[0]}][localId.x * 2] = unpackedA.x;
2331
+ tile[localId.y + ${this.workgroupSize[0]}][localId.x * 2 + 1] = unpackedA.y;
2332
+ }
2333
+ workgroupBarrier();
2334
+
2335
+ let outputWidth = uniforms.outShape[${e === 3 ? "2" : "1"}]; // Output width
2336
+ let outputHeight = uniforms.outShape[${e === 3 ? "1" : "0"}] * 2; // Output height
2337
+ x = i32(workgroupId.y) * ${n / 2} + i32(localId.x);
2338
+ y = i32(workgroupId.x) * ${n} + i32(localId.y);
2339
+ if (x < outputWidth && y < outputHeight) {
2340
+ result[batchOffsetOut + y * outputWidth + x] = i32(pack2x16float(vec2<f32>(tile[localId.x * 2][localId.y], tile[localId.x * 2 + 1][localId.y])));
2341
+ }
2342
+ // Second store to cover the tile
2343
+ y = y + ${this.workgroupSize[0]};
2344
+ if (x < outputWidth && y < outputHeight) {
2345
+ result[batchOffsetOut + y * outputWidth + x] = i32(pack2x16float(vec2<f32>(tile[localId.x * 2][localId.y + ${this.workgroupSize[0]}], tile[localId.x * 2 + 1][localId.y + ${this.workgroupSize[0]}])));
2346
+ }
2347
+ }
2348
+ `;
2349
+ }
2350
+ };
2351
+ // lib/ops/webgpu/transpose16_program.ts
2352
+ function We(e) {
2353
+ let t = e.length;
2354
+ if (t > 6) throw Error(`Transpose for rank ${t} is not yet supported`);
2355
+ let n = Array(t);
2356
+ for (let t = 0; t < e.length; t++) n[e[t]] = `coords.${P(t)}`;
2357
+ return n.join();
2358
+ }
2359
+ var Ge = class {
2360
+ variableNames = ["A"];
2361
+ shaderKey;
2362
+ outputShape;
2363
+ dispatchLayout;
2364
+ dispatch;
2365
+ workPerThread = 1;
2366
+ workgroupSize = [
2367
+ 64,
2368
+ 1,
2369
+ 1
2370
+ ];
2371
+ newDim;
2372
+ size = !0;
2373
+ constructor(e, t) {
2374
+ let n = Array(e.length);
2375
+ for (let r = 0; r < n.length; r++) n[r] = e[t[r]];
2376
+ this.outputShape = n, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
2377
+ this.workPerThread,
2378
+ 1,
2379
+ 1
2380
+ ]), this.newDim = t, this.shaderKey = `transpose16_${t}`;
2381
+ }
2382
+ getUserCode() {
2383
+ let e = j(this.outputShape.length), t = We(this.newDim);
2384
+ return `
2385
+ ${M("index")} {
2386
+ for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
2387
+ let flatIndex = index * ${this.workPerThread} + i;
2388
+ if(flatIndex < uniforms.size) {
2389
+ let coords = getCoordsFromIndex(flatIndex);
2390
+ result[flatIndex] = A[getIndexFromCoords${this.outputShape.length}D(
2391
+ ${e}(${t}), uniforms.aShape)];
2392
+ }
2393
+ }
2394
+ }
2395
+ `;
2396
+ }
2397
+ };
2398
+ // lib/ops/webgpu/transpose16.ts
2399
+ function Ke(e) {
2400
+ let { inputs: t, attrs: n } = e, { x: r } = t, { perm: i } = n, a = e.backend, s = E(r);
2401
+ if (s && i[i.length - 1] !== r.shape.length - 1) {
2402
+ let e = r.shape.length, t = e === 4 ? i.map((e) => e - 1).filter((e) => e >= 0) : i, n = e === 4 ? w(r, [
2403
+ r.shape[0] * r.shape[1],
2404
+ r.shape[2],
2405
+ r.shape[3]
2406
+ ]) : r, s = new Ue(n.shape, t), c = a.runWebGPUProgram(s, [n], "packedF16");
2407
+ if (e === 4) {
2408
+ n.dispose();
2409
+ let e = o().makeTensorFromTensorInfo(c), t = w(e, [
2410
+ r.shape[0],
2411
+ r.shape[1],
2412
+ c.shape[1],
2413
+ c.shape[2]
2414
+ ]);
2415
+ return e.dispose(), t;
2416
+ }
2417
+ return c;
2418
+ }
2419
+ if (s) {
2420
+ let e = new Ge(r.shape, i);
2421
+ return a.runWebGPUProgram(e, [r], "packedF16");
2422
+ }
2423
+ return S(r, i);
2424
+ }
2425
+ l({
2426
+ kernelName: "Transpose16",
2427
+ backendName: "webgpu",
2428
+ kernelFunc: Ke
2429
+ });
2430
+ // lib/ops/webgpu/sum16.ts
2431
+ var qe = class extends K {
2432
+ shaderKey = "sum16";
2433
+ constructor(e, t, n) {
2434
+ super(e, t, {
2435
+ reductionOp: "sum",
2436
+ elementwise: !1
2437
+ }, n), n && (this.shaderKey += "_packed");
2438
+ }
2439
+ };
2440
+ function Je(e) {
2441
+ let { x: t } = e.inputs, { axis: n, keepDims: r } = e.attrs, i = e.backend, a = [], o = J(i), c = E(t);
2442
+ if (!c) return h(t, n, r);
2443
+ let l = s(n ?? -1, t.shape), u = g(l, t.shape.length), d = t;
2444
+ u != null && (d = ne(t, u), a.push(d));
2445
+ let f = q(new qe(o, G([d], -1), c), [d], i);
2446
+ return a.forEach((e) => e.dispose()), f;
2447
+ }
2448
+ l({
2449
+ kernelName: "Sum16",
2450
+ backendName: "webgpu",
2451
+ kernelFunc: Je
2452
+ });
2453
+ // lib/ops/webgpu/slice16.ts
2454
+ function Ye(e) {
2455
+ switch (e) {
2456
+ case 1: return "1D";
2457
+ case 2: return "2D";
2458
+ case 3: return "3D";
2459
+ case 4: return "4D";
2460
+ }
2461
+ return "";
2462
+ }
2463
+ var Xe = class {
2464
+ variableNames = ["source"];
2465
+ uniforms;
2466
+ outputShape;
2467
+ shaderKey;
2468
+ rank;
2469
+ dispatchLayout;
2470
+ dispatch;
2471
+ workPerThread = 1;
2472
+ workgroupSize = [
2473
+ 64,
2474
+ 1,
2475
+ 1
2476
+ ];
2477
+ start;
2478
+ size = !0;
2479
+ constructor(e, t) {
2480
+ this.outputShape = t, this.rank = t.length, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
2481
+ this.workPerThread,
2482
+ 1,
2483
+ 1
2484
+ ]), this.start = e, this.uniforms = `start : ${j(e.length)}, `, this.shaderKey = "slice";
2485
+ }
2486
+ getUserCode() {
2487
+ let e = j(this.rank), t;
2488
+ return t = this.start.length === 1 ? this.outputShape.map(() => "sourceLoc = uniforms.start + coords;") : this.outputShape.map((e, t) => `sourceLoc.${Ze[t]} = uniforms.start.${P(t)} + coords.${Ze[t]};`), `
2489
+ ${M("index")} {
2490
+ if (index < uniforms.size) {
2491
+ var sourceLoc : ${e};
2492
+ let coords = getCoordsFromIndex(index);
2493
+ ${t.join("\n")}
2494
+ result[index] = source[getIndexFromCoords${Ye(this.rank)}(sourceLoc, uniforms.sourceShape)];
2495
+ }
2496
+ }
2497
+ `;
2498
+ }
2499
+ }, Ze = [
2500
+ "x",
2501
+ "y",
2502
+ "z",
2503
+ "w",
2504
+ "u",
2505
+ "v"
2506
+ ];
2507
+ function Qe(e) {
2508
+ let { inputs: t, backend: n, attrs: r } = e, { x: i } = t, { begin: a, size: o } = r, [s, c] = p(i, a, o);
2509
+ if (v(i, s, c), u(c) === 0) return n.makeTensorInfo(c, i.dtype, []);
2510
+ let l = new Xe(s, c), d = [{
2511
+ type: "int32",
2512
+ data: s
2513
+ }];
2514
+ return n.runWebGPUProgram(l, [i], i.dtype, d);
2515
+ }
2516
+ l({
2517
+ kernelName: "Slice16",
2518
+ backendName: "webgpu",
2519
+ kernelFunc: Qe
2520
+ });
2521
+ // lib/ops/webgpu/utils/binary_op.ts
2522
+ var Q = class {
2523
+ dispatch;
2524
+ dispatchLayout;
2525
+ outputComponent;
2526
+ op;
2527
+ outputShape;
2528
+ shaderKey;
2529
+ size = !0;
2530
+ variableNames = ["A", "B"];
2531
+ workgroupSize;
2532
+ variableComponents;
2533
+ constructor(e, t, n) {
2534
+ this.outputShape = c(t, n), this.dispatchLayout = A(this.outputShape), this.op = e;
2535
+ let r = t.length > 0 && t[t.length - 1] % 4 == 0, i = n.length > 0 && n[n.length - 1] % 4 == 0;
2536
+ if (r && i) this.outputComponent = 4, this.variableComponents = [4, 4];
2537
+ else if (r && (a(n) || n[n.length - 1] === 1) || i && (a(t) || t[t.length - 1] === 1)) throw Error("Cannot broadcast 16-bit float binary ops with mixed vector sizes");
2538
+ else throw Error("16-bit float binary ops require inner dimension to be multiple of 4");
2539
+ this.shaderKey = `binary_${e}_${this.variableComponents}`, this.workgroupSize = [
2540
+ 128,
2541
+ 1,
2542
+ 1
2543
+ ], this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
2544
+ this.outputComponent,
2545
+ 1,
2546
+ 1
2547
+ ]);
2548
+ }
2549
+ getUserCode() {
2550
+ let e = this.outputComponent === 4 ? "vec4<f32>" : "f32";
2551
+ return `
2552
+ ${`
2553
+ fn binaryOperation(a : ${e}, b : ${e}) -> ${e} {
2554
+ ${I(this.op, this.outputComponent === 4)}
2555
+ };
2556
+ `}
2557
+ ${M("index")} {
2558
+ if (index < uniforms.size) {
2559
+ let a = A[index];
2560
+ let b = B[index];
2561
+
2562
+ let v4a1 = vec4<f32>(
2563
+ unpack2x16float(u32(a.x)),
2564
+ unpack2x16float(u32(a.y))
2565
+ );
2566
+ let v4a2 = vec4<f32>(
2567
+ unpack2x16float(u32(a.z)),
2568
+ unpack2x16float(u32(a.w))
2569
+ );
2570
+ let v4b1 = vec4<f32>(
2571
+ unpack2x16float(u32(b.x)),
2572
+ unpack2x16float(u32(b.y))
2573
+ );
2574
+ let v4b2 = vec4<f32>(
2575
+ unpack2x16float(u32(b.z)),
2576
+ unpack2x16float(u32(b.w))
2577
+ );
2578
+
2579
+ let v4res1 = binaryOperation(v4a1, v4b1);
2580
+ let v4res2 = binaryOperation(v4a2, v4b2);
2581
+
2582
+ let res = vec4<i32>(
2583
+ i32(pack2x16float(v4res1.xy)),
2584
+ i32(pack2x16float(v4res1.zw)),
2585
+ i32(pack2x16float(v4res2.xy)),
2586
+ i32(pack2x16float(v4res2.zw))
2587
+ );
2588
+
2589
+ result[index] = res;
2590
+ }
2591
+ }
2592
+ `;
2593
+ }
2594
+ }, $e = class {
2595
+ dispatch;
2596
+ dispatchLayout;
2597
+ outputComponent;
2598
+ op;
2599
+ outputShape;
2600
+ shaderKey;
2601
+ size = !0;
2602
+ variableNames = ["A", "B"];
2603
+ workgroupSize;
2604
+ variableComponents;
2605
+ constructor(e, t) {
2606
+ if (this.outputShape = t, this.dispatchLayout = A(this.outputShape), this.op = e, t.length > 0 && t[t.length - 1] % 4 == 0) this.outputComponent = 4, this.variableComponents = [4, 1];
2607
+ else throw Error("16-bit float binary ops require inner dimension to be multiple of 4");
2608
+ this.shaderKey = `binary_scal_${e}_${this.variableComponents}`, this.workgroupSize = [
2609
+ 128,
2610
+ 1,
2611
+ 1
2612
+ ], this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
2613
+ this.outputComponent,
2614
+ 1,
2615
+ 1
2616
+ ]);
2617
+ }
2618
+ getUserCode() {
2619
+ let e = this.outputComponent === 4 ? "vec4<f32>" : "f32";
2620
+ return `
2621
+ ${`
2622
+ fn binaryOperation(a : ${e}, b : ${e}) -> ${e} {
2623
+ ${I(this.op, this.outputComponent === 4)}
2624
+ };
2625
+ `}
2626
+ ${M("index")} {
2627
+ if (index < uniforms.size) {
2628
+ let a = A[index];
2629
+ let b = B[0];
2630
+
2631
+ let v4a1 = vec4<f32>(
2632
+ unpack2x16float(u32(a.x)),
2633
+ unpack2x16float(u32(a.y))
2634
+ );
2635
+ let v4a2 = vec4<f32>(
2636
+ unpack2x16float(u32(a.z)),
2637
+ unpack2x16float(u32(a.w))
2638
+ );
2639
+
2640
+ let v4res1 = binaryOperation(v4a1, vec4<f32>(b));
2641
+ let v4res2 = binaryOperation(v4a2, vec4<f32>(b));
2642
+
2643
+ let res = vec4<i32>(
2644
+ i32(pack2x16float(v4res1.xy)),
2645
+ i32(pack2x16float(v4res1.zw)),
2646
+ i32(pack2x16float(v4res2.xy)),
2647
+ i32(pack2x16float(v4res2.zw))
2648
+ );
2649
+
2650
+ result[index] = res;
2651
+ }
2652
+ }
2653
+ `;
2654
+ }
2655
+ };
2656
+ // lib/ops/webgpu/add16.ts
2657
+ function et(e) {
2658
+ let { a: t, b: n } = e.inputs, r = e.backend, i = new Q(L.ADD, t.shape, n.shape);
2659
+ return r.runWebGPUProgram(i, [t, n], "packedF16");
2660
+ }
2661
+ l({
2662
+ kernelName: "Add16",
2663
+ backendName: "webgpu",
2664
+ kernelFunc: et
2665
+ });
2666
+ // lib/ops/webgpu/concat16.ts
2667
+ var tt = class {
2668
+ outputShape;
2669
+ shaderKey;
2670
+ dispatchLayout;
2671
+ dispatch;
2672
+ variableNames;
2673
+ uniforms = "";
2674
+ workPerThread = 1;
2675
+ workgroupSize = [
2676
+ 64,
2677
+ 1,
2678
+ 1
2679
+ ];
2680
+ size = !0;
2681
+ offsetLength;
2682
+ constructor(e) {
2683
+ this.outputShape = f(e, 1), this.variableNames = e.map((e, t) => `T${t}`), this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize, [
2684
+ this.workPerThread,
2685
+ 1,
2686
+ 1
2687
+ ]), this.offsetLength = e.length - 1;
2688
+ for (let e = 0; e < this.offsetLength; e++) this.uniforms += `offset${e} : i32,`;
2689
+ this.shaderKey = "concat16";
2690
+ }
2691
+ getUserCode() {
2692
+ let e = [];
2693
+ if (this.offsetLength > 0) {
2694
+ e.push("if (yC < uniforms.offset0){ result[getIndexFromCoords2D(coords, uniforms.outShape)] = T0[getIndexFromCoords2D(vec2<i32>(yR, yC), uniforms.t0Shape)]; }");
2695
+ for (let t = 1; t < this.offsetLength; t++) e.push(`else if (yC < uniforms.offset${[t]}){ result[getIndexFromCoords2D(coords, uniforms.outShape)] = T${t}[getIndexFromCoords2D(vec2<i32>(yR, yC - uniforms.offset${t - 1}), uniforms.t${t}Shape)]; }`);
2696
+ let t = this.offsetLength, n = this.offsetLength - 1;
2697
+ e.push(`else { result[getIndexFromCoords2D(coords, uniforms.outShape)] = T${t}[getIndexFromCoords2D(vec2<i32>(yR, yC - uniforms.offset${n}), uniforms.t${t}Shape)]; }`);
2698
+ } else e.push("result[getIndexFromCoords2D(coords, uniforms.outShape)] = T0[getIndexFromCoords2D(vec2<i32>(yR, yC), uniforms.t0Shape)];");
2699
+ return `
2700
+ ${M("index")} {
2701
+ for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
2702
+ let flatIndex = index * ${this.workPerThread} + i;
2703
+ if(flatIndex < uniforms.size) {
2704
+ let coords = getCoordsFromIndex(flatIndex);
2705
+ let yR = coords.x;
2706
+ let yC = coords.y;
2707
+
2708
+ ${e.join("\n ")}
2709
+ }
2710
+ }
2711
+ }
2712
+ `;
2713
+ }
2714
+ };
2715
+ function $(e, t, n) {
2716
+ let r = n.device.limits.maxStorageBuffersPerShaderStage - 1;
2717
+ if (e.length > r) {
2718
+ let i = [];
2719
+ for (let a = 0; a < e.length; a += r) {
2720
+ let o = e.slice(a, a + r);
2721
+ i.push($(o, t, n));
2722
+ }
2723
+ let a = $(i, t, n);
2724
+ for (let e of i) n.disposeData(e.dataId);
2725
+ return a;
2726
+ }
2727
+ let { tensors2D: i, outShape: a } = nt(e, t, n), o = i.map((e) => e.shape), s = new tt(o), c = [], l = Array(o.length - 1);
2728
+ if (l.length > 0) {
2729
+ l[0] = o[0][1], c.push({
2730
+ type: "int32",
2731
+ data: [l[0]]
2732
+ });
2733
+ for (let e = 1; e < l.length; e++) l[e] = l[e - 1] + o[e][1], c.push({
2734
+ type: "int32",
2735
+ data: [l[e]]
2736
+ });
2737
+ }
2738
+ let u = n.runWebGPUProgram(s, i, i[0].dtype, c);
2739
+ i.forEach((e) => n.disposeData(e.dataId));
2740
+ let d = R({
2741
+ inputs: { x: u },
2742
+ backend: n,
2743
+ attrs: { shape: a }
2744
+ });
2745
+ return n.disposeData(u.dataId), d;
2746
+ }
2747
+ function nt(e, t, n) {
2748
+ let r = f(e.map((e) => e.shape), t);
2749
+ return {
2750
+ tensors2D: e.map((e) => R({
2751
+ inputs: { x: e },
2752
+ backend: n,
2753
+ attrs: { shape: [u(e.shape.slice(0, t)), u(e.shape.slice(t))] }
2754
+ })),
2755
+ outShape: r
2756
+ };
2757
+ }
2758
+ function rt(e) {
2759
+ let { inputs: t, backend: n, attrs: r } = e, { axis: i } = r, a = s(i, t[0].shape)[0], o = t.map((e) => e.shape);
2760
+ d(o, a);
2761
+ let c = f(t.map((e) => e.shape), a);
2762
+ return u(c) === 0 ? n.makeTensorInfo(c, t[0].dtype, []) : $(t.filter((e) => u(e.shape) > 0), a, n);
2763
+ }
2764
+ l({
2765
+ kernelName: "Concat16",
2766
+ backendName: "webgpu",
2767
+ kernelFunc: rt
2768
+ });
2769
+ // lib/ops/webgpu/mul16.ts
2770
+ function it(e) {
2771
+ let { a: t, b: n } = e.inputs, r = e.backend, i = n.shape.length === 0 ? new $e(L.MUL, t.shape) : new Q(L.MUL, t.shape, n.shape);
2772
+ return r.runWebGPUProgram(i, [t, n], "packedF16");
2773
+ }
2774
+ l({
2775
+ kernelName: "Mul16",
2776
+ backendName: "webgpu",
2777
+ kernelFunc: it
2778
+ });
2779
+ // lib/ops/webgpu/sub16.ts
2780
+ function at(e) {
2781
+ let { a: t, b: n } = e.inputs, r = e.backend, i = new Q(L.SUB, t.shape, n.shape);
2782
+ return r.runWebGPUProgram(i, [t, n], "packedF16");
2783
+ }
2784
+ l({
2785
+ kernelName: "Sub16",
2786
+ backendName: "webgpu",
2787
+ kernelFunc: at
2788
+ });
2789
+ // lib/ops/webgpu/softmax16grad.ts
2790
+ var ot = class extends K {
2791
+ constructor(e, t) {
2792
+ super(e, t, {
2793
+ reductionOp: "sum",
2794
+ elementwise: !0
2795
+ }, !0), this.shaderKey = "SoftmaxGrad16", this.variableNames = ["dy", "softmaxOutput"], this.variableComponents = [1, 1];
2796
+ }
2797
+ getReadSnippet() {
2798
+ return "\n let d: vec2<f32> = unpack2x16float(u32(dy[index]));\n let l: vec2<f32> = unpack2x16float(u32(softmaxOutput[index]));\n return d * l;\n ";
2799
+ }
2800
+ getWriteSnippet() {
2801
+ return "\n let d: vec2<f32> = unpack2x16float(u32(dy[offset + k]));\n let l: vec2<f32> = unpack2x16float(u32(softmaxOutput[offset + k]));\n let outVal = l * (d - bestValue);\n result[offset + k] = i32(pack2x16float(outVal));\n ";
2802
+ }
2803
+ };
2804
+ function st(e) {
2805
+ let { dy: t, softmaxOutput: n } = e.inputs, r = e.backend, i = J(r), a = E(t), o = E(n);
2806
+ if (!(a && o)) throw Error("softmaxGradGPU: dy and softmaxOutput must be packed tensors");
2807
+ let s = [t, n];
2808
+ return q(new ot(i, G(s, -1)), s, r);
2809
+ }
2810
+ l({
2811
+ kernelName: "Softmax16Grad",
2812
+ backendName: "webgpu",
2813
+ kernelFunc: st
2814
+ });
2815
+ // lib/ops/webgpu/norm2.ts
2816
+ var ct = class extends K {
2817
+ shaderKey = "norm2";
2818
+ atomic = !0;
2819
+ utilityFunctions = "\n fn atomicAddF32(sum: ptr<storage, atomic<i32>, read_write>, value: f32) -> f32 {\n var old = atomicLoad(sum);\n loop {\n let new_value = value + bitcast<f32>(old);\n let exchange_result = atomicCompareExchangeWeak(sum, old, bitcast<i32>(new_value));\n if (exchange_result.exchanged) {\n return new_value;\n }\n old = exchange_result.old_value;\n }\n }\n ";
2820
+ constructor(e, t, n) {
2821
+ super(e, t, {
2822
+ reductionOp: "sum",
2823
+ elementwise: !1,
2824
+ forceWorkgroupSize: n
2825
+ }, !1), this.uniforms += "lossScaling: f32, index: i32";
2826
+ }
2827
+ getPreprocessSnippet() {
2828
+ return "\n candidate = candidate * uniforms.lossScaling;\n candidate = candidate * candidate;\n ";
2829
+ }
2830
+ getWriteSnippet() {
2831
+ return "\n if (tid == 0) {\n atomicAddF32(&result[uniforms.index], bestValue);\n }\n ";
2832
+ }
2833
+ };
2834
+ function lt(e) {
2835
+ let { x: t, output: n } = e.inputs, { invLossScaling: r, index: i } = e.attrs, a = e.backend, o = [], s = J(a), c = Math.min(512, a.device.limits.maxComputeWorkgroupSizeX), l = u(t.shape);
2836
+ for (; l % (c * 4) != 0 && c > 1;) c /= 2;
2837
+ if (c === 1) throw Error(`Cannot find suitable workgroup size for Norm2Program with reduce size ${l}`);
2838
+ let d = q(new ct(s, {
2839
+ inSize: c * 4,
2840
+ outSize: 1,
2841
+ batchSize: l / (c * 4),
2842
+ windowSize: c
2843
+ }, c), [t], a, [{
2844
+ type: "float32",
2845
+ data: [r]
2846
+ }, {
2847
+ type: "int32",
2848
+ data: [i]
2849
+ }], n);
2850
+ return o.forEach((e) => e.dispose()), d;
2851
+ }
2852
+ l({
2853
+ kernelName: "Norm2",
2854
+ backendName: "webgpu",
2855
+ kernelFunc: lt
2856
+ });
2857
+ // lib/ops/webgpu/clipScale.ts
2858
+ var ut = class extends K {
2859
+ shaderKey = "clipscale";
2860
+ constructor(e, t, n) {
2861
+ super(e, t, {
2862
+ reductionOp: "sum",
2863
+ elementwise: !1,
2864
+ forceWorkgroupSize: n
2865
+ }, !1), this.uniforms += "scaling: f32, clipNorm: f32";
2866
+ }
2867
+ getReadSnippet() {
2868
+ return "\n return bitcast<f32>(u32(x[index]));\n ";
2869
+ }
2870
+ getWriteSnippet() {
2871
+ return "\n if (tid == 0) {\n let cnorm = uniforms.clipNorm;\n let gradNorm = sqrt(max(bestValue, 0.0));\n result[0] = (cnorm / max(cnorm, gradNorm)) * uniforms.scaling;\n result[1] = gradNorm;\n }\n ";
2872
+ }
2873
+ };
2874
+ function dt(e) {
2875
+ let { x: t } = e.inputs, { invLossScaling: n, clipNorm: r } = e.attrs, i = e.backend, a = [];
2876
+ if (t.shape.length !== 1) throw Error(`ClipScaleProgram requires 1D input, but got shape ${t.shape}`);
2877
+ let o = J(i), s = 128, c = 1, l = t.shape[0];
2878
+ l <= 16 ? s = 16 : l <= 32 ? s = 32 : l <= 64 && (s = 64), l > 128 && (c = Math.ceil(l / 128));
2879
+ let u = q(new ut(o, {
2880
+ inSize: s * c,
2881
+ outSize: 2,
2882
+ batchSize: 1,
2883
+ windowSize: s
2884
+ }, s), [t], i, [{
2885
+ type: "float32",
2886
+ data: [n]
2887
+ }, {
2888
+ type: "float32",
2889
+ data: [r]
2890
+ }]);
2891
+ return a.forEach((e) => e.dispose()), u;
2892
+ }
2893
+ l({
2894
+ kernelName: "ClipScale",
2895
+ backendName: "webgpu",
2896
+ kernelFunc: dt
2897
+ });
2898
+ // lib/ops/webgpu/dropout16.ts
2899
+ var ft = class {
2900
+ variableNames = ["x"];
2901
+ outputShape;
2902
+ shaderKey = "Dropout16";
2903
+ dispatchLayout;
2904
+ dispatch;
2905
+ workgroupSize = [
2906
+ 64,
2907
+ 1,
2908
+ 1
2909
+ ];
2910
+ size = !0;
2911
+ uniforms = "dropout: f32, seed: f32";
2912
+ constructor(e) {
2913
+ this.shaderKey = "Dropout16", this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
2914
+ }
2915
+ getUserCode() {
2916
+ return `
2917
+
2918
+ fn random(coords: vec3<i32>) -> vec2<f32> {
2919
+ let x1 = f32(coords.x * 4096 + coords.y * 256 + coords.z * 2 * 16);
2920
+ let x2 = f32(coords.x * 4096 + coords.y * 256 + (coords.z * 2 + 1) * 16);
2921
+ return vec2<f32>(fract(sin(uniforms.seed + x1) * 43758.5453123), fract(sin(uniforms.seed + x2) * 43758.5453123));
2922
+ }
2923
+
2924
+ ${M("index")} {
2925
+ if (index < uniforms.size) {
2926
+ let coords = getCoordsFromIndex(index);
2927
+ let values = unpack2x16float(u32(x[index]));
2928
+ let keepProb = 1.0 - uniforms.dropout;
2929
+ let rand = random(coords);
2930
+ let mask = step(rand, vec2<f32>(keepProb));
2931
+ let outVal = values * mask / keepProb;
2932
+ result[index] = i32(pack2x16float(outVal));
2933
+ }
2934
+ }
2935
+ `;
2936
+ }
2937
+ };
2938
+ function pt(e) {
2939
+ let { x: t } = e.inputs, { dropout: n, seed: r } = e.attrs, i = e.backend, a = new ft(t.shape), o = [{
2940
+ type: "float32",
2941
+ data: [n]
2942
+ }, {
2943
+ type: "float32",
2944
+ data: [r]
2945
+ }];
2946
+ return i.runWebGPUProgram(a, [t], "packedF16", o);
2947
+ }
2948
+ l({
2949
+ kernelName: "Dropout16",
2950
+ backendName: "webgpu",
2951
+ kernelFunc: pt
2952
+ });
2953
+ // lib/ops/webgpu/silu.ts
2954
+ var mt = class {
2955
+ outputShape;
2956
+ shaderKey;
2957
+ dispatchLayout;
2958
+ dispatch;
2959
+ variableNames = ["A"];
2960
+ workgroupSize;
2961
+ size = !0;
2962
+ constructor(e) {
2963
+ this.workgroupSize = [
2964
+ 128,
2965
+ 1,
2966
+ 1
2967
+ ], this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = "unary_silu";
2968
+ }
2969
+ getUserCode() {
2970
+ return `
2971
+ fn unaryOperation(x : f32) -> f32 {
2972
+ return x / (1.0 + exp(-x));
2973
+ }
2974
+ ${M("index")} {
2975
+ if (index < uniforms.size) {
2976
+ let a = getAByOutputIndex(index);
2977
+ setOutputAtIndex(index, unaryOperation(a));
2978
+ }
2979
+ }
2980
+ `;
2981
+ }
2982
+ };
2983
+ function ht(e) {
2984
+ let { x: t } = e.inputs, n = e.backend, r = new mt(t.shape);
2985
+ return n.runWebGPUProgram(r, [t], "float32");
2986
+ }
2987
+ l({
2988
+ kernelName: "Silu",
2989
+ backendName: "webgpu",
2990
+ kernelFunc: ht
2991
+ });
2992
+ var gt = class {
2993
+ variableNames = ["dy", "x"];
2994
+ outputShape;
2995
+ shaderKey = "SiluGrad16";
2996
+ dispatchLayout;
2997
+ dispatch;
2998
+ workgroupSize = [
2999
+ 128,
3000
+ 1,
3001
+ 1
3002
+ ];
3003
+ size = !0;
3004
+ constructor(e) {
3005
+ this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
3006
+ }
3007
+ getUserCode() {
3008
+ return `
3009
+ fn activationGrad(dy: f32, X: f32) -> f32 {
3010
+ let sigmoid = 1.0 / (1.0 + exp(-X));
3011
+ return dy * (sigmoid + X * sigmoid * (1.0 - sigmoid));
3012
+ }
3013
+ ${M("index")} {
3014
+ if (index < uniforms.size) {
3015
+ let X = unpack2x16float(u32(x[index]));
3016
+ let DY = unpack2x16float(u32(dy[index]));
3017
+ let dsilu = vec2<f32>(
3018
+ activationGrad(DY.x, X.x),
3019
+ activationGrad(DY.y, X.y)
3020
+ );
3021
+ result[index] = i32(pack2x16float(dsilu));
3022
+ }
3023
+ }`;
3024
+ }
3025
+ }, _t = class {
3026
+ variableNames = ["dy", "x"];
3027
+ outputShape;
3028
+ shaderKey = "SiluGrad32";
3029
+ dispatchLayout;
3030
+ dispatch;
3031
+ workgroupSize = [
3032
+ 128,
3033
+ 1,
3034
+ 1
3035
+ ];
3036
+ size = !0;
3037
+ constructor(e) {
3038
+ this.outputShape = e, this.dispatchLayout = A(this.outputShape), this.dispatch = N(this.dispatchLayout, this.outputShape, this.workgroupSize);
3039
+ }
3040
+ getUserCode() {
3041
+ return `
3042
+ fn activationGrad(dy: f32, X: f32) -> f32 {
3043
+ let sigmoid = 1.0 / (1.0 + exp(-X));
3044
+ return dy * (sigmoid + X * sigmoid * (1.0 - sigmoid));
3045
+ }
3046
+ ${M("index")} {
3047
+ if (index < uniforms.size) {
3048
+ let X = getXByOutputIndex(index);
3049
+ let DY = getDyByOutputIndex(index);
3050
+ let dsilu = activationGrad(DY, X);
3051
+ setOutputAtIndex(index, dsilu);
3052
+ }
3053
+ }`;
3054
+ }
3055
+ };
3056
+ function vt(e) {
3057
+ let { dy: t, x: n } = e.inputs, r = e.backend, i = E(t), a = i ? new gt(n.shape) : new _t(n.shape);
3058
+ return r.runWebGPUProgram(a, [t, n], i ? "packedF16" : "float32");
3059
+ }
3060
+ l({
3061
+ kernelName: "SiluGrad",
3062
+ backendName: "webgpu",
3063
+ kernelFunc: vt
3064
+ });
3065
+ // lib/ops/webgpu/sparseCrossEntropy.ts
3066
+ var yt = class {
3067
+ stage;
3068
+ attrs;
3069
+ variableNames;
3070
+ outputShape;
3071
+ shaderKey;
3072
+ dispatchLayout;
3073
+ dispatch;
3074
+ workgroupSize = [
3075
+ 64,
3076
+ 1,
3077
+ 1
3078
+ ];
3079
+ size = !0;
3080
+ subgroups;
3081
+ subgroupBuiltins;
3082
+ constructor(e, t, n) {
3083
+ this.stage = e, this.attrs = t;
3084
+ let { rows: r, classes: i, groups: a } = t;
3085
+ this.subgroups = e !== "Grad" && n.subgroupsSupported, this.subgroupBuiltins = this.subgroups && (n.variableSubgroups || n.subgroupMaxSize === 0), this.subgroups && !this.subgroupBuiltins && (this.workgroupSize = [
3086
+ Math.min(64, n.subgroupMaxSize),
3087
+ 1,
3088
+ 1
3089
+ ]), this.variableNames = e === "Stats" ? ["logits", "labels"] : e === "Reduce" ? t.masked ? ["stats", "labels"] : ["stats"] : [
3090
+ "logits",
3091
+ "labels",
3092
+ "stats",
3093
+ "reduced",
3094
+ "dy"
3095
+ ], this.outputShape = e === "Stats" ? [r, 3] : e === "Reduce" ? [2, a] : [r, i], this.dispatchLayout = A(this.outputShape), this.dispatch = e === "Stats" ? [
3096
+ r,
3097
+ 1,
3098
+ 1
3099
+ ] : e === "Reduce" ? [
3100
+ a,
3101
+ 1,
3102
+ 1
3103
+ ] : N(this.dispatchLayout, this.outputShape, this.workgroupSize), this.shaderKey = `SparseCrossEntropy${e}_${JSON.stringify(t)}_${this.subgroups}_${this.subgroupBuiltins}`;
3104
+ }
3105
+ reduce(e, t, n) {
3106
+ let r = this.workgroupSize[0], i = (e, t) => n === "max" ? `max(${e}, ${t})` : `${e} + ${t}`;
3107
+ if (!this.subgroups) return `
3108
+ ${t}[tid] = ${e};
3109
+ workgroupBarrier();
3110
+ for (var stride = ${r / 2}; stride > 0; stride /= 2) {
3111
+ if (tid < stride) {
3112
+ ${t}[tid] = ${i(`${t}[tid]`, `${t}[tid + stride]`)};
3113
+ }
3114
+ workgroupBarrier();
3115
+ }
3116
+ ${e} = ${t}[0];
3117
+ `;
3118
+ let a = n === "max" ? "subgroupMax" : "subgroupAdd", o = n === "max" ? "-3.402823e38" : "vec2<f32>(0.0)";
3119
+ return `
3120
+ ${e} = ${a}(${e});
3121
+ ${this.subgroupBuiltins ? `
3122
+ if (subgroupInvocationId == 0u) {
3123
+ ${t}[localId.x / subgroupSize] = ${e};
3124
+ }
3125
+ workgroupBarrier();
3126
+ ${e} = ${o};
3127
+ // Fold subgroup totals even when there are more subgroups than lanes.
3128
+ for (var part = subgroupInvocationId;
3129
+ part < (${r}u + subgroupSize - 1u) / subgroupSize;
3130
+ part += subgroupSize) {
3131
+ ${e} = ${i(e, `${t}[part]`)};
3132
+ }
3133
+ ${e} = ${a}(${e});
3134
+ workgroupBarrier();
3135
+ ` : ""}
3136
+ `;
3137
+ }
3138
+ getUserCode() {
3139
+ let { classes: e, groups: t, groupSize: n, masked: r, smoothing: i } = this.attrs, a = this.workgroupSize[0], o = !this.subgroups || this.subgroupBuiltins;
3140
+ return this.stage === "Stats" ? `
3141
+ ${o ? `
3142
+ var<workgroup> maxima: array<f32, ${a}>;
3143
+ var<workgroup> sums: array<vec2<f32>, ${a}>;
3144
+ ` : ""}
3145
+ ${M("index")} {
3146
+ let row = index / ${a};
3147
+ let tid = i32(localId.x);
3148
+ let label = labels[row];
3149
+ var maximum = -3.402823e38;
3150
+ for (var c = tid; c < ${e}; c += ${a}) {
3151
+ maximum = max(maximum, logits[row * ${e} + c]);
3152
+ }
3153
+ ${this.reduce("maximum", "maxima", "max")}
3154
+ let rowMax = maximum;
3155
+ var sum = vec2<f32>(0.0);
3156
+ for (var c = tid; c < ${e}; c += ${a}) {
3157
+ let stable = logits[row * ${e} + c] - rowMax;
3158
+ sum += vec2<f32>(exp(stable), ${i > 0 ? "stable" : "0.0"});
3159
+ }
3160
+ ${this.reduce("sum", "sums", "sum")}
3161
+ if (tid == 0 && row < uniforms.outShape[0]) {
3162
+ var loss = 0.0;
3163
+ if (${r ? "label != 65535" : "true"}) {
3164
+ let targetLogit = logits[row * ${e} + label] - rowMax;
3165
+ loss = log(sum.x) - ${1 - i} * targetLogit
3166
+ - ${i / e} * sum.y;
3167
+ }
3168
+ result[row * 3] = rowMax;
3169
+ result[row * 3 + 1] = 1.0 / sum.x;
3170
+ result[row * 3 + 2] = loss;
3171
+ }
3172
+ }` : this.stage === "Reduce" ? `
3173
+ ${o ? `var<workgroup> sums: array<vec2<f32>, ${a}>;` : ""}
3174
+ ${M("index")} {
3175
+ let group = index / ${a};
3176
+ let tid = i32(localId.x);
3177
+ var sum = vec2<f32>(0.0);
3178
+ for (var r = group * ${n} + tid; r < (group + 1) * ${n}; r += ${a}) {
3179
+ sum.x += stats[r * 3 + 2];
3180
+ sum.y += ${r ? "select(0.0, 1.0, labels[r] != 65535)" : "1.0"};
3181
+ }
3182
+ ${this.reduce("sum", "sums", "sum")}
3183
+ if (tid == 0 && group < uniforms.outShape[1]) {
3184
+ result[group] = select(sum.x / sum.y, uniforms.NAN, sum.y == 0.0);
3185
+ result[${t} + group] = sum.y;
3186
+ }
3187
+ }` : `
3188
+ ${M("index")} {
3189
+ if (index < uniforms.size) {
3190
+ let row = index / ${e};
3191
+ let col = index % ${e};
3192
+ let group = row / ${n};
3193
+ if (reduced[${t} + group] == 0.0) {
3194
+ result[index] = uniforms.NAN;
3195
+ return;
3196
+ }
3197
+ let probability = exp(logits[index] - stats[row * 3]) * stats[row * 3 + 1];
3198
+ let targetWeight = select(0.0, ${1 - i}, labels[row] == col);
3199
+ let valid = ${r ? "select(0.0, 1.0, labels[row] != 65535)" : "1.0"};
3200
+ result[index] = (probability - ${i / e} - targetWeight)
3201
+ * (dy[group] / reduced[${t} + group]) * valid;
3202
+ }
3203
+ }`;
3204
+ }
3205
+ };
3206
+ for (let e of [
3207
+ "Stats",
3208
+ "Reduce",
3209
+ "Grad"
3210
+ ]) l({
3211
+ kernelName: `SparseCrossEntropy${e}`,
3212
+ backendName: "webgpu",
3213
+ kernelFunc: ({ inputs: t, attrs: n, backend: r }) => {
3214
+ let i = r, a = new yt(e, n, J(i));
3215
+ return i.runWebGPUProgram(a, a.variableNames.map((e) => {
3216
+ let n = t[e];
3217
+ if (!n) throw Error(`Missing sparse cross-entropy input: ${e}`);
3218
+ return n;
3219
+ }), "float32");
3220
+ }
3221
+ });