@genai-fi/nanogpt 1.4.1 → 1.6.0

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 (341) hide show
  1. package/dist/{DatasetBuilder-DU1G1OKX.js → DatasetBuilder-DRDW8tcM.js} +85 -86
  2. package/dist/Generator-BcR_14Cj.js +316 -0
  3. package/dist/{RealDiv-CSnvtN2E.js → RealDiv-Cl8k3YTx.js} +54 -62
  4. package/dist/{Reshape-BlylqwWy.js → Reshape-CKxKPKqi.js} +9 -12
  5. package/dist/Reshape-H5zZRgr9.js +16 -0
  6. package/dist/RoPECache-dYscFINl.js +722 -0
  7. package/dist/TeachableLLM.js +29 -34
  8. package/dist/api/beamer.d.ts +1 -0
  9. package/dist/api/beamer.js +19 -10
  10. package/dist/api/responses.js +11 -12
  11. package/dist/api/training.js +12 -14
  12. package/dist/axis_util-rF9RnwKE.js +37 -0
  13. package/dist/backend.js +5 -6
  14. package/dist/{backend_util-DAV0I34P.js → backend_util-Cpp0Gwlp.js} +180 -185
  15. package/dist/{binary_op_util-CrYk9LXL.js → binary_op_util-WY9YIl0q.js} +3 -7
  16. package/dist/broadcast_to-CGvLNiQ0.js +20 -0
  17. package/dist/checks/appendCache.js +7 -7
  18. package/dist/checks/attentionMask.js +9 -8
  19. package/dist/checks/check.js +1 -2
  20. package/dist/checks/gelu.js +6 -6
  21. package/dist/checks/index.js +24 -25
  22. package/dist/checks/matMulGelu.js +7 -7
  23. package/dist/checks/normRMS.js +14 -12
  24. package/dist/checks/normRMSGrad.js +9 -8
  25. package/dist/checks/packUnpack.js +7 -7
  26. package/dist/checks/qkv.js +1 -34
  27. package/dist/checks/rope.js +6 -6
  28. package/dist/checks/weights.js +1 -2
  29. package/dist/clip_by_value-D-UX9am5.js +13 -0
  30. package/dist/complex-Cl904TqN.js +13 -0
  31. package/dist/{complex_util-CkazZsaH.js → complex_util-BBlPAm-s.js} +1 -2
  32. package/dist/concat-Oip5acVY.js +14 -0
  33. package/dist/{concat_util-CWzvQQlK.js → concat_util-CY45Hf4F.js} +2 -3
  34. package/dist/data/docx.js +3 -4
  35. package/dist/data/pdf.js +11 -14
  36. package/dist/data/stream.js +1 -2
  37. package/dist/data/textLoader.js +16 -15
  38. package/dist/data-CV_i_H6B.js +11 -0
  39. package/dist/data.js +5 -12
  40. package/dist/dist-CMMLi-qO.js +2675 -0
  41. package/dist/{dist-BGVm64AY.js → dist-DeVH1nGn.js} +1465 -1573
  42. package/dist/{dist-CwK5S7Ls.js → dist-DyL7qSLJ.js} +2664 -2400
  43. package/dist/dropout16-CA31Ud5a.js +20 -0
  44. package/dist/dropout_util-SiFMbFXz.js +22 -0
  45. package/dist/{eventemitter3-D_qV3Lof.js → eventemitter3-wmfmOP_f.js} +2 -3
  46. package/dist/expand_dims-Dh3Fulyn.js +10 -0
  47. package/dist/floor-BwjmUb7X.js +8 -0
  48. package/dist/gather-B5Z1RFt5.js +14 -0
  49. package/dist/gatherSub-CRUfUzBa.js +22 -0
  50. package/dist/gelu-Xx9-ohH9.js +25 -0
  51. package/dist/{gpgpu_math-20tPK8LM.js → gpgpu_math-48m8q3jI.js} +265 -286
  52. package/dist/inference/Beamer.d.ts +14 -2
  53. package/dist/inference/Beamer.js +170 -105
  54. package/dist/inference/Generator.js +1 -259
  55. package/dist/inference/tokenisePrompt.d.ts +2 -1
  56. package/dist/inference/tokenisePrompt.js +15 -11
  57. package/dist/inference/types.d.ts +7 -0
  58. package/dist/inference/utilities.js +1 -2
  59. package/dist/{jszip.min-DKa1Rjyn.js → jszip.min-Btv48m44.js} +68 -64
  60. package/dist/{kernel_funcs_utils-ql8Y8qPn.js → kernel_funcs_utils-BYRpSfV_.js} +39 -42
  61. package/dist/layers/BaseLayer.js +9 -10
  62. package/dist/layers/{CausalSelfAttention.d.ts → GQA.d.ts} +8 -3
  63. package/dist/layers/GQA.js +102 -0
  64. package/dist/layers/HeadLayer.d.ts +12 -0
  65. package/dist/layers/HeadLayer.js +28 -0
  66. package/dist/layers/LoRA.js +17 -20
  67. package/dist/layers/MHA.d.ts +43 -0
  68. package/dist/layers/MHA.js +102 -0
  69. package/dist/layers/MLP.d.ts +5 -1
  70. package/dist/layers/MLP.js +33 -20
  71. package/dist/layers/PositionEmbedding.js +14 -13
  72. package/dist/layers/RMSNorm.d.ts +2 -0
  73. package/dist/layers/RMSNorm.js +16 -11
  74. package/dist/layers/RoPECache.js +1 -337
  75. package/dist/layers/TiedEmbedding.js +15 -14
  76. package/dist/layers/TransformerBlock.d.ts +4 -10
  77. package/dist/layers/TransformerBlock.js +29 -30
  78. package/dist/layers/WeightStore.js +4 -5
  79. package/dist/layers-CFqEip3s.js +13 -0
  80. package/dist/layers.d.ts +1 -1
  81. package/dist/layers.js +4 -12
  82. package/dist/loader/load.js +27 -24
  83. package/dist/loader/loadHF.js +3 -3
  84. package/dist/loader/loadTransformers.js +22 -7
  85. package/dist/loader/loadZipMeta.js +1 -2
  86. package/dist/loader/newZipLoad.js +1 -2
  87. package/dist/loader/oldZipLoad.js +8 -9
  88. package/dist/loader/save.js +31 -17
  89. package/dist/loader/types.d.ts +8 -2
  90. package/dist/main.js +3281 -3463
  91. package/dist/matMul16-tE26fnhf.js +87 -0
  92. package/dist/{matMulGelu-CBoqTZM7.js → matMulGelu-ASUWlKqu.js} +33 -33
  93. package/dist/mat_mul-R9_DWmIT.js +16 -0
  94. package/dist/models/Llama.d.ts +16 -0
  95. package/dist/models/Llama.js +88 -0
  96. package/dist/models/NanoGPTV1.js +53 -54
  97. package/dist/models/NanoGPTV2.js +48 -49
  98. package/dist/models/Qwen3.d.ts +16 -0
  99. package/dist/models/Qwen3.js +88 -0
  100. package/dist/models/config.d.ts +18 -1
  101. package/dist/models/config.js +3 -8
  102. package/dist/models/factory.js +14 -11
  103. package/dist/models/model.d.ts +5 -7
  104. package/dist/models/model.js +1 -2
  105. package/dist/models-DyBpJJwM.js +13 -0
  106. package/dist/models.js +6 -14
  107. package/dist/mul16-C7sqgqik.js +41 -0
  108. package/dist/non_max_suppression_impl-B0H318rb.js +72 -0
  109. package/dist/not_equal-Bu3O8rh_.js +67 -0
  110. package/dist/one_hot-TEMPumJj.js +14 -0
  111. package/dist/ones-DpPXWa6A.js +13 -0
  112. package/dist/ops/adamAdjust.js +2 -3
  113. package/dist/ops/adamMoments.js +2 -3
  114. package/dist/ops/add16.js +2 -3
  115. package/dist/ops/appendCache.js +9 -8
  116. package/dist/ops/attentionMask.d.ts +1 -1
  117. package/dist/ops/attentionMask.js +8 -5
  118. package/dist/ops/concat16.js +5 -5
  119. package/dist/ops/cpu/adamAdjust.js +7 -8
  120. package/dist/ops/cpu/adamMoments.js +5 -5
  121. package/dist/ops/cpu/appendCache.js +3 -3
  122. package/dist/ops/cpu/attentionMask.js +12 -8
  123. package/dist/ops/cpu/fusedSoftmax.js +3 -3
  124. package/dist/ops/cpu/gatherSub.js +1 -12
  125. package/dist/ops/cpu/gelu.js +12 -13
  126. package/dist/ops/cpu/matMul16.js +7 -7
  127. package/dist/ops/cpu/matMulGelu.js +21 -18
  128. package/dist/ops/cpu/matMulMul.js +8 -9
  129. package/dist/ops/cpu/mulDropout.js +8 -9
  130. package/dist/ops/cpu/normRMS.js +12 -13
  131. package/dist/ops/cpu/qkv.js +14 -13
  132. package/dist/ops/cpu/rope.js +11 -8
  133. package/dist/ops/cpu/scatterSub.js +1 -12
  134. package/dist/ops/dot16.js +16 -17
  135. package/dist/ops/dropout.js +9 -8
  136. package/dist/ops/dropout16.js +1 -22
  137. package/dist/ops/gatherSub.js +3 -4
  138. package/dist/ops/gelu.js +1 -2
  139. package/dist/ops/globalNorm.js +14 -14
  140. package/dist/ops/grads/add16.js +16 -17
  141. package/dist/ops/grads/attentionMask.js +6 -7
  142. package/dist/ops/grads/dropout16.js +1 -1
  143. package/dist/ops/grads/gelu.js +1 -2
  144. package/dist/ops/grads/matMul16.js +1 -2
  145. package/dist/ops/grads/matMulGelu.js +6 -7
  146. package/dist/ops/grads/mul16.js +1 -1
  147. package/dist/ops/grads/normRMS.js +8 -9
  148. package/dist/ops/grads/pack16.js +1 -2
  149. package/dist/ops/grads/qkv.js +10 -10
  150. package/dist/ops/grads/rope.js +1 -2
  151. package/dist/ops/grads/silu.d.ts +2 -0
  152. package/dist/ops/grads/silu.js +1 -0
  153. package/dist/ops/grads/softmax16.js +6 -7
  154. package/dist/ops/grads/unpack16.js +1 -2
  155. package/dist/ops/grads/utils.js +1 -2
  156. package/dist/ops/matMul16.d.ts +2 -2
  157. package/dist/ops/matMul16.js +1 -2
  158. package/dist/ops/matMulGelu.js +3 -4
  159. package/dist/ops/matMulMul.js +2 -3
  160. package/dist/ops/mul16.js +1 -43
  161. package/dist/ops/mulDrop.js +2 -3
  162. package/dist/ops/normRMS.d.ts +1 -1
  163. package/dist/ops/normRMS.js +10 -11
  164. package/dist/ops/pack16.js +1 -2
  165. package/dist/ops/qkv.js +2 -3
  166. package/dist/ops/reshape16.js +11 -11
  167. package/dist/ops/rope.d.ts +1 -1
  168. package/dist/ops/rope.js +1 -2
  169. package/dist/ops/scatterSub.js +3 -4
  170. package/dist/ops/silu.d.ts +3 -0
  171. package/dist/ops/silu.js +1 -0
  172. package/dist/ops/slice16.js +5 -5
  173. package/dist/ops/softmax16.js +3 -4
  174. package/dist/ops/sub16.js +3 -4
  175. package/dist/ops/sum16.js +3 -3
  176. package/dist/ops/transpose16.js +16 -15
  177. package/dist/ops/unpack16.js +1 -2
  178. package/dist/ops/webgl/adamAdjust.js +8 -9
  179. package/dist/ops/webgl/adamMoments.js +2 -3
  180. package/dist/ops/webgl/appendCache.js +2 -3
  181. package/dist/ops/webgl/attentionMask.js +2 -3
  182. package/dist/ops/webgl/dropout16.js +2 -3
  183. package/dist/ops/webgl/fusedSoftmax.js +13 -13
  184. package/dist/ops/webgl/gatherSub.js +2 -3
  185. package/dist/ops/webgl/gelu.js +11 -12
  186. package/dist/ops/webgl/log.js +10 -10
  187. package/dist/ops/webgl/matMul16.js +31 -24
  188. package/dist/ops/webgl/matMulGelu.js +1 -2
  189. package/dist/ops/webgl/matMulMul.js +3 -4
  190. package/dist/ops/webgl/mulDropout.js +2 -3
  191. package/dist/ops/webgl/normRMS.js +11 -10
  192. package/dist/ops/webgl/qkv.js +2 -3
  193. package/dist/ops/webgl/rope.js +10 -9
  194. package/dist/ops/webgl/scatterSub.js +2 -3
  195. package/dist/ops/webgpu/adamAdjust.js +13 -14
  196. package/dist/ops/webgpu/adamMoments.js +13 -14
  197. package/dist/ops/webgpu/add16.js +3 -4
  198. package/dist/ops/webgpu/appendCache.js +20 -21
  199. package/dist/ops/webgpu/attentionMask.js +18 -19
  200. package/dist/ops/webgpu/attentionMask32_program.js +7 -8
  201. package/dist/ops/webgpu/clipScale.js +11 -12
  202. package/dist/ops/webgpu/concat16.js +17 -18
  203. package/dist/ops/webgpu/dropout16.js +6 -7
  204. package/dist/ops/webgpu/gatherSub.js +11 -12
  205. package/dist/ops/webgpu/gelu.js +10 -11
  206. package/dist/ops/webgpu/index.js +17 -16
  207. package/dist/ops/webgpu/matMul16.js +74 -57
  208. package/dist/ops/webgpu/matMul16_program.d.ts +4 -3
  209. package/dist/ops/webgpu/matMul16_program.js +30 -22
  210. package/dist/ops/webgpu/mul16.js +3 -4
  211. package/dist/ops/webgpu/norm2.js +9 -10
  212. package/dist/ops/webgpu/normRMS.js +13 -14
  213. package/dist/ops/webgpu/normRMS16_program.d.ts +2 -1
  214. package/dist/ops/webgpu/normRMS16_program.js +5 -5
  215. package/dist/ops/webgpu/normRMS32_program.d.ts +2 -1
  216. package/dist/ops/webgpu/normRMS32_program.js +5 -5
  217. package/dist/ops/webgpu/normRMSGrad.js +30 -30
  218. package/dist/ops/webgpu/pack16.js +2 -3
  219. package/dist/ops/webgpu/pack16_program.js +3 -4
  220. package/dist/ops/webgpu/qkv.js +10 -11
  221. package/dist/ops/webgpu/rope.js +113 -49
  222. package/dist/ops/webgpu/scatterSub.js +12 -13
  223. package/dist/ops/webgpu/silu.d.ts +14 -0
  224. package/dist/ops/webgpu/silu.js +117 -0
  225. package/dist/ops/webgpu/slice16.js +17 -18
  226. package/dist/ops/webgpu/softmax16.js +9 -9
  227. package/dist/ops/webgpu/softmax16_program.js +9 -10
  228. package/dist/ops/webgpu/softmax16_subgroup_program.js +11 -12
  229. package/dist/ops/webgpu/softmax16grad.js +8 -9
  230. package/dist/ops/webgpu/sub16.js +3 -4
  231. package/dist/ops/webgpu/sum16.js +16 -15
  232. package/dist/ops/webgpu/transpose16.js +13 -12
  233. package/dist/ops/webgpu/transpose16_program.js +3 -4
  234. package/dist/ops/webgpu/transpose16_shared_program.js +17 -18
  235. package/dist/ops/webgpu/unpack16.js +8 -9
  236. package/dist/ops/webgpu/utils/binary_op.js +20 -21
  237. package/dist/ops/webgpu/utils/deviceInfo.js +1 -2
  238. package/dist/ops/webgpu/utils/reductions.js +21 -20
  239. package/dist/ops-Be5ACU5R.js +13 -0
  240. package/dist/ops-C1UpdEYM.js +509 -0
  241. package/dist/{pack16-BhuXNUS7.js → pack16-BHO4t1-M.js} +14 -17
  242. package/dist/pad-Dy-1IP3A.js +13 -0
  243. package/dist/patches/webgpu_backend.js +18 -19
  244. package/dist/patches/webgpu_base.js +2 -3
  245. package/dist/patches/webgpu_program.js +21 -22
  246. package/dist/{pdf-Bzuk68Vy.js → pdf-CbnQ75VG.js} +380 -701
  247. package/dist/{picomatch-BO4HbNfo.js → picomatch--TW6gyBJ.js} +229 -291
  248. package/dist/qkv-BQfNPucX.js +42 -0
  249. package/dist/rand_util-_vCY93Uw.js +44 -0
  250. package/dist/random_normal-DUIT8kyC.js +11 -0
  251. package/dist/range-CYvQC3fW.js +13 -0
  252. package/dist/relu-C4XULT8A.js +8 -0
  253. package/dist/reshape-DJb1jgMt.js +8 -0
  254. package/dist/resize_nearest_neighbor-DAqcTYUe.js +188 -0
  255. package/dist/{chunk-CWhphoD1.js → rolldown-runtime-CwxnZyOB.js} +4 -5
  256. package/dist/rope-JjBVufF_.js +24 -0
  257. package/dist/scatterSub-BOnqk-uY.js +27 -0
  258. package/dist/scatter_nd_util-BepMCpLY.js +34 -0
  259. package/dist/seedrandom-SHEGFK6H.js +282 -0
  260. package/dist/selu_util-DeOTf-sc.js +27 -0
  261. package/dist/shared-BIDMUBCs.js +1864 -0
  262. package/dist/{shared-CfTzpULd.js → shared-CX_iPI5K.js} +2 -3
  263. package/dist/silu-DsAE2cJ5.js +23 -0
  264. package/dist/slice-Dlb1FlzG.js +13 -0
  265. package/dist/{slice_util-Dve4TkDn.js → slice_util-BVgPRoij.js} +3 -4
  266. package/dist/softmax-Dpav_dWw.js +10 -0
  267. package/dist/split-DYnT8chz.js +11 -0
  268. package/dist/squeeze-B3XYGAlg.js +9 -0
  269. package/dist/stack-Dbbt9mIk.js +10 -0
  270. package/dist/step-DA-5DNu9.js +348 -0
  271. package/dist/{stream-BpAwcvHz.js → stream-BBe2apn4.js} +68 -88
  272. package/dist/sum-C8qNbFNp.js +13 -0
  273. package/dist/tensor-ALxWZfmz.js +7 -0
  274. package/dist/tensor1d-BHgkkhTE.js +9 -0
  275. package/dist/tensor2d-ARItvqVn.js +10 -0
  276. package/dist/tensor4d-D1zRBipJ.js +10 -0
  277. package/dist/tfjs_backend-CsXOum0h.js +685 -0
  278. package/dist/tile-DfyQ0KX-.js +10 -0
  279. package/dist/tokenise-DbS2Ea-T.js +14 -0
  280. package/dist/tokenise.js +6 -15
  281. package/dist/tokeniser/BaseTokeniser.js +5 -9
  282. package/dist/tokeniser/CharTokeniser.js +1 -2
  283. package/dist/tokeniser/bpe.js +19 -20
  284. package/dist/topk-BrU2pkrR.js +19 -0
  285. package/dist/training/AdamW.js +35 -31
  286. package/dist/training/BasicTrainer.js +56 -56
  287. package/dist/training/DatasetBuilder.js +1 -2
  288. package/dist/training/Evaluator.js +8 -5
  289. package/dist/training/LRScheduler.js +1 -2
  290. package/dist/training/PreTrainer.js +7 -8
  291. package/dist/training/SFTTrainer.js +7 -8
  292. package/dist/training/configure.js +16 -15
  293. package/dist/training/factory.js +1 -2
  294. package/dist/training/loss.js +1 -2
  295. package/dist/training/orthoGrad.js +2 -3
  296. package/dist/training/prepareData.js +18 -17
  297. package/dist/training/sparseCrossEntropy.js +38 -32
  298. package/dist/training/tasks/TokenStore.js +21 -22
  299. package/dist/training/tasks/tokenStream.js +1 -2
  300. package/dist/training/validateOptions.js +1 -2
  301. package/dist/training/validation.js +1 -2
  302. package/dist/transpose-BC-M_OoT.js +34 -0
  303. package/dist/unsorted_segment_sum-BelC7R-q.js +408 -0
  304. package/dist/utilities/arrayClose.js +5 -4
  305. package/dist/utilities/arrayShape.js +1 -2
  306. package/dist/utilities/datasetID.js +1 -2
  307. package/dist/utilities/dummy.js +15 -15
  308. package/dist/utilities/float16.js +10 -10
  309. package/dist/utilities/maxHeap.d.ts +16 -0
  310. package/dist/utilities/maxHeap.js +54 -0
  311. package/dist/utilities/multinomialCPU.d.ts +1 -2
  312. package/dist/utilities/multinomialCPU.js +6 -8
  313. package/dist/utilities/packed.js +2 -3
  314. package/dist/utilities/parameters.js +34 -19
  315. package/dist/utilities/performance.js +2 -3
  316. package/dist/utilities/profile.js +3 -4
  317. package/dist/utilities/random.js +1 -2
  318. package/dist/utilities/safetensors.js +14 -14
  319. package/dist/utilities/sentences.js +16 -13
  320. package/dist/utilities/tokenParse.js +1 -2
  321. package/dist/utilities/tokens.js +5 -6
  322. package/dist/utilities/topP.d.ts +1 -0
  323. package/dist/utilities/topP.js +20 -13
  324. package/dist/utilities/waitForModel.js +1 -2
  325. package/dist/utilities/weights.js +4 -4
  326. package/dist/utilities/yielder.js +1 -2
  327. package/dist/{v4-BK7K-jy_.js → v4-YCkfo8OR.js} +4 -7
  328. package/dist/{webgpu-IAn9VotJ.js → webgpu-BHX-uBym.js} +156 -163
  329. package/dist/{webgpu_program-B0PokuRJ.js → webgpu_program-DvkFqRlR.js} +28 -29
  330. package/dist/{webgpu_util-DfODg6XI.js → webgpu_util-5QTyovaf.js} +2 -3
  331. package/dist/zeros-hxKGkRfl.js +12 -0
  332. package/package.json +3 -3
  333. package/dist/Reshape-CwxdaU8n.js +0 -17
  334. package/dist/dist-Da20xy8E.js +0 -6375
  335. package/dist/gelu-B6637MKa.js +0 -27
  336. package/dist/layers/CausalSelfAttention.js +0 -99
  337. package/dist/matMul16-DGtlziMn.js +0 -81
  338. package/dist/rope-C8EAiSGY.js +0 -25
  339. package/dist/selu_util-B_AFEfoz.js +0 -24
  340. package/dist/shared-24EoeHJl.js +0 -1314
  341. package/dist/tfjs_backend-h5weiy1O.js +0 -614
