Spaces:
Running
Running
| /* Ares browser runtime. It uses an optional user-trained ONNX checkpoint; otherwise it stays in local foundation mode. */ | |
| let modelSession=null, modelConfig={block_size:256}; | |
| async function loadAresModel(){try{if(!window.ort)return; modelSession=await ort.InferenceSession.create('ares_model.onnx',{executionProviders:['wasm']}); const el=document.querySelector('.runtime span'); if(el)el.textContent='Trained checkpoint loaded'; const sm=document.querySelector('.runtime small'); if(sm)sm.textContent='local ONNX inference';}catch(e){console.info('No browser checkpoint loaded; using foundation mode.',e.message)}} | |
| function utf8bytes(s){return [...new TextEncoder().encode(s)]} | |
| async function generateAres(prompt,maxNew=180){if(!modelSession)return null;let ids=utf8bytes(prompt);for(let i=0;i<maxNew;i++){let x=ids.slice(-modelConfig.block_size);let t=new ort.Tensor('int64',BigInt64Array.from(x.map(BigInt)),[1,x.length]);let out=await modelSession.run({input_ids:t});let a=out.logits.data, vocab=out.logits.dims[2], off=(x.length-1)*vocab;let best=0;for(let j=1;j<vocab;j++)if(a[off+j]>a[off+best])best=j;ids.push(best);if(best===10&&i>20)break}return new TextDecoder().decode(new Uint8Array(ids)).replace(/^.*?Ares:\s*/s,'')} | |
| const $=s=>document.querySelector(s); const chat=$('#chat'), input=$('#input'); | |
| const KEY='ares-memory-v1'; let memory=JSON.parse(localStorage.getItem(KEY)||'[]'); | |
| const architecture=`Ares is being built as a decoder-only Transformer. The planned path is: trained BPE tokenizer → token embeddings → RoPE positional rotations → grouped-query multi-head attention with KV cache → RMSNorm → SwiGLU feed-forward layers → residual stream → RMSNorm → unembedding and softmax. This static foundation slice currently provides the tokenizer, context accounting, local memory, and a deterministic planner. Transformer weights are deliberately not faked: the next milestone is an offline-trained checkpoint exported for browser inference.`; | |
| function tokenize(s){return s.trim().split(/\s+/).filter(Boolean).flatMap(w=>{let out=[]; for(let i=0;i<w.length;i+=4) out.push(w.slice(i,i+4)); return out});} | |
| function updateCount(){let n=tokenize(input.value).length; $('#tokenCount').textContent=`${n.toLocaleString()} / 2,048 tokens`; let pct=Math.min(100,n/2048*100); $('#ctxBar').style.width=pct+'%';$('#ctxLabel').textContent=Math.round(pct)+'%'} | |
| function save(){localStorage.setItem(KEY,JSON.stringify(memory));$('#memoryCount').textContent=`${memory.length} local record${memory.length===1?'':'s'}`} | |
| function add(role,text){let row=document.createElement('div');row.className='message '+role;if(role==='assistant')row.innerHTML='<div class="mini">A</div><div class="bubble"></div>';else row.innerHTML='<div class="bubble"></div>';row.querySelector('.bubble').textContent=text;chat.append(row);chat.scrollTop=chat.scrollHeight} | |
| function findMemory(q){let words=q.toLowerCase().split(/\W+/).filter(x=>x.length>3);return memory.filter(x=>words.some(w=>x.text.toLowerCase().includes(w))).slice(-3)} | |
| async function respond(q){let l=q.toLowerCase(); if(modelSession&&!/remember|my name|call me|memory/.test(l)){let generated=await generateAres('User: '+q+'\nAres: '); if(generated&&generated.trim().length>0)return generated.trim()} if(/architecture|transformer|how.*built|components/.test(l))return architecture; if(/what.*train|training|first step|roadmap/.test(l))return `We should earn capability in small, testable stages:\n\n1. Train and evaluate a 16k–32k vocabulary tokenizer.\n2. Train a tiny decoder-only model (millions of parameters) with next-token cross-entropy, AdamW, gradient clipping, and checkpoints.\n3. Add data quality filters, held-out evaluation, and code/conversation SFT.\n4. Add retrieval and safe tools outside the core model.\n5. Scale only after loss curves and evals improve.\n\nA static Hugging Face Space cannot train a billion-parameter model or keep a server-side SQLite database; those require an offline GPU runner or hosted backend. This UI is the deployable shell.`; if(/remember|my name|call me/.test(l)){let fact=q.replace(/^.*?(remember|call me)\s*/i,'').trim();memory.push({text:fact||q,at:Date.now()});save();return `I stored that in browser-local memory. It stays on this device until you clear it.`} if(/memory|remember/.test(l)&&memory.length)return `I found ${memory.length} local record${memory.length===1?'':'s'}:\n`+memory.map(x=>'• '+x.text).join('\n');let hits=findMemory(q);let context=hits.length?'\n\nRelevant local memory:\n'+hits.map(x=>'• '+x.text).join('\n'):''; if(/hello|hi\b|hey/.test(l))return `Hello. I’m Ares in local foundation mode. I can explain the build plan, track local notes, and help turn the next component into code.`;return `I’m running the no-network foundation runtime, so I won’t pretend a randomly initialized Transformer is intelligent. I can still help structure this task.\n\nYou asked: “${q}”${context}\n\nTry asking about the architecture, training order, or say “remember …”.`} | |
| function send(){let q=input.value.trim();if(!q)return;document.querySelector('.welcome')?.remove();add('user',q);input.value='';updateCount();setTimeout(async()=>add('assistant',await respond(q)),180)} | |
| $('#composer').addEventListener('submit',e=>{e.preventDefault();send()});input.addEventListener('input',updateCount);input.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send()}});document.querySelectorAll('.suggestions button').forEach(b=>b.onclick=()=>{input.value=b.textContent;send()});$('#clearMemory').onclick=()=>{memory=[];save();add('assistant','Local memory cleared.')};$('#newChat').onclick=()=>{chat.innerHTML='';location.reload()};save(); loadAresModel(); | |