File size: 2,613 Bytes
5bb7ffa
 
 
 
a8293d1
5bb7ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8293d1
5bb7ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// DR-Tulu2-4B as a GGUF (bartowski Q4_K_M) on wllama: llama.cpp compiled to WebAssembly, with its WebGPU backend.
// Sampling, the prompt-prefix cache and the context window are llama.cpp's own (the same server-context as llama-server).
import { Wllama } from './vendor/wllama/index.js';

export const SAMPLING = { temperature: 1.0, top_p: 0.95, top_k: 20, min_p: 0, presence_penalty: 1.5 };   // min_p 0: llama.cpp defaults to 0.05   // DR Tulu 2's BrowseComp-Plus eval settings

export async function createEngine({ url, nCtx = 32768, gpu = true, onProgress, onStatus }) {
  const wllama = new Wllama({ default: new URL('./vendor/wllama/wllama.wasm', import.meta.url).href });
  const tryLoad = async (n_ctx, useCache) => {
    await wllama.loadModelFromUrl(url, {
      n_ctx, n_gpu_layers: gpu ? 999 : 0, connections: 6, cache_type_k: 'f16', cache_type_v: 'f16', useCache,
      progressCallback: ({ loaded, total }) => onProgress?.(loaded, total),
    });
  };
  let useCache = true;
  for (let attempt = 0; ; attempt++) {
    try { await tryLoad(nCtx, useCache); break; } catch (e) {
      console.warn('load failed:', e);
      await wllama.exit().catch(() => {});
      if (useCache && /quota|storage is full|QuotaExceeded/i.test(`${e?.name} ${e?.message}`)) {    // no room to keep the model on disk: load it without the cache
        onStatus?.('Not enough browser storage to keep the model for next time: loading it without saving…'); useCache = false; continue;
      }
      if (nCtx > 16384 && attempt < 3) { onStatus?.('Could not load with the long context (memory?), retrying with a 16k one…'); nCtx = 16384; continue; }
      throw e;
    }
  }
  let info = {}; try { info = wllama.getLoadedContextInfo(); } catch { /* optional */ }
  return {
    nCtx, info,
    // Stream a raw completion. `prompt` is the whole transcript so far; llama.cpp reuses the cached prefix, so only new text is read.
    async *complete(prompt, { maxTokens = 6000, signal, sampling = SAMPLING } = {}) {
      const stream = await wllama.createCompletion({ prompt, stream: true, max_tokens: maxTokens, abortSignal: signal, return_progress: true, ...sampling });
      for await (const chunk of stream) {
        const c = chunk.choices?.[0];
        yield { text: c?.text ?? '', finish: c?.finish_reason ?? null, progress: chunk.prompt_progress ?? null, usage: chunk.usage ?? null, timings: chunk.timings ?? null };
      }
    },
    async countTokens(text) { try { return (await wllama.tokenize(text)).length; } catch { return Math.ceil(text.length / 3.2); } },
    async exit() { await wllama.exit(); },
  };
}