File size: 11,515 Bytes
d376ead
7952faf
d376ead
 
 
 
7952faf
d376ead
 
 
 
 
 
 
7952faf
d376ead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7952faf
d376ead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7952faf
d376ead
 
 
 
 
 
 
 
7952faf
d376ead
7952faf
d376ead
 
 
 
 
 
7952faf
d376ead
 
 
 
 
 
 
7952faf
d376ead
 
 
 
7952faf
d376ead
7952faf
d376ead
 
7952faf
d376ead
 
 
 
 
 
 
 
7952faf
d376ead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7952faf
 
d376ead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7952faf
d376ead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { Wllama } from 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.1/esm/index.js';

// Constants
const MODEL_MAX_CONTEXT = 512;
const MODEL_FILE = 'model_f16.gguf';
const textDecoder = new TextDecoder();

// State
let wllama = null;
let engineReady = false;
let isGenerating = false;
let userStopped = false;
let abortController = null;
let progressTimer = null;  // delay timer β€” prevents flicker on fast connections

// DOM
const deviceBadge       = document.getElementById('deviceBadge');
const promptInput       = document.getElementById('promptInput');
const generateBtn       = document.getElementById('generateBtn');
const generateBtnText   = document.getElementById('generateBtnText');
const stopBtn           = document.getElementById('stopBtn');
const copyBtn           = document.getElementById('copyBtn');
const clearBtn          = document.getElementById('clearBtn');
const outputBox         = document.getElementById('outputBox');
const statusText        = document.getElementById('statusText');
const tempInput         = document.getElementById('temperature');
const tempVal           = document.getElementById('tempValue');
const progressOverlay   = document.getElementById('progressOverlay');
const progressFill      = document.getElementById('progressFill');
const progressPct       = document.getElementById('progressPct');
const progressLabel     = document.getElementById('progressLabel');
const progressSub       = document.getElementById('progressSub');
const promptTokenMetric = document.getElementById('promptTokenMetric');
const generatedTokenMetric = document.getElementById('generatedTokenMetric');
const speedMetric       = document.getElementById('speedMetric');
const timeMetric        = document.getElementById('timeMetric');

// Slider UI
tempInput.addEventListener('input', (e) =>
    tempVal.textContent = parseFloat(e.target.value).toFixed(2));

// ──────────────────────────────────────────
// Progress overlay helpers
// ──────────────────────────────────────────
function showProgress(label = 'Downloading model…', sub = 'FP16 Β· 43 MB Β· first run only') {
    progressLabel.textContent = label;
    progressSub.textContent = sub;
    setProgress(0);
    // Delay by 400ms β€” if download finishes faster, overlay never appears (no flicker)
    clearTimeout(progressTimer);
    progressTimer = setTimeout(() => {
        progressOverlay.classList.remove('hidden');
    }, 400);
}

function setProgress(pct, loaded, total) {
    const p = Math.min(100, Math.max(0, pct));
    progressFill.style.width = `${p}%`;
    progressPct.textContent = `${Math.round(p)}%`;
    if (typeof loaded === 'number' && typeof total === 'number' && total > 0) {
        const mb = (total / 1024 / 1024).toFixed(0);
        const done = (loaded / 1024 / 1024).toFixed(1);
        progressSub.textContent = `${done} / ${mb} MB downloaded`;
    }
}

function hideProgress() {
    clearTimeout(progressTimer);  // cancel delayed show if download was fast
    progressTimer = null;
    progressOverlay.classList.add('hidden');
    setProgress(0);
}

// ──────────────────────────────────────────
// Engine initialisation (lazy β€” called on first Generate click)
// ──────────────────────────────────────────
async function initializeEngine() {
    deviceBadge.textContent = 'Loading…';
    deviceBadge.className = 'badge loading';
    showProgress('Downloading model…', 'FP16 Β· 43 MB Β· cached after first run');

    const CONFIG_PATHS = {
        'single-thread/wllama.wasm': 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.1/src/single-thread/wllama.wasm',
        'multi-thread/wllama.wasm':  'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.1/src/multi-thread/wllama.wasm',
    };

    wllama = new Wllama(CONFIG_PATHS);

    const nThreads = Math.min(8, navigator.hardwareConcurrency || 4);
    const modelUrl = new URL(`./${MODEL_FILE}`, import.meta.url).href;

    await wllama.loadModelFromUrl(modelUrl, {
        n_ctx: MODEL_MAX_CONTEXT,
        n_threads: nThreads,
        cache_type_k: 'f32',
        cache_type_v: 'f32',
        progressCallback: ({ loaded, total }) => {
            if (total > 0) setProgress((loaded / total) * 100, loaded, total);
        },
    });

    hideProgress();
    engineReady = true;
    deviceBadge.className = 'badge webgpu';
    deviceBadge.textContent = 'FP16 Β· WASM';
    console.log('Wllama engine ready.');
}

// ──────────────────────────────────────────
// Update prompt-token metric
// ──────────────────────────────────────────
async function updatePromptMetric() {
    if (!wllama) return;
    try {
        const tokens = await wllama.tokenize(promptInput.value || '');
        promptTokenMetric.textContent = `${tokens.length} prompt tok`;
    } catch (_) {}
}

promptInput.addEventListener('input', updatePromptMetric);

