@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,1007 @@
1
+ import { Ct as e, Di as t, Ei as n, H as r, Ii as i, M as a, Ni as o, Pi as s, St as c, Ti as l, Wi as u, X as d, ca as f, ia as p, s as m, sa as h, ta as g, wt as _ } from "./dist-JOPw9zTN.js";
2
+ // node_modules/@tensorflow/tfjs-backend-webgpu/dist/shader_util.js
3
+ function v(e, t) {
4
+ if (Math.max(...e) > 5) throw Error("Cannot symbolically compute strides for rank > 6 tensor.");
5
+ let n = e.length, r = e.map((e) => `${t}.${"xyzwuv"[e]}`), i = Array(n - 1);
6
+ i[n - 2] = r[n - 1];
7
+ for (let e = n - 3; e >= 0; --e) i[e] = `(${i[e + 1]} * ${r[e + 1]})`;
8
+ return i;
9
+ }
10
+ var ee = (e, t, n) => n === "int32" ? `atomicAdd(${e}, bitcast<i32>(${t}));` : `
11
+ {
12
+ var oldValue = 0;
13
+ loop {
14
+ let newValueF32 = bitcast<f32>(oldValue) + (${t});
15
+ let newValue = bitcast<i32>(newValueF32);
16
+ let res = atomicCompareExchangeWeak(${e}, oldValue, newValue);
17
+ if res.exchanged {
18
+ break;
19
+ }
20
+ oldValue = res.old_value;
21
+ }
22
+ }`, y;
23
+ (function(e) {
24
+ e[e.FROM_PIXELS = 0] = "FROM_PIXELS", e[e.DRAW = 1] = "DRAW";
25
+ })(y ||= {});
26
+ var b = (e, t, n, r, i) => {
27
+ let a = D(n, {
28
+ dtype: r.dtype,
29
+ shape: r.shape
30
+ }, t), o = e.createShaderModule({
31
+ code: a,
32
+ label: t.constructor.name
33
+ }), s = l().get("WEBGPU_PRINT_SHADER");
34
+ if (s !== "") {
35
+ s = s.toLowerCase();
36
+ let e = s.split(",");
37
+ (s === "all" || e.some((e) => t.shaderKey.toLowerCase().includes(e))) && (console.group(t.shaderKey), console.debug(a), console.groupEnd());
38
+ }
39
+ return i ? e.createComputePipelineAsync({
40
+ compute: {
41
+ module: o,
42
+ entryPoint: "_start"
43
+ },
44
+ label: t.constructor.name,
45
+ layout: "auto"
46
+ }) : e.createComputePipeline({
47
+ compute: {
48
+ module: o,
49
+ entryPoint: "_start"
50
+ },
51
+ label: t.constructor.name,
52
+ layout: "auto"
53
+ });
54
+ }, x = (e, t = "f32") => {
55
+ switch (e) {
56
+ case 1: return `${t}`;
57
+ case 2: return `vec2<${t}>`;
58
+ case 3: return `vec3<${t}>`;
59
+ case 4: return `vec4<${t}>`;
60
+ default: throw Error(`${e}-component ${t} is not supported.`);
61
+ }
62
+ };
63
+ function S(e) {
64
+ if (e <= 1) return "i32";
65
+ if (e === 2) return "vec2<i32>";
66
+ if (e === 3) return "vec3<i32>";
67
+ if (e === 4) return "vec4<i32>";
68
+ if (e === 5) return "vec5";
69
+ if (e === 6) return "vec6";
70
+ throw Error(`GPU for rank ${e} is not yet supported`);
71
+ }
72
+ function C(e) {
73
+ if (e === 0) return "x";
74
+ if (e === 1) return "y";
75
+ if (e === 2) return "z";
76
+ if (e === 3) return "w";
77
+ if (e === 4) return "u";
78
+ if (e === 5) return "v";
79
+ throw Error(`Index ${e} is not yet supported`);
80
+ }
81
+ function w(...e) {
82
+ let t;
83
+ switch (e.length) {
84
+ case 0:
85
+ t = "\n fn main()\n ";
86
+ break;
87
+ case 1:
88
+ t = `
89
+ fn main(${e[0]} : i32)
90
+ `;
91
+ break;
92
+ default: throw Error("Unreachable");
93
+ }
94
+ return t;
95
+ }
96
+ function T(e, t) {
97
+ let n;
98
+ return n = `
99
+ ${E(t)}
100
+ fn _start(@builtin(local_invocation_id) LocalId : vec3<u32>,
101
+ @builtin(global_invocation_id) GlobalId : vec3<u32>,
102
+ @builtin(local_invocation_index) LocalIndex: u32,
103
+ @builtin(workgroup_id) WorkgroupId : vec3<u32>,
104
+ ${t.subgroupBuiltins ? "@builtin(subgroup_invocation_id) SubgroupInvocationId : u32," : ""}
105
+ ${t.subgroupBuiltins ? "@builtin(subgroup_size) SubgroupSize : u32," : ""}
106
+ @builtin(num_workgroups) NumWorkgroups : vec3<u32>) {
107
+ localId = LocalId;
108
+ localIndex = LocalIndex;
109
+ globalId = GlobalId;
110
+ numWorkgroups = NumWorkgroups;
111
+ workgroupId = WorkgroupId;
112
+ ${t.subgroupBuiltins ? "subgroupInvocationId = SubgroupInvocationId" : ""};
113
+ ${t.subgroupBuiltins ? "subgroupSize = SubgroupSize" : ""};
114
+ ${e ? "main(getGlobalIndex());" : "main();"};
115
+ }
116
+ `, n;
117
+ }
118
+ function E(e) {
119
+ return `
120
+ @compute @workgroup_size(${e.workgroupSize[0]}, ${e.workgroupSize[1]}, ${e.workgroupSize[2]})
121
+ `;
122
+ }
123
+ function D(e, t, n) {
124
+ let r = [], i = n.workgroupSize[0] * n.workgroupSize[1] * n.workgroupSize[2];
125
+ if (n.outputComponent = n.outputComponent ? n.outputComponent : 1, r.push(`
126
+
127
+ var<private> localId: vec3<u32>;
128
+ var<private> localIndex: u32;
129
+ var<private> globalId: vec3<u32>;
130
+ var<private> numWorkgroups: vec3<u32>;
131
+ var<private> workgroupId: vec3<u32>;
132
+ ${n.subgroupBuiltins ? "var<private> subgroupInvocationId: u32;" : ""}
133
+ ${n.subgroupBuiltins ? "var<private> subgroupSize: u32;" : ""}
134
+
135
+ // Only used when the y/z dimension of workgroup size is 1.
136
+ fn getGlobalIndex() -> i32 {
137
+ ${F(n) ? " return i32(globalId.x);" : ` return i32((workgroupId.z * numWorkgroups.x * numWorkgroups.y +
138
+ workgroupId.y * numWorkgroups.x + workgroupId.x) * ${i}u +
139
+ localIndex);
140
+ `}
141
+ }
142
+ `), n.pixelsOpType != null) {
143
+ let i = n.pixelsOpType === y.FROM_PIXELS ? `@group(0) @binding(0) var<storage, read_write> result: array<${I(t.dtype, n.outputComponent)}>;` : `@group(0) @binding(1) var<storage, read> inBuf : array<${I(e[0].dtype, n.outputComponent)}>;`, a = t.shape.length === 3 ? "vec2<i32>" : "i32";
144
+ r.push(`
145
+ struct Uniform {
146
+ outShapeStrides : ${a},
147
+ size : i32,
148
+ numChannels : i32,
149
+ alpha : f32,
150
+ };
151
+
152
+ ${i}
153
+ @group(0) @binding(2) var<uniform> uniforms: Uniform;
154
+ `);
155
+ let o = L(n);
156
+ return [
157
+ k,
158
+ r.join("\n"),
159
+ A(t.shape),
160
+ n.getUserCode(),
161
+ T(o, n)
162
+ ].join("\n");
163
+ }
164
+ let a, o, s = "struct Uniforms { NAN : f32, INFINITY : f32, ";
165
+ n.variableNames.forEach((t, n) => {
166
+ let r = S(e[n].shape.length);
167
+ s += `${t.charAt(0).toLowerCase() + t.slice(1)}Shape : ${r}, `, a = e[n].shape.length - 1, o = S(a), s += `${t.charAt(0).toLowerCase() + t.slice(1)}ShapeStrides: ${o}, `;
168
+ });
169
+ let c = S(t.shape.length);
170
+ s += `outShape : ${c}, `, a = t.shape.length - 1, o = S(a), s += `
171
+ outShapeStrides: ${o}, `, n.size && (s += "size : i32, "), n.uniforms && (s += n.uniforms), s += "};", s = ie(s), r.push(s), n.atomic ? r.push("\n @group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;\n ") : r.push(`
172
+ @group(0) @binding(0) var<storage, read_write> result: array<${I(t.dtype, n.outputComponent)}>;
173
+ `), n.variableNames.forEach((t, i) => {
174
+ r.push(`
175
+ @group(0) @binding(${1 + i}) var<storage, read> ${t}: array<${n.variableComponents ? I(e[i].dtype, n.variableComponents[i]) : I(e[i].dtype, n.outputComponent)}>;
176
+ `);
177
+ }), s !== "" && r.push(`
178
+ @group(0) @binding(${1 + n.variableNames.length}) var<uniform> uniforms: Uniforms;
179
+ `);
180
+ let l = P(t.shape, n.dispatchLayout), u = [
181
+ n.subgroups ? "enable subgroups;" : "",
182
+ k,
183
+ r.join("\n") + te,
184
+ A(t.shape),
185
+ l,
186
+ ne(t.shape.length)
187
+ ];
188
+ n.atomic || u.push(re(t.shape, t.dtype, n.outputComponent)), n.variableNames.forEach((t, n) => {
189
+ u.push(`${A(e[n].shape, t)}`);
190
+ });
191
+ let d = e.map((e, r) => N(e, t.shape, n.variableComponents ? n.variableComponents[r] : n.outputComponent, n.dispatchLayout.x.length === t.shape.length)).join("\n");
192
+ u.push(d), u.push(n.getUserCode());
193
+ let f = L(n);
194
+ return u.push(T(f, n)), u.join("\n");
195
+ }
196
+ function O(e, t, r) {
197
+ let i = e.shaderKey;
198
+ if (e.pixelsOpType != null) return i;
199
+ let o = [], s = [];
200
+ t.forEach((e) => {
201
+ o.push(e.shape), s.push(e.dtype);
202
+ }), o.push(r.shape), s.push(r.dtype);
203
+ let c = t.map((e) => a(e.shape, r.shape)), l = t.map((e) => n(e.shape, r.shape)).join("_"), u = c.map((e) => e.join("_")).join(";"), d = F(e) ? "flatDispatch" : "";
204
+ return i += "_" + (e.workgroupSize ? e.workgroupSize.join(",") : "") + o.map((e) => e.length).join(",") + s.join(",") + e.variableNames.join(",") + u + l + d, i;
205
+ }
206
+ var k = "\n struct vec5 {x: i32, y: i32, z: i32, w: i32, u: i32};\n struct vec6 {x: i32, y: i32, z: i32, w: i32, u: i32, v: i32};\n\n // Checks whether coordinates lie within the bounds of the shape.\n fn coordsInBounds2D(coord : vec2<i32>, shape : vec2<i32>) -> bool {\n return all(coord >= vec2<i32>(0)) && all(coord < shape);\n }\n fn coordsInBounds3D(coord : vec3<i32>, shape : vec3<i32>) -> bool {\n return all(coord >= vec3<i32>(0)) && all(coord < shape);\n }\n fn coordsInBounds4D(coord : vec4<i32>, shape : vec4<i32>) -> bool {\n return all(coord >= vec4<i32>(0)) && all(coord < shape);\n }\n\n fn getIndexFromCoords1D(coord : i32, shape : i32) -> i32 {\n return coord;\n }\n fn getIndexFromCoords2D(coords : vec2<i32>, shape : vec2<i32>) -> i32 {\n return dot(coords, vec2<i32>(shape.y, 1));\n }\n fn getIndexFromCoords3D(coords : vec3<i32>, shape : vec3<i32>) -> i32 {\n return dot(coords, vec3<i32>(shape.y * shape.z, shape.z, 1));\n }\n fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n }\n fn getIndexFromCoords5D(coords : vec5, shape : vec5) -> i32 {\n let shapeStrides: vec5 = vec5(shape.y * shape.z * shape.w * shape.u, shape.z * shape.w * shape.u, shape.w * shape.u, shape.u, 1);\n return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u;\n }\n fn getIndexFromCoords6D(coords : vec6, shape : vec6) -> i32 {\n let shapeStrides: vec6 = vec6(shape.y * shape.z * shape.w * shape.u * shape.v, shape.z * shape.w * shape.u * shape.v, shape.w * shape.u * shape.v, shape.u * shape.v, shape.v, 1);\n return coords.x*shapeStrides.x + coords.y*shapeStrides.y + coords.z*shapeStrides.z + coords.w*shapeStrides.w + coords.u*shapeStrides.u + coords.v*shapeStrides.v;\n }\n\n // NaN defination in IEEE 754-1985 is :\n // - sign = either 0 or 1.\n // - biased exponent = all 1 bits.\n // - fraction = anything except all 0 bits (since all 0 bits represents infinity).\n // https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers\n fn isnan(val: f32) -> bool {\n let floatToUint: u32 = bitcast<u32>(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n fn isnanVec4(val : vec4<f32>) -> vec4<bool> {\n let floatToUint: vec4<u32> = bitcast<vec4<u32>>(val);\n return (floatToUint & vec4<u32>(0x7fffffffu)) > vec4<u32>(0x7f800000u);\n }\n", te = "\n fn isinf(val: f32) -> bool {\n return abs(val) == uniforms.INFINITY;\n }\n";
207
+ function A(e, t = "") {
208
+ let n = e.length, r = t === "" ? "getCoordsFromIndex" : `get${t.charAt(0).toUpperCase() + t.slice(1)}CoordsFromIndex`, i = t === "" ? "outShapeStrides" : `${t.charAt(0).toLowerCase() + t.slice(1)}ShapeStrides`;
209
+ if (n <= 1) return `fn ${r}(index : i32) -> i32 { return index; }`;
210
+ let a = o(e), s = S(n), c = [];
211
+ for (let e = 0; e < n; e++) c.push(`d${e}`);
212
+ if (a.length === 1) return ` fn ${r}(index : i32) -> vec2<i32> {
213
+ let d0 = index / uniforms.${i}; let d1 = index - d0 * uniforms.${i};
214
+ return vec2<i32>(d0, d1);
215
+ }`;
216
+ let l;
217
+ return l = "var index2 = index;" + a.map((e, t) => `${`let ${c[t]} = index2 / uniforms.${i}.${C(t)}`}; ${t === a.length - 1 ? `let ${c[t + 1]} = index2 - ${c[t]} * uniforms.${i}.${C(t)}` : `index2 = index2 - ${c[t]} * uniforms.${i}.${C(t)}`};`).join(""), `
218
+ fn ${r}(index : i32) -> ${s} {
219
+ ${l}
220
+ return ${s}(${c.join(",")});
221
+ }
222
+ `;
223
+ }
224
+ function j(e, t) {
225
+ let n = e.name, r = e.shape.length, i = S(r), a = "get" + n.charAt(0).toUpperCase() + n.slice(1), o = [
226
+ "d0",
227
+ "d1",
228
+ "d2",
229
+ "d3",
230
+ "d4",
231
+ "d5"
232
+ ].slice(0, r), s = o.map((e) => `${e} : i32`).join(", ");
233
+ if (r < 1) return `
234
+ fn ${a}() -> ${x(t)} {
235
+ return ${x(t)}(${n}[0]);
236
+ }
237
+ `;
238
+ let c = `uniforms.${n.charAt(0).toLowerCase() + n.slice(1)}Shape`, l = `${r}D`;
239
+ return r === 0 && (l = "1D"), `
240
+ fn ${a}(${s}) -> ${x(t)} {
241
+ return ${x(t)}(${n}[getIndexFromCoords${l}(${i}(${o.join(",")}),
242
+ ${c})${t === 1 ? "" : ` / ${t}`}]);
243
+ }
244
+ `;
245
+ }
246
+ function M(e, t, r, i) {
247
+ let o = e.name, s = o.charAt(0).toUpperCase() + o.slice(1), c = "get" + s + "ByOutput", l = e.shape.length, u = t.length, d = S(u);
248
+ if (n(e.shape, t) && i) return `
249
+ fn ${c}Index(globalIndex : i32) -> ${x(r)} {
250
+ return ${x(r)}(${o}[globalIndex]);
251
+ }
252
+
253
+ fn ${c}Coords(coords : ${d}) -> ${x(r)} {
254
+ return ${x(r)}(${o}[${u > 1 ? "getOutputIndexFromCoords(coords)" : "coords"}${r === 1 ? "" : ` / ${r}`}]);
255
+ }
256
+ `;
257
+ let f = a(e.shape, t), p = u - l, m = "";
258
+ if (l === 0) return `
259
+ fn ${c}Index(globalIndex : i32) -> ${x(r)}{
260
+ return get${s}();
261
+ }
262
+
263
+ fn ${c}Coords(coords : ${d}) -> ${x(r)}{
264
+ return get${s}();
265
+ }
266
+ `;
267
+ m = u < 2 && f.length >= 1 ? "coords = 0;" : f.map((e) => `coords.${C(e + p)} = 0;`).join("\n");
268
+ let h = "";
269
+ h = u < 2 && l > 0 ? "coords" : u > 1 ? `${S(l)}(${e.shape.map((e, t) => `coords.${C(t + p)}`).join(", ")})` : "coords";
270
+ let g = `uniforms.${o.charAt(0).toLowerCase() + o.slice(1)}Shape`, _ = `${l}D`;
271
+ return `
272
+ fn ${c}Index(globalIndex : i32) -> ${x(r)} {
273
+ var coords = getCoordsFromIndex(globalIndex);
274
+ ${m}
275
+ return ${x(r)}(${o}[getIndexFromCoords${_}(${h}, ${g})${r === 1 ? "" : ` / ${r}`}]);
276
+ }
277
+
278
+ fn ${c}Coords(coordsIn : ${d}) -> ${x(r)} {
279
+ var coords = coordsIn;
280
+ ${m}
281
+ return ${x(r)}(${o}[getIndexFromCoords${_}(${h}, ${g})${r === 1 ? "" : ` / ${r}`}]);
282
+ }
283
+ `;
284
+ }
285
+ function N(e, t, n, r) {
286
+ let i = j(e, n);
287
+ return e.shape.length <= t.length && (i += M(e, t, n, r)), i;
288
+ }
289
+ function P(e, t) {
290
+ let { x: n, y: r = [], z: i = [] } = t, a = e.length, o = n.length + r.length + i.length;
291
+ if (o !== a) return "";
292
+ if (n.length === a) return `fn getOutputCoords() -> ${S(a)}{
293
+ let globalIndex = getGlobalIndex();
294
+ return getCoordsFromIndex(globalIndex);
295
+ }
296
+ `;
297
+ let s = "", c = [
298
+ n,
299
+ r,
300
+ i
301
+ ];
302
+ for (let e = 0; e < c.length; e++) {
303
+ let t = c[e];
304
+ if (t.length !== 0) {
305
+ if (t.length === 1) s += `let d${t[0]} = i32(globalId[${e}]);`;
306
+ else {
307
+ let n = v(t, "uniforms.outShape");
308
+ s += `var index${e} = i32(globalId[${e}]);`;
309
+ for (let r = 0; r < n.length; r++) s += `let d${t[r]} = index${e} / ${n[r]};`, r === n.length - 1 ? s += `let d${t[r + 1]} = index${e} - d${t[r]} * ${n[r]};` : s += `index${e} = index${e} - d${t[r]} * ${n[r]};`;
310
+ }
311
+ }
312
+ }
313
+ let l = [];
314
+ for (let e = 0; e < o; e++) l.push(`d${e}`);
315
+ let u = S(o), d = `fn getOutputCoords() -> ${u} {
316
+ ${s}
317
+ `;
318
+ return l.length === 0 ? d += `return ${u}(0); }` : d += `return ${u}(${l.join(",")}); }`, d;
319
+ }
320
+ function ne(e) {
321
+ let n = "";
322
+ switch (e) {
323
+ case 0:
324
+ case 1:
325
+ n += "\n fn getOutputIndexFromCoords(coords : i32) -> i32 {\n return coords;\n }\n ";
326
+ break;
327
+ case 2:
328
+ n += "\n fn getOutputIndexFromCoords(coords : vec2<i32>) -> i32 {\n return dot(coords, vec2<i32>(uniforms.outShapeStrides, 1));\n }\n ";
329
+ break;
330
+ case 3:
331
+ n += "\n fn getOutputIndexFromCoords(coords : vec3<i32>) -> i32 {\n return dot(coords, vec3<i32>(uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, 1));\n }\n ";
332
+ break;
333
+ case 4:
334
+ n += "\n fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n uniforms.outShapeStrides.x, uniforms.outShapeStrides.y, uniforms.outShapeStrides.z, 1));\n }\n ";
335
+ break;
336
+ case 5:
337
+ n += "\n fn getOutputIndexFromCoords(coords : vec5) -> i32 {\n return coords.x * uniforms.outShapeStrides.x +\n coords.y * uniforms.outShapeStrides.y +\n coords.z * uniforms.outShapeStrides.z +\n coords.w * uniforms.outShapeStrides.w +\n coords.u;\n }\n ";
338
+ break;
339
+ case 6:
340
+ n += "\n fn getOutputIndexFromCoords(coords : vec6) -> i32 {\n return coords.x * uniforms.outShapeStrides.x +\n coords.y * uniforms.outShapeStrides.y +\n coords.z * uniforms.outShapeStrides.z +\n coords.w * uniforms.outShapeStrides.w +\n coords.u * uniforms.outShapeStrides.u +\n coords.v;\n }\n ";
341
+ break;
342
+ default: t(!1, () => `Unsupported ${e}D shape`);
343
+ }
344
+ return n;
345
+ }
346
+ function F(e) {
347
+ return e.dispatch[1] === 1 && e.dispatch[2] === 1;
348
+ }
349
+ function I(e, t = 1) {
350
+ if (e === "float32") return x(t, "f32");
351
+ if (e === "int32" || e === "bool" || e === "packedF16") return x(t, "i32");
352
+ throw Error(`type ${e} is not supported.`);
353
+ }
354
+ function re(e, t, n) {
355
+ let r = e.length, i = I(t, n), a = `fn setOutputAtIndex(flatIndex : i32, value : ${x(n)}) {
356
+ result[flatIndex] = ${i}(value);
357
+ }
358
+
359
+ fn setOutputAtIndexI32(flatIndex : i32, value : ${x(n, "i32")}) {
360
+ result[flatIndex] = ${i}(value);
361
+ }
362
+ `;
363
+ if (r >= 2) {
364
+ let e = [
365
+ "d0",
366
+ "d1",
367
+ "d2",
368
+ "d3",
369
+ "d4",
370
+ "d5"
371
+ ].slice(0, r), t = S(r);
372
+ a += `
373
+ fn setOutputAtCoords(${e.map((e) => `${e} : i32`).join(", ")}, value : ${x(n)}) {
374
+ let flatIndex = getOutputIndexFromCoords(${t}(${e.join(", ")}));
375
+ setOutputAtIndex(flatIndex${n === 1 ? "" : ` / ${n}`}, value);
376
+ }
377
+ fn setOutputAtCoordsI32(${e.map((e) => `${e} : i32`).join(", ")}, value : ${x(n, "i32")}) {
378
+ let flatIndex = getOutputIndexFromCoords(${t}(${e.join(", ")}));
379
+ setOutputAtIndexI32(flatIndex${n === 1 ? "" : ` / ${n}`}, value);
380
+ }
381
+ `;
382
+ }
383
+ return a;
384
+ }
385
+ function ie(e) {
386
+ return e = e.replace(/(\w+)\s*:\s*vec(5|6)/g, (e) => "@align(16) " + e), e = e.replace(/vec(5|6)\s*,\s*(\w+)/g, (e, t, n) => `vec${t}, @align(16) ${n}`), e;
387
+ }
388
+ function L(e) {
389
+ return !(e.dispatchLayout.hasOwnProperty("y") && e.dispatchLayout.y.length !== 0 || e.dispatchLayout.hasOwnProperty("z") && e.dispatchLayout.z.length !== 0);
390
+ }
391
+ // node_modules/@tensorflow/tfjs-backend-webgpu/dist/webgpu_util.js
392
+ var R = (e) => {
393
+ let t = 1;
394
+ for (let n = 0; n < e.length; n++) t *= e[n];
395
+ return t;
396
+ };
397
+ function z(e, t, n = [
398
+ 1,
399
+ 1,
400
+ 1
401
+ ], r = [
402
+ 1,
403
+ 1,
404
+ 1
405
+ ]) {
406
+ let [i, a, o] = [
407
+ Math.ceil(R(e.x.map((e) => t[e])) / (n[0] * r[0])),
408
+ e.y ? Math.ceil(R(e.y.map((e) => t[e])) / (n[1] * r[1])) : 1,
409
+ e.z ? Math.ceil(R(e.z.map((e) => t[e])) / (n[2] * r[2])) : 1
410
+ ];
411
+ return [
412
+ i,
413
+ a,
414
+ o
415
+ ];
416
+ }
417
+ function B(e, t, n, r = !1) {
418
+ let i = [
419
+ 8,
420
+ 8,
421
+ 1
422
+ ], a = [
423
+ 4,
424
+ 4,
425
+ 1
426
+ ];
427
+ return r || (e <= 8 && (a[1] = 1), t <= 16 && n <= 16 && (i[0] = 4)), {
428
+ workgroupSize: i,
429
+ elementsPerThread: a
430
+ };
431
+ }
432
+ function V(e, t, n = !1) {
433
+ if (n) return [
434
+ 8,
435
+ 8,
436
+ 1
437
+ ];
438
+ let r = R(e.x.map((e) => t[e])), i = R(e.y.map((e) => t[e]));
439
+ return r <= 4 ? [
440
+ 4,
441
+ 16,
442
+ 1
443
+ ] : i <= 4 ? [
444
+ 16,
445
+ 4,
446
+ 1
447
+ ] : [
448
+ 16,
449
+ 16,
450
+ 1
451
+ ];
452
+ }
453
+ function H(e, t, n = !1) {
454
+ if (n) return [
455
+ 4,
456
+ 4,
457
+ 1
458
+ ];
459
+ let r = R(e.x.map((e) => t[e])), i = R(e.y.map((e) => t[e]));
460
+ return r <= 4 ? [
461
+ 1,
462
+ 2,
463
+ 1
464
+ ] : i <= 4 ? [
465
+ 2,
466
+ 1,
467
+ 1
468
+ ] : [
469
+ 2,
470
+ 2,
471
+ 1
472
+ ];
473
+ }
474
+ function U(e) {
475
+ return { x: e.map((e, t) => t) };
476
+ }
477
+ function W(e) {
478
+ if (e === "float32" || e === "int32" || e === "bool" || e === "string" || e === "packedF16") return 4;
479
+ if (e === "complex64") return 8;
480
+ throw Error(`Unknown dtype ${e}`);
481
+ }
482
+ function G() {
483
+ return !!(typeof globalThis < "u" && globalThis.navigator && globalThis.navigator.gpu);
484
+ }
485
+ function K(e, n) {
486
+ Array.isArray(e) || (e = [e]), e.forEach((e) => {
487
+ e != null && t(e.dtype !== "complex64", () => `${n} does not support complex64 tensors in the WebGPU backend.`);
488
+ });
489
+ }
490
+ var q;
491
+ (function(e) {
492
+ e[e.MatMulReduceProgram = 0] = "MatMulReduceProgram", e[e.MatMulSplitKProgram = 1] = "MatMulSplitKProgram", e[e.MatMulSmallOutputSizeProgram = 2] = "MatMulSmallOutputSizeProgram", e[e.MatMulPackedProgram = 3] = "MatMulPackedProgram", e[e.MatMulMax = 4] = "MatMulMax";
493
+ })(q ||= {});
494
+ // node_modules/@tensorflow/tfjs-backend-webgpu/dist/flags_webgpu.js
495
+ var J = l();
496
+ J.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE", () => 15), J.registerFlag("WEBGPU_CPU_FORWARD", () => !0), J.registerFlag("WEBGPU_MATMUL_PROGRAM_TYPE", () => -1), J.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE", () => !0), J.registerFlag("WEBGPU_USE_LOW_POWER_GPU", () => !1), J.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD", () => 1e3), J.registerFlag("WEBGPU_USE_PROFILE_TOOL", () => !1), J.registerFlag("WEBGPU_IMPORT_EXTERNAL_TEXTURE", () => !0), J.registerFlag("WEBGPU_USE_NAIVE_CONV2D_DEBUG", () => !1), J.registerFlag("WEBGPU_THRESHOLD_TO_INCREASE_WORKGROUPS_FOR_MATMUL", () => -1), J.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER", () => !1), J.registerFlag("WEBGPU_PRINT_SHADER", () => ""), J.registerFlag("WEBGPU_ENGINE_COMPILE_ONLY", () => !1);
497
+ // node_modules/@tensorflow/tfjs-backend-webgpu/dist/adapter_info.js
498
+ var ae = class {
499
+ constructor(e) {
500
+ e && (this.vendor = e.vendor, this.architecture = e.architecture, this.intelGPUGeneration = this.getIntelGPUGeneration());
501
+ }
502
+ getIntelGPUGeneration() {
503
+ if (this.isIntel()) {
504
+ if (this.architecture.startsWith("gen")) return Number(this.architecture.match(/\d+/));
505
+ if (this.architecture.startsWith("xe")) return 12;
506
+ }
507
+ return 0;
508
+ }
509
+ isIntel() {
510
+ return this.vendor === "intel";
511
+ }
512
+ }, Y = class {
513
+ constructor(e) {
514
+ this.device = e, this.numUsedBuffers = 0, this.numFreeBuffers = 0, this.freeBuffers = /* @__PURE__ */ new Map(), this.usedBuffers = /* @__PURE__ */ new Map(), this.numBytesUsed = 0, this.numBytesAllocated = 0;
515
+ }
516
+ acquireBuffer(e, t, n = !1, r = !0) {
517
+ let i, a = X(e, t);
518
+ return r ? (this.freeBuffers.has(a) || this.freeBuffers.set(a, []), this.freeBuffers.get(a).length > 0 ? (i = this.freeBuffers.get(a).pop(), this.numFreeBuffers--) : (i = this.device.createBuffer({
519
+ size: e,
520
+ usage: t,
521
+ mappedAtCreation: n
522
+ }), this.numBytesAllocated += e)) : (i = this.device.createBuffer({
523
+ size: e,
524
+ usage: t,
525
+ mappedAtCreation: n
526
+ }), this.numBytesAllocated += e), this.usedBuffers.has(a) || this.usedBuffers.set(a, []), this.usedBuffers.get(a).push(i), this.numUsedBuffers++, this.numBytesUsed += e, i;
527
+ }
528
+ releaseBuffer(e, t = !0) {
529
+ if (this.freeBuffers.size === 0) return;
530
+ let n = e.size, r = e.usage, i = X(n, r), a = this.usedBuffers.get(i), o = a.indexOf(e);
531
+ if (o < 0) throw Error("Cannot find the buffer in buffer manager");
532
+ a[o] = a[a.length - 1], a.pop(), this.numUsedBuffers--, this.numBytesUsed -= n, t ? (this.freeBuffers.get(i).push(e), this.numFreeBuffers++) : (e.destroy(), this.numBytesAllocated -= n);
533
+ }
534
+ getNumUsedBuffers() {
535
+ return this.numUsedBuffers;
536
+ }
537
+ getNumFreeBuffers() {
538
+ return this.numFreeBuffers;
539
+ }
540
+ dispose() {
541
+ this.freeBuffers.forEach((e, t) => {
542
+ e.forEach((e) => {
543
+ e.destroy();
544
+ });
545
+ }), this.usedBuffers.forEach((e, t) => {
546
+ e.forEach((e) => {
547
+ e.destroy();
548
+ });
549
+ }), this.freeBuffers = /* @__PURE__ */ new Map(), this.usedBuffers = /* @__PURE__ */ new Map(), this.numUsedBuffers = 0, this.numFreeBuffers = 0, this.numBytesUsed = 0, this.numBytesAllocated = 0;
550
+ }
551
+ };
552
+ function X(e, t) {
553
+ return `${e}_${t}`;
554
+ }
555
+ // node_modules/@tensorflow/tfjs-backend-webgpu/dist/texture_manager.js
556
+ var oe = class {
557
+ constructor(e) {
558
+ this.device = e, this.numUsedTextures = 0, this.numFreeTextures = 0, this.freeTextures = /* @__PURE__ */ new Map(), this.usedTextures = /* @__PURE__ */ new Map(), this.numBytesUsed = 0, this.numBytesAllocated = 0;
559
+ }
560
+ acquireTexture(e, t, n, r) {
561
+ let i = Q(n), a = e * t * i, o = Z(e, t, n, r);
562
+ if (this.freeTextures.has(o) || this.freeTextures.set(o, []), this.usedTextures.has(o) || this.usedTextures.set(o, []), this.numBytesUsed += a, this.numUsedTextures++, this.freeTextures.get(o).length > 0) {
563
+ this.numFreeTextures--;
564
+ let e = this.freeTextures.get(o).shift();
565
+ return this.usedTextures.get(o).push(e), e;
566
+ }
567
+ this.numBytesAllocated += a;
568
+ let s = this.device.createTexture({
569
+ size: [e, t],
570
+ format: n,
571
+ usage: r
572
+ });
573
+ return this.usedTextures.get(o).push(s), s;
574
+ }
575
+ releaseTexture(e) {
576
+ if (this.freeTextures.size === 0) return;
577
+ let t = e.width, n = e.height, r = e.format, i = e.usage, a = Z(t, n, r, i);
578
+ this.freeTextures.has(a) || this.freeTextures.set(a, []), this.freeTextures.get(a).push(e), this.numFreeTextures++, this.numUsedTextures--;
579
+ let o = this.usedTextures.get(a), s = o.indexOf(e);
580
+ if (s < 0) throw Error("Cannot release a texture that was never provided by this texture manager");
581
+ o.splice(s, 1);
582
+ let c = Q(r), l = t * n * c;
583
+ this.numBytesUsed -= l;
584
+ }
585
+ getNumUsedTextures() {
586
+ return this.numUsedTextures;
587
+ }
588
+ getNumFreeTextures() {
589
+ return this.numFreeTextures;
590
+ }
591
+ dispose() {
592
+ this.freeTextures.forEach((e, t) => {
593
+ e.forEach((e) => {
594
+ e.destroy();
595
+ });
596
+ }), this.usedTextures.forEach((e, t) => {
597
+ e.forEach((e) => {
598
+ e.destroy();
599
+ });
600
+ }), this.freeTextures = /* @__PURE__ */ new Map(), this.usedTextures = /* @__PURE__ */ new Map(), this.numUsedTextures = 0, this.numFreeTextures = 0, this.numBytesUsed = 0, this.numBytesAllocated = 0;
601
+ }
602
+ };
603
+ function Z(e, t, n, r) {
604
+ return `${e}_${t}_${n}_${r}`;
605
+ }
606
+ function Q(e) {
607
+ if (e === "rgba8unorm") return 16;
608
+ throw Error(`${e} is not supported!`);
609
+ }
610
+ // node_modules/@tensorflow/tfjs-backend-webgpu/dist/backend_webgpu.js
611
+ var se = l().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"), ce = (e, n) => {
612
+ let r = e.limits.maxComputeWorkgroupsPerDimension, i = n.dispatchLayout, a = n.dispatch;
613
+ if (a.every((e) => e <= r)) return a;
614
+ t(a[0] > r && i.y === void 0 && i.z === void 0, () => "Dispatch size exceeds WebGPU limits in Y or Z dimension.");
615
+ let o = Math.ceil(Math.sqrt(a[0]));
616
+ return o > r ? (o = Math.ceil(Math.cbrt(a[0])), t(o <= r, () => "Total dispatch size exceeds WebGPU maximum."), [
617
+ o,
618
+ o,
619
+ o
620
+ ]) : [
621
+ o,
622
+ o,
623
+ 1
624
+ ];
625
+ }, $ = class n extends f {
626
+ nextDataId() {
627
+ return n.nextDataId++;
628
+ }
629
+ constructor(e, t) {
630
+ if (super(), this.commandQueueOwnedIds = /* @__PURE__ */ new WeakSet(), this.dispatchCountInPass = 0, this.disposed = !1, this.downloadWaitMs = 0, this.tensorDataPendingDisposal = [], this.queryResolveBuffer = null, this.querySet = null, this.querySetCount = 2, this.stagingPendingDisposal = [], this.uniformPendingDisposal = [], this.uploadWaitMs = 0, this.hasReadSyncWarned = !1, this.hasTimestampQueryWarned = !1, !G()) throw Error("WebGPU is not supported on this device");
631
+ this.pipelineCache = {}, this.device = e, this.queue = e.queue, this.commandEncoder = null, this.computePassEncoder = null, this.adapterInfo = new ae(t), this.supportTimestampQuery = this.device.features.has("timestamp-query"), this.thresholdToIncreaseWorkgroups = this.adapterInfo.intelGPUGeneration >= 12 ? 16 : 8, this.bufferManager = new Y(this.device), this.textureManager = new oe(this.device), this.tensorMap = new h(this, d()), l().getBool("WEBGPU_USE_PROFILE_TOOL") && (this.dummyCanvas = document.createElement("canvas"), this.dummyCanvas.width = 1, this.dummyCanvas.height = 1, this.dummyContext = this.dummyCanvas.getContext("webgpu"), this.dummyContext.configure({
632
+ device: e,
633
+ format: "bgra8unorm"
634
+ }), document.body.appendChild(this.dummyCanvas));
635
+ }
636
+ floatPrecision() {
637
+ return 32;
638
+ }
639
+ disposeData(e, t = !1) {
640
+ if (!this.tensorMap.has(e)) return !0;
641
+ let n = this.tensorMap.get(e);
642
+ return t ? n.refCount = 0 : n.refCount--, n.refCount > 0 ? !1 : (n.complexTensorInfos != null && (this.disposeData(n.complexTensorInfos.real.dataId), this.disposeData(n.complexTensorInfos.imag.dataId)), this.commandQueueOwnedIds.has(e) ? (this.tensorDataPendingDisposal.push(e), !0) : (this.releaseResource(e), this.tensorMap.delete(e), !0));
643
+ }
644
+ memory() {
645
+ return {
646
+ numBytesInGPU: this.bufferManager.numBytesUsed,
647
+ numBytesAllocatedInGPU: this.bufferManager.numBytesAllocated,
648
+ unreliable: !1
649
+ };
650
+ }
651
+ releaseResource(e) {
652
+ let t = this.tensorMap.get(e);
653
+ t && t.resource && (t.external || (t.resource instanceof GPUBuffer ? this.bufferManager.releaseBuffer(t.resource) : t.resource instanceof GPUTexture && this.textureManager.releaseTexture(t.resource)), t.resource = null);
654
+ }
655
+ refCount(e) {
656
+ return this.tensorMap.has(e) ? this.tensorMap.get(e).refCount : 0;
657
+ }
658
+ incRef(e) {
659
+ let t = this.tensorMap.get(e);
660
+ t.refCount++;
661
+ }
662
+ decRef(e) {
663
+ if (this.tensorMap.has(e)) {
664
+ let t = this.tensorMap.get(e);
665
+ t.refCount--;
666
+ }
667
+ }
668
+ write(e, t, n) {
669
+ if (n === "complex64" && e != null) throw Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
670
+ let r = { id: this.nextDataId() };
671
+ return this.tensorMap.set(r, {
672
+ dtype: n,
673
+ shape: t,
674
+ values: e,
675
+ refCount: 1
676
+ }), r;
677
+ }
678
+ move(e, t, n, r, i) {
679
+ if (r === "complex64") throw Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");
680
+ this.tensorMap.set(e, {
681
+ dtype: r,
682
+ shape: n,
683
+ values: t,
684
+ refCount: i
685
+ });
686
+ }
687
+ submitQueue() {
688
+ this.queue.submit([this.commandEncoder.finish()]), this.commandEncoder = null, this.dispatchCountInPass = 0, this.commandQueueOwnedIds = /* @__PURE__ */ new WeakSet(), this.tensorDataPendingDisposal.forEach((e) => {
689
+ this.releaseResource(e), this.tensorMap.delete(e);
690
+ }), this.uniformPendingDisposal.forEach((e) => this.bufferManager.releaseBuffer(e)), this.stagingPendingDisposal.forEach((e) => this.bufferManager.releaseBuffer(e, !1)), this.tensorDataPendingDisposal = [], this.uniformPendingDisposal = [], this.stagingPendingDisposal = [];
691
+ }
692
+ ensureCommandEncoderReady() {
693
+ this.commandEncoder ||= this.device.createCommandEncoder();
694
+ }
695
+ endComputePassEncoder() {
696
+ this.computePassEncoder &&= (this.computePassEncoder.end(), null);
697
+ }
698
+ async checkCompileCompletionAsync() {
699
+ let e;
700
+ try {
701
+ e = await Promise.all(Object.values(this.pipelineCache));
702
+ } catch (e) {
703
+ throw Error(e.message);
704
+ }
705
+ Object.keys(this.pipelineCache).map((t, n) => {
706
+ this.pipelineCache[t] = e[n];
707
+ });
708
+ }
709
+ async getBufferData(e) {
710
+ if (l().getBool("WEBGPU_ENGINE_COMPILE_ONLY")) return console.warn("The data may be invalid since WEBGPU_ENGINE_COMPILE_ONLY is true, this can only be called when WEBGPU_ENGINE_COMPILE_ONLY is false"), null;
711
+ let n = e.size, r = this.bufferManager.acquireBuffer(n, GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ);
712
+ this.ensureCommandEncoderReady(), this.endComputePassEncoder(), this.commandEncoder.copyBufferToBuffer(e, 0, r, 0, n), this.submitQueue(), await r.mapAsync(GPUMapMode.READ);
713
+ let i = r.getMappedRange().slice(0);
714
+ return r.unmap(), r != null && this.bufferManager.releaseBuffer(r), l().getBool("WEBGPU_USE_PROFILE_TOOL") && (t(this.dummyContext !== void 0, () => "Fail to get context for profiling tool"), this.dummyContext.getCurrentTexture()), i;
715
+ }
716
+ convertAndCacheOnCPU(e, t) {
717
+ let n = this.tensorMap.get(e);
718
+ return n.values = t, n.values;
719
+ }
720
+ readSync(e) {
721
+ let n = this.tensorMap.get(e), { values: r, complexTensorInfos: i } = n;
722
+ if (r != null || n.dtype === "string") return r;
723
+ if (n.dtype === "complex64") {
724
+ let t = this.readSync(i.real.dataId), n = this.readSync(i.imag.dataId), r = s(m(t, n).buffer, "float32");
725
+ return this.convertAndCacheOnCPU(e, r), r;
726
+ }
727
+ this.hasReadSyncWarned || (this.hasReadSyncWarned = !0, console.warn("The performance of synchronously reading data from GPU to CPU is poor on the webgpu backend, please use asynchronous APIs instead."));
728
+ let a = ["opaque", "premultiplied"], o = n.resource, c = o.size;
729
+ t(c % 4 == 0, () => "Because there is 4 bytes for one pixel, buffer size must be multiple of 4.");
730
+ let l = c / 4, u = new ArrayBuffer(c), d = a.map((e) => new OffscreenCanvas(256, 256)), f = new OffscreenCanvas(256, 256);
731
+ this.endComputePassEncoder(), d.map((e, t) => {
732
+ let n = e.getContext("webgpu");
733
+ return n.configure({
734
+ device: this.device,
735
+ format: "bgra8unorm",
736
+ usage: GPUTextureUsage.COPY_DST,
737
+ alphaMode: a[t]
738
+ }), n.getCurrentTexture();
739
+ }).map((e, t) => {
740
+ let n = (n, r, i) => {
741
+ this.ensureCommandEncoderReady(), this.commandEncoder.copyBufferToTexture({
742
+ buffer: o,
743
+ bytesPerRow: 1024,
744
+ offset: i
745
+ }, { texture: e }, {
746
+ width: n,
747
+ height: r
748
+ }), this.submitQueue();
749
+ let s = f.getContext("2d", { willReadFrequently: !0 });
750
+ s.clearRect(0, 0, n, r), s.drawImage(d[t], 0, 0);
751
+ let c = s.getImageData(0, 0, n, r).data, l = a[t], p = new Uint8ClampedArray(u, i, n * r * 4);
752
+ for (let e = 0; e < p.length; e += 4) if (l === "premultiplied") p[e + 3] = c[e + 3];
753
+ else {
754
+ let t = c[e];
755
+ p[e] = c[e + 2], p[e + 1] = c[e + 1], p[e + 2] = t;
756
+ }
757
+ }, r = Math.floor(l / 65536), i = 256, s = 256, c = 0;
758
+ for (let e = 0; e < r; e++) n(i, s, c), c += 262144;
759
+ let p = l % 65536;
760
+ s = Math.floor(p / 256), s > 0 && (n(i, s, c), c += s * 1024), i = p % 256, i > 0 && n(i, 1, c);
761
+ });
762
+ let p = s(u, n.dtype);
763
+ return this.convertAndCacheOnCPU(e, p), p;
764
+ }
765
+ async read(e) {
766
+ if (!this.tensorMap.has(e)) throw Error(`Tensor ${e} was not registered!`);
767
+ let t = this.tensorMap.get(e), { values: n } = t;
768
+ if (n != null) return n;
769
+ let r;
770
+ if (t.dtype === "complex64") {
771
+ let e = await Promise.all([this.read(t.complexTensorInfos.real.dataId), this.read(t.complexTensorInfos.imag.dataId)]), n = e[0], i = e[1];
772
+ r = m(n, i);
773
+ } else {
774
+ let e = await this.getBufferData(t.resource);
775
+ r = s(e, t.dtype);
776
+ }
777
+ return this.convertAndCacheOnCPU(e, r), r;
778
+ }
779
+ copyBuffer(e) {
780
+ let t = e.size, n = e.usage, r = this.bufferManager.acquireBuffer(t, n);
781
+ return this.ensureCommandEncoderReady(), this.endComputePassEncoder(), this.commandEncoder.copyBufferToBuffer(e, 0, r, 0, t), this.submitQueue(), r;
782
+ }
783
+ createTensorFromGPUData(e, t, n) {
784
+ let r = e.buffer;
785
+ if (n === "complex64") throw Error("Cannot write to a complex64 dtype. ");
786
+ let i = { id: this.nextDataId() };
787
+ this.tensorMap.set(i, {
788
+ dtype: n,
789
+ shape: t,
790
+ values: null,
791
+ refCount: 1,
792
+ external: e.zeroCopy
793
+ });
794
+ let a = this.tensorMap.get(i), o = W(a.dtype) * g(a.shape);
795
+ if (e.buffer.size < o) throw Error(`GPUBuffer size(${e.buffer.size}) is smaller than tensor size(${o})!`);
796
+ if ((e.buffer.usage & (GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC)) !== (GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC)) throw Error("GPUBuffer.usage should include GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC!");
797
+ return e.zeroCopy !== !0 && (r = this.copyBuffer(r)), a.resource = r, d().makeTensorFromDataId(i, t, n, this);
798
+ }
799
+ readToGPU(e) {
800
+ let { values: t, dtype: n, shape: r, resource: i } = this.tensorMap.get(e);
801
+ if (n === "complex64") throw Error("Does not support reading buffer for complex64 dtype.");
802
+ if (i == null) throw Error(t == null ? "There is no data on GPU or CPU." : "Data is not on GPU but on CPU.");
803
+ let a = i, o = a.size, s = a.usage, c = this.bufferManager.acquireBuffer(o, s);
804
+ this.ensureCommandEncoderReady(), this.endComputePassEncoder(), this.commandEncoder.copyBufferToBuffer(i, 0, c, 0, o), this.submitQueue();
805
+ let l = this.makeTensorInfo(r, n), u = d().makeTensorFromTensorInfo(l), f = this.tensorMap.get(l.dataId);
806
+ return f.resource = c, {
807
+ tensorRef: u,
808
+ buffer: c
809
+ };
810
+ }
811
+ bufferSync(e) {
812
+ let t = this.readSync(e.dataId);
813
+ if (e.dtype === "string") try {
814
+ let n = t.map((e) => c(e));
815
+ return r(e.shape, e.dtype, n);
816
+ } catch {
817
+ throw Error("Failed to decode encoded string bytes into utf-8");
818
+ }
819
+ return r(e.shape, e.dtype, t);
820
+ }
821
+ async time(e) {
822
+ !this.supportTimestampQuery && !this.hasTimestampQueryWarned && (console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --enable-dawn-features=allow_unsafe_apis to try it again. Otherwise, zero will be shown for the kernel time when profiling mode is enabled."), this.hasTimestampQueryWarned = !0);
823
+ let t = this.activeTimers, n = [], r = !1;
824
+ this.programTimersStack == null ? (this.programTimersStack = n, r = !0) : this.activeTimers.push(n), this.activeTimers = n, e();
825
+ let i = _(this.activeTimers.map((e) => e.query)).filter((e) => e != null), a = _(this.activeTimers.map((e) => e.name)).filter((e) => e != null);
826
+ this.activeTimers = t, r && (this.programTimersStack = null);
827
+ let o = {
828
+ uploadWaitMs: this.uploadWaitMs,
829
+ downloadWaitMs: this.downloadWaitMs,
830
+ kernelMs: null,
831
+ wallMs: null
832
+ }, s = await Promise.all(i);
833
+ return o.kernelMs = p(s), o.getExtraProfileInfo = () => s.map((e, t) => ({
834
+ name: a[t],
835
+ ms: e
836
+ })).map((e) => `${e.name}: ${e.ms}`).join(", "), this.uploadWaitMs = 0, this.downloadWaitMs = 0, o;
837
+ }
838
+ makeTensorInfo(t, n, r) {
839
+ return n === "string" && r != null && r.length > 0 && u(r[0]) && (r = r.map((t) => e(t))), {
840
+ dataId: this.write(r, t, n),
841
+ shape: t,
842
+ dtype: n
843
+ };
844
+ }
845
+ tensorToBinding(e) {
846
+ if (!e) return null;
847
+ let t = this.tensorMap.get(e.dataId).resource;
848
+ return t instanceof GPUBuffer ? { buffer: t } : t instanceof GPUTexture ? t.createView() : t;
849
+ }
850
+ uploadToGPU(e) {
851
+ let t = this.tensorMap.get(e);
852
+ if (t.resource != null) return;
853
+ let n = W(t.dtype) * g(t.shape), r, i = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
854
+ if (t.values) {
855
+ if (r = this.bufferManager.acquireBuffer(n, i, !0), r.mapState === "unmapped") {
856
+ let e = this.bufferManager.acquireBuffer(n, GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC, !0, !1), i = e.getMappedRange();
857
+ t.dtype === "int32" || t.dtype === "packedF16" || t.dtype === "bool" ? new Int32Array(i).set(t.values) : new Float32Array(i).set(t.values), e.unmap(), this.ensureCommandEncoderReady(), this.endComputePassEncoder(), this.commandEncoder.copyBufferToBuffer(e, 0, r, 0, n), this.stagingPendingDisposal.push(e);
858
+ } else {
859
+ let e = r.getMappedRange();
860
+ t.dtype === "int32" || t.dtype === "packedF16" || t.dtype === "bool" ? new Int32Array(e).set(t.values) : new Float32Array(e).set(t.values), r.unmap();
861
+ }
862
+ t.values = null;
863
+ } else r = this.bufferManager.acquireBuffer(n, i);
864
+ t.resource = r;
865
+ }
866
+ makeUniforms(e) {
867
+ let n = 0, r = 0, i = [], a = 1;
868
+ e.forEach((e) => {
869
+ e.data.length === 0 && (e.data = [1]);
870
+ let o;
871
+ switch (e.data.length) {
872
+ case 1:
873
+ o = 4;
874
+ break;
875
+ case 2:
876
+ o = 8;
877
+ break;
878
+ case 3:
879
+ o = 16;
880
+ break;
881
+ case 4:
882
+ o = 16;
883
+ break;
884
+ case 5:
885
+ o = 16;
886
+ break;
887
+ case 6:
888
+ o = 16;
889
+ break;
890
+ default: t(!1, () => `Unsupported ${e.data.length}D shape`);
891
+ }
892
+ (r === 5 || r === 6) && (o = 16), o > a && (a = o), n = Math.ceil(n / o) * o, r = e.data.length, i.push(n), n += e.data.length * 4;
893
+ }), n = Math.ceil(n / a) * a;
894
+ let o = new ArrayBuffer(n);
895
+ e.forEach((e, t) => {
896
+ let n = i[t];
897
+ e.type === "int32" ? new Int32Array(o, n, e.data.length).set(e.data) : e.type === "uint32" ? new Uint32Array(o, n, e.data.length).set(e.data) : new Float32Array(o, n, e.data.length).set(e.data);
898
+ });
899
+ let s = this.bufferManager.acquireBuffer(n, GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM);
900
+ return this.queue.writeBuffer(s, 0, o, 0, n), this.uniformPendingDisposal.push(s), {
901
+ offset: 0,
902
+ size: n,
903
+ buffer: s
904
+ };
905
+ }
906
+ runWebGPUProgram(e, t, n, r, a) {
907
+ if (a ||= this.makeTensorInfo(e.outputShape, n), g(a.shape) === 0) return this.tensorMap.get(a.dataId).values = i(a.dtype, 0), a;
908
+ this.uploadToGPU(a.dataId), e.dispatch = ce(this.device, e);
909
+ let o = t.map((t, n) => {
910
+ if (t.dtype === "complex64") throw Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");
911
+ return this.uploadToGPU(t.dataId), {
912
+ dtype: this.tensorMap.get(t.dataId).dtype,
913
+ shape: t.shape,
914
+ name: e.variableNames[n]
915
+ };
916
+ });
917
+ e.shaderKey = O(e, o, a);
918
+ let s = l().getBool("WEBGPU_ENGINE_COMPILE_ONLY");
919
+ return e.shaderKey in this.pipelineCache || (this.pipelineCache[e.shaderKey] = b(this.device, e, o, a, s)), e.pipeline = this.pipelineCache[e.shaderKey], s || this.recordAndSubmit(e, a, t, r), a;
920
+ }
921
+ recordAndSubmit(e, t, n, r) {
922
+ if (e.pipeline instanceof Promise) throw Error("Please call checkCompileCompletionAsync to ensure parallel compilation is done!");
923
+ let i = [], a = [], s = "int32";
924
+ if (e.pixelsOpType == null) {
925
+ i.push({
926
+ type: "float32",
927
+ data: [NaN]
928
+ }, {
929
+ type: "float32",
930
+ data: [Infinity]
931
+ }), a = n.concat(t).map((e) => e.shape);
932
+ let e = "int32";
933
+ a.map((t) => {
934
+ i.push({
935
+ type: e,
936
+ data: t
937
+ });
938
+ let n = o(t);
939
+ i.push({
940
+ type: e,
941
+ data: n
942
+ });
943
+ });
944
+ } else {
945
+ let e = o(t.shape);
946
+ i.push({
947
+ type: s,
948
+ data: e
949
+ });
950
+ }
951
+ if (e.size) {
952
+ let t = g(e.outputShape);
953
+ i.push({
954
+ type: s,
955
+ data: [e.outputComponent ? t / e.outputComponent : t]
956
+ });
957
+ }
958
+ r && (i = [...i, ...r]);
959
+ let c = [
960
+ this.tensorToBinding(t),
961
+ ...n.map((e) => this.tensorToBinding(e)),
962
+ this.makeUniforms(i)
963
+ ];
964
+ n.forEach((e) => {
965
+ this.commandQueueOwnedIds.add(e.dataId);
966
+ }), this.commandQueueOwnedIds.add(t.dataId);
967
+ let u = this.device.createBindGroup({
968
+ layout: e.pipeline.getBindGroupLayout(0),
969
+ entries: c.map((e, t) => ({
970
+ binding: t,
971
+ resource: e
972
+ }))
973
+ }), d = this.activeTimers != null;
974
+ this.ensureCommandEncoderReady();
975
+ let f = {};
976
+ d && this.supportTimestampQuery ? (this.endComputePassEncoder(), this.querySet ??= this.device.createQuerySet({
977
+ type: "timestamp",
978
+ count: this.querySetCount
979
+ }), f.timestampWrites = {
980
+ querySet: this.querySet,
981
+ beginningOfPassWriteIndex: 0,
982
+ endOfPassWriteIndex: 1
983
+ }, this.computePassEncoder = this.commandEncoder.beginComputePass(f)) : this.computePassEncoder ||= this.commandEncoder.beginComputePass(f), this.computePassEncoder.setPipeline(e.pipeline), this.computePassEncoder.setBindGroup(0, u), this.computePassEncoder.dispatchWorkgroups(e.dispatch[0], e.dispatch[1], e.dispatch[2]), this.dispatchCountInPass++, (d || l().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE") <= this.dispatchCountInPass || e.pixelsOpType === y.DRAW) && (this.endComputePassEncoder(), d ? this.activeTimers.push({
984
+ name: e.constructor.name,
985
+ query: this.getQueryTime()
986
+ }) : this.submitQueue());
987
+ }
988
+ async getQueryTime() {
989
+ if (!this.supportTimestampQuery) return 0;
990
+ this.queryResolveBuffer ??= this.bufferManager.acquireBuffer(this.querySetCount * 8, GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST | GPUBufferUsage.QUERY_RESOLVE), this.commandEncoder.resolveQuerySet(this.querySet, 0, this.querySetCount, this.queryResolveBuffer, 0);
991
+ let e = this.bufferManager.acquireBuffer(this.querySetCount * 8, GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST);
992
+ this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer, 0, e, 0, this.querySetCount * 8), this.submitQueue(), await e.mapAsync(GPUMapMode.READ);
993
+ let t = new BigUint64Array(e.getMappedRange()), n = Number(t[1] - t[0]) / 1e6;
994
+ return e.unmap(), this.bufferManager.releaseBuffer(e), n;
995
+ }
996
+ shouldExecuteOnCPU(e, t = se) {
997
+ return l().getBool("WEBGPU_CPU_FORWARD") && e.every((e) => this.tensorMap.get(e.dataId).resource == null && g(e.shape) < t);
998
+ }
999
+ numDataIds() {
1000
+ return this.tensorMap.numDataIds() - this.tensorDataPendingDisposal.length;
1001
+ }
1002
+ dispose() {
1003
+ this.disposed ||= (this.querySet != null && this.querySet.destroy(), this.bufferManager.dispose(), this.textureManager.dispose(), !0);
1004
+ }
1005
+ };
1006
+ $.nextDataId = 0;
1007
+ export { O as _, H as a, v as b, U as c, I as d, S as f, E as g, w as h, z as i, G as l, C as m, q as n, B as o, A as p, K as r, V as s, $ as t, y as u, x as v, ee as y };