@@ -6,13 +6,25 @@ export default class Beamer {
6
6
  private readonly tokeniser;
7
7
  private actualTokeniser;
8
8
  private active;
9
+ private options;
10
+ private conversation;
11
+ private heap;
12
+ private hasRoot;
13
+ private totalCandidates;
14
+ private seen;
9
15
  constructor(model: Model<ModelForwardAttributes>, tokeniser: ITokeniser);
10
16
  private shouldTerminate;
11
17
  private initialise;
12
18
  private tokeniseConversation;
13
19
  private createInitialContext;
14
20
  private appendTokenToContext;
15
- private batchedNextProbabilities;
16
21
  cancel(): void;
17
- beam(conversation: Conversation[], options: BeamerOptions, onStep?: (beams: IBeam[]) => void): Promise<IBeam[]>;
22
+ begin(conversation: Conversation[], options: BeamerOptions): void;
23
+ private expand;
24
+ private pushNextChild;
25
+ private entryToBeam;
26
+ next(): Promise<IBeam | null>;
27
+ private _next;
28
+ beam(onStep?: (beams: IBeam[]) => void): Promise<IBeam[]>;
29
+ dispose(): void;
18
30
  }
@@ -1,19 +1,32 @@
1
1
  import e from "../tokeniser/CharTokeniser.js";