// ──────────────────────────────────────────
// Main Generate handler
// ──────────────────────────────────────────
async function handleGenerate() {
    if (isGenerating) return;

    const promptText = promptInput.value.trim();
    if (!promptText) { promptInput.focus(); return; }

    // First click: load the engine, then immediately generate
    if (!engineReady) {
        generateBtn.disabled = true;
        generateBtnText.textContent = 'Loading…';
        statusText.textContent = '';
        try {
            await initializeEngine();
        } catch (err) {
            console.error('Engine load failed:', err);
            deviceBadge.className = 'badge wasm';
            deviceBadge.textContent = 'Error';
            statusText.textContent = 'Failed to load model.';
            generateBtn.disabled = false;
            generateBtnText.textContent = 'Retry';
            hideProgress();
            return;
        }
        generateBtn.disabled = false;
        generateBtnText.textContent = 'Generate';
    }

    await runGeneration(promptText);
}

// ──────────────────────────────────────────
// Token-by-token generation loop
// ──────────────────────────────────────────
async function runGeneration(promptText) {
    const temperature = parseFloat(tempInput.value);
    const maxNewTokens = MODEL_MAX_CONTEXT - 20; // use almost full context

    isGenerating = true;
    userStopped = false;
    abortController = new AbortController();

    generateBtn.disabled = true;
    generateBtnText.textContent = 'Generating…';
    stopBtn.disabled = false;
    statusText.textContent = '';

    // Build output DOM
    outputBox.innerHTML = '';
    const promptSpan = document.createElement('span');
    promptSpan.className = 'prompt-text';
    promptSpan.textContent = promptText;
    const generatedNode = document.createTextNode('');
    const cursorSpan = document.createElement('span');
    cursorSpan.className = 'cursor';
    cursorSpan.textContent = '|';
    outputBox.appendChild(promptSpan);
    outputBox.appendChild(generatedNode);
    outputBox.appendChild(cursorSpan);

    let count = 0;
    const t0 = performance.now();
    const eosId = wllama.getEOS();

    try {
        await wllama.kvClear();

        // BOS fix: wllama tokenizer never adds BOS, so we prepend manually
        const rawTokens   = await wllama.tokenize(promptText, false);
        const promptTokens = [wllama.getBOS(), ...rawTokens];

        await wllama.decode(promptTokens, { skipLogits: false });
        await wllama.samplingInit({
            temp: temperature,
            top_k: 40,
            top_p: 0.90,
            penalty_repeat: 1.15,
            penalty_last_n: 256,
            penalty_present: 0.5,
            penalty_freq: 0.5,
        }, promptTokens);

        for (let i = 0; i < maxNewTokens; i++) {
            if (userStopped || abortController.signal.aborted) break;

            const sampled = await wllama.samplingSample();
            const tok = sampled.token;
            if (tok === eosId || tok === 3 || tok === 0) break;

            await wllama.samplingAccept([tok]);

            const piece = typeof sampled.piece === 'string'
                ? sampled.piece
                : textDecoder.decode(sampled.piece, { stream: true });

            generatedNode.data += piece;
            count++;

            await wllama.decode([tok], { skipLogits: false });

            const elapsed = (performance.now() - t0) / 1000;
            if (elapsed > 0) {
                generatedTokenMetric.textContent = `${count} tok generated`;
                speedMetric.textContent = `${(count / elapsed).toFixed(1)} tok/s`;
                timeMetric.textContent = `${elapsed.toFixed(1)}s`;
            }
            outputBox.scrollTop = outputBox.scrollHeight;
        }

        statusText.textContent = userStopped ? 'Stopped' : 'Done';
        await updatePromptMetric();

    } catch (err) {
        statusText.textContent = userStopped ? 'Stopped' : 'Error';
        if (!userStopped) console.error(err);
    } finally {
        isGenerating = false;
        generateBtn.disabled = false;
        generateBtnText.textContent = 'Generate';
        stopBtn.disabled = true;
        cursorSpan.remove();
    }
}

// ──────────────────────────────────────────
// Event Listeners
// ──────────────────────────────────────────
generateBtn.addEventListener('click', handleGenerate);

stopBtn.addEventListener('click', () => {
    userStopped = true;
    abortController?.abort();
});

copyBtn.addEventListener('click', () => {
    const text = outputBox.innerText.replace(/\|$/, '');
    navigator.clipboard.writeText(text).then(() => {
        const orig = copyBtn.textContent;
        copyBtn.textContent = 'Copied!';
        setTimeout(() => copyBtn.textContent = orig, 1800);
    });
});

clearBtn.addEventListener('click', () => {
    if (isGenerating) return;
    promptInput.value = '';
    outputBox.innerHTML = '<span class="placeholder-text">ΰ€†ΰ€ͺΰ€•ΰ₯€ ΰ€•ΰ€Ήΰ€Ύΰ€¨ΰ₯€ ΰ€―ΰ€Ήΰ€Ύΰ€ ΰ€¦ΰ€Ώΰ€–ΰ€Ύΰ€ˆ ΰ€¦ΰ₯‡ΰ€—ΰ₯€β€¦</span>';
    promptTokenMetric.textContent = 'β€”';
    generatedTokenMetric.textContent = 'β€”';
    speedMetric.textContent = 'β€”';
    timeMetric.textContent = 'β€”';
    statusText.textContent = '';
});

document.querySelectorAll('.sample-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        if (isGenerating) return;
        const text = btn.getAttribute('data-prompt');
        promptInput.value = text;
        outputBox.innerHTML = `<span class="prompt-text">${text}</span><span class="cursor">|</span>`;
        promptInput.focus();
        if (engineReady) updatePromptMetric();
    });
});