-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitnet3.html
More file actions
253 lines (220 loc) · 12.5 KB
/
bitnet3.html
File metadata and controls
253 lines (220 loc) · 12.5 KB
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
<!DOCTYPE html>
<html lang="pt-pt">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>BitNet v1.58 - Mobile Runner</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body { background: #050508; color: #e2e8f0; font-family: ui-monospace, 'JetBrains Mono', monospace; }
.glass { background: rgba(15, 23, 42, 0.9); backdrop-filter: blur(12px); border: 1px solid rgba(51, 65, 85, 0.4); }
.hide-scrollbar::-webkit-scrollbar { display: none; }
@keyframes pulse-slow { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
.loading-text { animation: pulse-slow 2s infinite; }
.terminal-log { font-size: 10px; color: #64748b; line-height: 1.4; }
</style>
</head>
<body class="flex flex-col h-screen overflow-hidden p-4">
<!-- Header -->
<header class="flex justify-between items-center mb-4">
<div>
<h1 class="text-lg font-black text-blue-500 italic uppercase">BitNet <span class="text-white">Mobile</span></h1>
<div class="flex items-center gap-2">
<div id="device-led" class="w-2 h-2 rounded-full bg-red-500"></div>
<p id="device-tag" class="text-[9px] text-zinc-500 font-bold uppercase tracking-widest">WebGPU: Indisponível</p>
</div>
</div>
<button onclick="location.reload()" class="p-2 bg-zinc-900 rounded-xl border border-white/5">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#64748b" stroke-width="2"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg>
</button>
</header>
<!-- Main Stack -->
<div class="flex-1 flex flex-col space-y-4 overflow-hidden">
<!-- Terminal Logs -->
<div id="terminal" class="glass rounded-2xl p-4 h-32 overflow-y-auto hide-scrollbar terminal-log">
<div>[SISTEMA] Aguardando inicialização...</div>
</div>
<!-- Action Panel -->
<div id="main-panel" class="flex-1 flex flex-col space-y-4 overflow-hidden">
<!-- Selection View -->
<div id="selection-view" class="space-y-3">
<div class="p-4 bg-blue-500/5 border border-blue-500/20 rounded-2xl">
<p class="text-[10px] text-blue-400 font-bold mb-2 uppercase">Modo de Execução</p>
<select id="device-select" class="w-full bg-zinc-900 border border-white/10 rounded-xl p-3 text-xs outline-none focus:ring-1 focus:ring-blue-500">
<option value="webgpu">WebGPU (Acelerado - Recomendado)</option>
<option value="cpu">CPU (Modo de Segurança / Lento)</option>
</select>
</div>
<button onclick="bootModel('onnx-community/BitNet-b1.58-100M-ONNX')" class="w-full bg-blue-600 hover:bg-blue-500 p-5 rounded-3xl text-left transition-all shadow-lg shadow-blue-900/20 active:scale-95">
<h3 class="font-bold text-white text-sm">Carregar BitNet 100M</h3>
<p class="text-[9px] text-blue-200 mt-1 opacity-70 italic uppercase">Otimizado para baixa latência</p>
</button>
<!-- WebGPU Guide (Visible if offline) -->
<div id="webgpu-guide" class="p-4 bg-zinc-900/50 border border-zinc-800 rounded-2xl space-y-2">
<p class="text-[10px] font-bold text-zinc-500 uppercase">Como ativar WebGPU no Android:</p>
<ol class="text-[10px] text-zinc-600 space-y-1 ml-3 list-decimal">
<li>Acede a <span class="text-blue-500">chrome://flags</span></li>
<li>Procura por <span class="text-blue-500">Unsafe WebGPU</span> e ativa.</li>
<li>Procura por <span class="text-blue-500">WebGPU Developer Mode</span> e ativa.</li>
<li>Reinicia o Chrome.</li>
</ol>
</div>
</div>
<!-- Loader (Hidden) -->
<div id="loader" class="hidden glass rounded-3xl p-6 space-y-4">
<div class="flex justify-between items-end">
<div class="space-y-1">
<p id="file-name" class="text-[10px] text-blue-400 font-bold uppercase">A descarregar...</p>
<p class="text-[9px] text-zinc-500 font-bold loading-text uppercase">Transferindo Pesos do Modelo</p>
</div>
<span id="load-pct" class="text-2xl font-black text-white tracking-tighter">00%</span>
</div>
<div class="h-1 w-full bg-white/5 rounded-full overflow-hidden">
<div id="progress-bar" class="h-full bg-blue-500 w-0 transition-all duration-300"></div>
</div>
</div>
<!-- Chat (Hidden) -->
<div id="chat-messages" class="hidden flex-1 overflow-y-auto space-y-4 pr-1 hide-scrollbar"></div>
</div>
<!-- Input Area -->
<footer id="chat-input" class="hidden pb-6">
<div class="flex gap-2">
<input id="prompt-in" type="text" placeholder="Comando de prompt..." class="flex-1 bg-white/5 border border-white/10 rounded-2xl px-5 py-4 text-xs focus:outline-none focus:ring-1 focus:ring-blue-500">
<button id="send-btn" class="bg-blue-600 p-4 rounded-2xl text-white active:scale-90 shadow-lg shadow-blue-900/40">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>
</button>
</div>
</footer>
</div>
<script type="module">
import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.0.0-alpha.19';
const dom = {
terminal: document.getElementById('terminal'),
deviceTag: document.getElementById('device-tag'),
deviceLed: document.getElementById('device-led'),
deviceSelect: document.getElementById('device-select'),
selection: document.getElementById('selection-view'),
loader: document.getElementById('loader'),
pBar: document.getElementById('progress-bar'),
pPct: document.getElementById('load-pct'),
pFname: document.getElementById('file-name'),
chat: document.getElementById('chat-messages'),
input: document.getElementById('chat-input'),
guide: document.getElementById('webgpu-guide')
};
let generator = null;
function log(msg, type = 'info') {
const div = document.createElement('div');
const color = type === 'error' ? 'text-red-500' : (type === 'success' ? 'text-emerald-500' : 'text-zinc-500');
div.className = color;
div.innerText = `[${new Date().toLocaleTimeString().split(' ')[0]}] ${msg}`;
dom.terminal.appendChild(div);
dom.terminal.scrollTop = dom.terminal.scrollHeight;
}
async function checkHardware() {
log("A verificar compatibilidade de hardware...");
if (!navigator.gpu) {
log("WebGPU não suportada neste navegador.", "error");
dom.deviceSelect.value = "cpu";
return;
}
try {
const adapter = await navigator.gpu.requestAdapter();
if (adapter) {
dom.deviceTag.innerText = `WebGPU: ${adapter.name.substring(0, 15)}...`;
dom.deviceLed.classList.replace('bg-red-500', 'bg-emerald-500');
dom.guide.classList.add('hidden');
log("Aceleração WebGPU detetada: " + adapter.name, "success");
} else {
throw new Error("Adaptador GPU recusado.");
}
} catch (e) {
log("Falha ao aceder à GPU: " + e.message, "error");
dom.deviceSelect.value = "cpu";
}
}
window.bootModel = async (modelId) => {
dom.selection.classList.add('hidden');
dom.loader.classList.remove('hidden');
const selectedDevice = dom.deviceSelect.value;
log(`A carregar pipeline (${selectedDevice})...`);
try {
env.allowLocalModels = false;
env.useBrowserCache = true;
env.remoteHost = 'https://huggingface.co';
generator = await pipeline('text-generation', modelId, {
device: selectedDevice,
dtype: selectedDevice === 'webgpu' ? 'fp32' : 'fp32',
progress_callback: (p) => {
if (p.status === 'progress') {
dom.pBar.style.width = `${p.progress}%`;
dom.pPct.innerText = `${Math.round(p.progress)}%`;
}
if (p.status === 'initiate') {
dom.pFname.innerText = p.file.split('/').pop();
}
}
});
log("Modelo carregado com sucesso!", "success");
dom.loader.classList.add('hidden');
dom.chat.classList.remove('hidden');
dom.input.classList.remove('hidden');
appendMsg('ai', `Sistema BitNet ativo via ${selectedDevice.toUpperCase()}. Preparado para inferência local.`);
} catch (err) {
log("Erro no carregamento: " + err.message, "error");
dom.loader.classList.add('hidden');
dom.selection.classList.remove('hidden');
if (err.message.includes("401")) {
log("DICA: Tenta carregar o modelo novamente ou verifica a tua ligação.", "error");
}
}
};
function appendMsg(role, text, latency = null) {
const div = document.createElement('div');
const isAi = role === 'ai';
div.className = `flex flex-col gap-1 ${!isAi ? 'items-end' : ''}`;
div.innerHTML = `
<span class="text-[8px] font-bold text-zinc-600 uppercase tracking-tighter">${isAi ? 'BitNet.Out' : 'User.In'}</span>
<div class="${isAi ? 'bg-zinc-900 border border-white/5' : 'bg-blue-600 text-white'} p-4 rounded-2xl text-[12px] max-w-[85%] leading-relaxed">
${text}
</div>
${latency ? `<span class="text-[8px] font-mono text-zinc-700 mt-1 italic uppercase">Latência: ${latency}s</span>` : ''}
`;
dom.chat.appendChild(div);
dom.chat.scrollTop = dom.chat.scrollHeight;
}
async function generate() {
const input = document.getElementById('prompt-in');
const text = input.value.trim();
if (!text || !generator) return;
input.value = '';
appendMsg('user', text);
log("A processar inferência...");
const aiDiv = appendMsg('ai', '<span class="loading-text italic">A gerar resposta...</span>');
const contentBox = aiDiv.querySelector('div');
const start = performance.now();
try {
const output = await generator(text, {
max_new_tokens: 50,
temperature: 0.7,
do_sample: true
});
const latency = ((performance.now() - start) / 1000).toFixed(2);
const result = output[0].generated_text.slice(text.length).trim();
contentBox.innerText = result || "(Sem saída)";
const meta = document.createElement('span');
meta.className = "text-[8px] font-mono text-zinc-700 mt-1 italic uppercase block";
meta.innerText = `Latência: ${latency}s | Kernel: ${dom.deviceSelect.value.toUpperCase()}`;
aiDiv.appendChild(meta);
log(`Inferência concluída em ${latency}s.`);
} catch (err) {
log("Erro na geração: " + err.message, "error");
contentBox.innerText = "Falha crítica na inferência.";
}
}
document.getElementById('send-btn').onclick = generate;
document.getElementById('prompt-in').onkeypress = (e) => e.key === 'Enter' && generate();
checkHardware();
</script>
</body>
</html>