Upload index.html
Browse files- index.html +163 -66
index.html
CHANGED
|
@@ -197,16 +197,16 @@ textarea{width:100%;min-height:90px;font:inherit;font-size:.95rem;background:var
|
|
| 197 |
const ORG = "VeroLM"; // Hugging Face organization name
|
| 198 |
|
| 199 |
const T = {
|
| 200 |
-
en:{optTemp:"Temperature",optTopK:"Top-k",optMax:"Max length",optEod:"EOD code",optStop:"Stop at EOD",navData:"Datasets",hData:"Datasets",subData:"Open datasets published by VeroLM on Hugging Face.",sErrCustom:"The model’s own runner failed to start. Check the browser console for details.",note:"Not every model runs directly in the browser. Mostly newer, compatible models do. If a model can’t run, its Run button is greyed out and can’t be clicked.",noRun:"Not available in the browser",navModels:"Models",h1:"Open models at every size.",lead:"Fast, efficient and mostly open source. We train language models from tiny to large and release them for everyone to use for free.",ctaModels:"Browse models",ctaHF:"Follow on Hugging Face",hModels:"Series and models",subModels:"Our current models on Hugging Face. Inspect opens the model page, Run tries it in your browser.",hAbout:"Our approach",subAbout:"VeroLM is an independent AI lab.",p1h:"Quality first",p1:"We build models that genuinely perform, not just models that exist.",p2h:"Speed and efficiency",p2:"Every model is as fast and optimized as we can make it, so it runs on the hardware people actually have.",p3h:"Open by default",p3:"Most of what we train is open source and free. Good AI shouldn’t sit behind a paywall.",p4h:"Experimentation",p4:"We constantly try rarely explored ideas in architecture, training and optimization.",foot:"Built with curiosity, released for everyone.",
|
| 201 |
inspect:"Inspect",run:"Run",close:"Close",model:"model",models:"models",ds:"dataset",dss:"datasets",dsTag:"Dataset",dl:"downloads",oopsT:"Oops, no models here yet.",oopsB:"New releases will show up here as soon as they’re published.",phPrompt:"Type something...",
|
| 202 |
sNoGpu:"WebGPU isn’t available in this browser, so the slower CPU mode will be used.",sGpu:"WebGPU is ready. The first run downloads the model and keeps it in your browser.",sLoad:"Loading model",sReady:"Model ready.",sGen:"Generating...",sErr:"Couldn’t open this model in the browser. It may not be published in a browser-ready (ONNX) format yet."},
|
| 203 |
-
tr:{optTemp:"Sıcaklık",optTopK:"Top-k",optMax:"Maks. uzunluk",optEod:"EOD kodu",optStop:"EOD’da dur",navData:"Veri setleri",hData:"Veri setleri",subData:"VeroLM’in Hugging Face’te yayınladığı açık veri setleri.",sErrCustom:"Modelin kendi çalıştırıcısı başlatılamadı. Ayrıntı için tarayıcı konsoluna bak.",note:"Her model doğrudan tarayıcıda çalışmaz, genellikle yeni ve uygun modeller çalışır. Çalışmayacak modellerde Çalıştır düğmesi sönük olur ve tıklanamaz.",noRun:"Bu model tarayıcıda çalışmaz",navModels:"Modeller",h1:"Her boyutta açık modeller.",lead:"Hızlı, verimli ve çoğunlukla açık kaynak. Küçükten büyüğe dil modelleri eğitiyor, herkesin ücretsiz kullanabilmesi için yayınlıyoruz.",ctaModels:"Modelleri incele",ctaHF:"Hugging Face’te takip et",hModels:"Seriler ve modeller",subModels:"Hugging Face’teki güncel modellerimiz. İncele ile model sayfasını aç, Çalıştır ile tarayıcında dene.",hAbout:"Yaklaşımımız",subAbout:"VeroLM, bağımsız bir yapay zeka laboratuvarı.",p1h:"Önce kalite",p1:"Sadece var olan değil, gerçekten iyi çalışan modeller üretiyoruz.",p2h:"Hız ve verimlilik",p2:"Her model, insanların elindeki donanımda çalışacak şekilde olabildiğince hızlı ve optimize.",p3h:"Varsayılan olarak açık",p3:"Eğittiklerimizin çoğu açık kaynak ve ücretsiz. İyi yapay zeka ücretli duvarların arkasında kalmamalı.",p4h:"Deneysellik",p4:"Mimari, eğitim ve optimizasyonda az denenmiş fikirleri sürekli deniyoruz.",foot:"Merakla geliştirildi, herkes için yayınlandı.",
|
| 204 |
inspect:"İncele",run:"Çalıştır",close:"Kapat",model:"model",models:"model",ds:"veri seti",dss:"veri seti",dsTag:"Veri seti",dl:"indirme",oopsT:"Oops, burada henüz model yok.",oopsB:"Yeni modeller yayınlandığında burada görünecek.",phPrompt:"Bir şey yaz...",
|
| 205 |
sNoGpu:"Bu tarayıcıda WebGPU yok, daha yavaş olan CPU modu kullanılacak.",sGpu:"WebGPU hazır. İlk çalıştırmada model indirilir ve tarayıcıda saklanır.",sLoad:"Model yükleniyor",sReady:"Model hazır.",sGen:"Yanıt üretiliyor...",sErr:"Model tarayıcıda açılamadı. Bu model henüz tarayıcı (ONNX) biçiminde yayınlanmamış olabilir."},
|
| 206 |
-
fr:{optTemp:"Température",optTopK:"Top-k",optMax:"Longueur max.",optEod:"Code EOD",optStop:"Arrêt à l’EOD",navData:"Jeux de données",hData:"Jeux de données",subData:"Jeux de données ouverts publiés par VeroLM sur Hugging Face.",sErrCustom:"Le runner propre au modèle n’a pas pu démarrer. Consultez la console du navigateur.",note:"Tous les modèles ne fonctionnent pas directement dans le navigateur, en général seuls les modèles récents et compatibles le font. Si un modèle ne peut pas s’exécuter, son bouton Exécuter est grisé et non cliquable.",noRun:"Ce modèle ne fonctionne pas dans le navigateur",navModels:"Modèles",h1:"Des modèles ouverts, à toutes les tailles.",lead:"Rapides, efficaces et surtout open source. Nous entraînons des modèles de langage du plus petit au plus grand et les publions pour que tout le monde puisse les utiliser gratuitement.",ctaModels:"Voir les modèles",ctaHF:"Suivre sur Hugging Face",hModels:"Séries et modèles",subModels:"Nos modèles actuels sur Hugging Face. Examiner ouvre la page du modèle, Exécuter l’essaie dans votre navigateur.",hAbout:"Notre approche",subAbout:"VeroLM est un laboratoire d’IA indépendant.",p1h:"La qualité d’abord",p1:"Nous construisons des modèles qui performent vraiment, pas seulement des modèles qui existent.",p2h:"Vitesse et efficacité",p2:"Chaque modèle est aussi rapide et optimisé que possible, pour tourner sur le matériel que les gens ont vraiment.",p3h:"Ouvert par défaut",p3:"La plupart de nos modèles sont open source et gratuits. Une bonne IA ne devrait pas être derrière un paywall.",p4h:"Expérimentation",p4:"Nous testons sans cesse des idées peu explorées en architecture, entraînement et optimisation.",foot:"Créé avec curiosité, publié pour tous.",
|
| 207 |
inspect:"Examiner",run:"Exécuter",close:"Fermer",model:"modèle",models:"modèles",ds:"jeu de données",dss:"jeux de données",dsTag:"Jeu de données",dl:"téléchargements",oopsT:"Oups, aucun modèle ici pour l’instant.",oopsB:"Les nouvelles versions apparaîtront ici dès leur publication.",phPrompt:"Écrivez quelque chose...",
|
| 208 |
sNoGpu:"WebGPU n’est pas disponible dans ce navigateur, le mode CPU, plus lent, sera utilisé.",sGpu:"WebGPU est prêt. Le premier lancement télécharge le modèle et le conserve dans votre navigateur.",sLoad:"Chargement du modèle",sReady:"Modèle prêt.",sGen:"Génération en cours...",sErr:"Impossible d’ouvrir ce modèle dans le navigateur. Il n’est peut-être pas encore publié au format ONNX."},
|
| 209 |
-
es:{optTemp:"Temperatura",optTopK:"Top-k",optMax:"Longitud máx.",optEod:"Código EOD",optStop:"Parar en EOD",navData:"Conjuntos de datos",hData:"Conjuntos de datos",subData:"Conjuntos de datos abiertos publicados por VeroLM en Hugging Face.",sErrCustom:"El runner propio del modelo no pudo iniciarse. Revisa la consola del navegador.",note:"No todos los modelos funcionan directamente en el navegador, normalmente solo los modelos nuevos y compatibles. Si un modelo no puede ejecutarse, su botón Ejecutar aparece atenuado y no se puede pulsar.",noRun:"Este modelo no funciona en el navegador",navModels:"Modelos",h1:"Modelos abiertos de todos los tamaños.",lead:"Rápidos, eficientes y en su mayoría de código abierto. Entrenamos modelos de lenguaje, de pequeños a grandes, y los publicamos para que todos puedan usarlos gratis.",ctaModels:"Ver modelos",ctaHF:"Seguir en Hugging Face",hModels:"Series y modelos",subModels:"Nuestros modelos actuales en Hugging Face. Inspeccionar abre la página del modelo, Ejecutar lo prueba en tu navegador.",hAbout:"Nuestro enfoque",subAbout:"VeroLM es un laboratorio de IA independiente.",p1h:"Primero la calidad",p1:"Construimos modelos que realmente funcionan bien, no solo modelos que existen.",p2h:"Velocidad y eficiencia",p2:"Cada modelo es tan rápido y optimizado como podemos, para que funcione en el hardware que la gente realmente tiene.",p3h:"Abierto por defecto",p3:"La mayoría de lo que entrenamos es de código abierto y gratuito. La buena IA no debería estar detrás de un muro de pago.",p4h:"Experimentación",p4:"Probamos constantemente ideas poco exploradas en arquitectura, entrenamiento y optimización.",foot:"Hecho con curiosidad, publicado para todos.",
|
| 210 |
inspect:"Inspeccionar",run:"Ejecutar",close:"Cerrar",model:"modelo",models:"modelos",ds:"conjunto de datos",dss:"conjuntos de datos",dsTag:"Conjunto de datos",dl:"descargas",oopsT:"Vaya, aún no hay modelos aquí.",oopsB:"Las nuevas versiones aparecerán aquí en cuanto se publiquen.",phPrompt:"Escribe algo...",
|
| 211 |
sNoGpu:"WebGPU no está disponible en este navegador, se usará el modo CPU, más lento.",sGpu:"WebGPU está listo. La primera ejecución descarga el modelo y lo guarda en tu navegador.",sLoad:"Cargando modelo",sReady:"Modelo listo.",sGen:"Generando...",sErr:"No se pudo abrir este modelo en el navegador. Puede que aún no esté publicado en formato ONNX."}
|
| 212 |
};
|
|
@@ -238,6 +238,23 @@ function el(tag, props = {}, ...kids){
|
|
| 238 |
return e;
|
| 239 |
}
|
| 240 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
async function load(){
|
| 242 |
try{
|
| 243 |
// The list endpoint truncates each collection to 4 items, so fetch every collection again for its full item list.
|
|
@@ -283,11 +300,19 @@ async function load(){
|
|
| 283 |
try{ cfg = await (await fetch("https://huggingface.co/" + m.id + "/resolve/main/config.json")).json(); }catch(e){}
|
| 284 |
}
|
| 285 |
const stFiles = f.includes("model.safetensors") ? ["model.safetensors"] : f.filter(n => /^model-\d+-of-\d+\.safetensors$/.test(n)).sort();
|
| 286 |
-
const kind = nativeKind(cfg);
|
|
|
|
| 287 |
if(kind && stFiles.length && !(m.manifest && m.manifest.builtin === false)){
|
| 288 |
-
|
| 289 |
-
|
|
|
|
| 290 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
m.runnable = !!m.runtime;
|
| 292 |
}catch(e){ m.runtime = null; m.runnable = false; }
|
| 293 |
}));
|
|
@@ -537,44 +562,108 @@ function readSafetensors(buf){
|
|
| 537 |
return out;
|
| 538 |
}
|
| 539 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 540 |
/* ---- built-in engines: run a model straight from config.json + weights, no per-repo code needed ---- */
|
| 541 |
// To support another architecture, add an entry to NATIVE_ARCHS keyed by the model_type in its config.json.
|
| 542 |
// Each entry has: build(cfg, tensors) -> model object, and generate(model, prompt, onToken, opts) -> Promise.
|
| 543 |
const NATIVE_ALIASES = {NoTokenLMForCausalLM:"notokenlm"};
|
| 544 |
function nativeKind(cfg){
|
| 545 |
if(!cfg) return null;
|
| 546 |
-
|
| 547 |
-
|
|
|
|
| 548 |
return kind && (!NATIVE_ARCHS[kind].supports || NATIVE_ARCHS[kind].supports(cfg)) ? kind : null;
|
| 549 |
}
|
| 550 |
|
| 551 |
/* NoTokenLM: byte-level (vocab 256), RoPE, RMSNorm, SwiGLU, weight-tied head, UTF-8-safe sampling */
|
| 552 |
-
function
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 567 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
const blocks = [];
|
| 569 |
for(let i = 0; i < L; i++){
|
| 570 |
-
const
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 575 |
}
|
| 576 |
-
|
| 577 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
}
|
| 579 |
|
| 580 |
// y[o] = sum_i W[o*n + i] * x[i] (W is [out, in] row-major, like torch.nn.Linear)
|
|
@@ -645,7 +734,7 @@ function ntStep(M, st, tok, pos, wantLogits){
|
|
| 645 |
}
|
| 646 |
if(wantLogits){
|
| 647 |
ntRms(x, M.fn, xn, D, M.eps);
|
| 648 |
-
ntMatVec(M.
|
| 649 |
}
|
| 650 |
}
|
| 651 |
|
|
@@ -733,56 +822,64 @@ function openRun(m){
|
|
| 733 |
}
|
| 734 |
$("#rclose").onclick = () => $("#dlg").close();
|
| 735 |
|
| 736 |
-
|
| 737 |
-
async function getEngine(m, stat){
|
| 738 |
-
if(engines.has(m.id)) return engines.get(m.id);
|
| 739 |
const pct = p => typeof p === "number" ? " " + Math.round(p) + "%" : "";
|
| 740 |
-
|
| 741 |
-
if(m.runtime === "native"){
|
| 742 |
const base = "https://huggingface.co/" + m.id + "/resolve/main/", arch = NATIVE_ARCHS[m.native.kind], tensors = new Map();
|
| 743 |
for(let i = 0; i < m.native.files.length; i++){
|
| 744 |
stat.textContent = t("sLoad") + "...";
|
| 745 |
const buf = await fetchBuffer(base + m.native.files[i], p => { stat.textContent = t("sLoad") + " (weights" + (m.native.files.length > 1 ? " " + (i + 1) + "/" + m.native.files.length : "") + ")" + pct(p); });
|
| 746 |
for(const [k, v] of readSafetensors(buf)) tensors.set(k, v);
|
| 747 |
}
|
| 748 |
-
const model = arch.build(m.native.cfg, tensors);
|
| 749 |
-
|
| 750 |
-
}
|
|
|
|
| 751 |
const mf = m.manifest || {}, base = "https://huggingface.co/" + m.id + "/resolve/main/";
|
| 752 |
const onProgress = (p, msg) => { stat.textContent = t("sLoad") + (msg ? " (" + msg + ")" : "") + pct(p); };
|
| 753 |
stat.textContent = t("sLoad") + "...";
|
| 754 |
const code = await (await fetch(base + (mf.runner || "verolm-runner.js"))).text();
|
| 755 |
const mod = await import(URL.createObjectURL(new Blob([code], {type:"text/javascript"})));
|
| 756 |
-
|
|
|
|
| 757 |
if(mf.weights){
|
| 758 |
const buf = await fetchBuffer(base + mf.weights, p => onProgress(p, "weights"));
|
| 759 |
-
if(mf.format === "pt"){ onProgress(undefined, "reading .pt"); ctx.tensors = await readPt(buf); }
|
| 760 |
-
else if(mf.format === "safetensors"){ ctx.tensors = readSafetensors(buf); }
|
| 761 |
else ctx.weights = buf;
|
| 762 |
}
|
| 763 |
const r = await mod.load(ctx);
|
| 764 |
-
|
| 765 |
-
}
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 783 |
}
|
| 784 |
-
|
| 785 |
-
return eng;
|
| 786 |
}
|
| 787 |
|
| 788 |
$("#rgo").onclick = async () => {
|
|
@@ -802,8 +899,8 @@ $("#rgo").onclick = async () => {
|
|
| 802 |
}catch(e){
|
| 803 |
console.error(e);
|
| 804 |
engines.delete(current.id);
|
| 805 |
-
const detail = String((e && e.message) || e).slice(0,
|
| 806 |
-
stat.textContent =
|
| 807 |
}
|
| 808 |
go.disabled = false;
|
| 809 |
};
|
|
|
|
| 197 |
const ORG = "VeroLM"; // Hugging Face organization name
|
| 198 |
|
| 199 |
const T = {
|
| 200 |
+
en:{sErrRun:"Couldn’t start this model. Every available engine was tried; details follow.",optTemp:"Temperature",optTopK:"Top-k",optMax:"Max length",optEod:"EOD code",optStop:"Stop at EOD",navData:"Datasets",hData:"Datasets",subData:"Open datasets published by VeroLM on Hugging Face.",sErrCustom:"The model’s own runner failed to start. Check the browser console for details.",note:"Not every model runs directly in the browser. Mostly newer, compatible models do. If a model can’t run, its Run button is greyed out and can’t be clicked.",noRun:"Not available in the browser",navModels:"Models",h1:"Open models at every size.",lead:"Fast, efficient and mostly open source. We train language models from tiny to large and release them for everyone to use for free.",ctaModels:"Browse models",ctaHF:"Follow on Hugging Face",hModels:"Series and models",subModels:"Our current models on Hugging Face. Inspect opens the model page, Run tries it in your browser.",hAbout:"Our approach",subAbout:"VeroLM is an independent AI lab.",p1h:"Quality first",p1:"We build models that genuinely perform, not just models that exist.",p2h:"Speed and efficiency",p2:"Every model is as fast and optimized as we can make it, so it runs on the hardware people actually have.",p3h:"Open by default",p3:"Most of what we train is open source and free. Good AI shouldn’t sit behind a paywall.",p4h:"Experimentation",p4:"We constantly try rarely explored ideas in architecture, training and optimization.",foot:"Built with curiosity, released for everyone.",
|
| 201 |
inspect:"Inspect",run:"Run",close:"Close",model:"model",models:"models",ds:"dataset",dss:"datasets",dsTag:"Dataset",dl:"downloads",oopsT:"Oops, no models here yet.",oopsB:"New releases will show up here as soon as they’re published.",phPrompt:"Type something...",
|
| 202 |
sNoGpu:"WebGPU isn’t available in this browser, so the slower CPU mode will be used.",sGpu:"WebGPU is ready. The first run downloads the model and keeps it in your browser.",sLoad:"Loading model",sReady:"Model ready.",sGen:"Generating...",sErr:"Couldn’t open this model in the browser. It may not be published in a browser-ready (ONNX) format yet."},
|
| 203 |
+
tr:{sErrRun:"Model başlatılamadı. Kullanılabilir tüm motorlar denendi; ayrıntılar aşağıda.",optTemp:"Sıcaklık",optTopK:"Top-k",optMax:"Maks. uzunluk",optEod:"EOD kodu",optStop:"EOD’da dur",navData:"Veri setleri",hData:"Veri setleri",subData:"VeroLM’in Hugging Face’te yayınladığı açık veri setleri.",sErrCustom:"Modelin kendi çalıştırıcısı başlatılamadı. Ayrıntı için tarayıcı konsoluna bak.",note:"Her model doğrudan tarayıcıda çalışmaz, genellikle yeni ve uygun modeller çalışır. Çalışmayacak modellerde Çalıştır düğmesi sönük olur ve tıklanamaz.",noRun:"Bu model tarayıcıda çalışmaz",navModels:"Modeller",h1:"Her boyutta açık modeller.",lead:"Hızlı, verimli ve çoğunlukla açık kaynak. Küçükten büyüğe dil modelleri eğitiyor, herkesin ücretsiz kullanabilmesi için yayınlıyoruz.",ctaModels:"Modelleri incele",ctaHF:"Hugging Face’te takip et",hModels:"Seriler ve modeller",subModels:"Hugging Face’teki güncel modellerimiz. İncele ile model sayfasını aç, Çalıştır ile tarayıcında dene.",hAbout:"Yaklaşımımız",subAbout:"VeroLM, bağımsız bir yapay zeka laboratuvarı.",p1h:"Önce kalite",p1:"Sadece var olan değil, gerçekten iyi çalışan modeller üretiyoruz.",p2h:"Hız ve verimlilik",p2:"Her model, insanların elindeki donanımda çalışacak şekilde olabildiğince hızlı ve optimize.",p3h:"Varsayılan olarak açık",p3:"Eğittiklerimizin çoğu açık kaynak ve ücretsiz. İyi yapay zeka ücretli duvarların arkasında kalmamalı.",p4h:"Deneysellik",p4:"Mimari, eğitim ve optimizasyonda az denenmiş fikirleri sürekli deniyoruz.",foot:"Merakla geliştirildi, herkes için yayınlandı.",
|
| 204 |
inspect:"İncele",run:"Çalıştır",close:"Kapat",model:"model",models:"model",ds:"veri seti",dss:"veri seti",dsTag:"Veri seti",dl:"indirme",oopsT:"Oops, burada henüz model yok.",oopsB:"Yeni modeller yayınlandığında burada görünecek.",phPrompt:"Bir şey yaz...",
|
| 205 |
sNoGpu:"Bu tarayıcıda WebGPU yok, daha yavaş olan CPU modu kullanılacak.",sGpu:"WebGPU hazır. İlk çalıştırmada model indirilir ve tarayıcıda saklanır.",sLoad:"Model yükleniyor",sReady:"Model hazır.",sGen:"Yanıt üretiliyor...",sErr:"Model tarayıcıda açılamadı. Bu model henüz tarayıcı (ONNX) biçiminde yayınlanmamış olabilir."},
|
| 206 |
+
fr:{sErrRun:"Impossible de démarrer ce modèle. Tous les moteurs disponibles ont été essayés ; détails ci-dessous.",optTemp:"Température",optTopK:"Top-k",optMax:"Longueur max.",optEod:"Code EOD",optStop:"Arrêt à l’EOD",navData:"Jeux de données",hData:"Jeux de données",subData:"Jeux de données ouverts publiés par VeroLM sur Hugging Face.",sErrCustom:"Le runner propre au modèle n’a pas pu démarrer. Consultez la console du navigateur.",note:"Tous les modèles ne fonctionnent pas directement dans le navigateur, en général seuls les modèles récents et compatibles le font. Si un modèle ne peut pas s’exécuter, son bouton Exécuter est grisé et non cliquable.",noRun:"Ce modèle ne fonctionne pas dans le navigateur",navModels:"Modèles",h1:"Des modèles ouverts, à toutes les tailles.",lead:"Rapides, efficaces et surtout open source. Nous entraînons des modèles de langage du plus petit au plus grand et les publions pour que tout le monde puisse les utiliser gratuitement.",ctaModels:"Voir les modèles",ctaHF:"Suivre sur Hugging Face",hModels:"Séries et modèles",subModels:"Nos modèles actuels sur Hugging Face. Examiner ouvre la page du modèle, Exécuter l’essaie dans votre navigateur.",hAbout:"Notre approche",subAbout:"VeroLM est un laboratoire d’IA indépendant.",p1h:"La qualité d’abord",p1:"Nous construisons des modèles qui performent vraiment, pas seulement des modèles qui existent.",p2h:"Vitesse et efficacité",p2:"Chaque modèle est aussi rapide et optimisé que possible, pour tourner sur le matériel que les gens ont vraiment.",p3h:"Ouvert par défaut",p3:"La plupart de nos modèles sont open source et gratuits. Une bonne IA ne devrait pas être derrière un paywall.",p4h:"Expérimentation",p4:"Nous testons sans cesse des idées peu explorées en architecture, entraînement et optimisation.",foot:"Créé avec curiosité, publié pour tous.",
|
| 207 |
inspect:"Examiner",run:"Exécuter",close:"Fermer",model:"modèle",models:"modèles",ds:"jeu de données",dss:"jeux de données",dsTag:"Jeu de données",dl:"téléchargements",oopsT:"Oups, aucun modèle ici pour l’instant.",oopsB:"Les nouvelles versions apparaîtront ici dès leur publication.",phPrompt:"Écrivez quelque chose...",
|
| 208 |
sNoGpu:"WebGPU n’est pas disponible dans ce navigateur, le mode CPU, plus lent, sera utilisé.",sGpu:"WebGPU est prêt. Le premier lancement télécharge le modèle et le conserve dans votre navigateur.",sLoad:"Chargement du modèle",sReady:"Modèle prêt.",sGen:"Génération en cours...",sErr:"Impossible d’ouvrir ce modèle dans le navigateur. Il n’est peut-être pas encore publié au format ONNX."},
|
| 209 |
+
es:{sErrRun:"No se pudo iniciar este modelo. Se probaron todos los motores disponibles; detalles a continuación.",optTemp:"Temperatura",optTopK:"Top-k",optMax:"Longitud máx.",optEod:"Código EOD",optStop:"Parar en EOD",navData:"Conjuntos de datos",hData:"Conjuntos de datos",subData:"Conjuntos de datos abiertos publicados por VeroLM en Hugging Face.",sErrCustom:"El runner propio del modelo no pudo iniciarse. Revisa la consola del navegador.",note:"No todos los modelos funcionan directamente en el navegador, normalmente solo los modelos nuevos y compatibles. Si un modelo no puede ejecutarse, su botón Ejecutar aparece atenuado y no se puede pulsar.",noRun:"Este modelo no funciona en el navegador",navModels:"Modelos",h1:"Modelos abiertos de todos los tamaños.",lead:"Rápidos, eficientes y en su mayoría de código abierto. Entrenamos modelos de lenguaje, de pequeños a grandes, y los publicamos para que todos puedan usarlos gratis.",ctaModels:"Ver modelos",ctaHF:"Seguir en Hugging Face",hModels:"Series y modelos",subModels:"Nuestros modelos actuales en Hugging Face. Inspeccionar abre la página del modelo, Ejecutar lo prueba en tu navegador.",hAbout:"Nuestro enfoque",subAbout:"VeroLM es un laboratorio de IA independiente.",p1h:"Primero la calidad",p1:"Construimos modelos que realmente funcionan bien, no solo modelos que existen.",p2h:"Velocidad y eficiencia",p2:"Cada modelo es tan rápido y optimizado como podemos, para que funcione en el hardware que la gente realmente tiene.",p3h:"Abierto por defecto",p3:"La mayoría de lo que entrenamos es de código abierto y gratuito. La buena IA no debería estar detrás de un muro de pago.",p4h:"Experimentación",p4:"Probamos constantemente ideas poco exploradas en arquitectura, entrenamiento y optimización.",foot:"Hecho con curiosidad, publicado para todos.",
|
| 210 |
inspect:"Inspeccionar",run:"Ejecutar",close:"Cerrar",model:"modelo",models:"modelos",ds:"conjunto de datos",dss:"conjuntos de datos",dsTag:"Conjunto de datos",dl:"descargas",oopsT:"Vaya, aún no hay modelos aquí.",oopsB:"Las nuevas versiones aparecerán aquí en cuanto se publiquen.",phPrompt:"Escribe algo...",
|
| 211 |
sNoGpu:"WebGPU no está disponible en este navegador, se usará el modo CPU, más lento.",sGpu:"WebGPU está listo. La primera ejecución descarga el modelo y lo guarda en tu navegador.",sLoad:"Cargando modelo",sReady:"Modelo listo.",sGen:"Generando...",sErr:"No se pudo abrir este modelo en el navegador. Puede que aún no esté publicado en formato ONNX."}
|
| 212 |
};
|
|
|
|
| 238 |
return e;
|
| 239 |
}
|
| 240 |
|
| 241 |
+
// Reads only the safetensors header (two small Range requests) and checks it against the built-in engine. Returns {error} on a definite mismatch, null if unsure (network/CORS).
|
| 242 |
+
async function probeNative(id, nat){
|
| 243 |
+
try{
|
| 244 |
+
const url = "https://huggingface.co/" + id + "/resolve/main/" + nat.files[0];
|
| 245 |
+
const h0 = await fetch(url, {headers:{Range:"bytes=0-7"}});
|
| 246 |
+
if(h0.status !== 206){ if(h0.body) h0.body.cancel(); return null; }
|
| 247 |
+
const n = Number(new DataView(await h0.arrayBuffer()).getBigUint64(0, true));
|
| 248 |
+
if(!(n > 0 && n < 1e8)) return null;
|
| 249 |
+
const h1 = await fetch(url, {headers:{Range:"bytes=8-" + (7 + n)}});
|
| 250 |
+
if(h1.status !== 206) return null;
|
| 251 |
+
const head = JSON.parse(await h1.text()), info = new Map();
|
| 252 |
+
for(const [k, v] of Object.entries(head)) if(k !== "__metadata__") info.set(k, {shape:v.shape, dtype:v.dtype});
|
| 253 |
+
ntPlan(nat.cfg, new TensorBag(info));
|
| 254 |
+
return {ok:true};
|
| 255 |
+
}catch(e){ return e && e.ntPlan ? {error:e.message} : null; }
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
async function load(){
|
| 259 |
try{
|
| 260 |
// The list endpoint truncates each collection to 4 items, so fetch every collection again for its full item list.
|
|
|
|
| 300 |
try{ cfg = await (await fetch("https://huggingface.co/" + m.id + "/resolve/main/config.json")).json(); }catch(e){}
|
| 301 |
}
|
| 302 |
const stFiles = f.includes("model.safetensors") ? ["model.safetensors"] : f.filter(n => /^model-\d+-of-\d+\.safetensors$/.test(n)).sort();
|
| 303 |
+
const kind = nativeKind(cfg), prior = m.runtime; // prior: custom / transformers, decided above
|
| 304 |
+
let nat = null;
|
| 305 |
if(kind && stFiles.length && !(m.manifest && m.manifest.builtin === false)){
|
| 306 |
+
nat = {kind, cfg, files:stFiles};
|
| 307 |
+
const pr = stFiles.length === 1 ? await probeNative(m.id, nat) : null;
|
| 308 |
+
if(pr && pr.error){ m.whyNot = pr.error; nat = null; } // definite mismatch: don't offer an engine that would fail
|
| 309 |
}
|
| 310 |
+
// engines are tried in this order at run time; a failure falls through to the next one
|
| 311 |
+
m.chain = [];
|
| 312 |
+
if(nat){ m.native = nat; m.chain.push("native"); m.manifest = Object.assign({arch:kind === "notokenlm" ? "byte-level transformer" : kind}, m.manifest || {}); }
|
| 313 |
+
if(prior === "custom") m.chain.push("custom");
|
| 314 |
+
if(hasOnnx || prior === "transformers") m.chain.push("transformers");
|
| 315 |
+
m.runtime = m.chain[0] || null;
|
| 316 |
m.runnable = !!m.runtime;
|
| 317 |
}catch(e){ m.runtime = null; m.runnable = false; }
|
| 318 |
}));
|
|
|
|
| 562 |
return out;
|
| 563 |
}
|
| 564 |
|
| 565 |
+
/* ---- tolerant tensor lookup: ignores wrapper prefixes (module., _orig_mod., model. ...) and w/weight, b/bias aliases ---- */
|
| 566 |
+
const NT_PRE = /^(module\.|_orig_mod\.|state_dict\.|model\.|transformer\.|backbone\.|net\.)/;
|
| 567 |
+
function canon(n){
|
| 568 |
+
n = String(n).toLowerCase(); let p;
|
| 569 |
+
do{ p = n; n = n.replace(NT_PRE, ""); }while(n !== p);
|
| 570 |
+
return n.replace(/\.w$/, ".weight").replace(/\.b$/, ".bias").replace(/\.(scale|gamma)$/, ".weight");
|
| 571 |
+
}
|
| 572 |
+
class TensorBag extends Map{
|
| 573 |
+
constructor(src){ super(src); this.idx = new Map(); this.memo = new Map(); for(const k of super.keys()){ const c = canon(k); if(!this.idx.has(c)) this.idx.set(c, k); } }
|
| 574 |
+
find(name){
|
| 575 |
+
if(super.has(name)) return name;
|
| 576 |
+
const c = canon(name);
|
| 577 |
+
if(this.idx.has(c)) return this.idx.get(c);
|
| 578 |
+
if(!this.memo.has(c)){ let hit = null, n = 0; for(const [k0, k] of this.idx) if(k0.endsWith("." + c)){ hit = k; n++; } this.memo.set(c, n === 1 ? hit : null); }
|
| 579 |
+
return this.memo.get(c);
|
| 580 |
+
}
|
| 581 |
+
get(name){ const k = this.find(name); return k == null ? undefined : super.get(k); }
|
| 582 |
+
has(name){ return this.find(name) != null; }
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
/* ---- built-in engines: run a model straight from config.json + weights, no per-repo code needed ---- */
|
| 586 |
// To support another architecture, add an entry to NATIVE_ARCHS keyed by the model_type in its config.json.
|
| 587 |
// Each entry has: build(cfg, tensors) -> model object, and generate(model, prompt, onToken, opts) -> Promise.
|
| 588 |
const NATIVE_ALIASES = {NoTokenLMForCausalLM:"notokenlm"};
|
| 589 |
function nativeKind(cfg){
|
| 590 |
if(!cfg) return null;
|
| 591 |
+
const mt = String(cfg.model_type || "").toLowerCase().replace(/[-_]/g, "");
|
| 592 |
+
let kind = NATIVE_ARCHS[mt] ? mt : null;
|
| 593 |
+
if(!kind) for(const a of cfg.architectures || []) if(/notokenlm/i.test(a)){ kind = "notokenlm"; break; }
|
| 594 |
return kind && (!NATIVE_ARCHS[kind].supports || NATIVE_ARCHS[kind].supports(cfg)) ? kind : null;
|
| 595 |
}
|
| 596 |
|
| 597 |
/* NoTokenLM: byte-level (vocab 256), RoPE, RMSNorm, SwiGLU, weight-tied head, UTF-8-safe sampling */
|
| 598 |
+
function ntFail(msg){ const e = new Error(msg); e.ntPlan = true; return e; }
|
| 599 |
+
const NT = {
|
| 600 |
+
emb:["token_embed.weight","embed_tokens.weight","wte.weight","tok_embeddings.weight","embedding.weight","embed.weight"],
|
| 601 |
+
fn:["final_norm.weight","norm.weight","ln_f.weight","norm_f.weight","final_layernorm.weight"],
|
| 602 |
+
head:["lm_head.weight","output.weight","head.weight"],
|
| 603 |
+
n1:["norm1.weight","input_layernorm.weight","attention_norm.weight","ln_1.weight","attn_norm.weight"],
|
| 604 |
+
qkv:["attn.qkv.weight","self_attn.qkv_proj.weight","attention.wqkv.weight","attn.qkv_proj.weight"],
|
| 605 |
+
q:["attn.q_proj.weight","self_attn.q_proj.weight","attention.wq.weight"], k:["attn.k_proj.weight","self_attn.k_proj.weight","attention.wk.weight"], v:["attn.v_proj.weight","self_attn.v_proj.weight","attention.wv.weight"],
|
| 606 |
+
out:["attn.out_proj.weight","self_attn.o_proj.weight","attention.wo.weight","attn.o_proj.weight","attn.proj.weight"],
|
| 607 |
+
n2:["norm2.weight","post_attention_layernorm.weight","ffn_norm.weight","ln_2.weight","mlp_norm.weight"],
|
| 608 |
+
wg:["mlp.w_gate.weight","mlp.gate_proj.weight","feed_forward.w1.weight","mlp.w1.weight"],
|
| 609 |
+
wu:["mlp.w_up.weight","mlp.up_proj.weight","feed_forward.w3.weight","mlp.w3.weight"],
|
| 610 |
+
wd:["mlp.w_down.weight","mlp.down_proj.weight","feed_forward.w2.weight","mlp.w2.weight"]
|
| 611 |
+
};
|
| 612 |
+
// Validates config + tensor names/sizes WITHOUT needing the weight data (shapes are enough), so it also runs on a safetensors header.
|
| 613 |
+
// Throws a tagged, descriptive error if this checkpoint is not exactly what the engine implements; never guesses silently.
|
| 614 |
+
function ntPlan(cfg, bag){
|
| 615 |
+
const used = new Set(), num = k => bag.get(k).shape.reduce((a, b) => a * b, 1);
|
| 616 |
+
const pick = (...ks) => { for(const k of ks) if(Number.isFinite(+cfg[k]) && +cfg[k] > 0) return +cfg[k]; };
|
| 617 |
+
const blk = (i, subs) => ["blocks.", "layers.", "h.", "block."].flatMap(p => subs.map(x => p + i + "." + x));
|
| 618 |
+
const any = c => c.some(n => bag.find(n) != null);
|
| 619 |
+
const first = (c, what, len) => {
|
| 620 |
+
for(const n of c){ const k = bag.find(n); if(k != null){
|
| 621 |
+
if(len != null && num(k) !== len) throw ntFail("Tensor " + k + " has " + num(k) + " values, expected " + len + " (" + what + "). config.json and the weights don't match.");
|
| 622 |
+
used.add(k); return k; } }
|
| 623 |
+
throw ntFail("Missing tensor " + c[0] + " (" + what + "). Available: " + [...bag.keys()].slice(0, 6).join(", ") + (bag.size > 6 ? ", ..." : ""));
|
| 624 |
};
|
| 625 |
+
const V = pick("vocab_size") || 256, ek = first(NT.emb, "token embedding"), en = num(ek);
|
| 626 |
+
const D = pick("d_model", "hidden_size", "n_embd", "dim", "embed_dim") || en / V;
|
| 627 |
+
if(!Number.isInteger(D) || en !== V * D) throw ntFail("Embedding has " + en + " values but vocab_size " + V + " x d_model " + D + " was expected.");
|
| 628 |
+
let L = pick("n_layer", "num_hidden_layers", "n_layers", "num_layers");
|
| 629 |
+
if(!L){ L = 0; while(any(blk(L, NT.n1))) L++; }
|
| 630 |
+
const H = pick("n_head", "num_attention_heads", "n_heads", "num_heads");
|
| 631 |
+
if(!(L > 0)) throw ntFail("No transformer blocks found (n_layer missing and no blocks.N.* tensors).");
|
| 632 |
+
if(!H) throw ntFail("config.json has no head count (n_head / num_attention_heads).");
|
| 633 |
+
const kv = pick("num_key_value_heads", "n_kv_head", "n_kv_heads");
|
| 634 |
+
if(kv && kv !== H) throw ntFail("Grouped-query attention (" + kv + " kv heads vs " + H + ") isn't supported by the built-in engine.");
|
| 635 |
+
if(D % H || (D / H) % 2) throw ntFail("Invalid config: d_model " + D + " must be divisible by n_head " + H + " and the head size must be even.");
|
| 636 |
+
const F = pick("d_ff", "intermediate_size", "ffn_dim", "ffn_hidden_size") || num(first(blk(0, NT.wg), "mlp gate")) / D;
|
| 637 |
+
if(!Number.isInteger(F) || F <= 0) throw ntFail("Could not determine the MLP width (d_ff).");
|
| 638 |
const blocks = [];
|
| 639 |
for(let i = 0; i < L; i++){
|
| 640 |
+
const b = {n1:first(blk(i, NT.n1), "block " + i + " norm1", D)};
|
| 641 |
+
if(any(blk(i, NT.qkv))) b.qkv = first(blk(i, NT.qkv), "block " + i + " qkv", 3 * D * D);
|
| 642 |
+
else b.qkv = [first(blk(i, NT.q), "block " + i + " q_proj", D * D), first(blk(i, NT.k), "block " + i + " k_proj", D * D), first(blk(i, NT.v), "block " + i + " v_proj", D * D)];
|
| 643 |
+
b.out = first(blk(i, NT.out), "block " + i + " attention output", D * D);
|
| 644 |
+
b.n2 = first(blk(i, NT.n2), "block " + i + " norm2", D);
|
| 645 |
+
b.wg = first(blk(i, NT.wg), "block " + i + " mlp gate", F * D);
|
| 646 |
+
b.wu = first(blk(i, NT.wu), "block " + i + " mlp up", F * D);
|
| 647 |
+
b.wd = first(blk(i, NT.wd), "block " + i + " mlp down", D * F);
|
| 648 |
+
blocks.push(b);
|
| 649 |
}
|
| 650 |
+
const fn = first(NT.fn, "final norm", D);
|
| 651 |
+
const hk = NT.head.map(n => bag.find(n)).find(k => k != null);
|
| 652 |
+
if(hk != null){ if(num(hk) !== V * D) throw ntFail("Output head has " + num(hk) + " values, expected " + V * D + "."); used.add(hk); }
|
| 653 |
+
// every remaining weight must be understood: otherwise this is a different architecture variant and output would be garbage
|
| 654 |
+
const extra = [...bag.keys()].filter(k => !used.has(k) && !/(inv_freq|position_ids|masked_bias|attn\.bias|rotary)/i.test(k));
|
| 655 |
+
if(extra.length) throw ntFail("Unsupported extra tensors (" + extra.slice(0, 4).join(", ") + (extra.length > 4 ? ", ..." : "") + "): this checkpoint is a different architecture variant than the built-in engine.");
|
| 656 |
+
return {D, H, L, F, V, embed:ek, fn, head:hk != null ? hk : ek, blocks};
|
| 657 |
+
}
|
| 658 |
+
|
| 659 |
+
function ntBuild(cfg, tensors){
|
| 660 |
+
const bag = tensors instanceof TensorBag ? tensors : new TensorBag(tensors), P = ntPlan(cfg, bag);
|
| 661 |
+
const f = k => toFloat32(bag.get(k));
|
| 662 |
+
const cat = ks => { const p = ks.map(f), o = new Float32Array(p.reduce((a, x) => a + x.length, 0)); let off = 0; for(const x of p){ o.set(x, off); off += x.length; } return o; };
|
| 663 |
+
const blocks = P.blocks.map(b => ({n1:f(b.n1), qkv:Array.isArray(b.qkv) ? cat(b.qkv) : f(b.qkv), out:f(b.out), n2:f(b.n2), wg:f(b.wg), wu:f(b.wu), wd:f(b.wd)}));
|
| 664 |
+
const embed = f(P.embed);
|
| 665 |
+
return {D:P.D, H:P.H, L:P.L, F:P.F, V:P.V, hd:P.D / P.H, embed, head:P.head === P.embed ? embed : f(P.head), fn:f(P.fn), blocks,
|
| 666 |
+
ropeLen:(cfg.block_size || cfg.max_position_embeddings || cfg.n_positions || 1024) * 4, theta:cfg.rope_theta || 10000, eps:cfg.rms_norm_eps || cfg.layer_norm_eps || 1e-6};
|
| 667 |
}
|
| 668 |
|
| 669 |
// y[o] = sum_i W[o*n + i] * x[i] (W is [out, in] row-major, like torch.nn.Linear)
|
|
|
|
| 734 |
}
|
| 735 |
if(wantLogits){
|
| 736 |
ntRms(x, M.fn, xn, D, M.eps);
|
| 737 |
+
ntMatVec(M.head, xn, st.logits, V, D); // weight-tied output head
|
| 738 |
}
|
| 739 |
}
|
| 740 |
|
|
|
|
| 822 |
}
|
| 823 |
$("#rclose").onclick = () => $("#dlg").close();
|
| 824 |
|
| 825 |
+
async function buildEngine(m, kind, stat){
|
|
|
|
|
|
|
| 826 |
const pct = p => typeof p === "number" ? " " + Math.round(p) + "%" : "";
|
| 827 |
+
if(kind === "native"){
|
|
|
|
| 828 |
const base = "https://huggingface.co/" + m.id + "/resolve/main/", arch = NATIVE_ARCHS[m.native.kind], tensors = new Map();
|
| 829 |
for(let i = 0; i < m.native.files.length; i++){
|
| 830 |
stat.textContent = t("sLoad") + "...";
|
| 831 |
const buf = await fetchBuffer(base + m.native.files[i], p => { stat.textContent = t("sLoad") + " (weights" + (m.native.files.length > 1 ? " " + (i + 1) + "/" + m.native.files.length : "") + ")" + pct(p); });
|
| 832 |
for(const [k, v] of readSafetensors(buf)) tensors.set(k, v);
|
| 833 |
}
|
| 834 |
+
const model = arch.build(m.native.cfg, new TensorBag(tensors));
|
| 835 |
+
return (prompt, onToken, o) => arch.generate(model, prompt, onToken, o);
|
| 836 |
+
}
|
| 837 |
+
if(kind === "custom"){
|
| 838 |
const mf = m.manifest || {}, base = "https://huggingface.co/" + m.id + "/resolve/main/";
|
| 839 |
const onProgress = (p, msg) => { stat.textContent = t("sLoad") + (msg ? " (" + msg + ")" : "") + pct(p); };
|
| 840 |
stat.textContent = t("sLoad") + "...";
|
| 841 |
const code = await (await fetch(base + (mf.runner || "verolm-runner.js"))).text();
|
| 842 |
const mod = await import(URL.createObjectURL(new Blob([code], {type:"text/javascript"})));
|
| 843 |
+
// tensors come as a TensorBag: runners may ask for "pos_conv.w" and still find "model.pos_conv.weight", "module.pos_conv.w", etc.
|
| 844 |
+
const ctx = {modelId:m.id, baseUrl:base, manifest:mf, onProgress, tools:{readPt, readSafetensors, fetchBuffer, toFloat32, TensorBag}};
|
| 845 |
if(mf.weights){
|
| 846 |
const buf = await fetchBuffer(base + mf.weights, p => onProgress(p, "weights"));
|
| 847 |
+
if(mf.format === "pt"){ onProgress(undefined, "reading .pt"); ctx.tensors = new TensorBag(await readPt(buf)); }
|
| 848 |
+
else if(mf.format === "safetensors"){ ctx.tensors = new TensorBag(readSafetensors(buf)); }
|
| 849 |
else ctx.weights = buf;
|
| 850 |
}
|
| 851 |
const r = await mod.load(ctx);
|
| 852 |
+
return (prompt, onToken, o) => r.generate(prompt, {onToken, maxTokens:o.maxTokens, temperature:o.temperature, topK:o.topK, eod:o.eod, stopAtEod:o.stopAtEod});
|
| 853 |
+
}
|
| 854 |
+
if(!lib) lib = await import("https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.2");
|
| 855 |
+
stat.textContent = t("sLoad") + "...";
|
| 856 |
+
const gpu = !!navigator.gpu, has = n => (m.onnxFiles || []).includes("onnx/" + n);
|
| 857 |
+
const dtype = gpu
|
| 858 |
+
? (has("model_q4.onnx") ? "q4" : has("model_fp16.onnx") ? "fp16" : has("model_quantized.onnx") ? "q8" : "fp32")
|
| 859 |
+
: (has("model_quantized.onnx") ? "q8" : has("model_q4.onnx") ? "q4" : "fp32");
|
| 860 |
+
const gen = await lib.pipeline("text-generation", m.id, {
|
| 861 |
+
device: gpu ? "webgpu" : "wasm", dtype,
|
| 862 |
+
progress_callback: p => { if(p.status === "progress") stat.textContent = t("sLoad") + pct(p.progress || 0); }
|
| 863 |
+
});
|
| 864 |
+
return async (prompt, onToken, o) => {
|
| 865 |
+
const streamer = new lib.TextStreamer(gen.tokenizer, {skip_prompt:true, callback_function:onToken});
|
| 866 |
+
const cfg = {max_new_tokens:o.maxTokens, do_sample:o.temperature > 0, streamer};
|
| 867 |
+
if(o.temperature > 0){ cfg.temperature = o.temperature; if(o.topK > 0) cfg.top_k = o.topK; }
|
| 868 |
+
await gen([{role:"user", content:prompt}], cfg);
|
| 869 |
+
};
|
| 870 |
+
}
|
| 871 |
+
|
| 872 |
+
// Tries every engine that can plausibly run this model, in order; only fails if all of them fail, and then reports each reason.
|
| 873 |
+
async function getEngine(m, stat){
|
| 874 |
+
if(engines.has(m.id)) return engines.get(m.id);
|
| 875 |
+
const errs = [];
|
| 876 |
+
for(const kind of (m.chain && m.chain.length ? m.chain : [m.runtime])){
|
| 877 |
+
try{
|
| 878 |
+
const eng = await buildEngine(m, kind, stat);
|
| 879 |
+
engines.set(m.id, eng); return eng;
|
| 880 |
+
}catch(e){ console.error("[" + m.id + "] engine '" + kind + "' failed:", e); errs.push(kind + ": " + String((e && e.message) || e)); }
|
| 881 |
}
|
| 882 |
+
throw new Error(errs.join(" | "));
|
|
|
|
| 883 |
}
|
| 884 |
|
| 885 |
$("#rgo").onclick = async () => {
|
|
|
|
| 899 |
}catch(e){
|
| 900 |
console.error(e);
|
| 901 |
engines.delete(current.id);
|
| 902 |
+
const detail = String((e && e.message) || e).slice(0, 700);
|
| 903 |
+
stat.textContent = t("sErrRun") + " [" + detail + "]";
|
| 904 |
}
|
| 905 |
go.disabled = false;
|
| 906 |
};
|