Ares Publisher commited on
Commit ·
8efdc48
1
Parent(s): feab5f3
Add Ares Lab source and Colab training notebook
Browse files- .gitignore +8 -0
- README.md +50 -10
- apps/static/app.js +1 -0
- apps/static/index.html +1 -0
- apps/static/style.css +1 -0
- ares/__init__.py +0 -0
- ares/cli.py +9 -0
- ares/config.py +16 -0
- ares/init_models.py +14 -0
- ares/memory.py +13 -0
- ares/model.py +45 -0
- ares/runtime.py +43 -0
- ares/server.py +28 -0
- ares/tokenizer.py +65 -0
- ares/train.py +24 -0
- docs/ROADMAP.md +20 -0
- index.html +1 -19
- notebooks/ares_xiphos_training.ipynb +107 -0
- requirements.txt +2 -0
- tests/test_smoke.py +10 -0
.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
artifacts/
|
| 5 |
+
runs/
|
| 6 |
+
corpus/
|
| 7 |
+
*.pt
|
| 8 |
+
*.sqlite3
|
README.md
CHANGED
|
@@ -1,10 +1,50 @@
|
|
| 1 |
-
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
---
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ares — from-scratch transformer research project
|
| 2 |
+
|
| 3 |
+
Ares is a two-role system: **Ares** answers and assists; **Xiphos** drafts *reviewable* capability plans. Xiphos never executes code, modifies tools, browses, or trains anything without an explicit user approval recorded in a plan.
|
| 4 |
+
|
| 5 |
+
## What this first increment delivers
|
| 6 |
+
|
| 7 |
+
* A dependency-light, trained byte-level BPE tokenizer (special tokens and chat sections).
|
| 8 |
+
* A decoder-only PyTorch transformer: tied token embedding/unembedding, RoPE, causal grouped-query attention, KV cache, pre-norm RMSNorm, SwiGLU, and AdamW training.
|
| 9 |
+
* Streaming text pipeline, checkpoint/resume, SQLite profile/memory store, and an approval-gated Xiphos plan schema.
|
| 10 |
+
* A dependency-free **static** Hugging Face Spaces-compatible UI. It is an interface and local memory/planning demonstration; static hosting cannot run a multi-million parameter Python/PyTorch model server-side.
|
| 11 |
+
|
| 12 |
+
It deliberately starts as a small, testable model. Scaling configuration is a controlled experiment, not a claim of capability.
|
| 13 |
+
|
| 14 |
+
## Honest deployment constraints
|
| 15 |
+
|
| 16 |
+
Training a credible 1B-parameter foundation model from scratch needs a very large licensed/clean corpus, distributed GPU infrastructure, lengthy runs, and substantial cost. A free static HF Space cannot train or serve it. Static Pages can host this UI and model artifacts, but **inference requires either browser-compatible quantized weights with enough client RAM/download, or a separately operated inference service**. Neither is secretly substituted with an external model/API here.
|
| 17 |
+
|
| 18 |
+
Do not scrape or train on data without checking licenses, terms, privacy, and provenance. Never store secrets in this repository.
|
| 19 |
+
|
| 20 |
+
## Quick start (Python 3.10+)
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
python -m venv .venv && source .venv/bin/activate
|
| 24 |
+
pip install -r requirements.txt
|
| 25 |
+
# Place UTF-8, license-reviewed .txt files below corpus/.
|
| 26 |
+
python -m ares.tokenizer train --input corpus --out artifacts/tokenizer.json --vocab-size 16000
|
| 27 |
+
python -m ares.train --tokenizer artifacts/tokenizer.json --data corpus --out runs/tiny
|
| 28 |
+
python -m ares.cli --checkpoint runs/tiny/latest.pt --tokenizer artifacts/tokenizer.json
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
`python -m unittest discover -s tests` runs architecture smoke tests.
|
| 32 |
+
|
| 33 |
+
## Hugging Face static setup (jacmor64)
|
| 34 |
+
|
| 35 |
+
1. Create a **Static** Space named `Ares` under `jacmor64` (no Docker/Gradio SDK).
|
| 36 |
+
2. Upload the contents of `apps/static/` to its repository root (including `index.html`).
|
| 37 |
+
3. Host model checkpoints/datasets separately only after their licences, safety review, and sizes are approved. Do not put giant checkpoints in a static UI repository.
|
| 38 |
+
|
| 39 |
+
Read `docs/ROADMAP.md` before moving beyond this foundation.
|
| 40 |
+
|
| 41 |
+
## Local two-model runtime (Phase 1)
|
| 42 |
+
|
| 43 |
+
A Static Space cannot host this Python process. Run it on a computer or separately approved service after training:
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
python -m ares.init_models --tokenizer artifacts/tokenizer.json --out models
|
| 47 |
+
python -m ares.server --ares models/ares.pt --xiphos models/xiphos.pt --tokenizer artifacts/tokenizer.json
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
`init_models` produces two **random, untrained** checkpoints purely to validate wiring. The server explicitly refuses to present them as intelligent. Train Ares and Xiphos separately, evaluate each checkpoint, then mark only reviewed checkpoints as `training_complete: true`. `POST /chat` serves Ares; `POST /xiphos/plan` produces a proposal envelope and **never executes it**.
|
apps/static/app.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
const $=s=>document.querySelector(s),msgs=$('#messages');let local=false;$('#consent').onclick=()=>{local=!local;$('#consent').textContent=local?'Local session notes enabled':'Enable local session notes'};$('#form').onsubmit=e=>{e.preventDefault();const text=$('#input').value.trim();if(!text)return;msgs.insertAdjacentHTML('beforeend',`<article><b>YOU</b><p>${text.replaceAll('<','<')}</p></article><article class="ares"><b>ARES</b><p>Static UI demonstration: no runtime is attached, so I cannot fabricate a model response. Deploy the approved Python runtime separately, or add a reviewed browser inference build.</p></article>`);$('#input').value='';msgs.scrollTop=msgs.scrollHeight};const proposal={title:'Example: add a calculator tool',status:'PROPOSED — NOT EXECUTABLE',scope:'A pure local arithmetic module only.',data:'No data access.',risks:['Incorrect results; test boundary cases.'],tests:['unit tests for arithmetic and divide-by-zero'],rollback:'Delete the module and plan record.',commands:['python -m unittest tests/test_calculator.py']};$('#plan').onclick=()=>{$('#review').hidden=false;$('#proposal').textContent=JSON.stringify(proposal,null,2)};$('#approve').onclick=()=>{proposal.status='APPROVED RECORD ONLY — still requires sandbox execution';$('#proposal').textContent=JSON.stringify(proposal,null,2)};$('#reject').onclick=()=>{$('#review').hidden=true};
|
apps/static/index.html
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Ares | Control Deck</title><link rel="stylesheet" href="style.css"><body><main><header><div><p class="eyebrow">ARES / LOCAL-FIRST RESEARCH SYSTEM</p><h1>Ares <span>Control Deck</span></h1></div><div class="status">● STATIC UI · NO MODEL CONNECTED</div></header><section class="layout"><aside><h2>Memory</h2><p>Conversation memory is off by default. This static prototype stores nothing remotely.</p><button id="consent">Enable local session notes</button><hr><h2>Xiphos</h2><p>Planning model — proposals only. Nothing executes from this page.</p><button id="plan">Draft sample plan</button></aside><section class="chat"><div id="messages"><article class="ares"><b>ARES</b><p>Interface online. Connect an approved, from-scratch Ares runtime to chat. I will not silently call another AI model or execute Xiphos plans.</p></article></div><form id="form"><input id="input" aria-label="Message" placeholder="Message Ares…" autocomplete="off"><button>Send</button></form></section></section><section id="review" hidden><h2>Xiphos proposal — review required</h2><pre id="proposal"></pre><div><button id="approve">Approve plan record</button><button id="reject">Reject</button></div></section><footer>Core intelligence: planned from-scratch transformer · User-controlled memory · Approval-gated tools</footer></main><script src="app.js"></script></body></html>
|
apps/static/style.css
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
:root{--bg:#081015;--panel:#101d24;--line:#20343d;--ink:#e7f1ef;--mute:#91a6a6;--gold:#e4b653;--aqua:#65ddcf}*{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at 80% 0,#17333a,transparent 35%),var(--bg);color:var(--ink);font:15px system-ui,sans-serif}main{max-width:1100px;margin:auto;padding:34px 22px}header{display:flex;justify-content:space-between;align-items:end;border-bottom:1px solid var(--line);padding-bottom:24px}.eyebrow,b{letter-spacing:.12em;color:var(--aqua);font-size:11px}h1{margin:3px 0;font-size:42px}h1 span{font-weight:300;color:var(--mute)}.status{font-size:12px;color:var(--gold)}.layout{display:grid;grid-template-columns:270px 1fr;gap:20px;margin:24px 0}aside,.chat,#review{background:#0d181e;border:1px solid var(--line);border-radius:12px;padding:20px}h2{font-size:16px;margin-top:0}p{color:var(--mute);line-height:1.55}hr{border:0;border-top:1px solid var(--line);margin:20px 0}button{background:transparent;color:var(--aqua);border:1px solid #34746c;border-radius:6px;padding:9px 11px;cursor:pointer}#messages{height:390px;overflow:auto}article{padding:14px;border-left:2px solid var(--aqua);background:#112229}form{display:flex;gap:9px;margin-top:16px}input{flex:1;background:#071116;color:white;border:1px solid var(--line);border-radius:6px;padding:12px}pre{white-space:pre-wrap;background:#071116;padding:14px;color:#c0d4d0}footer{color:var(--mute);font-size:12px}@media(max-width:700px){header,.layout{display:block}.status{margin-top:12px}.layout aside{margin-bottom:15px}}
|
ares/__init__.py
ADDED
|
File without changes
|
ares/cli.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse,torch
|
| 2 |
+
from .tokenizer import ByteBPETokenizer
|
| 3 |
+
from .model import AresTransformer
|
| 4 |
+
from .config import AresConfig
|
| 5 |
+
def main():
|
| 6 |
+
p=argparse.ArgumentParser();p.add_argument('--checkpoint',required=True);p.add_argument('--tokenizer',required=True);a=p.parse_args();t=ByteBPETokenizer.load(a.tokenizer);z=torch.load(a.checkpoint,map_location='cpu');m=AresTransformer(AresConfig(**z['config']));m.load_state_dict(z['model']);m.eval();print('Ares local CLI. Type /quit.')
|
| 7 |
+
while (q:=input('you> '))!='/quit':
|
| 8 |
+
ids=torch.tensor([t.encode('<user>'+q+'<assistant>',True)]);print('ares>',t.decode(m.generate(ids,80)[0].tolist()))
|
| 9 |
+
if __name__=='__main__':main()
|
ares/config.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass, asdict
|
| 2 |
+
|
| 3 |
+
@dataclass
|
| 4 |
+
class AresConfig:
|
| 5 |
+
vocab_size: int = 16_000
|
| 6 |
+
max_seq_len: int = 2048
|
| 7 |
+
dim: int = 512
|
| 8 |
+
n_layers: int = 12
|
| 9 |
+
n_heads: int = 8
|
| 10 |
+
n_kv_heads: int = 2
|
| 11 |
+
ffn_multiplier: float = 2.67
|
| 12 |
+
rope_theta: float = 10000.0
|
| 13 |
+
rms_norm_eps: float = 1e-5
|
| 14 |
+
dropout: float = 0.0
|
| 15 |
+
tie_embeddings: bool = True
|
| 16 |
+
def to_dict(self): return asdict(self)
|
ares/init_models.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Creates two *untrained* independent checkpoints. This is infrastructure, not intelligence."""
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import torch
|
| 5 |
+
from .config import AresConfig
|
| 6 |
+
from .model import AresTransformer
|
| 7 |
+
from .tokenizer import ByteBPETokenizer
|
| 8 |
+
def main():
|
| 9 |
+
p=argparse.ArgumentParser();p.add_argument('--tokenizer',required=True);p.add_argument('--out',default='models');p.add_argument('--dim',type=int,default=256);p.add_argument('--layers',type=int,default=6);p.add_argument('--context',type=int,default=1024);a=p.parse_args()
|
| 10 |
+
t=ByteBPETokenizer.load(a.tokenizer);c=AresConfig(vocab_size=t.vocab_size,dim=a.dim,n_layers=a.layers,n_heads=8,n_kv_heads=2,max_seq_len=a.context);Path(a.out).mkdir(parents=True,exist_ok=True)
|
| 11 |
+
for role in ('ares','xiphos'):
|
| 12 |
+
torch.manual_seed(2026 if role=='ares' else 4141);m=AresTransformer(c);torch.save({'model':m.state_dict(),'config':c.to_dict(),'role':role,'training_complete':False},Path(a.out)/f'{role}-untrained.pt')
|
| 13 |
+
print('Created separate untrained Ares and Xiphos checkpoints. Do not use these for answers or plans.')
|
| 14 |
+
if __name__=='__main__':main()
|
ares/memory.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local, inspectable memory. Profiles are user-controlled, not hidden model training data."""
|
| 2 |
+
import sqlite3, json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
SCHEMA='''CREATE TABLE IF NOT EXISTS memories(id INTEGER PRIMARY KEY, kind TEXT NOT NULL, text TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP, consent INTEGER NOT NULL DEFAULT 0); CREATE TABLE IF NOT EXISTS plans(id INTEGER PRIMARY KEY, title TEXT, plan_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'proposed', created_at TEXT DEFAULT CURRENT_TIMESTAMP);'''
|
| 5 |
+
class MemoryStore:
|
| 6 |
+
def __init__(self,path='ares.sqlite3'):self.db=sqlite3.connect(path);self.db.executescript(SCHEMA)
|
| 7 |
+
def add(self,kind,text,consent=False):
|
| 8 |
+
if not consent:raise PermissionError('Explicit user consent is required to retain memory.')
|
| 9 |
+
self.db.execute('INSERT INTO memories(kind,text,consent) VALUES(?,?,1)',(kind,text));self.db.commit()
|
| 10 |
+
def search(self,q,limit=8):return self.db.execute('SELECT id,kind,text FROM memories WHERE text LIKE ? ORDER BY id DESC LIMIT ?',('%'+q+'%',limit)).fetchall()
|
| 11 |
+
def propose_plan(self,title,steps):
|
| 12 |
+
self.db.execute('INSERT INTO plans(title,plan_json) VALUES(?,?)',(title,json.dumps({'steps':steps,'requires_approval':True})));self.db.commit()
|
| 13 |
+
def approve(self,id):self.db.execute("UPDATE plans SET status='approved' WHERE id=?",(id,));self.db.commit()
|
ares/model.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math, torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from .config import AresConfig
|
| 5 |
+
|
| 6 |
+
class RMSNorm(nn.Module):
|
| 7 |
+
def __init__(self,d,eps=1e-5): super().__init__();self.weight=nn.Parameter(torch.ones(d));self.eps=eps
|
| 8 |
+
def forward(self,x): return x*torch.rsqrt(x.pow(2).mean(-1,keepdim=True)+self.eps)*self.weight
|
| 9 |
+
|
| 10 |
+
def rope(x, positions, theta):
|
| 11 |
+
# x B,H,T,D; RoPE on even-dimensional head features
|
| 12 |
+
d=x.size(-1);freq=1.0/(theta**(torch.arange(0,d,2,device=x.device,dtype=x.dtype)/d));ang=positions.to(x.dtype)[None,None,:,None]*freq
|
| 13 |
+
c,s=ang.cos(),ang.sin();a,b=x[...,::2],x[...,1::2];return torch.stack((a*c-b*s,a*s+b*c),-1).flatten(-2)
|
| 14 |
+
class Attention(nn.Module):
|
| 15 |
+
def __init__(self,c):
|
| 16 |
+
super().__init__();assert c.dim%c.n_heads==0 and c.n_heads%c.n_kv_heads==0;self.h,self.kh,self.d=c.n_heads,c.n_kv_heads,c.dim//c.n_heads
|
| 17 |
+
self.q=nn.Linear(c.dim,c.dim,bias=False);self.k=nn.Linear(c.dim,self.kh*self.d,bias=False);self.v=nn.Linear(c.dim,self.kh*self.d,bias=False);self.o=nn.Linear(c.dim,c.dim,bias=False);self.theta=c.rope_theta
|
| 18 |
+
def forward(self,x,cache=None):
|
| 19 |
+
b,t,_=x.shape; past=0 if cache is None else cache[0].size(2);pos=torch.arange(past,past+t,device=x.device)
|
| 20 |
+
q=rope(self.q(x).view(b,t,self.h,self.d).transpose(1,2),pos,self.theta);k=rope(self.k(x).view(b,t,self.kh,self.d).transpose(1,2),pos,self.theta);v=self.v(x).view(b,t,self.kh,self.d).transpose(1,2)
|
| 21 |
+
if cache is not None:k=torch.cat((cache[0],k),2);v=torch.cat((cache[1],v),2)
|
| 22 |
+
k=k.repeat_interleave(self.h//self.kh,1);v=v.repeat_interleave(self.h//self.kh,1)
|
| 23 |
+
# is_causal correctly handles full prefill; generation uses one query and all keys.
|
| 24 |
+
y=F.scaled_dot_product_attention(q,k,v,is_causal=(t>1 and past==0));return self.o(y.transpose(1,2).reshape(b,t,-1)),(k[:,::self.h//self.kh],v[:,::self.h//self.kh])
|
| 25 |
+
class MLP(nn.Module):
|
| 26 |
+
def __init__(self,c): super().__init__();h=int(8*c.dim*c.ffn_multiplier/3)//64*64;self.w1=nn.Linear(c.dim,h,bias=False);self.w3=nn.Linear(c.dim,h,bias=False);self.w2=nn.Linear(h,c.dim,bias=False)
|
| 27 |
+
def forward(self,x):return self.w2(F.silu(self.w1(x))*self.w3(x))
|
| 28 |
+
class Block(nn.Module):
|
| 29 |
+
def __init__(self,c):super().__init__();self.n1=RMSNorm(c.dim,c.rms_norm_eps);self.a=Attention(c);self.n2=RMSNorm(c.dim,c.rms_norm_eps);self.m=MLP(c)
|
| 30 |
+
def forward(self,x,cache=None):a,k=self.a(self.n1(x),cache);return x+a+self.m(self.n2(x+a)),k
|
| 31 |
+
class AresTransformer(nn.Module):
|
| 32 |
+
def __init__(self,c=AresConfig()):
|
| 33 |
+
super().__init__();self.config=c;self.embed=nn.Embedding(c.vocab_size,c.dim);self.blocks=nn.ModuleList([Block(c) for _ in range(c.n_layers)]);self.norm=RMSNorm(c.dim,c.rms_norm_eps);self.lm_head=nn.Linear(c.dim,c.vocab_size,bias=False)
|
| 34 |
+
if c.tie_embeddings:self.lm_head.weight=self.embed.weight
|
| 35 |
+
def forward(self,ids,targets=None,kv_cache=None):
|
| 36 |
+
x=self.embed(ids);new=[]
|
| 37 |
+
for i,b in enumerate(self.blocks):x,k=b(x,None if kv_cache is None else kv_cache[i]);new.append(k)
|
| 38 |
+
logits=self.lm_head(self.norm(x));loss=F.cross_entropy(logits[:,:-1].reshape(-1,logits.size(-1)),targets[:,1:].reshape(-1)) if targets is not None else None
|
| 39 |
+
return logits,loss,new
|
| 40 |
+
@torch.no_grad()
|
| 41 |
+
def generate(self,ids,max_new=128,temperature=.8):
|
| 42 |
+
cache=None
|
| 43 |
+
for _ in range(max_new):
|
| 44 |
+
logits,_,cache=self(ids[:,-self.config.max_seq_len:] if cache is None else ids[:,-1:],kv_cache=cache);p=F.softmax(logits[:,-1]/max(temperature,1e-5),-1);ids=torch.cat((ids,torch.multinomial(p,1)),1)
|
| 45 |
+
return ids
|
ares/runtime.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local runtime for separately trained Ares and Xiphos checkpoints.
|
| 2 |
+
Neither role executes a tool. Xiphos returns a reviewable proposal only.
|
| 3 |
+
"""
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import re, torch
|
| 7 |
+
from .config import AresConfig
|
| 8 |
+
from .model import AresTransformer
|
| 9 |
+
from .tokenizer import ByteBPETokenizer
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class LoadedModel:
|
| 13 |
+
model: AresTransformer
|
| 14 |
+
tokenizer: ByteBPETokenizer
|
| 15 |
+
device: str
|
| 16 |
+
trained: bool
|
| 17 |
+
checkpoint: str
|
| 18 |
+
|
| 19 |
+
def load_model(checkpoint, tokenizer_path, device=None, expected_role=None):
|
| 20 |
+
device=device or ('cuda' if torch.cuda.is_available() else 'cpu')
|
| 21 |
+
tok=ByteBPETokenizer.load(tokenizer_path)
|
| 22 |
+
ckpt=torch.load(checkpoint,map_location=device,weights_only=False)
|
| 23 |
+
if expected_role and ckpt.get('role') not in (None, expected_role):
|
| 24 |
+
raise ValueError(f'Checkpoint role {ckpt.get("role")!r} cannot be loaded as {expected_role!r}')
|
| 25 |
+
model=AresTransformer(AresConfig(**ckpt['config'])).to(device)
|
| 26 |
+
model.load_state_dict(ckpt['model']); model.eval()
|
| 27 |
+
return LoadedModel(model,tok,device,bool(ckpt.get('training_complete',False)),str(checkpoint))
|
| 28 |
+
|
| 29 |
+
def respond(role, loaded, message, max_new=160):
|
| 30 |
+
if not loaded.trained:
|
| 31 |
+
return f'{role} is installed but its checkpoint is not trained yet. Train and evaluate it before using its output.'
|
| 32 |
+
# Role headers are data boundaries, not a security boundary; server never executes generated text.
|
| 33 |
+
prompt=f'<system>You are {role}. ' + ('Answer the user directly and helpfully.' if role=='Ares' else 'Draft a concise, non-executable implementation plan for user review.') + f'</system><user>{message}</user><assistant>'
|
| 34 |
+
ids=torch.tensor([loaded.tokenizer.encode(prompt,add_bos=True)],device=loaded.device)
|
| 35 |
+
if ids.size(1)>loaded.model.config.max_seq_len-1: ids=ids[:,-loaded.model.config.max_seq_len+1:]
|
| 36 |
+
out=loaded.model.generate(ids,max_new=max_new,temperature=.7)[0].tolist()
|
| 37 |
+
answer=loaded.tokenizer.decode(out[len(ids[0]):])
|
| 38 |
+
# Strip control tokens if a model emits them; never parse a response as commands.
|
| 39 |
+
return re.sub(r'<[^>]+>','',answer).strip()
|
| 40 |
+
|
| 41 |
+
def proposed_plan(xiphos, request):
|
| 42 |
+
"""Return model text in a plan envelope. Approval/execution is deliberately separate."""
|
| 43 |
+
return {'status':'proposed','executable':False,'request':request,'proposal':respond('Xiphos',xiphos,request),'required_review':['scope and files','data licences/privacy','resource estimate','tests and rollback','exact allowlisted commands']}
|
ares/server.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""No-framework local HTTP runtime. Intended for localhost or a separately secured host, not Static Spaces."""
|
| 2 |
+
import argparse,json
|
| 3 |
+
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
|
| 4 |
+
from .runtime import load_model,respond,proposed_plan
|
| 5 |
+
class App:
|
| 6 |
+
ares=None;xiphos=None
|
| 7 |
+
class Handler(BaseHTTPRequestHandler):
|
| 8 |
+
def reply(self,status,obj):
|
| 9 |
+
raw=json.dumps(obj).encode();self.send_response(status);self.send_header('Content-Type','application/json');self.send_header('Access-Control-Allow-Origin','*');self.send_header('Content-Length',str(len(raw)));self.end_headers();self.wfile.write(raw)
|
| 10 |
+
def do_OPTIONS(self):self.send_response(204);self.send_header('Access-Control-Allow-Origin','*');self.send_header('Access-Control-Allow-Headers','Content-Type');self.end_headers()
|
| 11 |
+
def do_GET(self):
|
| 12 |
+
if self.path=='/health':return self.reply(200,{'ok':True,'ares_loaded':bool(App.ares),'xiphos_loaded':bool(App.xiphos),'execution':'disabled'})
|
| 13 |
+
self.reply(404,{'error':'not found'})
|
| 14 |
+
def do_POST(self):
|
| 15 |
+
if self.path not in ('/chat','/xiphos/plan'):return self.reply(404,{'error':'not found'})
|
| 16 |
+
try:
|
| 17 |
+
n=int(self.headers.get('Content-Length','0')); body=json.loads(self.rfile.read(min(n,100_000)));message=str(body['message']).strip()
|
| 18 |
+
if not message or len(message)>20_000:raise ValueError('message must contain 1–20,000 characters')
|
| 19 |
+
if self.path=='/chat':return self.reply(200,{'role':'Ares','response':respond('Ares',App.ares,message)})
|
| 20 |
+
return self.reply(200,proposed_plan(App.xiphos,message))
|
| 21 |
+
except (ValueError,KeyError,json.JSONDecodeError) as e:self.reply(400,{'error':str(e)})
|
| 22 |
+
def log_message(self,*args):pass
|
| 23 |
+
def main():
|
| 24 |
+
p=argparse.ArgumentParser();p.add_argument('--ares',required=True);p.add_argument('--xiphos',required=True);p.add_argument('--tokenizer',required=True);p.add_argument('--host',default='127.0.0.1');p.add_argument('--port',type=int,default=8787);a=p.parse_args()
|
| 25 |
+
App.ares=load_model(a.ares,a.tokenizer,expected_role='ares');App.xiphos=load_model(a.xiphos,a.tokenizer,expected_role='xiphos')
|
| 26 |
+
print(f'Local runtime at http://{a.host}:{a.port}; tool execution is disabled.')
|
| 27 |
+
ThreadingHTTPServer((a.host,a.port),Handler).serve_forever()
|
| 28 |
+
if __name__=='__main__':main()
|
ares/tokenizer.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, auditable byte-pair encoder trained only on supplied local text."""
|
| 2 |
+
import argparse, collections, json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
SPECIAL = ["<pad>", "<bos>", "<eos>", "<system>", "<user>", "<assistant>", "<tool>", "<plan>", "<memory>"]
|
| 5 |
+
|
| 6 |
+
class ByteBPETokenizer:
|
| 7 |
+
def __init__(self, merges=None, special_tokens=SPECIAL):
|
| 8 |
+
self.special_tokens = special_tokens
|
| 9 |
+
self.special_to_id = {s:i for i,s in enumerate(special_tokens)}
|
| 10 |
+
self.merges = [tuple(x) for x in (merges or [])] # child token IDs, in priority order
|
| 11 |
+
self.base = len(special_tokens)
|
| 12 |
+
self.pair_to_token = {p:self.base+256+i for i,p in enumerate(self.merges)}
|
| 13 |
+
self.vocab_size = self.base + 256 + len(self.merges)
|
| 14 |
+
def encode_bytes(self, raw):
|
| 15 |
+
ids = [self.base+b for b in raw]
|
| 16 |
+
# Standard BPE: always apply the currently lowest-ranked available pair.
|
| 17 |
+
while len(ids) > 1:
|
| 18 |
+
choices=[(i, self.merges.index((ids[i],ids[i+1]))) for i in range(len(ids)-1) if (ids[i],ids[i+1]) in self.pair_to_token]
|
| 19 |
+
if not choices: break
|
| 20 |
+
i,rank=min(choices,key=lambda x:x[1]); ids[i:i+2]=[self.base+256+rank]
|
| 21 |
+
return ids
|
| 22 |
+
def encode(self, text, add_bos=False, add_eos=False):
|
| 23 |
+
ids=[]; pos=0
|
| 24 |
+
while pos < len(text):
|
| 25 |
+
found=next(((s,i) for s,i in self.special_to_id.items() if text.startswith(s,pos)),None)
|
| 26 |
+
if found: ids.append(found[1]);pos+=len(found[0]);continue
|
| 27 |
+
ends=[text.find(s,pos) for s in self.special_to_id if text.find(s,pos)>=0]; end=min(ends) if ends else len(text)
|
| 28 |
+
ids.extend(self.encode_bytes(text[pos:end].encode('utf8')));pos=end
|
| 29 |
+
return ([self.special_to_id['<bos>']] if add_bos else [])+ids+([self.special_to_id['<eos>']] if add_eos else [])
|
| 30 |
+
def decode(self, ids):
|
| 31 |
+
def expand(x):
|
| 32 |
+
if x < self.base: return b''
|
| 33 |
+
if x < self.base+256: return bytes([x-self.base])
|
| 34 |
+
a,b=self.merges[x-self.base-256]; return expand(a)+expand(b)
|
| 35 |
+
out=[];data=bytearray()
|
| 36 |
+
for x in ids:
|
| 37 |
+
if x < self.base:
|
| 38 |
+
if data: out.append(data.decode('utf8',errors='replace'));data.clear()
|
| 39 |
+
out.append(self.special_tokens[x])
|
| 40 |
+
else:data.extend(expand(x))
|
| 41 |
+
if data:out.append(data.decode('utf8',errors='replace'))
|
| 42 |
+
return ''.join(out)
|
| 43 |
+
def save(self,path): Path(path).parent.mkdir(parents=True,exist_ok=True);Path(path).write_text(json.dumps({'merges':self.merges,'special_tokens':self.special_tokens}))
|
| 44 |
+
@classmethod
|
| 45 |
+
def load(cls,path):
|
| 46 |
+
d=json.loads(Path(path).read_text());return cls(d['merges'],d['special_tokens'])
|
| 47 |
+
|
| 48 |
+
def train(files,vocab_size):
|
| 49 |
+
symbols=[len(SPECIAL)+b for b in b''.join(Path(p).read_bytes() for p in files)];merges=[]
|
| 50 |
+
while len(SPECIAL)+256+len(merges)<vocab_size:
|
| 51 |
+
pairs=collections.Counter(zip(symbols,symbols[1:]));
|
| 52 |
+
if not pairs:break
|
| 53 |
+
pair,n=pairs.most_common(1)[0]
|
| 54 |
+
if n<2:break
|
| 55 |
+
token=len(SPECIAL)+256+len(merges);merges.append(pair);new=[];i=0
|
| 56 |
+
while i<len(symbols):
|
| 57 |
+
if i+1<len(symbols) and (symbols[i],symbols[i+1])==pair:new.append(token);i+=2
|
| 58 |
+
else:new.append(symbols[i]);i+=1
|
| 59 |
+
symbols=new
|
| 60 |
+
return ByteBPETokenizer(merges)
|
| 61 |
+
|
| 62 |
+
def main():
|
| 63 |
+
p=argparse.ArgumentParser(); sub=p.add_subparsers(dest='cmd',required=True); t=sub.add_parser('train'); t.add_argument('--input',required=True);t.add_argument('--out',required=True);t.add_argument('--vocab-size',type=int,default=16000);a=p.parse_args()
|
| 64 |
+
files=list(Path(a.input).rglob('*.txt')); assert files, 'No .txt files found'; tok=train(files,a.vocab_size);tok.save(a.out);print(f'Saved {tok.vocab_size} tokens to {a.out}')
|
| 65 |
+
if __name__=='__main__': main()
|
ares/train.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse, math, random
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import torch
|
| 4 |
+
from torch.utils.data import Dataset,DataLoader
|
| 5 |
+
from .tokenizer import ByteBPETokenizer
|
| 6 |
+
from .config import AresConfig
|
| 7 |
+
from .model import AresTransformer
|
| 8 |
+
class Tokens(Dataset):
|
| 9 |
+
def __init__(self,root,tok,seq):
|
| 10 |
+
self.seq=seq; self.ids=[]
|
| 11 |
+
for p in Path(root).rglob('*.txt'):self.ids+=tok.encode(p.read_text(errors='ignore'),True,True)
|
| 12 |
+
def __len__(self):return max(0,(len(self.ids)-1)//self.seq)
|
| 13 |
+
def __getitem__(self,i):return torch.tensor(self.ids[i*self.seq:i*self.seq+self.seq+1],dtype=torch.long)
|
| 14 |
+
def main():
|
| 15 |
+
p=argparse.ArgumentParser();p.add_argument('--tokenizer',required=True);p.add_argument('--data',required=True);p.add_argument('--out',required=True);p.add_argument('--role',choices=('ares','xiphos'),default='ares');p.add_argument('--steps',type=int,default=1000);p.add_argument('--batch-size',type=int,default=2);p.add_argument('--seq-len',type=int,default=512);p.add_argument('--lr',type=float,default=3e-4);p.add_argument('--dim',type=int,default=512);p.add_argument('--layers',type=int,default=12);p.add_argument('--heads',type=int,default=8);p.add_argument('--kv-heads',type=int,default=2);a=p.parse_args()
|
| 16 |
+
tok=ByteBPETokenizer.load(a.tokenizer); c=AresConfig(vocab_size=tok.vocab_size,max_seq_len=a.seq_len,dim=a.dim,n_layers=a.layers,n_heads=a.heads,n_kv_heads=a.kv_heads); ds=Tokens(a.data,tok,a.seq_len);assert len(ds),'Not enough tokenized data';dl=iter(DataLoader(ds,batch_size=a.batch_size,shuffle=True,drop_last=True));dev='cuda' if torch.cuda.is_available() else 'cpu';m=AresTransformer(c).to(dev);opt=torch.optim.AdamW(m.parameters(),lr=a.lr,betas=(.9,.95),weight_decay=.1);Path(a.out).mkdir(parents=True,exist_ok=True)
|
| 17 |
+
for step in range(a.steps):
|
| 18 |
+
try:x=next(dl)
|
| 19 |
+
except StopIteration:dl=iter(DataLoader(ds,batch_size=a.batch_size,shuffle=True,drop_last=True));x=next(dl)
|
| 20 |
+
x=x.to(dev); _,loss,_=m(x[:,:-1],x);opt.zero_grad();loss.backward();torch.nn.utils.clip_grad_norm_(m.parameters(),1.0);opt.step()
|
| 21 |
+
if step%20==0:print(step,float(loss))
|
| 22 |
+
if step%500==0 and step:torch.save({'model':m.state_dict(),'config':c.to_dict(),'step':step,'role':a.role,'training_complete':False},Path(a.out)/'latest.pt')
|
| 23 |
+
torch.save({'model':m.state_dict(),'config':c.to_dict(),'step':a.steps,'role':a.role,'training_complete':False},Path(a.out)/'latest.pt')
|
| 24 |
+
if __name__=='__main__':main()
|
docs/ROADMAP.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ares engineering roadmap and review gates
|
| 2 |
+
|
| 3 |
+
## Corrections to the initial concept
|
| 4 |
+
|
| 5 |
+
- **128K vocabulary is not an early milestone.** It makes embedding/output matrices very large. Validate 8–16K first; grow only after corpus-language analysis.
|
| 6 |
+
- **8192 context is architecture-ready but not the first training length.** Attention is quadratic. Train 512/1024 first, then lengthen through a measured curriculum and RoPE validation.
|
| 7 |
+
- **Petabyte SQLite is unsuitable.** SQLite is for local metadata/profiles. Large corpora need immutable shards, an index, and separate metadata services.
|
| 8 |
+
- **RLHF requires human preference data and governance.** Start with SFT/evaluation; use DPO/RLHF only with consented data, reward evaluation, and rollback.
|
| 9 |
+
- Capability never justifies unrestricted execution: tool use is reviewed, sandboxed, and least-privilege.
|
| 10 |
+
|
| 11 |
+
## Phases
|
| 12 |
+
1. **Foundation (included):** local BPE, reference decoder transformer, causal loss/AdamW, corpus stream, checkpoint, SQLite memory, static UI.
|
| 13 |
+
2. **Data/evaluation:** dataset manifest with licence/provenance/hash, dedupe, PII filtering, held-out perplexity and safety/task evals. No automatic downloads.
|
| 14 |
+
3. **Scale:** mixed precision, gradient accumulation/checkpointing, distributed plan, token budget and hardware estimate. Compare 20M → 100M before proposing 1B.
|
| 15 |
+
4. **Post-training:** curated SFT and adversarial tests; preference governance before DPO/RLHF.
|
| 16 |
+
5. **RAG/tools:** retrieval from approved docs with citations. Xiphos only drafts plans; user approves each action.
|
| 17 |
+
6. **Deployment:** Static Space UI plus separately approved inference. Browser inference is optional and constrained by device RAM/download.
|
| 18 |
+
|
| 19 |
+
## Xiphos plan contract
|
| 20 |
+
Every plan states purpose, scope, files/data, licences, risks, tests, rollback, resource estimate, and proposed commands. It is never executable until explicit user approval, then runs only in a sandbox allowlist.
|
index.html
CHANGED
|
@@ -1,19 +1 @@
|
|
| 1 |
-
<!doctype html>
|
| 2 |
-
<html>
|
| 3 |
-
<head>
|
| 4 |
-
<meta charset="utf-8" />
|
| 5 |
-
<meta name="viewport" content="width=device-width" />
|
| 6 |
-
<title>My static Space</title>
|
| 7 |
-
<link rel="stylesheet" href="style.css" />
|
| 8 |
-
</head>
|
| 9 |
-
<body>
|
| 10 |
-
<div class="card">
|
| 11 |
-
<h1>Welcome to your static Space!</h1>
|
| 12 |
-
<p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
|
| 13 |
-
<p>
|
| 14 |
-
Also don't forget to check the
|
| 15 |
-
<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
|
| 16 |
-
</p>
|
| 17 |
-
</div>
|
| 18 |
-
</body>
|
| 19 |
-
</html>
|
|
|
|
| 1 |
+
<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Ares Lab</title><style>body{max-width:760px;margin:8vh auto;padding:24px;background:#081015;color:#e7f1ef;font:17px system-ui}h1{font-size:44px;margin-bottom:0}p,li{line-height:1.6;color:#b6c8c7}a,code{color:#65ddcf}section{border:1px solid #254047;padding:20px;border-radius:12px;margin:18px 0}.warning{color:#e4b653}</style><h1>Ares Lab</h1><p>From-scratch Ares & Xiphos training materials.</p><section><h2>Colab notebook</h2><p><a href="notebooks/ares_xiphos_training.ipynb">Download the Colab-compatible training notebook</a>. In Google Colab choose <b>File → Upload notebook</b>, select the downloaded file, then choose a GPU runtime.</p><p class="warning">The included run is a small wiring test—not a general AI. It produces unapproved checkpoints and does not expose a public API.</p></section><section><h2>Architecture</h2><ul><li>Ares: answer/assist role</li><li>Xiphos: separate weights; proposal-only role</li><li>No generated plan can execute code.</li><li>Use licensed, documented data only.</li></ul></section>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
notebooks/ares_xiphos_training.ipynb
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"nbformat": 4,
|
| 3 |
+
"nbformat_minor": 5,
|
| 4 |
+
"metadata": {
|
| 5 |
+
"colab": {
|
| 6 |
+
"name": "Ares_Xiphos_Training.ipynb",
|
| 7 |
+
"provenance": []
|
| 8 |
+
},
|
| 9 |
+
"kernelspec": {
|
| 10 |
+
"display_name": "Python 3",
|
| 11 |
+
"name": "python3"
|
| 12 |
+
},
|
| 13 |
+
"language_info": {
|
| 14 |
+
"name": "python"
|
| 15 |
+
}
|
| 16 |
+
},
|
| 17 |
+
"cells": [
|
| 18 |
+
{
|
| 19 |
+
"cell_type": "markdown",
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"source": [
|
| 22 |
+
"# Ares & Xiphos \u2014 Colab training smoke run\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"This notebook trains *from scratch*. It begins with a deliberately small validation model\u2014not a capable general model. Use only licensed, documented data. Ares and Xiphos receive separate weights and separate training runs.\n"
|
| 25 |
+
],
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"outputs": null
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"# In Colab: Runtime \u2192 Change runtime type \u2192 T4 GPU, if available.\n",
|
| 34 |
+
"!nvidia-smi || true\n",
|
| 35 |
+
"!python --version\n"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# Fetch public source. No token needed.\n",
|
| 45 |
+
"!rm -rf ares-lab\n",
|
| 46 |
+
"!git clone --depth 1 https://huggingface.co/spaces/jacmor64/Ares-Lab ares-lab\n",
|
| 47 |
+
"%cd ares-lab\n",
|
| 48 |
+
"!pip -q install torch tqdm\n"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Tiny licensed smoke corpus: validates plumbing only, not intelligence.\n",
|
| 58 |
+
"from pathlib import Path\n",
|
| 59 |
+
"Path('corpus').mkdir(exist_ok=True)\n",
|
| 60 |
+
"Path('corpus/smoke.txt').write_text('''Ares is a research language model. Ares answers questions clearly.\\nXiphos drafts plans for review. A plan is not execution.\\nSafety, consent, tests, and rollback matter.\\n''' * 500)\n",
|
| 61 |
+
"!python -m ares.tokenizer train --input corpus --out artifacts/tokenizer.json --vocab-size 512\n"
|
| 62 |
+
],
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"outputs": []
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"source": [
|
| 70 |
+
"# Tiny Ares run from random initialization.\n",
|
| 71 |
+
"!python -m ares.train --role ares --tokenizer artifacts/tokenizer.json --data corpus --out runs/ares-smoke --steps 100 --batch-size 4 --seq-len 128 --dim 128 --layers 4 --heads 4 --kv-heads 2 --lr 0.0003\n"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# Independently initialized Xiphos run. Production requires a separate reviewed planning/SFT corpus.\n",
|
| 81 |
+
"!python -m ares.train --role xiphos --tokenizer artifacts/tokenizer.json --data corpus --out runs/xiphos-smoke --steps 100 --batch-size 4 --seq-len 128 --dim 128 --layers 4 --heads 4 --kv-heads 2 --lr 0.0003\n"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# Check architecture tests. Smoke checkpoints remain unapproved: training_complete=false.\n",
|
| 91 |
+
"!python -m unittest discover -s tests -v\n"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# Optional local-only runtime; do not expose it publicly without authentication, rate limits, and review.\n",
|
| 101 |
+
"# !python -m ares.server --ares runs/ares-smoke/latest.pt --xiphos runs/xiphos-smoke/latest.pt --tokenizer artifacts/tokenizer.json\n"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
}
|
| 106 |
+
]
|
| 107 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.2
|
| 2 |
+
tqdm>=4.66
|
tests/test_smoke.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest, torch
|
| 2 |
+
from ares.config import AresConfig
|
| 3 |
+
from ares.model import AresTransformer
|
| 4 |
+
from ares.tokenizer import ByteBPETokenizer
|
| 5 |
+
class TestAres(unittest.TestCase):
|
| 6 |
+
def test_tokenizer_roundtrip(self):
|
| 7 |
+
t=ByteBPETokenizer();s='<user>Hello, Ares! 🌍<assistant>';self.assertEqual(t.decode(t.encode(s)),s)
|
| 8 |
+
def test_transformer_shapes_and_cache(self):
|
| 9 |
+
c=AresConfig(vocab_size=64,max_seq_len=16,dim=32,n_layers=2,n_heads=4,n_kv_heads=2);m=AresTransformer(c);x=torch.randint(0,64,(2,8));logits,loss,cache=m(x,x);self.assertEqual(logits.shape,(2,8,64));self.assertTrue(torch.isfinite(loss));self.assertEqual(len(cache),2)
|
| 10 |
+
if __name__=='__main__':unittest.main()
|