Sandbox / index.html
omurberaisik's picture
Upload index.html
3e2d254 verified
Raw History Blame Contribute Delete
141 kB
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="VeroLM: an independent lab training open, experimental language models from small to large."> <title>VeroLM</title> <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='525 200 500 630'%3E%3Cpolygon fill='%23e10b17' points='537,340 626,304 626,594 537,528'/%3E%3Cpolygon fill='%23e10b17' points='665,314 803,265 803,703 665,614'/%3E%3Cpolygon fill='%23e10b17' points='840,270 1012,212 1012,817 840,710'/%3E%3C/svg%3E"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:wght@600;800&family=Hanken+Grotesk:wght@400;600;700&display=swap" rel="stylesheet"> <style> :root{--bg:#f3f3f1;--fg:#121214;--mut:#5c5c65;--line:#d8d8dc;--card:#fff;--side:#ebebe8;--dot:rgba(0,0,0,.07);--glow:rgba(225,11,23,.05);--red:#e10b17; --font:"Hanken Grotesk",system-ui,-apple-system,"Segoe UI",sans-serif;--disp:"Bricolage Grotesque","Hanken Grotesk",system-ui,sans-serif} @media (prefers-color-scheme:dark){:root{--bg:#0a0f18;--fg:#ececee;--mut:#9aa6b8;--line:#222c3b;--card:#111826;--side:#0d1320;--dot:rgba(140,170,255,.07);--glow:rgba(40,90,220,.16)}} *{box-sizing:border-box} [hidden]{display:none!important} body{margin:0;background:var(--bg);color:var(--fg);font-family:var(--font);line-height:1.6;-webkit-font-smoothing:antialiased;height:100vh;display:grid;grid-template-columns:268px 1fr;overflow:hidden} a{color:inherit} :focus-visible{outline:2px solid var(--fg);outline-offset:3px} .wrap{max-width:1120px;margin:0 auto;padding:0 24px} .l-ink{fill:var(--fg)}.l-red{fill:url(#redg)} .b{transform-box:fill-box;transform-origin:bottom;animation:rise .9s cubic-bezier(.2,.8,.2,1) both} .b2{animation-delay:.12s}.b3{animation-delay:.24s} @keyframes rise{from{transform:scaleY(.15);opacity:0}to{transform:none;opacity:1}} .brand .b{animation:none} @media (prefers-reduced-motion:reduce){.b{animation:none}} .side{background:var(--side);border-right:1px solid var(--line);display:flex;flex-direction:column;height:100vh;padding:16px 12px;overflow:auto} .brand{display:flex;align-items:center;gap:10px;font:800 1.2rem var(--disp);letter-spacing:-.02em;text-decoration:none;padding:6px 10px 20px} .brand svg{width:26px;height:32px} .brand .b{animation:none} .tabs{display:flex;flex-direction:column;gap:2px} .tab{font-weight:600;font-size:.93rem;color:var(--mut);text-decoration:none;padding:9px 12px;border-radius:10px} .tab:hover{color:var(--fg);background:color-mix(in srgb,var(--fg) 6%,transparent)} .tab[aria-current=page]{color:var(--fg);background:color-mix(in srgb,var(--fg) 10%,transparent);box-shadow:inset 3px 0 0 var(--red)} .sl{font-size:.8rem;font-weight:600;color:var(--mut);padding:22px 12px 6px} .sr{display:block;width:100%;text-align:left;font:inherit;font-size:.88rem;color:var(--fg);background:none;border:0;border-radius:10px;padding:7px 12px;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .sr:hover{background:color-mix(in srgb,var(--fg) 6%,transparent)} .sfoot{margin-top:auto;display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:16px 4px 0} .main{height:100vh;overflow:auto;background:radial-gradient(70% 45% at 50% 108%,var(--glow),transparent),radial-gradient(var(--dot) 1px,transparent 1.5px) 0 0/22px 22px,var(--bg)} .main .wrap{padding:0 44px} .mbar{display:none} .news{display:flex;flex-direction:column;gap:14px;max-width:760px} .ni{--c:#8b8b94;background:var(--card);border:1px solid var(--line);border-left:4px solid var(--c);border-radius:10px;padding:18px 20px} .ni.n1{--c:#f2b705}.ni.n2{--c:#3b82f6}.ni.n3{--c:#22a559} .nd{display:flex;gap:10px;align-items:center;font-size:.8rem;color:var(--mut);margin-bottom:6px} .nd i{width:8px;height:8px;border-radius:50%;background:var(--c)} .nd .tg{border:1px solid var(--c);border-radius:4px;padding:0 8px;color:var(--fg)} .ni h3{margin:0 0 6px;font-size:1.2rem;letter-spacing:-.02em} .ni h3 a{text-decoration:none}.ni h3 a:hover{text-decoration:underline} .ni p{margin:0;color:var(--mut)} .chip{font:inherit;font-size:.85rem;color:var(--fg);background:transparent;border:1px solid var(--line);border-radius:999px;padding:6px 14px;cursor:pointer;text-decoration:none;display:inline-block} .chip:hover{border-color:var(--mut)} .chip[aria-pressed=true]{background:var(--fg);color:var(--bg);border-color:var(--fg)} select.chip{appearance:none;-webkit-appearance:none;background-color:var(--bg);padding-right:26px;background-repeat:no-repeat;background-position:right 11px center;background-size:9px 6px;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 6'%3E%3Cpath d='M1 1l3.5 3.5L8 1' fill='none' stroke='%238d8d95' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")} .panel{padding:56px 0 24px} h1,h2,h3,h4{font-family:var(--disp)} h2{font-size:clamp(1.8rem,4vw,2.6rem);letter-spacing:-.03em;line-height:1.05;margin:0 0 10px} .sub{color:var(--mut);margin:0 0 32px;max-width:60ch} .hero{display:grid;grid-template-columns:1.5fr .5fr;align-items:end;gap:48px;padding:16px 0 64px} .hero h1{font-size:clamp(2.8rem,8vw,6.2rem);line-height:.95;letter-spacing:-.045em;font-weight:800;margin:0 0 24px} .hero p{max-width:52ch;color:var(--mut);font-size:1.12rem;margin:0 0 32px} .hero svg{width:min(100%,200px);height:auto;justify-self:end} .cta{display:flex;gap:10px;flex-wrap:wrap} .btn{font:inherit;font-weight:600;font-size:.9rem;border:1px solid transparent;border-radius:8px;padding:10px 18px;cursor:pointer;color:#fff;text-decoration:none;display:inline-block} .btn.red,.btn.green{background:var(--red)} .btn.ghost,.btn.blue{background:transparent;color:var(--fg);border-color:var(--line)} .btn.ghost:hover,.btn.blue:hover{border-color:var(--fg)} .btn.red:hover,.btn.green:hover{filter:brightness(1.1)} .btn[disabled]{opacity:.5;cursor:wait} .card .btn[disabled]{opacity:.35;cursor:not-allowed;filter:grayscale(.7)} .rt{font-size:1rem;letter-spacing:0;margin:0 0 16px;color:var(--mut);font-weight:600} .ruler{position:relative;height:150px;border-bottom:1px solid var(--fg);margin:0 14px 56px} .rb{position:absolute;bottom:0;width:10px;margin-left:-5px;padding:0;border:0;background:var(--red);cursor:pointer;border-radius:2px 2px 0 0} .rb:hover{background:var(--fg)} .tick{position:absolute;bottom:-28px;transform:translateX(-50%);font-size:.8rem;color:var(--mut)} .tick::before{content:"";position:absolute;left:50%;top:-12px;height:7px;border-left:1px solid var(--mut)} .cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));margin-top:24px} .cols>div{border-left:1px solid var(--line);padding:4px 28px 8px} .cols>div:first-child{border-left:0;padding-left:0} .cols h3,.areas h3{margin:0 0 8px;font-size:1.3rem;letter-spacing:-.02em} .cols p,.areas p{margin:0;color:var(--mut)} .areas{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:0 48px} .areas>div{border-top:1px solid var(--fg);padding:20px 0 36px} .about{max-width:62ch;font-size:1.15rem} .about p{margin:0 0 18px} .tools{display:flex;gap:10px;flex-wrap:wrap;margin:0 0 28px} .in{font:inherit;font-size:.9rem;background:var(--card);color:var(--fg);border:1px solid var(--line);border-radius:999px;padding:7px 16px;min-width:min(100%,260px)} .note{border-left:3px solid var(--red);padding:2px 0 2px 14px;margin:0 0 32px;color:var(--mut);font-size:.92rem;max-width:70ch} .series{margin-bottom:44px} .series h3{display:flex;align-items:baseline;gap:12px;margin:0 0 8px;font-size:1.4rem;letter-spacing:-.02em} .series h3 a{text-decoration:none} .series h3 a:hover{text-decoration:underline} .series h3 small{color:var(--mut);font:400 .85rem var(--font)} .series .desc{color:var(--mut);margin:0 0 18px;max-width:70ch;font-size:.95rem} .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:14px} .card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:20px;display:flex;flex-direction:column;gap:12px} .sz{font:800 2.6rem/1 var(--disp);letter-spacing:-.045em} .mtr{height:3px;background:var(--line);border-radius:2px} .mtr i{display:block;height:100%;background:var(--red);border-radius:2px} .card h4{margin:0;font-size:1rem;font-weight:600;word-break:break-word} .meta{display:flex;flex-wrap:wrap;gap:6px;font-size:.78rem;color:var(--mut)} .meta span{border:1px solid var(--line);border-radius:4px;padding:1px 8px} .meta .ok{color:var(--fg);border-color:var(--fg)} .card .act{display:flex;gap:8px;margin-top:auto;padding-top:8px} .empty{text-align:center;padding:48px 16px;color:var(--mut)} .empty strong{display:block;color:var(--fg);font-size:1.2rem;margin-bottom:6px} .skel{height:150px;border-radius:10px;background:linear-gradient(90deg,var(--card),var(--line),var(--card));background-size:200% 100%;animation:sh 1.4s infinite} @keyframes sh{to{background-position:-200% 0}} footer{border-top:1px solid var(--line);margin-top:64px;padding:28px 0 48px;color:var(--mut);font-size:.9rem;display:flex;justify-content:space-between;flex-wrap:wrap;gap:12px} dialog{border:1px solid var(--line);border-radius:12px;background:var(--card);color:var(--fg);width:min(640px,92vw);max-height:92vh;overflow:auto;padding:24px;font-family:var(--font)} dialog::backdrop{background:rgba(0,0,0,.55)} .opts{display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:10px;margin-top:12px} .opts label{font-size:.78rem;color:var(--mut);display:flex;flex-direction:column;gap:4px} .opts input[type=number]{font:inherit;font-size:.9rem;background:var(--bg);color:var(--fg);border:1px solid var(--line);border-radius:6px;padding:6px 8px;width:100%} .opts .chk{flex-direction:row;align-items:center;gap:8px;align-self:end;padding-bottom:7px;color:var(--fg)} dialog h3{margin:0 0 4px;word-break:break-all} #rstat{color:var(--mut);font-size:.88rem;margin:0 0 14px;min-height:1.4em} textarea{width:100%;min-height:90px;font:inherit;font-size:.95rem;background:var(--bg);color:var(--fg);border:1px solid var(--line);border-radius:6px;padding:10px;resize:vertical} #rout{white-space:pre-wrap;background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:12px;margin-top:12px;min-height:60px;max-height:260px;overflow:auto;font-size:.92rem} .drow{display:flex;gap:8px;margin-top:12px;justify-content:flex-end} @media (max-width:820px){ body{grid-template-columns:1fr;grid-template-rows:auto 1fr} .mbar{display:flex;align-items:center;gap:12px;padding:10px 16px;border-bottom:1px solid var(--line);background:var(--side);font:800 1.1rem var(--disp)} .side{position:fixed;inset:0 auto 0 0;width:min(300px,84vw);z-index:20;transform:translateX(-102%);transition:transform .2s} .side.open{transform:none;box-shadow:0 0 0 100vmax rgba(0,0,0,.55)} .main{height:auto;min-height:0}.main .wrap{padding:0 20px} .hero{grid-template-columns:1fr;padding-bottom:48px}.hero svg{width:88px;order:-1;justify-self:start} .cols>div{border-left:0;border-top:1px solid var(--line);padding:20px 0}.cols>div:first-child{border-top:0} .ruler{height:120px}} </style> </head> <body> <svg width="0" height="0" style="position:absolute;overflow:hidden" aria-hidden="true"> <defs> <linearGradient id="redg" x1="0" y1="0" x2="0" y2="1"> <stop offset="0" stop-color="#ee0f1a"/> <stop offset="1" stop-color="#860000"/> </linearGradient> <symbol id="logo" viewBox="525 200 500 630" width="100%" height="100%"> <g class="b b1"><polygon class="l-ink" points="537,340 626,304 626,594 537,528"/><path class="l-red" d="M537 362Q580 450 612 522Q622 545 626 594L537 528Z"/></g> <g class="b b2"><polygon class="l-ink" points="665,314 803,265 803,703 665,614"/><path class="l-red" d="M803 375L692 503Q680 517 680 535L680 624L803 703Z"/></g> <g class="b b3"><polygon class="l-ink" points="840,270 1012,212 1012,817 840,710"/><path class="l-red" d="M1012 346L866 506Q855 518 855 534L855 719L1012 817Z"/></g> </symbol> </defs> </svg> <div class="mbar"><button class="chip" id="sMenu" type="button" aria-label="Menu">&#9776;</button>VeroLM</div> <aside class="side" id="side"> <a class="brand" href="#overview" aria-label="VeroLM"><svg viewBox="0 0 500 630" aria-hidden="true"><use href="#logo"/></svg>VeroLM</a> <nav class="tabs" aria-label="Sections"> <a class="tab" data-p="overview" href="#overview" data-t="navHome"></a> <a class="tab" data-p="news" href="#news" data-t="navNews"></a> <a class="tab" data-p="models" href="#models" data-t="navModels"></a> <a class="tab" id="navData" data-p="datasets" href="#datasets" data-t="navData" hidden></a> <a class="tab" data-p="research" href="#research" data-t="navRes"></a> <a class="tab" data-p="about" href="#about" data-t="navAbout"></a> </nav> <div class="sl" id="sidel" data-t="hModels" hidden></div> <div id="sidesr"></div> <div class="sfoot"> <a class="chip hf" href="#" target="_blank" rel="noopener">Hugging Face</a> <select class="chip" id="lang" aria-label="Language"></select> </div> </aside> <div class="main" id="main"><main class="wrap"> <section class="panel" data-p="overview"> <div class="hero"> <div> <h1 data-t="h1"></h1> <p data-t="lead"></p> <div class="cta"> <a class="btn red" href="#models" data-t="ctaModels"></a> <a class="btn ghost" href="#research" data-t="ctaRes"></a> </div> </div> <svg viewBox="0 0 500 630" role="img" aria-label="VeroLM"><use href="#logo"/></svg> </div> <div id="rwrap" hidden><h2 class="rt" data-t="scT"></h2><div class="ruler" id="ruler"></div></div> <div class="cols"> <div><h3 data-t="w1h"></h3><p data-t="w1"></p></div> <div><h3 data-t="w2h"></h3><p data-t="w2"></p></div> <div><h3 data-t="w3h"></h3><p data-t="w3"></p></div> </div> </section> <section class="panel" data-p="news" hidden> <h2 data-t="hNews"></h2> <p class="sub" data-t="subNews"></p> <div class="news" id="newsList"></div> </section> <section class="panel" data-p="models" hidden> <h2 data-t="hModels"></h2> <p class="sub" data-t="subModels"></p> <div class="tools"> <input class="in" id="q" type="search" data-t-ph="q" autocomplete="off"> <button class="chip" id="fRun" type="button" aria-pressed="false" data-t="fRun"></button> </div> <p class="note" data-t="note"></p> <div id="list"><div class="grid"><div class="skel"></div><div class="skel"></div><div class="skel"></div></div></div> </section> <section class="panel" data-p="datasets" hidden> <h2 data-t="hData"></h2> <p class="sub" data-t="subData"></p> <div id="dlist" class="grid"></div> </section> <section class="panel" data-p="research" hidden> <h2 data-t="hRes"></h2> <p class="sub" data-t="subRes"></p> <div class="areas"> <div><h3 data-t="r1h"></h3><p data-t="r1"></p></div> <div><h3 data-t="r2h"></h3><p data-t="r2"></p></div> <div><h3 data-t="r3h"></h3><p data-t="r3"></p></div> <div><h3 data-t="r4h"></h3><p data-t="r4"></p></div> </div> </section> <section class="panel" data-p="about" hidden> <h2 data-t="abH"></h2> <div class="about"><p data-t="ab1"></p><p data-t="ab2"></p></div> <div class="cta"><a class="btn red hf" href="#" target="_blank" rel="noopener" data-t="ctaHF"></a></div> </section> <footer> <span>© VeroLM</span> <span data-t="foot"></span> </footer> </main></div> <dialog id="dlg"> <h3 id="rname"></h3> <p id="rstat"></p> <textarea id="rin" data-t-ph="phPrompt" placeholder="..."></textarea> <div class="opts"> <label><span data-t="optTemp">Temperature</span><input id="oTemp" type="number" min="0" max="5" step="0.1"></label> <label><span data-t="optTopK">Top-k</span><input id="oTopK" type="number" min="0" max="256" step="1"></label> <label><span data-t="optMax">Max length</span><input id="oMax" type="number" min="1" max="4096" step="1"></label> <label class="eodopt"><span data-t="optEod">EOD code</span><input id="oEod" type="number" min="0" step="1" placeholder="auto"></label> <label class="chk eodopt"><input id="oStop" type="checkbox" checked><span data-t="optStop">Stop at EOD</span></label> </div> <div id="rout" hidden></div> <div class="drow"> <button class="btn ghost" id="rclose" type="button" data-t="close">Close</button> <button class="btn green" id="rgo" type="button" data-t="run">Run</button> </div> </dialog> <script> const ORG = "VeroLM"; // Hugging Face organization name const T = { en:{sErrArch:"This model uses an architecture the in-browser engines don’t support yet (its weights don’t match any built-in layout). It can’t run here; details are in the browser console.",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.", 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...", 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."}, tr:{sErrArch:"Bu model, tarayıcıdaki motorların henüz desteklemediği bir mimari kullanıyor (ağırlıkları hiçbir yerleşik düzenle eşleşmiyor). Burada çalıştırılamaz; ayrıntılar tarayıcı konsolunda.",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ı.", 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...", 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."}, fr:{sErrArch:"Ce modèle utilise une architecture que les moteurs du navigateur ne prennent pas encore en charge (ses poids ne correspondent à aucune disposition intégrée). Il ne peut pas s’exécuter ici ; détails dans la console.",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.", 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...", 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."}, es:{sErrArch:"Este modelo usa una arquitectura que los motores del navegador aún no admiten (sus pesos no coinciden con ningún diseño integrado). No se puede ejecutar aquí; detalles en la consola.",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.", 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...", 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."} }; const X = { en:{navHome:"Overview",navRes:"Research",navAbout:"About",q:"Search models",fRun:"Runs in browser",noMatch:"No models match.", h1:"Open models, from tiny to vast.",lead:"VeroLM is an independent lab for open, experimental research. We train language models at every scale and on unusual architectures, and publish them for anyone to use.",ctaRes:"How we work", scT:"Every model we’ve released, by size", w1h:"Every scale",w1:"From small experiments to large runs, we train the whole ladder and publish each step.", w2h:"Unusual architectures",w2:"We try ideas that rarely get a full training run: byte-level, hierarchical and hybrid designs.", w3h:"Open by default",w3:"Models and datasets live on Hugging Face, and many run right here in your browser.", hRes:"Research",subRes:"What we study, and how.", r1h:"Scaling ladders",r1:"One recipe trained at several sizes, so differences come from scale and not from luck.", r2h:"Architecture experiments",r2:"Attention variants, byte-level models, hierarchical layouts and hybrids.", r3h:"Training recipes",r3:"Data mixes, optimizers and schedules, tested small before we trust them large.", r4h:"Efficient inference",r4:"Models built to run on hardware people already own, even inside a browser tab.", abH:"About VeroLM",ab1:"VeroLM is an independent lab for open, experimental AI research. Our main work is training models from small to large, on both established and experimental architectures.",ab2:"Everything we release lives on Hugging Face, where anyone can inspect, download and build on it. Many models also run directly on this site.",ctaHF:"Follow on Hugging Face",navNews:"News",hNews:"News",subNews:"Latest news, announcements and updates.",newsEmpty:"Nothing here yet.",newsEmptyS:"New announcements will appear here."}, tr:{navHome:"Genel bakış",navRes:"Araştırma",navAbout:"Hakkımızda",q:"Model ara",fRun:"Tarayıcıda çalışır",noMatch:"Eşleşen model yok.", h1:"Küçükten büyüğe, açık modeller.",lead:"VeroLM, açık ve deneysel araştırma yapan bağımsız bir laboratuvar. Her ölçekte ve alışılmadık mimarilerde dil modelleri eğitiyor, herkesin kullanabilmesi için yayınlıyoruz.",ctaRes:"Nasıl çalışıyoruz", scT:"Yayınladığımız tüm modeller, boyutlarına göre", w1h:"Her ölçek",w1:"Küçük denemelerden büyük eğitimlere kadar tüm basamakları eğitiyor ve hepsini yayınlıyoruz.", w2h:"Alışılmadık mimariler",w2:"Nadiren tam eğitim şansı bulan fikirleri deniyoruz: bayt düzeyinde, hiyerarşik ve hibrit tasarımlar.", w3h:"Varsayılan olarak açık",w3:"Modeller ve veri setleri Hugging Face’te; birçoğu doğrudan burada, tarayıcında çalışıyor.", hRes:"Araştırma",subRes:"Neyi, nasıl inceliyoruz.", r1h:"Ölçek basamakları",r1:"Aynı tarif birkaç boyutta eğitilir; fark şanstan değil ölçekten gelir.", r2h:"Mimari deneyleri",r2:"Dikkat varyantları, bayt düzeyinde modeller, hiyerarşik yapılar ve hibritler.", r3h:"Eğitim tarifleri",r3:"Veri karışımları, optimizasyon ve zamanlamalar; büyükte güvenmeden önce küçükte sınanır.", r4h:"Verimli çıkarım",r4:"İnsanların elindeki donanımda, hatta bir tarayıcı sekmesinde çalışacak modeller.", abH:"VeroLM hakkında",ab1:"VeroLM, açık ve deneysel yapay zeka araştırması yapan bağımsız bir laboratuvar. Asıl işimiz, hem yerleşik hem deneysel mimarilerde küçükten büyüğe modeller eğitmek.",ab2:"Yayınladığımız her şey Hugging Face’te; herkes inceleyebilir, indirebilir ve üzerine geliştirebilir. Birçok model bu sitede de doğrudan çalışır.",ctaHF:"Hugging Face’te takip et",navNews:"Haberler",hNews:"Haberler",subNews:"Yeni haberler, duyurular ve güncellemeler.",newsEmpty:"Henüz haber yok.",newsEmptyS:"Yeni duyurular burada görünecek."}, fr:{navHome:"Aperçu",navRes:"Recherche",navAbout:"À propos",q:"Rechercher un modèle",fRun:"Fonctionne dans le navigateur",noMatch:"Aucun modèle correspondant.", h1:"Des modèles ouverts, du minuscule au vaste.",lead:"VeroLM est un laboratoire indépendant de recherche ouverte et expérimentale. Nous entraînons des modèles de langage à toutes les échelles et sur des architectures inhabituelles, et les publions pour tous.",ctaRes:"Notre méthode", scT:"Tous nos modèles publiés, par taille", w1h:"Toutes les échelles",w1:"Des petites expériences aux grands entraînements, nous entraînons toute l’échelle et publions chaque palier.", w2h:"Architectures inhabituelles",w2:"Nous testons des idées rarement entraînées à fond : conceptions au niveau de l’octet, hiérarchiques et hybrides.", w3h:"Ouvert par défaut",w3:"Modèles et jeux de données sont sur Hugging Face, et beaucoup s’exécutent ici, dans votre navigateur.", hRes:"Recherche",subRes:"Ce que nous étudions, et comment.", r1h:"Échelles de taille",r1:"Une même recette à plusieurs tailles, pour que les écarts viennent de l’échelle et non du hasard.", r2h:"Expériences d’architecture",r2:"Variantes d’attention, modèles au niveau de l’octet, structures hiérarchiques et hybrides.", r3h:"Recettes d’entraînement",r3:"Mélanges de données, optimiseurs et plannings, testés en petit avant d’être crus en grand.", r4h:"Inférence efficace",r4:"Des modèles conçus pour tourner sur le matériel que chacun possède, même dans un onglet.", abH:"À propos de VeroLM",ab1:"VeroLM est un laboratoire indépendant de recherche IA ouverte et expérimentale. Notre travail principal : entraîner des modèles du petit au grand, sur des architectures établies comme expérimentales.",ab2:"Tout ce que nous publions est sur Hugging Face, où chacun peut examiner, télécharger et construire dessus. Beaucoup de modèles s’exécutent aussi directement ici.",ctaHF:"Suivre sur Hugging Face",navNews:"Actualités",hNews:"Actualités",subNews:"Dernières actualités, annonces et mises à jour.",newsEmpty:"Rien pour le moment.",newsEmptyS:"Les prochaines annonces apparaîtront ici."}, es:{navHome:"Resumen",navRes:"Investigación",navAbout:"Acerca de",q:"Buscar modelos",fRun:"Se ejecuta en el navegador",noMatch:"Ningún modelo coincide.", h1:"Modelos abiertos, de lo diminuto a lo vasto.",lead:"VeroLM es un laboratorio independiente de investigación abierta y experimental. Entrenamos modelos de lenguaje a todas las escalas y con arquitecturas inusuales, y los publicamos para todos.",ctaRes:"Cómo trabajamos", scT:"Todos nuestros modelos publicados, por tamaño", w1h:"Todas las escalas",w1:"De pequeños experimentos a grandes entrenamientos, entrenamos toda la escalera y publicamos cada peldaño.", w2h:"Arquitecturas inusuales",w2:"Probamos ideas que rara vez reciben un entrenamiento completo: diseños a nivel de byte, jerárquicos e híbridos.", w3h:"Abierto por defecto",w3:"Modelos y conjuntos de datos están en Hugging Face, y muchos se ejecutan aquí, en tu navegador.", hRes:"Investigación",subRes:"Qué estudiamos y cómo.", r1h:"Escaleras de escala",r1:"Una misma receta en varios tamaños, para que las diferencias vengan de la escala y no del azar.", r2h:"Experimentos de arquitectura",r2:"Variantes de atención, modelos a nivel de byte, estructuras jerárquicas e híbridos.", r3h:"Recetas de entrenamiento",r3:"Mezclas de datos, optimizadores y calendarios, probados en pequeño antes de confiar en grande.", r4h:"Inferencia eficiente",r4:"Modelos pensados para el hardware que la gente ya tiene, incluso en una pestaña del navegador.", abH:"Acerca de VeroLM",ab1:"VeroLM es un laboratorio independiente de investigación de IA abierta y experimental. Nuestro trabajo principal es entrenar modelos de pequeños a grandes, en arquitecturas consolidadas y experimentales.",ab2:"Todo lo que publicamos está en Hugging Face, donde cualquiera puede inspeccionarlo, descargarlo y construir sobre ello. Muchos modelos también se ejecutan directamente aquí.",ctaHF:"Seguir en Hugging Face",navNews:"Noticias",hNews:"Noticias",subNews:"Últimas noticias, anuncios y actualizaciones.",newsEmpty:"Todavía no hay nada.",newsEmptyS:"Los nuevos anuncios aparecerán aquí."} }; Object.keys(X).forEach(l => Object.assign(T[l], X[l])); let Q = "", ONLY = false; let lang = "en"; const $ = s => document.querySelector(s); const t = k => (T[lang] && T[lang][k] != null) ? T[lang][k] : T.en[k]; /* ---- 40 languages: the 5 most common are listed, plus the visitor's own (auto-selected) ---- Row format: code|name|Home|Models|Research|About|News|Inspect|Run|Close en, tr, fr, es already have full dictionaries above; other languages fall back to English per missing key. */ const LANGDATA = `en|English zh|中文|概览|模型|研究|关于|新闻|查看|运行|关闭 hi|हिन्दी|अवलोकन|मॉडल|शोध|हमारे बारे में|समाचार|देखें|चलाएँ|बंद करें es|Español ar|العربية|نظرة عامة|النماذج|الأبحاث|من نحن|الأخبار|استعراض|تشغيل|إغلاق fr|Français pt|Português|Visão geral|Modelos|Pesquisa|Sobre|Notícias|Inspecionar|Executar|Fechar bn|বাংলা|ওভারভিউ|মডেল|গবেষণা|আমাদের সম্পর্কে|খবর|দেখুন|চালান|বন্ধ করুন ru|Русский|Обзор|Модели|Исследования|О нас|Новости|Просмотр|Запустить|Закрыть ur|اردو|جائزہ|ماڈلز|تحقیق|ہمارے بارے میں|خبریں|دیکھیں|چلائیں|بند کریں id|Bahasa Indonesia|Ikhtisar|Model|Riset|Tentang|Berita|Periksa|Jalankan|Tutup de|Deutsch|Übersicht|Modelle|Forschung|Über uns|Neuigkeiten|Ansehen|Ausführen|Schließen ja|日本語|概要|モデル|研究|私たちについて|ニュース|詳細|実行|閉じる sw|Kiswahili|Muhtasari|Miundo|Utafiti|Kuhusu|Habari|Kagua|Endesha|Funga mr|मराठी|आढावा|मॉडेल्स|संशोधन|आमच्याबद्दल|बातम्या|पहा|चालवा|बंद करा te|తెలుగు|అవలోకనం|మోడల్స్|పరిశోధన|మా గురించి|వార్తలు|చూడండి|రన్ చేయండి|మూసివేయి tr|Türkçe ta|தமிழ்|கண்ணோட்டம்|மாதிரிகள்|ஆராய்ச்சி|எங்களைப் பற்றி|செய்திகள்|பார்க்க|இயக்கு|மூடு vi|Tiếng Việt|Tổng quan|Mô hình|Nghiên cứu|Giới thiệu|Tin tức|Xem|Chạy|Đóng ko|한국어|개요|모델|연구|소개|뉴스|살펴보기|실행|닫기 it|Italiano|Panoramica|Modelli|Ricerca|Chi siamo|Notizie|Esamina|Esegui|Chiudi th|ไทย|ภาพรวม|โมเดล|งานวิจัย|เกี่ยวกับเรา|ข่าว|ตรวจดู|เรียกใช้|ปิด gu|ગુજરાતી|ઝાંખી|મોડલ્સ|સંશોધન|અમારા વિશે|સમાચાર|જુઓ|ચલાવો|બંધ કરો pl|Polski|Przegląd|Modele|Badania|O nas|Aktualności|Zobacz|Uruchom|Zamknij uk|Українська|Огляд|Моделі|Дослідження|Про нас|Новини|Переглянути|Запустити|Закрити fa|فارسی|نمای کلی|مدل‌ها|پژوهش|درباره ما|اخبار|بررسی|اجرا|بستن ml|മലയാളം|അവലോകനം|മോഡലുകൾ|ഗവേഷണം|ഞങ്ങളെക്കുറിച്ച്|വാർത്തകൾ|പരിശോധിക്കുക|പ്രവർത്തിപ്പിക്കുക|അടയ്ക്കുക kn|ಕನ್ನಡ|ಅವಲೋಕನ|ಮಾದರಿಗಳು|ಸಂಶೋಧನೆ|ನಮ್ಮ ಬಗ್ಗೆ|ಸುದ್ದಿ|ವೀಕ್ಷಿಸಿ|ಚಾಲನೆ ಮಾಡಿ|ಮುಚ್ಚಿ nl|Nederlands|Overzicht|Modellen|Onderzoek|Over ons|Nieuws|Bekijken|Uitvoeren|Sluiten ro|Română|Prezentare|Modele|Cercetare|Despre noi|Noutăți|Inspectează|Rulează|Închide el|Ελληνικά|Επισκόπηση|Μοντέλα|Έρευνα|Σχετικά|Νέα|Επιθεώρηση|Εκτέλεση|Κλείσιμο hu|Magyar|Áttekintés|Modellek|Kutatás|Rólunk|Hírek|Megtekintés|Futtatás|Bezárás cs|Čeština|Přehled|Modely|Výzkum|O nás|Novinky|Prohlédnout|Spustit|Zavřít sv|Svenska|Översikt|Modeller|Forskning|Om oss|Nyheter|Granska|Kör|Stäng he|עברית|סקירה|מודלים|מחקר|אודות|חדשות|עיון|הרצה|סגירה fil|Filipino|Pangkalahatang-tanaw|Mga Modelo|Pananaliksik|Tungkol sa Amin|Balita|Suriin|Patakbuhin|Isara ms|Bahasa Melayu|Gambaran|Model|Penyelidikan|Tentang|Berita|Periksa|Jalankan|Tutup bg|Български|Общ преглед|Модели|Изследвания|За нас|Новини|Преглед|Стартиране|Затвори da|Dansk|Overblik|Modeller|Forskning|Om os|Nyheder|Undersøg|Kør|Luk fi|Suomi|Yleiskatsaus|Mallit|Tutkimus|Tietoa|Uutiset|Tarkastele|Suorita|Sulje`; const LANGS = {}, LKEYS = ["navHome","navModels","navRes","navAbout","navNews","inspect","run","close"]; LANGDATA.split("\n").forEach(r => { const [c, name, ...v] = r.split("|"); LANGS[c] = name; if (v.length) T[c] = Object.fromEntries(LKEYS.map((k, i) => [k, v[i]])); }); const TOP5 = ["en","zh","hi","es","ar"], RTL = ["ar","fa","ur","he"], ALIAS = {iw:"he", in:"id", tl:"fil"}; function detectLang(){ const list = (navigator.languages && navigator.languages.length) ? navigator.languages : [navigator.language || "en"]; for (const l of list){ let c = String(l).toLowerCase().split("-")[0]; c = ALIAS[c] || c; if (LANGS[c]) return c; } return "en"; } const OWN = detectLang(); lang = OWN; try { const sv = localStorage.getItem("lang"); if (sv && LANGS[sv] && (TOP5.includes(sv) || sv === OWN)) lang = sv; } catch(e){} (() => { const sel = document.getElementById("lang"); [...TOP5, ...(TOP5.includes(OWN) ? [] : [OWN])].forEach(c => sel.add(new Option(LANGS[c], c))); })(); function applyLang(){ document.documentElement.lang = lang; document.documentElement.dir = RTL.includes(lang) ? "rtl" : "ltr"; document.querySelectorAll("[data-t]").forEach(n => n.textContent = t(n.dataset.t)); document.querySelectorAll("[data-t-ph]").forEach(n => n.placeholder = t(n.dataset.tPh)); $("#lang").value = lang; render(); } $("#lang").onchange = e => { lang = e.target.value; try { localStorage.setItem("lang", lang); } catch(x){} applyLang(); }; document.querySelectorAll(".hf").forEach(a => a.href = "https://huggingface.co/" + ORG); /* ---- series = Hugging Face collections of the organization ---- */ let SERIES = null, DATASETS = []; const unit = {k:.001,m:1,b:1000}; function sizeOf(name){ const m = name.match(/(\d+(?:\.\d+)?)\s?([kmb])\b/i); return m ? m[1]+m[2].toUpperCase() : null; } function fmt(n){ return n>=1e6 ? (n/1e6).toFixed(1)+"M" : n>=1e3 ? (n/1e3).toFixed(1)+"K" : String(n); } function el(tag, props = {}, ...kids){ const e = Object.assign(document.createElement(tag), props); kids.flat().forEach(k => e.append(k)); return e; } // Numeric defaults of generate_raw()/generate() in the repo's modeling file (repetition_penalty, no_repeat_ngram, ...). Text only. async function repoGen(id, mod){ try{ const src = await (await fetch("https://huggingface.co/" + id + "/resolve/main/" + mod + ".py")).text(), out = {}; let i = src.indexOf("def generate_raw("); if(i < 0) i = src.indexOf("def generate("); if(i < 0) return out; for(const a of src.slice(i, src.indexOf("):", i)).matchAll(/(\w+)\s*=\s*(-?\d+(?:\.\d+)?)/g)) out[a[1]] = +a[2]; return out; }catch(e){ return {}; } } // Which activation does the repo's modeling_*.py use? (first of gelu / relu / silu mentioned; "gelu_tanh" if approximate="tanh") async function repoActivation(id, mod){ try{ const src = await (await fetch("https://huggingface.co/" + id + "/resolve/main/" + mod + ".py")).text(); const hit = [["gelu", src.search(/gelu/i)], ["relu", src.search(/relu/i)], ["silu", src.search(/silu|swish/i)]].filter(x => x[1] >= 0).sort((a, b) => a[1] - b[1])[0]; return !hit ? "" : hit[0] === "gelu" && /approximate\s*=\s*["']tanh["']/.test(src) ? "gelu_tanh" : hit[0]; }catch(e){ return ""; } } // Collects candidate character vocabularies from config.json keys and common vocab files (the size is checked against the embedding later). async function repoVocabs(id, f, cfg){ const out = [], add = (src, j) => { const itos = parseVocab(j); if(itos) out.push({src, itos}); }; for(const k of ["chars", "vocab", "stoi", "itos", "char_vocab", "id_to_char", "char_to_id", "characters"]) if(cfg[k] != null) add("config." + k, cfg[k]); for(const name of f.filter(n => /^(vocab|chars|charset|stoi|itos|char_vocab|char_to_id|id_to_char|tokenizer|meta)\.(json|txt)$/i.test(n)).slice(0, 4)){ try{ const txt = await (await fetch("https://huggingface.co/" + id + "/resolve/main/" + name)).text(); if(/\.txt$/i.test(name)) add(name, txt.replace(/\r?\n$/, "").split(/\r?\n/)); else add(name, JSON.parse(txt)); }catch(e){} } return out; } // Reads the numeric defaults from the repo's configuration_*.py __init__ signature (what HF fills in for keys missing in config.json). Text only, never executed. async function repoDefaults(id, mod){ try{ const src = await (await fetch("https://huggingface.co/" + id + "/resolve/main/" + mod + ".py")).text(), out = {}, i = src.indexOf("def __init__"); if(i < 0) return out; for(const a of src.slice(i, src.indexOf("):", i)).matchAll(/(\w+)\s*:\s*[^=,]+?=\s*(-?\d+(?:\.\d+)?(?:e-?\d+)?)\s*[,)\n]/gi)) out[a[1]] = +a[2]; return out; }catch(e){ return {}; } } // Reads the repo's own modeling_*.py as text (never executes it) and returns the model-class attributes that __init__ creates // but no other method ever touches: training-only parts (auxiliary heads, deep supervision ...) whose weights inference can safely skip. async function repoUnused(id, mod, cls){ try{ const src = await (await fetch("https://huggingface.co/" + id + "/resolve/main/" + mod + ".py")).text(), out = new Set(); for(const c of src.split(/\nclass /).slice(1)){ if(!c.startsWith(cls + "(")) continue; const parts = c.split(/\n def /), init = parts.find(x => x.startsWith("__init__")); if(!init) continue; const rest = parts.filter(x => x !== init).join("\n"); for(const a of init.matchAll(/self\.(\w+)\s*=/g)) if(!new RegExp("self\\." + a[1] + "\\b").test(rest)) out.add(a[1]); } return [...out]; }catch(e){ return []; } } // 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). async function probeNative(id, nat){ try{ const url = "https://huggingface.co/" + id + "/resolve/main/" + nat.files[0]; const h0 = await fetch(url, {headers:{Range:"bytes=0-7"}}); if(h0.status !== 206){ if(h0.body) h0.body.cancel(); return null; } const n = Number(new DataView(await h0.arrayBuffer()).getBigUint64(0, true)); if(!(n > 0 && n < 1e8)) return null; const h1 = await fetch(url, {headers:{Range:"bytes=8-" + (7 + n)}}); if(h1.status !== 206) return null; const head = JSON.parse(await h1.text()), info = new Map(); for(const [k, v] of Object.entries(head)) if(k !== "__metadata__") info.set(k, {shape:v.shape, dtype:v.dtype}); const bag = new TensorBag(info), errs = []; for(const k of nat.kinds){ try{ NATIVE_ARCHS[k].plan(nat.cfg, bag, nat.unused); return {ok:true, kind:k}; } catch(e){ if(!(e && e.ntPlan)) throw e; errs.push(k + ": " + e.message); } } return {error:errs.join(" ;; ")}; }catch(e){ return e && e.ntPlan ? {error:e.message} : null; } } async function load(){ try{ // The list endpoint truncates each collection to 4 items, so fetch every collection again for its full item list. const r = await fetch("https://huggingface.co/api/collections?owner=" + encodeURIComponent(ORG) + "&limit=100&sort=lastModified"); if(!r.ok) throw 0; const list = await r.json(); const full = await Promise.all(list.map(async c => { try{ const d = await fetch("https://huggingface.co/api/collections/" + c.slug); return d.ok ? await d.json() : c; }catch(e){ return c; } })); SERIES = full .map(c => ({ title: c.title, desc: c.description || "", url: "https://huggingface.co/collections/" + c.slug, items: (c.items || []).filter(i => i.type === "model") })) .filter(c => c.items.length); // A model is runnable if (a) its repo has a verolm.json key file, (b) it ships a verolm-runner.js, or (c) it has standard ONNX files. const safe = n => typeof n === "string" && /^[\w.\-\/]+$/.test(n) && !n.includes("..") && !n.startsWith("/"); await Promise.all(SERIES.flatMap(s => s.items).filter(i => i.type === "model").map(async m => { m.runtime = null; m.runnable = false; try{ const d = await (await fetch("https://huggingface.co/api/models/" + m.id)).json(); const f = (d.siblings || []).map(x => x.rfilename); const own = m.id.toLowerCase().startsWith(ORG.toLowerCase() + "/"); m.onnxFiles = f.filter(n => /^onnx\/.+\.onnx$/.test(n)); const hasOnnx = m.onnxFiles.length > 0 && f.includes("config.json") && f.includes("tokenizer.json"); if(own && f.includes("verolm.json")){ try{ const mf = await (await fetch("https://huggingface.co/" + m.id + "/resolve/main/verolm.json")).json(); const runner = mf.runner || "verolm-runner.js"; if(mf.runtime === "custom" && safe(runner) && f.includes(runner) && (!mf.weights || (safe(mf.weights) && f.includes(mf.weights)))){ m.runtime = "custom"; m.manifest = mf; }else if(mf.runtime === "onnx" && hasOnnx){ m.runtime = "transformers"; m.manifest = mf; } }catch(e){} }else if(own && f.includes("verolm-runner.js")){ m.runtime = "custom"; m.manifest = {}; } if(!m.runtime && hasOnnx) m.runtime = "transformers"; // (d) built-in engine: any repo whose config.json names an architecture we implement natively and that ships safetensors weights. // No per-repo code is needed or executed, so it works for any owner. A verolm.json with "builtin": false opts out. let cfg = d.config || null; if((!nativeKind(cfg) || (/gen55/i.test(String(cfg.model_type)) && cfg.theta == null)) && f.includes("config.json")){ try{ cfg = await (await fetch("https://huggingface.co/" + m.id + "/resolve/main/config.json")).json(); }catch(e){} } const stFiles = f.includes("model.safetensors") ? ["model.safetensors"] : f.filter(n => /^model-\d+-of-\d+\.safetensors$/.test(n)).sort(); const kinds = nativeKinds(cfg), kind = kinds[0], prior = m.runtime; // prior: custom / transformers, decided above let nat = null; if(kind && stFiles.length && !(m.manifest && m.manifest.builtin === false)){ nat = {kind, kinds, cfg, files:stFiles, unused:[]}; const g55 = /gen55/i.test(String(cfg.model_type)), am = g55 ? [] : String((cfg.auto_map || {}).AutoModelForCausalLM || "").split("."); if(am.length === 2 && f.includes(am[0] + ".py")) nat.unused = await repoUnused(m.id, am[0], am[1]); if(!g55) nat.cfg = Object.assign({}, nat.cfg, {__act:await repoActivation(m.id, am[0]), __gen:await repoGen(m.id, am[0])}); const ac = g55 ? [] : String((cfg.auto_map || {}).AutoConfig || "").split("."); if(ac.length === 2 && f.includes(ac[0] + ".py")) nat.cfg = Object.assign({}, nat.cfg, {__defaults:await repoDefaults(m.id, ac[0])}); if(f.includes("generation_config.json")) try{ const gc = await (await fetch("https://huggingface.co/" + m.id + "/resolve/main/generation_config.json")).json(); nat.gen = {temperature:gc.temperature, top_k:gc.top_k, maxTokens:gc.max_new_tokens, eod_token_id:gc.eos_token_id}; }catch(e){} const vs = g55 ? [] : await repoVocabs(m.id, f, cfg); if(vs.length) nat.cfg = Object.assign({}, nat.cfg, {__vocabs:vs}); const pr = stFiles.length === 1 ? await probeNative(m.id, nat) : null; if(pr && pr.error){ m.whyNot = pr.error; nat = null; } else if(pr && pr.kind){ nat.kind = pr.kind; nat.kinds = [pr.kind]; } // definite mismatch: don't offer an engine that would fail } // engines are tried in this order at run time; a failure falls through to the next one if(!nat && !m.whyNot) m.whyNot = kind ? "built-in engine not applicable (sharded weights or disabled by verolm.json)" : "config.json names no built-in architecture (model_type " + JSON.stringify(cfg.model_type) + ")"; m.chain = []; if(prior === "custom") m.chain.push("custom"); // the model's own runner knows the model best, so it goes first if(nat){ m.native = nat; m.chain.push("native"); m.manifest = Object.assign({arch:nat.kind === "gpt" ? "byte-level GPT transformer" : nat.kind === "notokengen55" ? "hierarchical byte hybrid" : "byte-level transformer"}, nat.gen || {}, m.manifest || {}); } if(hasOnnx || prior === "transformers") m.chain.push("transformers"); m.runtime = m.chain[0] || null; m.runnable = !!m.runtime; }catch(e){ m.runtime = null; m.runnable = false; } })); }catch(e){ SERIES = []; } try{ const r = await fetch("https://huggingface.co/api/datasets?author=" + encodeURIComponent(ORG) + "&limit=100&sort=downloads&direction=-1"); DATASETS = r.ok ? await r.json() : []; }catch(e){ DATASETS = []; } render(); } const sizeM = n => { const m = n.match(/(\d+(?:\.\d+)?)\s?([kmb])\b/i); return m ? +m[1] * unit[m[2].toLowerCase()] : null; }; const pos = M => Math.max(0, Math.min(100, (Math.log10(M) + 1) / 6 * 100)); const PANELS = ["overview","news","models","datasets","research","about"]; function show(p){ if(!PANELS.includes(p)) p = "overview"; document.querySelectorAll(".panel").forEach(s => s.hidden = s.dataset.p !== p); document.querySelectorAll(".tab").forEach(a => a.setAttribute("aria-current", a.dataset.p === p ? "page" : "false")); $("#main").scrollTo(0, 0); $("#side").classList.remove("open"); } /* ---- NEWS: add the newest items to this list. Example: { date:"2026-11-23", tag:"Model", title:"New model announced: X", text:"X scores 41.2 on the Y benchmark.", url:"https://huggingface.co/VeroLM/X" } Newest = yellow, 2nd = blue, 3rd = green, older = grey. ---- */ const NEWS = [ { date:"2026-11-22T12:00", tag:{en:"Brand",tr:"Marka",fr:"Marque",es:"Marca"}, title:{ en:"Our logo’s second and main variant is out: white and red", tr:"Logomuzun 2. ve ana çeşidi yayınlandı: beyaz kırmızı", fr:"La deuxième variante de notre logo, désormais la principale, est disponible : blanc et rouge", es:"Ya está disponible la segunda variante de nuestro logo, la principal: blanco y rojo"}, text:{ en:"The VeroLM logo now has a white-and-red variant, and it becomes our main one. The reason is simple: most people on Hugging Face use a dark theme, and white and red on a dark background is clearer, sharper and easier on the eyes than the earlier version. You will see it first on our Hugging Face organization and model pages, and it will replace the old logo everywhere else step by step.", tr:"VeroLM logosunun beyaz kırmızı çeşidi yayınlandı ve artık ana logomuz bu. Sebebi basit: Hugging Face kullanan çoğu kişi koyu tema kullanıyor ve koyu zemin üzerinde beyaz kırmızı renkler hem daha net hem daha keskin görünüyor, gözü de daha az yoruyor. Önce Hugging Face organizasyon ve model sayfalarımızda göreceksiniz, diğer yerlerde de eski logonun yerini adım adım alacak.", fr:"Le logo de VeroLM a désormais une variante blanc et rouge, qui devient notre logo principal. La raison est simple : la plupart des utilisateurs de Hugging Face choisissent un thème sombre, et le blanc et le rouge sur fond sombre sont plus nets, plus lisibles et plus reposants que la version précédente. Vous le verrez d’abord sur notre organisation et nos pages de modèles Hugging Face, puis il remplacera progressivement l’ancien logo partout ailleurs.", es:"El logo de VeroLM ya tiene una variante en blanco y rojo, y pasa a ser la principal. El motivo es sencillo: la mayoría de los usuarios de Hugging Face usa un tema oscuro, y el blanco y el rojo sobre fondo oscuro se ven más nítidos y cansan menos la vista que la versión anterior. Lo verás primero en nuestra organización y en las páginas de modelos de Hugging Face, y sustituirá poco a poco al logo anterior en el resto de sitios."}}, { date:"2026-11-22T09:00", tag:{en:"Model",tr:"Model",fr:"Modèle",es:"Modelo"}, title:{en:"NoTokenLM-Gen-5.5 is out",tr:"NoTokenLM-Gen-5.5 çıktı",fr:"NoTokenLM-Gen-5.5 est disponible",es:"Ya está aquí NoTokenLM-Gen-5.5"}, url:"https://huggingface.co/VeroLM/NoTokenLM-Gen-5.5", text:{ en:"A tokenizer-free, byte-level base model with 168.9M parameters, trained on about 100B bytes of mostly English text plus math, code and French. No vocabulary, no BPE: UTF-8 bytes in, UTF-8 bytes out. It groups bytes into patches of about 6 bytes and runs a hybrid RWKV-7 and gated-attention trunk once per patch. It is a research base model, not a chat model. Apache-2.0.", tr:"Belirteçleyicisiz (tokenizer-free), bayt düzeyinde, 168,9M parametreli bir temel model. Çoğunlukla İngilizce metin, ayrıca matematik, kod ve Fransızca içeren yaklaşık 100B bayt üzerinde eğitildi. Sözlük yok, BPE yok: girdi UTF-8 baytları, çıktı UTF-8 baytları. Baytları yaklaşık 6 baytlık yamalara ayırıp melez RWKV-7 ve geçitli dikkat gövdesini yama başına bir kez çalıştırıyor. Sohbet modeli değil, bir araştırma temel modeli. Apache-2.0.", fr:"Un modèle de base sans tokenizer, au niveau de l’octet, de 168,9 M de paramètres, entraîné sur environ 100 Go d’octets, surtout en anglais, avec aussi des maths, du code et du français. Pas de vocabulaire, pas de BPE : des octets UTF-8 en entrée, des octets UTF-8 en sortie. Il regroupe les octets en patchs d’environ 6 octets et exécute un tronc hybride RWKV-7 et attention à portes une fois par patch. C’est un modèle de base de recherche, pas un modèle de chat. Apache-2.0.", es:"Un modelo base sin tokenizador, a nivel de byte, con 168,9 M de parámetros, entrenado con unos 100 000 millones de bytes, sobre todo en inglés, además de matemáticas, código y francés. Sin vocabulario ni BPE: entran bytes UTF-8 y salen bytes UTF-8. Agrupa los bytes en parches de unos 6 bytes y ejecuta un tronco híbrido RWKV-7 y atención con puertas una vez por parche. Es un modelo base de investigación, no de chat. Apache-2.0."}} ]; const pick = v => (v && typeof v === "object") ? (v[lang] || v.en) : v; function renderNews(){ const box = $("#newsList"); box.replaceChildren(); const items = NEWS.slice().sort((a, b) => String(b.date).localeCompare(String(a.date))); if(!items.length){ box.append(el("div",{className:"empty"}, el("strong",{textContent:t("newsEmpty")}), el("span",{textContent:t("newsEmptyS")}))); return; } items.forEach((n, i) => { const d = new Date(n.date), when = isNaN(d) ? n.date : d.toLocaleDateString(lang, {year:"numeric",month:"long",day:"numeric"}); const meta = el("div",{className:"nd"}, el("i",{}), el("span",{textContent:when})); if(n.tag) meta.append(el("span",{className:"tg",textContent:pick(n.tag)})); box.append(el("article",{className:"ni" + (i < 3 ? " n" + (i + 1) : "")}, meta, el("h3",{}, n.url ? el("a",{href:n.url,target:"_blank",rel:"noopener",textContent:pick(n.title)}) : (pick(n.title) || "")), n.text ? el("p",{textContent:pick(n.text)}) : "")); }); } function renderSide(){ const b = $("#sidesr"); b.replaceChildren(); $("#sidel").hidden = !(SERIES && SERIES.length); (SERIES || []).forEach((s, i) => { const x = el("button",{type:"button",className:"sr",textContent:s.title}); x.onclick = () => { Q = ""; $("#q").value = ""; render(); location.hash = "models"; setTimeout(() => { const e = document.getElementById("sr" + i); if(e) e.scrollIntoView({behavior:"smooth"}); $("#side").classList.remove("open"); }, 80); }; b.append(x); }); } function renderRuler(){ const box = $("#ruler"); box.replaceChildren(); if(!SERIES) return; [[1,"1M"],[10,"10M"],[100,"100M"],[1e3,"1B"],[1e4,"10B"]].forEach(([v, l]) => box.append(el("span",{className:"tick",textContent:l,style:"left:" + pos(v) + "%"}))); const seen = {}; let n = 0; SERIES.flatMap(s => s.items).forEach(m => { const name = m.id.split("/").pop(), M = sizeM(name); if(!M) return; n++; const k = seen[M] = (seen[M] || 0) + 1; const b = el("button",{type:"button",className:"rb",title:name}); b.setAttribute("aria-label", name); b.style.left = "calc(" + pos(M) + "% + " + (k - 1) * 13 + "px)"; b.style.height = (16 + pos(M) * 1.1) + "px"; b.onclick = () => { $("#q").value = Q = name; render(); location.hash = "models"; }; box.append(b); }); $("#rwrap").hidden = !n; } function renderDatasets(){ const box = $("#dlist"); box.replaceChildren(); $("#navData").hidden = !DATASETS.length; if(!DATASETS.length && location.hash === "#datasets") show("overview"); DATASETS.forEach(d => { const meta = el("div",{className:"meta"}, el("span",{textContent:t("dsTag")})); if(d.downloads != null) meta.append(el("span",{textContent:fmt(d.downloads)+" "+t("dl")})); box.append(el("div",{className:"card"}, el("h4",{textContent:d.id.split("/").pop()}), meta, el("div",{className:"act"}, el("a",{className:"btn ghost",href:"https://huggingface.co/datasets/"+d.id,target:"_blank",rel:"noopener",textContent:t("inspect")})))); }); } function render(){ renderDatasets(); renderRuler(); renderSide(); renderNews(); const box = $("#list"); if(SERIES === null) return; box.replaceChildren(); const q = Q.trim().toLowerCase(); let shown = 0; SERIES.forEach((sr, si) => { const items = sr.items.filter(m => (!ONLY || m.runnable) && (!q || m.id.toLowerCase().includes(q))); if(!items.length) return; shown++; const grid = el("div",{className:"grid"}); items.forEach(m => { const name = m.id.split("/").pop(), size = sizeOf(name), M = sizeM(name); const meta = el("div",{className:"meta"}); if(m.runnable) meta.append(el("span",{className:"ok",textContent:t("fRun")})); if(m.manifest && typeof m.manifest.arch === "string") meta.append(el("span",{textContent:m.manifest.arch.slice(0,24)})); if(m.pipeline_tag) meta.append(el("span",{textContent:m.pipeline_tag})); if(m.downloads != null) meta.append(el("span",{textContent:fmt(m.downloads)+" "+t("dl")})); const run = el("button",{className:"btn red",type:"button",textContent:t("run")}); run.dataset.id = m.id; run.disabled = !m.runnable; if(!m.runnable) run.title = t("noRun"); run.onclick = () => openRun(m); grid.append(el("div",{className:"card"}, size ? el("div",{className:"sz",textContent:size}) : "", size ? el("div",{className:"mtr"}, el("i",{style:"width:" + pos(M) + "%"})) : "", el("h4",{textContent:name}), meta, el("div",{className:"act"}, el("a",{className:"btn ghost",href:"https://huggingface.co/"+m.id,target:"_blank",rel:"noopener",textContent:t("inspect")}), run))); }); const nm = items.length; box.append(el("div",{className:"series",id:"sr" + si}, el("h3",{}, el("a",{href:sr.url,target:"_blank",rel:"noopener",textContent:sr.title}), el("small",{textContent:nm + " " + (nm === 1 ? t("model") : t("models"))})), sr.desc ? el("p",{className:"desc",textContent:sr.desc}) : "", grid)); }); if(!shown){ const none = SERIES.length > 0; box.append(el("div",{className:"empty"}, el("strong",{textContent:t(none ? "noMatch" : "oopsT")}), el("span",{textContent:none ? "" : t("oopsB")}))); } } /* ---- PyTorch .pt reader: parses zip + a restricted pickle, never executes code ---- */ const PT_TYPES = {FloatStorage:["float32",Float32Array],DoubleStorage:["float64",Float64Array],HalfStorage:["float16",Uint16Array],BFloat16Storage:["bfloat16",Uint16Array],LongStorage:["int64",BigInt64Array],IntStorage:["int32",Int32Array],ShortStorage:["int16",Int16Array],CharStorage:["int8",Int8Array],ByteStorage:["uint8",Uint8Array],BoolStorage:["bool",Uint8Array]}; async function inflateRaw(u8){ const out = new Blob([u8]).stream().pipeThrough(new DecompressionStream("deflate-raw")); return new Uint8Array(await new Response(out).arrayBuffer()); } async function readZip(buf){ const dv = new DataView(buf), u8 = new Uint8Array(buf); let e = buf.byteLength - 22; while(e >= 0 && dv.getUint32(e, true) !== 0x06054b50) e--; if(e < 0) throw new Error("This .pt file isn’t in the zip-based PyTorch format (legacy files aren’t supported)."); const n = dv.getUint16(e + 10, true); let off = dv.getUint32(e + 16, true); const files = new Map(), td = new TextDecoder(); for(let i = 0; i < n; i++){ if(dv.getUint32(off, true) !== 0x02014b50) throw new Error("Corrupt zip directory."); const method = dv.getUint16(off + 10, true), csize = dv.getUint32(off + 20, true); const nl = dv.getUint16(off + 28, true), xl = dv.getUint16(off + 30, true), cl = dv.getUint16(off + 32, true), lh = dv.getUint32(off + 42, true); if(csize === 0xffffffff || lh === 0xffffffff) throw new Error("Zip64 (very large) .pt files aren’t supported yet."); files.set(td.decode(u8.subarray(off + 46, off + 46 + nl)), {method, csize, lh}); off += 46 + nl + xl + cl; } const get = async name => { const f = files.get(name); if(!f) throw new Error("Missing " + name + " in .pt file."); const p = f.lh + 30 + dv.getUint16(f.lh + 26, true) + dv.getUint16(f.lh + 28, true); const raw = u8.subarray(p, p + f.csize); if(f.method === 0) return raw; if(f.method === 8) return inflateRaw(raw); throw new Error("Unsupported zip compression in .pt file."); }; return {files, get}; } function ptGlobal(fn, a){ switch(fn && fn.g){ case "collections.OrderedDict": return new Map(); case "torch._utils._rebuild_tensor_v2": case "torch._utils._rebuild_tensor": return {tensor:true, storage:a[0], offset:a[1], shape:a[2], stride:a[3]}; case "torch._utils._rebuild_parameter": return a[0]; default: throw new Error("Blocked object in .pt (" + (fn && fn.g || "unknown") + "). Save a plain state_dict: torch.save(model.state_dict(), 'model.pt')."); } } function unpickle(b){ const st = [], memo = new Map(), marks = [], td = new TextDecoder(); const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); let i = 0, nm = 0; const popMark = () => st.splice(marks.pop()); const take = n => { const v = b.subarray(i, i + n); i += n; return v; }; const line = () => { let j = i; while(b[j] !== 10) j++; const v = td.decode(b.subarray(i, j)); i = j + 1; return v; }; for(;;){ const op = b[i++]; switch(op){ case 0x80: i++; break; case 0x95: i += 8; break; case 0x7d: st.push(new Map()); break; case 0x5d: case 0x29: st.push([]); break; case 0x28: marks.push(st.length); break; case 0x71: memo.set(b[i++], st[st.length - 1]); break; case 0x72: memo.set(dv.getUint32(i, true), st[st.length - 1]); i += 4; break; case 0x94: memo.set(nm++, st[st.length - 1]); break; case 0x68: st.push(memo.get(b[i++])); break; case 0x6a: st.push(memo.get(dv.getUint32(i, true))); i += 4; break; case 0x4e: st.push(null); break; case 0x88: st.push(true); break; case 0x89: st.push(false); break; case 0x4b: st.push(b[i++]); break; case 0x4d: st.push(dv.getUint16(i, true)); i += 2; break; case 0x4a: st.push(dv.getInt32(i, true)); i += 4; break; case 0x8a: { const n = b[i++]; let v = 0n; for(let k = n - 1; k >= 0; k--) v = (v << 8n) | BigInt(b[i + k]); if(n && (b[i + n - 1] & 0x80)) v -= 1n << BigInt(8 * n); i += n; st.push(Number(v)); break; } case 0x47: st.push(dv.getFloat64(i, false)); i += 8; break; case 0x58: case 0x54: { const n = dv.getUint32(i, true); i += 4; st.push(td.decode(take(n))); break; } case 0x8c: case 0x55: { const n = b[i++]; st.push(td.decode(take(n))); break; } case 0x63: { const mod = line(), nme = line(); st.push({g: mod + "." + nme}); break; } case 0x93: { const nme = st.pop(), mod = st.pop(); st.push({g: mod + "." + nme}); break; } case 0x74: st.push(popMark()); break; case 0x85: st.push([st.pop()]); break; case 0x86: { const y = st.pop(), x = st.pop(); st.push([x, y]); break; } case 0x87: { const z = st.pop(), y = st.pop(), x = st.pop(); st.push([x, y, z]); break; } case 0x73: { const v = st.pop(), k = st.pop(); st[st.length - 1].set(k, v); break; } case 0x75: { const it = popMark(), d = st[st.length - 1]; for(let k = 0; k < it.length; k += 2) d.set(it[k], it[k + 1]); break; } case 0x61: { const v = st.pop(); st[st.length - 1].push(v); break; } case 0x65: { const it = popMark(); st[st.length - 1].push(...it); break; } case 0x52: { const args = st.pop(), fn = st.pop(); st.push(ptGlobal(fn, args)); break; } case 0x51: { // BINPERSID: ("storage", StorageClass, key, location, numel) const pid = st.pop(), cls = pid[1] && pid[1].g ? pid[1].g.split(".").pop() : ""; if(pid[0] !== "storage" || !PT_TYPES[cls]) throw new Error("Unsupported tensor storage in .pt file (" + cls + ")."); st.push({storage:true, cls, key:String(pid[2]), numel:pid[4]}); break; } case 0x62: st.pop(); break; // BUILD: attributes such as _metadata are ignored case 0x2e: return st.pop(); default: throw new Error("Unsupported pickle opcode 0x" + op.toString(16) + " in .pt file."); } } } async function readPt(buf){ const zip = await readZip(buf); const pkl = [...zip.files.keys()].find(n => n.endsWith("data.pkl")); if(!pkl) throw new Error(zip.files.has("constants.pkl") || [...zip.files.keys()].some(n => n.includes("/code/")) ? "TorchScript files can’t be read. Save a plain state_dict instead." : "No data.pkl found: not a PyTorch checkpoint."); const root = unpickle(await zip.get(pkl)), prefix = pkl.slice(0, -"data.pkl".length); const cache = new Map(), out = new Map(); const storageData = async (sd) => { if(!cache.has(sd.key)){ const bytes = await zip.get(prefix + "data/" + sd.key), Arr = PT_TYPES[sd.cls][1]; const aligned = bytes.byteOffset % Arr.BYTES_PER_ELEMENT === 0; const src = aligned ? bytes : bytes.slice(); cache.set(sd.key, new Arr(src.buffer, src.byteOffset, Math.floor(src.byteLength / Arr.BYTES_PER_ELEMENT))); } return cache.get(sd.key); }; const leaf = async (t) => { const arr = await storageData(t.storage), shape = t.shape, stride = t.stride; const numel = shape.reduce((a, b) => a * b, 1); let dense = true, acc = 1; for(let d = shape.length - 1; d >= 0; d--){ if(shape[d] !== 1 && stride[d] !== acc) dense = false; acc *= shape[d]; } let data; if(dense) data = arr.subarray(t.offset, t.offset + numel); else{ data = new arr.constructor(numel); const idx = new Array(shape.length).fill(0); for(let n = 0; n < numel; n++){ let p = t.offset; for(let d = 0; d < shape.length; d++) p += idx[d] * stride[d]; data[n] = arr[p]; for(let d = shape.length - 1; d >= 0; d--){ if(++idx[d] < shape[d]) break; idx[d] = 0; } } } return {shape, dtype:PT_TYPES[t.storage.cls][0], data}; }; const walk = async (node, path) => { if(node && node.tensor) out.set(path, await leaf(node)); else if(node instanceof Map) for(const [k, v] of node) if(k !== "_metadata") await walk(v, path ? path + "." + k : String(k)); }; await walk(root, ""); for(const pre of ["state_dict.", "model."]) if(out.size && [...out.keys()].every(k => k.startsWith(pre))){ const re = new Map(); for(const [k, v] of out) re.set(k.slice(pre.length), v); return re; } return out; } function toFloat32(t){ const d = t.data; if(t.dtype === "float32") return d; if(t.dtype === "bfloat16"){ const u = new Uint32Array(d.length); for(let i = 0; i < d.length; i++) u[i] = d[i] << 16; return new Float32Array(u.buffer); } if(t.dtype === "float16"){ const f = new Float32Array(d.length); for(let i = 0; i < d.length; i++){ const h = d[i], e = (h >> 10) & 31, m = h & 1023, sg = h & 0x8000 ? -1 : 1; f[i] = e === 0 ? sg * m * 5.960464477539063e-8 : e === 31 ? (m ? NaN : sg * Infinity) : sg * (1 + m / 1024) * Math.pow(2, e - 15); } return f; } return Float32Array.from(d, Number); } async function fetchBuffer(url, onProgress){ const r = await fetch(url); if(!r.ok) throw new Error("Download failed (" + r.status + "): " + url); const total = +r.headers.get("content-length") || 0; if(!r.body) return r.arrayBuffer(); const rd = r.body.getReader(); let got = 0; if(total){ // size known: write straight into one buffer, so memory peaks at 1x the file size instead of 2x const out = new Uint8Array(total); for(;;){ const {done, value} = await rd.read(); if(done) break; if(got + value.length > total) throw new Error("Download larger than announced size."); out.set(value, got); got += value.length; if(onProgress) onProgress(got / total * 100); } if(got !== total) throw new Error("Download was cut off (" + got + " of " + total + " bytes). Please try again."); return out.buffer; } const chunks = []; for(;;){ const {done, value} = await rd.read(); if(done) break; chunks.push(value); got += value.length; } const out = new Uint8Array(got); let o = 0; for(const c of chunks){ out.set(c, o); o += c.length; } return out.buffer; } /* ---- safetensors reader ---- */ const ST_TYPES = {F32:["float32",Float32Array],F64:["float64",Float64Array],F16:["float16",Uint16Array],BF16:["bfloat16",Uint16Array],I64:["int64",BigInt64Array],I32:["int32",Int32Array],I16:["int16",Int16Array],I8:["int8",Int8Array],U8:["uint8",Uint8Array],BOOL:["bool",Uint8Array]}; function readSafetensors(buf){ const dv = new DataView(buf), n = Number(dv.getBigUint64(0, true)); if(!(n > 0) || n > buf.byteLength - 8) throw new Error("Not a safetensors file."); const head = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, 8, n))), base = 8 + n, out = new Map(); for(const [name, info] of Object.entries(head)){ if(name === "__metadata__") continue; const ty = ST_TYPES[info.dtype]; if(!ty) throw new Error("Unsupported safetensors dtype " + info.dtype); const [a, b] = info.data_offsets, Arr = ty[1]; let data; if((base + a) % Arr.BYTES_PER_ELEMENT === 0) data = new Arr(buf, base + a, (b - a) / Arr.BYTES_PER_ELEMENT); else data = new Arr(buf.slice(base + a, base + b)); out.set(name, {shape:info.shape, dtype:ty[0], data}); } return out; } /* ---- tolerant tensor lookup: ignores wrapper prefixes (module., _orig_mod., model. ...) and w/weight, b/bias aliases ---- */ const NT_PRE = /^(module\.|_orig_mod\.|state_dict\.|model\.|transformer\.|backbone\.|net\.)/; function canon(n){ n = String(n).toLowerCase(); let p; do{ p = n; n = n.replace(NT_PRE, ""); }while(n !== p); return n.replace(/\.w$/, ".weight").replace(/\.b$/, ".bias").replace(/\.(scale|gamma)$/, ".weight") .replace(/^(token_embed|embed_tokens|tok_embeddings|tok_emb|wte|embeddings?|embed|emb)\./, "emb."); } // Compact inventory for error messages: the tensors outside the repeated blocks plus the names inside the first block. function tensorSummary(keys){ const isBlk = k => /(^|\.)[A-Za-z_]+\.\d+\./.test(k), out = keys.filter(k => !isBlk(k)).slice(0, 12); const b0 = keys.filter(k => /(^|\.)[A-Za-z_]+\.0\./.test(k) && !/aux_norms|multi_step/.test(k)).slice(0, 14); return "tensors outside the blocks: " + (out.join(", ") || "none") + (b0.length ? " | first block: " + b0.join(", ") : "") + " (" + keys.length + " total)"; } class TensorBag extends Map{ 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); } } find(name){ if(super.has(name)) return name; const c = canon(name); if(this.idx.has(c)) return this.idx.get(c); 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); } return this.memo.get(c); } get(name){ const k = this.find(name); return k == null ? undefined : super.get(k); } has(name){ return this.find(name) != null; } } /* ---- built-in engines: run a model straight from config.json + weights, no per-repo code needed ---- */ // To support another architecture, add an entry to NATIVE_ARCHS keyed by the model_type in its config.json. // Each entry has: build(cfg, tensors) -> model object, and generate(model, prompt, onToken, opts) -> Promise. const NATIVE_ALIASES = {NoTokenLMForCausalLM:"notokenlm"}; function nativeKinds(cfg){ if(!cfg) return []; const blob = [cfg.model_type, cfg.tokenizer_class].concat(cfg.architectures || [], Object.values(cfg.auto_map || {}).flat()).join(" "); const mt = String(cfg.model_type || "").toLowerCase().replace(/[-_]/g, ""); let kind = NATIVE_ARCHS[mt] ? mt : /notoken/i.test(blob) ? "notokenlm" : null; if(!kind && Number(cfg.vocab_size) === 256 && (cfg.d_model || cfg.hidden_size || cfg.n_embd) && (cfg.n_head || cfg.num_attention_heads)) kind = "notokenlm"; if(!kind) return []; return [kind].concat(Object.keys(NATIVE_ARCHS).filter(k => k !== kind)).filter(k => !NATIVE_ARCHS[k].supports || NATIVE_ARCHS[k].supports(cfg)); } function nativeKind(cfg){ return nativeKinds(cfg)[0] || null; } /* NoTokenLM: byte-level (vocab 256), RoPE, RMSNorm, SwiGLU, weight-tied head, UTF-8-safe sampling */ function ntFail(msg){ const e = new Error(msg); e.ntPlan = true; return e; } const NT = { emb:["token_embed.weight","embed_tokens.weight","wte.weight","tok_embeddings.weight","embedding.weight","embed.weight"], fn:["final_norm.weight","norm.weight","ln_f.weight","norm_f.weight","final_layernorm.weight"], head:["lm_head.weight","output.weight","head.weight"], n1:["norm1.weight","input_layernorm.weight","attention_norm.weight","ln_1.weight","attn_norm.weight"], qkv:["attn.qkv.weight","self_attn.qkv_proj.weight","attention.wqkv.weight","attn.qkv_proj.weight"], 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"], out:["attn.out_proj.weight","self_attn.o_proj.weight","attention.wo.weight","attn.o_proj.weight","attn.proj.weight"], n2:["norm2.weight","post_attention_layernorm.weight","ffn_norm.weight","ln_2.weight","mlp_norm.weight"], wg:["mlp.w_gate.weight","mlp.gate_proj.weight","feed_forward.w1.weight","mlp.w1.weight"], wu:["mlp.w_up.weight","mlp.up_proj.weight","feed_forward.w3.weight","mlp.w3.weight"], wd:["mlp.w_down.weight","mlp.down_proj.weight","feed_forward.w2.weight","mlp.w2.weight"] }; // Validates config + tensor names/sizes WITHOUT needing the weight data (shapes are enough), so it also runs on a safetensors header. // Throws a tagged, descriptive error if this checkpoint is not exactly what the engine implements; never guesses silently. function ntPlan(cfg, bag, unused){ const used = new Set(), num = k => bag.get(k).shape.reduce((a, b) => a * b, 1); const pick = (...ks) => { for(const k of ks) if(Number.isFinite(+cfg[k]) && +cfg[k] > 0) return +cfg[k]; }; const blk = (i, subs) => ["blocks.", "layers.", "h.", "block."].flatMap(p => subs.map(x => p + i + "." + x)); const any = c => c.some(n => bag.find(n) != null); const first = (c, what, len) => { for(const n of c){ const k = bag.find(n); if(k != null){ 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."); used.add(k); return k; } } throw ntFail("Missing tensor " + c[0] + " (" + what + "). " + tensorSummary([...bag.keys()])); }; const V = pick("vocab_size") || 256, ek = first(NT.emb, "token embedding"), en = num(ek); const D = pick("d_model", "hidden_size", "n_embd", "dim", "embed_dim") || en / V; if(!Number.isInteger(D) || en !== V * D) throw ntFail("Embedding has " + en + " values but vocab_size " + V + " x d_model " + D + " was expected."); let L = pick("n_layer", "num_hidden_layers", "n_layers", "num_layers"); if(!L){ L = 0; while(any(blk(L, NT.n1))) L++; } let H = pick("n_head", "num_attention_heads", "n_heads", "num_heads"); if(!H){ const rk = bag.find("rope_cos") ?? bag.find("rope_sin"); if(rk != null){ const sh = bag.get(rk).shape, hd = sh[sh.length - 1]; if(hd > 0 && D % hd === 0) H = D / hd; } } if(!H && cfg.__defaults) H = +cfg.__defaults.n_head || +cfg.__defaults.num_attention_heads || undefined; if(!(L > 0)) throw ntFail("No transformer blocks with a known naming (blocks.N / layers.N / h.N); " + tensorSummary([...bag.keys()])); if(!H) throw ntFail("config.json has no head count (n_head / num_attention_heads)."); const kv = pick("num_key_value_heads", "n_kv_head", "n_kv_heads"); if(kv && kv !== H) throw ntFail("Grouped-query attention (" + kv + " kv heads vs " + H + ") isn't supported by the built-in engine."); 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."); const F = pick("d_ff", "intermediate_size", "ffn_dim", "ffn_hidden_size") || num(first(blk(0, NT.wg), "mlp gate")) / D; if(!Number.isInteger(F) || F <= 0) throw ntFail("Could not determine the MLP width (d_ff)."); const blocks = []; for(let i = 0; i < L; i++){ const b = {n1:first(blk(i, NT.n1), "block " + i + " norm1", D)}; if(any(blk(i, NT.qkv))) b.qkv = first(blk(i, NT.qkv), "block " + i + " qkv", 3 * D * D); 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)]; b.out = first(blk(i, NT.out), "block " + i + " attention output", D * D); b.n2 = first(blk(i, NT.n2), "block " + i + " norm2", D); b.wg = first(blk(i, NT.wg), "block " + i + " mlp gate", F * D); b.wu = first(blk(i, NT.wu), "block " + i + " mlp up", F * D); b.wd = first(blk(i, NT.wd), "block " + i + " mlp down", D * F); blocks.push(b); } const fn = first(NT.fn, "final norm", D); const hk = NT.head.map(n => bag.find(n)).find(k => k != null); if(hk != null){ if(num(hk) !== V * D) throw ntFail("Output head has " + num(hk) + " values, expected " + V * D + "."); used.add(hk); } // every remaining weight must be understood: otherwise this is a different architecture variant and output would be garbage const extra = [...bag.keys()].filter(k => !used.has(k) && !/(inv_freq|position_ids|masked_bias|attn\.bias|rotary|rope_cos|rope_sin|cos_cached|sin_cached|aux_norms|multi_step_norm)/i.test(k) && !(unused || []).includes(canon(k).split(".")[0])); 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."); return {D, H, L, F, V, embed:ek, fn, head:hk != null ? hk : ek, blocks}; } function ntBuild(cfg, tensors, unused){ const bag = tensors instanceof TensorBag ? tensors : new TensorBag(tensors), P = ntPlan(cfg, bag, unused); const f = k => toFloat32(bag.get(k)); 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; }; 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)})); const embed = f(P.embed); 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, 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}; } // y[o] = sum_i W[o*n + i] * x[i] (W is [out, in] row-major, like torch.nn.Linear) function ntMatVec(W, x, y, out, n){ const n4 = n - (n % 4); for(let o = 0, base = 0; o < out; o++, base += n){ let s0 = 0, s1 = 0, s2 = 0, s3 = 0, i = 0; for(; i < n4; i += 4){ s0 += W[base + i] * x[i]; s1 += W[base + i + 1] * x[i + 1]; s2 += W[base + i + 2] * x[i + 2]; s3 += W[base + i + 3] * x[i + 3]; } for(; i < n; i++) s0 += W[base + i] * x[i]; y[o] = s0 + s1 + s2 + s3; } } function ntRms(x, w, y, n, eps){ let ss = 0; for(let i = 0; i < n; i++) ss += x[i] * x[i]; const r = 1 / Math.sqrt(ss / n + eps); for(let i = 0; i < n; i++) y[i] = x[i] * r * w[i]; } // Runs one token through the network at position `pos`; fills `st.logits` when wantLogits is true. function ntStep(M, st, tok, pos, wantLogits){ const {D, H, L, F, V, hd} = M, half = hd >> 1, scale = 1 / Math.sqrt(hd); const {x, xn, qkv, att, tmp, g, u, scores, cos, sin} = st; x.set(M.embed.subarray(tok * D, (tok + 1) * D)); for(let l = 0; l < L; l++){ const B = M.blocks[l], K = st.kc[l], Vc = st.vc[l]; ntRms(x, B.n1, xn, D, M.eps); ntMatVec(B.qkv, xn, qkv, 3 * D, D); // rotary embedding (rotate_half layout: pairs are (i, i + hd/2)) for(let h = 0; h < H; h++){ const o = h * hd; for(let i = 0; i < half; i++){ const c = cos[pos * half + i], s = sin[pos * half + i]; const q1 = qkv[o + i], q2 = qkv[o + i + half]; qkv[o + i] = q1 * c - q2 * s; qkv[o + i + half] = q2 * c + q1 * s; const k1 = qkv[D + o + i], k2 = qkv[D + o + i + half]; qkv[D + o + i] = k1 * c - k2 * s; qkv[D + o + i + half] = k2 * c + k1 * s; } } K.set(qkv.subarray(D, 2 * D), pos * D); Vc.set(qkv.subarray(2 * D, 3 * D), pos * D); for(let h = 0; h < H; h++){ const o = h * hd; let mx = -Infinity; for(let t = 0; t <= pos; t++){ let s = 0; const kb = t * D + o; for(let i = 0; i < hd; i++) s += qkv[o + i] * K[kb + i]; s *= scale; scores[t] = s; if(s > mx) mx = s; } let sum = 0; for(let t = 0; t <= pos; t++){ const e = Math.exp(scores[t] - mx); scores[t] = e; sum += e; } for(let i = 0; i < hd; i++) att[o + i] = 0; for(let t = 0; t <= pos; t++){ const w = scores[t] / sum, vb = t * D + o; for(let i = 0; i < hd; i++) att[o + i] += w * Vc[vb + i]; } } ntMatVec(B.out, att, tmp, D, D); for(let i = 0; i < D; i++) x[i] += tmp[i]; ntRms(x, B.n2, xn, D, M.eps); ntMatVec(B.wg, xn, g, F, D); ntMatVec(B.wu, xn, u, F, D); for(let i = 0; i < F; i++) g[i] = (g[i] / (1 + Math.exp(-g[i]))) * u[i]; // silu(gate) * up ntMatVec(B.wd, g, tmp, D, F); for(let i = 0; i < D; i++) x[i] += tmp[i]; } if(wantLogits){ ntRms(x, M.fn, xn, D, M.eps); ntMatVec(M.head, xn, st.logits, V, D); // weight-tied output head } } // Same rule as Utf8ValidityMask in tokenization_notokenlm.py function ntAllowed(rem, b){ if(rem > 0) return b >= 0x80 && b < 0xC0; return b < 0x80 || (b >= 0xC2 && b < 0xF5); } function ntAdvance(rem, b){ if(rem > 0) return rem - 1; if((b & 0x80) === 0) return 0; if((b & 0xE0) === 0xC0) return 1; if((b & 0xF0) === 0xE0) return 2; if((b & 0xF8) === 0xF0) return 3; return 0; } // Same two rules as the repo's generate_raw: logits of the last 50 tokens are divided by repetition_penalty, and any token that would // complete an n-gram already present in the history is banned (both applied before temperature / top-k). function ntAdjust(M, logits, hist){ const lg = Float32Array.from(logits), n = M.nrng; if(M.rep > 1) for(const t of new Set(hist.slice(-50))) lg[t] /= M.rep; if(n > 0 && hist.length >= n){ const pre = hist.slice(-(n - 1)); for(let i = 0; i + n <= hist.length; i++){ let ok = true; for(let j = 0; j < n - 1; j++) if(hist[i + j] !== pre[j]){ ok = false; break; } if(ok) lg[hist[i + n - 1]] = -Infinity; } } return lg; } async function ntGenerate(M, prompt, onToken, o){ const {D, H, L, V, hd} = M, half = hd >> 1; let bytes = M.vocab ? M.vocab.encode(prompt) : new TextEncoder().encode(prompt); if(M.vocab){ if(M.vocab.bos != null) bytes = [M.vocab.bos].concat(bytes); else if(!bytes.length) bytes = [M.vocab.start]; } if(bytes.length > M.ropeLen - 8) bytes = Array.from(bytes).slice(-Math.max(1, M.ropeLen >> 1)); // keep the end of an over-long prompt const maxNew = Math.max(0, Math.min(o.maxTokens, M.ropeLen - bytes.length)); const total = bytes.length + maxNew; if(!bytes.length || !maxNew) return; const hist = Array.from(bytes); const st = { x:new Float32Array(D), xn:new Float32Array(D), qkv:new Float32Array(3 * D), att:new Float32Array(D), tmp:new Float32Array(Math.max(D, M.F)), g:new Float32Array(M.F), u:new Float32Array(M.F), scores:new Float32Array(total), logits:new Float32Array(V), kc:Array.from({length:L}, () => new Float32Array(total * D)), vc:Array.from({length:L}, () => new Float32Array(total * D)), cos:new Float32Array(total * half), sin:new Float32Array(total * half) }; for(let p = 0; p < total; p++) for(let i = 0; i < half; i++){ const f = p * Math.pow(M.theta, -(2 * i) / hd); st.cos[p * half + i] = Math.cos(f); st.sin[p * half + i] = Math.sin(f); } let rem = 0; for(let p = 0; p < bytes.length; p++){ (M.step || ntStep)(M, st, bytes[p], p, p === bytes.length - 1); rem = ntAdvance(rem, bytes[p]); } const dec = new TextDecoder("utf-8"), eod = M.vocab ? (M.vocab.eos == null ? -1 : M.vocab.eos) : (o.eod === undefined ? 0 : o.eod), cand = [], vals = []; for(let n = 0; n < maxNew; n++){ const lg = (M.rep > 1 || M.nrng > 0) ? ntAdjust(M, st.logits, hist) : st.logits; cand.length = 0; vals.length = 0; for(let b = 0; b < V; b++) if(M.vocab || ntAllowed(rem, b)){ cand.push(b); vals.push(lg[b]); } let pick; if(!(o.temperature > 0)){ pick = 0; for(let i = 1; i < cand.length; i++) if(vals[i] > vals[pick]) pick = i; }else{ let thr = -Infinity; if(o.topK > 0 && o.topK < vals.length) thr = vals.slice().sort((a, b) => b - a)[o.topK - 1]; let mx = -Infinity; for(let i = 0; i < vals.length; i++) if(vals[i] >= thr && vals[i] > mx) mx = vals[i]; let sum = 0; const pr = new Float64Array(vals.length); for(let i = 0; i < vals.length; i++) if(vals[i] >= thr){ pr[i] = Math.exp((vals[i] - mx) / o.temperature); sum += pr[i]; } let r = Math.random() * sum; pick = vals.length - 1; for(let i = 0; i < vals.length; i++){ r -= pr[i]; if(pr[i] > 0 && r <= 0){ pick = i; break; } } } const b = cand[pick]; if(b === eod && o.stopAtEod) break; rem = ntAdvance(rem, b); hist.push(b); if(M.vocab){ const piece = M.vocab.decode(b); if(piece) onToken(piece); } else if(b !== 0) onToken(dec.decode(new Uint8Array([b]), {stream:true})); // byte 0 is the pad/EOD id: never shown if(n === maxNew - 1) break; (M.step || ntStep)(M, st, b, bytes.length + n, true); await new Promise(r => setTimeout(r, 0)); // let the page paint each token } } /* GPT-style decoder (nanoGPT layout): tok_emb + pos_emb, blocks of ln1 > attn(qkv, proj) > ln2 > mlp(fc1, act, fc2), ln_f, head. Byte-level only. */ const GPT = { pos:["pos_emb.weight","wpe.weight","position_embeddings.weight","pos_embed.weight","position_embedding.weight"], ln1:["ln1.weight","ln_1.weight","norm1.weight","input_layernorm.weight"], qkv:["attn.qkv.weight","attn.c_attn.weight","attention.qkv.weight","attn.qkv_proj.weight"], proj:["attn.proj.weight","attn.c_proj.weight","attn.out_proj.weight","attention.proj.weight"], ln2:["ln2.weight","ln_2.weight","norm2.weight","post_attention_layernorm.weight"], fc1:["mlp.fc1.weight","mlp.c_fc.weight","mlp.dense_h_to_4h.weight"], fc2:["mlp.fc2.weight","mlp.c_proj.weight","mlp.dense_4h_to_h.weight"], lnf:["ln_f.weight","final_norm.weight","norm.weight","final_layernorm.weight"], head:["head.weight","lm_head.weight","output.weight"] }; function gptActName(cfg){ const a = String(cfg.activation_function || cfg.activation || cfg.hidden_act || cfg.act || cfg.__act || "").toLowerCase(); return /silu|swish/.test(a) ? "silu" : /relu/.test(a) ? "relu" : /tanh|new|fast/.test(a) ? "gelu_tanh" : "gelu"; // no evidence at all -> exact GELU } function gptErf(x){ const sg = x < 0 ? -1 : 1; x = Math.abs(x); const t = 1 / (1 + 0.3275911 * x); return sg * (1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x)); } const GPT_ACT = { gelu:v => 0.5 * v * (1 + gptErf(v * Math.SQRT1_2)), gelu_tanh:v => 0.5 * v * (1 + Math.tanh(0.7978845608 * (v + 0.044715 * v * v * v))), relu:v => v > 0 ? v : 0, silu:v => v / (1 + Math.exp(-v)) }; function gptPlan(cfg, bag, unused){ const used = new Set(), sh = k => bag.get(k).shape, num = k => sh(k).reduce((a, b) => a * b, 1); const pick = (...ks) => { for(const k of ks) if(Number.isFinite(+cfg[k]) && +cfg[k] > 0) return +cfg[k]; }; const blk = (i, subs) => ["blocks.", "layers.", "h.", "block."].flatMap(p => subs.map(x => p + i + "." + x)); const bias = c => { const k = c.map(n => bag.find(n.replace(/\.weight$/, ".bias"))).find(x => x != null); if(k != null) used.add(k); return k; }; const first = (c, what) => { for(const n of c){ const k = bag.find(n); if(k != null){ used.add(k); return k; } } throw ntFail("Missing tensor " + c[0] + " (" + what + "). " + tensorSummary([...bag.keys()])); }; const tk = first(NT.emb, "token embedding"); if(sh(tk).length !== 2) throw ntFail("Token embedding is not a 2-D matrix."); const [V, D] = sh(tk), cv = pick("vocab_size"); if(cv && cv !== V) throw ntFail("config vocab_size " + cv + " but the embedding has " + V + " rows."); let vocab = null; if(V !== 256){ const vs = cfg.__vocabs || []; vocab = vs.find(v => v.itos.length === V); if(!vocab) throw ntFail("Character-level vocabulary of " + V + " tokens, but " + (vs.length ? "the vocabulary files found have " + vs.map(v => v.src + ": " + v.itos.length).join(", ") + " entries." : "no vocabulary was found (looked in config.json and vocab.json / chars.json / stoi.json / tokenizer.json). Add a vocab.json with the character list.")); } const pk = first(GPT.pos, "learned position embedding"); if(sh(pk).length !== 2 || sh(pk)[1] !== D) throw ntFail("Position embedding shape " + sh(pk) + " doesn't match d_model " + D + "."); const T = sh(pk)[0]; let L = pick("n_layer", "num_hidden_layers", "n_layers", "num_layers"); if(!L){ L = 0; while(blk(L, GPT.ln1).some(n => bag.find(n) != null)) L++; } if(!(L > 0)) throw ntFail("No transformer blocks with a known naming (blocks.N / layers.N / h.N); " + tensorSummary([...bag.keys()])); let H = pick("n_head", "num_attention_heads", "n_heads", "num_heads"); if(!H && cfg.__defaults) H = +cfg.__defaults.n_head || +cfg.__defaults.num_attention_heads || undefined; if(!H) throw ntFail("config.json has no head count (n_head / num_attention_heads); learned-position models carry no tensor that reveals it."); if(D % H) throw ntFail("d_model " + D + " is not divisible by n_head " + H + "."); const sq = sh(first(blk(0, GPT.qkv), "block 0 qkv")), tr = sq[0] === D && sq[1] === 3 * D; if(!tr && !(sq[0] === 3 * D && sq[1] === D)) throw ntFail("qkv shape " + sq + " doesn't fit d_model " + D + "."); const f1 = sh(first(blk(0, GPT.fc1), "block 0 fc1")), F = pick("d_ff", "intermediate_size", "ffn_dim", "n_inner") || (f1[0] === D ? f1[1] : f1[0]); const ln = (c, what) => { const w = first(c, what); if(num(w) !== D) throw ntFail("Tensor " + w + " has " + num(w) + " values, expected " + D + "."); return {w, b:bias(c)}; }; const lin = (c, what, out, inn) => { const w = first(c, what), s = sh(w), want = tr ? [inn, out] : [out, inn]; if(s.length !== 2 || s[0] !== want[0] || s[1] !== want[1]) throw ntFail("Tensor " + w + " has shape [" + s + "], expected [" + want + "] (" + what + ")."); return {w, t:tr, b:bias(c)}; }; const blocks = []; for(let i = 0; i < L; i++) blocks.push({ln1:ln(blk(i, GPT.ln1), "block " + i + " ln1"), qkv:lin(blk(i, GPT.qkv), "block " + i + " qkv", 3 * D, D), proj:lin(blk(i, GPT.proj), "block " + i + " attention proj", D, D), ln2:ln(blk(i, GPT.ln2), "block " + i + " ln2"), fc1:lin(blk(i, GPT.fc1), "block " + i + " fc1", F, D), fc2:lin(blk(i, GPT.fc2), "block " + i + " fc2", D, F)}); const lnf = ln(GPT.lnf, "final layer norm"), hk = GPT.head.map(n => bag.find(n)).find(k => k != null); if(hk != null){ if(num(hk) !== V * D) throw ntFail("Output head has " + num(hk) + " values, expected " + V * D + "."); used.add(hk); } const hb = hk != null ? bias(GPT.head) : undefined; const extra = [...bag.keys()].filter(k => !used.has(k) && !/(inv_freq|position_ids|masked_bias|attn\.bias|rotary|rope_cos|rope_sin|cos_cached|sin_cached|aux_norms|multi_step_norm)/i.test(k) && !(unused || []).includes(canon(k).split(".")[0])); if(extra.length) throw ntFail("Unsupported extra tensors (" + extra.slice(0, 4).join(", ") + (extra.length > 4 ? ", ..." : "") + "): different architecture variant than the built-in GPT engine."); return {D, H, L, F, V, T, tk, pk, blocks, lnf, head:hk, hb, vocab, act:gptActName(cfg), eps:+(cfg.layer_norm_epsilon || cfg.layer_norm_eps || 1e-5)}; } function gptBuild(cfg, tensors, unused){ const bag = tensors instanceof TensorBag ? tensors : new TensorBag(tensors), P = gptPlan(cfg, bag, unused), {D, F} = P; const f = k => toFloat32(bag.get(k)), g = k => k == null ? null : f(k); const mat = (o, out, inn) => { const w = f(o.w); if(!o.t) return w; const r = new Float32Array(w.length); for(let i = 0; i < inn; i++) for(let j = 0; j < out; j++) r[j * inn + i] = w[i * out + j]; return r; }; const ln = o => [f(o.w), g(o.b)]; const blocks = P.blocks.map(b => { const [l1w, l1b] = ln(b.ln1), [l2w, l2b] = ln(b.ln2); return {l1w, l1b, l2w, l2b, qkv:mat(b.qkv, 3 * D, D), qkvb:g(b.qkv.b), proj:mat(b.proj, D, D), projb:g(b.proj.b), fc1:mat(b.fc1, F, D), fc1b:g(b.fc1.b), fc2:mat(b.fc2, D, F), fc2b:g(b.fc2.b)}; }); const tok = f(P.tk), [lfw, lfb] = ln(P.lnf); if(cfg.__act === undefined && !(cfg.activation_function || cfg.activation || cfg.hidden_act || cfg.act)) console.warn("[GPT engine] no activation named in config or modeling file; assuming exact GELU."); return {D, H:P.H, L:P.L, F, V:P.V, hd:D / P.H, tok, pos:f(P.pk), head:P.head != null ? f(P.head) : tok, hb:g(P.hb), lfw, lfb, blocks, ropeLen:P.T, theta:10000, eps:P.eps, actf:GPT_ACT[P.act], step:gptStep, vocab:P.vocab ? mkVocab(P.vocab.itos, cfg) : null, rep:+(cfg.__gen || {}).repetition_penalty || 1, nrng:+(cfg.__gen || {}).no_repeat_ngram || 0}; } function gptLn(x, w, b, y, n, eps){ let mu = 0; for(let i = 0; i < n; i++) mu += x[i]; mu /= n; let v = 0; for(let i = 0; i < n; i++){ const d = x[i] - mu; v += d * d; } const r = 1 / Math.sqrt(v / n + eps); for(let i = 0; i < n; i++) y[i] = (x[i] - mu) * r * w[i] + (b ? b[i] : 0); } function gptStep(M, st, tok, pos, wantLogits){ const {D, H, L, F, V, hd} = M, scale = 1 / Math.sqrt(hd), {x, xn, qkv, att, tmp, g, scores} = st; for(let i = 0; i < D; i++) x[i] = M.tok[tok * D + i] + M.pos[pos * D + i]; for(let l = 0; l < L; l++){ const B = M.blocks[l], K = st.kc[l], Vc = st.vc[l]; gptLn(x, B.l1w, B.l1b, xn, D, M.eps); ntMatVec(B.qkv, xn, qkv, 3 * D, D); if(B.qkvb) for(let i = 0; i < 3 * D; i++) qkv[i] += B.qkvb[i]; K.set(qkv.subarray(D, 2 * D), pos * D); Vc.set(qkv.subarray(2 * D, 3 * D), pos * D); for(let h = 0; h < H; h++){ const o = h * hd; let mx = -Infinity; for(let t = 0; t <= pos; t++){ let s = 0; const kb = t * D + o; for(let i = 0; i < hd; i++) s += qkv[o + i] * K[kb + i]; s *= scale; scores[t] = s; if(s > mx) mx = s; } let sum = 0; for(let t = 0; t <= pos; t++){ const e = Math.exp(scores[t] - mx); scores[t] = e; sum += e; } for(let i = 0; i < hd; i++) att[o + i] = 0; for(let t = 0; t <= pos; t++){ const w = scores[t] / sum, vb = t * D + o; for(let i = 0; i < hd; i++) att[o + i] += w * Vc[vb + i]; } } ntMatVec(B.proj, att, tmp, D, D); for(let i = 0; i < D; i++) x[i] += tmp[i] + (B.projb ? B.projb[i] : 0); gptLn(x, B.l2w, B.l2b, xn, D, M.eps); ntMatVec(B.fc1, xn, g, F, D); for(let i = 0; i < F; i++) g[i] = M.actf(g[i] + (B.fc1b ? B.fc1b[i] : 0)); ntMatVec(B.fc2, g, tmp, D, F); for(let i = 0; i < D; i++) x[i] += tmp[i] + (B.fc2b ? B.fc2b[i] : 0); } if(wantLogits){ gptLn(x, M.lfw, M.lfb, xn, D, M.eps); ntMatVec(M.head, xn, st.logits, V, D); if(M.hb) for(let i = 0; i < V; i++) st.logits[i] += M.hb[i]; } } /* ---- character-level vocabulary: accepts list / charset string / token->id / id->token / {stoi|itos|chars|vocab|model:{vocab}} ---- */ function parseVocab(j, depth){ depth = depth || 0; if(j == null || depth > 3) return null; if(typeof j === "string") return Array.from(j); if(Array.isArray(j)) return j.every(x => typeof x === "string") ? j.slice() : null; if(typeof j !== "object") return null; const isI = k => /itos|id_to/i.test(k), ks = Object.keys(j).filter(k => /itos|id_to|chars|characters|stoi|to_id|vocab|^model$/i.test(k)).sort((a, b) => isI(b) - isI(a)); for(const k of ks){ const r = parseVocab(j[k], depth + 1); if(r) return r; } const ents = Object.entries(j), fill = a => { const b = Array.from(a); return b.length && b.every(x => x !== undefined) ? b : null; }; if(!ents.length) return null; if(ents.every(([k, v]) => Number.isInteger(v))){ const a = []; for(const [k, v] of ents) a[v] = k; return fill(a); } if(ents.every(([k, v]) => /^\d+$/.test(k) && typeof v === "string")){ const a = []; for(const [k, v] of ents) a[+k] = v; return fill(a); } return null; } function mkVocab(itos, cfg){ cfg = cfg || {}; const ci = k => Number.isInteger(cfg[k]) ? cfg[k] : -1, nm = re => itos.findIndex(t => re.test(t)); const bos = ci("bos_token_id") >= 0 ? ci("bos_token_id") : nm(/^(<bos>|<s>|\[bos\])$/i); const eos = ci("eos_token_id") >= 0 ? ci("eos_token_id") : nm(/^(<eos>|<\|endoftext\|>|<\/s>|\[eos\])$/i); const unk = nm(/^(<unk>|\[unk\])$/i), sp = new Set([bos, eos, unk, ci("pad_token_id")]); const isSp = i => sp.has(i) || /^<.*>$/.test(itos[i] || ""), stoi = new Map(); let maxLen = 1; itos.forEach((t, i) => { if(t && !isSp(i) && !stoi.has(t)){ stoi.set(t, i); maxLen = Math.max(maxLen, Array.from(t).length); } }); const one = c => { const v = stoi.get(c); if(v !== undefined) return v; if(unk >= 0) return unk; // like the model's own c_stoi.get(ch, <unk>) return stoi.has(c.toLowerCase()) ? stoi.get(c.toLowerCase()) : stoi.get(c.toUpperCase()); // no <unk>: lowercase-only vocabularies still accept capitals, else skip }; return { bos:bos >= 0 ? bos : null, eos:eos >= 0 ? eos : null, start:stoi.has("\n") ? stoi.get("\n") : 0, encode(text){ const ch = Array.from(text), out = []; for(let i = 0; i < ch.length;){ let n = 0; for(let l = Math.min(maxLen, ch.length - i); l > 1; l--){ const id = stoi.get(ch.slice(i, i + l).join("")); if(id !== undefined){ out.push(id); n = l; break; } } if(!n){ const id = one(ch[i]); if(id !== undefined) out.push(id); n = 1; } i += n; } return out; }, decode(id){ return itos[id] == null || isSp(id) ? "" : itos[id]; } }; } /* ---- NoTokenLM Gen-5.5: byte-level hierarchical hybrid ---- bytes -> (byte emb + hashed n-gram emb + ROSA) -> local encoder (conv, conv, windowed attn) -> entropy patches -> attention pooling -> trunk over patches (RWKV-7 / gated NoPE attention) -> local decoder (windowed attn) -> 256-way next-byte logits. Port of modeling_notoken_gen55.py. Everything is evaluated incrementally, one byte at a time; the trunk runs once per closed patch. */ const G55_DEF = { d:768, n_block:5, pattern:["R","A","R","R"], ffn:1792, head_dim:64, lora_decay:64, lora_a:64, lora_v:64, lora_g:128, attn_gate:true, qk_norm:true, ln_scale:true, d_loc:256, enc_blocks:["conv","conv","attn"], n_dec:4, loc_heads:4, loc_window:32, conv_k:4, loc_ffn:704, pool_heads:8, dec_cross:false, hash_orders:[3,4,5,6,7,8], hash_rows:[103424,103424,103424,103424,103424,103424], hash_dim:32, seq_len:4096, patch_max_len:16, ent_d:256, ent_layers:8, ent_ffn:704, ent_k:4, vocab:257, rosa:true, deepembed:"byte", theta:null }; function g55Cfg(cfg){ const c = Object.assign({}, G55_DEF, cfg || {}); c.pattern = Array.from(c.pattern); c.enc_blocks = Array.from(c.enc_blocks); c.hash_orders = Array.from(c.hash_orders); c.hash_rows = Array.from(c.hash_rows); c.n_hash = c.hash_orders.length; c.de_byte = c.deepembed === "byte"; c.rosa = !!c.rosa; return c; } // tensor name -> number of values, for the whole checkpoint function g55Spec(c){ const S = new Map(), dl = c.d_loc, d = c.d, ff = c.loc_ffn, nb = c.n_block, hd = c.head_dim, H = d / hd, add = (n, len) => S.set(n, len); add("emb_in", c.vocab * dl); const loc = (p, kind) => { add(p + ".n1", dl); add(p + ".n2", dl); add(p + ".ffn.w1", dl * ff); add(p + ".ffn.w3", dl * ff); add(p + ".ffn.w2", ff * dl); if(kind === "attn") for(const w of ["wq", "wk", "wv", "wo"]) add(p + "." + w, dl * dl); else add(p + ".conv", c.conv_k * dl); if(c.de_byte) add(p + ".de", c.vocab * ff); }; c.enc_blocks.forEach((k, i) => { if(k !== "conv" && k !== "attn") throw ntFail("Unknown encoder block type " + k); loc("enc." + i, k); }); add("enc_nf", dl); add("pool.ws", dl * c.pool_heads); add("pool.wv", dl * dl); add("pool.wo", dl * dl); add("pool.up", dl * d); add("pool.len_emb", 16 * d); add("pool.pool_nf", d); c.pattern.forEach((k, j) => { const p = "trunk.l" + j; add(p + ".n1", nb * d); add(p + ".n2", nb * d); add(p + ".ffn.w1", nb * d * c.ffn); add(p + ".ffn.w3", nb * d * c.ffn); add(p + ".ffn.w2", nb * c.ffn * d); if(k === "A"){ for(const w of ["wq", "wk", "wv", "wo"]) add(p + ".mix." + w, nb * d * d); if(c.qk_norm){ add(p + ".mix.qn", nb * hd); add(p + ".mix.kn", nb * hd); } if(c.attn_gate){ add(p + ".mix.gate_w", nb * d * H); add(p + ".mix.gate_b", nb * H); } }else if(k === "R"){ for(const w of ["x_r", "x_w", "x_k", "x_v", "x_a", "x_g", "w0", "a0", "k_k", "k_a", "v0", "ln_w", "ln_b"]) add(p + ".mix." + w, nb * d); add(p + ".mix.w1", nb * d * c.lora_decay); add(p + ".mix.w2", nb * c.lora_decay * d); add(p + ".mix.a1", nb * d * c.lora_a); add(p + ".mix.a2", nb * c.lora_a * d); add(p + ".mix.g1", nb * d * c.lora_g); add(p + ".mix.g2", nb * c.lora_g * d); add(p + ".mix.v1", nb * d * c.lora_v); add(p + ".mix.v2", nb * c.lora_v * d); add(p + ".mix.r_k", nb * H * hd); for(const w of ["Wr", "Wk", "Wv", "Wo"]) add(p + ".mix." + w, nb * d * d); }else throw ntFail("Unknown trunk layer type " + k); }); add("nf", d); add("down", d * dl); add("down_nf", dl); add("bos", dl); for(let i = 0; i < c.n_dec; i++) loc("dec." + i, "attn"); add("dec_nf", dl); add("head", dl * 256); if(c.rosa){ add("rosa.pe", 257 * dl); add("rosa.lg", 16 * dl); add("rosa.lb", 16 * dl); add("rosa.boost", 16); } if(c.n_hash){ add("hash_table", c.hash_rows.reduce((a, b) => a + b, 0) * c.hash_dim); add("hash_nw", c.n_hash * c.hash_dim); add("hash_proj", c.n_hash * c.hash_dim * dl); } add("patcher.emb", 256 * c.ent_d); add("patcher.nf", c.ent_d); add("patcher.head", c.ent_d * 256); for(let i = 0; i < c.ent_layers; i++){ const p = "patcher.layers." + i; add(p + ".n1", c.ent_d); add(p + ".n2", c.ent_d); add(p + ".conv", c.ent_k * c.ent_d); add(p + ".ffn.w1", c.ent_d * c.ent_ffn); add(p + ".ffn.w3", c.ent_d * c.ent_ffn); add(p + ".ffn.w2", c.ent_ffn * c.ent_d); } return S; } // Validates config + tensor names/sizes WITHOUT weight data (shapes only), so it also runs on a safetensors header. function g55Plan(cfg0, bag){ const c = g55Cfg(cfg0); if(c.dec_cross) throw ntFail("Decoder cross-attention variants aren't supported by the built-in Gen-5.5 engine."); if(c.deepembed !== "off" && c.deepembed !== "byte") throw ntFail("deepembed '" + c.deepembed + "' isn't supported by the built-in Gen-5.5 engine."); if(!(Number(c.theta) > 0)) throw ntFail("config.json has no calibrated patch threshold (theta)."); if(c.d % c.head_dim || c.d_loc % c.loc_heads || (c.d_loc / c.loc_heads) % 2 || c.d_loc % c.pool_heads) throw ntFail("Invalid Gen-5.5 config: head sizes don't divide the model widths."); if(c.hash_rows.length !== c.n_hash) throw ntFail("Invalid Gen-5.5 config: hash_rows and hash_orders differ in length."); const spec = g55Spec(c), used = new Set(); for(const [name, len] of spec){ const k = bag.find(name); if(k == null) throw ntFail("Missing tensor " + name + ". " + tensorSummary([...bag.keys()])); const n = bag.get(k).shape.reduce((a, b) => a * b, 1); if(n !== len) throw ntFail("Tensor " + k + " has " + n + " values, expected " + len + ". config.json and the weights don't match."); used.add(k); } const extra = [...bag.keys()].filter(k => !used.has(k)); 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 Gen-5.5 engine."); return {c, spec}; } /* ---- numeric helpers (row-major [in, out] weights: y = x @ W) ---- */ function g55Rms(x, xo, w, n, y, yo, mul){ let s = 0; for(let i = 0; i < n; i++){ const v = x[xo + i]; s += v * v; } const r = mul === undefined ? 1 / Math.sqrt(s / n + 1e-6) : mul / Math.sqrt(s / n + 1e-6); for(let i = 0; i < n; i++) y[yo + i] = x[xo + i] * r * w[i]; } function g55Vm(x, xo, W, wo, nIn, nOut, y, yo, acc){ if(!acc) for(let j = 0; j < nOut; j++) y[yo + j] = 0; let i = 0; for(; i + 3 < nIn; i += 4){ // four input rows per pass: a quarter of the loads/stores on y const x0 = x[xo + i], x1 = x[xo + i + 1], x2 = x[xo + i + 2], x3 = x[xo + i + 3]; const o0 = wo + i * nOut, o1 = o0 + nOut, o2 = o1 + nOut, o3 = o2 + nOut; for(let j = 0; j < nOut; j++) y[yo + j] += x0 * W[o0 + j] + x1 * W[o1 + j] + x2 * W[o2 + j] + x3 * W[o3 + j]; } for(; i < nIn; i++){ const xi = x[xo + i], o = wo + i * nOut; for(let j = 0; j < nOut; j++) y[yo + j] += xi * W[o + j]; } } const g55Sig = x => 1 / (1 + Math.exp(-x)); const g55Silu = x => x / (1 + Math.exp(-x)); function g55Build(cfg0, tensors){ const bag = tensors instanceof TensorBag ? tensors : new TensorBag(tensors), P = g55Plan(cfg0, bag), c = P.c, W = Object.create(null); for(const k of P.spec.keys()) W[k] = toFloat32(bag.get(k)); const dl = c.d_loc, d = c.d, nb = c.n_block, hd = c.head_dim, H = d / hd, np = c.pattern.length, sl = (a, i, n) => a.subarray(i * n, (i + 1) * n); const M = {c, W, dl, d, nb, hd, H, np, dh:dl / c.loc_heads, dhp:dl / c.pool_heads}; M.trunk = []; for(let b = 0; b < nb; b++){ const row = []; for(let j = 0; j < np; j++){ const p = "trunk.l" + j, kind = c.pattern[j], mx = p + ".mix."; const L = {kind, n1:sl(W[p + ".n1"], b, d), n2:sl(W[p + ".n2"], b, d), fw1:sl(W[p + ".ffn.w1"], b, d * c.ffn), fw3:sl(W[p + ".ffn.w3"], b, d * c.ffn), fw2:sl(W[p + ".ffn.w2"], b, c.ffn * d), s:c.ln_scale ? 1 / Math.sqrt(b * np + j + 1) : 1}; if(kind === "A"){ for(const w of ["wq", "wk", "wv", "wo"]) L[w] = sl(W[mx + w], b, d * d); if(c.qk_norm){ L.qn = sl(W[mx + "qn"], b, hd); L.kn = sl(W[mx + "kn"], b, hd); } if(c.attn_gate){ L.gw = sl(W[mx + "gate_w"], b, d * H); L.gb = sl(W[mx + "gate_b"], b, H); } }else{ for(const w of ["x_r", "x_w", "x_k", "x_v", "x_a", "x_g", "w0", "a0", "k_k", "k_a", "v0", "ln_w", "ln_b"]) L[w] = sl(W[mx + w], b, d); L.w1 = sl(W[mx + "w1"], b, d * c.lora_decay); L.w2 = sl(W[mx + "w2"], b, c.lora_decay * d); L.a1 = sl(W[mx + "a1"], b, d * c.lora_a); L.a2 = sl(W[mx + "a2"], b, c.lora_a * d); L.g1 = sl(W[mx + "g1"], b, d * c.lora_g); L.g2 = sl(W[mx + "g2"], b, c.lora_g * d); L.v1 = sl(W[mx + "v1"], b, d * c.lora_v); L.v2 = sl(W[mx + "v2"], b, c.lora_v * d); L.r_k = sl(W[mx + "r_k"], b, H * hd); for(const w of ["Wr", "Wk", "Wv", "Wo"]) L[w] = sl(W[mx + w], b, d * d); } row.push(L); } M.trunk.push(row); } // output head with the per-row mean removed (logits = rms(u) @ (head - head.mean(1))) const hs = W["head"], hc = new Float32Array(dl * 256); for(let i = 0; i < dl; i++){ let m = 0; for(let o = 0; o < 256; o++) m += hs[i * 256 + o]; m /= 256; for(let o = 0; o < 256; o++) hc[i * 256 + o] = hs[i * 256 + o] - m; } M.headc = hc; const mx = Math.max(dl, c.loc_ffn, c.ent_d, c.ent_ffn, d, c.ffn, c.lora_g, c.lora_decay, 64); M.sc = { // scratch buffers, reused for every call a:new Float32Array(mx), b:new Float32Array(mx), g:new Float32Array(mx), u:new Float32Array(mx), q:new Float32Array(dl), k:new Float32Array(dl), v:new Float32Array(dl), y:new Float32Array(dl), t:new Float32Array(dl), lg:new Float32Array(256), sc:new Float32Array(Math.max(c.loc_window, 16, 8) + 2), x:new Float32Array(d), h:new Float32Array(d), h2:new Float32Array(d), vf:new Float32Array(d), ya:new Float32Array(d), o:new Float32Array(d), f1:new Float32Array(c.ffn), f3:new Float32Array(c.ffn), xr:new Float32Array(d), xw:new Float32Array(d), xk:new Float32Array(d), xv:new Float32Array(d), xa:new Float32Array(d), xg:new Float32Array(d), r:new Float32Array(d), kk:new Float32Array(d), vv:new Float32Array(d), kx:new Float32Array(d), aa:new Float32Array(d), lw:new Float32Array(d), gg:new Float32Array(d), low:new Float32Array(Math.max(c.lora_decay, c.lora_a, c.lora_v, c.lora_g)), pq:new Float32Array(d), pk:new Float32Array(d), pv:new Float32Array(d), gt:new Float32Array(H + 1), pool:new Float32Array(dl), pool2:new Float32Array(dl), enc:new Float32Array(dl), ent:new Float32Array(c.n_hash * c.hash_dim), hrow:new Float32Array(dl), gl:new Float32Array(dl), sct:new Float32Array(4097) }; return M; } /* ---- ROSA: online suffix automaton, same bookkeeping as rosa_features() ---- */ const G55_EDGES = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 128, 256]; function g55Bucket(m){ if(m <= 0) return 0; for(let i = 0; i < G55_EDGES.length; i++) if(m <= G55_EDGES[i]) return i + 1; return 15; } function g55RosaReset(R){ R.nxt = [new Map()]; R.link = [-1]; R.ln = [0]; R.pos = [-1]; R.last = 0; } function g55RosaStep(R, xs, i){ const c = xs[i]; R.p1 = 0; R.bk = 0; if(c === 0){ g55RosaReset(R); return; } const {nxt, link, ln, pos} = R, cur = nxt.length; nxt.push(new Map()); link.push(0); ln.push(ln[R.last] + 1); pos.push(i); let p = R.last; while(p !== -1 && !nxt[p].has(c)){ nxt[p].set(c, cur); p = link[p]; } if(p === -1) link[cur] = 0; else{ const q = nxt[p].get(c); if(ln[p] + 1 === ln[q]) link[cur] = q; else{ const cl = nxt.length; nxt.push(new Map(nxt[q])); link.push(link[q]); ln.push(ln[p] + 1); pos.push(pos[q]); while(p !== -1 && nxt[p].get(c) === q){ nxt[p].set(c, cl); p = link[p]; } link[q] = cl; link[cur] = cl; } } R.last = cur; const m = link[cur]; if(m > 0 && pos[m] + 1 <= i){ R.p1 = xs[pos[m] + 1] + 1; R.bk = g55Bucket(Math.min(ln[m], 8192)); pos[m] = i; } } function g55Mix32(h){ h ^= h >>> 16; h = Math.imul(h, 0x7feb352d); h ^= h >>> 15; h = Math.imul(h, 0x846ca68b); h ^= h >>> 16; return h >>> 0; } /* ---- per-run state: every cache needed to advance by one byte ---- */ function g55Grow(a, need, Ctor){ if(a.length >= need) return a; const n = new Ctor(Math.max(need, a.length * 2)); n.set(a); return n; } function g55NewState(M, cap){ const c = M.c, dl = M.dl, d = M.d, S = { n:0, cap, x:new Uint8Array(cap), doc:new Int32Array(cap), logits:new Float32Array(256), pn:Array.from({length:c.ent_layers}, () => new Float32Array(cap * c.ent_d)), // patcher: normalised layer inputs eh:c.enc_blocks.map(k => k === "conv" ? new Float32Array(cap * dl) : null), // encoder conv history ek:c.enc_blocks.map(k => k === "attn" ? new Float32Array(cap * dl) : null), ev:c.enc_blocks.map(k => k === "attn" ? new Float32Array(cap * dl) : null), dk:Array.from({length:c.n_dec}, () => new Float32Array(cap * dl)), dv:Array.from({length:c.n_dec}, () => new Float32Array(cap * dl)), psc:new Float32Array(cap * c.pool_heads), phv:new Float32Array(cap * dl), // pooling scores / values per byte fpos:0, sNext:true, pStart:0, nStarted:0, nClosed:0, pdocs:[], gl:new Float32Array(64 * dl), hPrev:new Uint32Array(Math.max(9, Math.max(...c.hash_orders, 1) + 1)), hCur:new Uint32Array(Math.max(9, Math.max(...c.hash_orders, 1) + 1)), R:{p1:0, bk:0}, lastDoc:-1, cosT:null, sinT:null, tr:{S:[], xp:[], K:[], V:[]} }; g55RosaReset(S.R); const half = M.dh >> 1, hh = M.dh; S.cosT = new Float32Array(cap * half); S.sinT = new Float32Array(cap * half); for(let p = 0; p < cap; p++) for(let i = 0; i < half; i++){ const f = p * Math.pow(10000, -(2 * i) / hh); S.cosT[p * half + i] = Math.cos(f); S.sinT[p * half + i] = Math.sin(f); } for(let b = 0; b < M.nb; b++) for(let j = 0; j < M.np; j++){ if(c.pattern[j] === "R"){ S.tr.S.push(new Float32Array(M.H * M.hd * M.hd)); S.tr.xp.push(new Float32Array(d)); S.tr.K.push(null); S.tr.V.push(null); } else{ S.tr.S.push(null); S.tr.xp.push(null); S.tr.K.push(new Float32Array(64 * d)); S.tr.V.push(new Float32Array(64 * d)); } } return S; } // causal windowed attention of one new position (relative RoPE, window = loc_window, same document only) function g55LocalAttn(M, S, blk, hn, t, Kc, Vc, out){ const {dl, dh, c} = M, sc = M.sc, Hh = c.loc_heads, half = dh >> 1, w = c.loc_window, q = sc.q, k = sc.k, v = sc.v, y = sc.y, cs = S.cosT, sn = S.sinT, doc = S.doc; g55Vm(hn, 0, blk.wq, 0, dl, dl, q, 0); g55Vm(hn, 0, blk.wk, 0, dl, dl, k, 0); g55Vm(hn, 0, blk.wv, 0, dl, dl, v, 0); for(let h = 0; h < Hh; h++){ const o = h * dh, co = t * half; for(let i = 0; i < half; i++){ const cc = cs[co + i], ss = sn[co + i]; const q1 = q[o + i], q2 = q[o + half + i]; q[o + i] = q1 * cc - q2 * ss; q[o + half + i] = q1 * ss + q2 * cc; const k1 = k[o + i], k2 = k[o + half + i]; k[o + i] = k1 * cc - k2 * ss; k[o + half + i] = k1 * ss + k2 * cc; } } Kc.set(k, t * dl); Vc.set(v, t * dl); const lo = Math.max(0, t - w + 1), inv = 1 / Math.sqrt(dh), sct = sc.sct, dt = doc[t]; for(let h = 0; h < Hh; h++){ const o = h * dh; let mx = -Infinity; for(let p = lo; p <= t; p++){ if(doc[p] !== dt){ sct[p - lo] = -Infinity; continue; } let s = 0; const po = p * dl + o; for(let i = 0; i < dh; i++) s += q[o + i] * Kc[po + i]; s *= inv; sct[p - lo] = s; if(s > mx) mx = s; } let sum = 0; for(let p = lo; p <= t; p++){ const e = sct[p - lo] === -Infinity ? 0 : Math.exp(sct[p - lo] - mx); sct[p - lo] = e; sum += e; } for(let i = 0; i < dh; i++) y[o + i] = 0; for(let p = lo; p <= t; p++){ const a = sct[p - lo] / sum; if(a === 0) continue; const po = p * dl + o; for(let i = 0; i < dh; i++) y[o + i] += a * Vc[po + i]; } } g55Vm(y, 0, blk.wo, 0, dl, dl, out, 0); } // one local block (encoder or decoder) for the new position. x (dl) is updated in place. function g55LocalBlock(M, S, p, kind, x, t, byte, hist, Kc, Vc){ const {dl, c} = M, W = M.W, sc = M.sc, ff = c.loc_ffn, h = sc.a, tmp = sc.t; g55Rms(x, 0, W[p + ".n1"], dl, h, 0); if(kind === "attn"){ g55LocalAttn(M, S, {wq:W[p + ".wq"], wk:W[p + ".wk"], wv:W[p + ".wv"], wo:W[p + ".wo"]}, h, t, Kc, Vc, tmp); for(let i = 0; i < dl; i++) x[i] += tmp[i]; }else{ hist.set(h.subarray(0, dl), t * dl); const cw = W[p + ".conv"], K = c.conv_k, doc = S.doc; for(let i = 0; i < dl; i++) x[i] += cw[(K - 1) * dl + i] * h[i]; for(let i = 0; i < K - 1; i++){ const tp = t - (K - 1 - i); if(tp < 0 || doc[tp] !== doc[t]) continue; const o = tp * dl, wo = i * dl; for(let j = 0; j < dl; j++) x[j] += cw[wo + j] * hist[o + j]; } } const h2 = sc.b, g = sc.g, u = sc.u; g55Rms(x, 0, W[p + ".n2"], dl, h2, 0); g55Vm(h2, 0, W[p + ".ffn.w1"], 0, dl, ff, g, 0); g55Vm(h2, 0, W[p + ".ffn.w3"], 0, dl, ff, u, 0); if(c.de_byte){ const de = W[p + ".de"], o = byte * ff; for(let j = 0; j < ff; j++) g[j] = g55Silu(g[j]) * u[j] * (1 + de[o + j]); } else for(let j = 0; j < ff; j++) g[j] = g55Silu(g[j]) * u[j]; g55Vm(g, 0, W[p + ".ffn.w2"], 0, ff, dl, x, 0, true); } // attention pooling of the closed patch [s, s+n) -> sc.o (d) function g55Pool(M, S, s, n){ const {dl, d, c, dhp} = M, W = M.W, sc = M.sc, Hp = c.pool_heads, pool = sc.pool, sct = sc.sct; for(let h = 0; h < Hp; h++){ let mx = -Infinity; for(let k = 0; k < n; k++){ const v = S.psc[(s + k) * Hp + h]; sct[k] = v; if(v > mx) mx = v; } let sum = 0; for(let k = 0; k < n; k++){ sct[k] = Math.exp(sct[k] - mx); sum += sct[k]; } for(let i = 0; i < dhp; i++) pool[h * dhp + i] = 0; for(let k = 0; k < n; k++){ const a = sct[k] / sum, o = (s + k) * dl + h * dhp; for(let i = 0; i < dhp; i++) pool[h * dhp + i] += a * S.phv[o + i]; } } g55Vm(pool, 0, W["pool.wo"], 0, dl, dl, sc.pool2, 0); g55Vm(sc.pool2, 0, W["pool.up"], 0, dl, d, sc.ya, 0); const le = W["pool.len_emb"], lo = (Math.min(Math.max(n, 1), 16) - 1) * d; for(let i = 0; i < d; i++) sc.ya[i] += le[lo + i]; g55Rms(sc.ya, 0, W["pool.pool_nf"], d, sc.pv, 0); } // one patch (sc.pv, document id) through the 20-layer trunk; leaves rms_norm(nf) of the result in sc.o. mutates S.tr. function g55TrunkStep(M, S, docId){ const {c, d, hd, H, nb, np} = M, sc = M.sc, T = S.tr, W = M.W, x = sc.x, h = sc.h, h2 = sc.h2, vf = sc.vf, N = hd, npt = S.nClosed; // npt = index of this patch const newDoc = docId !== S.lastDoc, ffn = c.ffn; x.set(sc.pv); vf.fill(0); for(let b = 0; b < nb; b++) for(let j = 0; j < np; j++){ const L = M.trunk[b][j], idx = b * np + j; g55Rms(x, 0, L.n1, d, h, 0, L.s); const y = sc.ya; if(L.kind === "A"){ const q = sc.pq, k = sc.pk, v = sc.pv2 || (sc.pv2 = new Float32Array(d)); g55Vm(h, 0, L.wq, 0, d, d, q, 0); g55Vm(h, 0, L.wk, 0, d, d, k, 0); g55Vm(h, 0, L.wv, 0, d, d, v, 0); if(c.qk_norm) for(let hh = 0; hh < H; hh++){ g55Rms(q, hh * hd, L.qn, hd, q, hh * hd); g55Rms(k, hh * hd, L.kn, hd, k, hh * hd); } T.K[idx] = g55Grow(T.K[idx], (npt + 1) * d, Float32Array); T.V[idx] = g55Grow(T.V[idx], (npt + 1) * d, Float32Array); const Kc = T.K[idx], Vc = T.V[idx]; Kc.set(k, npt * d); Vc.set(v, npt * d); const inv = 1 / Math.sqrt(hd), sct = sc.sct.length > npt + 1 ? sc.sct : (sc.sct = new Float32Array((npt + 1) * 2)); if(c.attn_gate) g55Vm(h, 0, L.gw, 0, d, H, sc.gt, 0); for(let hh = 0; hh < H; hh++){ const o = hh * hd; let mx = -Infinity; for(let p = 0; p <= npt; p++){ if(S.pdocs[p] !== docId){ sct[p] = -Infinity; continue; } let s = 0; const po = p * d + o; for(let i = 0; i < hd; i++) s += q[o + i] * Kc[po + i]; s *= inv; sct[p] = s; if(s > mx) mx = s; } let sum = 0; for(let p = 0; p <= npt; p++){ const e = sct[p] === -Infinity ? 0 : Math.exp(sct[p] - mx); sct[p] = e; sum += e; } const gate = c.attn_gate ? g55Sig(sc.gt[hh] + L.gb[hh]) : 1; for(let i = 0; i < hd; i++) sc.o[o + i] = 0; for(let p = 0; p <= npt; p++){ const a = sct[p] / sum; if(a === 0) continue; const po = p * d + o; for(let i = 0; i < hd; i++) sc.o[o + i] += a * Vc[po + i]; } for(let i = 0; i < hd; i++) sc.o[o + i] *= gate; } g55Vm(sc.o, 0, L.wo, 0, d, d, y, 0); }else{ const St = T.S[idx], xp = T.xp[idx]; if(newDoc){ St.fill(0); xp.fill(0); } const xr = sc.xr, xw = sc.xw, xk = sc.xk, xv = sc.xv, xa = sc.xa, xg = sc.xg; for(let i = 0; i < d; i++){ const dx = xp[i] - h[i]; xr[i] = h[i] + dx * L.x_r[i]; xw[i] = h[i] + dx * L.x_w[i]; xk[i] = h[i] + dx * L.x_k[i]; xv[i] = h[i] + dx * L.x_v[i]; xa[i] = h[i] + dx * L.x_a[i]; xg[i] = h[i] + dx * L.x_g[i]; } xp.set(h); const r = sc.r, k = sc.kx, v = sc.vv, low = sc.low, lw = sc.lw, aa = sc.aa, gg = sc.gg, kk = sc.kk; g55Vm(xr, 0, L.Wr, 0, d, d, r, 0); g55Vm(xk, 0, L.Wk, 0, d, d, k, 0); g55Vm(xv, 0, L.Wv, 0, d, d, v, 0); const Ld = c.lora_decay; g55Vm(xw, 0, L.w1, 0, d, Ld, low, 0); for(let i = 0; i < Ld; i++) low[i] = Math.tanh(low[i]); g55Vm(low, 0, L.w2, 0, Ld, d, lw, 0); const EH = Math.exp(-0.5); for(let i = 0; i < d; i++) lw[i] = Math.exp(-g55Sig(L.w0[i] + lw[i]) * EH); // lw now holds the per-channel decay exp(log_w) if(b === 0 && j === 0) vf.set(v); else{ const Lv = c.lora_v; g55Vm(xv, 0, L.v1, 0, d, Lv, low, 0); g55Vm(low, 0, L.v2, 0, Lv, d, sc.o, 0); for(let i = 0; i < d; i++) v[i] += (vf[i] - v[i]) * g55Sig(L.v0[i] + sc.o[i]); } const La = c.lora_a; g55Vm(xa, 0, L.a1, 0, d, La, low, 0); g55Vm(low, 0, L.a2, 0, La, d, aa, 0); for(let i = 0; i < d; i++) aa[i] = g55Sig(L.a0[i] + aa[i]); const Lg = c.lora_g; g55Vm(xg, 0, L.g1, 0, d, Lg, low, 0); for(let i = 0; i < Lg; i++) low[i] = g55Sig(low[i]); g55Vm(low, 0, L.g2, 0, Lg, d, gg, 0); for(let hh = 0; hh < H; hh++){ const o = hh * N; let s = 0; for(let i = 0; i < N; i++){ const z = k[o + i] * L.k_k[o + i]; kk[o + i] = z; s += z * z; } const inv = 1 / Math.sqrt(s + 1e-24); for(let i = 0; i < N; i++) kk[o + i] *= inv; } for(let i = 0; i < d; i++) k[i] *= 1 + (aa[i] - 1) * L.k_a[i]; for(let hh = 0; hh < H; hh++){ const o = hh * N, so = hh * N * N; let mu = 0, va = 0; for(let i = 0; i < N; i++){ let skk = 0; const ro = so + i * N; for(let jj = 0; jj < N; jj++) skk += St[ro + jj] * kk[o + jj]; const vi = v[o + i]; let yy = 0; for(let jj = 0; jj < N; jj++){ const sv = St[ro + jj] * lw[o + jj] - skk * (kk[o + jj] * aa[o + jj]) + vi * k[o + jj]; St[ro + jj] = sv; yy += sv * r[o + jj]; } y[o + i] = yy; mu += yy; } mu /= N; for(let i = 0; i < N; i++){ const z = y[o + i] - mu; va += z * z; } va /= N; const rs = 1 / Math.sqrt(va + 64e-5); let bonus = 0; for(let i = 0; i < N; i++) bonus += r[o + i] * k[o + i] * L.r_k[o + i]; for(let i = 0; i < N; i++) y[o + i] = ((y[o + i] - mu) * rs * L.ln_w[o + i] + L.ln_b[o + i] + bonus * v[o + i]) * gg[o + i]; } g55Vm(y, 0, L.Wo, 0, d, d, sc.o, 0); y.set(sc.o.subarray(0, d)); } for(let i = 0; i < d; i++) x[i] += y[i]; g55Rms(x, 0, L.n2, d, h2, 0, L.s); g55Vm(h2, 0, L.fw1, 0, d, ffn, sc.f1, 0); g55Vm(h2, 0, L.fw3, 0, d, ffn, sc.f3, 0); for(let i = 0; i < ffn; i++) sc.f1[i] = g55Silu(sc.f1[i]) * sc.f3[i]; g55Vm(sc.f1, 0, L.fw2, 0, ffn, d, x, 0, true); } S.lastDoc = docId; g55Rms(x, 0, W["nf"], d, sc.o, 0); } /* ---- advance by one byte. Fills S.logits (next-byte logits) when wantLogits. ---- */ function g55Step(M, S, b, wantLogits){ const {c, W, dl, d} = M, sc = M.sc, t = S.n, ed = c.ent_d, Hn = c.n_hash; if(t >= S.cap) throw new Error("Gen-5.5 state is full."); S.x[t] = b; S.doc[t] = t === 0 ? 0 : S.doc[t - 1] + (S.x[t - 1] === 0 ? 1 : 0); const dc = S.doc[t]; // patch start of this byte (decided by the previous step) if(S.sNext){ S.pStart = t; S.nStarted++; S.pdocs.push(dc); } // --- entropy patcher (frozen causal TCN) let h = sc.g; const pe = W["patcher.emb"]; for(let i = 0; i < ed; i++) h[i] = pe[b * ed + i]; const hb = sc.a, tmp = sc.b; for(let l = 0; l < c.ent_layers; l++){ const p = "patcher.layers." + l, cw = W[p + ".conv"], K = c.ent_k, dil = 1 << l, pn = S.pn[l]; g55Rms(h, 0, W[p + ".n1"], ed, hb, 0); pn.set(hb.subarray(0, ed), t * ed); for(let i = 0; i < ed; i++) h[i] += cw[(K - 1) * ed + i] * hb[i]; for(let i = 0; i < K - 1; i++){ const tp = t - (K - 1 - i) * dil; if(tp < 0 || S.doc[tp] !== dc) continue; const o = tp * ed, wo = i * ed; for(let j = 0; j < ed; j++) h[j] += cw[wo + j] * pn[o + j]; } g55Rms(h, 0, W[p + ".n2"], ed, hb, 0); const ef = c.ent_ffn; g55Vm(hb, 0, W[p + ".ffn.w1"], 0, ed, ef, sc.f1, 0); g55Vm(hb, 0, W[p + ".ffn.w3"], 0, ed, ef, sc.f3, 0); for(let j = 0; j < ef; j++) sc.f1[j] = g55Silu(sc.f1[j]) * sc.f3[j]; g55Vm(sc.f1, 0, W[p + ".ffn.w2"], 0, ef, ed, h, 0, true); } g55Rms(h, 0, W["patcher.nf"], ed, hb, 0); g55Vm(hb, 0, W["patcher.head"], 0, ed, 256, sc.lg, 0); let mxl = -Infinity; for(let i = 0; i < 256; i++) if(sc.lg[i] > mxl) mxl = sc.lg[i]; let se = 0; for(let i = 0; i < 256; i++) se += Math.exp(sc.lg[i] - mxl); const lse = mxl + Math.log(se); let ent = 0; for(let i = 0; i < 256; i++){ const lp = sc.lg[i] - lse; ent -= Math.exp(lp) * lp; } // does the NEXT byte start a patch? (only depends on bytes seen so far) const force = b === 0 || ent > Number(c.theta); if(t === 0) S.fpos = 0; if(force) S.fpos = t + 1; const sNext = force || (((t + 1) - S.fpos) % c.patch_max_len === 0); // --- byte embedding: emb_in + ROSA + hashed n-grams const x = sc.enc, ei = W["emb_in"]; for(let i = 0; i < dl; i++) x[i] = ei[b * dl + i]; let p1 = 0, bk = 0; if(c.rosa){ g55RosaStep(S.R, S.x, t); p1 = S.R.p1; bk = S.R.bk; const rpe = W["rosa.pe"], rlg = W["rosa.lg"], rlb = W["rosa.lb"]; for(let i = 0; i < dl; i++) x[i] += rpe[p1 * dl + i] * rlg[bk * dl + i] + rlb[bk * dl + i]; } if(Hn){ const hc = S.hCur, hp = S.hPrev, u = (b + 1) >>> 0, hd2 = c.hash_dim, tab = W["hash_table"], ent2 = sc.ent, maxN = Math.max(...c.hash_orders); hc[1] = u; for(let n = 2; n <= maxN; n++) hc[n] = (Math.imul(hp[n - 1], 0x9E3779B1) + u) >>> 0; let off = 0; for(let oi = 0; oi < Hn; oi++){ const n = c.hash_orders[oi], nr = c.hash_rows[oi], valid = t >= n - 1 && S.doc[t - (n - 1)] === dc; const row = off + (g55Mix32((hc[n] ^ (Math.imul(n, 0x85EBCA6B) >>> 0)) >>> 0) % nr); for(let i = 0; i < hd2; i++) ent2[oi * hd2 + i] = valid ? tab[row * hd2 + i] : 0; off += nr; } for(let n = 1; n <= maxN; n++) hp[n] = hc[n]; const nh = Hn * hd2; g55Rms(ent2, 0, W["hash_nw"], nh, sc.pk, 0); g55Vm(sc.pk, 0, W["hash_proj"], 0, nh, dl, x, 0, true); } // --- local encoder c.enc_blocks.forEach((kind, i) => g55LocalBlock(M, S, "enc." + i, kind, x, t, b, S.eh[i], S.ek[i], S.ev[i])); g55Rms(x, 0, W["enc_nf"], dl, x, 0); // pooling inputs for this byte const Hp = c.pool_heads, ws = W["pool.ws"]; g55Vm(x, 0, ws, 0, dl, Hp, sc.gt, 0); for(let hh = 0; hh < Hp; hh++) S.psc[t * Hp + hh] = 5 * Math.tanh(sc.gt[hh] / 5); g55Vm(x, 0, W["pool.wv"], 0, dl, dl, sc.pool, 0); S.phv.set(sc.pool.subarray(0, dl), t * dl); // --- the patch ends here: pool it and advance the trunk by one step if(sNext){ const s = S.pStart, n = t - s + 1; g55Pool(M, S, s, n); g55TrunkStep(M, S, S.pdocs[S.nClosed]); S.gl = g55Grow(S.gl, (S.nClosed + 1) * dl, Float32Array); g55Vm(sc.o, 0, W["down"], 0, d, dl, sc.gl, 0); g55Rms(sc.gl, 0, W["down_nf"], dl, sc.t, 0); S.gl.set(sc.t.subarray(0, dl), S.nClosed * dl); S.nClosed++; } S.sNext = sNext; // --- decoder input: encoder output + latent of the latest closed patch (BOS if none / other document) const didx = S.nClosed, u = sc.hrow, bos = W["bos"]; if(didx > 0 && S.pdocs[didx - 1] === dc){ const o = (didx - 1) * dl; for(let i = 0; i < dl; i++) u[i] = x[i] + S.gl[o + i]; } else for(let i = 0; i < dl; i++) u[i] = x[i] + bos[i]; for(let i = 0; i < c.n_dec; i++) g55LocalBlock(M, S, "dec." + i, "attn", u, t, b, null, S.dk[i], S.dv[i]); if(wantLogits){ g55Rms(u, 0, W["dec_nf"], dl, sc.t, 0); g55Vm(sc.t, 0, M.headc, 0, dl, 256, S.logits, 0); if(c.rosa && p1 > 0) S.logits[p1 - 1] += W["rosa.boost"][bk]; } S.n = t + 1; } /* ---- sampling + streaming ---- */ async function g55Generate(M, prompt, onToken, o){ const c = M.c, limit = c.seq_len, maxIn = Math.max(0, Math.min(o.maxTokens, limit)); let bytes = Array.from(new TextEncoder().encode(prompt)); if(!bytes.length) bytes = [32]; if(bytes.length + maxIn > limit) bytes = bytes.slice(-Math.max(1, limit - maxIn)); const maxNew = Math.min(maxIn, limit - bytes.length); if(!maxNew) return; const S = g55NewState(M, bytes.length + maxNew), dec = new TextDecoder("utf-8"), eod = o.eod === undefined ? 0 : o.eod; for(let p = 0; p < bytes.length; p++){ g55Step(M, S, bytes[p], p === bytes.length - 1); if(p % 6 === 5) await new Promise(r => setTimeout(r, 0)); // keep the page responsive while the prompt is read } const lg = new Float32Array(256); for(let n = 0; n < maxNew; n++){ lg.set(S.logits); let pick = 0; if(!(o.temperature > 0)){ for(let i = 1; i < 256; i++) if(lg[i] > lg[pick]) pick = i; } else{ let thr = -Infinity; if(o.topK > 0 && o.topK < 256) thr = Array.from(lg).sort((a, b) => b - a)[o.topK - 1]; let mx = -Infinity; for(let i = 0; i < 256; i++) if(lg[i] >= thr && lg[i] > mx) mx = lg[i]; let sum = 0; const pr = new Float64Array(256); for(let i = 0; i < 256; i++) if(lg[i] >= thr){ pr[i] = Math.exp((lg[i] - mx) / o.temperature); sum += pr[i]; } let r = Math.random() * sum; pick = 255; for(let i = 0; i < 256; i++){ r -= pr[i]; if(pr[i] > 0 && r <= 0){ pick = i; break; } } } if(pick === eod && o.stopAtEod) break; if(pick !== 0) onToken(dec.decode(new Uint8Array([pick]), {stream:true})); if(n === maxNew - 1) break; g55Step(M, S, pick, true); await new Promise(r => setTimeout(r, 0)); } } const NATIVE_ARCHS = { notokengen55:{build:g55Build, plan:g55Plan, generate:g55Generate, supports:cfg => /gen55/i.test(String(cfg.model_type))}, // hierarchical byte-level hybrid (patcher + RWKV-7/attention trunk) notokenlm:{build:ntBuild, plan:ntPlan, generate:ntGenerate, supports:cfg => !/gen55/i.test(String(cfg.model_type)) && (cfg.vocab_size || 256) === 256}, // byte-level only gpt:{build:gptBuild, plan:gptPlan, generate:ntGenerate, supports:cfg => !/gen55/i.test(String(cfg.model_type))} // byte-level (256) or character-level with a vocabulary file }; /* ---- end built-in engines ---- */ /* ---- run in browser ---- */ let current = null; const engines = new Map(); let lib = null; function openRun(m){ current = m; $("#rname").textContent = m.id; $("#rout").hidden = true; $("#rout").textContent = ""; $("#rstat").textContent = navigator.gpu ? t("sGpu") : t("sNoGpu"); $("#rgo").disabled = false; const mf = m.manifest || {}; $("#oTemp").value = mf.temperature ?? 0.7; $("#oTopK").value = mf.top_k ?? 40; $("#oMax").value = mf.maxTokens ?? 256; $("#oEod").value = mf.eod_token_id ?? (m.runtime === "native" ? 0 : ""); $("#oStop").checked = true; document.querySelectorAll(".eodopt").forEach(n => n.hidden = m.runtime === "transformers"); // EOD controls apply to custom runners and built-in engines $("#dlg").showModal(); } $("#rclose").onclick = () => $("#dlg").close(); async function buildEngine(m, kind, stat){ const pct = p => typeof p === "number" ? " " + Math.round(p) + "%" : ""; if(kind === "native"){ const base = "https://huggingface.co/" + m.id + "/resolve/main/", tensors = new Map(); for(let i = 0; i < m.native.files.length; i++){ stat.textContent = t("sLoad") + "..."; 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); }); for(const [k, v] of readSafetensors(buf)) tensors.set(k, v); } const bag = new TensorBag(tensors), errs = []; for(const k of m.native.kinds){ try{ const arch = NATIVE_ARCHS[k], model = arch.build(m.native.cfg, bag, m.native.unused); return (prompt, onToken, o) => arch.generate(model, prompt, onToken, o); } catch(e){ errs.push(k + ": " + String((e && e.message) || e)); } } throw new Error(errs.join(" ;; ")); } if(kind === "custom"){ const mf = m.manifest || {}, base = "https://huggingface.co/" + m.id + "/resolve/main/"; const onProgress = (p, msg) => { stat.textContent = t("sLoad") + (msg ? " (" + msg + ")" : "") + pct(p); }; stat.textContent = t("sLoad") + "..."; const code = await (await fetch(base + (mf.runner || "verolm-runner.js"))).text(); const mod = await import(URL.createObjectURL(new Blob([code], {type:"text/javascript"}))); // tensors come as a TensorBag: runners may ask for "pos_conv.w" and still find "model.pos_conv.weight", "module.pos_conv.w", etc. const ctx = {modelId:m.id, baseUrl:base, manifest:mf, onProgress, tools:{readPt, readSafetensors, fetchBuffer, toFloat32, TensorBag}}; if(mf.weights){ const buf = await fetchBuffer(base + mf.weights, p => onProgress(p, "weights")); if(mf.format === "pt"){ onProgress(undefined, "reading .pt"); ctx.tensors = new TensorBag(await readPt(buf)); } else if(mf.format === "safetensors"){ ctx.tensors = new TensorBag(readSafetensors(buf)); } else ctx.weights = buf; } let r; try{ r = await mod.load(ctx); } catch(e){ const ks = ctx.tensors ? [...ctx.tensors.keys()] : []; throw new Error(String((e && e.message) || e) + (ks.length ? " | " + tensorSummary(ks) : "")); } return (prompt, onToken, o) => r.generate(prompt, {onToken, maxTokens:o.maxTokens, temperature:o.temperature, topK:o.topK, eod:o.eod, stopAtEod:o.stopAtEod}); } if(!lib) lib = await import("https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.2"); stat.textContent = t("sLoad") + "..."; const gpu = !!navigator.gpu, has = n => (m.onnxFiles || []).includes("onnx/" + n); const dtype = gpu ? (has("model_q4.onnx") ? "q4" : has("model_fp16.onnx") ? "fp16" : has("model_quantized.onnx") ? "q8" : "fp32") : (has("model_quantized.onnx") ? "q8" : has("model_q4.onnx") ? "q4" : "fp32"); const gen = await lib.pipeline("text-generation", m.id, { device: gpu ? "webgpu" : "wasm", dtype, progress_callback: p => { if(p.status === "progress") stat.textContent = t("sLoad") + pct(p.progress || 0); } }); return async (prompt, onToken, o) => { const streamer = new lib.TextStreamer(gen.tokenizer, {skip_prompt:true, callback_function:onToken}); const cfg = {max_new_tokens:o.maxTokens, do_sample:o.temperature > 0, streamer}; if(o.temperature > 0){ cfg.temperature = o.temperature; if(o.topK > 0) cfg.top_k = o.topK; } await gen([{role:"user", content:prompt}], cfg); }; } // Tries every engine that can plausibly run this model, in order; only fails if all of them fail, and then reports each reason. async function getEngine(m, stat){ if(engines.has(m.id)) return engines.get(m.id); const errs = []; for(const kind of (m.chain && m.chain.length ? m.chain : [m.runtime])){ try{ const eng = await buildEngine(m, kind, stat); engines.set(m.id, eng); return eng; }catch(e){ console.error("[" + m.id + "] engine '" + kind + "' failed:", e); errs.push(kind + ": " + String((e && e.message) || e)); } } if(m.whyNot) errs.push("built-in: " + m.whyNot); throw new Error(errs.join(" | ")); } $("#rgo").onclick = async () => { const go = $("#rgo"), out = $("#rout"), stat = $("#rstat"); const prompt = $("#rin").value.trim(); if(!prompt) return; go.disabled = true; out.hidden = false; out.textContent = ""; try{ const eng = await getEngine(current, stat); stat.textContent = t("sGen"); const num = (id, lo, hi, d) => { const v = parseFloat($(id).value); return Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : d; }; const eodRaw = $("#oEod").value.trim(); const opts = {temperature:num("#oTemp", 0, 5, 0.7), topK:Math.round(num("#oTopK", 0, 256, 40)), maxTokens:Math.round(num("#oMax", 1, 4096, 256)), eod:eodRaw === "" ? undefined : Math.round(num("#oEod", 0, 1e9, 0)), stopAtEod:$("#oStop").checked}; await eng(prompt, s => { out.textContent += s; }, opts); stat.textContent = t("sReady"); }catch(e){ console.error(e); engines.delete(current.id); const full = String((e && e.message) || e); console.error("[" + current.id + "] full error:", full); if(/Missing tensor|not found in model\.safetensors|Unsupported extra tensors|different architecture/i.test(full)){ current.runnable = false; current.whyNot = full; // definite architecture mismatch: remember it stat.textContent = t("sErrArch"); document.querySelectorAll("button[data-id]").forEach(b => { if(b.dataset.id === current.id){ b.disabled = true; b.title = t("noRun"); } }); }else{ stat.textContent = t("sErrRun") + " [" + full.slice(0, 300) + (full.length > 300 ? "…" : "") + "]"; } } go.disabled = false; }; addEventListener("hashchange", () => show(location.hash.slice(1))); $("#q").oninput = e => { Q = e.target.value; render(); }; $("#fRun").onclick = e => { ONLY = !ONLY; e.currentTarget.setAttribute("aria-pressed", ONLY); render(); }; $("#sMenu").onclick = () => $("#side").classList.toggle("open"); show(location.hash.slice(1)); applyLang(); load(); </script> </body> </html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="VeroLM: an independent lab training open, experimental language models from small to large.">
<title>VeroLM</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='525 200 500 630'%3E%3Cpolygon fill='%23e10b17' points='537,340 626,304 626,594 537,528'/%3E%3Cpolygon fill='%23e10b17' points='665,314 803,265 803,703 665,614'/%3E%3Cpolygon fill='%23e10b17' points='840,270 1012,212 1012,817 840,710'/%3E%3C/svg%3E">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:wght@600;800&family=Hanken+Grotesk:wght@400;600;700&display=swap" rel="stylesheet">
<style>
:root{--bg:#f3f3f1;--fg:#121214;--mut:#5c5c65;--line:#d8d8dc;--card:#fff;--side:#ebebe8;--dot:rgba(0,0,0,.07);--glow:rgba(225,11,23,.05);--red:#e10b17;
--font:"Hanken Grotesk",system-ui,-apple-system,"Segoe UI",sans-serif;--disp:"Bricolage Grotesque","Hanken Grotesk",system-ui,sans-serif}
@media (prefers-color-scheme:dark){:root{--bg:#0a0f18;--fg:#ececee;--mut:#9aa6b8;--line:#222c3b;--card:#111826;--side:#0d1320;--dot:rgba(140,170,255,.07);--glow:rgba(40,90,220,.16)}}
*{box-sizing:border-box}
[hidden]{display:none!important}
body{margin:0;background:var(--bg);color:var(--fg);font-family:var(--font);line-height:1.6;-webkit-font-smoothing:antialiased;height:100vh;display:grid;grid-template-columns:268px 1fr;overflow:hidden}
a{color:inherit}
:focus-visible{outline:2px solid var(--fg);outline-offset:3px}
.wrap{max-width:1120px;margin:0 auto;padding:0 24px}
.l-ink{fill:var(--fg)}.l-red{fill:url(#redg)}
.b{transform-box:fill-box;transform-origin:bottom;animation:rise .9s cubic-bezier(.2,.8,.2,1) both}
.b2{animation-delay:.12s}.b3{animation-delay:.24s}
@keyframes rise{from{transform:scaleY(.15);opacity:0}to{transform:none;opacity:1}}
.brand .b{animation:none}
@media (prefers-reduced-motion:reduce){.b{animation:none}}
.side{background:var(--side);border-right:1px solid var(--line);display:flex;flex-direction:column;height:100vh;padding:16px 12px;overflow:auto}
.brand{display:flex;align-items:center;gap:10px;font:800 1.2rem var(--disp);letter-spacing:-.02em;text-decoration:none;padding:6px 10px 20px}
.brand svg{width:26px;height:32px}
.brand .b{animation:none}
.tabs{display:flex;flex-direction:column;gap:2px}
.tab{font-weight:600;font-size:.93rem;color:var(--mut);text-decoration:none;padding:9px 12px;border-radius:10px}
.tab:hover{color:var(--fg);background:color-mix(in srgb,var(--fg) 6%,transparent)}
.tab[aria-current=page]{color:var(--fg);background:color-mix(in srgb,var(--fg) 10%,transparent);box-shadow:inset 3px 0 0 var(--red)}
.sl{font-size:.8rem;font-weight:600;color:var(--mut);padding:22px 12px 6px}
.sr{display:block;width:100%;text-align:left;font:inherit;font-size:.88rem;color:var(--fg);background:none;border:0;border-radius:10px;padding:7px 12px;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.sr:hover{background:color-mix(in srgb,var(--fg) 6%,transparent)}
.sfoot{margin-top:auto;display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:16px 4px 0}
.main{height:100vh;overflow:auto;background:radial-gradient(70% 45% at 50% 108%,var(--glow),transparent),radial-gradient(var(--dot) 1px,transparent 1.5px) 0 0/22px 22px,var(--bg)}
.main .wrap{padding:0 44px}
.mbar{display:none}
.news{display:flex;flex-direction:column;gap:14px;max-width:760px}
.ni{--c:#8b8b94;background:var(--card);border:1px solid var(--line);border-left:4px solid var(--c);border-radius:10px;padding:18px 20px}
.ni.n1{--c:#f2b705}.ni.n2{--c:#3b82f6}.ni.n3{--c:#22a559}
.nd{display:flex;gap:10px;align-items:center;font-size:.8rem;color:var(--mut);margin-bottom:6px}
.nd i{width:8px;height:8px;border-radius:50%;background:var(--c)}
.nd .tg{border:1px solid var(--c);border-radius:4px;padding:0 8px;color:var(--fg)}
.ni h3{margin:0 0 6px;font-size:1.2rem;letter-spacing:-.02em}
.ni h3 a{text-decoration:none}.ni h3 a:hover{text-decoration:underline}
.ni p{margin:0;color:var(--mut)}
.chip{font:inherit;font-size:.85rem;color:var(--fg);background:transparent;border:1px solid var(--line);border-radius:999px;padding:6px 14px;cursor:pointer;text-decoration:none;display:inline-block}
.chip:hover{border-color:var(--mut)}
.chip[aria-pressed=true]{background:var(--fg);color:var(--bg);border-color:var(--fg)}
select.chip{appearance:none;-webkit-appearance:none;background-color:var(--bg);padding-right:26px;background-repeat:no-repeat;background-position:right 11px center;background-size:9px 6px;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 9 6'%3E%3Cpath d='M1 1l3.5 3.5L8 1' fill='none' stroke='%238d8d95' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")}
.panel{padding:56px 0 24px}
h1,h2,h3,h4{font-family:var(--disp)}
h2{font-size:clamp(1.8rem,4vw,2.6rem);letter-spacing:-.03em;line-height:1.05;margin:0 0 10px}
.sub{color:var(--mut);margin:0 0 32px;max-width:60ch}
.hero{display:grid;grid-template-columns:1.5fr .5fr;align-items:end;gap:48px;padding:16px 0 64px}
.hero h1{font-size:clamp(2.8rem,8vw,6.2rem);line-height:.95;letter-spacing:-.045em;font-weight:800;margin:0 0 24px}
.hero p{max-width:52ch;color:var(--mut);font-size:1.12rem;margin:0 0 32px}
.hero svg{width:min(100%,200px);height:auto;justify-self:end}
.cta{display:flex;gap:10px;flex-wrap:wrap}
.btn{font:inherit;font-weight:600;font-size:.9rem;border:1px solid transparent;border-radius:8px;padding:10px 18px;cursor:pointer;color:#fff;text-decoration:none;display:inline-block}
.btn.red,.btn.green{background:var(--red)}
.btn.ghost,.btn.blue{background:transparent;color:var(--fg);border-color:var(--line)}
.btn.ghost:hover,.btn.blue:hover{border-color:var(--fg)}
.btn.red:hover,.btn.green:hover{filter:brightness(1.1)}
.btn[disabled]{opacity:.5;cursor:wait}
.card .btn[disabled]{opacity:.35;cursor:not-allowed;filter:grayscale(.7)}
.rt{font-size:1rem;letter-spacing:0;margin:0 0 16px;color:var(--mut);font-weight:600}
.ruler{position:relative;height:150px;border-bottom:1px solid var(--fg);margin:0 14px 56px}
.rb{position:absolute;bottom:0;width:10px;margin-left:-5px;padding:0;border:0;background:var(--red);cursor:pointer;border-radius:2px 2px 0 0}
.rb:hover{background:var(--fg)}
.tick{position:absolute;bottom:-28px;transform:translateX(-50%);font-size:.8rem;color:var(--mut)}
.tick::before{content:"";position:absolute;left:50%;top:-12px;height:7px;border-left:1px solid var(--mut)}
.cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(250px,1fr));margin-top:24px}
.cols>div{border-left:1px solid var(--line);padding:4px 28px 8px}
.cols>div:first-child{border-left:0;padding-left:0}
.cols h3,.areas h3{margin:0 0 8px;font-size:1.3rem;letter-spacing:-.02em}
.cols p,.areas p{margin:0;color:var(--mut)}
.areas{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:0 48px}
.areas>div{border-top:1px solid var(--fg);padding:20px 0 36px}
.about{max-width:62ch;font-size:1.15rem}
.about p{margin:0 0 18px}
.tools{display:flex;gap:10px;flex-wrap:wrap;margin:0 0 28px}
.in{font:inherit;font-size:.9rem;background:var(--card);color:var(--fg);border:1px solid var(--line);border-radius:999px;padding:7px 16px;min-width:min(100%,260px)}
.note{border-left:3px solid var(--red);padding:2px 0 2px 14px;margin:0 0 32px;color:var(--mut);font-size:.92rem;max-width:70ch}
.series{margin-bottom:44px}
.series h3{display:flex;align-items:baseline;gap:12px;margin:0 0 8px;font-size:1.4rem;letter-spacing:-.02em}
.series h3 a{text-decoration:none}
.series h3 a:hover{text-decoration:underline}
.series h3 small{color:var(--mut);font:400 .85rem var(--font)}
.series .desc{color:var(--mut);margin:0 0 18px;max-width:70ch;font-size:.95rem}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:14px}