2
- import { L as t, V as n, Y as r, _n as i, _r as a, di as o, xt as s } from "../dist-Da20xy8E.js";
3
- import c from "../utilities/topP.js";
4
- import { CHARS as l, padArray as u } from "./utilities.js";
5
- //#region lib/inference/Beamer.ts
6
- function d(e, t) {
7
- return e.map((e, t) => ({
2
+ import { Y as t, b as n } from "../dist-CMMLi-qO.js";
3
+ import { t as r } from "../concat-Oip5acVY.js";
4
+ import { t as i } from "../one_hot-TEMPumJj.js";
5
+ import { t as a } from "../softmax-Dpav_dWw.js";
6
+ import { t as o } from "../stack-Dbbt9mIk.js";
7
+ import { t as s } from "../tensor1d-BHgkkhTE.js";
8
+ import { CHARS as c, padArray as l } from "./utilities.js";
9
+ import u from "../utilities/topP.js";
10
+ import d from "../utilities/maxHeap.js";
11
+ // lib/inference/Beamer.ts
12
+ function f(e, t) {
13
+ let n = e.map((e, t) => ({
8
14
  token: t,
9
15
  prob: e
10
- })).filter((e) => e.prob > 0).sort((e, t) => t.prob - e.prob).slice(0, Math.max(1, t));
16
+ })).filter((e) => e.prob > 0).sort((e, t) => t.prob - e.prob);
17
+ return t === void 0 ? n : n.slice(0, Math.max(1, t));
11
18
  }
12
- var f = class {
19
+ var p = class {
13
20
  model;
14
21
  tokeniser;
15
22
  actualTokeniser;
16
23
  active = !1;
24
+ options = null;
25
+ conversation = [];
26
+ heap = new d((e) => e.score);
27
+ hasRoot = !1;
28
+ totalCandidates = 0;
29
+ seen = /* @__PURE__ */ new Set();
17
30
  constructor(e, t) {
18
31
  this.model = e, this.tokeniser = t, this.actualTokeniser = t;
19
32
  }
@@ -23,7 +36,7 @@ var f = class {
23
36
  return t === this.actualTokeniser.eosToken || t === n;
24
37
  }
25
38
  initialise(t) {
26
- let n = this.tokeniser.trained ? this.tokeniser : new e(u(l, this.tokeniser.vocabSize));
39
+ let n = this.tokeniser.trained ? this.tokeniser : new e(l(c, this.tokeniser.vocabSize));
27
40
  this.actualTokeniser = n, t?.loraName ? this.model.attachLoRA(t.loraName) : this.model.hasLoRA() && this.model.detachLoRA();
28
41
  }
29
42
  async tokeniseConversation(e) {
@@ -32,119 +45,171 @@ var f = class {
32
45
  return t;
33
46
  }
34
47
  createInitialContext(e) {
35
- let n = this.model.config.blockSize, r = e.length > n ? e.slice(-n) : e.slice();
48
+ let t = this.model.config.blockSize, n = e.length > t ? e.slice(-t) : e.slice(), r = n.concat(Array(t - n.length).fill(0));
36
49
  return {
37
- context: t(r.concat(Array(n - r.length).fill(0)), "int32"),
38
- contextLength: r.length
50
+ context: s(r, "int32"),
51
+ contextLength: n.length
39
52
  };
40
53
  }
41
- appendTokenToContext(e, n, r) {
54
+ appendTokenToContext(e, a, o) {
42
55
  let c = this.model.config.blockSize;
43
- return n < c ? {
44
- context: o(() => {
45
- let t = s([n], c).squeeze([0]).asType("int32"), a = i(1, "int32").sub(t), o = t.mul(i(r, "int32"));
46
- return e.mul(a).add(o);
56
+ return a < c ? {
57
+ context: t(() => {
58
+ let t = i([a], c).squeeze([0]).asType("int32"), r = n(1, "int32").sub(t), s = t.mul(n(o, "int32"));
59
+ return e.mul(r).add(s);
47
60
  }),
48
- contextLength: n + 1
61
+ contextLength: a + 1
49
62
  } : {
50
- context: o(() => a([e.slice([1], [c - 1]), t([r], "int32")], 0)),
63
+ context: t(() => {
64
+ let t = e.slice([1], [c - 1]), n = s([o], "int32");
65
+ return r([t, n], 0);
66
+ }),
51
67
  contextLength: c
52
68
  };
53
69
  }
54
- async batchedNextProbabilities(e, t, i) {
55
- if (e.length === 0) return [];
56
- let a = e[0], l = e.slice();
57
- for (; l.length < t;) l.push(a);
58
- let u = n(l.map((e) => e.context)), d = this.model.forward({
70
+ cancel() {
71
+ this.active = !1;
72
+ }
73
+ begin(e, t) {
74
+ if (!(!t || t.beams < 1 || t.maxBeamLength < 1)) {
75
+ if (this.options) throw Error("Beamer has already been initialized.");
76
+ this.conversation = e, this.options = t, this.initialise(t);
77
+ }
78
+ }
79
+ async expand(e, n) {
80
+ if (e.length === 0) return;
81
+ if (e.length > n) throw Error(`Number of nodes (${e.length}) exceeds fixed batch size (${n}).`);
82
+ let r = [...e];
83
+ if (e.length < n) for (; r.length < n;) r.push(e[e.length - 1]);
84
+ let s = o(r.map((e) => e.context)), c = this.model.forward({
59
85
  training: !1,
60
86
  mixedPrecision: !0
61
- }, u), f = l.map((e) => Math.max(0, e.contextLength - 1)), p = o(() => {
62
- let e = s(f, this.model.config.blockSize).expandDims(2);
63
- return r(d.mul(e).sum(1));
64
- }), m = e.length, h = m < t ? p.slice([0, 0], [m, this.model.config.vocabSize]) : p, g = await h.array();
65
- h !== p && h.dispose(), p.dispose(), d.dispose(), u.dispose();
66
- let _ = i.topP ?? 1;
67
- return g.map((e) => c(e, _));
87
+ }, s), l = r.map((e) => Math.max(0, e.contextLength - 1)), d = t(() => {
88
+ let e = i(l, this.model.config.blockSize).expandDims(2);
89
+ return a(c.mul(e).sum(1));
90
+ }), p = e.length, m = p < n ? d.slice([0, 0], [p, this.model.config.vocabSize]) : d, h = await m.array();
91
+ m !== d && m.dispose(), d.dispose(), c.dispose(), s.dispose();
92
+ let g = this.options?.topP ?? 1, _ = h.map((e) => f(u(e, g), this.options?.topK));
93
+ for (let t = 0; t < e.length; t++) e[t].sortedChildren = _[t], this.totalCandidates += _[t].length - 1;
68
94
  }
69
- cancel() {
70
- this.active = !1;
95
+ pushNextChild(e) {
96
+ if (!e.sortedChildren || e.nextChild >= e.sortedChildren.length) return;
97
+ let t = e.nextChild++, n = e.sortedChildren[t].token, r = e.sortedChildren[t].prob, i = this.options.maxBeamLength, a = this.shouldTerminate(this.options.allowSpecial ?? !1, n), o = this.actualTokeniser.decode([n]), s = e.tokens.length + 1 > i, c = this.options.endOnWhiteSpace === !0 && s && /\s/.test(o), l = this.options.endOnWhiteSpace ? e.tokens.length + 1 >= i + 10 : e.tokens.length + 1 >= i;
98
+ this.heap.push({
99
+ score: e.score * r,
100
+ parent: e,
101
+ idx: t,
102
+ tokenId: n,
103
+ tokenText: o,
104
+ probability: r,
105
+ terminated: a || c || l,
106
+ reason: a ? "token" : c ? "whitespace" : l ? "length" : void 0
107
+ });
71
108
  }
72
- async beam(e, t, n) {
73
- if (!t || t.beams < 1 || t.maxBeamLength < 1) return [];
74
- let r = Math.max(8, t.beams);
75
- this.initialise(t), this.active = !0;
76
- let i = await this.tokeniseConversation(e), a = this.createInitialContext(i), o = [{
77
- tokens: [],
78
- score: 1,
79
- text: "",
80
- terminated: !1,
81
- context: a.context,
82
- contextLength: a.contextLength,
83
- candidates: 0
84
- }], s = t.maxBeamLength, c = t.endOnWhiteSpace === !0 ? Math.max(s, t.maxLength ?? s + this.model.config.blockSize) : s, l = Date.now(), u = 0;
85
- for (let e = 0; e < c && this.active; e++) {
86
- let e = o.filter((e) => !e.terminated);
87
- if (e.length === 0) break;
88
- let i = await this.batchedNextProbabilities(e, r, t), a = [];
89
- for (let n = 0; n < e.length; n++) {
90
- let o = e[n], c = i[n], l = d(c, t.topK ? Math.min(t.topK, r) : Math.max(1, r));
91
- for (let e of l) {
92
- let n = this.actualTokeniser.decode([e.token]), r = this.shouldTerminate(t.allowSpecial ?? !1, e.token), i = o.tokens.length + 1 > s, c = t.endOnWhiteSpace === !0 && i && /\s/.test(n), l = c && o.tokens.length > 0 && /^\s/.test(n);
93
- a.push({
94
- parent: o,
95
- token: e.token,
96
- tokenText: n,
97
- score: o.score * e.prob,
98
- terminatedByToken: r,
99
- terminatedByWhitespace: c,
100
- dropLeadingWhitespaceTerminator: l
101
- });
102
- }
109
+ entryToBeam(e) {
110
+ let t = e.reason === "whitespace" && e.parent.tokens.length > 0 && /^\s/.test(e.tokenText), n = e.parent.tokens.map((t, n) => ({
111
+ token: t,
112
+ score: e.parent.probabilities[n],
113
+ text: this.actualTokeniser.decode([t]),
114
+ terminated: e.terminated,
115
+ confidence: null,
116
+ logits: null,
117
+ scores: null,
118
+ hiddenStates: null,
119
+ attention: null,
120
+ loss: null,
121
+ multinomialRand: null
122
+ }));
123
+ n.push({
124
+ token: e.tokenId,
125
+ score: e.probability,
126
+ text: e.tokenText,
127
+ terminated: e.terminated,
128
+ confidence: null,
129
+ logits: null,
130
+ scores: null,
131
+ hiddenStates: null,
132
+ attention: null,
133
+ loss: null,
134
+ multinomialRand: null
135
+ });
136
+ let r = {
137
+ tokens: t ? e.parent.tokens.slice() : [...e.parent.tokens, e.tokenId],
138
+ score: e.score,
139
+ text: t ? e.parent.text : e.parent.text + e.tokenText,
140
+ candidates: this.totalCandidates,
141
+ _output: n
142
+ };
143
+ if (!this.options?.keepDuplicates) {
144
+ if (this.seen.has(r.text.trim())) return this.totalCandidates--, null;
145
+ this.seen.add(r.text.trim());
146
+ }
147
+ return r;
148
+ }
149
+ async next() {
150
+ this.active = !0;
151
+ let e = await this._next();
152
+ return this.active = !1, e;
153
+ }
154
+ async _next() {
155
+ if (!this.options || !this.conversation) throw Error("Beamer not properly initialized with options and conversation.");
156
+ if (!this.hasRoot) {
157
+ let e = await this.tokeniseConversation(this.conversation), t = this.createInitialContext(e), n = {
158
+ tokens: [],
159
+ text: "",
160
+ score: 1,
161
+ context: t.context,
162
+ contextLength: t.contextLength,
163
+ terminated: !1,
164
+ nextChild: 0,
165
+ sortedChildren: void 0,
166
+ probabilities: []
167
+ };
168
+ this.totalCandidates = 1, await this.expand([n], 8), this.pushNextChild(n), this.hasRoot = !0;
169
+ }
170
+ for (; this.heap.size && this.active;) {
171
+ if (this.heap.peek().terminated) {
172
+ let e = this.heap.pop();
173
+ this.pushNextChild(e.parent);
174
+ let t = this.entryToBeam(e);
175
+ if (!t) continue;
176
+ return t;
103
177
  }
104
- let c = o.filter((e) => e.terminated), f = c.slice();
105
- a.sort((e, t) => t.score - e.score);
106
- for (let e of a) {
107
- if (f.length >= r) break;
108
- let t = e.terminatedByToken || e.terminatedByWhitespace, n = !e.dropLeadingWhitespaceTerminator, i = n ? e.parent.tokens.concat(e.token) : e.parent.tokens.slice(), a = e.terminatedByToken || e.dropLeadingWhitespaceTerminator ? e.parent.text : e.parent.text + e.tokenText, o = n ? this.appendTokenToContext(e.parent.context, e.parent.contextLength, e.token) : {
109
- context: e.parent.context.clone(),
110
- contextLength: e.parent.contextLength
111
- }, s = e.parent._output?.slice() ?? [];
112
- n && s.push({
113
- token: e.token,
114
- score: e.score,
115
- text: e.tokenText,
116
- terminated: t,
117
- confidence: null,
118
- logits: null,
119
- scores: null,
120
- hiddenStates: null,
121
- attention: null,
122
- loss: null,
123
- multinomialRand: null
124
- }), f.push({
125
- tokens: i,
126
- score: e.score,
127
- text: a,
128
- terminated: t,
129
- context: o.context,
130
- contextLength: o.contextLength,
131
- _output: s,
132
- candidates: u
178
+ let e = [];
179
+ for (; e.length < 8 && this.heap.size && !this.heap.peek().terminated;) {
180
+ let t = this.heap.pop();
181
+ this.pushNextChild(t.parent), e.push({
182
+ text: t.parent.text + t.tokenText,
183
+ tokens: [...t.parent.tokens, t.tokenId],
184
+ score: t.score,
185
+ ...this.appendTokenToContext(t.parent.context, t.parent.contextLength, t.tokenId),
186
+ terminated: t.terminated,
187
+ nextChild: 0,
188
+ sortedChildren: void 0,
189
+ probabilities: [...t.parent.probabilities, t.probability]
133
190
  });
134
191
  }
135
- if (u += a.length - f.length + c.length, o.forEach((e) => e.context.dispose()), f.length === 0) break;
136
- o = f, n && Date.now() - l >= 40 && (n(o.slice(0, t.beams)), l = Date.now());
192
+ await this.expand(e, 8);
193
+ for (let t of e) this.pushNextChild(t);
137
194
  }
138
- this.active = !1, u += o.length;
139
- let f = o.slice().sort((e, t) => t.score - e.score), p = [], m = /* @__PURE__ */ new Set();
140
- for (let e of f) {
141
- let n = e.text.trim();
142
- if (m.has(n) || (m.add(n), p.push(e)), p.length >= t.beams) break;
195
+ return null;
196
+ }
197
+ async beam(e) {
198
+ this.active = !0;
199
+ let t = [];
200
+ for (; t.length < (this.options?.beams ?? 8);) {
201
+ let n = await this._next();
202
+ if (!n) break;
203
+ t.push(n), e?.(t);
143
204
  }
144
- return o.forEach((e) => {
145
- e.context.dispose(), e.candidates = u;
146
- }), p;
205
+ return this.active = !1, t.forEach((e) => {
206
+ e.candidates = this.totalCandidates;
207
+ }), t;
208
+ }
209
+ dispose() {
210
+ this.active = !1, this.heap.values.forEach((e) => {
211
+ e.parent.context.dispose();
212
+ }), this.heap.clear();
147
213
  }
148
214
  };
149
- //#endregion
150
- export { f as default };
215
+ export { p as default };
@@ -1,259 +1 @@
1
- import { t as e } from "../eventemitter3-D_qV3Lof.js";
2
- import t from "../tokeniser/CharTokeniser.js";
3
- import { A as n, Ct as r, I as i, Y as a, _r as o, an as s, di as c, oi as l, yt as u } from "../dist-Da20xy8E.js";
4
- import d from "../utilities/multinomialCPU.js";
5
- import f from "../utilities/topP.js";
6
- import { sparseSoftmaxCrossEntropy as p } from "../training/sparseCrossEntropy.js";
7
- import m from "./tokenisePrompt.js";
8
- import { CHARS as h, getTokenConfidence as g, padArray as _ } from "./utilities.js";
9
- //#region lib/inference/Generator.ts
10
- function v(e) {
11
- return Array.isArray(e);
12
- }
13
- var y = class extends e {
14
- model;
15
- tokeniser;
16
- active = !1;
17
- cache = null;
18
- initialPrompt = null;
19
- outputConversation = [];
20
- actualTokeniser;
21
- lastToken = -1;
22
- lastLoss = null;
23
- rawOutput = [];
24
- jobQueue = [];
25
- processingJob = !1;
26
- startTime = null;
27
- tokenCount = 0;
28
- constructor(e, t) {
29
- super(), this.model = e, this.tokeniser = t, this.actualTokeniser = t;
30
- }
31
- shouldTerminate(e, t) {
32
- if (e) return !1;
33
- let n = this.tokeniser.getSpecialTokenIndex("<|assistant_end|>");
34
- return t === this.actualTokeniser.eosToken || t === n;
35
- }
36
- async _generateToken(e, t, o) {
37
- let m = o?.temperature ?? 1, h = o?.topK, _ = o?.topP, v = o?.usePadding ?? !1, y = {
38
- training: !1,
39
- attentionScores: o?.outputAttention ? { attentionOut: [] } : void 0,
40
- cache: t,
41
- outputEmbeddings: !!o?.outputHiddenStates
42
- }, [b, x] = c(() => {
43
- let t = e, n = t.shape[1], r = n <= this.model.config.blockSize ? t : t.slice([0, n - this.model.config.blockSize], [t.shape[0], this.model.config.blockSize]), a = v ? this.model.config.blockSize - r.shape[1] : 0, s = a > 0 ? u(r, [[0, 0], [0, a]]) : r, c = this.model.forward(y, s), d = c.shape[1] - 1 - a, f = c.slice([
44
- 0,
45
- d,
46
- 0
47
- ], [
48
- c.shape[0],
49
- 1,
50
- c.shape[2]
51
- ]), h;
52
- if (o?.targets) {
53
- let e = o.targets.shift();
54
- if (e !== void 0) {
55
- let t = i([[e]], [1, 1], "int32"), n = p(f, t);
56
- h = n.mean(), t.dispose(), n.dispose();
57
- }
58
- }
59
- return y.attentionScores?.attentionOut && y.attentionScores.attentionOut.forEach((e, t) => {
60
- e.shape[1] !== 1 && (y.attentionScores.attentionOut[t] = l(e.slice([
61
- 0,
62
- d,
63
- 0
64
- ], [
65
- e.shape[0],
66
- 1,
67
- e.shape[2]
68
- ])), e.dispose());
69
- }), c.dispose(), [f.div(m).squeeze([1]), h];
70
- }), S, C, w, T = Math.random();
71
- if (_) {
72
- let e = a(b), t = await e.array();
73
- e.dispose();
74
- let n = f(t, _);
75
- (o?.outputScores || o?.outputConfidence) && (C = t), S = d(n, T);
76
- } else if (h) {
77
- let { values: e, indices: t } = n(b, h), i = r(e, 1);
78
- S = s(t, i, 1), e.dispose(), t.dispose(), i.dispose();
79
- } else if (S = r(b, 1), o?.outputScores || o?.outputConfidence) {
80
- let e = a(b);
81
- C = await e.array(), e.dispose();
82
- }
83
- if (y.embeddings) {
84
- let e = (o?.outputHiddenStates === "all" ? y.embeddings : y.embeddings.filter((e) => e.name.startsWith("block_output_"))).map(async (e) => {
85
- let t = e.tensor.shape[1], n = e.tensor.slice([
86
- 0,
87
- t - 1,
88
- 0
89
- ], [
90
- e.tensor.shape[0],
91
- 1,
92
- e.tensor.shape[2]
93
- ]);
94
- e.tensor.dispose();
95
- let r = n.squeeze([1]);
96
- if (n.dispose(), o?.outputHiddenStates === "softmax") {
97
- let t = this.model.project(r);
98
- r.dispose();
99
- let n = a(t, -1);
100
- t.dispose();
101
- let i = {
102
- name: e.name,
103
- tensor: await n.array()
104
- };
105
- return n.dispose(), i;
106
- } else if (o?.outputHiddenStates === "logits") {
107
- let t = this.model.project(r);
108
- r.dispose();
109
- let n = {
110
- name: e.name,
111
- tensor: await t.array()
112
- };
113
- return t.dispose(), n;
114
- } else {
115
- let t = await r.array();
116
- return r.dispose(), {
117
- name: e.name,
118
- tensor: t
119
- };
120
- }
121
- });
122
- w = await Promise.all(e);
123
- }
124
- let E = S.reshape([1, 1]);
125
- S.dispose(), S = E;
126
- let D = (await S.array())[0][0], O = this.actualTokeniser.decode([D]);
127
- this.lastToken = D;
128
- let k = this.shouldTerminate(o?.allowSpecial ?? !1, D), A = {
129
- outputTensor: S,
130
- token: D,
131
- text: O,
132
- confidence: o?.outputConfidence && C ? g(C[0]) : null,
133
- score: o?.outputScore && C ? C[0][D] : null,
134
- logits: o?.outputLogits ? (await b.array())[0] : null,
135
- scores: o?.outputScores && C ? C[0] : null,
136
- hiddenStates: w ? w.map((e) => e.tensor[0]) : null,
137
- attention: o?.outputAttention ? await Promise.all(y.attentionScores?.attentionOut?.map((e) => e.array()) ?? []) : null,
138
- loss: this.lastLoss,
139
- multinomialRand: T,
140
- terminated: k
141
- };
142
- if (b.dispose(), x) {
143
- let e = await x.array();
144
- x.dispose(), A.loss = e;
145
- }
146
- return this.rawOutput.push(A), (!o?.chunkSize || this.tokenCount++ % o.chunkSize === 0) && (this.emit("tokens", A), o?._onChunk && await o._onChunk(A)), A;
147
- }
148
- async _generate(e, t) {
149
- let n = !1;
150
- this.outputConversation.length === 0 || this.outputConversation[this.outputConversation.length - 1]._completed || this.outputConversation[this.outputConversation.length - 1].role !== "assistant" && e?.nonConversational !== !0 || this.outputConversation[this.outputConversation.length - 1].role !== "text" && e?.nonConversational === !0 ? (this.outputConversation.push({
151
- role: e?.nonConversational === !0 ? "text" : "assistant",
152
- content: "",
153
- _timestamp: Date.now()
154
- }), n = !0, this.resetCache(!e?.noCache)) : (this.lastToken < 0 || t) && this.resetCache(!e?.noCache);
155
- let r = this.lastToken >= 0 && this.cache ? i([this.lastToken], [1, 1], "int32") : await m(this.actualTokeniser, this.model.config.blockSize, t ? n ? this.outputConversation.slice(0, -1) : this.outputConversation : void 0, n ? e : {
156
- ...e,
157
- continuation: !0
158
- }), a = e?.maxLength ?? 1e3;
159
- for (let t = 0; t < a && this.active; t++) {
160
- let n = await this._generateToken(r, this.cache ? this.cache : void 0, {
161
- ...e,
162
- usePadding: !this.cache
163
- });
164
- if (this.cache) r.dispose(), r = n.outputTensor;
165
- else {
166
- let e = r;
167
- r = o([r, n.outputTensor], 1), e.dispose();
168
- }
169
- let i = this.outputConversation[this.outputConversation.length - 1];
170
- if (this.cache || n.outputTensor.dispose(), n.terminated) {
171
- i._completed = !0;
172
- break;
173
- }
174
- t === a - 1 && a > 1 && (i._completed = !0, n.terminated = !0), i.content += n.text, i._output ||= [], i._output.push(n);
175
- }
176
- return r.dispose(), this.outputConversation;
177
- }
178
- resetCache(e) {
179
- this.cache && (this.cache.forEach((e) => {
180
- e && (e.k && e.k.dispose(), e.v && e.v.dispose(), e.k = void 0, e.v = void 0, e.cumulativeLength = 0, e.length = 0);
181
- }), e || (this.cache = null)), this.lastToken = -1;
182
- }
183
- reset() {
184
- this.resetCache(), this.outputConversation = [], this.initialPrompt = null, this.rawOutput = [], this.lastLoss = null, this.emit("reset");
185
- }
186
- dispose() {
187
- this.reset();
188
- }
189
- initialise(e, n) {
190
- if (this.cache && n?.noCache && this.reset(), this.initialPrompt = e || null, this.lastToken === -1 && this.outputConversation.length === 0 ? this.outputConversation = this.initialPrompt || [] : e && e.length > 0 && (e.forEach((e) => {
191
- this.outputConversation.push(e);
192
- }), this.resetCache()), !this.cache && !n?.noCache && (this.model.config.modelType !== "GenAI_NanoGPT_v1" || this.model.config.useRope)) {
193
- let e = Array(this.model.config.nLayer);
194
- for (let t = 0; t < this.model.config.nLayer; t++) e[t] = {
195
- k: void 0,
196
- v: void 0,
197
- length: 0,
198
- cumulativeLength: 0
199
- };
200
- this.cache = e, this.lastToken = -1;
201
- }
202
- let r = this.tokeniser.trained ? this.tokeniser : new t(_(h, this.tokeniser.vocabSize));
203
- this.actualTokeniser = r, n?.loraName ? this.model.attachLoRA(n.loraName) : this.model.hasLoRA() && this.model.detachLoRA();
204
- }
205
- async step(e, t) {
206
- let n = {
207
- ...t,
208
- maxLength: 1
209
- };
210
- return v(e) ? this.generate(e, n) : this.generate({
211
- ...e,
212
- ...n
213
- });
214
- }
215
- async generate(e, t) {
216
- let n;
217
- if (Array.isArray(e) ? n = e : typeof e == "object" && (t = e), this.processingJob) {
218
- if (this.jobQueue.length > 10) throw Error("Job queue is too long, rejecting new job");
219
- return new Promise((e, r) => {
220
- this.jobQueue.push({
221
- prompt: n,
222
- options: t,
223
- resolve: e,
224
- reject: r
225
- });
226
- });
227
- }
228
- this.processingJob = !0, this.startTime = Date.now();
229
- try {
230
- let e = await this.startJob(n, t);
231
- if (this.processingJob = !1, this.jobQueue.length > 0) {
232
- let e = this.jobQueue.shift();
233
- this.generate(e.prompt || [], e.options).then(e.resolve).catch(e.reject);
234
- }
235
- return e;
236
- } catch (e) {
237
- throw this.processingJob = !1, e;
238
- }
239
- }
240
- async startJob(e, t) {
241
- this.initialise(e, t), this.active = !0, this.model.metaData.generationSettings = t, t?.maxLength !== 1 && this.emit("start");
242
- let n = await this._generate(t, !!e);
243
- return this.active = !1, this.startTime !== null && (this.startTime = null), this.emit("stop"), n;
244
- }
245
- getQueueLength() {
246
- return this.jobQueue.length;
247
- }
248
- stop() {
249
- this.active = !1;
250
- }
251
- getConversation() {
252
- return this.outputConversation;
253
- }
254
- getRawOutput() {
255
- return this.rawOutput;
256
- }
257
- };
258
- //#endregion
259
- export { y as default, v as isConversation };
1
+ export { t as default, n as isConversation } from "../Generator-BcR_14Cj.js";
@@ -1,4 +1,5 @@
1
1
  import { Conversation, ITokeniser } from '../tokeniser/type';
2
2
  import { IGenerateOptions } from './types';
3
3
  import { Tensor } from '@tensorflow/tfjs-core';
4
- export default function tokenisePrompt(tokeniser: ITokeniser, blockSize: number, prompt?: Conversation[], options?: IGenerateOptions): Promise<Tensor>;
4
+ export declare function tensorFromTokens(tokens: number[]): Tensor;
5
+ export default function tokenisePrompt(tokeniser: ITokeniser, blockSize: number, prompt?: Conversation[], options?: IGenerateOptions): Promise<number[]>;
@@ -1,13 +1,17 @@
1
- import { I as e } from "../dist-Da20xy8E.js";
2
- //#region lib/inference/tokenisePrompt.ts
3
- async function t(t, n, r, i) {
4
- if (r) {
5
- let a = r.length > 0 && (r[r.length - 1].role === "text" || r[r.length - 1].role === "assistant"), o;
6
- return i?.nonConversational ? o = a && i?.continuation ? [t.bosToken, ...t.encode(r[r.length - 1].content)] : t.encodeAsSequence(r, !0) : a && i?.continuation ? (o = t.encodeConversation(r, !0), o[o.length - 1] === t.getSpecialTokenIndex("<|assistant_start|>") && o[o.length - 2] === t.getSpecialTokenIndex("<|assistant_end|>") && (o.pop(), o.pop())) : o = t.encodeConversation(r, !0), o.length > n && (o = o.slice(-n)), i?.debug && console.log("Tokenised prompt:", t.decode(o)), e([o], [1, o.length], "int32");
7
- } else {
8
- let n = i?.nonConversational ? void 0 : t.getSpecialTokenIndex("<|assistant_start|>"), r = n === void 0 ? [t.bosToken] : [t.bosToken, n];
9
- return e([r], [1, r.length], "int32");
1
+ import "../dist-CMMLi-qO.js";
2
+ import { t as e } from "../tensor2d-ARItvqVn.js";
3
+ // lib/inference/tokenisePrompt.ts
4
+ function t(t) {
5
+ return e([t], [1, t.length], "int32");
6
+ }
7
+ async function n(e, t, n, r) {
8
+ if (n) {
9
+ let i = n.length > 0 && (n[n.length - 1].role === "text" || n[n.length - 1].role === "assistant"), a;
10
+ return r?.nonConversational ? a = i && r?.continuation ? [e.bosToken, ...e.encode(n[n.length - 1].content)] : e.encodeAsSequence(n, !0) : i && r?.continuation ? (a = e.encodeConversation(n, !0), a[a.length - 1] === e.getSpecialTokenIndex("<|assistant_start|>") && a[a.length - 2] === e.getSpecialTokenIndex("<|assistant_end|>") && (a.pop(), a.pop())) : a = e.encodeConversation(n, !0), a.length > t && (a = a.slice(-t)), r?.debug && console.log("Tokenised prompt:", e.decode(a)), a;
11
+ }
12
+ {
13
+ let t = r?.nonConversational ? void 0 : e.getSpecialTokenIndex("<|assistant_start|>");
14
+ return t === void 0 ? [e.bosToken] : [e.bosToken, t];
10
15
  }
11
16
  }
12
- //#endregion
13
- export { t as default };
17
+ export { n as default, t as tensorFromTokens };