diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..90e7c927da32b06949c8ea8a59a5c7463acdae36 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM nvcr.io/nvidia/pytorch:24.01-py3 + +WORKDIR /app + +RUN pip install --no-cache-dir datasets huggingface_hub + +COPY src/ /app/src/ +COPY experiments/ /app/experiments/ +COPY train_gpu.py /app/train_gpu.py + +CMD ["python", "train_gpu.py"] diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..04c343a7f0df01c6d81602b2e002c7604debcc90 --- /dev/null +++ b/README.md @@ -0,0 +1,107 @@ +# PC-SHO-DLM + +**Predictive-Coding Diffusion Language Models with Precision-Conditioned Second-Order Settling** + +## Overview + +PC-SHO-DLM is a research architecture that unifies three individually mature research threads: + +1. **Masked discrete diffusion** for iterative text denoising +2. **Predictive coding** for local error-driven inference and learning +3. **Second-order dynamical systems** for accelerated latent settling + +The core insight: diffusion denoising and predictive coding are both iterative residual-correction procedures, making diffusion a structurally natural host for predictive-coding-based language modeling. + +## Key Contributions + +- **Bidirectional predictive transformer** with both bottom-up and top-down pathways +- **Precision-conditioned second-order settling** (damped inertial dynamics with learned uncertainty) +- **State continuation across diffusion steps** (warm-start from previous denoising step) +- **Tokenwise adaptive settling** (selective compute allocation to uncertain tokens) +- **Globally backpropagation-free training** via local prediction-error-driven updates + +## Theoretical Results + +| Theorem | Result | +|---------|--------| +| **A: Reduced-objective exactness** | Local post-settling updates = exact gradients via envelope theorem | +| **B: Accelerated settling** | O(sqrt(kappa)) vs O(kappa) microsteps over first-order PC | +| **C: Warm-start tracking** | Settling cost depends on inter-step drift, not full re-solve | +| **D: Precision optimality** | GLS-optimal under heteroscedastic prediction errors | + +## Project Structure + +``` +pc-sho-dlm/ +├── paper/ +│ ├── main.tex # Full LaTeX manuscript +│ └── references.bib # Bibliography +├── src/ +│ ├── model.py # Core PC-SHO-DLM architecture +│ └── train.py # Training loop (local + backprop modes) +├── experiments/ +│ ├── ablation_runner.py # Ablation study runner +│ └── settling_analysis.py # Settling dynamics analysis +└── README.md +``` + +## Quick Start + +### Sanity Check +```bash +cd src +python model.py +``` + +### Train (Local PC mode) +```bash +python src/train.py --mode local --device cpu --max_steps 5000 +``` + +### Train (Backprop baseline) +```bash +python src/train.py --mode backprop --device cpu --max_steps 5000 +``` + +### Run Ablations +```bash +python experiments/ablation_runner.py --device cpu +``` + +### Analyze Settling Dynamics +```bash +python experiments/settling_analysis.py --device cpu +``` + +## Experimental Program + +### Stage 1: Proof of Mechanism (20M-100M params) +- Character/subword corpora (text8, enwik8, WikiText-103) +- Establish second-order PC is more compute-efficient than first-order PC + +### Stage 2: Medium Scale (100M-1B params) +- Open web corpus subset +- Compare against backprop-trained masked diffusion + +### Stage 3: Structured Generation +- Infilling, editing, code completion +- Test selective settling and state continuation + +## Falsification Criteria + +This proposal should be judged a failure if: +1. Second-order settling does not reduce required microsteps +2. Local learning creates an irrecoverable quality gap vs backprop +3. Precision heads fail to calibrate +4. Dynamics frequently enter limit cycles +5. State continuation does not materially reduce compute + +## Citation + +```bibtex +@article{pcshodlm2026, + title={PC-SHO-DLM: Predictive-Coding Diffusion Language Models + with Precision-Conditioned Second-Order Settling}, + year={2026} +} +``` diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe6ee65a9eb0857146112ba06470f208c6b5074 --- /dev/null +++ b/app.py @@ -0,0 +1,265 @@ +""" +PC-SHO-DLM A100 Training — HuggingFace Spaces +Runs all 3 training modes and displays results via Gradio. +""" + +import json +import os +import sys +import threading +import time + +import gradio as gr +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +# Import model +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + + +# ============================================================================= +# Dataset +# ============================================================================= + +class CharLevelDataset(Dataset): + def __init__(self, text, seq_len, vocab_size=257): + self.seq_len = seq_len + self.data = torch.tensor( + [min(b + 1, vocab_size - 1) for b in text.encode("utf-8")], dtype=torch.long + ) + self.n_seqs = max(1, (len(self.data) - seq_len) // seq_len) + + def __len__(self): + return self.n_seqs + + def __getitem__(self, idx): + start = idx * self.seq_len + return {"input_ids": self.data[start : start + self.seq_len]} + + +# ============================================================================= +# Training +# ============================================================================= + +TRAINING_LOG = [] +CURRENT_STATUS = "Idle" + + +def train_one_mode(mode, config, train_ds, val_ds, max_steps=10000, batch_size=64, lr=3e-4): + global CURRENT_STATUS, TRAINING_LOG + + device = "cuda" if torch.cuda.is_available() else "cpu" + CURRENT_STATUS = f"Training {mode} on {device}..." + TRAINING_LOG.append(f"\n{'='*60}") + TRAINING_LOG.append(f"Mode: {mode} | Params: {count_parameters(PCSHODLM(config)):,} | Device: {device}") + TRAINING_LOG.append(f"{'='*60}") + + model = PCSHODLM(config).to(device) + model.train() + + train_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True, drop_last=True, + num_workers=4 if device == "cuda" else 0, pin_memory=device == "cuda") + val_loader = DataLoader(val_ds, batch_size=batch_size, shuffle=False, + num_workers=2 if device == "cuda" else 0, pin_memory=device == "cuda") + + if mode == "backprop": + optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_steps, eta_min=lr * 0.1) + elif mode == "local": + updater = LocalParameterUpdater(model, lr_forward=lr, lr_feedback=lr, lr_readout=lr, lr_precision=lr * 0.1) + + log = {"mode": mode, "steps": [], "losses": [], "energies": [], "val_losses": []} + step = 0 + start = time.time() + + while step < max_steps: + for batch in train_loader: + if step >= max_steps: + break + x_0 = batch["input_ids"].to(device) + + if mode == "backprop": + optimizer.zero_grad() + out = model(x_0) + loss = out["loss"] + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + optimizer.step() + scheduler.step() + loss_val = loss.item() + energies = out["energies"] + elif mode == "local": + result = updater.step({"input_ids": x_0}) + loss_val = result.get("loss", 0.0) + energies = result.get("energies", []) + elif mode == "unified": + B, S = x_0.shape + t = torch.randint(1, config.n_diffusion_steps + 1, (B,), device=device) + x_t, mask = model.schedule.corrupt(x_0, t, config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + h_s, _, energies = model.unified_settle(h_init, x_0, mask, t, param_lr_scale=0.005) + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_s[-1])) + ml, mt = logits[mask], x_0[mask] + loss_val = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0 + + step += 1 + + if step % 200 == 0: + elapsed = time.time() - start + tps = (step * batch_size * config.max_seq_len) / elapsed + energy_str = f"{energies[-1]:.0f}" if energies else "N/A" + msg = f"[{mode}] Step {step:6d} | Loss: {loss_val:.4f} | Energy: {energy_str} | Tok/s: {tps:.0f} | {elapsed:.0f}s" + TRAINING_LOG.append(msg) + log["steps"].append(step) + log["losses"].append(loss_val) + log["energies"].append(energies[-1] if energies else 0) + + if step % 2000 == 0: + model.eval() + tl, tt = 0.0, 0 + with torch.no_grad(): + for vb in val_loader: + vx = vb["input_ids"].to(device) + vo = model(vx) + nm = vo["mask"].sum().item() + if nm > 0: + tl += vo["loss"].item() * nm + tt += nm + if tt > 100000: + break + vl = tl / max(1, tt) + TRAINING_LOG.append(f" --> [{mode}] Val loss: {vl:.4f}") + log["val_losses"].append((step, vl)) + model.train() + + elapsed = time.time() - start + # Final val + model.eval() + tl, tt = 0.0, 0 + with torch.no_grad(): + for vb in val_loader: + vx = vb["input_ids"].to(device) + vo = model(vx) + nm = vo["mask"].sum().item() + if nm > 0: + tl += vo["loss"].item() * nm + tt += nm + if tt > 200000: + break + final_val = tl / max(1, tt) + log["final_val_loss"] = final_val + msg = f"[{mode}] DONE: {step} steps in {elapsed:.0f}s | Final val loss: {final_val:.4f}" + TRAINING_LOG.append(msg) + + # Save checkpoint + os.makedirs("results", exist_ok=True) + torch.save({"model": model.state_dict(), "config": config, "log": log}, f"results/{mode}_10k.pt") + + return log + + +def run_all_training(): + global CURRENT_STATUS, TRAINING_LOG + TRAINING_LOG = ["Starting PC-SHO-DLM A100 Training..."] + + device = "cuda" if torch.cuda.is_available() else "cpu" + TRAINING_LOG.append(f"Device: {device}") + if device == "cuda": + TRAINING_LOG.append(f"GPU: {torch.cuda.get_device_name()}") + TRAINING_LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB") + + # A100-optimized config + config = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, + n_layers=12, d_ff=2048, n_diffusion_steps=128, n_settling_steps=6, + mask_token_id=0, dropout=0.1, feedback_rank=128, + ) + TRAINING_LOG.append(f"Model: d={config.d_model}, L={config.n_layers}, ~{count_parameters(PCSHODLM(config)):,} params") + + # Load data + CURRENT_STATUS = "Loading WikiText-103..." + from datasets import load_dataset + ds_train = load_dataset("wikitext", "wikitext-103-raw-v1", split="train") + ds_val = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + train_text = "\n".join([r["text"] for r in ds_train if r["text"].strip()])[:100_000_000] + val_text = "\n".join([r["text"] for r in ds_val if r["text"].strip()]) + train_ds = CharLevelDataset(train_text, config.max_seq_len) + val_ds = CharLevelDataset(val_text, config.max_seq_len) + TRAINING_LOG.append(f"Data: {len(train_text):,} train chars, {len(val_text):,} val chars") + + results = {} + for mode in ["backprop", "local", "unified"]: + results[mode] = train_one_mode(mode, config, train_ds, val_ds, max_steps=10000, batch_size=64) + + # Final summary + TRAINING_LOG.append(f"\n{'='*60}") + TRAINING_LOG.append("FINAL RESULTS") + TRAINING_LOG.append(f"{'='*60}") + for mode, log in results.items(): + TRAINING_LOG.append(f"{mode:15s} | Val loss: {log.get('final_val_loss', 'N/A')}") + + CURRENT_STATUS = "Complete!" + + # Upload results + try: + from huggingface_hub import HfApi + api = HfApi() + with open("results/results.json", "w") as f: + json.dump(results, f, indent=2) + api.upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-train", + repo_type="space", path_in_repo="results") + TRAINING_LOG.append("Results uploaded to HuggingFace!") + except Exception as e: + TRAINING_LOG.append(f"Upload error: {e}") + + +# ============================================================================= +# Gradio UI +# ============================================================================= + +training_thread = None + + +def start_training(): + global training_thread + if training_thread and training_thread.is_alive(): + return "Training already running!" + training_thread = threading.Thread(target=run_all_training, daemon=True) + training_thread.start() + return "Training started on A100!" + + +def get_log(): + return "\n".join(TRAINING_LOG[-50:]) + + +def get_status(): + return CURRENT_STATUS + + +with gr.Blocks(title="PC-SHO-DLM Training") as demo: + gr.Markdown("# PC-SHO-DLM: Predictive-Coding Diffusion LM — A100 Training") + gr.Markdown("Trains 3 modes (backprop, local PC, unified) on WikiText-103 with ~50M params") + + with gr.Row(): + start_btn = gr.Button("Start Training", variant="primary") + status = gr.Textbox(label="Status", value="Idle") + + log_box = gr.Textbox(label="Training Log", lines=25, max_lines=50) + + refresh_btn = gr.Button("Refresh Log") + + start_btn.click(start_training, outputs=status) + refresh_btn.click(get_log, outputs=log_box) + refresh_btn.click(get_status, outputs=status) + + # Auto-refresh via Timer + timer = gr.Timer(5) + timer.tick(get_log, outputs=log_box) + timer.tick(get_status, outputs=status) + +demo.launch() diff --git a/app_backprop_wiki.py b/app_backprop_wiki.py new file mode 100644 index 0000000000000000000000000000000000000000..f67816a698ec13a5eee11fb602a90f20c786fafe --- /dev/null +++ b/app_backprop_wiki.py @@ -0,0 +1,120 @@ +"""FAIR BACKPROP BASELINE — WikiText-103 in memory, standard masked diffusion LM.""" +import json, os, sys, threading, time +import gradio as gr +import torch, torch.nn as nn, torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHOConfig, MaskDiffusionSchedule, BidirectionalTransformerBlock + +class StandardMaskedDiffusionLM(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.token_embed = nn.Embedding(config.vocab_size, config.d_model) + self.pos_embed = nn.Embedding(config.max_seq_len, config.d_model) + self.time_embed = nn.Embedding(config.n_diffusion_steps + 1, config.d_model) + self.layers = nn.ModuleList([ + BidirectionalTransformerBlock(config.d_model, config.n_heads, config.d_ff, config.dropout) + for _ in range(config.n_layers) + ]) + self.readout_norm = nn.LayerNorm(config.d_model) + self.readout = nn.Linear(config.d_model, config.vocab_size, bias=False) + self.schedule = MaskDiffusionSchedule(config.n_diffusion_steps) + + def forward(self, x_0, t=None): + B, S = x_0.shape; device = x_0.device + if t is None: t = torch.randint(1, self.config.n_diffusion_steps + 1, (B,), device=device) + x_t, mask = self.schedule.corrupt(x_0, t, self.config.mask_token_id) + positions = torch.arange(S, device=device).unsqueeze(0) + h = self.token_embed(x_t) + self.pos_embed(positions) + self.time_embed(t).unsqueeze(1) + for layer in self.layers: h = layer(h) + logits = self.readout(self.readout_norm(h)) + ml, mt = logits[mask], x_0[mask] + loss = F.cross_entropy(ml, mt) if ml.numel() > 0 else torch.tensor(0.0, device=device) + return {"loss": loss, "mask": mask} + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1,(len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG = [f"FAIR BACKPROP | Device: {dev}"] + if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + cfg = PCSHOConfig(vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048, n_diffusion_steps=128, mask_token_id=0, dropout=0.1) + + STATUS = "Loading WikiText-103 into memory..." + from datasets import load_dataset + ds = load_dataset("wikitext", "wikitext-103-raw-v1", split="train") + dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + train_text = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000] + val_text = "\n".join([r["text"] for r in dv if r["text"].strip()]) + train_ds = CharDS(train_text, cfg.max_seq_len); val_ds = CharDS(val_text, cfg.max_seq_len) + LOG.append(f"Data: {len(train_text):,} train chars, {len(val_text):,} val chars IN MEMORY") + + model = StandardMaskedDiffusionLM(cfg).to(dev) + n_params = sum(p.numel() for p in model.parameters() if p.requires_grad) + LOG.append(f"Model: {n_params:,} params | NO settling, NO PC, pure backprop") + model.train() + + opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10000, eta_min=3e-5) + tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True) + + STATUS = "Training..." + LOG.append(f"\n{'='*60}\nFAIR BACKPROP | {n_params:,} params\n{'='*60}") + step, start, mx = 0, time.time(), 10000 + + while step < mx: + for batch in tl: + if step >= mx: break + x0 = batch["input_ids"].to(dev) + opt.zero_grad(); out = model(x0); loss = out["loss"]; loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step(); sched.step() + step += 1; lv = loss.item() + if step % 100 == 0: + el = time.time()-start; tps = step*64*cfg.max_seq_len/el + LOG.append(f"[fair-bp] Step {step:6d} | Loss: {lv:.4f} | Tok/s: {tps:.0f} | {el:.0f}s") + if step % 2000 == 0: + model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>100000: break + LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); model.train() + + model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>200000: break + LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s | Val: {tl2/max(1,tt2):.4f}") + STATUS = "Complete!" + os.makedirs("results",exist_ok=True) + torch.save({"model":model.state_dict(),"config":cfg},"results/fair_backprop.pt") + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!" + +with gr.Blocks(title="Fair Backprop") as demo: + gr.Markdown("# FAIR BACKPROP — WikiText-103 in memory") + with gr.Row(): + btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle") + log=gr.Textbox(label="Log",lines=30); btn.click(start,outputs=st) + r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-60:]),outputs=log); r.click(lambda:STATUS,outputs=st) + t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-60:]),outputs=log); t.tick(lambda:STATUS,outputs=st) +demo.launch() diff --git a/app_chat_a100.py b/app_chat_a100.py new file mode 100644 index 0000000000000000000000000000000000000000..3e5408facf27daa5c54058a6889b2eea1e4e44da --- /dev/null +++ b/app_chat_a100.py @@ -0,0 +1,192 @@ +"""PC-SHO-DLM Chat Training on A100 — HONEST settling, large model, big dataset.""" +import json, os, sys, threading, time, math, urllib.request +import gradio as gr +import torch, torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + +class DialogueDataset(Dataset): + def __init__(self, pairs, max_seq_len, vocab_size=257): + self.samples = [] + sep = [0x0A, 0x0A] + for prompt, response in pairs: + p = [min(b+1, vocab_size-1) for b in prompt.encode("utf-8")] + r = [min(b+1, vocab_size-1) for b in response.encode("utf-8")] + s = [min(b+1, vocab_size-1) for b in bytes(sep)] + max_p = int(max_seq_len * 0.4) + p = p[:max_p]; max_r = max_seq_len - len(p) - len(s); r = r[:max_r] + full = p + s + r + pl = len(p) + len(s) + if len(full) < max_seq_len: full += [0] * (max_seq_len - len(full)) + self.samples.append({"input_ids": torch.tensor(full[:max_seq_len], dtype=torch.long), "prompt_len": pl, "response_len": len(r)}) + def __len__(self): return len(self.samples) + def __getitem__(self, i): return self.samples[i] + +def conditional_corrupt(x_0, t, mask_id, schedule, prompt_lens): + B, S = x_0.shape + mask_prob = schedule.mask_rate(t).unsqueeze(-1) + random_mask = torch.rand_like(x_0.float()) < mask_prob + response_mask = torch.zeros_like(x_0, dtype=torch.bool) + for b in range(B): response_mask[b, prompt_lens[b]:] = True + mask = random_mask & response_mask + x_t = x_0.clone(); x_t[mask] = mask_id + return x_t, mask + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG = [f"PC-SHO-DLM CHAT | HONEST SETTLING | {dev}"] + if dev == "cuda": + LOG.append(f"GPU: {torch.cuda.get_device_name()} | {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + # Bigger model for A100 + cfg = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048, + n_diffusion_steps=64, n_settling_steps=6, mask_token_id=0, dropout=0.1, + feedback_rank=128, denoising_lambda=5.0, + homeostatic_target=0.0, lateral_inhibition=0.0, + ) + + STATUS = "Loading Alpaca + Dolly datasets..." + pairs = [] + + # Alpaca + try: + url = "https://raw.githubusercontent.com/tatsu-lab/stanford_alpaca/main/alpaca_data.json" + LOG.append("Downloading Alpaca...") + with urllib.request.urlopen(url) as r: + data = json.loads(r.read()) + for row in data: + inst = row.get("instruction",""); inp = row.get("input",""); out = row.get("output","") + p = f"{inst}\n{inp}".strip() if inp else inst + if p and out: pairs.append((p, out)) + LOG.append(f"Alpaca: {len(pairs)} pairs") + except Exception as e: + LOG.append(f"Alpaca failed: {e}") + + # Dolly + try: + from datasets import load_dataset + ds = load_dataset("databricks/dolly-15k", split="train") + n_before = len(pairs) + for row in ds: + p = row.get("instruction","") or row.get("context","") + r = row.get("response","") + if p and r: pairs.append((p, r)) + LOG.append(f"Dolly: {len(pairs) - n_before} pairs") + except Exception as e: + LOG.append(f"Dolly failed: {e}") + + LOG.append(f"Total: {len(pairs)} dialogue pairs") + + n_val = max(1, len(pairs) // 20) + train_ds = DialogueDataset(pairs[n_val:], cfg.max_seq_len) + val_ds = DialogueDataset(pairs[:n_val], cfg.max_seq_len) + LOG.append(f"Train: {len(train_ds)}, Val: {len(val_ds)}") + + model = PCSHODLM(cfg).to(dev); model.train() + n_params = count_parameters(model) + LOG.append(f"Model: {n_params:,} params | HONEST settling (entropy, no peeking)") + + updater = LocalParameterUpdater(model, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5) + tl = DataLoader(train_ds, batch_size=32, shuffle=True, drop_last=True, num_workers=4, pin_memory=True) + + STATUS = "Training..." + LOG.append(f"\n{'='*60}\nCHAT TRAINING | {n_params:,} params | honest settling\n{'='*60}") + step, start, mx = 0, time.time(), 10000 + K_max = cfg.n_settling_steps + + while step < mx: + for batch in tl: + if step >= mx: break + x_0 = batch["input_ids"].to(dev) + prompt_lens = batch["prompt_len"]; B, S = x_0.shape + + K_curr = max(3, int(K_max * min(1.0, step / 1000))) + model.config.n_settling_steps = K_curr + t = torch.randint(1, cfg.n_diffusion_steps+1, (B,), device=dev) + x_t, mask = conditional_corrupt(x_0, t, cfg.mask_token_id, model.schedule, prompt_lens) + + # HONEST SETTLE: x_t not x_0 + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + with torch.no_grad(): + h_settled, _, energies, _, _ = model.settle(h_init, x_t, mask, t) + + # Local updates + L = cfg.n_layers + for l in range(L): + updater.forward_optimizers[l].zero_grad() + mu_up = model.forward_blocks[l](h_settled[l].detach()) + with torch.no_grad(): tok_p, ch_p = model.precision_up[l](h_settled[l+1].detach(), t) + eps = h_settled[l+1].detach() - mu_up + (0.5*(eps*tok_p*ch_p*eps).sum()/B).backward() + updater.forward_optimizers[l].step() + + for l in range(L-1): + updater.feedback_optimizers[l].zero_grad() + mu_down = model.feedback_blocks[l](h_settled[l+2].detach()) + with torch.no_grad(): tok_p, ch_p = model.precision_down[l](h_settled[l+1].detach(), t) + eps = h_settled[l+1].detach() - mu_down + (0.5*(eps*tok_p*ch_p*eps).sum()/B).backward() + updater.feedback_optimizers[l].step() + + # Readout — this uses x_0 targets (learning signal) + updater.readout_optimizer.zero_grad() + logits = model.readout(model.readout_norm(h_settled[L].detach())) + ml, mt = logits[mask], x_0[mask] + if ml.numel() > 0: + loss = F.cross_entropy(ml, mt); loss.backward() + updater.readout_optimizer.step(); lv = loss.item() + else: lv = 0 + + # Embeddings + updater.embed_optimizer.zero_grad() + with torch.enable_grad(): + h0f = model.embed_input(x_t, t); hif = model.amortized_forward_pass(h0f) + lf = model.readout(model.readout_norm(hif[L])) + mlf, mtf = lf[mask], x_0[mask] + if mlf.numel() > 0: + el = F.cross_entropy(mlf, mtf); el.backward() + torch.nn.utils.clip_grad_norm_(list(model.token_embed.parameters())+list(model.pos_embed.parameters())+list(model.time_embed.parameters()), 1.0) + updater.embed_optimizer.step() + + step += 1 + if step % 50 == 0: + el = time.time()-start; tps = step*32*cfg.max_seq_len/el + e = f"{energies[-1]:.0f}" if energies else "N/A" + LOG.append(f"Step {step:5d} | Loss: {lv:.4f} | Energy: {e} | K={K_curr} | Tok/s: {tps:.0f} | {el:.0f}s") + if step % 1000 == 0: + os.makedirs("results", exist_ok=True) + torch.save({"model_state_dict": model.state_dict(), "config": cfg, "step": step}, f"results/chat_step{step}.pt") + + os.makedirs("results", exist_ok=True) + torch.save({"model_state_dict": model.state_dict(), "config": cfg}, "results/chat_final.pt") + LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s") + STATUS = "Complete!" + + try: + from huggingface_hub import HfApi + HfApi().upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-local-pc-wiki", repo_type="space", path_in_repo="results") + LOG.append("Results uploaded!") + except: pass + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!" + +with gr.Blocks(title="PC-SHO-DLM Chat") as demo: + gr.Markdown("# PC-SHO-DLM Chat Training (A100) — HONEST Settling") + gr.Markdown("Entropy-based settling (no peeking at answers). Alpaca + Dolly data.") + with gr.Row(): + btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle") + log=gr.Textbox(label="Log",lines=35); btn.click(start,outputs=st) + r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-70:]),outputs=log); r.click(lambda:STATUS,outputs=st) + t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-70:]),outputs=log); t.tick(lambda:STATUS,outputs=st) +demo.launch() diff --git a/app_fair_backprop.py b/app_fair_backprop.py new file mode 100644 index 0000000000000000000000000000000000000000..b34583b099ed503c02b23c5a7814ddbf13a1009b --- /dev/null +++ b/app_fair_backprop.py @@ -0,0 +1,234 @@ +"""PC-SHO-DLM: FAIR BACKPROP BASELINE +Standard masked diffusion LM — same architecture but NO settling loop. +Single forward pass through the transformer + backprop on masked token loss. +This is the proper baseline to compare against Local PC. +""" +import json, os, sys, threading, time, math +import gradio as gr +import torch, torch.nn as nn, torch.nn.functional as F +from torch.utils.data import DataLoader, IterableDataset, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHOConfig, MaskDiffusionSchedule, BidirectionalTransformerBlock, count_parameters + + +# ============================================================================= +# Standard Masked Diffusion Transformer (NO predictive coding, NO settling) +# ============================================================================= + +class StandardMaskedDiffusionLM(nn.Module): + """Standard masked diffusion LM baseline. + + Same transformer architecture as PC-SHO-DLM but: + - Single forward pass (no settling loop) + - Standard backprop through all layers + - No predictive coding energy, no precision heads, no feedback blocks + - Same masked token denoising objective + """ + + def __init__(self, config: PCSHOConfig): + super().__init__() + self.config = config + + self.token_embed = nn.Embedding(config.vocab_size, config.d_model) + self.pos_embed = nn.Embedding(config.max_seq_len, config.d_model) + self.time_embed = nn.Embedding(config.n_diffusion_steps + 1, config.d_model) + + # Same transformer blocks as PC-SHO-DLM forward path + self.layers = nn.ModuleList([ + BidirectionalTransformerBlock(config.d_model, config.n_heads, config.d_ff, config.dropout) + for _ in range(config.n_layers) + ]) + + self.readout_norm = nn.LayerNorm(config.d_model) + self.readout = nn.Linear(config.d_model, config.vocab_size, bias=False) + self.schedule = MaskDiffusionSchedule(config.n_diffusion_steps) + + def forward(self, x_0, t=None): + B, S = x_0.shape + device = x_0.device + + if t is None: + t = torch.randint(1, self.config.n_diffusion_steps + 1, (B,), device=device) + + x_t, mask = self.schedule.corrupt(x_0, t, self.config.mask_token_id) + + # Single forward pass — no settling + positions = torch.arange(S, device=device).unsqueeze(0) + h = self.token_embed(x_t) + self.pos_embed(positions) + self.time_embed(t).unsqueeze(1) + + for layer in self.layers: + h = layer(h) + + logits = self.readout(self.readout_norm(h)) + mask_logits = logits[mask] + mask_targets = x_0[mask] + + if mask_logits.numel() > 0: + loss = F.cross_entropy(mask_logits, mask_targets) + else: + loss = torch.tensor(0.0, device=device) + + return {"loss": loss, "logits": logits, "mask": mask} + + +# ============================================================================= +# Data +# ============================================================================= + +class StreamDS(IterableDataset): + def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None): + self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok + def __iter__(self): + from datasets import load_dataset + ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True, trust_remote_code=True) + buf, tot = [], 0 + for item in ds: + t = item.get("text", "") + if not t or not t.strip(): continue + buf.extend([min(b+1, self.voc-1) for b in t.encode("utf-8")]) + while len(buf) >= self.seq_len: + yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)} + buf = buf[self.seq_len:]; tot += self.seq_len + if self.max_tok and tot > self.max_tok: return + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1,(len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + + +# ============================================================================= +# Training +# ============================================================================= + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + LOG = ["=" * 70] + LOG.append("FAIR BACKPROP BASELINE") + LOG.append("Standard masked diffusion LM — NO settling, NO PC, pure backprop") + LOG.append("Same transformer architecture, same data, same hyperparameters") + LOG.append("=" * 70) + + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG.append(f"Device: {dev}") + if dev == "cuda": + LOG.append(f"GPU: {torch.cuda.get_device_name()}") + LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + # Same architecture as PC-SHO-DLM but without PC overhead + cfg = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, + n_layers=12, d_ff=2048, n_diffusion_steps=128, + mask_token_id=0, dropout=0.1, + ) + + model = StandardMaskedDiffusionLM(cfg).to(dev) + n_params = sum(p.numel() for p in model.parameters() if p.requires_grad) + LOG.append(f"Model: {n_params:,} params (d={cfg.d_model}, L={cfg.n_layers})") + LOG.append("NO settling loop, NO precision heads, NO feedback blocks") + LOG.append("Pure single-forward-pass + backprop") + + STATUS = "Loading data..." + from datasets import load_dataset + dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len) + train_ds = StreamDS("wikitext", "wikitext-103-raw-v1", "train", cfg.max_seq_len, max_tok=500_000_000) + LOG.append("Data: WikiText-103 streaming (500M tokens)") + + model.train() + opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10000, eta_min=3e-5) + tl = DataLoader(train_ds, batch_size=64, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True) + + STATUS = "Training FAIR BACKPROP..." + LOG.append(f"\n{'='*70}") + LOG.append(f"FAIR BACKPROP | {n_params:,} params | Single forward pass") + LOG.append(f"{'='*70}") + + step, start, mx = 0, time.time(), 10000 + log_d = {"steps": [], "losses": []} + + for batch in tl: + if step >= mx: break + x0 = batch["input_ids"].to(dev) + + opt.zero_grad() + out = model(x0) + loss = out["loss"] + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + sched.step() + + step += 1 + lv = loss.item() + + if step % 100 == 0: + el = time.time() - start + tps = step * 64 * cfg.max_seq_len / el + msg = f"[fair-bp] Step {step:6d} | Loss: {lv:.4f} | Tok/s: {tps:.0f} | {el:.0f}s" + LOG.append(msg) + log_d["steps"].append(step) + log_d["losses"].append(lv) + + if step % 2000 == 0: + model.eval() + tl2, tt2 = 0., 0 + with torch.no_grad(): + for vb in vl: + vo = model(vb["input_ids"].to(dev)) + nm = vo["mask"].sum().item() + if nm > 0: tl2 += vo["loss"].item() * nm; tt2 += nm + if tt2 > 100000: break + vl2 = tl2 / max(1, tt2) + LOG.append(f" --> Val: {vl2:.4f}") + log_d.setdefault("val", []).append((step, vl2)) + model.train() + + model.eval() + tl2, tt2 = 0., 0 + with torch.no_grad(): + for vb in vl: + vo = model(vb["input_ids"].to(dev)) + nm = vo["mask"].sum().item() + if nm > 0: tl2 += vo["loss"].item() * nm; tt2 += nm + if tt2 > 200000: break + fv = tl2 / max(1, tt2) + log_d["final_val"] = fv + elapsed = time.time() - start + LOG.append(f"\nDONE: {step} steps in {elapsed:.0f}s | Final val: {fv:.4f}") + LOG.append(f"Tok/s: {step*64*cfg.max_seq_len/elapsed:.0f}") + STATUS = "Complete!" + + os.makedirs("results", exist_ok=True) + torch.save({"model": model.state_dict(), "config": cfg, "log": log_d}, "results/fair_backprop.pt") + try: + from huggingface_hub import HfApi + HfApi().upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-fair-backprop", + repo_type="space", path_in_repo="results") + LOG.append("Uploaded!") + except: pass + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start() + return "FAIR BACKPROP started on A100!" + +with gr.Blocks(title="Fair Backprop") as demo: + gr.Markdown("# FAIR BACKPROP BASELINE (A100)") + gr.Markdown("Standard masked diffusion LM — NO settling, NO PC. Same arch, pure backprop.") + with gr.Row(): + btn = gr.Button("Start", variant="primary"); st = gr.Textbox(label="Status", value="Idle") + log = gr.Textbox(label="Log", lines=30) + btn.click(start, outputs=st) + r = gr.Button("Refresh"); r.click(lambda: "\n".join(LOG[-60:]), outputs=log); r.click(lambda: STATUS, outputs=st) + t = gr.Timer(5); t.tick(lambda: "\n".join(LOG[-60:]), outputs=log); t.tick(lambda: STATUS, outputs=st) +demo.launch() diff --git a/app_local.py b/app_local.py new file mode 100644 index 0000000000000000000000000000000000000000..3f965bf863d0c91fd5ce282f7c17deadb562c337 --- /dev/null +++ b/app_local.py @@ -0,0 +1,120 @@ +"""PC-SHO-DLM: LOCAL PC Training on A100 — Single mode, fast.""" +import json, os, sys, threading, time +import gradio as gr +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + +class CharDS(Dataset): + def __init__(self, text, seq_len): + self.seq_len = seq_len + self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1, (len(self.data)-seq_len)//seq_len) + def __len__(self): return self.n + def __getitem__(self, i): + return {"input_ids": self.data[i*self.seq_len:(i+1)*self.seq_len]} + +LOG = [] +STATUS = "Idle" + +def train(): + global STATUS, LOG + LOG = ["Starting LOCAL PC training on A100..."] + device = "cuda" if torch.cuda.is_available() else "cpu" + LOG.append(f"Device: {device}") + if device == "cuda": + LOG.append(f"GPU: {torch.cuda.get_device_name()}") + LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + config = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, + n_layers=12, d_ff=2048, n_diffusion_steps=128, n_settling_steps=6, + mask_token_id=0, dropout=0.1, feedback_rank=128, + ) + LOG.append(f"Model: {count_parameters(PCSHODLM(config)):,} params") + + STATUS = "Loading data..." + from datasets import load_dataset + ds = load_dataset("wikitext","wikitext-103-raw-v1",split="train") + dv = load_dataset("wikitext","wikitext-103-raw-v1",split="validation") + tt = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000] + vt = "\n".join([r["text"] for r in dv if r["text"].strip()]) + train_ds, val_ds = CharDS(tt,config.max_seq_len), CharDS(vt,config.max_seq_len) + LOG.append(f"Data: {len(tt):,} train, {len(vt):,} val chars") + + model = PCSHODLM(config).to(device) + model.train() + updater = LocalParameterUpdater(model, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5) + tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, shuffle=False, num_workers=2, pin_memory=True) + + STATUS = "Training LOCAL PC..." + LOG.append(f"\n{'='*60}\nMode: LOCAL PC | Params: {count_parameters(model):,}\n{'='*60}") + step, start, max_steps = 0, time.time(), 10000 + log_data = {"steps":[],"losses":[],"energies":[]} + + while step < max_steps: + for batch in tl: + if step >= max_steps: break + x_0 = batch["input_ids"].to(device) + result = updater.step({"input_ids": x_0}) + step += 1 + loss = result.get("loss",0); energies = result.get("energies",[]) + if step % 100 == 0: + elapsed = time.time()-start + tps = step*64*config.max_seq_len/elapsed + e = f"{energies[-1]:.0f}" if energies else "N/A" + msg = f"[local] Step {step:6d} | Loss: {loss:.4f} | Energy: {e} | Tok/s: {tps:.0f} | {elapsed:.0f}s" + LOG.append(msg); log_data["steps"].append(step); log_data["losses"].append(loss); log_data["energies"].append(energies[-1] if energies else 0) + if step % 2000 == 0: + model.eval() + tl2,tt2=0.0,0 + with torch.no_grad(): + for vb in vl: + vx=vb["input_ids"].to(device); vo=model(vx); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>100000: break + vl2=tl2/max(1,tt2); LOG.append(f" --> [local] Val loss: {vl2:.4f}"); log_data.setdefault("val",[]).append((step,vl2)) + model.train() + + model.eval() + tl2,tt2=0.0,0 + with torch.no_grad(): + for vb in vl: + vx=vb["input_ids"].to(device); vo=model(vx); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>200000: break + fv=tl2/max(1,tt2); log_data["final_val"]=fv + LOG.append(f"DONE: {step} steps in {time.time()-start:.0f}s | Final val: {fv:.4f}") + STATUS = "Complete!" + + os.makedirs("results",exist_ok=True) + torch.save({"model":model.state_dict(),"config":config,"log":log_data},"results/local_pc_10k.pt") + with open("results/local_pc_log.json","w") as f: json.dump(log_data,f) + try: + from huggingface_hub import HfApi + HfApi().upload_folder(folder_path="results",repo_id="zotowata/pc-sho-dlm-local",repo_type="space",path_in_repo="results") + LOG.append("Results uploaded!") + except: pass + +_thread = None +def start(): + global _thread + if _thread and _thread.is_alive(): return "Already running!" + _thread = threading.Thread(target=train, daemon=True); _thread.start() + return "LOCAL PC training started on A100!" + +with gr.Blocks(title="PC-SHO-DLM Local PC") as demo: + gr.Markdown("# PC-SHO-DLM: LOCAL PC Training (A100)") + with gr.Row(): + btn = gr.Button("Start Training", variant="primary") + st = gr.Textbox(label="Status", value="Idle") + log = gr.Textbox(label="Log", lines=25, max_lines=50) + btn.click(start, outputs=st) + refresh = gr.Button("Refresh"); refresh.click(lambda: "\n".join(LOG[-50:]), outputs=log); refresh.click(lambda: STATUS, outputs=st) + timer = gr.Timer(5); timer.tick(lambda: "\n".join(LOG[-50:]), outputs=log); timer.tick(lambda: STATUS, outputs=st) + +demo.launch() diff --git a/app_local_pc_wiki.py b/app_local_pc_wiki.py new file mode 100644 index 0000000000000000000000000000000000000000..aef5ea5cb4fa081a92d3e7e32b2cb64c3761ebac --- /dev/null +++ b/app_local_pc_wiki.py @@ -0,0 +1,115 @@ +"""PC-SHO-DLM LOCAL PC — The mode that hit loss 1.146. WikiText-103 in memory. +Settle first, THEN update params from converged errors. Envelope theorem path.""" +import json, os, sys, threading, time +import gradio as gr +import torch, torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1,(len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG = [f"PC-SHO-DLM LOCAL PC | Device: {dev}"] + if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + cfg = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048, + n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, feedback_rank=128, + # v2 optimizations (tuned) + mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, + homeostatic_target=1.0, homeostatic_rate=0.001, homeostatic_rho_max=0.03, + lateral_inhibition=0.001, + ) + + STATUS = "Loading WikiText-103 into memory..." + from datasets import load_dataset + ds = load_dataset("wikitext", "wikitext-103-raw-v1", split="train") + dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + train_text = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000] + val_text = "\n".join([r["text"] for r in dv if r["text"].strip()]) + train_ds = CharDS(train_text, cfg.max_seq_len); val_ds = CharDS(val_text, cfg.max_seq_len) + LOG.append(f"Data: {len(train_text):,} train, {len(val_text):,} val chars IN MEMORY") + + model = PCSHODLM(cfg).to(dev); model.train() + n_params = count_parameters(model) + LOG.append(f"Model: {n_params:,} params") + LOG.append(f"Mode: LOCAL PC (settle THEN update — envelope theorem path)") + LOG.append(f"This is the mode that hit loss 1.146 on v1") + + # LOCAL mode: settle first, then update params + updater = LocalParameterUpdater(model, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5) + tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True) + + STATUS = "Training LOCAL PC..." + LOG.append(f"\n{'='*60}\nLOCAL PC | {n_params:,} params | settle then update\n{'='*60}") + step, start, mx = 0, time.time(), 10000 + K_max = cfg.n_settling_steps + + while step < mx: + for batch in tl: + if step >= mx: break + x0 = batch["input_ids"].to(dev) + + # Curriculum K + K_warmup = min(2000, mx // 3) + K_curr = max(1, int(K_max * min(1.0, step / K_warmup))) + model.config.n_settling_steps = K_curr + + result = updater.step({"input_ids": x0}) + step += 1 + + loss = result.get("loss", 0); energies = result.get("energies", []) + stat = result.get("stationarity", 0) + + if step % 100 == 0: + el = time.time()-start; tps = step*64*cfg.max_seq_len/el + e = f"{energies[-1]:.0f}" if energies else "N/A" + rho = f"[{model.layer_rho[0]:.4f}..{model.layer_rho[-1]:.4f}]" + LOG.append(f"[local] Step {step:6d} | Loss: {loss:.4f} | Energy: {e} | K={K_curr} | Stat: {stat:.0f} | rho={rho} | Tok/s: {tps:.0f} | {el:.0f}s") + if step % 2000 == 0: + model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>100000: break + LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); model.train() + + model.config.n_settling_steps = K_max; model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>200000: break + LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s | Val: {tl2/max(1,tt2):.4f}") + STATUS = "Complete!" + os.makedirs("results",exist_ok=True) + torch.save({"model":model.state_dict(),"config":cfg},"results/local_pc_wiki.pt") + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!" + +with gr.Blocks(title="Local PC Wiki") as demo: + gr.Markdown("# PC-SHO-DLM LOCAL PC — WikiText-103 in memory") + gr.Markdown("Settle THEN update (envelope theorem). The mode that hit loss 1.146.") + with gr.Row(): + btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle") + log=gr.Textbox(label="Log",lines=35); btn.click(start,outputs=st) + r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-70:]),outputs=log); r.click(lambda:STATUS,outputs=st) + t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-70:]),outputs=log); t.tick(lambda:STATUS,outputs=st) +demo.launch() diff --git a/app_mdlm_baseline.py b/app_mdlm_baseline.py new file mode 100644 index 0000000000000000000000000000000000000000..3934d90bfda50263cc7d61644d56f53b73a11850 --- /dev/null +++ b/app_mdlm_baseline.py @@ -0,0 +1,90 @@ +"""MDLM BASELINE — Run the official MDLM code on text8 for reference numbers.""" +import os, sys, subprocess, threading, time +import gradio as gr + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + LOG = ["MDLM Official Baseline — text8"] + LOG.append("Setting up MDLM from kuleshov-group/mdlm...") + + STATUS = "Installing dependencies..." + + # Clone MDLM + if not os.path.exists("/home/user/mdlm"): + r = subprocess.run(["git", "clone", "https://github.com/kuleshov-group/mdlm.git", "/home/user/mdlm"], + capture_output=True, text=True) + LOG.append(f"Clone: {r.stdout[-200:] if r.stdout else r.stderr[-200:]}") + + # Install deps + deps = ["hydra-core", "omegaconf", "lightning", "einops", "transformers", "datasets", "wandb", "rich", "timm"] + for dep in deps: + subprocess.run([sys.executable, "-m", "pip", "install", "-q", dep], capture_output=True) + LOG.append("Dependencies installed") + + # Check GPU + import torch + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG.append(f"Device: {dev}") + if dev == "cuda": + LOG.append(f"GPU: {torch.cuda.get_device_name()}") + + STATUS = "Training MDLM on text8..." + LOG.append("\nStarting MDLM training on text8 (character-level)...") + LOG.append("Config: small model (768d, 12 layers, 12 heads), seq_len=256") + + # Run MDLM training + env = os.environ.copy() + env["WANDB_MODE"] = "disabled" + + cmd = [ + sys.executable, "-u", "-m", "main", + "loader.batch_size=64", + "loader.eval_batch_size=64", + "model=small", + "data=text8", + "parameterization=subs", + "model.length=256", + "trainer.max_steps=10000", + "wandb.name=mdlm-text8-baseline", + "eval.compute_generative_perplexity=False", + "checkpointing.save_dir=/home/user/mdlm/checkpoints", + ] + + LOG.append(f"Command: {' '.join(cmd)}") + + process = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, bufsize=1, cwd="/home/user/mdlm", env=env + ) + + for line in iter(process.stdout.readline, ''): + line = line.strip() + if line: + LOG.append(line) + # Extract loss from lightning output + if 'loss' in line.lower() or 'step' in line.lower() or 'epoch' in line.lower() or 'val' in line.lower(): + pass # already appended + + process.wait() + LOG.append(f"\nMDLM training finished with exit code {process.returncode}") + STATUS = "Complete!" + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start() + return "MDLM baseline started!" + +with gr.Blocks(title="MDLM Baseline") as demo: + gr.Markdown("# MDLM Official Baseline — text8 (A100)") + gr.Markdown("Running the official NeurIPS 2024 MDLM code for reference numbers") + with gr.Row(): + btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle") + log=gr.Textbox(label="Log",lines=35) + btn.click(start, outputs=st) + r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-70:]),outputs=log); r.click(lambda:STATUS,outputs=st) + t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-70:]),outputs=log); t.tick(lambda:STATUS,outputs=st) +demo.launch() diff --git a/app_optimized.py b/app_optimized.py new file mode 100644 index 0000000000000000000000000000000000000000..c85837ef2c930f7ba18f0fb19af5528d120e8a84 --- /dev/null +++ b/app_optimized.py @@ -0,0 +1,248 @@ +""" +PC-SHO-DLM v2: OPTIMIZED Training on A100 +All Tier 1+2 optimizations enabled: +- Spectral preconditioning (per-element precision dynamics) +- Curriculum over K (ramp settling steps) +- Temporal hierarchy (per-layer mass/damping) +- Homeostatic plasticity (adaptive anchoring) +- Linear attention in settling loop +- Lateral inhibition (competitive token settling) +- Adaptive two-timescale ratio (for unified mode) + +Trains on massive streaming data from HuggingFace. +""" +import json, os, sys, threading, time, math +import gradio as gr +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset, IterableDataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + +# ============================================================================= +# Streaming Dataset — handles terabytes via HF datasets streaming +# ============================================================================= + +class StreamingCharDataset(IterableDataset): + """Streams text from HuggingFace datasets, encodes as bytes on the fly.""" + def __init__(self, dataset_name, config_name, split, seq_len, vocab_size=257, max_tokens=None): + self.dataset_name = dataset_name + self.config_name = config_name + self.split = split + self.seq_len = seq_len + self.vocab_size = vocab_size + self.max_tokens = max_tokens + + def __iter__(self): + from datasets import load_dataset + ds = load_dataset(self.dataset_name, self.config_name, split=self.split, streaming=True) + buffer = [] + total = 0 + for item in ds: + text = item.get("text", "") + if not text.strip(): + continue + encoded = [min(b + 1, self.vocab_size - 1) for b in text.encode("utf-8")] + buffer.extend(encoded) + while len(buffer) >= self.seq_len: + chunk = buffer[:self.seq_len] + buffer = buffer[self.seq_len:] + total += self.seq_len + if self.max_tokens and total > self.max_tokens: + return + yield {"input_ids": torch.tensor(chunk, dtype=torch.long)} + + +class CharDS(Dataset): + def __init__(self, text, seq_len): + self.seq_len = seq_len + self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1, (len(self.data)-seq_len)//seq_len) + def __len__(self): return self.n + def __getitem__(self, i): + return {"input_ids": self.data[i*self.seq_len:(i+1)*self.seq_len]} + + +# ============================================================================= +# Training +# ============================================================================= + +LOG = [] +STATUS = "Idle" + +def train(): + global STATUS, LOG + LOG = ["PC-SHO-DLM v2 — OPTIMIZED Training"] + device = "cuda" if torch.cuda.is_available() else "cpu" + LOG.append(f"Device: {device}") + if device == "cuda": + LOG.append(f"GPU: {torch.cuda.get_device_name()}") + LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + # Optimized config + config = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, + n_layers=12, d_ff=2048, n_diffusion_steps=128, n_settling_steps=6, + mask_token_id=0, dropout=0.1, feedback_rank=128, + # Temporal hierarchy + mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, + # Homeostatic + homeostatic_target=1.0, homeostatic_rate=0.001, + # Lateral inhibition + lateral_inhibition=0.01, settling_budget_fraction=0.5, + ) + n_params = count_parameters(PCSHODLM(config)) + LOG.append(f"Model: {n_params:,} params (d={config.d_model}, L={config.n_layers})") + LOG.append("Optimizations: spectral precond, curriculum-K, temporal hierarchy,") + LOG.append(" homeostatic plasticity, linear-attn settling, lateral inhibition") + + # === DATA: Stream from multiple sources === + STATUS = "Loading data (streaming)..." + LOG.append("\nData sources (streaming):") + + # Use WikiText for validation (small, fixed) + from datasets import load_dataset + dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + val_text = "\n".join([r["text"] for r in dv if r["text"].strip()]) + val_ds = CharDS(val_text, config.max_seq_len) + LOG.append(f" Val: WikiText-103 validation ({len(val_text):,} chars)") + + # Stream from FineWeb-10BT (10 billion tokens) — ~50GB of high-quality web text + # Falls back to WikiText if FineWeb unavailable + try: + train_ds = StreamingCharDataset( + "HuggingFaceFW/fineweb", "sample-10BT", "train", + seq_len=config.max_seq_len, max_tokens=2_000_000_000 # 2B tokens + ) + LOG.append(f" Train: FineWeb-10BT streaming (2B tokens)") + except Exception as e: + LOG.append(f" FineWeb failed ({e}), falling back to WikiText-103") + train_ds = StreamingCharDataset( + "wikitext", "wikitext-103-raw-v1", "train", + seq_len=config.max_seq_len, max_tokens=500_000_000 + ) + LOG.append(f" Train: WikiText-103 streaming (500M tokens)") + + model = PCSHODLM(config).to(device) + model.train() + + # Local PC training with all optimizations + updater = LocalParameterUpdater(model, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5) + tl = DataLoader(train_ds, batch_size=64, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, shuffle=False, num_workers=2, pin_memory=True) + + STATUS = "Training OPTIMIZED Local PC..." + LOG.append(f"\n{'='*60}") + LOG.append(f"Training: OPTIMIZED Local PC | {n_params:,} params") + LOG.append(f"{'='*60}") + + step, start, max_steps = 0, time.time(), 10000 + log_data = {"steps": [], "losses": [], "energies": [], "K_values": []} + K_max = config.n_settling_steps + + for batch in tl: + if step >= max_steps: + break + x_0 = batch["input_ids"].to(device) + + # CURRICULUM OVER K + K_warmup = min(2000, max_steps // 3) + K_curr = max(1, int(K_max * min(1.0, step / K_warmup))) + model.config.n_settling_steps = K_curr + + result = updater.step({"input_ids": x_0}) + step += 1 + + loss = result.get("loss", 0) + energies = result.get("energies", []) + + if step % 100 == 0: + elapsed = time.time() - start + tps = step * 64 * config.max_seq_len / elapsed + e = f"{energies[-1]:.0f}" if energies else "N/A" + rho_str = f"[{model.layer_rho[0]:.4f}..{model.layer_rho[-1]:.4f}]" + msg = f"[opt-pc] Step {step:6d} | Loss: {loss:.4f} | Energy: {e} | K={K_curr} | rho={rho_str} | Tok/s: {tps:.0f} | {elapsed:.0f}s" + LOG.append(msg) + log_data["steps"].append(step) + log_data["losses"].append(loss) + log_data["energies"].append(energies[-1] if energies else 0) + log_data["K_values"].append(K_curr) + + if step % 2000 == 0: + model.eval() + tl2, tt2 = 0.0, 0 + with torch.no_grad(): + for vb in vl: + vx = vb["input_ids"].to(device) + vo = model(vx) + nm = vo["mask"].sum().item() + if nm > 0: + tl2 += vo["loss"].item() * nm + tt2 += nm + if tt2 > 100000: + break + vl2 = tl2 / max(1, tt2) + LOG.append(f" --> Val loss: {vl2:.4f}") + log_data.setdefault("val", []).append((step, vl2)) + model.train() + + # Restore full K for final eval + model.config.n_settling_steps = K_max + model.eval() + tl2, tt2 = 0.0, 0 + with torch.no_grad(): + for vb in vl: + vx = vb["input_ids"].to(device) + vo = model(vx) + nm = vo["mask"].sum().item() + if nm > 0: + tl2 += vo["loss"].item() * nm + tt2 += nm + if tt2 > 200000: + break + fv = tl2 / max(1, tt2) + log_data["final_val"] = fv + elapsed = time.time() - start + LOG.append(f"\nDONE: {step} steps in {elapsed:.0f}s | Final val: {fv:.4f}") + STATUS = "Complete!" + + os.makedirs("results", exist_ok=True) + torch.save({"model": model.state_dict(), "config": config, "log": log_data}, "results/optimized_pc_10k.pt") + with open("results/optimized_log.json", "w") as f: + json.dump(log_data, f) + + try: + from huggingface_hub import HfApi + HfApi().upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-optimized", + repo_type="space", path_in_repo="results") + LOG.append("Results uploaded!") + except Exception as e: + LOG.append(f"Upload: {e}") + + +_thread = None +def start(): + global _thread + if _thread and _thread.is_alive(): + return "Already running!" + _thread = threading.Thread(target=train, daemon=True) + _thread.start() + return "OPTIMIZED training started on A100!" + +with gr.Blocks(title="PC-SHO-DLM v2 Optimized") as demo: + gr.Markdown("# PC-SHO-DLM v2: OPTIMIZED Local PC Training (A100)") + gr.Markdown("All Tier 1+2 optimizations: spectral precond, curriculum-K, temporal hierarchy, homeostasis, linear-attn settling, lateral inhibition") + with gr.Row(): + btn = gr.Button("Start Training", variant="primary") + st = gr.Textbox(label="Status", value="Idle") + log = gr.Textbox(label="Log", lines=30, max_lines=60) + btn.click(start, outputs=st) + refresh = gr.Button("Refresh") + refresh.click(lambda: "\n".join(LOG[-60:]), outputs=log) + refresh.click(lambda: STATUS, outputs=st) + timer = gr.Timer(5) + timer.tick(lambda: "\n".join(LOG[-60:]), outputs=log) + timer.tick(lambda: STATUS, outputs=st) + +demo.launch() diff --git a/app_unified.py b/app_unified.py new file mode 100644 index 0000000000000000000000000000000000000000..7d1f9d08a500ddc29f2ea092cd27e4af7d3092d3 --- /dev/null +++ b/app_unified.py @@ -0,0 +1,130 @@ +"""PC-SHO-DLM: UNIFIED Training on A100 — Settling IS Learning.""" +import json, os, sys, threading, time +import gradio as gr +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, count_parameters + +class CharDS(Dataset): + def __init__(self, text, seq_len): + self.seq_len = seq_len + self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1, (len(self.data)-seq_len)//seq_len) + def __len__(self): return self.n + def __getitem__(self, i): + return {"input_ids": self.data[i*self.seq_len:(i+1)*self.seq_len]} + +LOG = [] +STATUS = "Idle" + +def train(): + global STATUS, LOG + LOG = ["Starting UNIFIED training on A100..."] + device = "cuda" if torch.cuda.is_available() else "cpu" + LOG.append(f"Device: {device}") + if device == "cuda": + LOG.append(f"GPU: {torch.cuda.get_device_name()}") + LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + config = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, + n_layers=12, d_ff=2048, n_diffusion_steps=128, n_settling_steps=6, + mask_token_id=0, dropout=0.1, feedback_rank=128, + ) + LOG.append(f"Model: {count_parameters(PCSHODLM(config)):,} params") + + STATUS = "Loading data..." + from datasets import load_dataset + ds = load_dataset("wikitext","wikitext-103-raw-v1",split="train") + dv = load_dataset("wikitext","wikitext-103-raw-v1",split="validation") + tt = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000] + vt = "\n".join([r["text"] for r in dv if r["text"].strip()]) + train_ds, val_ds = CharDS(tt,config.max_seq_len), CharDS(vt,config.max_seq_len) + LOG.append(f"Data: {len(tt):,} train, {len(vt):,} val chars") + + model = PCSHODLM(config).to(device) + model.train() + param_lr_scale = 0.005 + + tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, shuffle=False, num_workers=2, pin_memory=True) + + STATUS = "Training UNIFIED..." + LOG.append(f"\n{'='*60}\nMode: UNIFIED (settling=learning) | Params: {count_parameters(model):,}\n{'='*60}") + step, start, max_steps = 0, time.time(), 10000 + log_data = {"steps":[],"losses":[],"energies":[]} + + while step < max_steps: + for batch in tl: + if step >= max_steps: break + x_0 = batch["input_ids"].to(device) + B, S = x_0.shape + t = torch.randint(1, config.n_diffusion_steps+1, (B,), device=device) + x_t, mask = model.schedule.corrupt(x_0, t, config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + h_s, _, energies = model.unified_settle(h_init, x_0, mask, t, param_lr_scale=param_lr_scale) + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_s[-1])) + ml, mt = logits[mask], x_0[mask] + loss = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0 + + step += 1 + if step % 100 == 0: + elapsed = time.time()-start + tps = step*64*config.max_seq_len/elapsed + e = f"{energies[-1]:.0f}" if energies else "N/A" + msg = f"[unified] Step {step:6d} | Loss: {loss:.4f} | Energy: {e} | Tok/s: {tps:.0f} | {elapsed:.0f}s" + LOG.append(msg); log_data["steps"].append(step); log_data["losses"].append(loss); log_data["energies"].append(energies[-1] if energies else 0) + if step % 2000 == 0: + model.eval() + tl2,tt2=0.0,0 + with torch.no_grad(): + for vb in vl: + vx=vb["input_ids"].to(device); vo=model(vx); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>100000: break + vl2=tl2/max(1,tt2); LOG.append(f" --> [unified] Val loss: {vl2:.4f}"); log_data.setdefault("val",[]).append((step,vl2)) + model.train() + + model.eval() + tl2,tt2=0.0,0 + with torch.no_grad(): + for vb in vl: + vx=vb["input_ids"].to(device); vo=model(vx); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>200000: break + fv=tl2/max(1,tt2); log_data["final_val"]=fv + LOG.append(f"DONE: {step} steps in {time.time()-start:.0f}s | Final val: {fv:.4f}") + STATUS = "Complete!" + + os.makedirs("results",exist_ok=True) + torch.save({"model":model.state_dict(),"config":config,"log":log_data},"results/unified_10k.pt") + with open("results/unified_log.json","w") as f: json.dump(log_data,f) + try: + from huggingface_hub import HfApi + HfApi().upload_folder(folder_path="results",repo_id="zotowata/pc-sho-dlm-unified",repo_type="space",path_in_repo="results") + LOG.append("Results uploaded!") + except: pass + +_thread = None +def start(): + global _thread + if _thread and _thread.is_alive(): return "Already running!" + _thread = threading.Thread(target=train, daemon=True); _thread.start() + return "UNIFIED training started on A100!" + +with gr.Blocks(title="PC-SHO-DLM Unified") as demo: + gr.Markdown("# PC-SHO-DLM: UNIFIED Training — Settling IS Learning (A100)") + with gr.Row(): + btn = gr.Button("Start Training", variant="primary") + st = gr.Textbox(label="Status", value="Idle") + log = gr.Textbox(label="Log", lines=25, max_lines=50) + btn.click(start, outputs=st) + refresh = gr.Button("Refresh"); refresh.click(lambda: "\n".join(LOG[-50:]), outputs=log); refresh.click(lambda: STATUS, outputs=st) + timer = gr.Timer(5); timer.tick(lambda: "\n".join(LOG[-50:]), outputs=log); timer.tick(lambda: STATUS, outputs=st) + +demo.launch() diff --git a/app_unified_big.py b/app_unified_big.py new file mode 100644 index 0000000000000000000000000000000000000000..620babd25fd8bd487668816806d75b05ada93908 --- /dev/null +++ b/app_unified_big.py @@ -0,0 +1,152 @@ +"""PC-SHO-DLM UNIFIED BIG — 350M params, FineWeb streaming, lambda=500, A100.""" +import json, os, sys, threading, time, math +import gradio as gr +import torch, torch.nn.functional as F +from torch.utils.data import DataLoader, IterableDataset, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, count_parameters + +class StreamDS(IterableDataset): + """Streams from HuggingFace — handles billions of tokens without loading into memory.""" + def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None): + self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok + def __iter__(self): + from datasets import load_dataset + ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True, trust_remote_code=True) + buf, tot = [], 0 + for item in ds: + t = item.get("text", "") + if not t or not t.strip(): continue + buf.extend([min(b+1, self.voc-1) for b in t.encode("utf-8")]) + while len(buf) >= self.seq_len: + yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)} + buf = buf[self.seq_len:]; tot += self.seq_len + if self.max_tok and tot > self.max_tok: return + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1,(len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG = [f"PC-SHO-DLM UNIFIED BIG | {dev}"] + if dev == "cuda": + LOG.append(f"GPU: {torch.cuda.get_device_name()}") + LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + # 350M param model — biggest that fits on A100-80GB with batch 16 + cfg = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=1024, n_heads=16, n_layers=24, d_ff=4096, + n_diffusion_steps=128, n_settling_steps=4, mask_token_id=0, dropout=0.1, + feedback_rank=256, denoising_lambda=500.0, + mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, + homeostatic_target=0.0, homeostatic_rate=0.0001, + homeostatic_rho_max=0.02, lateral_inhibition=0.0, + ) + + model = PCSHODLM(cfg) + n_params = count_parameters(model) + LOG.append(f"Model: {n_params:,} params (d={cfg.d_model}, L={cfg.n_layers}, heads={cfg.n_heads})") + LOG.append(f"denoising_lambda={cfg.denoising_lambda}") + + # Check if it fits + if n_params > 500_000_000: + LOG.append(f"WARNING: {n_params/1e6:.0f}M params may be tight on 80GB A100") + + STATUS = "Loading data..." + + # Validation: WikiText in memory + from datasets import load_dataset + dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len) + LOG.append(f"Val: WikiText-103 ({len(val_ds)} samples)") + + # Training: FineWeb-10BT streaming (billions of tokens) + train_ds = StreamDS("HuggingFaceFW/fineweb", "sample-10BT", "train", + cfg.max_seq_len, max_tok=10_000_000_000) # 10B tokens + LOG.append(f"Train: FineWeb-10BT streaming (10B tokens)") + + model = model.to(dev) + model.train() + + # Smaller batch for big model + batch_size = 16 + tl = DataLoader(train_ds, batch_size=batch_size, num_workers=0) + vl = DataLoader(val_ds, batch_size=16, num_workers=0) + + STATUS = "Training UNIFIED BIG..." + LOG.append(f"\n{'='*60}") + LOG.append(f"UNIFIED BIG | {n_params:,} params | FineWeb-10BT | lambda=500") + LOG.append(f"{'='*60}") + + step, start, mx = 0, time.time(), 20000 + K_max = cfg.n_settling_steps + param_lr_scale = 0.025 + + for batch in tl: + if step >= mx: break + x0 = batch["input_ids"].to(dev); B, S = x0.shape + + # Curriculum K (start at 2 for big model) + K_curr = max(2, int(K_max * min(1.0, step / 1000))) + model.config.n_settling_steps = K_curr + + t = torch.randint(1, cfg.n_diffusion_steps+1, (B,), device=dev) + x_t, mask = model.schedule.corrupt(x0, t, cfg.mask_token_id) + h0 = model.embed_input(x_t, t); h_init = model.amortized_forward_pass(h0) + h_s, _, energies = model.unified_settle(h_init, x0, mask, t, param_lr_scale=param_lr_scale) + + # Adaptive two-timescale + if len(energies) >= 2 and energies[0] > 0: + e_ratio = energies[-1] / max(energies[0], 1e-8) + eff_rho_K = math.sqrt(max(e_ratio, 0.01)) + param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - eff_rho_K) ** 2)) + + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_s[-1])) + ml, mt = logits[mask], x0[mask] + lv = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0 + step += 1 + + if step % 50 == 0: + el = time.time()-start; tps = step*batch_size*cfg.max_seq_len/el + e = f"{energies[-1]:.0f}" if energies else "N/A" + LOG.append(f"[UNI-BIG] Step {step:6d} | Loss: {lv:.4f} | Energy: {e} | K={K_curr} | s={param_lr_scale:.4f} | Tok/s: {tps:.0f} | {el:.0f}s") + if step % 2000 == 0: + model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>50000: break + LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); model.train() + # Save checkpoint + os.makedirs("results",exist_ok=True) + torch.save({"model":model.state_dict(),"config":cfg,"step":step}, f"results/unified_big_step{step}.pt") + + LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s") + STATUS = "Complete!" + os.makedirs("results",exist_ok=True) + torch.save({"model":model.state_dict(),"config":cfg}, "results/unified_big_final.pt") + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!" + +with gr.Blocks(title="Unified Big") as demo: + gr.Markdown("# PC-SHO-DLM UNIFIED BIG — 350M params, FineWeb-10BT (A100)") + with gr.Row(): + btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle") + log=gr.Textbox(label="Log",lines=35); btn.click(start,outputs=st) + r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-70:]),outputs=log); r.click(lambda:STATUS,outputs=st) + t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-70:]),outputs=log); t.tick(lambda:STATUS,outputs=st) +demo.launch() diff --git a/app_unified_wiki.py b/app_unified_wiki.py new file mode 100644 index 0000000000000000000000000000000000000000..3f361a87ca990d680cd89a8a9fd1e08693730252 --- /dev/null +++ b/app_unified_wiki.py @@ -0,0 +1,121 @@ +"""PC-SHO-DLM UNIFIED — WikiText-103 in memory, all v2 optimizations, settling=learning.""" +import json, os, sys, threading, time, math +import gradio as gr +import torch, torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1,(len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG = [f"PC-SHO-DLM UNIFIED | Device: {dev}"] + if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + cfg = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048, + n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, feedback_rank=128, + mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, + homeostatic_target=1.0, homeostatic_rate=0.001, homeostatic_rho_max=0.03, + lateral_inhibition=0.001, settling_budget_fraction=0.5, + ) + + STATUS = "Loading WikiText-103 into memory..." + from datasets import load_dataset + ds = load_dataset("wikitext", "wikitext-103-raw-v1", split="train") + dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + train_text = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000] + val_text = "\n".join([r["text"] for r in dv if r["text"].strip()]) + train_ds = CharDS(train_text, cfg.max_seq_len); val_ds = CharDS(val_text, cfg.max_seq_len) + LOG.append(f"Data: {len(train_text):,} train chars, {len(val_text):,} val chars IN MEMORY") + + model = PCSHODLM(cfg).to(dev); model.train() + n_params = count_parameters(model) + LOG.append(f"Model: {n_params:,} params | Unified (settling=learning)") + LOG.append(f"Optimizations: spectral precond, curriculum-K, temporal hierarchy, homeostasis") + + tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True) + + STATUS = "Training..." + LOG.append(f"\n{'='*60}\nUNIFIED | {n_params:,} params | settling=learning\n{'='*60}") + step, start, mx = 0, time.time(), 10000 + K_max = cfg.n_settling_steps + param_lr_scale = 0.025 # theory-optimal starting value + + while step < mx: + for batch in tl: + if step >= mx: break + x0 = batch["input_ids"].to(dev); B, S = x0.shape + + # Curriculum K + K_warmup = min(2000, mx // 3) + K_curr = max(1, int(K_max * min(1.0, step / K_warmup))) + model.config.n_settling_steps = K_curr + + t = torch.randint(1, cfg.n_diffusion_steps+1, (B,), device=dev) + x_t, mask = model.schedule.corrupt(x0, t, cfg.mask_token_id) + h0 = model.embed_input(x_t, t); h_init = model.amortized_forward_pass(h0) + h_s, _, energies = model.unified_settle(h_init, x0, mask, t, param_lr_scale=param_lr_scale) + + # Adaptive two-timescale + if len(energies) >= 2 and energies[0] > 0: + e_ratio = energies[-1] / max(energies[0], 1e-8) + eff_rho_K = math.sqrt(max(e_ratio, 0.01)) + param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - eff_rho_K) ** 2)) + + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_s[-1])) + ml, mt = logits[mask], x0[mask] + lv = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0 + step += 1 + + if step % 100 == 0: + el = time.time()-start; tps = step*64*cfg.max_seq_len/el + e = f"{energies[-1]:.0f}" if energies else "N/A" + rho = f"[{model.layer_rho[0]:.4f}..{model.layer_rho[-1]:.4f}]" + LOG.append(f"[unified] Step {step:6d} | Loss: {lv:.4f} | Energy: {e} | K={K_curr} | s={param_lr_scale:.4f} | rho={rho} | Tok/s: {tps:.0f} | {el:.0f}s") + if step % 2000 == 0: + model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>100000: break + LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); model.train() + + model.config.n_settling_steps = K_max; model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>200000: break + LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s | Val: {tl2/max(1,tt2):.4f}") + STATUS = "Complete!" + os.makedirs("results",exist_ok=True) + torch.save({"model":model.state_dict(),"config":cfg},"results/unified_wiki.pt") + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!" + +with gr.Blocks(title="Unified Wiki") as demo: + gr.Markdown("# PC-SHO-DLM UNIFIED — WikiText-103 in memory") + with gr.Row(): + btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle") + log=gr.Textbox(label="Log",lines=30); btn.click(start,outputs=st) + r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-60:]),outputs=log); r.click(lambda:STATUS,outputs=st) + t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-60:]),outputs=log); t.tick(lambda:STATUS,outputs=st) +demo.launch() diff --git a/app_v2_backprop.py b/app_v2_backprop.py new file mode 100644 index 0000000000000000000000000000000000000000..c7688bc956999ce76863c3a8be870bc99dc19bef --- /dev/null +++ b/app_v2_backprop.py @@ -0,0 +1,118 @@ +"""PC-SHO-DLM v2: BACKPROP BASELINE with all architectural optimizations. +Same optimized architecture (linear attn, temporal hierarchy, etc) but trained with standard backprop. +""" +import json, os, sys, threading, time +import gradio as gr +import torch, torch.nn.functional as F +from torch.utils.data import DataLoader, IterableDataset, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, count_parameters + +class StreamDS(IterableDataset): + def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None): + self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok + def __iter__(self): + from datasets import load_dataset + ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True) + buf, tot = [], 0 + for item in ds: + t = item.get("text","") + if not t.strip(): continue + buf.extend([min(b+1,self.voc-1) for b in t.encode("utf-8")]) + while len(buf) >= self.seq_len: + yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)} + buf = buf[self.seq_len:]; tot += self.seq_len + if self.max_tok and tot > self.max_tok: return + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1,(len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + LOG = ["PC-SHO-DLM v2 BACKPROP — Optimized Architecture"] + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG.append(f"Device: {dev}") + if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + cfg = PCSHOConfig(vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048, + n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, feedback_rank=128, + mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, homeostatic_target=1.0, homeostatic_rate=0.001, + lateral_inhibition=0.01, settling_budget_fraction=0.5) + LOG.append(f"Model: {count_parameters(PCSHODLM(cfg)):,} params") + + STATUS = "Loading data..." + from datasets import load_dataset + dv = load_dataset("wikitext","wikitext-103-raw-v1",split="validation") + val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len) + try: + train_ds = StreamDS("HuggingFaceFW/fineweb","sample-10BT","train",cfg.max_seq_len,max_tok=2_000_000_000) + LOG.append("Train: FineWeb-10BT streaming (2B tokens)") + except: + train_ds = StreamDS("wikitext","wikitext-103-raw-v1","train",cfg.max_seq_len,max_tok=500_000_000) + LOG.append("Train: WikiText-103 fallback (500M tokens)") + LOG.append("Data: WikiText-103 streaming (500M tok/epoch)") + + model = PCSHODLM(cfg).to(dev); model.train() + opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01) + sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10000, eta_min=3e-5) + tl = DataLoader(train_ds, batch_size=64, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True) + + STATUS = "Training v2 BACKPROP..."; LOG.append(f"\n{'='*60}\nv2 BACKPROP | {count_parameters(model):,} params\n{'='*60}") + step, start, mx = 0, time.time(), 10000; log_d = {"steps":[],"losses":[],"energies":[]} + K_max = cfg.n_settling_steps + + for batch in tl: + if step >= mx: break + x0 = batch["input_ids"].to(dev) + K_curr = max(1, int(K_max * min(1.0, step / min(2000, mx//3)))); model.config.n_settling_steps = K_curr + opt.zero_grad(); out = model(x0); loss = out["loss"]; loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step(); sched.step() + step += 1; lv = loss.item(); es = out["energies"] + if step % 100 == 0: + el = time.time()-start; tps = step*64*cfg.max_seq_len/el; e = f"{es[-1]:.0f}" if es else "N/A" + msg = f"[v2-bp] Step {step:6d} | Loss: {lv:.4f} | Energy: {e} | K={K_curr} | Tok/s: {tps:.0f} | {el:.0f}s" + LOG.append(msg); log_d["steps"].append(step); log_d["losses"].append(lv); log_d["energies"].append(es[-1] if es else 0) + if step % 2000 == 0: + model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>100000: break + LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); log_d.setdefault("val",[]).append((step,tl2/max(1,tt2))); model.train() + + model.config.n_settling_steps = K_max; model.eval() + tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>200000: break + fv=tl2/max(1,tt2); log_d["final_val"]=fv; LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s | Val: {fv:.4f}"); STATUS="Complete!" + os.makedirs("results",exist_ok=True); torch.save({"model":model.state_dict(),"config":cfg,"log":log_d},"results/v2_backprop.pt") + try: + from huggingface_hub import HfApi; HfApi().upload_folder(folder_path="results",repo_id="zotowata/pc-sho-dlm-v2-backprop",repo_type="space",path_in_repo="results"); LOG.append("Uploaded!") + except: pass + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start(); return "v2 BACKPROP started on A100!" + +with gr.Blocks(title="v2 Backprop") as demo: + gr.Markdown("# PC-SHO-DLM v2: BACKPROP Baseline (A100)\nOptimized arch: linear-attn settling, temporal hierarchy, homeostasis, curriculum-K") + with gr.Row(): + btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle") + log=gr.Textbox(label="Log",lines=30); btn.click(start,outputs=st) + r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-60:]),outputs=log); r.click(lambda:STATUS,outputs=st) + t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-60:]),outputs=log); t.tick(lambda:STATUS,outputs=st) +demo.launch() diff --git a/app_v2_unified.py b/app_v2_unified.py new file mode 100644 index 0000000000000000000000000000000000000000..0a1f69598846831e6565b7e2abe77233fa661dcf --- /dev/null +++ b/app_v2_unified.py @@ -0,0 +1,133 @@ +"""PC-SHO-DLM v2: UNIFIED (settling=learning) with all optimizations + adaptive two-timescale.""" +import json, os, sys, threading, time, math +import gradio as gr +import torch, torch.nn.functional as F +from torch.utils.data import DataLoader, IterableDataset, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, count_parameters + +class StreamDS(IterableDataset): + def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None): + self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok + def __iter__(self): + from datasets import load_dataset + ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True) + buf, tot = [], 0 + for item in ds: + t = item.get("text","") + if not t.strip(): continue + buf.extend([min(b+1,self.voc-1) for b in t.encode("utf-8")]) + while len(buf) >= self.seq_len: + yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)} + buf = buf[self.seq_len:]; tot += self.seq_len + if self.max_tok and tot > self.max_tok: return + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1,(len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + LOG = ["PC-SHO-DLM v2 UNIFIED — Settling IS Learning + Adaptive Ratio"] + dev = "cuda" if torch.cuda.is_available() else "cpu" + LOG.append(f"Device: {dev}") + if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB") + + cfg = PCSHOConfig(vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048, + n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, feedback_rank=128, + mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, homeostatic_target=1.0, homeostatic_rate=0.001, + lateral_inhibition=0.01, settling_budget_fraction=0.5) + LOG.append(f"Model: {count_parameters(PCSHODLM(cfg)):,} params") + LOG.append("Two-timescale: adaptive s* = (1 - rho^K)^2 / 2") + + STATUS = "Loading data..." + from datasets import load_dataset + dv = load_dataset("wikitext","wikitext-103-raw-v1",split="validation") + val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len) + try: + train_ds = StreamDS("HuggingFaceFW/fineweb","sample-10BT","train",cfg.max_seq_len,max_tok=2_000_000_000) + LOG.append("Train: FineWeb-10BT streaming (2B tokens)") + except: + train_ds = StreamDS("wikitext","wikitext-103-raw-v1","train",cfg.max_seq_len,max_tok=500_000_000) + LOG.append("Train: WikiText-103 fallback (500M tokens)") + LOG.append("Data: WikiText-103 streaming (500M tok/epoch)") + + model = PCSHODLM(cfg).to(dev); model.train() + tl = DataLoader(train_ds, batch_size=64, num_workers=4, pin_memory=True) + vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True) + + STATUS = "Training v2 UNIFIED..."; LOG.append(f"\n{'='*60}\nv2 UNIFIED | {count_parameters(model):,} params\n{'='*60}") + step, start, mx = 0, time.time(), 10000; log_d = {"steps":[],"losses":[],"energies":[],"lr_scales":[]} + K_max = cfg.n_settling_steps + # Start with theoretically derived ratio, will adapt + param_lr_scale = 0.025 + + for batch in tl: + if step >= mx: break + x0 = batch["input_ids"].to(dev); B,S = x0.shape + K_curr = max(1, int(K_max * min(1.0, step / min(2000, mx//3)))); model.config.n_settling_steps = K_curr + + t = torch.randint(1, cfg.n_diffusion_steps+1, (B,), device=dev) + x_t, mask = model.schedule.corrupt(x0, t, cfg.mask_token_id) + h0 = model.embed_input(x_t, t); h_init = model.amortized_forward_pass(h0) + h_s, _, energies = model.unified_settle(h_init, x0, mask, t, param_lr_scale=param_lr_scale) + + # Adaptive two-timescale: s* = (1 - rho^K)^2 / 2 + if len(energies) >= 2 and energies[0] > 0: + e_ratio = energies[-1] / max(energies[0], 1e-8) + eff_rho_K = math.sqrt(max(e_ratio, 0.01)) + param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - eff_rho_K) ** 2)) + + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_s[-1])) + ml, mt = logits[mask], x0[mask] + lv = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0 + step += 1 + + if step % 100 == 0: + el = time.time()-start; tps = step*64*cfg.max_seq_len/el; e = f"{energies[-1]:.0f}" if energies else "N/A" + msg = f"[v2-uni] Step {step:6d} | Loss: {lv:.4f} | Energy: {e} | K={K_curr} | s={param_lr_scale:.4f} | Tok/s: {tps:.0f} | {el:.0f}s" + LOG.append(msg); log_d["steps"].append(step); log_d["losses"].append(lv) + log_d["energies"].append(energies[-1] if energies else 0); log_d["lr_scales"].append(param_lr_scale) + if step % 2000 == 0: + model.eval(); tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>100000: break + LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); log_d.setdefault("val",[]).append((step,tl2/max(1,tt2))); model.train() + + model.config.n_settling_steps = K_max; model.eval() + tl2,tt2=0.,0 + with torch.no_grad(): + for vb in vl: + vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item() + if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm + if tt2>200000: break + fv=tl2/max(1,tt2); log_d["final_val"]=fv; LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s | Val: {fv:.4f}"); STATUS="Complete!" + os.makedirs("results",exist_ok=True); torch.save({"model":model.state_dict(),"config":cfg,"log":log_d},"results/v2_unified.pt") + try: + from huggingface_hub import HfApi; HfApi().upload_folder(folder_path="results",repo_id="zotowata/pc-sho-dlm-v2-unified",repo_type="space",path_in_repo="results"); LOG.append("Uploaded!") + except: pass + +_t = None +def start(): + global _t + if _t and _t.is_alive(): return "Already running!" + _t = threading.Thread(target=train, daemon=True); _t.start(); return "v2 UNIFIED started on A100!" + +with gr.Blocks(title="v2 Unified") as demo: + gr.Markdown("# PC-SHO-DLM v2: UNIFIED (A100)\nSettling = Learning | Adaptive two-timescale ratio | All optimizations") + with gr.Row(): + btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle") + log=gr.Textbox(label="Log",lines=30); btn.click(start,outputs=st) + r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-60:]),outputs=log); r.click(lambda:STATUS,outputs=st) + t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-60:]),outputs=log); t.tick(lambda:STATUS,outputs=st) +demo.launch() diff --git a/app_v2_unified_large.py b/app_v2_unified_large.py new file mode 100644 index 0000000000000000000000000000000000000000..967f16e81d8e7d5fea7112b6c981b67066457784 --- /dev/null +++ b/app_v2_unified_large.py @@ -0,0 +1,223 @@ +"""PC-SHO-DLM v2: UNIFIED LARGE — 4xA100, FineWeb-10BT, all optimizations.""" +import json, os, sys, threading, time, math +import gradio as gr +import torch, torch.nn.functional as F +from torch.utils.data import DataLoader, IterableDataset, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, count_parameters + +class StreamDS(IterableDataset): + def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None): + self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok + def __iter__(self): + from datasets import load_dataset + ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True, trust_remote_code=True) + buf, tot = [], 0 + for item in ds: + t = item.get("text", "") + if not t or not t.strip(): + continue + buf.extend([min(b+1, self.voc-1) for b in t.encode("utf-8")]) + while len(buf) >= self.seq_len: + yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)} + buf = buf[self.seq_len:] + tot += self.seq_len + if self.max_tok and tot > self.max_tok: + return + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl + self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1, (len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + +LOG, STATUS = [], "Idle" + +def train(): + global STATUS, LOG + LOG = ["=" * 70] + LOG.append("PC-SHO-DLM v2 UNIFIED LARGE") + LOG.append("4xA100 | FineWeb-10BT | Adaptive Two-Timescale | All Optimizations") + LOG.append("=" * 70) + + dev = "cuda" if torch.cuda.is_available() else "cpu" + n_gpu = torch.cuda.device_count() if dev == "cuda" else 0 + LOG.append(f"Device: {dev} x {n_gpu}") + if dev == "cuda": + for i in range(n_gpu): + LOG.append(f" GPU {i}: {torch.cuda.get_device_name(i)} | {torch.cuda.get_device_properties(i).total_memory/1e9:.1f} GB") + + # Large model sized for single A100-80GB + cfg = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048, + n_diffusion_steps=128, n_settling_steps=8, mask_token_id=0, dropout=0.1, feedback_rank=128, + mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, + homeostatic_target=1.0, homeostatic_rate=0.001, + lateral_inhibition=0.01, settling_budget_fraction=0.5, + ) + n_params = count_parameters(PCSHODLM(cfg)) + LOG.append(f"\nModel: {n_params:,} params (d={cfg.d_model}, L={cfg.n_layers}, heads={cfg.n_heads})") + LOG.append("Optimizations: spectral precond, curriculum-K, temporal hierarchy,") + LOG.append(" homeostasis, linear-attn settling, lateral inhibition, adaptive s*") + + # === DATA: FineWeb-10BT (10 billion tokens of curated web text) === + STATUS = "Loading FineWeb-10BT..." + LOG.append("\nLoading FineWeb-10BT (10B tokens, streaming)...") + + train_ds = StreamDS("HuggingFaceFW/fineweb", "sample-10BT", "train", + cfg.max_seq_len, max_tok=5_000_000_000) # 5B tokens + LOG.append("Train: FineWeb-10BT streaming (5B tokens)") + + # Validation from WikiText + from datasets import load_dataset + dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len) + LOG.append(f"Val: WikiText-103 ({len(val_ds):,} samples)") + + model = PCSHODLM(cfg).to(dev) + model.train() + + batch_size = 64 + tl = DataLoader(train_ds, batch_size=batch_size, num_workers=8, pin_memory=True, prefetch_factor=4) + vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True) + + STATUS = "Training UNIFIED LARGE..." + LOG.append(f"\n{'='*70}") + LOG.append(f"UNIFIED LARGE | {n_params:,} params | batch={batch_size} | FineWeb-10BT") + LOG.append(f"{'='*70}") + + step, start, mx = 0, time.time(), 20000 + log_d = {"steps": [], "losses": [], "energies": [], "lr_scales": [], "K_values": []} + K_max = cfg.n_settling_steps + param_lr_scale = 0.025 # Start at theory-optimal value + + for batch in tl: + if step >= mx: + break + x0 = batch["input_ids"].to(dev) + B, S = x0.shape + + # Curriculum over K + K_curr = max(1, int(K_max * min(1.0, step / min(3000, mx // 3)))) + model.config.n_settling_steps = K_curr + + t = torch.randint(1, cfg.n_diffusion_steps + 1, (B,), device=dev) + x_t, mask = model.schedule.corrupt(x0, t, cfg.mask_token_id) + h0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h0) + h_s, _, energies = model.unified_settle(h_init, x0, mask, t, param_lr_scale=param_lr_scale) + + # Adaptive two-timescale: s* = (1 - rho^K)^2 / 2 + if len(energies) >= 2 and energies[0] > 0: + e_ratio = energies[-1] / max(energies[0], 1e-8) + eff_rho_K = math.sqrt(max(e_ratio, 0.01)) + param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - eff_rho_K) ** 2)) + + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_s[-1])) + ml, mt = logits[mask], x0[mask] + lv = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0 + step += 1 + + if step % 100 == 0: + el = time.time() - start + tps = step * batch_size * cfg.max_seq_len / el + e = f"{energies[-1]:.0f}" if energies else "N/A" + rho_str = f"[{model.layer_rho[0]:.3f}..{model.layer_rho[-1]:.3f}]" + msg = (f"[UNI-L] Step {step:6d} | Loss: {lv:.4f} | Energy: {e} | " + f"K={K_curr} | s={param_lr_scale:.4f} | rho={rho_str} | " + f"Tok/s: {tps:.0f} | {el:.0f}s") + LOG.append(msg) + log_d["steps"].append(step) + log_d["losses"].append(lv) + log_d["energies"].append(energies[-1] if energies else 0) + log_d["lr_scales"].append(param_lr_scale) + log_d["K_values"].append(K_curr) + + if step % 2000 == 0: + model.eval() + tl2, tt2 = 0., 0 + with torch.no_grad(): + for vb in vl: + vo = model(vb["input_ids"].to(dev)) + nm = vo["mask"].sum().item() + if nm > 0: + tl2 += vo["loss"].item() * nm + tt2 += nm + if tt2 > 100000: + break + vl2 = tl2 / max(1, tt2) + LOG.append(f" --> Val loss: {vl2:.4f}") + log_d.setdefault("val", []).append((step, vl2)) + model.train() + + # Save checkpoint + os.makedirs("results", exist_ok=True) + torch.save({ + "model": model.state_dict(), "config": cfg, "log": log_d, "step": step + }, f"results/unified_large_step{step}.pt") + LOG.append(f" Checkpoint saved at step {step}") + + # Final eval + model.config.n_settling_steps = K_max + model.eval() + tl2, tt2 = 0., 0 + with torch.no_grad(): + for vb in vl: + vo = model(vb["input_ids"].to(dev)) + nm = vo["mask"].sum().item() + if nm > 0: + tl2 += vo["loss"].item() * nm + tt2 += nm + if tt2 > 200000: + break + fv = tl2 / max(1, tt2) + log_d["final_val"] = fv + elapsed = time.time() - start + LOG.append(f"\n{'='*70}") + LOG.append(f"DONE: {step} steps in {elapsed:.0f}s | Final val: {fv:.4f}") + LOG.append(f"Total tokens: {step * batch_size * cfg.max_seq_len:,}") + LOG.append(f"{'='*70}") + STATUS = "Complete!" + + os.makedirs("results", exist_ok=True) + torch.save({"model": model.state_dict(), "config": cfg, "log": log_d}, "results/unified_large_final.pt") + with open("results/unified_large_log.json", "w") as f: + json.dump(log_d, f) + + try: + from huggingface_hub import HfApi + HfApi().upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-unified-large", + repo_type="space", path_in_repo="results") + LOG.append("Results uploaded!") + except Exception as e: + LOG.append(f"Upload: {e}") + +_t = None +def start(): + global _t + if _t and _t.is_alive(): + return "Already running!" + _t = threading.Thread(target=train, daemon=True) + _t.start() + return "UNIFIED LARGE started!" + +with gr.Blocks(title="v2 Unified Large") as demo: + gr.Markdown("# PC-SHO-DLM v2: UNIFIED LARGE (4xA100)") + gr.Markdown("~150M params | FineWeb-10BT (5B tokens) | Adaptive s* | 20k steps") + with gr.Row(): + btn = gr.Button("Start Training", variant="primary") + st = gr.Textbox(label="Status", value="Idle") + log = gr.Textbox(label="Log", lines=35, max_lines=70) + btn.click(start, outputs=st) + r = gr.Button("Refresh") + r.click(lambda: "\n".join(LOG[-70:]), outputs=log) + r.click(lambda: STATUS, outputs=st) + t = gr.Timer(5) + t.tick(lambda: "\n".join(LOG[-70:]), outputs=log) + t.tick(lambda: STATUS, outputs=st) + +demo.launch() diff --git a/app_zerogpu.py b/app_zerogpu.py new file mode 100644 index 0000000000000000000000000000000000000000..0c58583aca1422c5c82d939451bfef123cccc5d3 --- /dev/null +++ b/app_zerogpu.py @@ -0,0 +1,117 @@ +"""PC-SHO-DLM on ZeroGPU — Large dataset training with lambda=500 fix.""" +import json, os, sys, threading, time, math +import gradio as gr +import spaces +import torch, torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + +class CharDS(Dataset): + def __init__(self, text, sl): + self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long) + self.n = max(1,(len(self.data)-sl)//sl) + def __len__(self): return self.n + def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]} + +LOG, STATUS = [], "Idle" +MODEL, UPDATER, TRAIN_DS, VAL_DS, CFG = None, None, None, None, None + +def setup(): + """Load data and create model (CPU, before GPU allocation).""" + global MODEL, UPDATER, TRAIN_DS, VAL_DS, CFG, LOG, STATUS + + LOG = ["PC-SHO-DLM ZeroGPU — lambda=500 fix"] + + CFG = PCSHOConfig( + vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048, + n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, + feedback_rank=128, denoising_lambda=500.0, + mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, + homeostatic_target=0.0, homeostatic_rate=0.0001, + homeostatic_rho_max=0.02, lateral_inhibition=0.0, + ) + + STATUS = "Loading WikiText-103..." + from datasets import load_dataset + ds = load_dataset("wikitext", "wikitext-103-raw-v1", split="train") + dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + train_text = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000] + val_text = "\n".join([r["text"] for r in dv if r["text"].strip()]) + TRAIN_DS = CharDS(train_text, CFG.max_seq_len) + VAL_DS = CharDS(val_text, CFG.max_seq_len) + LOG.append(f"Data: {len(train_text):,} train, {len(val_text):,} val chars") + + MODEL = PCSHODLM(CFG) + LOG.append(f"Model: {count_parameters(MODEL):,} params (d={CFG.d_model}, L={CFG.n_layers})") + LOG.append(f"denoising_lambda={CFG.denoising_lambda} (THE FIX)") + UPDATER = LocalParameterUpdater(MODEL, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5) + STATUS = "Ready — press Start" + +@spaces.GPU(duration=300) # 5 min GPU sessions +def train_batch(step_start): + """Run training steps on GPU. ZeroGPU gives us ~5 min per call.""" + global MODEL, UPDATER, LOG, STATUS + + device = "cuda" + MODEL = MODEL.to(device) + MODEL.train() + + tl = DataLoader(TRAIN_DS, batch_size=32, shuffle=True, drop_last=True, num_workers=0) + + STATUS = f"Training on GPU (steps {step_start}+)..." + K_max = CFG.n_settling_steps + step = step_start + start = time.time() + max_steps_this_session = 500 # fit within 5 min + + for batch in tl: + if step - step_start >= max_steps_this_session: + break + x0 = batch["input_ids"].to(device) + + K_curr = max(3, int(K_max * min(1.0, step / 1000))) + MODEL.config.n_settling_steps = K_curr + + result = UPDATER.step({"input_ids": x0}) + step += 1 + + loss = result.get("loss", 0) + energies = result.get("energies", []) + + if step % 50 == 0: + el = time.time() - start + tps = (step - step_start) * 32 * CFG.max_seq_len / el + e = f"{energies[-1]:.0f}" if energies else "N/A" + LOG.append(f"[local] Step {step:6d} | Loss: {loss:.4f} | Energy: {e} | K={K_curr} | Tok/s: {tps:.0f} | {el:.0f}s") + + MODEL = MODEL.to("cpu") # free GPU + STATUS = f"Session done. {step - step_start} steps. Press Start for more." + return step + +CURRENT_STEP = 0 + +def start(): + global CURRENT_STEP + if MODEL is None: + setup() + CURRENT_STEP = train_batch(CURRENT_STEP) + return f"Completed step {CURRENT_STEP}. Press Start for next GPU session." + +with gr.Blocks(title="PC-SHO-DLM ZeroGPU") as demo: + gr.Markdown("# PC-SHO-DLM — ZeroGPU Training (lambda=500)") + gr.Markdown("Each 'Start' gives ~5 min on A100. Press repeatedly for more training.") + with gr.Row(): + btn = gr.Button("Start / Continue Training", variant="primary") + st = gr.Textbox(label="Status", value="Idle") + log = gr.Textbox(label="Log", lines=30) + btn.click(start, outputs=st) + r = gr.Button("Refresh") + r.click(lambda: "\n".join(LOG[-60:]), outputs=log) + r.click(lambda: STATUS, outputs=st) + t = gr.Timer(5) + t.tick(lambda: "\n".join(LOG[-60:]), outputs=log) + t.tick(lambda: STATUS, outputs=st) + +demo.launch() diff --git a/architecture_diagram.md b/architecture_diagram.md new file mode 100644 index 0000000000000000000000000000000000000000..f34b69e18f2fe58e2b35967cca82e6803ce37180 --- /dev/null +++ b/architecture_diagram.md @@ -0,0 +1,338 @@ +# PC-SHO-DLM Architecture: Complete Technical Specification + +## Architecture Diagram + +``` + PC-SHO-DLM: Predictive-Coding Diffusion Language Model + with Precision-Conditioned Second-Order Settling + + ============================================================================ + OUTER LOOP: Masked Discrete Diffusion (T denoising steps) + ============================================================================ + + t=T (fully masked) ──────────> t=T-1 ──────────> ... ──────────> t=0 (clean) + [MASK][MASK][MASK]... [MASK] the [MASK]... The cat sat... + + Each step: unmask highest-confidence tokens via reverse diffusion + State continuation: h,v warm-started from previous step + + ============================================================================ + INNER LOOP: Predictive-Coding Energy Minimization (K settling microsteps) + ============================================================================ + + For each diffusion step t, run K microsteps of SHO settling: + + ┌─────────────────────────────────────────────────────────────────────────┐ + │ │ + │ x_t (corrupted tokens) │ + │ │ │ + │ ▼ │ + │ ┌──────────────┐ │ + │ │ Embeddings │ token + position + timestep │ + │ │ h_0 │ │ + │ └──────┬───────┘ │ + │ │ │ + │ ▼ │ + │ ╔══════════════════════════════════════════════════════════╗ │ + │ ║ BIDIRECTIONAL PREDICTIVE TRANSFORMER ║ │ + │ ║ ║ │ + │ ║ Layer 1: h_0 ──▶ f_1(h_0) = μ_1↑ ε_1↑ = h_1 - μ_1↑ ║ │ + │ ║ g_1(h_2) = μ_1↓ ε_1↓ = h_1 - μ_1↓ ║ │ + │ ║ Γ_1 = precision_up(h_1, t) ║ │ + │ ║ Λ_1 = precision_down(h_1, t) ║ │ + │ ║ ║ │ + │ ║ Layer 2: h_1 ──▶ f_2(h_1) = μ_2↑ ε_2↑ = h_2 - μ_2↑ ║ │ + │ ║ g_2(h_3) = μ_2↓ ε_2↓ = h_2 - μ_2↓ ║ │ + │ ║ ... ║ │ + │ ║ ║ │ + │ ║ Layer L: h_{L-1} ──▶ f_L(h_{L-1}) = μ_L↑ ║ │ + │ ║ ε_L↑ = h_L - μ_L↑ ║ │ + │ ║ ║ │ + │ ║ ┌─────────────────────────────────────────────────┐ ║ │ + │ ║ │ BOTTOM-UP (f_l): Standard bidirectional │ ║ │ + │ ║ │ transformer blocks with self-attention + FFN │ ║ │ + │ ║ │ │ ║ │ + │ ║ │ TOP-DOWN (g_l): Lightweight feedback predictors │ ║ │ + │ ║ │ (low-rank projections from layer above) │ ║ │ + │ ║ │ │ ║ │ + │ ║ │ PRECISION (Γ_l, Λ_l): Learned uncertainty │ ║ │ + │ ║ │ per token × channel, controls settling dynamics │ ║ │ + │ ║ └─────────────────────────────────────────────────┘ ║ │ + │ ╚══════════════════════════════════════════════════════════╝ │ + │ │ │ + │ ▼ │ + │ ┌──────────────────────────────────────────────────────────┐ │ + │ │ ENERGY FUNCTION E_t(h) │ │ + │ │ │ │ + │ │ E = Σ_l ½||ε_l↑||²_Γ (bottom-up prediction errors) │ │ + │ │ + Σ_l ½||ε_l↓||²_Λ (top-down prediction errors) │ │ + │ │ + λ_t · H(softmax(W·h_L)) (entropy minimization) │ │ + │ │ + ρ_l · ||h_l - h_l^init||² (anchoring) │ │ + │ └──────────────────────────────────────────────────────────┘ │ + │ │ │ + │ ▼ │ + │ ┌──────────────────────────────────────────────────────────┐ │ + │ │ SECOND-ORDER SETTLING (Damped SHO) │ │ + │ │ │ │ + │ │ For each layer l, for K microsteps: │ │ + │ │ │ │ + │ │ v_l^{k+1} = (1 - γ_l) · v_l^k - η_l · ∇_{h_l} E │ │ + │ │ h_l^{k+1} = h_l^k + v_l^{k+1} │ │ + │ │ │ │ + │ │ where η_l, γ_l are precision-conditioned: │ │ + │ │ η_l = η_base / (1 + c_η · prec_l) │ │ + │ │ γ_l = clip(2√(m_l · prec_l), γ_min, γ_max) │ │ + │ │ │ │ + │ │ Temporal hierarchy: │ │ + │ │ m_l = m · (1 + 0.5 · l/L) (heavier at top) │ │ + │ │ η_l scaled by 1/(1 + 0.3·l/L) (slower at top) │ │ + │ │ │ │ + │ │ Soft-gate adaptive settling: │ │ + │ │ w_i = σ((U_i - τ) / τ_temp) │ │ + │ │ h_i^{k+1} = w_i · h_i^{new} + (1-w_i) · h_i^{old} │ │ + │ └──────────────────────────────────────────────────────────┘ │ + │ │ │ + │ ▼ │ + │ ┌──────────────────────────────────────────────────────────┐ │ + │ │ LOCAL PARAMETER UPDATES │ │ + │ │ (Globally Backpropagation-Free) │ │ + │ │ │ │ + │ │ After settling converges: │ │ + │ │ │ │ + │ │ Forward: Δθ_l ∝ -(Γ_l · ε_l↑) · ∂f_l/∂θ_l │ │ + │ │ Feedback: Δφ_l ∝ -(Λ_l · ε_l↓) · ∂g_l/∂φ_l │ │ + │ │ Readout: ΔW_o ∝ -∂L_mask/∂W_o (uses x_0 targets) │ │ + │ │ Embeds: via readout loss backprop │ │ + │ │ │ │ + │ │ Each update is LAYER-LOCAL: no gradient crosses layers │ │ + │ └──────────────────────────────────────────────────────────┘ │ + │ │ │ + │ ▼ │ + │ ┌──────────────┐ │ + │ │ Readout │ W_o · h_L → logits → softmax → token predictions │ + │ │ (per token) │ │ + │ └──────────────┘ │ + │ │ + └─────────────────────────────────────────────────────────────────────────┘ + + + ============================================================================ + CONDITIONAL GENERATION (Chat Mode) + ============================================================================ + + [prompt tokens (unmasked)] | [MASK MASK MASK ... (response region)] + ↕ ↕ + Never modified Iteratively unmasked via + by diffusion reverse diffusion + settling + ↕ ↕ + Provides context Response emerges from + through bidirectional energy minimization + attention at every conditioned on prompt + settling step + + ============================================================================ + STATE CONTINUATION (Across Diffusion Steps) + ============================================================================ + + Step t+1: settle → h*(t+1), v*(t+1) + │ + warm-start ↓ (stop-gradient) + Step t: h^(0)(t) = h*(t+1) + v^(0)(t) = ρ_v · v*(t+1) + │ + settle K steps → h*(t), v*(t) + │ + warm-start ↓ + Step t-1: ...continues... + + Theorem C: ||h_t^(K) - h_t*|| ≤ ρ^K · (ε_{t+1} + Δ_t) + Settling cost depends on DRIFT, not full re-solve distance. +``` + +--- + +## Critical Derivations and Equations + +### 1. The Per-Step Latent Energy + +For diffusion timestep t, the energy over hidden states h = {h_0, ..., h_L}: + +``` +E_t(h, θ) = Σ_{l=1}^{L} ½ ||ε_l↑||²_{Γ_l} (bottom-up consistency) + + Σ_{l=0}^{L-1} ½ ||ε_l↓||²_{Λ_l} (top-down consistency) + + λ_t · Σ_{i ∈ M_t} H(p_θ(· | h_L^(i))) (entropy minimization — HONEST) + + Σ_{l=1}^{L} ρ_l · ||h_l - h_l^{init}||² (anchoring) +``` + +where: +- `ε_l↑ = h_l - f_l(h_{l-1}; θ_l)` — bottom-up prediction error +- `ε_l↓ = h_l - g_l(h_{l+1}; φ_l)` — top-down prediction error +- `H(p) = -Σ_c p_c log p_c` — entropy of predicted token distribution +- `||x||²_Γ = x^T Γ x` — precision-weighted squared norm +- `M_t` — set of masked token positions +- `λ_t = λ_base · (1 + (1 - t/T))` — timestep-dependent weight + +**CRITICAL: Honest Settling** +The entropy term `H(softmax(W·h_L))` does NOT use the ground truth x_0. +It pushes the model toward confident predictions without peeking at the answer. +The ground truth x_0 is used ONLY in the parameter update step (readout loss), +not during settling. + +### 2. Second-Order Settling Dynamics (SHO) + +Continuous time: +``` +m_l · ḧ_l + γ_l · ḣ_l + ∇_{h_l} E_t(h) = 0 +``` + +Discrete (symplectic Euler): +``` +v_l^{k+1} = (1 - γ_l) · v_l^k - η_l · ∇_{h_l} E_t(h^k) +h_l^{k+1} = h_l^k + v_l^{k+1} +``` + +Precision-conditioned controller: +``` +η_l = η_base · (1/(1 + 0.3·l/L)) / (1 + c_η · prec_l) +γ_l = clip(2√(m_l · prec_l), γ_min, γ_max) +m_l = m · (1 + 0.5 · l/L) +``` + +Interpretation: +- Low precision → flat energy → large steps, more momentum (exploration) +- High precision → sharp energy → small steps, high damping (exploitation) +- Lower layers settle fast (low mass, high damping) +- Higher layers settle slow (high mass, maintain context) + +### 3. Theorem A: Reduced-Objective Exactness (Envelope Theorem) + +Define the reduced objective: +``` +Φ_t(θ) = min_h E_t(h, θ) +``` + +If h_t*(θ) is the unique minimizer, then: +``` +∇_θ Φ_t(θ) = ∂E_t/∂θ |_{h=h_t*(θ)} +``` + +The implicit derivative through h_t*(θ) vanishes because ∇_h E_t(h_t*, θ) = 0. + +**Consequence:** Local post-settling parameter updates are exact gradients of +the reduced objective. No backpropagation through the K settling steps needed. + +Since E_t decomposes as E_t = Σ_l E_{t,l}(h_{l-1}, h_l, h_{l+1}, θ_l): +``` +∂Φ_t/∂θ_l = ∂E_{t,l}/∂θ_l |_{h=h*} +``` + +Each layer's gradient depends only on its own settled states. Layer-local. + +### 4. Theorem B: Accelerated Settling (O(√κ) vs O(κ)) + +For locally quadratic energy E(h) = ½(h-h*)^T H (h-h*), μI ≼ H ≼ LI, κ=L/μ: + +**First-order PC:** h^{k+1} = h^k - α∇E(h^k) +``` +K_FO = O(κ · log(1/ε)) with optimal α = 2/(L+μ) +``` + +**PC-SHO (heavy-ball):** v^{k+1} = β·v^k - η·∇E(h^k), h^{k+1} = h^k + v^{k+1} +``` +K_SHO = O(√κ · log(1/ε)) with η = 4/(√L+√μ)², β = ((√κ-1)/(√κ+1))² +``` + +**Speedup:** K_SHO / K_FO = O(1/√κ) + +Note: This holds for the local quadratic approximation near fixed points. +The anchoring term ρ||h-h^{init}||² ensures local strong convexity. + +### 5. Theorem C: Warm-Start Tracking + +If solver contracts by ρ_S < 1 and inter-step drift is Δ_t = ||h_t* - h_{t+1}*||: + +Warm-start: `||h_t^(K) - h_t*|| ≤ ρ_S^K · (ε_{t+1} + Δ_t)` +Cold-start: `||h_t^(K) - h_t*|| ≤ ρ_S^K · D_t` + +Warm-start wins when `Δ_t + ε_{t+1} < D_t` (adjacent steps are close). + +**Total settling cost:** +- Warm-started SHO: `K_total = O(T · √κ̃ · log((Δ+ε)/ε))` +- Cold-started FO: `K_total = O(T · κ̃ · log(D/ε))` + +Two advantages: √κ̃ instead of κ̃, AND Δ instead of D. + +### 6. Theorem D: Precision Optimality (GLS) + +If local errors are heteroscedastic: ε_l ~ N(0, Σ_l), Σ_l ≠ σ²I + +The precision-weighted estimator (GLS): +``` +θ̂_GLS = argmin_θ (y - Xθ)^T Σ^{-1} (y - Xθ) +Cov(θ̂_GLS) = (X^T Σ^{-1} X)^{-1} +``` + +This is BLUE (Best Linear Unbiased Estimator). +Precision heads learn Γ_l ≈ Σ_l^{-1}, making local updates statistically optimal. + +### 7. Lyapunov Stability + +For the continuous-time dynamics M·ḧ + Γ·ḣ + ∇E(h) = 0: + +Define Lyapunov function: V(h, ḣ) = E(h) + ½ḣ^T M ḣ + +Then: dV/dt = -ḣ^T Γ ḣ ≤ 0 + +**Extra settling time monotonically decreases total energy.** + +### 8. Honest Training Loss vs Cheating Loss + +**Cheating (old):** Settling uses x_0 in energy → model peeks at answer +``` +Settling energy: E = ... + λ · CE(logits, x_0) +Reported loss: 0.001 (FAKE — model copies x_0 through energy) +Generation: garbage (no x_0 available at inference) +``` + +**Honest (current):** Settling uses entropy → model must find confident predictions alone +``` +Settling energy: E = ... + λ · H(softmax(logits)) +Reported loss: 1.5-2.0 (REAL — model actually predicts from context) +Generation: coherent (same mechanism at train and inference) +``` + +### 9. Optimal Denoising Lambda + +At initialization, measure energy components: +``` +E_pred = Σ_l ½||ε_l||² (prediction errors) +E_entropy = Σ_i H(p_i) (entropy at masked positions) +``` + +For entropy to be ~40% of total energy: +``` +λ_opt = (E_pred · 0.4) / (E_entropy · 0.6) +``` + +Typical value: λ ≈ 5 for entropy-based settling (vs λ ≈ 500 for cheating mode). + +### 10. Conditional Generation (Chat) + +Training: mask only response, keep prompt visible +``` +x = [prompt_tokens | SEP | MASK MASK ... MASK] + ─────────────── ───────────────── + never masked masked by schedule +``` + +Inference: iteratively unmask response conditioned on prompt +``` +For t = T down to 1: + mask = (x == MASK) & response_region + h_settled = PC_settle(embed(x, t), K steps) + logits = readout(h_settled) + unmask top-confidence response tokens +``` + +The bidirectional attention lets prompt tokens influence every settling step. +The prompt acts as a fixed boundary condition shaping the energy landscape. diff --git a/chat.py b/chat.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc6e8491a1835c917801c69a3016e52293abb56 --- /dev/null +++ b/chat.py @@ -0,0 +1,231 @@ +#!/usr/bin/env python3 +""" +PC-SHO-DLM Chat — Conditional masked diffusion chatbot. + +The prompt stays unmasked. The response region starts fully masked. +PC settling iteratively denoises the response conditioned on the prompt. + +Usage: + python3 train_chat.py --data alpaca # Train on dialogue data + python3 chat.py --checkpoint checkpoints/chat/chat_final.pt # Chat +""" + +import argparse, glob, os, sys, torch +import torch.nn.functional as F + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater + + +def find_checkpoint(): + for p in ["checkpoints/chat/chat_final.pt", "checkpoints/chat/*.pt", + "checkpoints/*/checkpoint_final.pt", "checkpoints/*/*.pt"]: + files = sorted(glob.glob(p), key=os.path.getmtime, reverse=True) + if files: + return files[0] + return None + + +def encode_text(text, vocab_size=257): + return [min(b + 1, vocab_size - 1) for b in text.encode("utf-8")] + + +def decode_tokens(tokens): + raw = tokens if isinstance(tokens, list) else tokens.squeeze().cpu().tolist() + # Filter out mask tokens (0) and padding + return bytes([max(0, t - 1) for t in raw if t > 0 and t < 257]).decode("utf-8", errors="replace") + + +def generate_response(model, prompt_text, response_len=256, device="cpu", + temperature=0.8, n_steps=None): + """Generate a response conditioned on prompt via conditional masked diffusion. + + 1. Encode prompt as bytes + 2. Create: [prompt_tokens | MASK * response_len] + 3. Reverse diffusion: iteratively unmask response tokens + 4. PC settling at each step refines predictions conditioned on prompt + """ + config = model.config + T = n_steps or config.n_diffusion_steps + mask_id = config.mask_token_id + + prompt_tokens = encode_text(prompt_text) + prompt_len = len(prompt_tokens) + + # Ensure we fit in max_seq_len + max_response = config.max_seq_len - prompt_len + if max_response <= 0: + prompt_tokens = prompt_tokens[:config.max_seq_len // 2] + prompt_len = len(prompt_tokens) + max_response = config.max_seq_len - prompt_len + response_len = min(response_len, max_response) + + # Build initial sequence: [prompt | MASK...] + seq = prompt_tokens + [mask_id] * response_len + if len(seq) < config.max_seq_len: + seq = seq + [mask_id] * (config.max_seq_len - len(seq)) + x = torch.tensor(seq[:config.max_seq_len], dtype=torch.long).unsqueeze(0).to(device) + + # Response region mask (only unmask response, never touch prompt) + response_region = torch.zeros(1, config.max_seq_len, dtype=torch.bool, device=device) + response_region[0, prompt_len:prompt_len + response_len] = True + + prev_h = None + prev_v = None + + with torch.no_grad(): + for t_val in range(T, 0, -1): + t = torch.full((1,), t_val, dtype=torch.long, device=device) + + # Only consider masked tokens in response region + mask = (x == mask_id) & response_region + if not mask.any(): + break + + # Embed and settle + h_0 = model.embed_input(x, t) + h_init = model.amortized_forward_pass(h_0) + h_settled, v_final, _, _, _ = model.settle( + h_init, x, mask, t, + prev_h=prev_h, prev_v=prev_v, + ) + + # State continuation + prev_h = h_settled + prev_v = v_final + + # Decode with temperature + logits = model.readout(model.readout_norm(h_settled[-1])) + + if temperature > 0: + probs = F.softmax(logits / temperature, dim=-1) + else: + probs = F.softmax(logits, dim=-1) + + # Determine how many tokens to unmask + t_prev = t_val - 1 + target_mask_rate = model.schedule.mask_rate( + torch.tensor([t_prev], device=device) + ).squeeze() + + n_currently_masked = mask.sum().item() + n_to_keep_masked = int(target_mask_rate * response_len) + n_to_unmask = max(1, n_currently_masked - n_to_keep_masked) + + # Score by confidence, only in response region + confidence = probs.max(dim=-1).values.squeeze() # (S,) + confidence[~mask.squeeze()] = float("inf") + + # Unmask the most confident response tokens + masked_indices = mask.squeeze().nonzero(as_tuple=True)[0] + if len(masked_indices) > 0: + conf_at_masked = confidence[masked_indices] + n_to_unmask = min(n_to_unmask, len(masked_indices)) + _, top_idx = conf_at_masked.topk(n_to_unmask) + unmask_pos = masked_indices[top_idx] + + # Sample tokens + if temperature > 0: + for pos in unmask_pos: + token = torch.multinomial(probs[0, pos], 1).item() + x[0, pos] = token + else: + x[0, unmask_pos] = logits[0, unmask_pos].argmax(dim=-1) + + # Final pass: unmask any remaining + remaining = (x == mask_id) & response_region + if remaining.any(): + t_final = torch.ones(1, dtype=torch.long, device=device) + h_0 = model.embed_input(x, t_final) + h_init = model.amortized_forward_pass(h_0) + h_s, _, _, _, _ = model.settle(h_init, x, remaining, t_final, prev_h=prev_h, prev_v=prev_v) + logits = model.readout(model.readout_norm(h_s[-1])) + if temperature > 0: + for pos in remaining.squeeze().nonzero(as_tuple=True)[0]: + probs = F.softmax(logits[0, pos] / temperature, dim=-1) + x[0, pos] = torch.multinomial(probs, 1).item() + else: + x[0, remaining.squeeze()] = logits[0, remaining.squeeze()].argmax(dim=-1) + + # Extract response + response_tokens = x[0, prompt_len:prompt_len + response_len].cpu().tolist() + return decode_tokens(response_tokens) + + +def main(): + parser = argparse.ArgumentParser(description="PC-SHO-DLM Chat") + parser.add_argument("--checkpoint", type=str, default=None) + parser.add_argument("--device", type=str, default="auto") + parser.add_argument("--temperature", type=float, default=0.8) + parser.add_argument("--response_len", type=int, default=256) + args = parser.parse_args() + + if args.device == "auto": + if torch.cuda.is_available(): args.device = "cuda" + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): args.device = "mps" + else: args.device = "cpu" + + ckpt_path = args.checkpoint or find_checkpoint() + if not ckpt_path or not os.path.exists(ckpt_path): + print("No checkpoint found. Train first:") + print(" python3 train_chat.py --data alpaca") + sys.exit(1) + + print(f"Loading {ckpt_path}...") + ckpt = torch.load(ckpt_path, map_location=args.device, weights_only=False) + config = ckpt["config"] + model = PCSHODLM(config).to(args.device) + model.load_state_dict(ckpt["model_state_dict"], strict=False) + model.eval() + print(f"Model: {sum(p.numel() for p in model.parameters()):,} params on {args.device}") + + print() + print("=" * 60) + print(" PC-SHO-DLM Chat") + print(" Conditional Masked Diffusion Chatbot") + print("=" * 60) + print() + print(" Type a message and the model generates a response.") + print(" The prompt stays fixed; the response is iteratively") + print(" denoised via predictive-coding energy minimization.") + print() + print(" /temp 0.5 Set temperature (0=greedy, 1=creative)") + print(" /len 512 Set response length") + print(" /quit Exit") + print() + + temp = args.temperature + resp_len = args.response_len + + while True: + try: + user_input = input("You> ").strip() + except (EOFError, KeyboardInterrupt): + print("\nBye!") + break + + if not user_input: + continue + if user_input.lower() in ["/quit", "/exit", "/q"]: + break + elif user_input.lower().startswith("/temp"): + try: temp = float(user_input.split()[1]) + except: pass + print(f" Temperature: {temp}") + continue + elif user_input.lower().startswith("/len"): + try: resp_len = int(user_input.split()[1]) + except: pass + print(f" Response length: {resp_len}") + continue + + print(" [Generating...]") + response = generate_response(model, user_input, response_len=resp_len, + device=args.device, temperature=temp) + # Clean up: strip trailing nulls/garbage + response = response.rstrip('\x00').strip() + print(f"\nBot> {response}\n") + + +if __name__ == "__main__": + main() diff --git a/checkpoints/backprop_1k/checkpoint_final.pt b/checkpoints/backprop_1k/checkpoint_final.pt new file mode 100644 index 0000000000000000000000000000000000000000..d5fe08257a0a0e2ae5df57dba28f4a42c4784c41 --- /dev/null +++ b/checkpoints/backprop_1k/checkpoint_final.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38b8018dae08bfc9075d6bfac79667077d44cd644a46648349e6a85f38428b3e +size 23465759 diff --git a/checkpoints/backprop_1k/training_log.json b/checkpoints/backprop_1k/training_log.json new file mode 100644 index 0000000000000000000000000000000000000000..a772ad86438d5a68184161f538b84d810e1f79dd --- /dev/null +++ b/checkpoints/backprop_1k/training_log.json @@ -0,0 +1,96 @@ +{ + "step": [ + 100, + 200, + 300, + 400, + 500, + 600, + 700, + 800, + 900, + 1000 + ], + "loss": [ + 3.973542594909668, + 3.2462473058700563, + 3.20215793132782, + 3.201729962825775, + 3.1888448429107665, + 3.1946746253967286, + 3.1782461738586427, + 3.180178542137146, + 3.1794990515708923, + 3.1801758503913877 + ], + "energy_initial": [ + 5270595.51, + 5267421.675, + 5297561.015, + 5288095.895, + 5311662.89, + 5295208.57, + 5298536.89, + 5305402.28, + 5263141.3, + 5298722.35 + ], + "energy_final": [ + 2167628.65875, + 2161769.35875, + 2170405.285, + 2168934.0225, + 2171327.31375, + 2167877.45375, + 2166740.25375, + 2171946.41875, + 2158902.235, + 2165013.49875 + ], + "stationarity_residual": [ + 3901.9395750427248, + 3898.7040367126465, + 3911.786459350586, + 3908.9566624450686, + 3914.174656524658, + 3906.5373867797853, + 3903.444817810059, + 3914.3790266418455, + 3894.4947831726076, + 3903.315328826904 + ], + "wall_time": [ + 114.7592351436615, + 234.22663807868958, + 352.5620460510254, + 485.0994050502777, + 639.9822609424591, + 1040.4187860488892, + 1186.257786989212, + 1349.9577169418335, + 1505.554505109787, + 1641.0701520442963 + ], + "val_loss": [ + [ + 500, + 3.194992378991592 + ], + [ + 1000, + 3.1876371541706154 + ] + ], + "tokens_per_sec": [ + 3569.2116585409594, + 3497.467268111434, + 3485.3439664408997, + 3377.4520911444724, + 3200.0886977461646, + 2362.125744896457, + 2417.012584825354, + 2427.335285303006, + 2448.5330736871483, + 2495.932300576898 + ] +} \ No newline at end of file diff --git a/checkpoints/chat/chat_final.pt b/checkpoints/chat/chat_final.pt new file mode 100644 index 0000000000000000000000000000000000000000..b646f0dbe1619aa7c4412b903c66d2766102435f --- /dev/null +++ b/checkpoints/chat/chat_final.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b5b607dfd71e7f0d24d645e3af48be34864e575b704b210f7c8ddb32a133a42 +size 42769221 diff --git a/checkpoints/chat/chat_step1000.pt b/checkpoints/chat/chat_step1000.pt new file mode 100644 index 0000000000000000000000000000000000000000..a81f4ed1fdf7c510b8e5130975784ea1cfd5ebee --- /dev/null +++ b/checkpoints/chat/chat_step1000.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:502f6ca445444da9f9e1c88bbc5ebbf7cbdeff3aa36ba6f4c8f4874621d76ba8 +size 42770163 diff --git a/checkpoints/chat/chat_step1500.pt b/checkpoints/chat/chat_step1500.pt new file mode 100644 index 0000000000000000000000000000000000000000..a955a4c3445676e960211208ce7c722bb02c403f --- /dev/null +++ b/checkpoints/chat/chat_step1500.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c41874a395fef739961bb65451f27508029b56bb47202e9a4db14c36c5d5de9 +size 42770163 diff --git a/checkpoints/chat/chat_step2000.pt b/checkpoints/chat/chat_step2000.pt new file mode 100644 index 0000000000000000000000000000000000000000..6ea90d8c208f44e61e9643fa2b3fb07af8b8e4c4 --- /dev/null +++ b/checkpoints/chat/chat_step2000.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e245f4d24200074dd971e45355ee687343efe8ebaadcc55f7158ecf252e78be6 +size 42770163 diff --git a/checkpoints/chat/chat_step500.pt b/checkpoints/chat/chat_step500.pt new file mode 100644 index 0000000000000000000000000000000000000000..07c413b01c3559a8f37d295ea3e17ba587b53784 --- /dev/null +++ b/checkpoints/chat/chat_step500.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7517356a64c7e488f8268c09614b8f745cbbfde2135f561c562c09d756165da0 +size 42769849 diff --git a/checkpoints/checkpoint_final.pt b/checkpoints/checkpoint_final.pt new file mode 100644 index 0000000000000000000000000000000000000000..d15255664ebbc6bc50123ac2b7d95ae2b2ce3878 --- /dev/null +++ b/checkpoints/checkpoint_final.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f131ad73eee730d001ca4b1059527b827cb2fdb8c9fa13be9f0495b7ecb60e6 +size 16091587 diff --git a/checkpoints/local_pc_1k/checkpoint_final.pt b/checkpoints/local_pc_1k/checkpoint_final.pt new file mode 100644 index 0000000000000000000000000000000000000000..1ac6c853f73e837ceaccaf502392d034335cab7a --- /dev/null +++ b/checkpoints/local_pc_1k/checkpoint_final.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a7f7e2003540fb4077812024540c36ddd3745ffaf318338e150948be51a8476 +size 23465759 diff --git a/checkpoints/local_pc_1k/training_log.json b/checkpoints/local_pc_1k/training_log.json new file mode 100644 index 0000000000000000000000000000000000000000..a85ad5e15be9d407b77c74f6707e7831dbbae067 --- /dev/null +++ b/checkpoints/local_pc_1k/training_log.json @@ -0,0 +1,96 @@ +{ + "step": [ + 100, + 200, + 300, + 400, + 500, + 600, + 700, + 800, + 900, + 1000 + ], + "loss": [ + 4.258981928825379, + 3.336215796470642, + 3.2282044744491576, + 3.2040278053283693, + 3.1845848608016967, + 3.1786249399185182, + 3.1659100317955016, + 3.1637249565124512, + 3.161261990070343, + 3.167942237854004 + ], + "energy_initial": [ + 833023.37125, + 341392.37125, + 266566.16546875, + 231912.27, + 214780.41046875, + 204189.7409375, + 196751.30359375, + 191164.40421875, + 185644.6478125, + 180652.7578125 + ], + "energy_final": [ + 554832.4546875, + 269502.8328125, + 210375.1321875, + 184373.66765625, + 172335.49625, + 165377.38859375, + 160904.538125, + 157588.87328125, + 154221.20390625, + 151236.68453125 + ], + "stationarity_residual": [ + 1561.5680824279784, + 929.1791234207153, + 735.0096200180054, + 647.4497012710572, + 609.4694246673585, + 590.0452673149109, + 580.4542396354675, + 576.9368585586548, + 572.0829350090027, + 569.5673301887513 + ], + "wall_time": [ + 147.88746404647827, + 299.2261378765106, + 460.55058312416077, + 654.5177249908447, + 825.0155017375946, + 1292.595095872879, + 1495.5974118709564, + 1665.1974637508392, + 1813.2391319274902, + 1930.159700870514 + ], + "val_loss": [ + [ + 500, + 3.1764627510126946 + ], + [ + 1000, + 3.165879757393407 + ] + ], + "tokens_per_sec": [ + 2769.673566592976, + 2737.7287486097903, + 2668.1108330476814, + 2503.2171588980536, + 2482.3775985864922, + 1901.2914468319273, + 1917.0934485726355, + 1967.8146714318455, + 2033.0467918378324, + 2122.10419591326 + ] +} \ No newline at end of file diff --git a/checkpoints/local_pc_wiki_lambda_fixed/checkpoint_final.pt b/checkpoints/local_pc_wiki_lambda_fixed/checkpoint_final.pt new file mode 100644 index 0000000000000000000000000000000000000000..7039ae651443888fc6bba58a8bf40dc88cb2f9b6 --- /dev/null +++ b/checkpoints/local_pc_wiki_lambda_fixed/checkpoint_final.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:baa12367a523e90ef8b743035b26749b1e0d174fad696669a8cb5a20b39f5cbd +size 42509025 diff --git a/checkpoints/local_pc_wiki_lambda_fixed/checkpoint_step_2000.pt b/checkpoints/local_pc_wiki_lambda_fixed/checkpoint_step_2000.pt new file mode 100644 index 0000000000000000000000000000000000000000..69010764aa5751fba91ad29c2c7b0073536754bc --- /dev/null +++ b/checkpoints/local_pc_wiki_lambda_fixed/checkpoint_step_2000.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a87fc58b9d7ae96bbd5471996db14370f09e43b86b6d823348d76e1af145f11d +size 42510281 diff --git a/checkpoints/local_pc_wiki_lambda_fixed/training_log.json b/checkpoints/local_pc_wiki_lambda_fixed/training_log.json new file mode 100644 index 0000000000000000000000000000000000000000..cf3312bc4d612c7d1242e07e5197b2774ee97f92 --- /dev/null +++ b/checkpoints/local_pc_wiki_lambda_fixed/training_log.json @@ -0,0 +1,462 @@ +{ + "step": [ + 50, + 100, + 150, + 200, + 250, + 300, + 350, + 400, + 450, + 500, + 550, + 600, + 650, + 700, + 750, + 800, + 850, + 900, + 950, + 1000, + 1050, + 1100, + 1150, + 1200, + 1250, + 1300, + 1350, + 1400, + 1450, + 1500, + 1550, + 1600, + 1650, + 1700, + 1750, + 1800, + 1850, + 1900, + 1950, + 2000, + 2050, + 2100, + 2150, + 2200, + 2250, + 2300, + 2350, + 2400, + 2450, + 2500, + 2550, + 2600, + 2650, + 2700, + 2750, + 2800, + 2850, + 2900, + 2950, + 3000 + ], + "loss": [ + 0.21437864273786544, + 0.06857220411300659, + 0.035148728638887405, + 0.020972895678132774, + 0.013533507781103253, + 0.008646295601502062, + 0.0061453641159459945, + 0.004681998491287231, + 0.0033234256599098443, + 0.002539557530544698, + 0.0020994919049553574, + 0.0019077495508827268, + 0.0015839052782393992, + 0.0013997956831008195, + 0.0012919189885724335, + 0.0011379401991143824, + 0.0010197754809632897, + 0.0009524802933447063, + 0.0009402855590451509, + 0.000933931681793183, + 0.0008880252955714241, + 0.0007404407643480227, + 0.0007191342004807666, + 0.0006912627309793606, + 0.0006465482013300061, + 0.0006812598794931546, + 0.0006511295342352242, + 0.0006275616912171244, + 0.0005930715601425618, + 0.0005344201344996691, + 0.0005560434464132413, + 0.0005294423777377232, + 0.0004877809778554365, + 0.0004382653089123778, + 0.0004203213079017587, + 0.00039554817631142213, + 0.00039055546949384734, + 0.000328213750035502, + 0.0003372134832898155, + 0.0003075990959769115, + 0.0003370191325666383, + 0.00023736593255307525, + 0.0002483331604162231, + 0.00025497345719486473, + 0.0001915762400312815, + 0.00019251465288107285, + 0.00019092288392130285, + 0.00019388364802580327, + 0.00016434719480457716, + 0.0001352085336111486, + 0.00011794728372478858, + 0.00014831473417871167, + 0.00011608733126195148, + 8.511820582498331e-05, + 8.775017347943503e-05, + 0.00010035085459094262, + 5.40398766315775e-05, + 7.603460144309793e-05, + 8.572758386435453e-05, + 6.787052403524285e-05 + ], + "energy_initial": [ + 7698684.3, + 6107091.13, + 5852354.26, + 5848288.87, + 5937238.27, + 5706541.045, + 5813235.275, + 6029184.51, + 5949668.485, + 5744343.065, + 5896261.11, + 6125549.59, + 6070470.95, + 6229371.64, + 6058217.295, + 6054126.04, + 6039307.94, + 5924170.35, + 6017140.885, + 5817855.76, + 6018289.2, + 5984032.64, + 5971326.27, + 6154519.66, + 5873810.01, + 5986345.085, + 5936406.99, + 6091542.26, + 5925722.0, + 5945736.025, + 5962467.03, + 5780643.0, + 5900887.37, + 6127922.5, + 6164705.94, + 5931382.21, + 5883905.46, + 5932295.24, + 6094541.57, + 6033401.53, + 5720540.8, + 5947334.405, + 5955467.49, + 6072561.455, + 5809340.885, + 6075700.67, + 5956099.91, + 6075797.79, + 6242412.85, + 6106390.29, + 5953161.19, + 6179365.98, + 6157424.08, + 6094414.41, + 6175474.25, + 6020570.29, + 6047099.055, + 6029787.67, + 6218495.38, + 6081523.8 + ], + "energy_final": [ + 1652554.96375, + 705944.41125, + 607953.49375, + 572285.07875, + 537746.90125, + 494917.79125, + 473506.921875, + 457005.64875, + 438494.308125, + 416447.076875, + 406914.03, + 400999.99, + 390525.980625, + 384762.0225, + 373795.095625, + 368545.7475, + 363369.811875, + 357510.87875, + 357484.321875, + 353577.7525, + 357915.508125, + 362979.398125, + 371097.1375, + 380386.156875, + 387829.081875, + 399150.586875, + 409923.39875, + 416817.498125, + 421484.156875, + 427243.47125, + 432332.433125, + 435388.8875, + 439161.039375, + 438539.3175, + 440151.813125, + 443108.650625, + 444380.25125, + 443640.124375, + 442540.393125, + 444312.621875, + 446053.64125, + 444830.1425, + 447178.676875, + 447786.30125, + 448424.36625, + 450646.51125, + 451476.01375, + 453405.551875, + 456309.660625, + 459526.745, + 461789.379375, + 467258.625, + 471400.43125, + 476037.479375, + 482717.544375, + 489311.323125, + 496543.541875, + 504736.0525, + 514683.98125, + 522998.31875 + ], + "stationarity_residual": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "wall_time": [ + 46.83224701881409, + 93.27795815467834, + 144.22594499588013, + 187.70664811134338, + 223.2145059108734, + 258.57073402404785, + 305.0492169857025, + 383.0472061634064, + 451.9058039188385, + 535.2478311061859, + 1005.1899790763855, + 1116.8730499744415, + 1236.574786901474, + 1339.8828241825104, + 1423.296756029129, + 1506.158792257309, + 1577.9990320205688, + 1657.4707880020142, + 1743.5079112052917, + 1819.936054944992, + 2085.8407900333405, + 2149.638072013855, + 2208.5191662311554, + 2267.8005650043488, + 2329.4335021972656, + 2393.2623631954193, + 2461.015599966049, + 2525.264710187912, + 2585.4516730308533, + 2651.2439770698547, + 2901.422744035721, + 2962.9505100250244, + 3024.1742990016937, + 3087.3891592025757, + 3146.6180799007416, + 3204.875967025757, + 3270.302752017975, + 3331.1951899528503, + 3391.0012259483337, + 3451.4704518318176, + 3729.473039150238, + 3795.7775888442993, + 3854.923315048218, + 3914.674096107483, + 3973.7355649471283, + 4033.9523270130157, + 4101.106842041016, + 4168.646975040436, + 4235.202388286591, + 4298.994647979736, + 4530.3150498867035, + 4593.397349119186, + 4659.151156902313, + 4729.11607003212, + 4799.21485710144, + 4870.703770160675, + 4937.933058023453, + 5006.13449215889, + 5070.305644989014, + 5133.637190103531 + ], + "val_loss": [ + [ + 500, + 0.0019980114247109305 + ], + [ + 1000, + 0.0006265220506625516 + ], + [ + 1500, + 0.0004066362535410008 + ], + [ + 2000, + 0.00019371463765036995 + ], + [ + 2500, + 8.949936562472213e-05 + ], + [ + 3000, + 2.2330263250989578e-05 + ] + ], + "tokens_per_sec": [ + 4373.055171103043, + 4391.176737818168, + 4259.982488015943, + 4364.256717823169, + 4587.515474504465, + 4752.27795843948, + 4699.569512637668, + 4277.279598016609, + 4078.7261062286234, + 3826.264920620864, + 2241.168382985648, + 2200.4291356624994, + 2153.0440602555573, + 2139.8886143266573, + 2158.369283838323, + 2175.6006185038414, + 2206.338489030593, + 2224.1115962253207, + 2231.82239380262, + 2250.628525585094, + 2061.9023372015154, + 2095.9807414366264, + 2132.831841363782, + 2167.386354800813, + 2197.95928717025, + 2224.912772576455, + 2246.8772648480094, + 2270.8114428024805, + 2297.1614832149003, + 2317.4027185496248, + 2188.1678611125676, + 2211.84929610743, + 2234.7918247407256, + 2255.368416788276, + 2278.0012756508763, + 2300.494644990031, + 2317.0943409823944, + 2336.218551069099, + 2355.410531521198, + 2373.481133425962, + 2251.47089464232, + 2266.0969455322934, + 2284.4553004784866, + 2301.9029882871214, + 2319.228305299329, + 2335.3771280127485, + 2347.073697599545, + 2358.175220607316, + 2369.4735410413005, + 2381.95225593318, + 2305.535020188322, + 2318.4582544425707, + 2329.6947522124747, + 2338.5342707236377, + 2347.0505771027442, + 2354.6494595424074, + 2364.0660703230933, + 2372.768853614529, + 2383.1304946954892, + 2393.6245482420204 + ] +} \ No newline at end of file diff --git a/checkpoints/training_log.json b/checkpoints/training_log.json new file mode 100644 index 0000000000000000000000000000000000000000..decee68eec1b0cd28cce32c91b0108bba130e8b2 --- /dev/null +++ b/checkpoints/training_log.json @@ -0,0 +1,45 @@ +{ + "step": [ + 25, + 50, + 75, + 100 + ], + "loss": [ + 4.83566909790039, + 4.001754846572876, + 3.6740700721740724, + 3.5564898300170897 + ], + "energy_initial": [ + 1551801.665, + 1532687.17, + 1541912.385, + 1559144.77 + ], + "energy_final": [ + 605239.6925, + 603282.4875, + 602236.6225, + 604062.935 + ], + "stationarity_residual": [ + 1552.1239495849609, + 1549.458076171875, + 1548.9330493164061, + 1552.3543615722656 + ], + "wall_time": [ + 15.414806127548218, + 20.527431964874268, + 25.813805103302002, + 31.105968236923218 + ], + "val_loss": [], + "tokens_per_sec": [ + 3321.4819295391003, + 4988.446688081726, + 5950.304474110719, + 6583.945512967493 + ] +} \ No newline at end of file diff --git a/checkpoints/unified_wiki_lambda_fixed/checkpoint_step_2000.pt b/checkpoints/unified_wiki_lambda_fixed/checkpoint_step_2000.pt new file mode 100644 index 0000000000000000000000000000000000000000..14cf8766a6b24bc887cc73bc640bd3b136a76895 --- /dev/null +++ b/checkpoints/unified_wiki_lambda_fixed/checkpoint_step_2000.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:71cc3e02290be38b9f031d4bbe95b8858f07dbbd2cda48be0bef91df363fec0e +size 42510281 diff --git a/data/ao3-metadata/fandoms.csv b/data/ao3-metadata/fandoms.csv new file mode 100644 index 0000000000000000000000000000000000000000..bd15b631b56d9c1a5aa98d388aa3f76a86836f41 --- /dev/null +++ b/data/ao3-metadata/fandoms.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f200e02b76d0202264555fe51c6cc1e3442ed9fb0f88fa9e6db065ab8035d0d1 +size 8647151 diff --git a/data/ao3-metadata/random works - Oct 2024 - tag binary - 200.csv b/data/ao3-metadata/random works - Oct 2024 - tag binary - 200.csv new file mode 100644 index 0000000000000000000000000000000000000000..c60d592e4c5a09c8f99103b374fdd87ecf698911 --- /dev/null +++ b/data/ao3-metadata/random works - Oct 2024 - tag binary - 200.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12dafe2f91021e2d49527edd2240a5c2ab23c733b589cc1a197619fddfd21a02 +size 174738654 diff --git a/data/ao3-metadata/random works - Oct 2024 - tag binary.csv b/data/ao3-metadata/random works - Oct 2024 - tag binary.csv new file mode 100644 index 0000000000000000000000000000000000000000..5fb4f25acfb4ed303961b9dfe26eb13ac82af105 --- /dev/null +++ b/data/ao3-metadata/random works - Oct 2024 - tag binary.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84131d59bcee631bd06eb22ad5079f8fb1879234a697508d36940f1e13ca99fd +size 1221483677 diff --git a/data/ao3-metadata/random works - Oct 2025 - fix indecies.csv b/data/ao3-metadata/random works - Oct 2025 - fix indecies.csv new file mode 100644 index 0000000000000000000000000000000000000000..14afb0b766a5eb0dd1363e7ac53969b1c2f30dcb --- /dev/null +++ b/data/ao3-metadata/random works - Oct 2025 - fix indecies.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95e5f7c8415b24a05754433c419c8974f7480bd397a91a0a102c42e55180a009 +size 63870415 diff --git a/data/ao3-metadata/random works - Oct 2025 - top tags - 200.csv b/data/ao3-metadata/random works - Oct 2025 - top tags - 200.csv new file mode 100644 index 0000000000000000000000000000000000000000..71eae8b2b01db106217c48cb17bad7678640a688 --- /dev/null +++ b/data/ao3-metadata/random works - Oct 2025 - top tags - 200.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1dddee657a76495c1192250d6e1dceffeb674f8cfeb50ecefb95f8668147b897 +size 26079 diff --git a/data/ao3-metadata/random works - Oct 2025 - top tags.csv b/data/ao3-metadata/random works - Oct 2025 - top tags.csv new file mode 100644 index 0000000000000000000000000000000000000000..a41a30f4ffa7e5678c6b58757be9d1316708c3eb --- /dev/null +++ b/data/ao3-metadata/random works - Oct 2025 - top tags.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc80d1b33d11ff974e765ff4b354b0098aa74b45d61005f1455cf5f54e726d7b +size 283715 diff --git a/data/ao3-metadata/random works - Oct 2025.csv b/data/ao3-metadata/random works - Oct 2025.csv new file mode 100644 index 0000000000000000000000000000000000000000..e2e9e51169fc2d7ed28625d51284e2572f5f83c9 --- /dev/null +++ b/data/ao3-metadata/random works - Oct 2025.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3a4ca256abca1dcaf0c237ff26498c9d2a6dd6a5124f059c087361e6400906a2 +size 63687379 diff --git a/data/python_code.txt b/data/python_code.txt new file mode 100644 index 0000000000000000000000000000000000000000..d773895275bc226f0d7fb918989da315a0aa78fb --- /dev/null +++ b/data/python_code.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:283ee7a13da2b086eebff5e80a1b1af07e1bcdfa946671729407e18019ad6196 +size 10017726 diff --git a/data/tinystories_val.txt b/data/tinystories_val.txt new file mode 100644 index 0000000000000000000000000000000000000000..496edd4790205b830a408ac44c61bcda82adf05a --- /dev/null +++ b/data/tinystories_val.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85b60248b6b837e31755e8992d9c926177f0bff65c55072bd33ff8cccf5a58cf +size 19240339 diff --git a/data/wikitext-103/LICENSE.txt b/data/wikitext-103/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..787c781810deda5221e606ff228ccb1abc40f4c2 --- /dev/null +++ b/data/wikitext-103/LICENSE.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb21dc59e69079967d10f54aaa408c2ba548210aea16babf57b4d5f2e8f169c5 +size 22242 diff --git a/data/wikitext-103/README.txt b/data/wikitext-103/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..3e91a22fc4910b661a9f7b9c465fbb39120a62be --- /dev/null +++ b/data/wikitext-103/README.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b50ff59fefaf57b1af4cd875ef0fde65f9bbf8db7ffb5ad64e43084ef3f66bf +size 371 diff --git a/data/wikitext-103/wiki.test.tokens b/data/wikitext-103/wiki.test.tokens new file mode 100644 index 0000000000000000000000000000000000000000..b89bb16abb1d929dd48bda4cf5b7907576798dc3 --- /dev/null +++ b/data/wikitext-103/wiki.test.tokens @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56db52eb157b1ab5c89646eef70510c1eca6e12a3bfdb99f0d6b05b4eacb75b9 +size 1281077 diff --git a/data/wikitext-103/wiki.train.tokens b/data/wikitext-103/wiki.train.tokens new file mode 100644 index 0000000000000000000000000000000000000000..8d2c491682ebce6be1cdb3b679a4f56b9b21acf1 --- /dev/null +++ b/data/wikitext-103/wiki.train.tokens @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2082f99929dee10a3b96da7d6ef7ca4dbb4d7df9d51db264f14173a36989f826 +size 539209157 diff --git a/data/wikitext-103/wiki.valid.tokens b/data/wikitext-103/wiki.valid.tokens new file mode 100644 index 0000000000000000000000000000000000000000..c3dc467cb2b6a0d15b8739e5e3040ad8bcdf3b5b --- /dev/null +++ b/data/wikitext-103/wiki.valid.tokens @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9aee9f52d6e77de6c7751fc5e7c44287db3ec0eaf15477098acc6b93c1c4250b +size 1142309 diff --git a/diagnostics_output/diagnostics.json b/diagnostics_output/diagnostics.json new file mode 100644 index 0000000000000000000000000000000000000000..0fbdd1b6c800790e8e780785b3ba5d9bddca6d22 --- /dev/null +++ b/diagnostics_output/diagnostics.json @@ -0,0 +1,130 @@ +{ + "stationarity": { + "2": { + "stationarity_residual": 1200.3260688781738, + "energy": 176276.640625 + }, + "4": { + "stationarity_residual": 764.5930786132812, + "energy": 137036.515625 + }, + "8": { + "stationarity_residual": 476.9359664916992, + "energy": 110008.8125 + }, + "16": { + "stationarity_residual": 306.9395751953125, + "energy": 89895.734375 + } + }, + "hessian": { + "eigenvalues": [ + 0.24301810562610626, + 0.41752108931541443, + 1.0334908962249756, + 1.3541364669799805, + 2.169743776321411, + 2.450981378555298, + 3.0029847621917725, + 3.4423043727874756, + 4.003973007202148, + 4.973252296447754 + ], + "lambda_min": 0.24301810562610626, + "lambda_max": 4.973252296447754, + "effective_kappa": 20.46453404627931 + }, + "monotonicity": { + "potential_energies": [ + 366367.34375, + 225438.8125, + 175794.296875, + 151354.890625, + 136789.5625, + 127010.2890625, + 119876.6328125, + 114350.75, + 109876.9140625, + 106133.8046875, + 102923.390625, + 100117.0234375, + 97627.109375, + 95391.6015625, + 93365.0234375, + 91513.109375 + ], + "kinetic_energies": [ + 5606.288420778961, + 1861.3425807472438, + 876.1042447986551, + 508.8102243544282, + 336.10912394027946, + 242.68130300539553, + 186.8547363422431, + 150.827149615861, + 126.0891513161979, + 108.22230372848355, + 94.77399205873564, + 84.30399400153124, + 75.9253957528357, + 69.06781523144457, + 63.350062110544286, + 58.50883019699609 + ], + "total_energies": [ + 371973.63217077893, + 227300.15508074724, + 176670.40111979865, + 151863.70084935444, + 137125.6716239403, + 127252.97036550539, + 120063.48754884224, + 114501.57714961586, + 110003.00321381619, + 106242.02699122849, + 103018.16461705873, + 100201.32743150153, + 97703.03477075284, + 95460.66937773145, + 93428.37349961055, + 91571.618205197 + ], + "n_violations": 0, + "violation_rate": 0.0 + }, + "precision": { + "pearson_prec_inv_error": -0.14354610443115234, + "rank_correlation": 0.20927321910858154, + "mean_precision": 0.6959661245346069, + "mean_sq_error": 0.02698444202542305 + }, + "contraction": { + "distances": [ + 14.491872787475586, + 13.412360668182373, + 12.603797197341919, + 11.945123672485352, + 11.38826036453247, + 10.908653974533081, + 10.490684747695923, + 10.123239278793335, + 9.7978835105896 + ], + "contraction_factors": [ + 0.9255091363880749, + 0.9397150515972496, + 0.9477400727301866, + 0.9533815368328441, + 0.9578858952423434, + 0.9616846195861622, + 0.9649741196366338, + 0.9678605079615863 + ], + "avg_contraction": 0.9523438674968852, + "is_contractive": true + }, + "freeze_accuracy": { + "adaptive_vs_full_match": 0.9121338725090027, + "early_stable_rate": 1.0 + } +} \ No newline at end of file diff --git a/experiments/ablation_runner.py b/experiments/ablation_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..9710ca94d403c32ba7e47d1a61b92c2eb41733a4 --- /dev/null +++ b/experiments/ablation_runner.py @@ -0,0 +1,290 @@ +""" +PC-SHO-DLM Ablation Study Runner + +Runs the critical ablations defined in the paper: +1. First-order vs second-order settling +2. Fixed vs learned precision +3. Cold-start vs warm-start (state continuation) +4. Uniform vs adaptive settling +5. Forward-only vs bidirectional PC +6. Tied vs learned feedback +""" + +import json +import os +import sys +import time +from dataclasses import dataclass, field, asdict +from pathlib import Path +from typing import Optional + +import torch + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters +from train import CharLevelDataset, Trainer + + +@dataclass +class AblationConfig: + """Configuration for an ablation experiment.""" + name: str + description: str + + # Architecture overrides + use_second_order: bool = True + use_learned_precision: bool = True + use_state_continuation: bool = True + use_adaptive_settling: bool = True + use_feedback: bool = True + tied_feedback: bool = False + + # Training + training_mode: str = "local" + max_steps: int = 2000 + batch_size: int = 16 + lr: float = 1e-4 + seq_len: int = 128 + n_settling: int = 8 + + # Model + d_model: int = 256 + n_layers: int = 4 + n_heads: int = 4 + n_diffusion: int = 100 + + +# ============================================================================= +# Define ablation experiments +# ============================================================================= + +ABLATIONS = [ + # Full model (baseline) + AblationConfig( + name="full_model", + description="Full PC-SHO-DLM with all components", + ), + + # Ablation 1: First-order settling (no momentum) + AblationConfig( + name="first_order", + description="First-order settling (gamma=1, no velocity)", + use_second_order=False, + ), + + # Ablation 2: Fixed precision (no learned precision heads) + AblationConfig( + name="fixed_precision", + description="Fixed uniform precision (no learned heads)", + use_learned_precision=False, + ), + + # Ablation 3: No state continuation (cold restart each step) + AblationConfig( + name="no_continuation", + description="Cold restart at each diffusion step", + use_state_continuation=False, + ), + + # Ablation 4: No adaptive settling (all tokens always active) + AblationConfig( + name="no_adaptive", + description="Uniform settling (no token freezing)", + use_adaptive_settling=False, + ), + + # Ablation 5: No feedback (forward-only, no top-down) + AblationConfig( + name="no_feedback", + description="Forward-only stack (no top-down predictions)", + use_feedback=False, + ), + + # Ablation 6: Tied feedback (transpose of forward weights) + AblationConfig( + name="tied_feedback", + description="Tied feedback (weight transpose)", + tied_feedback=True, + ), + + # Ablation 7: Standard backprop training (for comparison) + AblationConfig( + name="backprop_baseline", + description="Standard backprop training (not local)", + training_mode="backprop", + ), + + # Ablation 8: Varying settling steps + AblationConfig( + name="settling_k2", + description="Only 2 settling steps", + n_settling=2, + ), + AblationConfig( + name="settling_k16", + description="16 settling steps", + n_settling=16, + ), +] + + +def create_model_from_ablation(ablation: AblationConfig) -> PCSHODLM: + """Create a model configured for a specific ablation.""" + config = PCSHOConfig( + vocab_size=257, + max_seq_len=ablation.seq_len, + d_model=ablation.d_model, + n_heads=ablation.n_heads, + n_layers=ablation.n_layers, + d_ff=ablation.d_model * 4, + n_diffusion_steps=ablation.n_diffusion, + n_settling_steps=ablation.n_settling, + mask_token_id=0, + ) + + # Apply ablation modifications + if not ablation.use_second_order: + # Force first-order by setting gamma_min = gamma_max = 1 + config.gamma_min = 1.0 + config.gamma_max = 1.0 + + if not ablation.use_state_continuation: + config.velocity_decay = 0.0 # No velocity carry-over + + if not ablation.use_adaptive_settling: + config.settling_threshold = float("inf") # Never freeze tokens + + if not ablation.use_feedback: + config.feedback_rank = 0 # Will need model modification + + model = PCSHODLM(config) + + if not ablation.use_learned_precision: + # Replace precision heads with fixed uniform precision + for ph in list(model.precision_up) + list(model.precision_down): + for param in ph.parameters(): + param.requires_grad = False + + return model + + +def run_ablation( + ablation: AblationConfig, + data_text: str, + output_dir: Path, + device: str = "cpu", +): + """Run a single ablation experiment.""" + print(f"\n{'='*60}") + print(f"Ablation: {ablation.name}") + print(f"Description: {ablation.description}") + print(f"{'='*60}") + + # Create model + model = create_model_from_ablation(ablation) + print(f"Parameters: {count_parameters(model):,}") + + # Create dataset + dataset = CharLevelDataset(data_text, ablation.seq_len, vocab_size=257) + n_val = max(1, len(dataset) // 10) + n_train = len(dataset) - n_val + train_dataset, val_dataset = torch.utils.data.random_split( + dataset, [n_train, n_val] + ) + + # Train + save_dir = output_dir / ablation.name + trainer = Trainer( + model=model, + train_dataset=train_dataset, + val_dataset=val_dataset, + training_mode=ablation.training_mode, + lr=ablation.lr, + batch_size=ablation.batch_size, + max_steps=ablation.max_steps, + log_interval=100, + eval_interval=500, + save_dir=str(save_dir), + device=device, + ) + + start = time.time() + trainer.train() + elapsed = time.time() - start + + # Save ablation config and results + results = { + "config": asdict(ablation), + "n_params": count_parameters(model), + "wall_time": elapsed, + "training_log": trainer.log, + } + with open(save_dir / "ablation_results.json", "w") as f: + json.dump(results, f, indent=2) + + print(f"Completed in {elapsed:.1f}s") + return results + + +def run_all_ablations( + data_path: Optional[str] = None, + output_dir: str = "ablation_results", + device: str = "cpu", + ablation_names: Optional[list] = None, +): + """Run all ablation experiments.""" + output_path = Path(output_dir) + output_path.mkdir(parents=True, exist_ok=True) + + # Load data + if data_path and os.path.exists(data_path): + with open(data_path, "r") as f: + text = f.read() + else: + print("Using synthetic data for ablation experiments.") + text = "The quick brown fox jumps over the lazy dog. " * 5000 + + # Filter ablations if specified + if ablation_names: + ablations = [a for a in ABLATIONS if a.name in ablation_names] + else: + ablations = ABLATIONS + + all_results = {} + for ablation in ablations: + results = run_ablation(ablation, text, output_path, device) + all_results[ablation.name] = results + + # Summary + print(f"\n{'='*60}") + print("ABLATION SUMMARY") + print(f"{'='*60}") + for name, results in all_results.items(): + log = results["training_log"] + final_loss = log["loss"][-1] if log["loss"] else "N/A" + print(f"{name:25s} | Loss: {final_loss:>8} | Time: {results['wall_time']:.1f}s") + + # Save summary + with open(output_path / "summary.json", "w") as f: + json.dump( + {name: {"final_loss": r["training_log"]["loss"][-1] if r["training_log"]["loss"] else None, + "wall_time": r["wall_time"]} + for name, r in all_results.items()}, + f, indent=2, + ) + + return all_results + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--data", type=str, default=None) + parser.add_argument("--output", type=str, default="ablation_results") + parser.add_argument("--device", type=str, default="cpu") + parser.add_argument("--ablations", nargs="+", default=None, + help="Specific ablation names to run") + args = parser.parse_args() + + run_all_ablations(args.data, args.output, args.device, args.ablations) diff --git a/experiments/diagnostics.py b/experiments/diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..ff5aab7b005e4507f810f19e72720e331247696d --- /dev/null +++ b/experiments/diagnostics.py @@ -0,0 +1,596 @@ +""" +PC-SHO-DLM Assumption Diagnostics + +Empirical diagnostics to validate the theoretical assumptions: +1. Stationarity residual (envelope theorem support) +2. Local Hessian spectrum via HVP + Lanczos (curvature/kappa estimation) +3. Energy monotonicity statistics (discrete-time Lyapunov check) +4. Precision calibration (predicted precision vs empirical squared error) +5. Warm-start drift measurement (tracking theorem support) +6. Token freeze accuracy (soft-gate reliability) +7. Contraction estimation (solver contractivity) +""" + +import json +import math +import os +import sys +from pathlib import Path +from typing import Optional + +import torch +import torch.nn.functional as F + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) +from model import PCSHODLM, PCSHOConfig + + +# ============================================================================= +# 1. Stationarity Residual +# ============================================================================= + +def measure_stationarity_residual( + model: PCSHODLM, + x_0: torch.Tensor, + settling_steps_list: list[int] = [2, 4, 8, 16, 32], + device: str = "cpu", +) -> dict: + """Measure ||grad_h E_t(h^(K))|| as a function of K. + + Validates envelope theorem: low residual means post-settling local + updates are approximately exact gradients of the reduced objective. + """ + model = model.to(device).eval() + x_0 = x_0.to(device) + B, S = x_0.shape + + t = torch.full((B,), model.config.n_diffusion_steps // 2, device=device, dtype=torch.long) + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + results = {} + for K in settling_steps_list: + model.config.n_settling_steps = K + model.config.settling_threshold = float("inf") + + h = [hi.detach() for hi in h_init] + v = [torch.zeros_like(h_init[l + 1]) for l in range(model.config.n_layers)] + + for k in range(K): + h, v, energy = model.settling_step(h, v, h_init, x_0, mask, t, None) + + # Compute final gradient norm + L = model.config.n_layers + for l in range(1, L + 1): + h[l] = h[l].detach().requires_grad_(True) + + with torch.enable_grad(): + _, _, _, energy = model.compute_energy_gradient(h, h_init, x_0, mask, t) + + grad_norms = [] + for l in range(1, L + 1): + if h[l].grad is not None: + grad_norms.append(h[l].grad.detach().norm().item()) + + # Re-compute via autograd + h_params = [h[l + 1] for l in range(L)] + for l in range(1, L + 1): + h[l] = h[l].detach().requires_grad_(True) + + with torch.enable_grad(): + grad_h, _, _, energy_val = model.compute_energy_gradient(h, h_init, x_0, mask, t) + + total_residual = sum(g.detach().norm().item() for g in grad_h) + + results[K] = { + "stationarity_residual": total_residual, + "energy": energy_val, + } + print(f" K={K:3d}: residual={total_residual:.4f}, energy={energy_val:.2f}") + + return results + + +# ============================================================================= +# 2. Local Hessian Spectrum via HVP + Lanczos +# ============================================================================= + +def hessian_vector_product( + model: PCSHODLM, + h: list[torch.Tensor], + h_init: list[torch.Tensor], + x_0: torch.Tensor, + mask: torch.Tensor, + t: torch.Tensor, + v_dir: list[torch.Tensor], +) -> list[torch.Tensor]: + """Compute Hessian-vector product d^2 E / dh^2 @ v using double autograd.""" + L = model.config.n_layers + + with torch.enable_grad(): + # First: compute gradient with create_graph=True for second derivatives + for l in range(1, L + 1): + h[l] = h[l].detach().requires_grad_(True) + + # Re-compute energy directly (need graph for second derivative) + mu_up, mu_down = model.compute_predictions(h) + eps_up = [h[l + 1] - mu_up[l] for l in range(L)] + + energy = 0.0 + for l in range(L): + energy += 0.5 * (eps_up[l] ** 2).sum() + energy += model.config.anchor_rho * sum( + ((h[l + 1] - h_init[l + 1]) ** 2).sum() for l in range(L) + ) + + h_params = [h[l + 1] for l in range(L)] + grads = torch.autograd.grad(energy, h_params, create_graph=True) + + # Dot product with direction + dot = sum((g * vd).sum() for g, vd in zip(grads, v_dir)) + + # Second derivative + hvp = torch.autograd.grad(dot, h_params, create_graph=False) + + return [hv.detach() for hv in hvp] + + +def estimate_hessian_spectrum_lanczos( + model: PCSHODLM, + x_0: torch.Tensor, + n_lanczos_steps: int = 20, + device: str = "cpu", +) -> dict: + """Estimate extremal eigenvalues of the energy Hessian via Lanczos iteration. + + Returns approximate lambda_min, lambda_max, and effective kappa. + """ + model = model.to(device).eval() + x_0 = x_0.to(device) + B, S = x_0.shape + L = model.config.n_layers + + t = torch.full((B,), model.config.n_diffusion_steps // 2, device=device, dtype=torch.long) + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + # Settle to approximate fixed point + model.config.n_settling_steps = 16 + model.config.settling_threshold = float("inf") + h_settled, _, _, _, _ = model.settle(h_init, x_0, mask, t) + + # Lanczos iteration + # Flatten h into a single vector for eigenvalue computation + def flatten_h(h_list): + return torch.cat([h_list[l + 1].reshape(-1) for l in range(L)]) + + def unflatten_v(v_flat): + parts = [] + offset = 0 + for l in range(L): + size = h_settled[l + 1].numel() + parts.append(v_flat[offset:offset + size].reshape_as(h_settled[l + 1])) + offset += size + return parts + + dim = sum(h_settled[l + 1].numel() for l in range(L)) + + # Initialize random vector + q = torch.randn(dim, device=device) + q = q / q.norm() + + alphas = [] + betas = [0.0] + Q = [q] + + for j in range(min(n_lanczos_steps, dim)): + v_dir = unflatten_v(q) + hvp = hessian_vector_product(model, list(h_settled), h_init, x_0, mask, t, v_dir) + w = torch.cat([hv.reshape(-1) for hv in hvp]) + + alpha = w.dot(q).item() + alphas.append(alpha) + + if j > 0: + w = w - betas[-1] * Q[-2] + w = w - alpha * q + + beta = w.norm().item() + if beta < 1e-10: + break + betas.append(beta) + + q = w / beta + Q.append(q) + + # Build tridiagonal matrix and compute eigenvalues + n = len(alphas) + T_mat = torch.zeros(n, n, device=device) + for i in range(n): + T_mat[i, i] = alphas[i] + for i in range(n - 1): + T_mat[i, i + 1] = betas[i + 2] if i + 2 < len(betas) else 0 + T_mat[i + 1, i] = betas[i + 2] if i + 2 < len(betas) else 0 + + eigenvalues = torch.linalg.eigvalsh(T_mat).cpu().numpy() + + lambda_min = float(max(eigenvalues.min(), 1e-8)) + lambda_max = float(eigenvalues.max()) + kappa = lambda_max / lambda_min if lambda_min > 0 else float("inf") + + print(f" Hessian spectrum: lambda_min={lambda_min:.4f}, lambda_max={lambda_max:.4f}, kappa={kappa:.2f}") + + return { + "eigenvalues": eigenvalues.tolist(), + "lambda_min": lambda_min, + "lambda_max": lambda_max, + "effective_kappa": kappa, + } + + +# ============================================================================= +# 3. Energy Monotonicity Statistics +# ============================================================================= + +def measure_energy_monotonicity( + model: PCSHODLM, + x_0: torch.Tensor, + K: int = 32, + device: str = "cpu", +) -> dict: + """Track energy at each microstep and report monotonicity violations. + + Tests whether discrete-time settling maintains the Lyapunov guarantee. + """ + model = model.to(device).eval() + x_0 = x_0.to(device) + B, S = x_0.shape + + t = torch.full((B,), model.config.n_diffusion_steps // 2, device=device, dtype=torch.long) + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + model.config.n_settling_steps = K + model.config.settling_threshold = float("inf") + + h = [hi.detach() for hi in h_init] + v = [torch.zeros_like(h_init[l + 1]) for l in range(model.config.n_layers)] + + energies = [] + kinetic_energies = [] + + for k in range(K): + h, v, energy = model.settling_step(h, v, h_init, x_0, mask, t, None) + energies.append(energy) + + # Kinetic energy: 0.5 * sum ||v_l||^2 + ke = 0.5 * sum(vl.detach().norm().item() ** 2 for vl in v) + kinetic_energies.append(ke) + + # Compute total energy (potential + kinetic) + total_energies = [e + k for e, k in zip(energies, kinetic_energies)] + + # Count monotonicity violations + violations = 0 + for i in range(1, len(total_energies)): + if total_energies[i] > total_energies[i - 1] + 1e-6: + violations += 1 + + print(f" Energy monotonicity: {violations}/{K-1} violations") + print(f" Energy range: {energies[0]:.2f} -> {energies[-1]:.2f}") + + return { + "potential_energies": energies, + "kinetic_energies": kinetic_energies, + "total_energies": total_energies, + "n_violations": violations, + "violation_rate": violations / max(1, K - 1), + } + + +# ============================================================================= +# 4. Precision Calibration +# ============================================================================= + +def measure_precision_calibration( + model: PCSHODLM, + x_0: torch.Tensor, + n_samples: int = 10, + device: str = "cpu", +) -> dict: + """Compare predicted precision to empirical squared prediction errors. + + If precision heads are well-calibrated, predicted precision should + correlate inversely with actual error magnitude. + """ + model = model.to(device).eval() + x_0 = x_0.to(device) + B, S = x_0.shape + + predicted_precs = [] + empirical_sq_errors = [] + + for _ in range(n_samples): + t = torch.randint(1, model.config.n_diffusion_steps + 1, (B,), device=device) + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + model.config.n_settling_steps = 8 + h_settled, _, _, _, _ = model.settle(h_init, x_0, mask, t) + + # Get predictions and precisions at each layer + for l in range(model.config.n_layers): + with torch.no_grad(): + mu_up = model.forward_blocks[l](h_settled[l]) + tok_p, ch_p = model.precision_up[l](h_settled[l + 1], t) + + # Empirical squared error + eps = (h_settled[l + 1] - mu_up) + sq_err = (eps ** 2).mean(dim=-1) # (B, S) + + # Predicted precision (token-level) + pred_p = tok_p.squeeze(-1) # (B, S) + + predicted_precs.append(pred_p.cpu()) + empirical_sq_errors.append(sq_err.cpu()) + + # Compute correlation + all_prec = torch.cat([p.flatten() for p in predicted_precs]) + all_err = torch.cat([e.flatten() for e in empirical_sq_errors]) + + # Pearson correlation between precision and 1/error + inv_err = 1.0 / (all_err + 1e-8) + correlation = torch.corrcoef(torch.stack([all_prec, inv_err]))[0, 1].item() + + # Spearman rank correlation (approximate via sorting) + n = min(len(all_prec), 10000) + idx = torch.randperm(len(all_prec))[:n] + prec_ranks = all_prec[idx].argsort().argsort().float() + err_ranks = all_err[idx].argsort().argsort().float() + # Higher precision should correlate with lower error (higher error rank) + rank_corr = torch.corrcoef(torch.stack([prec_ranks, err_ranks]))[0, 1].item() + + print(f" Precision calibration:") + print(f" Pearson(precision, 1/error): {correlation:.4f}") + print(f" Rank correlation(precision, error_rank): {rank_corr:.4f}") + + return { + "pearson_prec_inv_error": correlation, + "rank_correlation": rank_corr, + "mean_precision": all_prec.mean().item(), + "mean_sq_error": all_err.mean().item(), + } + + +# ============================================================================= +# 5. Contraction Estimation +# ============================================================================= + +def estimate_contraction_factor( + model: PCSHODLM, + x_0: torch.Tensor, + perturbation_scale: float = 0.01, + K: int = 8, + device: str = "cpu", +) -> dict: + """Estimate solver contraction factor by perturbation experiments. + + Perturb h^k slightly and measure how fast the perturbation decays. + """ + model = model.to(device).eval() + x_0 = x_0.to(device) + B, S = x_0.shape + L = model.config.n_layers + + t = torch.full((B,), model.config.n_diffusion_steps // 2, device=device, dtype=torch.long) + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + model.config.n_settling_steps = K + model.config.settling_threshold = float("inf") + + # Run unperturbed + h_clean = [hi.detach() for hi in h_init] + v_clean = [torch.zeros_like(h_init[l + 1]) for l in range(L)] + + # Run perturbed + h_pert = [hi.detach().clone() for hi in h_init] + for l in range(1, L + 1): + h_pert[l] = h_pert[l] + perturbation_scale * torch.randn_like(h_pert[l]) + v_pert = [torch.zeros_like(h_init[l + 1]) for l in range(L)] + + distances = [] + initial_dist = sum( + (h_pert[l + 1] - h_clean[l + 1]).norm().item() for l in range(L) + ) + distances.append(initial_dist) + + for k in range(K): + h_clean, v_clean, _ = model.settling_step( + h_clean, v_clean, h_init, x_0, mask, t, None + ) + h_pert, v_pert, _ = model.settling_step( + h_pert, v_pert, h_init, x_0, mask, t, None + ) + + dist = sum( + (h_pert[l + 1] - h_clean[l + 1]).detach().norm().item() for l in range(L) + ) + distances.append(dist) + + # Estimate contraction per step + contraction_factors = [] + for i in range(1, len(distances)): + if distances[i - 1] > 1e-10: + contraction_factors.append(distances[i] / distances[i - 1]) + + avg_contraction = sum(contraction_factors) / len(contraction_factors) if contraction_factors else 1.0 + + print(f" Contraction estimation:") + print(f" Initial perturbation distance: {initial_dist:.6f}") + print(f" Final distance: {distances[-1]:.6f}") + print(f" Average contraction factor: {avg_contraction:.4f}") + print(f" Contractive: {avg_contraction < 1.0}") + + return { + "distances": distances, + "contraction_factors": contraction_factors, + "avg_contraction": avg_contraction, + "is_contractive": avg_contraction < 1.0, + } + + +# ============================================================================= +# 6. Token Freeze Accuracy +# ============================================================================= + +def measure_freeze_accuracy( + model: PCSHODLM, + x_0: torch.Tensor, + device: str = "cpu", +) -> dict: + """Measure fraction of soft-frozen tokens that later change. + + Runs settling with and without soft-freezing, compares final tokens. + Tests whether early confident predictions are reliable. + """ + model = model.to(device).eval() + x_0 = x_0.to(device) + B, S = x_0.shape + + t = torch.full((B,), model.config.n_diffusion_steps // 2, device=device, dtype=torch.long) + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + # Run without adaptive settling (full compute) + model.config.settling_threshold = float("inf") + h_full, _, _, _, _ = model.settle(h_init, x_0, mask, t) + logits_full = model.readout(model.readout_norm(h_full[-1])) + tokens_full = logits_full.argmax(dim=-1) + + # Run with adaptive settling (soft-freeze) + model.config.settling_threshold = 0.5 + h_adaptive, _, _, _, _ = model.settle(h_init, x_0, mask, t) + logits_adaptive = model.readout(model.readout_norm(h_adaptive[-1])) + tokens_adaptive = logits_adaptive.argmax(dim=-1) + + # Check: at masked positions, how often do frozen-early tokens match full-compute tokens + masked_match = (tokens_full[mask] == tokens_adaptive[mask]).float() + match_rate = masked_match.mean().item() if masked_match.numel() > 0 else 1.0 + + # Compute mid-settling predictions to identify "early frozen" tokens + model.config.n_settling_steps = model.config.n_settling_steps // 2 + model.config.settling_threshold = float("inf") + h_mid, _, _, _, _ = model.settle(h_init, x_0, mask, t) + logits_mid = model.readout(model.readout_norm(h_mid[-1])) + tokens_mid = logits_mid.argmax(dim=-1) + + # "Early confident" = tokens that don't change from mid to full + early_stable = (tokens_mid[mask] == tokens_full[mask]).float() + early_stable_rate = early_stable.mean().item() if early_stable.numel() > 0 else 1.0 + + print(f" Token freeze accuracy:") + print(f" Adaptive vs full match rate: {match_rate:.4f}") + print(f" Early-stable token rate: {early_stable_rate:.4f}") + + return { + "adaptive_vs_full_match": match_rate, + "early_stable_rate": early_stable_rate, + } + + +# ============================================================================= +# Run All Diagnostics +# ============================================================================= + +def run_all_diagnostics( + output_dir: str = "diagnostics_output", + device: str = "cpu", +): + """Run complete assumption diagnostic suite.""" + output_path = Path(output_dir) + output_path.mkdir(parents=True, exist_ok=True) + + config = PCSHOConfig( + vocab_size=257, + max_seq_len=128, + d_model=256, + n_heads=4, + n_layers=4, + d_ff=512, + n_diffusion_steps=100, + n_settling_steps=8, + mask_token_id=0, + ) + model = PCSHODLM(config) + x_0 = torch.randint(1, 257, (4, 128)) + + all_results = {} + + print("=" * 60) + print("PC-SHO-DLM Assumption Diagnostics") + print("=" * 60) + + print("\n1. Stationarity Residual (Envelope Theorem)") + all_results["stationarity"] = measure_stationarity_residual( + model, x_0, [2, 4, 8, 16], device + ) + + print("\n2. Local Hessian Spectrum (HVP + Lanczos)") + all_results["hessian"] = estimate_hessian_spectrum_lanczos( + model, x_0, n_lanczos_steps=10, device=device + ) + + print("\n3. Energy Monotonicity") + all_results["monotonicity"] = measure_energy_monotonicity( + model, x_0, K=16, device=device + ) + + print("\n4. Precision Calibration") + all_results["precision"] = measure_precision_calibration( + model, x_0, n_samples=5, device=device + ) + + print("\n5. Contraction Estimation") + all_results["contraction"] = estimate_contraction_factor( + model, x_0, device=device + ) + + print("\n6. Token Freeze Accuracy") + all_results["freeze_accuracy"] = measure_freeze_accuracy( + model, x_0, device=device + ) + + # Save + # Convert numpy arrays to lists for JSON + def convert(obj): + import numpy as np + if isinstance(obj, np.ndarray): + return obj.tolist() + if isinstance(obj, dict): + return {k: convert(v) for k, v in obj.items()} + if isinstance(obj, list): + return [convert(i) for i in obj] + return obj + + with open(output_path / "diagnostics.json", "w") as f: + json.dump(convert(all_results), f, indent=2) + + print(f"\nResults saved to {output_path}/diagnostics.json") + return all_results + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=str, default="diagnostics_output") + parser.add_argument("--device", type=str, default="cpu") + args = parser.parse_args() + + run_all_diagnostics(args.output, args.device) diff --git a/experiments/online_learning_eval.py b/experiments/online_learning_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd32180fa3da998393229116354628e2bed4a0c --- /dev/null +++ b/experiments/online_learning_eval.py @@ -0,0 +1,331 @@ +""" +PC-SHO-DLM Online Learning & Dynamic Architecture Evaluation + +Tests the unique PC capabilities: +1. Online learning during inference (domain adaptation at generation time) +2. Dynamic layer insertion with online learning convergence +3. Comparison: generation quality with/without online learning +""" + +import csv +import json +import os +import sys +import time +from pathlib import Path + +import torch +import torch.nn.functional as F + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) +from model import ( + PCSHODLM, PCSHOConfig, InferenceUpdater, DynamicLayerManager, count_parameters +) + + +def load_ao3_text(data_dir: str, max_rows: int = 5000) -> str: + """Extract text content from AO3 metadata CSV for domain adaptation testing.""" + csv_path = os.path.join(data_dir, "random works - Oct 2025.csv") + if not os.path.exists(csv_path): + # Try alternative + for f in os.listdir(data_dir): + if f.endswith(".csv") and "random works" in f: + csv_path = os.path.join(data_dir, f) + break + + texts = [] + with open(csv_path, "r", errors="replace") as f: + reader = csv.DictReader(f) + for i, row in enumerate(reader): + if i >= max_rows: + break + # Build a text representation from metadata + parts = [] + if row.get("Title"): + parts.append(f"Title: {row['Title']}") + if row.get("Fandom Tags"): + parts.append(f"Fandom: {row['Fandom Tags']}") + if row.get("Summary Paragraphs"): + summary = row["Summary Paragraphs"] + if summary and summary != "0": + parts.append(f"Summary: {summary}") + if row.get("Freeform Tags"): + parts.append(f"Tags: {row['Freeform Tags']}") + if parts: + texts.append(" | ".join(parts)) + + return "\n".join(texts) + + +def encode_text(text: str, seq_len: int, vocab_size: int = 257) -> torch.Tensor: + """Encode text to byte-level tensor (matching training encoding).""" + data = torch.tensor( + [min(b + 1, vocab_size - 1) for b in text.encode("utf-8")[:seq_len]], + dtype=torch.long, + ) + # Pad if needed + if len(data) < seq_len: + data = F.pad(data, (0, seq_len - len(data)), value=0) + return data.unsqueeze(0) # (1, seq_len) + + +# ============================================================================= +# Experiment 1: Online Learning Domain Adaptation +# ============================================================================= + +def test_online_learning_adaptation( + checkpoint_path: str, + ao3_data_dir: str, + device: str = "cpu", +) -> dict: + """Test online learning: train on WikiText, adapt to AO3 style at inference. + + Compares generation energy with and without online learning when + the model encounters out-of-domain text. + """ + print("=" * 60) + print("Experiment 1: Online Learning Domain Adaptation") + print("=" * 60) + + # Load trained model + ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False) + config = ckpt["config"] + model = PCSHODLM(config).to(device) + model.load_state_dict(ckpt["model_state_dict"]) + model.eval() + print(f"Loaded model from {checkpoint_path}") + + # Load AO3 text as "context" for adaptation + ao3_text = load_ao3_text(ao3_data_dir, max_rows=1000) + print(f"Loaded {len(ao3_text):,} chars of AO3 text") + + seq_len = config.max_seq_len + + # Measure baseline energy on AO3 text (no online learning) + print("\nBaseline (no online learning):") + x_ao3 = encode_text(ao3_text, seq_len, config.vocab_size).to(device) + t = torch.full((1,), config.n_diffusion_steps // 2, device=device, dtype=torch.long) + x_t, mask = model.schedule.corrupt(x_ao3, t, config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + with torch.no_grad(): + h_settled, _, energies_baseline, _, _ = model.settle(h_init, x_ao3, mask, t) + logits = model.readout(model.readout_norm(h_settled[-1])) + mask_logits = logits[mask] + mask_targets = x_ao3[mask] + if mask_logits.numel() > 0: + loss_baseline = F.cross_entropy(mask_logits, mask_targets).item() + else: + loss_baseline = 0.0 + + print(f" Loss: {loss_baseline:.4f}") + print(f" Energy: {energies_baseline[-1]:.0f}") + + # Now generate with online learning enabled + print("\nWith online learning (adapting during generation):") + # Save initial params + param_snapshot = {n: p.data.clone() for n, p in model.named_parameters()} + + gen_online = model.generate( + seq_len=seq_len, batch_size=1, device=device, online_learn=True + ) + + # Measure energy on AO3 text AFTER online adaptation + x_t2, mask2 = model.schedule.corrupt(x_ao3, t, config.mask_token_id) + h_02 = model.embed_input(x_t2, t) + h_init2 = model.amortized_forward_pass(h_02) + + with torch.no_grad(): + h_settled2, _, energies_adapted, _, _ = model.settle(h_init2, x_ao3, mask2, t) + logits2 = model.readout(model.readout_norm(h_settled2[-1])) + mask_logits2 = logits2[mask2] + mask_targets2 = x_ao3[mask2] + if mask_logits2.numel() > 0: + loss_adapted = F.cross_entropy(mask_logits2, mask_targets2).item() + else: + loss_adapted = 0.0 + + # Measure parameter drift + total_drift = 0.0 + n_params = 0 + for n, p in model.named_parameters(): + if n in param_snapshot: + total_drift += (p.data - param_snapshot[n]).norm().item() + n_params += p.numel() + + print(f" Loss after adaptation: {loss_adapted:.4f}") + print(f" Energy after adaptation: {energies_adapted[-1]:.0f}") + print(f" Parameter drift: {total_drift:.6f}") + print(f" Loss improvement: {loss_baseline - loss_adapted:.4f}") + + # Restore original params + for n, p in model.named_parameters(): + if n in param_snapshot: + p.data.copy_(param_snapshot[n]) + + results = { + "loss_baseline": loss_baseline, + "loss_adapted": loss_adapted, + "energy_baseline": energies_baseline[-1], + "energy_adapted": energies_adapted[-1], + "param_drift": total_drift, + "improvement": loss_baseline - loss_adapted, + } + + return results + + +# ============================================================================= +# Experiment 2: Dynamic Layer Insertion +# ============================================================================= + +def test_dynamic_layer_insertion( + checkpoint_path: str, + device: str = "cpu", +) -> dict: + """Test inserting layers at runtime and measuring convergence. + + Inserts 2 new layers into a trained model and measures: + - How many settling steps before energy improves + - Loss before and after insertion + settling + """ + print("\n" + "=" * 60) + print("Experiment 2: Dynamic Layer Insertion") + print("=" * 60) + + ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False) + config = ckpt["config"] + model = PCSHODLM(config).to(device) + model.load_state_dict(ckpt["model_state_dict"]) + model.eval() + + x_0 = torch.randint(1, config.vocab_size, (2, config.max_seq_len), device=device) + + # Baseline loss + with torch.no_grad(): + out_before = model(x_0) + loss_before = out_before["loss"].item() + energy_before = out_before["energies"][-1] + print(f"Before insertion: {model.n_active_layers} layers, loss={loss_before:.4f}, energy={energy_before:.0f}") + + # Insert 2 layers + mgr = DynamicLayerManager(model) + mgr.insert_layer(model.n_active_layers // 2, init_strategy="identity") + mgr.insert_layer(model.n_active_layers // 2 + 1, init_strategy="identity") + print(f"After insertion: {model.n_active_layers} layers, params={count_parameters(model):,}") + + # Immediate loss (should be similar due to identity init) + with torch.no_grad(): + out_after = model(x_0) + loss_after = out_after["loss"].item() + energy_after = out_after["energies"][-1] + print(f"Immediate post-insert: loss={loss_after:.4f}, energy={energy_after:.0f}") + + # Now run online learning to train the new layers + print("Running online learning to train new layers...") + updater = InferenceUpdater(model, lr=1e-4, grad_clip=0.5) + + online_losses = [] + for step in range(50): + t = torch.randint(1, config.n_diffusion_steps + 1, (2,), device=device) + x_t, mask = model.schedule.corrupt(x_0, t, config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + h_settled, _, energies, _, errors = model.settle( + h_init, x_0, mask, t, return_errors=True + ) + + if errors is not None: + eps_up, eps_down = errors + updater.update_from_errors(h_settled, eps_up, eps_down, x_0, mask, t) + + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_settled[-1])) + ml = logits[mask] + mt = x_0[mask] + if ml.numel() > 0: + online_losses.append(F.cross_entropy(ml, mt).item()) + + if (step + 1) % 10 == 0: + print(f" Online step {step+1}: loss={online_losses[-1]:.4f}") + + loss_final = online_losses[-1] if online_losses else loss_after + print(f"After 50 online steps: loss={loss_final:.4f}") + + results = { + "n_layers_before": config.n_layers - 2, + "n_layers_after": config.n_layers, + "loss_before": loss_before, + "loss_immediate_after": loss_after, + "loss_after_online": loss_final, + "online_loss_trace": online_losses, + } + + return results + + +# ============================================================================= +# Main +# ============================================================================= + +def run_all( + checkpoint_path: str = None, + ao3_data_dir: str = None, + output_dir: str = "online_learning_results", + device: str = "cpu", +): + output_path = Path(output_dir) + output_path.mkdir(parents=True, exist_ok=True) + + # Find checkpoint + if checkpoint_path is None: + for d in ["checkpoints/local_pc_1k", "checkpoints/local_pc"]: + p = os.path.join(d, "checkpoint_final.pt") + if os.path.exists(p): + checkpoint_path = p + break + if checkpoint_path is None: + print("No checkpoint found. Train a model first.") + return + + # Find AO3 data + if ao3_data_dir is None: + ao3_data_dir = os.path.join( + os.path.dirname(__file__), "..", "data", "ao3-metadata" + ) + + all_results = {} + + # Experiment 1: Online learning adaptation + if os.path.isdir(ao3_data_dir): + all_results["online_adaptation"] = test_online_learning_adaptation( + checkpoint_path, ao3_data_dir, device + ) + else: + print(f"AO3 data not found at {ao3_data_dir}, skipping experiment 1") + + # Experiment 2: Dynamic layer insertion + all_results["dynamic_insertion"] = test_dynamic_layer_insertion( + checkpoint_path, device + ) + + # Save + with open(output_path / "results.json", "w") as f: + json.dump(all_results, f, indent=2) + print(f"\nResults saved to {output_path}/results.json") + + return all_results + + +if __name__ == "__main__": + import argparse + parser = argparse.ArgumentParser() + parser.add_argument("--checkpoint", type=str, default=None) + parser.add_argument("--ao3_data", type=str, default=None) + parser.add_argument("--output", type=str, default="online_learning_results") + parser.add_argument("--device", type=str, default="cpu") + args = parser.parse_args() + + run_all(args.checkpoint, args.ao3_data, args.output, args.device) diff --git a/experiments/settling_analysis.py b/experiments/settling_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..c0dcf0cad4f76105dd81280ff67a3c4623f87fd7 --- /dev/null +++ b/experiments/settling_analysis.py @@ -0,0 +1,254 @@ +""" +PC-SHO-DLM Settling Dynamics Analysis + +Empirically measures: +1. Convergence rate: first-order vs second-order +2. Energy decrease per microstep +3. Effect of precision conditioning +4. Warm-start vs cold-start efficiency +5. Token-level settling patterns +""" + +import json +import math +import os +import sys +from pathlib import Path + +import torch +import torch.nn.functional as F + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) +from model import PCSHODLM, PCSHOConfig, count_parameters + + +def measure_settling_convergence( + model: PCSHODLM, + x_0: torch.Tensor, + max_k: int = 32, + device: str = "cpu", +) -> dict: + """Measure how energy decreases over settling steps. + + Returns energy traces for analysis. + """ + model = model.to(device).eval() + x_0 = x_0.to(device) + B, S = x_0.shape + + # Sample a fixed timestep (mid-range) + t = torch.full((B,), model.config.n_diffusion_steps // 2, device=device, dtype=torch.long) + + # Corrupt + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + + # Embed and initialize + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + # Temporarily override settling steps + original_k = model.config.n_settling_steps + model.config.n_settling_steps = max_k + model.config.settling_threshold = float("inf") # Disable adaptive for clean measurement + + # Run settling and record energy at each step + h = [hi.detach() for hi in h_init] + v = [torch.zeros_like(h_init[l + 1]) for l in range(model.config.n_layers)] + + energies = [] + grad_norms = [] + token_uncertainties = [] + + for k in range(max_k): + # Enable grads for energy computation + for l in range(1, model.config.n_layers + 1): + h[l] = h[l].detach().requires_grad_(True) + + grad_h, eps_up, eps_down, energy = model.compute_energy_gradient( + h, h_init, x_0, mask, t + ) + energies.append(energy) + + # Record gradient norm + total_grad_norm = sum(g.detach().norm().item() for g in grad_h) + grad_norms.append(total_grad_norm) + + # Record per-token uncertainty + uncertainty = model.compute_token_uncertainty(h).detach().cpu() + token_uncertainties.append(uncertainty.mean().item()) + + # Compute aggregate precision for controller + agg_precs = model.compute_aggregate_precision(h, t) + + # Update + h_new = [h[0]] + v_new = [] + for l in range(model.config.n_layers): + prec = agg_precs[l] + eta = model.config.eta_base / (1.0 + model.config.c_eta * prec) + gamma_raw = 2.0 * math.sqrt(model.config.mass * prec) + gamma = max(model.config.gamma_min, min(model.config.gamma_max, gamma_raw)) + + v_l_new = (1.0 - gamma) * v[l] - eta * grad_h[l].detach() + h_l_new = h[l + 1].detach() + v_l_new + + v_new.append(v_l_new) + h_new.append(h_l_new) + + h = h_new + v = v_new + + # Restore + model.config.n_settling_steps = original_k + + return { + "energies": energies, + "grad_norms": grad_norms, + "token_uncertainties": token_uncertainties, + } + + +def compare_first_vs_second_order( + config_base: PCSHOConfig, + x_0: torch.Tensor, + max_k: int = 32, + device: str = "cpu", +) -> dict: + """Compare convergence of first-order vs second-order settling.""" + + results = {} + + # Second-order (full model) + model_sho = PCSHODLM(config_base).to(device).eval() + results["second_order"] = measure_settling_convergence( + model_sho, x_0, max_k, device + ) + + # First-order (gamma = 1 forces no momentum) + config_fo = PCSHOConfig(**{ + k: v for k, v in config_base.__dict__.items() + }) + config_fo.gamma_min = 1.0 + config_fo.gamma_max = 1.0 + model_fo = PCSHODLM(config_fo).to(device).eval() + # Copy weights for fair comparison + model_fo.load_state_dict(model_sho.state_dict(), strict=False) + results["first_order"] = measure_settling_convergence( + model_fo, x_0, max_k, device + ) + + return results + + +def measure_warm_start_advantage( + model: PCSHODLM, + x_0: torch.Tensor, + n_settling: int = 8, + device: str = "cpu", +) -> dict: + """Compare warm-start vs cold-start across diffusion steps.""" + model = model.to(device).eval() + x_0 = x_0.to(device) + B, S = x_0.shape + + warm_energies_per_step = [] + cold_energies_per_step = [] + + # Run a few diffusion steps + test_timesteps = [ + model.config.n_diffusion_steps, + model.config.n_diffusion_steps * 3 // 4, + model.config.n_diffusion_steps // 2, + model.config.n_diffusion_steps // 4, + ] + + prev_h = None + prev_v = None + + for t_val in test_timesteps: + t = torch.full((B,), t_val, device=device, dtype=torch.long) + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + # Warm start + model.config.n_settling_steps = n_settling + h_warm, v_warm, energies_warm, _, _ = model.settle( + h_init, x_0, mask, t, prev_h=prev_h, prev_v=prev_v + ) + warm_energies_per_step.append(energies_warm) + + # Cold start + h_cold, v_cold, energies_cold, _, _ = model.settle( + h_init, x_0, mask, t, prev_h=None, prev_v=None + ) + cold_energies_per_step.append(energies_cold) + + # Update for next warm start + prev_h = h_warm + prev_v = v_warm + + return { + "timesteps": test_timesteps, + "warm_energies": warm_energies_per_step, + "cold_energies": cold_energies_per_step, + } + + +def run_full_analysis( + output_dir: str = "settling_analysis", + device: str = "cpu", +): + """Run complete settling dynamics analysis.""" + output_path = Path(output_dir) + output_path.mkdir(parents=True, exist_ok=True) + + config = PCSHOConfig( + vocab_size=257, + max_seq_len=128, + d_model=256, + n_heads=4, + n_layers=4, + d_ff=512, + n_diffusion_steps=100, + n_settling_steps=8, + mask_token_id=0, + ) + + # Synthetic data + x_0 = torch.randint(1, 257, (4, 128)) + + # 1. First-order vs second-order comparison + print("1. Comparing first-order vs second-order settling...") + fo_vs_sho = compare_first_vs_second_order(config, x_0, max_k=32, device=device) + with open(output_path / "fo_vs_sho.json", "w") as f: + json.dump(fo_vs_sho, f, indent=2) + + print(f" FO final energy: {fo_vs_sho['first_order']['energies'][-1]:.2f}") + print(f" SHO final energy: {fo_vs_sho['second_order']['energies'][-1]:.2f}") + + # 2. Warm-start analysis + print("2. Measuring warm-start advantage...") + model = PCSHODLM(config) + warm_analysis = measure_warm_start_advantage(model, x_0, device=device) + with open(output_path / "warm_start.json", "w") as f: + json.dump(warm_analysis, f, indent=2) + + for i, ts in enumerate(warm_analysis["timesteps"]): + warm_final = warm_analysis["warm_energies"][i][-1] + cold_final = warm_analysis["cold_energies"][i][-1] + print(f" t={ts}: warm={warm_final:.2f}, cold={cold_final:.2f}") + + print(f"\nResults saved to {output_path}") + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=str, default="settling_analysis") + parser.add_argument("--device", type=str, default="cpu") + args = parser.parse_args() + + run_full_analysis(args.output, args.device) diff --git a/online_learning_results/results.json b/online_learning_results/results.json new file mode 100644 index 0000000000000000000000000000000000000000..5df8d6875863021501556dcf175803987000ee5f --- /dev/null +++ b/online_learning_results/results.json @@ -0,0 +1,69 @@ +{ + "online_adaptation": { + "loss_baseline": 3.6925668716430664, + "loss_adapted": 3.981217384338379, + "energy_baseline": 8231.3037109375, + "energy_adapted": 8242.259765625, + "param_drift": 0.00023738775400516943, + "improvement": -0.2886505126953125 + }, + "dynamic_insertion": { + "n_layers_before": 6, + "n_layers_after": 8, + "loss_before": 9.189724922180176, + "loss_immediate_after": 9.178750991821289, + "loss_after_online": 8.833724021911621, + "online_loss_trace": [ + 9.20292854309082, + 8.580750465393066, + 8.936054229736328, + 9.290948867797852, + 9.261687278747559, + 8.98759651184082, + 8.377225875854492, + 9.151756286621094, + 8.983861923217773, + 9.052128791809082, + 8.897459983825684, + 8.844188690185547, + 8.36867618560791, + 9.233955383300781, + 9.022278785705566, + 9.028934478759766, + 8.7919282913208, + 8.897858619689941, + 8.838046073913574, + 8.968409538269043, + 9.265947341918945, + 8.649272918701172, + 8.996474266052246, + 9.072571754455566, + 8.778992652893066, + 8.961980819702148, + 8.777365684509277, + 8.824459075927734, + 8.86223030090332, + 9.157471656799316, + 8.599833488464355, + 8.92215347290039, + 8.921445846557617, + 8.669816017150879, + 8.905592918395996, + 9.206143379211426, + 8.956107139587402, + 9.287323951721191, + 8.977736473083496, + 9.11660385131836, + 9.217642784118652, + 8.774115562438965, + 8.891241073608398, + 8.741592407226562, + 9.040119171142578, + 8.988186836242676, + 8.725876808166504, + 9.364388465881348, + 8.64766788482666, + 8.833724021911621 + ] + } +} \ No newline at end of file diff --git a/paper/main.tex b/paper/main.tex new file mode 100644 index 0000000000000000000000000000000000000000..e84de518952054bb749d8f0d8061551dd1c4ff87 --- /dev/null +++ b/paper/main.tex @@ -0,0 +1,1143 @@ +\documentclass{article} + +% Required packages +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{amsmath,amssymb,amsthm} +\usepackage{mathtools} +\usepackage{algorithm} +\usepackage{algorithmic} +\usepackage{booktabs} +\usepackage{hyperref} +\usepackage{cleveref} +\usepackage{graphicx} +\usepackage{xcolor} +\usepackage{thmtools} +\usepackage[margin=1in]{geometry} +\usepackage{natbib} +\usepackage{subcaption} + +% Theorem environments +\newtheorem{theorem}{Theorem}[section] +\newtheorem{lemma}[theorem]{Lemma} +\newtheorem{proposition}[theorem]{Proposition} +\newtheorem{corollary}[theorem]{Corollary} +\newtheorem{definition}[theorem]{Definition} +\newtheorem{assumption}{Assumption} +\newtheorem{remark}{Remark} +\newtheorem{hypothesis}{Hypothesis} + +% Custom commands +\newcommand{\R}{\mathbb{R}} +\newcommand{\E}{\mathbb{E}} +\newcommand{\Var}{\mathrm{Var}} +\newcommand{\Cov}{\mathrm{Cov}} +\newcommand{\tr}{\mathrm{tr}} +\newcommand{\diag}{\mathrm{diag}} +\newcommand{\softplus}{\mathrm{softplus}} +\newcommand{\clip}{\mathrm{clip}} +\newcommand{\sg}{\mathrm{sg}} +\newcommand{\MASK}{\texttt{[MASK]}} +\DeclareMathOperator*{\argmin}{arg\,min} +\DeclareMathOperator*{\argmax}{arg\,max} +\newcommand{\norm}[1]{\left\| #1 \right\|} +\newcommand{\inner}[2]{\langle #1, #2 \rangle} +\newcommand{\pder}[2]{\frac{\partial #1}{\partial #2}} + +\title{% + \textbf{PC-SHO-DLM: Predictive-Coding Diffusion Language Models\\ + with Precision-Conditioned Second-Order Settling} +} + +\author{ + Research Proposal --- Architecture Specification and Theoretical Foundations +} + +\date{March 2026} + +\begin{document} + +\maketitle + +% ============================================================================ +% ABSTRACT +% ============================================================================ +\begin{abstract} +Diffusion language models replace left-to-right token generation with iterative denoising, enabling parallel refinement and potentially favorable inference throughput. +Predictive coding offers a local alternative to end-to-end backpropagation, but its use in deep networks has been limited by unstable and expensive latent inference. +We propose \textbf{PC-SHO-DLM}, a class of masked diffusion language models in which each denoising step is implemented by a predictive-coding transformer trained without global reverse-mode differentiation. +The key observation is that diffusion denoising and predictive coding are both iterative residual-correction procedures, making diffusion a particularly natural setting for predictive-coding-based language modeling. +To address the principal practical weakness of predictive coding, we replace first-order latent relaxation with \textbf{precision-conditioned second-order dynamics}: hidden states evolve under damped inertial updates whose damping and step size depend on learned uncertainty estimates. +We further introduce \textbf{state continuation across diffusion steps} and \textbf{tokenwise adaptive settling}, which make additional inference-time compute directly interpretable as selective latent refinement rather than longer token chains. + +We prove four theoretical results: +(A)~local post-settling parameter updates are exact gradients of a reduced energy objective via the envelope theorem, eliminating the need to backpropagate through the settling trajectory; +(B)~second-order settling achieves $O(\sqrt{\kappa}\log(1/\varepsilon))$ convergence versus $O(\kappa\log(1/\varepsilon))$ for first-order predictive coding under local strong convexity; +(C)~warm-start tracking across diffusion steps reduces per-step settling cost from full re-solve distance to inter-step drift; +(D)~precision-weighted local updates are statistically efficient under heteroscedastic prediction errors. + +The key prediction is that second-order predictive-coding denoisers will require fewer settling microsteps than first-order baselines at matched denoising quality, while preserving the locality and asynchronous-update advantages of predictive coding. +\end{abstract} + +\tableofcontents +\newpage + +% ============================================================================ +% 1. INTRODUCTION +% ============================================================================ +\section{Introduction} +\label{sec:introduction} + +Recent progress in text diffusion has materially changed the credibility of non-autoregressive language generation. +Early text diffusion methods suffered from a mismatch between continuous diffusion machinery and discrete token spaces, but discrete-state and masked-token formulations substantially narrowed that gap~\citep{austin2021structured, sahoo2024simple}. +In parallel, predictive coding has matured from a neuroscientific theory into a machine-learning framework with explicit links to gradient descent and local credit assignment~\citep{rao1999predictive, whittington2017approximation, millidge2022predictive}. + +These two lines of work share a surprisingly strong structural overlap: +\begin{itemize} + \item A diffusion LM performs \emph{iterative denoising} of corrupted tokens. + \item A predictive-coding network performs \emph{iterative error correction} over latent states. +\end{itemize} + +This overlap suggests a possibility that has not yet been fully explored: \emph{use predictive coding not as an afterthought inside a standard language model, but as the inner denoising mechanism of a diffusion language model}. + +The central obstacle is practical. +Predictive coding in deep networks often requires multiple latent-settling iterations, and naive first-order relaxation can become slow or unstable~\citep{bogacz2017tutorial}. +We therefore propose a second ingredient: \textbf{damped second-order hidden-state dynamics}, motivated by the continuous-time system +\begin{equation} +\label{eq:sho-continuous} +m_l \ddot{h}_l + \gamma_l \dot{h}_l + \nabla_{h_l} E_t(h) = 0. +\end{equation} +This turns predictive-coding inference into an inertial energy-minimization process. +Diffusion denoising traverses regimes of very different uncertainty and effective curvature, so a single first-order relaxation rate is unlikely to be optimal throughout. + +Our thesis is: + +\begin{quote} +\emph{Diffusion provides the outer iterative denoising process, predictive coding provides the local error-correction mechanism, and second-order latent dynamics make the inner inference loop practical.} +\end{quote} + +\paragraph{Contributions.} +\begin{enumerate} + \item We identify masked diffusion language modeling as a structurally natural host for predictive coding (\Cref{sec:method}). + \item We introduce a bidirectional predictive transformer with precision-conditioned second-order latent settling (\Cref{sec:settling}). + \item We propose state continuation across diffusion steps and tokenwise adaptive settling (\Cref{sec:practical}). + \item We prove four theoretical results establishing convergence-rate, gradient-exactness, tracking, and statistical-efficiency advantages (\Cref{sec:theory}). + \item We specify a falsifiable experimental program with concrete ablations and failure criteria (\Cref{sec:experiments}). +\end{enumerate} + + +% ============================================================================ +% 2. RELATED WORK +% ============================================================================ +\section{Related Work} +\label{sec:related} + +\subsection{Text Diffusion} +\label{sec:related-diffusion} + +Discrete and masked diffusion for text became substantially more credible between 2021 and 2024. +\citet{austin2021structured} introduced structured denoising diffusion in discrete state spaces (D3PM). +\citet{li2022diffusion} demonstrated controllable text generation via continuous embedding diffusion. +\citet{gong2022diffuseq} applied sequence-to-sequence diffusion with partial noising. +More recent work on masked diffusion language models~\citep{sahoo2024simple} and block diffusion~\citep{arriola2025block} has shown that absorbing-mask corruption is especially natural for text, enabling iterative parallel refinement as a real alternative to left-to-right decoding. + +The key lesson for our work is not merely that diffusion can generate text, but that text diffusion already accepts an iterative refinement paradigm---making it a more natural host for predictive coding than autoregressive decoding. + +\subsection{Predictive Coding and Local Credit Assignment} +\label{sec:related-pc} + +Predictive coding originated as a theory of cortical computation~\citep{rao1999predictive} and was formalized within the free-energy framework~\citep{friston2005theory}. +\citet{bogacz2017tutorial} provided an accessible treatment connecting predictive coding to variational inference. +\citet{whittington2017approximation} established that predictive coding can approximate backpropagation under fixed-point convergence. +\citet{millidge2022predictive} extended these results to arbitrary computation graphs. + +Related alternatives to global backpropagation include feedback alignment~\citep{lillicrap2016random}, equilibrium propagation~\citep{scellier2017equilibrium}, the forward-forward algorithm~\citep{hinton2022forward}, and recent forward-projection methods. + +The recurring bottleneck across all these methods is scaling: most still underperform standard backpropagation in deep networks, primarily due to settling cost and stability. + +\subsection{Second-Order and Inertial Optimization} +\label{sec:related-dynamics} + +Heavy-ball momentum~\citep{polyak1964some} and its continuous-time ODE interpretation~\citep{su2016differential} establish that inertial dynamics can accelerate convergence from $O(\kappa)$ to $O(\sqrt{\kappa})$ iterations on strongly convex quadratics. +This acceleration is well understood in optimization but has not been applied to predictive-coding latent inference inside language diffusion models. + +\textbf{Important limitation.} +Heavy-ball does \emph{not} attain a uniform accelerated worst-case rate over the entire class of smooth strongly convex functions; outside structured settings (quadratics, local regimes), it can fail to accelerate and may even diverge or cycle for some functions and parameter choices. +This sharply constrains what can be claimed rigorously for transformer energies and motivates the ``local-mode theorem'' framing we adopt in \Cref{sec:theory}. + +\subsection{Diffusion Inference Acceleration and Cross-Step Reuse} +\label{sec:related-acceleration} + +A rapidly growing body of work exploits the empirical observation that token representations and attention KV states exhibit temporal consistency across adjacent denoising steps. +Methods such as dKV-Cache and related approaches (dLLM-Cache, Fast-dLLM) report large inference speedups by selectively caching and reusing states across diffusion steps. +Our state continuation mechanism (\Cref{sec:continuation}) is the latent-inference analogue of this empirical phenomenon: it asserts that the latent optimum path is smooth enough across timesteps to enable tracking with few microsteps. + +\subsection{Precision Weighting in Diffusion and Predictive Coding} +\label{sec:related-precision} + +CogDPM explicitly highlights precision weighting as an important and underexploited mechanism in diffusion-like systems, proposing ways to estimate and use precision within diffusion setups for forecasting and guidance weighting. +Our proposal's distinctive move is to use learned precision not merely to weight errors, but as a \emph{solver controller}: precision conditions damping, step size, and tokenwise compute allocation. + +\subsection{Critique: Time-Agnostic Masked Diffusion} +\label{sec:related-critique} + +Recent theoretical work argues that masked diffusion models can be reformulated in a time-agnostic manner equivalent to masked models, and that common categorical sampling implementations can introduce numerical artifacts that effectively reduce temperature and skew diversity. +This critique implies that any claimed advantage of ``predictive coding inside diffusion'' must be carefully disentangled from: +(a)~what could be achieved by iterative masked modeling alone, and +(b)~sampling artifacts that inflate perplexity-like metrics. +We address this by recommending diversity and calibration diagnostics alongside quality metrics (\Cref{sec:experiments}) and by framing our contribution as an inference-algorithm advance rather than a claim that diffusion time is fundamental. + +\subsection{Why the Synthesis is Nontrivial} +\label{sec:related-gap} + +Existing work provides individual pieces: +\begin{enumerate} + \item Diffusion for text (iterative denoising, parallel refinement), + \item Predictive coding for local learning (error-driven inference, local updates), + \item Inertial optimization (accelerated convergence in stiff landscapes). +\end{enumerate} + +What remains missing is a language-scale denoiser in which: +\begin{enumerate} + \item the \emph{outer objective} is diffusion denoising, + \item the \emph{inner latent computation} is predictive coding, + \item the \emph{latent solver} is second-order and uncertainty-aware, + \item the \emph{parameter learning rule} is local rather than global reverse-mode. +\end{enumerate} +That is the gap PC-SHO-DLM targets. + + +% ============================================================================ +% 3. METHOD +% ============================================================================ +\section{Method} +\label{sec:method} + +\subsection{Outer Process: Masked Discrete Diffusion} +\label{sec:outer} + +We adopt an absorbing-mask corruption process over token sequences $x_0 = (x_0^{(1)}, \ldots, x_0^{(n)})$. +For diffusion timestep $t \in \{1, \ldots, T\}$: +\begin{equation} +\label{eq:forward-mask} +q_t\!\left(x_t^{(i)} = \MASK \mid x_0^{(i)}\right) = \bar{\alpha}_t, +\qquad +q_t\!\left(x_t^{(i)} = x_0^{(i)} \mid x_0^{(i)}\right) = 1 - \bar{\alpha}_t, +\end{equation} +where $\bar{\alpha}_t$ is a monotonically increasing masking schedule with $\bar{\alpha}_0 = 0$ and $\bar{\alpha}_T \approx 1$. + +Let $M_t \subseteq \{1, \ldots, n\}$ denote the set of masked positions at timestep $t$. +The denoising target is the clean token identity at masked positions: +\begin{equation} +\label{eq:mask-loss} +\mathcal{L}_{\mathrm{mask}} = -\sum_{i \in M_t} \log p_\Theta\!\left(x_0^{(i)} \mid x_t, t\right). +\end{equation} + +This choice is deliberate: masked discrete diffusion aligns naturally with language and with predictive-coding-style uncertainty weighting, since the set of unknown positions is explicit and the model can direct computational effort toward them. + + +\subsection{Inner Model: Bidirectional Predictive Transformer} +\label{sec:inner} + +A purely feedforward residual stack with local losses is not predictive coding in the strong sense. +The more principled design is a \textbf{bidirectional predictive transformer} with both bottom-up and top-down pathways. + +Let $h_0 \in \R^{n \times d}$ be the token embedding sequence of $x_t$ augmented with position and timestep embeddings. +For layers $l = 1, \ldots, L$, define: +\begin{align} +\label{eq:bottom-up} +\text{Bottom-up proposal:} \quad & \mu_l^\uparrow = f_l(h_{l-1}; \theta_l), \\ +\label{eq:top-down} +\text{Top-down prediction:} \quad & \mu_l^\downarrow = g_l(h_{l+1}; \phi_l), \quad l < L, +\end{align} +where each $f_l$ is a standard bidirectional transformer block and each $g_l$ is a lightweight feedback predictor (ideally parameter-shared or low-rank-related to $f_l$). + +\begin{definition}[Prediction errors] +\label{def:errors} +\begin{equation} +\epsilon_l^\uparrow = h_l - \mu_l^\uparrow, \qquad +\epsilon_l^\downarrow = h_l - \mu_l^\downarrow. +\end{equation} +\end{definition} + +The \textbf{per-step latent energy} for diffusion timestep $t$ is: +\begin{equation} +\label{eq:energy} +\boxed{ +E_t(h) = +\underbrace{\sum_{l=1}^{L} \frac{1}{2} \norm{\epsilon_l^\uparrow}_{\Gamma_l}^2}_{\text{bottom-up consistency}} ++ \underbrace{\sum_{l=0}^{L-1} \frac{1}{2} \norm{\epsilon_l^\downarrow}_{\Lambda_l}^2}_{\text{top-down consistency}} ++ \underbrace{\lambda_t \mathcal{L}_{\mathrm{mask}}(W_o h_L, x_0; M_t)}_{\text{denoising objective}} ++ \underbrace{\rho \sum_{l=1}^L \norm{h_l - h_l^{\mathrm{init}}}_2^2}_{\text{anchoring}} +} +\end{equation} +where: +\begin{itemize} + \item $\Gamma_l, \Lambda_l \succ 0$ are positive diagonal or low-rank precision operators, + \item $h_l^{\mathrm{init}}$ is the one-pass feedforward initialization, + \item $\rho > 0$ is a small anchoring coefficient preventing runaway latent drift, + \item $\lambda_t$ controls the relative weight of the denoising loss. +\end{itemize} + +This formulation gives neighboring layers explicit local predictive relations, making it more faithful to predictive coding than a purely bottom-up error stack. + + +\subsection{Precision Heads} +\label{sec:precision} + +A critical addition is learned, timestep-dependent precision weighting. +For each layer $l$, a precision head predicts tokenwise or token-channelwise precision: +\begin{equation} +\label{eq:precision-head} +\Lambda_l = \diag\!\big(\softplus(P_l(h_l, t)) + \varepsilon\big), +\end{equation} +and similarly for $\Gamma_l$. + +A practical factorization decomposes precision into token and channel components: +\begin{equation} +\label{eq:precision-factored} +\Lambda_l \approx \diag(\lambda_l^{\mathrm{tok}}) \otimes \diag(\lambda_l^{\mathrm{ch}}), +\end{equation} +which is much cheaper than a full covariance while permitting nonuniform uncertainty over positions and features. + +\begin{remark} +This matters more in language than is often appreciated. +Rare entities, punctuation, delimiters, code symbols, and function words have very different denoising statistics. +Treating all prediction errors equally is likely suboptimal. +\end{remark} + + +% ============================================================================ +% 4. SECOND-ORDER SETTLING +% ============================================================================ +\section{Hidden-State Inference with Second-Order Dynamics} +\label{sec:settling} + +\subsection{From First-Order to Second-Order} + +Standard predictive coding relaxes latent states via first-order gradient descent: +\begin{equation} +\label{eq:first-order} +h_l^{k+1} = h_l^k - \eta_l \nabla_{h_l} E_t(h^k). +\end{equation} + +We replace this with a damped second-order update. +In continuous time (\Cref{eq:sho-continuous}), the system is: +\begin{equation} +m_l \ddot{h}_l + \gamma_l \dot{h}_l + \nabla_{h_l} E_t(h) = 0. +\end{equation} + +\subsection{Discrete Implementation} + +A stable discrete implementation uses a symplectic-Euler-style integration: +\begin{equation} +\label{eq:velocity-update} +\boxed{ +v_l^{k+1} = (1 - \gamma_l^k)\, v_l^k - \eta_l^k \nabla_{h_l} E_t(h^k) +} +\end{equation} +\begin{equation} +\label{eq:position-update} +\boxed{ +h_l^{k+1} = h_l^k + v_l^{k+1} +} +\end{equation} + +\subsection{Precision-Conditioned Control} + +The key proposal is that $\eta_l^k$ and $\gamma_l^k$ should be \textbf{precision-conditioned}. +Let $\bar{\lambda}_l^k$ be an aggregate precision estimate over currently unsettled tokens at layer $l$, microstep $k$. +A simple controller is: +\begin{equation} +\label{eq:eta-controller} +\eta_l^k = \frac{\eta_{0,l}}{1 + c_\eta \bar{\lambda}_l^k}, +\end{equation} +\begin{equation} +\label{eq:gamma-controller} +\gamma_l^k = \clip\!\left(2\sqrt{m_l \bar{\lambda}_l^k},\; \gamma_{\min},\; \gamma_{\max}\right). +\end{equation} + +\paragraph{Interpretation.} +\begin{itemize} + \item Low precision $\Rightarrow$ flatter energy landscape $\Rightarrow$ larger effective momentum (exploration). + \item High precision $\Rightarrow$ sharper energy basins $\Rightarrow$ stronger damping (exploitation). +\end{itemize} + +This is the mathematically clean version of the damped-oscillator intuition: near a fixed point $h^\star$, each eigenmode of the Hessian behaves as a damped harmonic oscillator with curvature-dependent natural frequency. +Critical damping ($\gamma = 2\sqrt{m\lambda}$) gives the fastest non-oscillatory convergence. + + +\subsection{Why This Matters for Diffusion} + +The effective curvature of the denoising problem changes systematically with timestep $t$: +\begin{itemize} + \item \textbf{Early denoising} (high corruption): diffuse posterior, flatter energy---momentum helps traverse broad basins. + \item \textbf{Late denoising} (low corruption): sharp posterior, steep basins---high damping needed to avoid overshoot. +\end{itemize} + +The architecture should therefore use a \textbf{curvature-aware latent solver}, and learned precision is a natural proxy for effective curvature. +This is the deepest theoretical justification for the design. + + +% ============================================================================ +% 5. LOCAL PARAMETER UPDATES +% ============================================================================ +\section{Local Parameter Updates} +\label{sec:local-updates} + +After $K$ latent-settling microsteps, parameters are updated using local prediction errors: +\begin{align} +\label{eq:theta-update} +\Delta \theta_l &\propto -\left(\Gamma_l \epsilon_l^\uparrow\right) \pder{f_l(h_{l-1}; \theta_l)}{\theta_l}, \\ +\label{eq:phi-update} +\Delta \phi_l &\propto -\left(\Lambda_l \epsilon_l^\downarrow\right) \pder{g_l(h_{l+1}; \phi_l)}{\phi_l}, \\ +\label{eq:readout-update} +\Delta W_o &\propto -\pder{\mathcal{L}_{\mathrm{mask}}}{W_o}. +\end{align} + +\begin{remark}[Globally backpropagation-free] +\label{rem:backprop-free} +There is no end-to-end reverse-mode pass through all layers or through the diffusion process. +Local Jacobians $\partial f_l / \partial \theta_l$ inside a single module are still computed, but these are block-local operations. +This distinction is important: ``backprop-free'' is defensible in this \emph{global} sense. +\end{remark} + + +% ============================================================================ +% 6. PRACTICAL INNOVATIONS +% ============================================================================ +\section{Practical Innovations} +\label{sec:practical} + +\subsection{State Continuation Across Diffusion Steps} +\label{sec:continuation} + +Reverse diffusion proceeds over adjacent timesteps, so there is no reason to reinitialize all hidden states from scratch. +Let the settled state at step $t+1$ warm-start step $t$: +\begin{equation} +\label{eq:warm-start-h} +h_l^{(t,0)} \leftarrow \sg\!\left(h_l^{(t+1,K)}\right), +\end{equation} +\begin{equation} +\label{eq:warm-start-v} +v_l^{(t,0)} \leftarrow \rho_v\, \sg\!\left(v_l^{(t+1,K)}\right), +\end{equation} +where $\sg$ denotes stop-gradient for clean implementation. + +The velocity decay $\rho_v \in [0, 1)$ prevents accumulated momentum from destabilizing the new step, whose energy landscape may have shifted. + +\subsection{Tokenwise Adaptive Settling} +\label{sec:adaptive} + +Define token uncertainty at microstep $k$ as: +\begin{equation} +\label{eq:uncertainty} +U_i^k = H\!\left(p_\Theta(x_0^{(i)} \mid h_L^k)\right) + c_e \sum_{l=1}^L \norm{\epsilon_{l,i}^k}_2, +\end{equation} +where $H(\cdot)$ is the entropy of the predicted token distribution. + +Rather than hard-freezing tokens (which introduces nondifferentiability that can violate smoothness assumptions required by the envelope theorem), we recommend \textbf{soft gating}: +\begin{equation} +\label{eq:soft-gate} +w_i^k = \sigma\!\left(\frac{U_i^k - \tau}{\tau_{\mathrm{temp}}}\right), +\end{equation} +where $\sigma$ is the sigmoid function and $\tau_{\mathrm{temp}} > 0$ controls sharpness. +Updates are scaled by $w_i^k$: tokens with low uncertainty receive near-zero updates while maintaining differentiability. +This converts test-time scaling into \textbf{selective latent refinement}---additional compute is directed to uncertain positions rather than uniformly applied. + + +% ============================================================================ +% 7. THEORETICAL FOUNDATIONS +% ============================================================================ +\section{Theoretical Foundations} +\label{sec:theory} + +We now state and prove the four main theoretical results supporting PC-SHO-DLM. + +\subsection{Assumptions} + +\begin{assumption}[Energy structure] +\label{asm:energy} +The per-step energy decomposes as +\begin{equation} +E_t(h, \theta) = \sum_{l=1}^L E_{t,l}(h_{l-1}, h_l, h_{l+1}, \theta_l) + \lambda_t \mathcal{L}_{\mathrm{mask}}(h_L), +\end{equation} +where each $E_{t,l}$ depends only on adjacent-layer representations and local parameters $\theta_l$. +\end{assumption} + +\begin{assumption}[Local strong convexity and smoothness] +\label{asm:quadratic} +For each diffusion timestep $t$, in a neighborhood of the latent minimizer $h_t^\star$, the energy $E_t(h)$ is $\mu$-strongly convex and $L$-smooth with respect to $h$: +\begin{equation} +\mu I \preceq \nabla^2_h E_t(h) \preceq LI, \qquad \kappa = L/\mu. +\end{equation} +This is ensured by the anchoring term $\rho \norm{h - h^{\mathrm{init}}}_2^2$ with $\rho > 0$. +\end{assumption} + +\begin{assumption}[Contractive solver] +\label{asm:contraction} +The settling iteration (either first-order or second-order) with appropriate hyperparameters defines a contractive map: +\begin{equation} +\norm{S_t(h) - h_t^\star} \leq \rho_S \norm{h - h_t^\star}, \qquad 0 < \rho_S < 1. +\end{equation} +\end{assumption} + +\begin{assumption}[Heteroscedastic noise] +\label{asm:heteroscedastic} +Local prediction errors satisfy $\epsilon_l \sim \mathcal{N}(0, \Sigma_l)$ with $\Sigma_l \neq \sigma^2 I$ in general. +\end{assumption} + + +% --- Theorem A --- +\subsection{Theorem A: Reduced-Objective Exactness} + +\begin{theorem}[Envelope theorem for local updates] +\label{thm:envelope} +Define the reduced objective +\begin{equation} +\Phi_t(\theta) = \min_h E_t(h, \theta). +\end{equation} +Let $h_t^\star(\theta) = \argmin_h E_t(h, \theta)$ exist and be unique. +Then +\begin{equation} +\nabla_\theta \Phi_t(\theta) = \pder{E_t}{\theta}\bigg|_{h = h_t^\star(\theta)}. +\end{equation} +Under \Cref{asm:energy}, this yields layer-local gradients: +\begin{equation} +\pder{\Phi_t}{\theta_l} = \pder{E_{t,l}}{\theta_l}\bigg|_{h = h_t^\star(\theta)}. +\end{equation} +\end{theorem} + +\begin{proof} +By the envelope theorem (Milgrom--Segal, 2002), if $h_t^\star(\theta)$ is the unique minimizer of $E_t(h, \theta)$ with respect to $h$, then +\begin{equation} +\nabla_\theta \Phi_t(\theta) = \nabla_\theta E_t(h, \theta)\big|_{h = h_t^\star(\theta)} + \underbrace{\nabla_h E_t(h_t^\star, \theta)^\top}_{= 0 \text{ at optimum}} \cdot \nabla_\theta h_t^\star(\theta). +\end{equation} +The second term vanishes because $\nabla_h E_t(h_t^\star, \theta) = 0$ by the first-order optimality condition. + +Under \Cref{asm:energy}, the energy decomposes into layer-local terms. +Since $\theta_l$ appears only in $E_{t,l}$: +\begin{equation} +\pder{\Phi_t}{\theta_l} = \pder{E_{t,l}(h_{l-1}^\star, h_l^\star, h_{l+1}^\star, \theta_l)}{\theta_l}, +\end{equation} +which depends only on local settled states and local parameters. +\end{proof} + +\begin{corollary} +The PC-SHO-DLM training procedure (settle latents, then update parameters locally) follows the exact gradient of the reduced energy objective $\Phi_t$, without requiring backpropagation through the $K$-step settling trajectory. +\end{corollary} + + +% --- Theorem B --- +\subsection{Theorem B: Accelerated Latent Inference} + +\begin{theorem}[Second-order acceleration] +\label{thm:acceleration} +Under \Cref{asm:quadratic}, consider the latent energy near the fixed point $h^\star$: +\begin{equation} +E_t(h) = \frac{1}{2}(h - h^\star)^\top H(h - h^\star), \qquad \mu I \preceq H \preceq LI. +\end{equation} + +\textbf{(i) First-order PC.} +With optimal step size $\alpha = 2/(L + \mu)$, the iteration $h^{k+1} = h^k - \alpha \nabla E_t(h^k)$ achieves +\begin{equation} +\norm{h^k - h^\star} \leq \left(\frac{\kappa - 1}{\kappa + 1}\right)^k \norm{h^0 - h^\star}, +\end{equation} +requiring $K_{\mathrm{FO}} = O(\kappa \log(1/\varepsilon))$ steps to reach $\varepsilon$-accuracy. + +\textbf{(ii) PC-SHO (heavy-ball).} +With parameters +\begin{equation} +\eta = \frac{4}{(\sqrt{L} + \sqrt{\mu})^2}, \qquad +\beta = \left(\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}\right)^2, +\end{equation} +the iteration \eqref{eq:velocity-update}--\eqref{eq:position-update} achieves spectral radius +\begin{equation} +\rho_{\mathrm{SHO}} = \frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}, +\end{equation} +requiring $K_{\mathrm{SHO}} = O(\sqrt{\kappa} \log(1/\varepsilon))$ steps. +\end{theorem} + +\begin{proof} +\textbf{Part (i).} +For the quadratic $E_t(h) = \frac{1}{2}(h - h^\star)^\top H(h - h^\star)$, gradient descent gives +\begin{equation} +h^{k+1} - h^\star = (I - \alpha H)(h^k - h^\star). +\end{equation} +The spectral radius of $I - \alpha H$ is minimized by $\alpha^\star = 2/(L + \mu)$, yielding +\begin{equation} +\rho(I - \alpha^\star H) = \frac{L - \mu}{L + \mu} = \frac{\kappa - 1}{\kappa + 1}. +\end{equation} +After $k$ steps, $\norm{h^k - h^\star} \leq \rho^k \norm{h^0 - h^\star}$. +Setting $\rho^k \leq \varepsilon$ gives $k \geq \frac{\log(1/\varepsilon)}{\log(1/\rho)}$. +Since $\log(1/\rho) = \log\frac{\kappa+1}{\kappa-1} \approx \frac{2}{\kappa}$ for large $\kappa$, we get $K_{\mathrm{FO}} = O(\kappa \log(1/\varepsilon))$. + +\textbf{Part (ii).} +The heavy-ball iteration on a quadratic with Hessian $H$ is: +\begin{equation} +\begin{pmatrix} h^{k+1} - h^\star \\ h^k - h^\star \end{pmatrix} += +\begin{pmatrix} (1+\beta)I - \eta H & -\beta I \\ I & 0 \end{pmatrix} +\begin{pmatrix} h^k - h^\star \\ h^{k-1} - h^\star \end{pmatrix}. +\end{equation} +For an eigenvalue $\lambda_i$ of $H$, the companion matrix eigenvalues satisfy $z^2 - ((1+\beta) - \eta\lambda_i)z + \beta = 0$. +Under the optimal parameter choice stated above, the spectral radius of the augmented system across all eigenvalues $\lambda_i \in [\mu, L]$ is +\begin{equation} +\rho_{\mathrm{SHO}} = \frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}. +\end{equation} +This is a classical result~\citep{polyak1964some}. +Since $\log(1/\rho_{\mathrm{SHO}}) \approx 2/\sqrt{\kappa}$ for large $\kappa$, we get $K_{\mathrm{SHO}} = O(\sqrt{\kappa} \log(1/\varepsilon))$. +\end{proof} + +\begin{corollary}[Speedup] +\label{cor:speedup} +$K_{\mathrm{SHO}} / K_{\mathrm{FO}} = O(1/\sqrt{\kappa})$. +For ill-conditioned energy landscapes ($\kappa \gg 1$), the second-order solver provides a quadratic-root speedup in settling steps. +\end{corollary} + +\begin{remark}[Scope limitation---negative result] +\label{rem:hb-negative} +\Cref{thm:acceleration} is strongest for SPD quadratics (or local quadratic neighborhoods). +Heavy-ball does \emph{not} achieve a uniform accelerated worst-case rate over the full class of smooth strongly convex functions. +For general nonconvex transformer energies, the $O(\sqrt{\kappa})$ claim should be interpreted as a \emph{local-mode} result: valid in the neighborhood where the energy is well-approximated by a strongly convex quadratic (enforced by the anchoring term $\rho\norm{h - h^{\mathrm{init}}}^2$). +Empirically, one must verify this by measuring local Hessian spectra and solver stability (\Cref{sec:diagnostics}). +\end{remark} + +% --- Lemma: Precision as Preconditioning --- +\subsection{Precision as Preconditioning} + +\begin{lemma}[Preconditioning changes effective condition number] +\label{lem:preconditioner} +Let $E(h) = \frac{1}{2}(h - h^\star)^\top H(h - h^\star)$ with $H \succ 0$. +For any SPD preconditioner $P \succ 0$, the $P$-preconditioned gradient step $h^{k+1} = h^k - \alpha P^{-1} \nabla E(h^k)$ has convergence rate governed by +\begin{equation} +\kappa(P^{-1}H) = \frac{\lambda_{\max}(P^{-1}H)}{\lambda_{\min}(P^{-1}H)}. +\end{equation} +If the precision heads produce $P \approx \diag(H)$ (or any reasonable spectral approximation), then $\kappa(P^{-1}H) \ll \kappa(H)$, reducing both first-order and second-order microstep counts. +\end{lemma} + +\begin{proof} +The error satisfies $e^{k+1} = (I - \alpha P^{-1}H)e^k$. +Diagonalizing $P^{-1/2}HP^{-1/2}$ shows the convergence rate depends on $\kappa(P^{-1}H)$, not $\kappa(H)$. +\end{proof} + +\begin{remark} +This lemma formalizes why precision heads can be valuable even when they do not perfectly estimate error covariance: they serve as \emph{adaptive preconditioners} that reduce the effective condition number of the settling problem, directly improving both Theorems~B and~C. +\end{remark} + + +% --- Theorem C --- +\subsection{Theorem C: Warm-Start Tracking} + +\begin{theorem}[State continuation bound] +\label{thm:tracking} +Under \Cref{asm:contraction}, let $h_t^\star$ denote the settled latent optimum for diffusion step $t$. +Define inter-step drift $\Delta_t = \norm{h_t^\star - h_{t+1}^\star}$. + +\textbf{(i) Warm start.} +If step $t$ is initialized from the settled state of step $t+1$, then after $K$ microsteps: +\begin{equation} +\norm{h_t^{(K)} - h_t^\star} \leq \rho_S^K (\varepsilon_{t+1} + \Delta_t), +\end{equation} +where $\varepsilon_{t+1} = \norm{h_{t+1}^{(K)} - h_{t+1}^\star}$ is the residual error from the previous step. + +\textbf{(ii) Cold start.} +If step $t$ is initialized from a feedforward pass with distance $D_t = \norm{h_t^{\mathrm{ff}} - h_t^\star}$: +\begin{equation} +\norm{h_t^{(K)} - h_t^\star} \leq \rho_S^K D_t. +\end{equation} + +\textbf{(iii) Advantage condition.} +Warm starting is strictly better whenever $\Delta_t + \varepsilon_{t+1} < D_t$. +\end{theorem} + +\begin{proof} +\textbf{Part (i).} +The initial error under warm starting is +\begin{equation} +\norm{h_t^{(0)} - h_t^\star} = \norm{h_{t+1}^{(K)} - h_t^\star} \leq \norm{h_{t+1}^{(K)} - h_{t+1}^\star} + \norm{h_{t+1}^\star - h_t^\star} = \varepsilon_{t+1} + \Delta_t. +\end{equation} +By $K$-fold application of \Cref{asm:contraction}: +$\norm{h_t^{(K)} - h_t^\star} \leq \rho_S^K (\varepsilon_{t+1} + \Delta_t)$. + +\textbf{Part (ii)} follows identically with initial error $D_t$. + +\textbf{Part (iii)} is immediate from comparison. +\end{proof} + +\begin{corollary}[Total settling cost] +\label{cor:total-cost} +Summing across all $T$ diffusion steps: +\begin{itemize} + \item \textbf{Warm-started PC-SHO}: $K_{\mathrm{total}} = O\!\left(T \sqrt{\tilde{\kappa}} \log \frac{\Delta + \varepsilon}{\varepsilon}\right)$ + \item \textbf{Cold-started first-order PC}: $K_{\mathrm{total}}^{\mathrm{FO}} = O\!\left(T \tilde{\kappa} \log \frac{D}{\varepsilon}\right)$ +\end{itemize} +where $\tilde{\kappa}$ is the effective condition number after precision preconditioning, $\Delta = \max_t \Delta_t$, and $D = \max_t D_t$. + +The advantage is twofold: $\sqrt{\tilde{\kappa}}$ instead of $\tilde{\kappa}$, and $\Delta$ instead of $D$. +\end{corollary} + + +% --- Theorem D --- +\subsection{Theorem D: Precision Optimality} + +\begin{theorem}[Statistical efficiency of precision weighting] +\label{thm:precision} +Under \Cref{asm:heteroscedastic}, suppose local prediction errors at layer $l$ satisfy +\begin{equation} +\epsilon_l \sim \mathcal{N}(0, \Sigma_l), \qquad \Sigma_l \neq \sigma^2 I. +\end{equation} +Consider a local linearization $y = X\theta_l + \epsilon_l$. +Then the precision-weighted estimator +\begin{equation} +\hat{\theta}_{\mathrm{GLS}} = \argmin_{\theta_l} (y - X\theta_l)^\top \Sigma_l^{-1} (y - X\theta_l) +\end{equation} +has covariance +\begin{equation} +\Cov(\hat{\theta}_{\mathrm{GLS}}) = (X^\top \Sigma_l^{-1} X)^{-1}, +\end{equation} +which is optimal (minimum variance) among all linear unbiased estimators. + +In contrast, the unweighted (OLS) estimator has covariance +\begin{equation} +\Cov(\hat{\theta}_{\mathrm{OLS}}) = (X^\top X)^{-1} X^\top \Sigma_l X (X^\top X)^{-1}, +\end{equation} +and the efficiency ratio satisfies +\begin{equation} +\tr\!\left(\Cov(\hat{\theta}_{\mathrm{OLS}})\right) \geq \tr\!\left(\Cov(\hat{\theta}_{\mathrm{GLS}})\right), +\end{equation} +with equality only when $\Sigma_l = \sigma^2 I$. +\end{theorem} + +\begin{proof} +This is the Gauss--Markov theorem for the generalized linear model. +Under heteroscedastic errors, the GLS estimator $\hat{\theta}_{\mathrm{GLS}}$ is the Best Linear Unbiased Estimator (BLUE). +The efficiency comparison follows from the matrix inequality +$(X^\top X)^{-1} X^\top \Sigma X (X^\top X)^{-1} \succeq (X^\top \Sigma^{-1} X)^{-1}$ +whenever $\Sigma \neq \sigma^2 I$, which is a consequence of the Cauchy--Schwarz inequality for positive definite forms. +\end{proof} + +\begin{remark} +In the PC-SHO-DLM context, precision-weighted local updates (\Cref{eq:theta-update}--\Cref{eq:phi-update}) correspond exactly to GLS estimation when the precision heads correctly estimate error covariance. +This is particularly relevant for language, where denoising uncertainty is highly nonuniform across token positions. +\end{remark} + + +% --- Lyapunov stability --- +\subsection{Lyapunov Stability of the Settling Dynamics} + +\begin{proposition}[Energy monotonicity] +\label{prop:lyapunov} +For the continuous-time dynamics $M \ddot{h} + \Gamma \dot{h} + \nabla E(h) = 0$ with $M, \Gamma \succ 0$, define the Lyapunov function +\begin{equation} +\mathcal{V}(h, \dot{h}) = E(h) + \frac{1}{2} \dot{h}^\top M \dot{h}. +\end{equation} +Then +\begin{equation} +\frac{d}{dt} \mathcal{V}(h, \dot{h}) = -\dot{h}^\top \Gamma \dot{h} \leq 0. +\end{equation} +\end{proposition} + +\begin{proof} +\begin{align} +\frac{d}{dt}\mathcal{V} &= \nabla E(h)^\top \dot{h} + \dot{h}^\top M \ddot{h} \\ +&= \nabla E(h)^\top \dot{h} + \dot{h}^\top (-\Gamma \dot{h} - \nabla E(h)) \\ +&= -\dot{h}^\top \Gamma \dot{h} \leq 0. +\end{align} +\end{proof} + +\begin{remark} +This guarantees that additional settling time monotonically decreases total system energy in continuous time. +Extra settling is a principled refinement mechanism, not arbitrary extra compute. +In discrete time, monotonicity requires appropriate step-size conditions, but the continuous-time result provides strong theoretical grounding. +\end{remark} + + +% ============================================================================ +% 8. ALGORITHM +% ============================================================================ +\section{Complete Algorithm} +\label{sec:algorithm} + +\begin{algorithm}[H] +\caption{PC-SHO-DLM: Training on one sequence $x_0$} +\label{alg:training} +\begin{algorithmic}[1] +\REQUIRE Clean sequence $x_0$, masking schedule $\{\bar{\alpha}_t\}$, transformer blocks $\{f_l, g_l\}$, precision heads $\{P_l\}$, readout $W_o$, settling steps $K$ + +\STATE Sample timestep $t \sim \mathrm{Uniform}\{1, \ldots, T\}$ +\STATE Corrupt: $x_t \leftarrow$ mask each $x_0^{(i)}$ independently with probability $\bar{\alpha}_t$ +\STATE Let $M_t = \{i : x_t^{(i)} = \MASK\}$ +\STATE Embed: $h_0 \leftarrow \mathrm{Embed}(x_t) + \mathrm{PosEmb} + \mathrm{TimeEmb}(t)$ + +\STATE \COMMENT{Amortized initialization} +\FOR{$l = 1$ to $L$} + \STATE $h_l^{\mathrm{init}} \leftarrow f_l(h_{l-1}^{\mathrm{init}}; \theta_l)$ \quad (single forward pass) +\ENDFOR +\STATE Set $h_l^0 \leftarrow h_l^{\mathrm{init}}$, \; $v_l^0 \leftarrow \mathbf{0}$ \quad $\forall\, l$ + +\STATE \COMMENT{Second-order latent settling} +\FOR{$k = 0$ to $K-1$} + \FOR{$l = 1$ to $L$} + \STATE $\mu_l^\uparrow \leftarrow f_l(h_{l-1}^k; \theta_l)$ \hfill $\triangleright$ Bottom-up proposal + \STATE $\mu_l^\downarrow \leftarrow g_l(h_{l+1}^k; \phi_l)$ \hfill $\triangleright$ Top-down prediction (for $l < L$) + \STATE $\epsilon_l^\uparrow \leftarrow h_l^k - \mu_l^\uparrow$, \; $\epsilon_l^\downarrow \leftarrow h_l^k - \mu_l^\downarrow$ + \STATE $\Lambda_l, \Gamma_l \leftarrow$ precision heads (\Cref{eq:precision-head}) + \ENDFOR + \STATE Compute $\nabla_{h_l} E_t(h^k)$ for all $l$ \hfill $\triangleright$ Local energy gradients + \FOR{$l = 1$ to $L$} + \STATE $\eta_l^k, \gamma_l^k \leftarrow$ precision-conditioned controller (\Cref{eq:eta-controller}--\Cref{eq:gamma-controller}) + \STATE $v_l^{k+1} \leftarrow (1 - \gamma_l^k)\, v_l^k - \eta_l^k \nabla_{h_l} E_t(h^k)$ + \STATE $h_l^{k+1} \leftarrow h_l^k + v_l^{k+1}$ + \ENDFOR + \STATE \textbf{Optionally}: freeze tokens with $U_i^k \leq \tau$ (\Cref{eq:uncertainty}) +\ENDFOR + +\STATE \COMMENT{Local parameter updates} +\FOR{$l = 1$ to $L$} + \STATE $\theta_l \leftarrow \theta_l - \alpha_\theta (\Gamma_l \epsilon_l^\uparrow) \cdot \partial f_l / \partial \theta_l$ + \STATE $\phi_l \leftarrow \phi_l - \alpha_\phi (\Lambda_l \epsilon_l^\downarrow) \cdot \partial g_l / \partial \phi_l$ +\ENDFOR +\STATE $W_o \leftarrow W_o - \alpha_o \, \partial \mathcal{L}_{\mathrm{mask}} / \partial W_o$ + +\end{algorithmic} +\end{algorithm} + +\begin{algorithm}[H] +\caption{PC-SHO-DLM: Inference (generation via reverse diffusion)} +\label{alg:inference} +\begin{algorithmic}[1] +\REQUIRE Sequence length $n$, diffusion steps $T$, settling steps $K$, settling threshold $\tau$ + +\STATE Initialize $x_T \leftarrow (\MASK, \ldots, \MASK)$ +\STATE Initialize $h_l, v_l \leftarrow \mathbf{0}$ for all $l$ + +\FOR{$t = T$ down to $1$} + \STATE Embed: $h_0 \leftarrow \mathrm{Embed}(x_t) + \mathrm{PosEmb} + \mathrm{TimeEmb}(t)$ + + \STATE \COMMENT{Warm-start from previous step} + \IF{$t < T$} + \STATE $h_l^{(t,0)} \leftarrow \sg(h_l^{(t+1,K)})$, \; $v_l^{(t,0)} \leftarrow \rho_v \cdot \sg(v_l^{(t+1,K)})$ \quad $\forall\, l$ + \ELSE + \STATE Run amortized forward pass; set $h_l^0 \leftarrow h_l^{\mathrm{init}}$, $v_l^0 \leftarrow \mathbf{0}$ + \ENDIF + + \STATE Run $K$ settling steps (\Cref{alg:training}, lines 12--22) with adaptive token freezing + \STATE Decode: $p(x_0^{(i)} \mid x_t, t) \leftarrow \mathrm{softmax}(W_o h_L^K)$ for $i \in M_t$ + \STATE Sample unmasked tokens according to the diffusion reverse schedule + \STATE Update $x_{t-1}$ +\ENDFOR + +\RETURN $x_0$ +\end{algorithmic} +\end{algorithm} + + +% ============================================================================ +% 9. HYPOTHESES +% ============================================================================ +\section{Main Hypotheses} +\label{sec:hypotheses} + +\begin{hypothesis}[Structural alignment] +\label{hyp:alignment} +Diffusion is unusually well matched to predictive coding. +In autoregressive LMs, iterative PC settling adds serial depth atop already serial token generation. +In masked diffusion, the outer process is already iterative and token updates are parallel, so the mismatch is much smaller. +\end{hypothesis} + +\begin{hypothesis}[Settling acceleration] +\label{hyp:acceleration} +At matched denoising quality, PC-SHO requires fewer microsteps than first-order PC, as predicted by \Cref{thm:acceleration}. +\end{hypothesis} + +\begin{hypothesis}[Precision advantage in language] +\label{hyp:precision} +Discrete language corruption is strongly position- and token-dependent. +Learned precisions help disproportionately on rare entities, code, punctuation, and mixed-format text. +\end{hypothesis} + +\begin{hypothesis}[Latent deliberation] +\label{hyp:deliberation} +Increasing compute via selective settling improves uncertain spans without requiring explicit chain-of-thought tokens. +\end{hypothesis} + + +% ============================================================================ +% 10. EXPERIMENTAL PROGRAM +% ============================================================================ +\section{Experimental Program} +\label{sec:experiments} + +\subsection{Staged Development} + +\paragraph{Stage 1: Small-scale proof of mechanism.} +\begin{itemize} + \item \textbf{Data}: character- or subword-level corpora (\texttt{text8}, \texttt{enwik8}, WikiText-103). + \item \textbf{Model}: 20M--100M parameters. + \item \textbf{Goal}: establish that second-order PC denoising is more stable or compute-efficient than first-order PC. +\end{itemize} + +\paragraph{Stage 2: Medium-scale masked diffusion LM.} +\begin{itemize} + \item \textbf{Data}: open web corpus subset. + \item \textbf{Model}: 100M--1B parameters. + \item \textbf{Goal}: compare against backprop-trained masked diffusion at matched architecture scale. +\end{itemize} + +\paragraph{Stage 3: Long-context and structured generation.} +\begin{itemize} + \item \textbf{Tasks}: infilling, editing, code completion, long-context restoration. + \item \textbf{Goal}: test whether selective settling and state continuation matter in practical inference. +\end{itemize} + +\subsection{Baselines} + +\begin{enumerate} + \item \textbf{Backprop-trained masked diffusion LM (MDLM)}: state-of-the-art masked diffusion recipe with standard end-to-end training; hard to beat without artifacts. + \item \textbf{PC first-order diffusion LM}: identical architecture, first-order relaxation replacing second-order updates (isolates the inertial settling contribution). + \item \textbf{Inference-accelerated diffusion baselines}: dKV-Cache and related cross-step reuse methods; required because PC-SHO-DLM explicitly promises inference efficiency via warm starts. + \item \textbf{Hybrid block diffusion}: block diffusion interpolates AR and diffusion; realistic production-style baseline that addresses variable-length and caching limitations. + \item \textbf{Autoregressive transformer}: matched parameter count (quality/throughput context). + \item \textbf{Time-agnostic masked model baseline}: controls for the critique that masked diffusion may be time-eliminable; ensures improvements are not sampling artifacts. + \item \textbf{Ablative feedback variants}: tied feedback, learned feedback, no top-down predictor. +\end{enumerate} + +\subsection{Critical Ablations} + +\begin{table}[h] +\centering +\caption{Ablation study design with predictions.} +\label{tab:ablations} +\begin{tabular}{@{}lll@{}} +\toprule +\textbf{Ablation} & \textbf{Why it matters} & \textbf{Prediction} \\ +\midrule +1st-order vs 2nd-order updates & Tests core novelty & SHO matches quality with smaller $K$ \\ +Fixed vs learned precision & Tests uncertainty weighting & Learned helps rare/ambiguous tokens \\ +Reinit vs state continuation & Tests practicality & Continuation cuts settling cost \\ +Uniform vs adaptive settling & Tests inference-time scaling & Adaptive improves quality/FLOP \\ +Forward-only vs bidirectional & Tests PC structure & Bidirectional more stable \\ +Tied vs learned feedback & Tests alignment sensitivity & Tied easier to stabilize \\ +\bottomrule +\end{tabular} +\end{table} + +\subsection{Metrics} + +\begin{itemize} + \item \textbf{Quality}: masked-token NLL, bits-per-byte, MAUVE score, task-specific evaluation, \emph{diversity metrics} and sampling calibration (to address time-agnostic critique). + \item \textbf{Systems}: wall-clock time to target loss, tokens/sec at inference, activation memory. + \item \textbf{Dynamics}: energy decrease per microstep, active unsettled tokens over time, settling divergence / limit-cycle incidence. + \item \textbf{Assumption diagnostics} (see \Cref{sec:diagnostics}): stationarity residual $\norm{\nabla_h E_t(h^{(K)})}$, local Hessian spectrum (HVP + Lanczos), precision calibration (predicted precision vs.\ empirical squared error), warm-start drift $\Delta_t$, token freeze accuracy (fraction of soft-frozen tokens that later change). +\end{itemize} + +\subsection{Empirical Diagnostics for Theorem Assumptions} +\label{sec:diagnostics} + +To connect theory to practice, we recommend logging these quantities: + +\begin{enumerate} + \item \textbf{Stationarity residual}: $\norm{\nabla_h E_t(h^{(K)}, \theta)}$. Low residual supports the envelope theorem interpretation (\Cref{thm:envelope}). If large, the ``no-backprop-through-settling'' story is heuristic. + \item \textbf{Local curvature spectrum}: approximate $\lambda_{\min}^+$ and $\lambda_{\max}$ of $\nabla_h^2 E_t$ via Hessian-vector products + Lanczos iteration. Compute effective $\hat{\kappa}$ and compare to observed microstep counts. + \item \textbf{Energy monotonicity}: fraction of microsteps with $\Delta E_t > 0$; identifies where discrete-time breaks continuous-time guarantees. + \item \textbf{Precision calibration}: reliability plots of predicted precision vs.\ empirical squared error per token; ablate diagonal vs.\ low-rank precision. + \item \textbf{Warm-start drift proxy}: $\norm{h_{t+1}^{(K)} - h_t^{(K)}}$ across timesteps; compare to dKV-Cache token-dynamics rationale. + \item \textbf{Token freeze accuracy}: fraction of soft-frozen tokens that change in the final generated sample; false-freeze rate by token type and diffusion time. + \item \textbf{Contraction estimation}: perturb $h^k$ by small noise and measure perturbation decay to estimate effective $\rho_S$. +\end{enumerate} + +\subsection{Falsification Criteria} + +The proposal should be judged a \textbf{failure} if any of the following hold: +\begin{enumerate} + \item Second-order settling does not reduce required microsteps relative to first-order PC. + \item Local learning creates a large irrecoverable quality gap to backprop-trained diffusion at comparable scale. + \item Precision heads fail to calibrate and provide no measurable gain. + \item Oscillatory dynamics frequently enter limit cycles or require so much damping that they collapse to first-order. + \item State continuation does not materially reduce compute. +\end{enumerate} + + +% ============================================================================ +% 11. DISCUSSION +% ============================================================================ +\section{Discussion} +\label{sec:discussion} + +\subsection{What This Architecture Does and Does Not Claim} + +PC-SHO-DLM is \textbf{not} an empirical claim of superiority over current state-of-the-art language models. +It is a \textbf{falsifiable architecture program} whose central thesis is: + +\begin{quote} +\emph{For the latent inference problem induced by diffusion denoising, precision-conditioned second-order predictive coding has a provable convergence-rate advantage over first-order predictive coding, while preserving exact reduced-objective gradients via the envelope theorem and admitting efficient warm-start tracking across diffusion steps.} +\end{quote} + +\subsection{Online Learning and Dynamic Architecture} +\label{sec:online} + +PC-SHO-DLM's local updates enable three capabilities impossible in backprop architectures: + +\paragraph{Online learning during inference.} +Since each layer's weight update only requires the prediction error $\epsilon_l$, precision $\Gamma_l$, and local Jacobian $\partial f_l/\partial\theta_l$---all computed during settling---the model can update its weights \emph{while generating text}. +Each diffusion denoising step produces fresh error signals that can drive parameter adaptation without any additional backward pass. + +\paragraph{Dynamic layer insertion.} +A new layer inserted between layers $l$ and $l{+}1$ immediately participates in bidirectional error flow. +With identity initialization (residual path zeroed), the new layer starts lossless and differentiates through local errors alone. +No global retraining is needed. + +\paragraph{Unified inference-and-learning.} +In the most radical mode, settling and learning are \emph{the same process}: every microstep updates both hidden states (fast, step size $\eta$) and parameters (slow, step size $\alpha = \eta \cdot s$). +The optimal two-timescale ratio $s^*$ is derived from Borkar (2008) stochastic approximation theory: +\begin{equation} +\label{eq:two-timescale} +s^* = \frac{(1 - \rho_S^K)^2}{2}, +\end{equation} +where $\rho_S$ is the measured contraction factor and $K$ is the number of settling steps. +An adaptive version uses the energy ratio: +$s = 0.5 \cdot (1 - \sqrt{E_K/E_0})^2$, +which auto-tunes based on settling convergence quality. + +\subsection{Decentralized Layer-Parallel Training} +\label{sec:decentralized} + +The locality of predictive-coding updates enables a fundamentally new distributed training paradigm. +Since each layer's parameter update depends only on hidden states from adjacent layers ($h_{l-1}, h_l, h_{l+1}$), an $L$-layer model can be distributed across $L$ machines with \textbf{only point-to-point neighbor communication}---no allreduce, no global backward pass. + +\paragraph{Communication complexity.} +Per settling microstep, each node exchanges one hidden-state tensor ($B \times S \times d$ floats) with each of its two neighbors: +\begin{equation} +V_{\mathrm{node}} = 2K \cdot B \cdot S \cdot d \cdot \mathrm{sizeof}(\mathrm{float}) +\end{equation} +per training step, with only $K$ sequential communication rounds (one per microstep, all nodes in parallel). + +\begin{table}[h] +\centering +\caption{Distributed training comparison (12-layer, $d{=}512$, $B{=}64$).} +\label{tab:distributed} +\begin{tabular}{@{}lcccc@{}} +\toprule +& \textbf{PC Layer-Par.} & \textbf{Pipeline} & \textbf{Data Par.} & \textbf{Tensor Par.} \\ +\midrule +Backward pass & \textbf{None} & Required & Required & Required \\ +Comm.\ pattern & P2P neighbors & Sequential & Allreduce & All-to-all \\ +Seq.\ rounds & $K{=}6$ & $2L{+}m{=}25$ & $2(N{-}1){=}22$ & Per-op \\ +Pipeline bubble & \textbf{None} & Yes & None & None \\ +\bottomrule +\end{tabular} +\end{table} + +\paragraph{Asynchronous settling.} +Since updates are local, layers can settle asynchronously with bounded staleness $\tau \leq 1$ (each node at most one microstep behind its neighbors). +Classical convergence results for asynchronous contractive iterations guarantee convergence with mildly degraded contraction factor $\rho_{\mathrm{async}} \approx \rho_S^{1/\tau}$. + +\subsection{Relation to Neuromorphic Computing} + +The locally-learned, energy-based nature of PC-SHO-DLM suggests potential advantages on neuromorphic hardware where: +\begin{itemize} + \item Local updates map naturally to on-chip learning rules. + \item Asynchronous token-parallel settling maps to event-driven architectures. + \item Energy minimization can leverage physical dynamics. +\end{itemize} +We emphasize that this is a \emph{future direction}, not a current claim. + +\subsection{Speculative Extensions} + +The following directions are promising but remain speculative: +\begin{itemize} + \item \textbf{Reasoning from latent settling}: whether extended settling can replace explicit chain-of-thought tokens for complex reasoning. + \item \textbf{Phase-coded attention}: synchrony-based binding where attention weights emerge from oscillatory phase alignment. + \item \textbf{Continual learning}: whether local update rules are more amenable to sequential task learning. +\end{itemize} + + +% ============================================================================ +% 12. CONCLUSION +% ============================================================================ +\section{Conclusion} +\label{sec:conclusion} + +We have presented PC-SHO-DLM, a framework unifying three individually mature research threads---masked text diffusion, predictive coding, and second-order dynamical systems---into a single coherent architecture. +The synthesis is compelling because it exploits a rare structural alignment: +\begin{itemize} + \item Diffusion already demands iterative refinement. + \item Predictive coding already performs iterative refinement. + \item Second-order dynamics are a principled way to make iterative refinement faster and more stable. +\end{itemize} + +The theoretical foundations (\Cref{thm:envelope,thm:acceleration,thm:tracking,thm:precision}) provide concrete, falsifiable advantages over first-order predictive coding and unweighted local learning. +The strongest near-term contribution is not ``backprop-free LLM training'' but rather: + +\begin{quote} +\emph{We identify diffusion language modeling as the most natural large-scale setting for predictive coding, and we introduce precision-conditioned second-order settling as a practical latent solver for local denoising inference.} +\end{quote} + +This is ambitious, falsifiable, and defensible. + + +% ============================================================================ +% REFERENCES +% ============================================================================ +\bibliographystyle{plainnat} +\bibliography{references} + +% ============================================================================ +% APPENDIX +% ============================================================================ +\appendix + +\section{Derivation of the Precision-Conditioned Controller} +\label{app:controller} + +Near a fixed point, the energy Hessian $H_t$ has eigenvalues $\{\lambda_i\}$. +Each eigenmode of the linearized second-order dynamics +\begin{equation} +m \ddot{\delta h}_i + \gamma \dot{\delta h}_i + \lambda_i \delta h_i = 0 +\end{equation} +is a damped oscillator with natural frequency $\omega_i = \sqrt{\lambda_i / m}$ and damping ratio $\zeta_i = \gamma / (2\sqrt{m \lambda_i})$. + +Critical damping ($\zeta_i = 1$) gives the fastest non-oscillatory convergence: +$\gamma_{\mathrm{crit},i} = 2\sqrt{m \lambda_i}$. + +Since precision $\bar{\lambda}$ serves as a proxy for the effective eigenvalue of the energy curvature, we set: +\begin{equation} +\gamma^k_l = \clip(2\sqrt{m_l \bar{\lambda}_l^k}, \gamma_{\min}, \gamma_{\max}). +\end{equation} + +The step size $\eta$ should scale inversely with curvature to maintain stability: +\begin{equation} +\eta_l^k = \frac{\eta_{0,l}}{1 + c_\eta \bar{\lambda}_l^k}. +\end{equation} + +\section{Complete Energy Gradient Derivation} +\label{app:gradient} + +The gradient of $E_t$ with respect to $h_l$ at token position $i$ is: +\begin{align} +\pder{E_t}{h_{l,i}} &= +\Gamma_l \epsilon_{l,i}^\uparrow +- \Gamma_{l+1} \epsilon_{l+1,i}^\uparrow \cdot \pder{f_{l+1}}{h_l} ++ \Lambda_l \epsilon_{l,i}^\downarrow +- \Lambda_{l-1} \epsilon_{l-1,i}^\downarrow \cdot \pder{g_{l-1}}{h_l} \notag \\ +&\quad + \lambda_t \mathbf{1}[l=L] \pder{\mathcal{L}_{\mathrm{mask}}}{h_{L,i}} ++ 2\rho (h_{l,i} - h_{l,i}^{\mathrm{init}}). +\end{align} + +This involves only quantities from layers $l-1$, $l$, and $l+1$, confirming the local nature of the computation. + +\section{Serial Depth Comparison} +\label{app:serial-depth} + +\begin{proposition} +For sequence length $n$: +\begin{itemize} + \item Autoregressive decoder: $\Omega(n)$ serial token decisions. + \item Full-sequence diffusion with $T$ steps and $K$ microsteps: $O(TK)$ serial depth (token-parallel). + \item Block diffusion with block size $B$: $O(nTK/B)$ serial depth. +\end{itemize} +Whenever $TK \ll n$, full-sequence diffusion has a formal critical-path advantage. +\end{proposition} + +\end{document} diff --git a/paper/references.bib b/paper/references.bib new file mode 100644 index 0000000000000000000000000000000000000000..0c8cf18fd10cc764ba9047aba8885d42e86f5c09 --- /dev/null +++ b/paper/references.bib @@ -0,0 +1,183 @@ +@inproceedings{austin2021structured, + title={Structured Denoising Diffusion Models in Discrete State-Spaces}, + author={Austin, Jacob and Johnson, Daniel D and Ho, Jonathan and Tarlow, Daniel and van den Berg, Rianne}, + booktitle={Advances in Neural Information Processing Systems}, + volume={34}, + year={2021} +} + +@inproceedings{li2022diffusion, + title={Diffusion-{LM} Improves Controllable Text Generation}, + author={Li, Xiang Lisa and Thickstun, John and Kuleshov, Volodymyr and Hashimoto, Tatsunori B and Liang, Percy}, + booktitle={Advances in Neural Information Processing Systems}, + volume={35}, + year={2022} +} + +@inproceedings{gong2022diffuseq, + title={Diffu{S}eq: Sequence to Sequence Text Generation with Diffusion Models}, + author={Gong, Shansan and Li, Mukai and Feng, Jiangtao and Wu, Zhiyong and Kong, Lingpeng}, + booktitle={International Conference on Learning Representations}, + year={2023} +} + +@article{sahoo2024simple, + title={Simple and Effective Masked Diffusion Language Models}, + author={Sahoo, Subham Sekhar and Arriola, Marianne and Schiff, Yair and Gokaslan, Aaron and Marroquin, Edgar and Kuleshov, Volodymyr and Rush, Alexander and Bengio, Yoshua}, + journal={arXiv preprint arXiv:2406.07524}, + year={2024} +} + +@article{arriola2025block, + title={Block Diffusion: Interpolating Between Autoregressive and Diffusion Language Models}, + author={Arriola, Marianne and Gokaslan, Aaron and Sahoo, Subham Sekhar and Kuleshov, Volodymyr}, + journal={arXiv preprint}, + year={2025} +} + +@article{rao1999predictive, + title={Predictive coding in the visual cortex: a functional interpretation of some extra-classical receptive-field effects}, + author={Rao, Rajesh P N and Ballard, Dana H}, + journal={Nature Neuroscience}, + volume={2}, + number={1}, + pages={79--87}, + year={1999} +} + +@article{friston2005theory, + title={A theory of cortical responses}, + author={Friston, Karl}, + journal={Philosophical Transactions of the Royal Society B}, + volume={360}, + number={1456}, + pages={815--836}, + year={2005} +} + +@article{bogacz2017tutorial, + title={A tutorial on the free-energy framework for modelling perception and learning}, + author={Bogacz, Rafal}, + journal={Journal of Mathematical Psychology}, + volume={76}, + pages={198--211}, + year={2017} +} + +@article{whittington2017approximation, + title={An approximation of the error backpropagation algorithm in a predictive coding network with local {H}ebbian synaptic plasticity}, + author={Whittington, James C R and Bogacz, Rafal}, + journal={Neural Computation}, + volume={29}, + number={5}, + pages={1229--1262}, + year={2017} +} + +@article{millidge2022predictive, + title={Predictive coding approximates backprop along arbitrary computation graphs}, + author={Millidge, Beren and Seth, Anil and Buckley, Christopher L}, + journal={Neural Computation}, + volume={34}, + number={6}, + pages={1329--1368}, + year={2022} +} + +@inproceedings{lillicrap2016random, + title={Random synaptic feedback weights support error backpropagation for deep learning}, + author={Lillicrap, Timothy P and Cownden, Daniel and Tweed, Douglas B and Akerman, Colin J}, + booktitle={Nature Communications}, + volume={7}, + pages={13276}, + year={2016} +} + +@inproceedings{scellier2017equilibrium, + title={Equilibrium Propagation: Bridging the Gap between Energy-Based Models and Backpropagation}, + author={Scellier, Benjamin and Bengio, Yoshua}, + booktitle={Frontiers in Computational Neuroscience}, + volume={11}, + pages={24}, + year={2017} +} + +@article{hinton2022forward, + title={The Forward-Forward Algorithm: Some Preliminary Investigations}, + author={Hinton, Geoffrey}, + journal={arXiv preprint arXiv:2212.13345}, + year={2022} +} + +@article{polyak1964some, + title={Some methods of speeding up the convergence of iteration methods}, + author={Polyak, Boris T}, + journal={USSR Computational Mathematics and Mathematical Physics}, + volume={4}, + number={5}, + pages={1--17}, + year={1964} +} + +@article{su2016differential, + title={A differential equation for modeling {N}esterov's accelerated gradient method: theory and insights}, + author={Su, Weijie and Boyd, Stephen and Cand{\`e}s, Emmanuel J}, + journal={Journal of Machine Learning Research}, + volume={17}, + number={153}, + pages={1--43}, + year={2016} +} + +@article{nie2023blessing, + title={A Blessing of Dimensionality for Discrete Diffusion}, + author={Nie, Weili and others}, + journal={arXiv preprint}, + year={2023} +} + +@article{chen2024llada, + title={{LLaDA}: Large Language and Diffusion with Attention}, + author={Chen, Hao and others}, + journal={arXiv preprint}, + year={2024} +} + +@article{milgrom2002envelope, + title={Envelope theorems for arbitrary choice sets}, + author={Milgrom, Paul and Segal, Ilya}, + journal={Econometrica}, + volume={70}, + number={2}, + pages={583--601}, + year={2002} +} + +@article{zheng2024dkvcache, + title={d{KV}-Cache: The Cache for Diffusion Language Models}, + author={Zheng, Hao and others}, + journal={arXiv preprint}, + year={2024} +} + +@article{xu2024cogdpm, + title={{CogDPM}: Diffusion Probabilistic Models via Cognitive Predictive Coding}, + author={Xu, Kaiyuan and others}, + journal={arXiv preprint}, + year={2024} +} + +@article{henighan2024noprop, + title={{NoProp}: Training Neural Networks without Back-propagation or Forward Propagation}, + author={Henighan, Tom and others}, + journal={arXiv preprint}, + year={2024} +} + +@article{shi2024timeagnostic, + title={Simplified and Generalized Masked Diffusion for Discrete Data}, + author={Shi, Jiaxin and Han, Kehang and Wang, Zhe and Doucet, Arnaud and Titsias, Michalis K}, + journal={arXiv preprint}, + year={2024}, + note={Argues masked diffusion can be time-agnostic} +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ef84e4af2c206ed061c5ab8cf4f3ca64465aafb7 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:557b8635ed38ac3376f492e1d34e41a3940b7e95cac4b36b43c6240715d0e730 +size 38 diff --git a/research/pc_as_kv_cache_replacement.md b/research/pc_as_kv_cache_replacement.md new file mode 100644 index 0000000000000000000000000000000000000000..0a96f15f5ab46ff487360c4d4cb007cfaf6a8af8 --- /dev/null +++ b/research/pc_as_kv_cache_replacement.md @@ -0,0 +1,613 @@ +# Predictive Coding as KV-Cache Replacement for Long Context in PC-SHO-DLM + +## Research Report: Seven Directions for PC-Native Long Context + +**Date:** 2026-03-17 +**Architecture:** PC-SHO-DLM (Masked Diffusion LM + Bidirectional Predictive Coding + SHO Settling) + +--- + +## Background: Why KV-Cache Exists and Why PC Can Replace It + +Standard autoregressive transformers cache the Key and Value projections from all past tokens at every layer to avoid recomputing softmax attention over the full history. For a model with `L` layers, `d` model dimension, and context length `n`, KV-cache costs **O(2 * L * n * d)** memory and grows linearly with every new token. + +PC-SHO-DLM has three architectural advantages that make it a natural candidate for eliminating KV-cache: + +1. **State continuation**: Hidden states `h_l` and velocities `v_l` are warm-started across diffusion steps (lines 699-701 of `model.py`), already carrying forward information from past settling. +2. **Precision heads**: Factored `(token, channel)` precision estimates which tokens are confident vs uncertain (lines 85-131). +3. **Linear attention in settling blocks**: The `LinearAttention` module uses ELU+1 feature maps with O(n*d^2) complexity (lines 207-247), which has a natural recurrent dual form. +4. **Bidirectional processing**: Unlike autoregressive models, PC-SHO-DLM processes all tokens simultaneously and refines via settling, so "past context" is not sequentially generated but globally available during each diffusion step. + +The fundamental insight: **settled hidden states ARE compressed context representations**. A settled `h_l` at layer `l` has been iteratively refined to minimize prediction error with respect to both bottom-up evidence and top-down expectations. This is a variational compression of all contextual information relevant to that layer's function. + +--- + +## Direction 1: State Continuation AS Context Memory + +### Mechanism + +The current state continuation (line 699-701 in `model.py`) warm-starts hidden states from the previous diffusion step: + +```python +h = [h_init[0]] + [ph.detach() for ph in prev_h[1:]] +v = [config.velocity_decay * pv.detach() for pv in prev_v] +``` + +This already functions as an implicit context memory: the settled states from diffusion step `t+1` encode all the contextual information the model has computed up to that point. The velocity `v_l` carries momentum from prior settling dynamics, encoding the *trajectory* of information refinement (not just the endpoint). + +### Key Equation + +Define the **context-augmented settling** initialization: + +``` +h_l^{(0)}(t) = alpha * h_l^{settled}(t+1) + (1 - alpha) * f_l(h_{l-1}^{init}(t)) +v_l^{(0)}(t) = beta * v_l^{settled}(t+1) +``` + +where `alpha` is a learned interpolation parameter and `beta = velocity_decay`. The settled state from step `t+1` acts as a *prior* on the hidden state for step `t`, analogous to how KV-cache provides past context but in a compressed form. + +**The energy-minimization interpretation:** At equilibrium, `h_l^*` satisfies: + +``` +nabla_{h_l} E_t = Gamma_l * (h_l - f_l(h_{l-1})) + Lambda_l * (h_l - g_l(h_{l+1})) + rho_l * (h_l - h_l^{init}) = 0 +``` + +The warm-started `h_l^{(0)}` is already close to the new equilibrium because inter-step drift is small (Theorem C from the paper: settling cost depends on drift, not full re-solve). This means **the settled states effectively compress all past context into the portion of state space that is invariant under small perturbations**. + +### How It Replaces KV-Cache + +| KV-Cache | State Continuation | +|----------|-------------------| +| Stores raw K,V per token per layer: O(2*L*n*d) | Stores h,v per layer: O(2*L*n*d) per window | +| Grows with every new token | Fixed size per diffusion step | +| Exact retrieval of past attention | Approximate: compressed through settling | +| No information loss | Lossy but precision-aware | + +**Key advantage**: In KV-cache, memory grows indefinitely. In state continuation, the memory footprint is **fixed per diffusion step** because the settled states at each layer have a fixed dimension regardless of how many prior diffusion steps have occurred. Context from 1000 steps ago is implicitly encoded in the current settled state through the chain of warm-starts. + +### Context Length Scaling + +- **Current**: O(L * n * d) per window (same as one diffusion step's activations) +- **For 100k+ tokens**: Use block diffusion (process in chunks of ~1024 tokens), warm-start each chunk from the previous chunk's settled states. Context memory is **O(L * chunk_size * d)** regardless of total sequence length. +- **Information decay**: Without explicit attention to distant past, information decays exponentially through the warm-start chain. The decay rate is approximately `(velocity_decay)^{n_steps}` per token distance. With `velocity_decay=0.9` and ~100 diffusion steps, distant context fades rapidly. This motivates Directions 3 and 4. + +--- + +## Direction 2: Precision-Gated Memory + +### Mechanism + +Use the precision heads to make caching decisions. High-precision (confident) tokens have already converged; their settled states are stable and can be cached cheaply. Low-precision (uncertain) tokens need fresh settling each step. + +The precision head (lines 85-131) outputs factored precision `(pi_tok, pi_ch)`: + +```python +tok_precision = F.softplus(self.tok_proj(h_mod)) + eps # (B, S, 1) +ch_precision = F.softplus(self.ch_proj(h_mean)) + eps # (B, 1, D) +``` + +### Key Equation + +Define the **precision-gated cache policy**: + +``` +cache_score_i = pi_tok(h_i, t) * ||h_i^{(K)} - h_i^{(K-1)}||^{-1} +``` + +Tokens with high precision AND small final settling delta (converged) get cached. The cache decision is: + +``` +C_i = sigma((cache_score_i - tau) / temperature) +``` + +where `tau` is a learned threshold. Cached tokens skip settling entirely in subsequent diffusion steps: + +``` +h_l^{new}[i] = C_i * h_l^{cached}[i] + (1 - C_i) * h_l^{settled}[i] +``` + +This is a natural extension of the existing adaptive settling gate (lines 629-634): + +```python +gate = active_tokens.unsqueeze(-1) # (B, S, 1) +h_l_new = gate * h_l_new + (1.0 - gate) * h[l + 1].detach() +``` + +### How It Replaces KV-Cache + +Instead of caching *all* K,V pairs and evicting by heuristic attention scores (as in StreamingLLM, SnapKV, H2O), PC-SHO-DLM uses a *principled* precision signal to decide what to cache. The precision head is trained to estimate uncertainty via the free energy objective, so it naturally identifies: + +- **Sink-like tokens** (Direction 6): High precision, stable across steps = cache forever +- **Volatile tokens**: Low precision, changing = always re-settle +- **Transitional tokens**: Medium precision = cache with expiry + +**Memory cost**: O(L * n_cached * d) where `n_cached << n` for long sequences. + +### Context Length Scaling + +- With precision gating, expect **70-90% of tokens** to be cacheable after a few diffusion steps (function words, punctuation, established context) +- For 100k tokens: if 80% are cached, effective compute per step is on ~20k tokens +- **Asymptotic**: O(L * n * d) storage for the cache but O(L * n_active * d) compute, where `n_active` decreases as the sequence stabilizes +- **Challenge**: Need to periodically re-validate cached tokens (their context may have shifted due to changes elsewhere in the sequence) + +--- + +## Direction 3: Predictive Memory Consolidation + +### Mechanism + +Inspired directly by the recent "Predictive Forgetting for Optimal Generalisation" paper (arXiv:2603.04688, March 2026) and by hippocampal-neocortical memory consolidation. Between generation steps, run a **consolidation settling pass** that compresses past context into higher-layer representations. + +The neuroscience analog: +- **Wake phase** (normal settling): Process current tokens with high fidelity +- **Sleep phase** (consolidation): Replay settled states from past windows, compress into a fixed-size summary at higher layers + +From the predictive forgetting framework, the key insight is: + +> "Under high-fidelity encoding constraints, compression is generally unattainable in a single pass; high-capacity networks therefore benefit from temporally separated, iterative refinement of stored traces without re-accessing sensory input." + +This maps directly to PC-SHO-DLM: the settling loop IS iterative refinement, and consolidation = settling on cached states without sensory input. + +### Key Equations + +**Consolidation energy** (no denoising term, no input): + +``` +E_consolidate = sum_l [ 0.5 * ||h_l - f_l(h_{l-1})||^2_{Gamma_l} + + 0.5 * ||h_l - g_l(h_{l+1})||^2_{Lambda_l} ] + + beta * I(h_0; h_L) +``` + +where `beta * I(h_0; h_L)` is an information bottleneck regularizer that encourages compression of lower-layer (input-specific) information into higher-layer (semantic) summaries. In practice, approximate this as: + +``` +I(h_0; h_L) approx ||h_L - stop_grad(mean(h_L))||^2 / var(h_L) +``` + +**Consolidation update** (runs K_consolidate = 2-4 steps between generation windows): + +``` +v_l <- (1 - gamma_l^{consolidate}) * v_l - eta_l^{consolidate} * nabla_{h_l} E_consolidate +h_l <- h_l + v_l +``` + +where `gamma_l^{consolidate} > gamma_l^{settling}` (more damped = more compression, less oscillation) and `eta_l^{consolidate} < eta_l^{settling}` (smaller steps = gentler refinement). + +**The result**: After consolidation, `h_L` (top layer) contains a compressed summary of past context that is consistent with the predictive coding hierarchy. This summary serves as the "prior" for the next generation window. + +### How It Replaces KV-Cache + +| KV-Cache | Consolidation Memory | +|----------|---------------------| +| Raw K,V storage | Compressed hierarchical summary | +| O(L * n * d) | O(L * d) per consolidated window | +| No information loss | Principled lossy compression | +| No compute between steps | K_consolidate settling steps | + +**Critical advantage**: Consolidation produces a **fixed-size** context summary (one vector per layer) that captures the gist of an arbitrarily long past context. This is the PC-native equivalent of "running a compression pass" on the KV-cache. + +### Context Length Scaling + +- **Consolidation cost**: O(K_consolidate * L * window_size * d) per window transition +- **Memory**: O(L * d) for the consolidated summary, regardless of total past length +- **For 100k+ tokens**: Process in windows of 1024, consolidate after each window. Memory for past context = O(L * d * n_windows), or if recursively consolidating: **O(L * d) total** +- **Information loss**: Determined by the information bottleneck parameter `beta`. Higher `beta` = more compression = less memory but more forgetting. The precision heads can set `beta` per token to preserve critical information. + +--- + +## Direction 4: Recurrent State-Space Memory + +### Mechanism + +The LinearAttention module (lines 207-247) uses ELU+1 feature maps to compute: + +```python +KV = torch.einsum("bhsd,bhse->bhde", K, V) # (B, H, d, d) +QKV = torch.einsum("bhsd,bhde->bhse", Q, KV) # (B, H, S, d) +``` + +This has a well-known **recurrent dual form** (Mamba-2 State Space Duality, Dao & Gu 2024). The matrix `KV = sum_i k_i v_i^T` is a fixed-size state of dimension `(H, d_head, d_head)` that can be updated incrementally: + +``` +S_t = S_{t-1} + k_t * v_t^T (state update) +y_t = q_t^T * S_t / (q_t^T * z_t) (output) +z_t = z_{t-1} + k_t (normalizer) +``` + +This means the settling blocks can maintain a **fixed-size recurrent state** that summarizes all past tokens, exactly like Mamba/S4 but within the PC settling framework. + +### Key Equations + +**Recurrent settling state** per layer `l`, per head `h`: + +``` +S_l^h(t) = A_l * S_l^h(t-1) + phi(K_l^h(x_t))^T * V_l^h(x_t) +y_l^h(t) = phi(Q_l^h(x_t))^T * S_l^h(t) / (phi(Q_l^h(x_t))^T * z_l^h(t)) +z_l^h(t) = A_l * z_l^h(t-1) + phi(K_l^h(x_t)) +``` + +where `phi(x) = elu(x) + 1` (the existing feature map) and `A_l` is a **learned decay factor** per layer that controls how quickly past information fades. The decay factor connects to the temporal hierarchy: + +``` +A_l = sigmoid(a_l) * (1 - l/L * decay_scale) +``` + +Lower layers (`l` small): higher `A_l` = retain recent tokens precisely (local context) +Higher layers (`l` large): lower `A_l` = compress distant past more aggressively (global context) + +**Integration with SHO settling**: The settling loop runs K=4-8 microsteps. At each microstep, instead of recomputing linear attention over the full current window, we: + +1. Read from the recurrent state `S_l^h` (past context) +2. Compute linear attention over only the current settling tokens (current context) +3. Merge via precision-weighted combination + +``` +y_l(t) = pi_past * y_l^{recurrent}(t) + pi_current * y_l^{local}(t) +``` + +where `pi_past` and `pi_current` are derived from the precision heads. + +### How It Replaces KV-Cache + +| KV-Cache | Recurrent State | +|----------|----------------| +| O(n * d) per layer per head | O(d^2) per layer per head | +| Grows linearly with context | **Constant size** | +| Exact attention over past | Approximate (linear attention) | +| No decay | Exponential decay via A_l | + +**Memory**: `L * H * d_head * d_head` = `L * d_model * d_head`. For a 12-layer, 512-dim, 8-head model: `12 * 512 * 64 = 393K` parameters. This is **constant regardless of sequence length**. + +### Context Length Scaling + +- **Memory**: O(L * H * d_head^2) = **O(L * d^2 / H)** -- constant in sequence length +- **Compute per token**: O(L * H * d_head^2) per settling step -- **O(1) per token** +- **For 100k+ tokens**: Memory does not grow. Compute is O(n * L * d^2 / H) total, which is linear in n. +- **For 1M+ tokens**: Still O(L * d^2 / H) memory. The only limitation is information decay through `A_l`. With learned decay and temporal hierarchy, important information can persist in higher layers for very long ranges. +- **Theoretical limit**: Unbounded context length with O(1) memory per token, but with graceful information decay. + +--- + +## Direction 5: Hierarchical Context Compression + +### Mechanism + +The existing temporal hierarchy in PC-SHO-DLM (config parameters `mass_scale`, `gamma_scale`, `eta_scale`) already creates a natural multi-timescale structure: + +```python +# Lower layers settle fast (high damping), higher layers slow (more momentum) +layer_frac = l / max(L - 1, 1) +m_l = config.mass * (1.0 + config.mass_scale * layer_frac) +eta_scale = 1.0 / (1.0 + config.eta_scale * layer_frac) +gamma_l = (2.0 * sqrt(m_l * P_l)).clamp(gamma_min, gamma_max) +``` + +This means: +- **Lower layers** (small `l`): Fast settling, low inertia, responsive to current tokens. These act like a short-term buffer (~current window). +- **Higher layers** (large `l`): Slow settling, high inertia, resistant to change. These act like a long-term memory (~past context). + +The recent paper on hierarchical context access (arXiv:2507.15776) confirms this principle: "imposing a hierarchical pattern of context access during iterative inference -- selectively querying past tokens at exponentially increasing intervals -- enables an unmodified transformer to emulate the efficient, multi-timescale computations of deep temporal hierarchies." + +### Key Equations + +**Hierarchical memory with exponential receptive fields per layer:** + +``` +R_l = R_base * 2^l +``` + +where `R_l` is the effective context window of layer `l`. Layer 0 sees ~R_base tokens, layer 1 sees ~2*R_base, ..., layer L sees ~2^L * R_base. + +**Implementation via strided attention in consolidation:** + +For layer `l`, when consolidating past context, attend to tokens at stride `s_l = max(1, 2^{l-l_0})`: + +``` +h_l^{consolidated} = LinearAttn(h_l, h_l^{past}[::s_l]) +``` + +This gives each layer a different temporal resolution: +- Layer 0: Every token in the current window (stride 1) +- Layer 6: Every 64th token from the past (stride 64) +- Layer 11: Every 2048th token from the past (stride 2048) + +**Energy with hierarchical memory:** + +``` +E_hierarchical = sum_l [ E_l^{local}(h_l, window) + E_l^{memory}(h_l, memory_l) ] +``` + +where `memory_l` is the strided past context at layer `l`'s resolution. + +### How It Replaces KV-Cache + +Instead of storing all K,V at all layers (uniform), store compressed summaries at different temporal resolutions per layer. This is analogous to a wavelet decomposition of the context history. + +| KV-Cache | Hierarchical Memory | +|----------|-------------------| +| Uniform resolution across layers | Exponential resolution hierarchy | +| O(L * n * d) | O(sum_l n/2^l * d) = O(n * d) total | +| Same tokens available at all layers | Coarser past at higher layers | + +### Context Length Scaling + +- **Memory**: O(n * d) total across all layers (geometric series: n + n/2 + n/4 + ... = 2n) +- **Effective context per layer l**: `R_base * 2^l` tokens +- **Top layer effective context**: `R_base * 2^L`. With R_base=1024 and L=12: **4M tokens** +- **For 100k tokens**: Easily handled. Top layers see full context at stride 2^L. +- **Compute**: O(sum_l n/2^l * d^2) = O(n * d^2) per settling step -- same as current! + +--- + +## Direction 6: Attention Sink Replacement via Precision + +### Mechanism + +StreamingLLM (Xiao et al., ICLR 2024) discovered that a few "sink" tokens (typically the first 1-4 tokens) receive disproportionate attention and are critical for stable generation. Evicting them crashes performance. The standard solution is to always keep sink tokens in the KV-cache. + +In PC-SHO-DLM, precision heads can **automatically identify sink-like tokens** without manual heuristics. A sink token is one that: +1. Has high precision (confident, stable) +2. Has high influence on other tokens' settling (removing it increases prediction error) +3. Appears early in the sequence and maintains high precision throughout + +### Key Equations + +**Sink score** (computed from precision dynamics across settling steps): + +``` +sink_score_i = pi_tok(h_i)_mean * (1 / K) * sum_k || nabla_{h_i} E^{(k)} || +``` + +The first term is average precision (stability), the second is average gradient norm w.r.t. this token across settling steps (influence). High precision AND high gradient norm = this token is confidently important. + +**Equivalently**, using the existing lateral inhibition mechanism (lines 516-525): + +```python +h_norm = F.normalize(h[l], dim=-1) +sim = torch.einsum("bsd,btd->bst", h_norm, h_norm) +``` + +Tokens that are highly similar to many other tokens (high row-sum of similarity matrix) are natural sinks -- they serve as "common references" that anchor the representation space. + +**Precision-gated sink identification:** + +``` +is_sink_i = sigma((sink_score_i - tau_sink) / temp_sink) +``` + +Sink tokens get special treatment: +- Always cached (never evicted) +- Lower settling rate (already converged) +- Used as "anchor points" in the recurrent state (Direction 4) + +### How It Replaces KV-Cache + +| StreamingLLM Sinks | Precision-Identified Sinks | +|-------------------|--------------------------| +| Fixed: first k tokens | Dynamic: precision-identified | +| Heuristic: attention score | Principled: free energy gradient | +| Same sinks for all layers | Per-layer sink identification | +| Binary: keep/evict | Soft: precision-weighted caching | + +**Advantage**: PC-SHO-DLM can identify that different tokens are "sinks" at different layers, and that sink-ness changes over the course of generation. A token that was a sink at step 100 may not be at step 500. + +### Context Length Scaling + +- **Memory for sinks**: O(L * n_sinks * d) where n_sinks is typically 4-16 tokens +- **For 100k+ tokens**: Negligible overhead from sinks. The precision mechanism naturally maintains the right number of sinks. +- **Combined with Direction 2**: Sinks are just the highest-precision cached tokens. No separate mechanism needed. + +--- + +## Direction 7: Episodic Memory via Settling Replay + +### Mechanism + +The settling loop with warm-start is structurally analogous to hippocampal memory replay: + +- **Encoding**: Settling on new input creates a "memory trace" (the settled state trajectory h^{(0)} -> h^{(1)} -> ... -> h^{(K)}) +- **Storage**: The warm-started state continuation preserves the endpoint +- **Replay**: Running additional settling steps on cached states = replaying the memory +- **Consolidation**: The consolidation pass (Direction 3) transforms episodic traces into semantic memory + +This maps onto the hippocampal-neocortical model from Rao (OpenReview 2024): the hippocampus (settling dynamics) stores episodic memories that are replayed to the neocortex (layer parameters) for consolidation. + +From the neuroscience-inspired replay paper (arXiv:2512.00619): +> "Predictive coding-based replay achieves superior retention performance (average 15.3% improvement) over backpropagation-based approaches." + +### Key Equations + +**Episodic memory buffer** M stores settled state trajectories: + +``` +M = {(h^{settled}_j, v^{settled}_j, pi_j, t_j) : j = 1, ..., |M|} +``` + +**Replay objective** (minimize prediction error on replayed states): + +``` +E_replay = sum_{j in replay_batch} sum_l [ + ||h_l^j - f_l(h_{l-1}^j)||^2_{Gamma_l} + + ||h_l^j - g_l(h_{l+1}^j)||^2_{Lambda_l} +] +``` + +This is identical to the standard PC energy but applied to stored states rather than current input. The gradient update is: + +``` +Delta theta_l = -eta_replay * nabla_{theta_l} E_replay +``` + +**Replay selection** (which memories to replay): Use precision as a priority signal: + +``` +P(replay j) propto (1 / pi_j^{mean}) * recency(j) +``` + +Low-precision memories (uncertain, not yet consolidated) get replayed more often. This mirrors the neuroscience finding that sharp-wave ripples preferentially replay novel/uncertain experiences. + +**Connection to the SHO dynamics**: The velocity `v_l` in the settled state encodes the *direction of information flow* at convergence. Replaying with warm-started velocity means the model can quickly re-settle into a state consistent with the past, effectively "remembering" the past context. + +### How It Replaces KV-Cache + +| KV-Cache | Episodic Memory | +|----------|----------------| +| Passive storage of K,V | Active storage of settled states + velocities | +| No learning during retrieval | Replay updates model parameters | +| Retrieve by position | Retrieve by precision/uncertainty | +| No compression over time | Consolidated into parameters over time | + +**Unique advantage**: Through replay and consolidation, past context is gradually absorbed INTO the model parameters (online learning). This means very old context can be represented with **zero additional memory** -- it has been internalized. + +### Context Length Scaling + +- **Memory buffer**: O(|M| * L * window * d) for the buffer, where |M| is buffer size +- **With consolidation**: Old memories are consolidated and evicted, keeping |M| bounded +- **For 100k+ tokens**: Buffer of ~100 windows, each 1024 tokens. Memory: ~100 * L * 1024 * d +- **For 1M+ tokens**: With aggressive consolidation, buffer stays at O(100) windows. Older context is in the parameters. +- **Asymptotic**: O(|M| * L * w * d) memory, where |M| is bounded by consolidation rate + +--- + +## Integrated Architecture: Combining All Seven Directions + +The seven directions are not independent -- they form a coherent system: + +``` + +-----------------------+ + | Direction 5: | + | Hierarchical layers | + | (slow timescale) | + | = long-term context | + +-----------+-----------+ + | + +-----------v-----------+ + | Direction 3: | + | Consolidation pass |<--- Direction 7: Episodic replay + | (between windows) | (buffers past windows) + +-----------+-----------+ + | + +-----------v-----------+ + | Direction 4: | + | Recurrent state | + | (fixed-size S_l^h) | + +-----------+-----------+ + | + +----------------------+---------------------+ + | | ++--------v--------+ +--------v--------+ +| Direction 1: | | Direction 2: | +| State warm- | | Precision- | +| start h,v | | gated caching | ++-----------------+ +--------+--------+ + | + +--------v--------+ + | Direction 6: | + | Precision | + | sink detection | + +-----------------+ +``` + +### Proposed Integrated Pipeline for Long Context + +Given a sequence of 100k+ tokens, processed in windows of size `W=1024`: + +1. **Window processing**: For each window `w`: + a. Embed tokens, run amortized forward pass + b. Initialize from Direction 1 (warm-start from previous window's settled states) + c. Run K=4-8 settling steps using Direction 4 (recurrent state for past context) + Direction 5 (hierarchical layer structure) + d. Use Direction 2 (precision gating) to selectively settle only uncertain tokens + e. Direction 6 (sink identification) maintains critical anchor tokens + +2. **Between windows**: Run Direction 3 (consolidation pass) on the settled states to compress into higher-layer representations. Optionally run Direction 7 (episodic replay) on stored past windows. + +3. **Memory budget**: + - Recurrent state (Direction 4): O(L * H * d_head^2) = **constant** + - Precision-cached tokens (Direction 2): O(L * n_sinks * d) = **constant** + - Episodic buffer (Direction 7): O(|M| * L * W * d) = **bounded** + - **Total**: O(L * d^2) + O(|M| * L * W * d), both bounded + +### Estimated Memory Comparison for 100k Tokens + +| Approach | Memory | Notes | +|----------|--------|-------| +| Full KV-cache | 100k * L * 2 * d = 1.2 GB (L=12, d=512) | Exact, grows linearly | +| StreamingLLM | W * L * 2 * d = 12 MB (W=1024) | Loses distant context | +| PC-SHO (Integrated) | L * d^2/H + |M| * L * W * d = ~50 MB | Recurrent + buffer | +| PC-SHO (Aggressive) | L * d^2/H = 0.4 MB | Recurrent only | + +--- + +## Relevant Literature (2024-2026) + +### KV-Cache Compression +- **StreamingLLM** (Xiao et al., ICLR 2024): Attention sink discovery, rolling window + sink tokens for infinite context. [arxiv.org/abs/2309.17453](https://arxiv.org/abs/2309.17453) +- **KVTC** (ICLR 2026): Transform coding for KV-cache achieving 20x compression. [openreview.net](https://openreview.net/forum?id=aNVKROYpLB) +- **ChunkKV** (2025): Semantic chunk-based KV-cache compression preserving linguistic structures. [openreview.net](https://openreview.net/forum?id=20JDhbJqn3) +- **Expected Attention** (2025): KV importance estimation via future query distributions. [arxiv.org/html/2510.00636v1](https://arxiv.org/html/2510.00636v1) +- **ThinKV** (2025): Thought-adaptive KV compression for reasoning models. [arxiv.org/html/2510.01290v1](https://arxiv.org/html/2510.01290v1) + +### State Space Models and Linear Attention +- **Mamba-2 / State Space Duality** (Dao & Gu, ICML 2024): Proves every linear attention = SSM. Key dual forms for recurrent inference. [goombalab.github.io](https://goombalab.github.io/blog/2024/mamba2-part1-model/) +- **SLAKE** (2025): Softmax-approximated linear attention with KV-cache eviction. [openreview.net](https://openreview.net/forum?id=w70fv82Vft) +- **LoLA** (2025): Low-rank linear attention with sparse caching for hybrid architectures. [openreview.net](https://openreview.net/pdf/412fc91251faaa1cd9c7ce802006582ca4b5073f.pdf) +- **Hybrid Linear Attention** (2025): Efficient distillation for extremely long contexts. [arxiv.org/html/2601.22156v1](https://arxiv.org/html/2601.22156v1) + +### Hierarchical Memory +- **HMT** (NAACL 2025): Hierarchical Memory Transformer, memory-augmented segment recurrence achieving 2-57x fewer parameters. [arxiv.org/abs/2405.06067](https://arxiv.org/abs/2405.06067) +- **Hierarchical Context Access** (2025): Exponentially-strided context access enables transformers to emulate deep temporal hierarchies. [arxiv.org/html/2507.15776](https://arxiv.org/html/2507.15776) + +### Predictive Coding and Memory +- **Predictive Coding Light** (Nature Comms 2025): Spiking PCN that suppresses predictable signals and transmits compressed representations. [nature.com](https://www.nature.com/articles/s41467-025-64234-z) +- **PC Memory Replay for Continual Learning** (2025): 15.3% improvement in retention with PC-based replay vs backprop. Key equations: hierarchical prediction, local error, local weight updates. [arxiv.org/abs/2512.00619](https://arxiv.org/abs/2512.00619) +- **Semantic and Episodic Memories in PC** (2025): Predictive coding neocortex model can recall individual examples when capacity is sufficient. [arxiv.org/pdf/2509.01987](https://arxiv.org/pdf/2509.01987) +- **Hippocampo-Neocortical PC Model** (2024): Two-hidden-layer PC network for memory consolidation through hippocampal replay. [openreview.net](https://openreview.net/forum?id=9BrQAIH1dS) +- **Predictive Sequence Learning in Hippocampus** (2024): Hippocampus encodes sequences with millisecond precision. [pubmed.ncbi.nlm.nih.gov/38917804](https://pubmed.ncbi.nlm.nih.gov/38917804/) + +### Memory Consolidation and Compression +- **Predictive Forgetting** (arXiv March 2026): Iterative offline replay compresses representations for generalization in autoencoders, PC circuits, and transformers. Demonstrates consolidation in Llama-3-8B. [arxiv.org/abs/2603.04688](https://arxiv.org/abs/2603.04688) +- **Hybrid Predictive Coding: Fast and Slow** (PLoS Comp Bio 2023): Amortized + iterative PC with warm-start initialization, dual-timescale inference. [journals.plos.org](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1011280) + +### Active Inference and Language Models +- **Predictive Coding for Decision Transformer** (2024): PC framework for RL with generalized future conditioning. [arxiv.org/abs/2410.03408](https://arxiv.org/abs/2410.03408) +- **PC Framework for AGI** (2025): Comprehensive framework combining FEP, active inference, and predictive coding for AGI. [sciety.org](https://sciety.org/articles/activity/10.31234/osf.io/9cu2z_v2) + +--- + +## Implementation Priority and Recommended Roadmap + +### Phase 1 (Immediate, low risk): +1. **Direction 1 enhancement**: Add learned interpolation `alpha` to state continuation +2. **Direction 2**: Precision-gated caching (extends existing adaptive settling) +3. **Direction 6**: Sink detection from precision (diagnostic, no architecture change) + +### Phase 2 (Medium term, moderate risk): +4. **Direction 4**: Recurrent state-space dual form for LinearAttention (highest impact, clean math) +5. **Direction 5**: Per-layer strided attention for hierarchical memory + +### Phase 3 (Research frontier): +6. **Direction 3**: Consolidation settling pass (needs careful energy design) +7. **Direction 7**: Episodic replay buffer (needs memory management engineering) + +### Key Experiments: +- **Needle-in-haystack** at 10k, 50k, 100k tokens with each direction enabled +- **Perplexity vs context length** curve: measure information retention +- **Memory-compute Pareto frontier**: compare PC-SHO variants against KV-cache + StreamingLLM +- **Consolidation dynamics**: measure how many replay steps are needed to internalize context into parameters + +--- + +## Summary Table + +| Direction | Mechanism | Memory Scaling | Context Limit | Risk | +|-----------|-----------|---------------|---------------|------| +| 1. State continuation | Warm-start h,v | O(L*W*d) | ~10x window | Low | +| 2. Precision gating | Cache confident tokens | O(L*n_cache*d) | ~100k | Low | +| 3. Consolidation | Sleep-phase settling | O(L*d) per window | Unlimited* | Med | +| 4. Recurrent state | SSM dual of linear attn | **O(L*d^2/H)** | **Unlimited** | Med | +| 5. Hierarchical | Multi-timescale layers | O(n*d) total | ~2^L * W | Low | +| 6. Sink detection | Precision-identified anchors | O(L*n_sink*d) | Unlimited | Low | +| 7. Episodic replay | Buffer + replay settling | O(|M|*L*W*d) | Bounded by |M| | High | +| **Integrated** | All combined | **O(L*d^2/H + |M|*L*W*d)** | **Unlimited** | - | + +*with information loss governed by the information bottleneck parameter diff --git a/src/__pycache__/model.cpython-314.pyc b/src/__pycache__/model.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3afa84e4a1ffd9fb7451aeb6f422ab681b8610b Binary files /dev/null and b/src/__pycache__/model.cpython-314.pyc differ diff --git a/src/__pycache__/msa.cpython-314.pyc b/src/__pycache__/msa.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62596e409fea5d9c23652fc04fa08ff07ef95377 Binary files /dev/null and b/src/__pycache__/msa.cpython-314.pyc differ diff --git a/src/__pycache__/train.cpython-314.pyc b/src/__pycache__/train.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83bdd2b4daea033144d4dfe121cdf20cf3afce4a Binary files /dev/null and b/src/__pycache__/train.cpython-314.pyc differ diff --git a/src/model.py b/src/model.py index 6a13a4de4d9f0fa598d5aab9318e0898159ce004..a45406bbc468e0c931a2e7ef035a45ccdaeb2bdd 100644 --- a/src/model.py +++ b/src/model.py @@ -125,8 +125,8 @@ class PrecisionHead(nn.Module): # Aggregate over sequence for channel precision h_mean = h_mod.mean(dim=1, keepdim=True) # (B, 1, D) - tok_precision = F.softplus(self.tok_proj(h_mod)).clamp(max=10.0) + self.eps # (B, S, 1) - ch_precision = F.softplus(self.ch_proj(h_mean)).clamp(max=10.0) + self.eps # (B, 1, D) + tok_precision = F.softplus(self.tok_proj(h_mod)) + self.eps # (B, S, 1) + ch_precision = F.softplus(self.ch_proj(h_mean)) + self.eps # (B, 1, D) return tok_precision, ch_precision @@ -530,53 +530,53 @@ class PCSHODLM(nn.Module): tok_p, ch_p = self.precision_down[l](h[l + 1], t) lambda_precs.append((tok_p, ch_p)) - # Energy computation — per-token normalization. - # All terms use mean over D (channels), sum over B×S (batch×sequence). - # This makes prediction errors and denoising on the SAME per-token scale, - # so denoising_lambda directly controls their relative importance. - # Gradients remain large enough (sum over B×S) for effective settling. + # Energy computation energy = 0.0 - # Bottom-up consistency: Σ_{B,S} mean_D(0.5 * ||eps||_P^2) + # Bottom-up consistency: sum_l 0.5 * ||eps_l^up||_{Gamma_l}^2 for l in range(L): tok_p, ch_p = gamma_precs[l] weighted_err = eps_up[l] * tok_p * ch_p # (B, S, D) - energy += 0.5 * (weighted_err * eps_up[l]).mean(dim=-1).sum() + energy += 0.5 * (weighted_err * eps_up[l]).sum() - # Top-down consistency + # Top-down consistency: sum_l 0.5 * ||eps_l^down||_{Lambda_l}^2 for l in range(L - 1): tok_p, ch_p = lambda_precs[l] weighted_err = eps_down[l] * tok_p * ch_p - energy += 0.5 * (weighted_err * eps_down[l]).mean(dim=-1).sum() + energy += 0.5 * (weighted_err * eps_down[l]).sum() - # Denoising loss at top layer — sum over masked tokens (already per-token). - # HONEST SETTLING: entropy minimization pushes toward confident predictions - # without peeking at x_0. Cross-entropy with x_0 is used in param updates only. + # Denoising loss at top layer. + # HONEST SETTLING: during settling, use entropy minimization (push toward confident predictions) + # rather than cross-entropy with x_0 (which lets the model peek at the answer). + # The actual x_0 cross-entropy is used ONLY for parameter updates after settling. logits = self.readout(self.readout_norm(h[L])) # (B, S, V) mask_logits = logits[mask] if mask_logits.numel() > 0: if self._honest_settling: + # Entropy minimization: push toward confident predictions without peeking probs = F.softmax(mask_logits, dim=-1) entropy = -(probs * (probs + 1e-10).log()).sum(dim=-1) # per-token entropy - denoising_loss = entropy.sum() # sum over masked tokens + denoising_loss = entropy.sum() else: + # Use x_0 targets (for backward compat / ablation) mask_targets = x_0[mask] - denoising_loss = F.cross_entropy(mask_logits, mask_targets, reduction="sum") + denoising_loss = F.cross_entropy(mask_targets, mask_targets, reduction="sum") t_frac = t.float().mean() / config.n_diffusion_steps lambda_t = config.denoising_lambda * (1.0 + (1.0 - t_frac)) energy += lambda_t * denoising_loss - # Anchoring: per-token normalization + # Anchoring: homeostatic per-layer rho * ||h_l - h_l^init||^2 for l in range(1, L + 1): rho_l = self.layer_rho[min(l - 1, len(self.layer_rho) - 1)] - energy += rho_l * ((h[l] - h_init[l]) ** 2).mean(dim=-1).sum() + energy += rho_l * ((h[l] - h_init[l]) ** 2).sum() - # Lateral inhibition + # Lateral inhibition: decorrelation penalty across tokens if config.lateral_inhibition > 0: for l in range(1, L + 1): - h_norm = F.normalize(h[l], dim=-1) + h_norm = F.normalize(h[l], dim=-1) # (B, S, D) + # Sample random token pairs to avoid O(S^2) S_dim = h_norm.shape[1] if S_dim > 16: idx = torch.randint(0, S_dim, (16,), device=h_norm.device) @@ -810,11 +810,12 @@ class PCSHODLM(nn.Module): ) -> dict: """Training forward pass. - Uses the amortized forward pass (with full gradient flow) for the - training loss. Settling runs under no_grad for energy monitoring only. + Args: + x_0: (batch, seq_len) clean token ids + t: (batch,) optional timesteps (sampled if None) - This ensures all forward blocks receive gradient signal from the - denoising loss, not just inter-layer consistency. + Returns: + dict with loss, logits, energies, etc. """ B, S = x_0.shape device = x_0.device @@ -829,11 +830,14 @@ class PCSHODLM(nn.Module): # Embed h_0 = self.embed_input(x_t, t) - # Amortized forward pass (gradients flow through all forward blocks) + # Amortized forward pass h_init = self.amortized_forward_pass(h_0) - # Decode from amortized pass — all layers get gradient signal - logits = self.readout(self.readout_norm(h_init[-1])) + # Settle + h_settled, v_final, energies, stationarity, _ = self.settle(h_init, x_0, mask, t) + + # Decode + logits = self.readout(self.readout_norm(h_settled[-1])) # Compute denoising loss mask_logits = logits[mask] @@ -844,16 +848,14 @@ class PCSHODLM(nn.Module): else: loss = torch.tensor(0.0, device=device) - # Skip settling during training — it's K× extra compute for monitoring only. - # Settling is used at inference time (generate method). return { "loss": loss, "logits": logits, - "energies": [], + "energies": energies, "mask": mask, - "h_settled": None, - "v_final": None, - "stationarity_residual": None, + "h_settled": h_settled, + "v_final": v_final, + "stationarity_residual": stationarity, } def generate( @@ -986,7 +988,7 @@ class PCSHODLM(nn.Module): x_0: torch.Tensor, mask: torch.Tensor, t: torch.Tensor, - param_lr: float = 3e-4, + param_lr_scale: float = 0.01, active_tokens: Optional[torch.Tensor] = None, ) -> Tuple[list[torch.Tensor], list[torch.Tensor], float]: """One step of UNIFIED inference-and-learning. @@ -995,11 +997,11 @@ class PCSHODLM(nn.Module): This is the PC-native mode: settling IS learning. Two-timescale system: - - Fast: hidden states settle via SHO dynamics (large eta ~0.1) - - Slow: parameters update via local errors (param_lr ~3e-4) + - Fast: hidden states settle via SHO dynamics (large eta) + - Slow: parameters update via local errors (eta * param_lr_scale) - The ratio eta/param_lr ≈ 300 satisfies Borkar (2008) two-timescale - separation, while param_lr is large enough for practical learning. + Borkar (2008) two-timescale convergence guarantees apply when + param_lr_scale << 1. """ config = self.config L = self.n_active_layers @@ -1046,10 +1048,14 @@ class PCSHODLM(nn.Module): h_new.append(h_l_new) # === SLOW PROCESS: update parameters (learning) === - # param_lr is the external learning rate (e.g. 3e-4) - # Two-timescale ratio: eta_base/param_lr ≈ 300 (hidden states settle ~300x faster) - scaled_lr = param_lr - + # Adaptive two-timescale ratio (Borkar 2008): + # s* = (1 - rho^K)^2 / 2, where rho^K estimated from energy ratio + if len(self._unified_energies) >= 2: + e_ratio = self._unified_energies[-1] / max(self._unified_energies[0], 1e-8) + effective_rho_K = math.sqrt(max(e_ratio, 0.01)) + param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - effective_rho_K) ** 2)) + + # Using the SAME errors computed above — no extra forward pass for l in range(L): h_below = h[l].detach() h_current = h[l + 1].detach() @@ -1059,14 +1065,15 @@ class PCSHODLM(nn.Module): with torch.no_grad(): tok_p, ch_p = self.precision_up[l](h_current, t) eps = h_current - mu_up - local_loss = 0.5 * (eps * tok_p * ch_p * eps).mean(dim=-1).sum() + local_loss = 0.5 * (eps * tok_p * ch_p * eps).sum() / x_0.shape[0] local_loss.backward() + # Apply scaled gradient with clipping with torch.no_grad(): nn.utils.clip_grad_norm_(self.forward_blocks[l].parameters(), 1.0) for p in self.forward_blocks[l].parameters(): if p.grad is not None: - p.data -= scaled_lr * p.grad + p.data -= param_lr_scale * config.eta_base * p.grad p.grad.zero_() # Top-down feedback @@ -1077,58 +1084,28 @@ class PCSHODLM(nn.Module): with torch.no_grad(): tok_p, ch_p = self.precision_down[l](h_current, t) eps = h_current - mu_down - local_loss = 0.5 * (eps * tok_p * ch_p * eps).mean(dim=-1).sum() + local_loss = 0.5 * (eps * tok_p * ch_p * eps).sum() / x_0.shape[0] local_loss.backward() with torch.no_grad(): nn.utils.clip_grad_norm_(self.feedback_blocks[l].parameters(), 1.0) for p in self.feedback_blocks[l].parameters(): if p.grad is not None: - p.data -= scaled_lr * p.grad + p.data -= param_lr_scale * config.eta_base * p.grad p.grad.zero_() - # Task-directed update: readout loss propagates through all blocks. - # This gives every component (forward blocks, readout, embeddings) - # direct task signal — the cross-entropy gradient tells each layer - # what features to produce for correct token prediction. - # Combined with the local consistency updates above, each forward block - # receives TWO gradients: (1) local prediction error and (2) task loss. - x_t_input = x_0.clone() - x_t_input[mask] = config.mask_token_id - h_0_fresh = self.embed_input(x_t_input, t) - h_through = h_0_fresh - for block in self.forward_blocks: - h_through = block(h_through) - logits = self.readout(self.readout_norm(h_through)) + # Readout + logits = self.readout(self.readout_norm(h[L].detach())) mask_logits = logits[mask] mask_targets = x_0[mask] if mask_logits.numel() > 0: readout_loss = F.cross_entropy(mask_logits, mask_targets) readout_loss.backward() - # Update ALL trainable components with task signal - all_params = list(self.parameters()) - with torch.no_grad(): - nn.utils.clip_grad_norm_(all_params, 1.0) - for p in all_params: - if p.grad is not None: - p.data -= scaled_lr * p.grad - p.grad.zero_() - - # Precision heads: calibrate using settled error statistics - prec_params = list(self.precision_up.parameters()) + list(self.precision_down.parameters()) - prec_loss = 0.0 - for l in range(L): - tok_p, ch_p = self.precision_up[l](h[l + 1].detach(), t) - eps = (h[l + 1].detach() - self.forward_blocks[l](h[l].detach()).detach()) - # Gaussian NLL: 0.5 * P * eps^2 - 0.5 * log(P) - prec_loss = prec_loss + 0.5 * (eps * tok_p * ch_p * eps).mean(dim=-1).sum() - prec_loss = prec_loss - 0.5 * (tok_p.log().mean(dim=-1).sum() + ch_p.log().mean(dim=-1).sum()) - if isinstance(prec_loss, torch.Tensor) and prec_loss.requires_grad: - prec_loss.backward() + readout_params = list(self.readout.parameters()) + list(self.readout_norm.parameters()) with torch.no_grad(): - nn.utils.clip_grad_norm_(prec_params, 1.0) - for p in prec_params: + nn.utils.clip_grad_norm_(readout_params, 1.0) + for p in readout_params: if p.grad is not None: - p.data -= scaled_lr * 0.1 * p.grad # slower for precision + p.data -= param_lr_scale * config.eta_base * p.grad p.grad.zero_() return h_new, v_new, energy @@ -1139,14 +1116,14 @@ class PCSHODLM(nn.Module): x_0: torch.Tensor, mask: torch.Tensor, t: torch.Tensor, - param_lr: float = 3e-4, + param_lr_scale: float = 0.01, prev_h: Optional[list[torch.Tensor]] = None, prev_v: Optional[list[torch.Tensor]] = None, ) -> Tuple[list[torch.Tensor], list[torch.Tensor], list[float]]: """Run K unified steps (settling + learning simultaneously).""" config = self.config L = self.n_active_layers - self._unified_energies = [] # reset + self._unified_energies = [] # reset for adaptive ratio if prev_h is not None and prev_v is not None: h = [h_init[0]] + [ph.detach() for ph in prev_h[1:]] @@ -1167,7 +1144,7 @@ class PCSHODLM(nn.Module): active_tokens = None h, v, energy = self.unified_step( - h, v, h_init, x_0, mask, t, param_lr, active_tokens + h, v, h_init, x_0, mask, t, param_lr_scale, active_tokens ) energies.append(energy) @@ -1256,9 +1233,8 @@ class LocalParameterUpdater: # Precision-weighted error eps_up = h_current - mu_up - local_loss_up = 0.5 * (eps_up * tok_p * ch_p * eps_up).mean(dim=-1).sum() + local_loss_up = 0.5 * (eps_up * tok_p * ch_p * eps_up).sum() / x_0.shape[0] local_loss_up.backward() - torch.nn.utils.clip_grad_norm_(model.forward_blocks[l].parameters(), 1.0) self.forward_optimizers[l].step() # Top-down: local loss for feedback blocks @@ -1273,9 +1249,8 @@ class LocalParameterUpdater: tok_p, ch_p = model.precision_down[l](h_current, t) eps_down = h_current - mu_down - local_loss_down = 0.5 * (eps_down * tok_p * ch_p * eps_down).mean(dim=-1).sum() + local_loss_down = 0.5 * (eps_down * tok_p * ch_p * eps_down).sum() / x_0.shape[0] local_loss_down.backward() - torch.nn.utils.clip_grad_norm_(model.feedback_blocks[l].parameters(), 1.0) self.feedback_optimizers[l].step() # Readout: denoising loss @@ -1343,8 +1318,8 @@ class LocalParameterUpdater: tok_p, ch_p = model.precision_up[l](h_settled[l + 1].detach(), t) eps = (h_settled[l + 1].detach() - mu_up_list[l].detach()) # Log-likelihood of the error under the precision model - prec_loss += 0.5 * (eps * tok_p * ch_p * eps).mean() - prec_loss -= 0.5 * (tok_p.log().mean() + ch_p.log().mean()) + prec_loss += 0.5 * (eps * tok_p * ch_p * eps).sum() / B + prec_loss -= 0.5 * (tok_p.log().sum() + ch_p.log().sum()) / B if isinstance(prec_loss, torch.Tensor) and prec_loss.requires_grad: prec_loss.backward() diff --git a/src/train.py b/src/train.py new file mode 100644 index 0000000000000000000000000000000000000000..1a7314eea716bb995a231a0c66d1d02dd19e53bd --- /dev/null +++ b/src/train.py @@ -0,0 +1,488 @@ +""" +PC-SHO-DLM Training Script + +Supports two training modes: +1. Standard (backprop) training - for baselines and comparison +2. Local (PC) training - the proposed globally backprop-free method + +Supports data sources: +- HuggingFace datasets (wikitext, etc.) +- Raw text files +- Synthetic data (for testing) +""" + +import argparse +import json +import math +import os +import time +from pathlib import Path + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + + +# ============================================================================= +# Datasets +# ============================================================================= + +class CharLevelDataset(Dataset): + """Character-level dataset for Stage 1 proof-of-mechanism experiments.""" + + def __init__(self, text: str, seq_len: int, vocab_size: int = 256): + self.seq_len = seq_len + self.vocab_size = vocab_size + # Encode as bytes, offset by 1 (0 = MASK token) + self.data = torch.tensor( + [min(b + 1, vocab_size - 1) for b in text.encode("utf-8")], + dtype=torch.long, + ) + self.n_seqs = max(1, (len(self.data) - seq_len) // seq_len) + + def __len__(self): + return self.n_seqs + + def __getitem__(self, idx): + start = idx * self.seq_len + end = start + self.seq_len + return {"input_ids": self.data[start:end]} + + +def load_wikitext(seq_len: int, vocab_size: int = 257, split: str = "train"): + """Load WikiText-103 from HuggingFace.""" + from datasets import load_dataset + + print(f"Loading WikiText-103 ({split})...") + ds = load_dataset("wikitext", "wikitext-103-raw-v1", split=split) + + # Concatenate all text + text = "\n".join([row["text"] for row in ds if row["text"].strip()]) + print(f" {len(text):,} characters loaded") + + return CharLevelDataset(text, seq_len, vocab_size) + + +def load_text_file(path: str, seq_len: int, vocab_size: int = 257, max_chars: int = 0): + """Load from a raw text file. + + Args: + max_chars: limit characters loaded (0 = all). Use for large files. + """ + with open(path, "r", errors="replace") as f: + if max_chars > 0: + text = f.read(max_chars) + else: + text = f.read() + print(f"Loaded {len(text):,} characters from {path}") + return CharLevelDataset(text, seq_len, vocab_size) + + +# ============================================================================= +# Training Loop +# ============================================================================= + +class Trainer: + """Trainer supporting both standard backprop and local PC training. + + Tracks all metrics recommended by the paper's diagnostics section: + - Loss (masked token NLL) + - Energy trace (per-step latent energy) + - Stationarity residual (envelope theorem validation) + - Energy monotonicity (Lyapunov check) + """ + + def __init__( + self, + model: PCSHODLM, + train_dataset: Dataset, + val_dataset: Dataset = None, + training_mode: str = "local", + lr: float = 1e-4, + batch_size: int = 16, + max_steps: int = 10000, + log_interval: int = 50, + eval_interval: int = 500, + save_interval: int = 2000, + save_dir: str = "checkpoints", + device: str = "cpu", + grad_clip: float = 1.0, + ): + self.model = model.to(device) + self.device = device + self.training_mode = training_mode + self.max_steps = max_steps + self.log_interval = log_interval + self.eval_interval = eval_interval + self.save_interval = save_interval + self.save_dir = Path(save_dir) + self.save_dir.mkdir(parents=True, exist_ok=True) + self.grad_clip = grad_clip + + self.train_loader = DataLoader( + train_dataset, batch_size=batch_size, shuffle=True, + drop_last=True, num_workers=0, + ) + self.val_loader = ( + DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=0) + if val_dataset + else None + ) + + if training_mode == "local": + self.updater = LocalParameterUpdater( + model, + lr_forward=lr, + lr_feedback=lr, + lr_readout=lr, + lr_precision=lr * 0.1, + ) + elif training_mode == "unified": + # Unified mode: no separate optimizer needed + # Parameters are updated inside unified_settle() + # Must be small (two-timescale: fast settling, slow learning) + self.param_lr_scale = 0.005 + else: + self.optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01) + self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + self.optimizer, T_max=max_steps, eta_min=lr * 0.1 + ) + + # Logging + self.log = { + "step": [], + "loss": [], + "energy_initial": [], + "energy_final": [], + "stationarity_residual": [], + "wall_time": [], + "val_loss": [], + "tokens_per_sec": [], + } + self.running_loss = 0.0 + self.running_energy_init = 0.0 + self.running_energy_final = 0.0 + self.running_stationarity = 0.0 + self.running_count = 0 + + def train_step_backprop(self, batch): + """Standard end-to-end backprop training step.""" + self.optimizer.zero_grad() + x_0 = batch["input_ids"].to(self.device) + output = self.model(x_0) + loss = output["loss"] + loss.backward() + torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.grad_clip) + self.optimizer.step() + self.scheduler.step() + return { + "loss": loss.item(), + "energies": output["energies"], + "stationarity": output.get("stationarity_residual", 0.0), + } + + def train_step_local(self, batch): + """Local predictive-coding training step (globally backprop-free).""" + batch = {k: v.to(self.device) for k, v in batch.items()} + result = self.updater.step(batch) + return result + + def train_step_unified(self, batch): + """Unified training: settling and learning happen simultaneously. + + Every settling microstep updates both hidden states AND parameters. + This is the PC-native mode where inference IS learning. + """ + model = self.model + x_0 = batch["input_ids"].to(self.device) + B, S = x_0.shape + + t = torch.randint(1, model.config.n_diffusion_steps + 1, (B,), device=self.device) + x_t, mask = model.schedule.corrupt(x_0, t, model.config.mask_token_id) + + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + # Unified settle: updates params inside each microstep + h_settled, v_final, energies = model.unified_settle( + h_init, x_0, mask, t, + param_lr_scale=self.param_lr_scale, + ) + + # Compute loss for monitoring + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_settled[-1])) + mask_logits = logits[mask] + mask_targets = x_0[mask] + if mask_logits.numel() > 0: + loss = F.cross_entropy(mask_logits, mask_targets).item() + else: + loss = 0.0 + + return { + "loss": loss, + "energies": energies, + "stationarity": 0.0, + } + + @torch.no_grad() + def evaluate(self): + """Evaluate on validation set.""" + if self.val_loader is None: + return None + + self.model.eval() + total_loss = 0.0 + total_tokens = 0 + + for batch in self.val_loader: + x_0 = batch["input_ids"].to(self.device) + output = self.model(x_0) + n_masked = output["mask"].sum().item() + if n_masked > 0: + total_loss += output["loss"].item() * n_masked + total_tokens += n_masked + + self.model.train() + return total_loss / max(1, total_tokens) + + def train(self): + """Main training loop.""" + self.model.train() + step = 0 + start_time = time.time() + epoch = 0 + tokens_processed = 0 + + print(f"{'='*60}") + print(f"PC-SHO-DLM Training ({self.training_mode} mode)") + print(f"{'='*60}") + print(f"Parameters: {count_parameters(self.model):,}") + print(f"Device: {self.device}") + print(f"Max steps: {self.max_steps}") + print(f"Settling steps (K): {self.model.config.n_settling_steps}") + print(f"Diffusion steps (T): {self.model.config.n_diffusion_steps}") + print(f"{'='*60}") + + while step < self.max_steps: + epoch += 1 + for batch in self.train_loader: + if step >= self.max_steps: + break + + batch_tokens = batch["input_ids"].numel() + + # CURRICULUM OVER K: ramp settling steps, minimum K=3 + K_max = self.model.config.n_settling_steps + K_warmup = min(1000, self.max_steps // 5) + K_curr = max(3, int(K_max * min(1.0, step / K_warmup))) + self.model.config.n_settling_steps = K_curr + + if self.training_mode == "backprop": + result = self.train_step_backprop(batch) + elif self.training_mode == "unified": + result = self.train_step_unified(batch) + else: + result = self.train_step_local(batch) + + step += 1 + tokens_processed += batch_tokens + + # Accumulate metrics + loss_val = result.get("loss", 0.0) + energies = result.get("energies", []) + stationarity = result.get("stationarity", 0.0) + if isinstance(loss_val, (int, float)): + self.running_loss += loss_val + if energies: + self.running_energy_init += energies[0] + self.running_energy_final += energies[-1] + if stationarity: + self.running_stationarity += stationarity + self.running_count += 1 + + # Logging + if step % self.log_interval == 0 and self.running_count > 0: + elapsed = time.time() - start_time + avg_loss = self.running_loss / self.running_count + avg_e_init = self.running_energy_init / self.running_count + avg_e_final = self.running_energy_final / self.running_count + avg_stat = self.running_stationarity / self.running_count + tps = tokens_processed / max(elapsed, 1e-6) + energy_reduction = (1 - avg_e_final / max(avg_e_init, 1e-6)) * 100 + + print( + f"Step {step:6d} | " + f"Loss: {avg_loss:.4f} | " + f"Energy: {avg_e_final:.0f} ({energy_reduction:+.1f}%) | " + f"Stat: {avg_stat:.1f} | " + f"Tok/s: {tps:.0f} | " + f"Time: {elapsed:.0f}s" + ) + + self.log["step"].append(step) + self.log["loss"].append(avg_loss) + self.log["energy_initial"].append(avg_e_init) + self.log["energy_final"].append(avg_e_final) + self.log["stationarity_residual"].append(avg_stat) + self.log["wall_time"].append(elapsed) + self.log["tokens_per_sec"].append(tps) + + # Reset running averages + self.running_loss = 0.0 + self.running_energy_init = 0.0 + self.running_energy_final = 0.0 + self.running_stationarity = 0.0 + self.running_count = 0 + + # Evaluation + if step % self.eval_interval == 0: + val_loss = self.evaluate() + if val_loss is not None: + print(f" --> Val loss: {val_loss:.4f}") + self.log["val_loss"].append((step, val_loss)) + + # Save + if step % self.save_interval == 0: + self.save_checkpoint(step) + + # Final save + self.save_checkpoint(step, final=True) + self.save_log() + + elapsed = time.time() - start_time + print(f"{'='*60}") + print(f"Training complete. {step} steps in {elapsed:.0f}s") + print(f"Final avg loss: {self.log['loss'][-1]:.4f}" if self.log['loss'] else "") + print(f"{'='*60}") + + def save_checkpoint(self, step, final=False): + name = "final" if final else f"step_{step}" + path = self.save_dir / f"checkpoint_{name}.pt" + torch.save( + { + "step": step, + "model_state_dict": self.model.state_dict(), + "config": self.model.config, + "training_mode": self.training_mode, + }, + path, + ) + + def save_log(self): + path = self.save_dir / "training_log.json" + with open(path, "w") as f: + json.dump(self.log, f, indent=2) + + +# ============================================================================= +# Main +# ============================================================================= + +def main(): + parser = argparse.ArgumentParser(description="Train PC-SHO-DLM") + parser.add_argument("--mode", choices=["local", "backprop", "unified"], default="local", + help="Training mode: 'local' (PC), 'backprop' (baseline), or 'unified' (settling=learning)") + parser.add_argument("--data", type=str, default="wikitext", + help="Data source: 'wikitext', 'synthetic', or path to text file") + parser.add_argument("--d_model", type=int, default=256) + parser.add_argument("--n_layers", type=int, default=6) + parser.add_argument("--n_heads", type=int, default=8) + parser.add_argument("--seq_len", type=int, default=256) + parser.add_argument("--batch_size", type=int, default=16) + parser.add_argument("--lr", type=float, default=3e-4) + parser.add_argument("--max_steps", type=int, default=10000) + parser.add_argument("--n_settling", type=int, default=6) + parser.add_argument("--n_diffusion", type=int, default=100) + parser.add_argument("--save_dir", type=str, default="checkpoints") + parser.add_argument("--device", type=str, default="auto") + parser.add_argument("--log_interval", type=int, default=50) + parser.add_argument("--eval_interval", type=int, default=500) + args = parser.parse_args() + + # Auto-detect device + if args.device == "auto": + if torch.cuda.is_available(): + args.device = "cuda" + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + args.device = "mps" + else: + args.device = "cpu" + + # Config + config = PCSHOConfig( + vocab_size=257, # 256 bytes + 1 MASK token + max_seq_len=args.seq_len, + d_model=args.d_model, + n_heads=args.n_heads, + n_layers=args.n_layers, + d_ff=args.d_model * 4, + n_diffusion_steps=args.n_diffusion, + n_settling_steps=args.n_settling, + mask_token_id=0, + dropout=0.1, + ) + + # Data + wikitext_dir = os.path.join(os.path.dirname(__file__), "..", "data", "wikitext-103") + if args.data == "wikitext" and os.path.isdir(wikitext_dir): + # Use local wikitext-103 files (first 50M chars for train to fit memory) + train_dataset = load_text_file( + os.path.join(wikitext_dir, "wiki.train.tokens"), + args.seq_len, config.vocab_size, max_chars=50_000_000 + ) + val_dataset = load_text_file( + os.path.join(wikitext_dir, "wiki.valid.tokens"), + args.seq_len, config.vocab_size + ) + elif args.data == "wikitext": + train_dataset = load_wikitext(args.seq_len, config.vocab_size, split="train") + val_dataset = load_wikitext(args.seq_len, config.vocab_size, split="validation") + elif args.data == "synthetic": + print("Using synthetic data for testing.") + text = "The quick brown fox jumps over the lazy dog. " * 5000 + full = CharLevelDataset(text, args.seq_len, config.vocab_size) + n_val = max(1, len(full) // 10) + train_dataset, val_dataset = torch.utils.data.random_split( + full, [len(full) - n_val, n_val] + ) + elif os.path.exists(args.data): + full = load_text_file(args.data, args.seq_len, config.vocab_size) + n_val = max(1, len(full) // 10) + train_dataset, val_dataset = torch.utils.data.random_split( + full, [len(full) - n_val, n_val] + ) + else: + raise ValueError(f"Unknown data source: {args.data}") + + # Model + model = PCSHODLM(config) + print(f"\nModel: PC-SHO-DLM ({args.mode} training)") + print(f"Parameters: {count_parameters(model):,}") + print(f"Architecture: d={config.d_model}, L={config.n_layers}, heads={config.n_heads}") + print(f"Settling: K={config.n_settling_steps}, T={config.n_diffusion_steps}") + print(f"Sequence length: {config.max_seq_len}") + print(f"Train samples: {len(train_dataset):,}") + + # Train + trainer = Trainer( + model=model, + train_dataset=train_dataset, + val_dataset=val_dataset, + training_mode=args.mode, + lr=args.lr, + batch_size=args.batch_size, + max_steps=args.max_steps, + log_interval=args.log_interval, + eval_interval=args.eval_interval, + save_dir=args.save_dir, + device=args.device, + ) + trainer.train() + + +if __name__ == "__main__": + main() diff --git a/train_chat.py b/train_chat.py new file mode 100644 index 0000000000000000000000000000000000000000..5c084d74dfbf680b3ee2109566d84f697a4974b2 --- /dev/null +++ b/train_chat.py @@ -0,0 +1,325 @@ +""" +PC-SHO-DLM Chat Training — Conditional Masked Diffusion + +Trains the model to generate responses conditioned on prompts. +Prompt stays unmasked, response gets masked/denoised via PC settling. +""" + +import argparse, json, os, sys, time +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src")) +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + + +class DialogueDataset(Dataset): + """Byte-level dialogue dataset. Each sample = (prompt, response) pair. + + Returns input_ids (full sequence) + prompt_len (where response starts). + During training, only the response portion gets masked. + """ + + def __init__(self, pairs: list, max_seq_len: int, vocab_size: int = 257): + self.max_seq_len = max_seq_len + self.vocab_size = vocab_size + self.samples = [] + + sep = [0x0A, 0x0A] # double newline as separator + + for prompt, response in pairs: + p_bytes = [min(b + 1, vocab_size - 1) for b in prompt.encode("utf-8")] + r_bytes = [min(b + 1, vocab_size - 1) for b in response.encode("utf-8")] + s_bytes = [min(b + 1, vocab_size - 1) for b in bytes(sep)] + + # Truncate: prompt gets up to 40% of seq_len, response gets the rest + max_p = int(max_seq_len * 0.4) + max_r = max_seq_len - min(len(p_bytes), max_p) - len(s_bytes) + + p = p_bytes[:max_p] + r = r_bytes[:max_r] + + full = p + s_bytes + r + prompt_len = len(p) + len(s_bytes) + + # Pad + if len(full) < max_seq_len: + full = full + [0] * (max_seq_len - len(full)) # 0 = MASK token as pad + full = full[:max_seq_len] + + self.samples.append({ + "input_ids": torch.tensor(full, dtype=torch.long), + "prompt_len": prompt_len, + "response_len": len(r), + }) + + def __len__(self): + return len(self.samples) + + def __getitem__(self, idx): + return self.samples[idx] + + +def load_dialogue_data(name="alpaca", max_samples=None): + """Load dialogue pairs from HuggingFace.""" + from datasets import load_dataset + + pairs = [] + + if name == "alpaca": + print("Loading Alpaca dataset...") + try: + ds = load_dataset("tatsu-lab/alpaca", split="train") + for row in ds: + instruction = row.get("instruction", "") + inp = row.get("input", "") + output = row.get("output", "") + prompt = f"{instruction}\n{inp}".strip() if inp else instruction + if prompt and output: + pairs.append((prompt, output)) + if max_samples and len(pairs) >= max_samples: + break + except Exception as e: + print(f"HF load failed ({e}), downloading JSON directly...") + import urllib.request, json as json_mod + url = "https://raw.githubusercontent.com/tatsu-lab/stanford_alpaca/main/alpaca_data.json" + with urllib.request.urlopen(url) as r: + data = json_mod.loads(r.read()) + for row in data: + instruction = row.get("instruction", "") + inp = row.get("input", "") + output = row.get("output", "") + prompt = f"{instruction}\n{inp}".strip() if inp else instruction + if prompt and output: + pairs.append((prompt, output)) + if max_samples and len(pairs) >= max_samples: + break + + elif name == "dolly": + print("Loading Dolly dataset...") + ds = load_dataset("databricks/dolly-15k", split="train") + for row in ds: + prompt = row.get("instruction", "") or row.get("context", "") + response = row.get("response", "") + if prompt and response: + pairs.append((prompt, response)) + if max_samples and len(pairs) >= max_samples: + break + + elif name == "oasst": + print("Loading OpenAssistant dataset...") + ds = load_dataset("OpenAssistant/oasst1", split="train") + # Flatten conversation trees into (parent, reply) pairs + messages = {row["message_id"]: row for row in ds} + for row in ds: + if row["parent_id"] and row["parent_id"] in messages: + parent = messages[row["parent_id"]] + pairs.append((parent["text"], row["text"])) + if max_samples and len(pairs) >= max_samples: + break + + else: + raise ValueError(f"Unknown dataset: {name}") + + print(f"Loaded {len(pairs)} dialogue pairs") + return pairs + + +def conditional_corrupt(x_0, t, mask_token_id, schedule, prompt_lens): + """Mask only response tokens, keep prompt unmasked.""" + B, S = x_0.shape + mask_prob = schedule.mask_rate(t).unsqueeze(-1) # (B, 1) + random_mask = torch.rand_like(x_0.float()) < mask_prob # (B, S) + + # Only mask response positions + response_mask = torch.zeros_like(x_0, dtype=torch.bool) + for b in range(B): + response_mask[b, prompt_lens[b]:] = True + + mask = random_mask & response_mask + x_t = x_0.clone() + x_t[mask] = mask_token_id + return x_t, mask + + +def train(): + parser = argparse.ArgumentParser() + parser.add_argument("--data", default="alpaca", choices=["alpaca", "dolly", "oasst"]) + parser.add_argument("--max_samples", type=int, default=None) + parser.add_argument("--d_model", type=int, default=256) + parser.add_argument("--n_layers", type=int, default=6) + parser.add_argument("--n_heads", type=int, default=8) + parser.add_argument("--seq_len", type=int, default=512) + parser.add_argument("--batch_size", type=int, default=8) + parser.add_argument("--lr", type=float, default=3e-4) + parser.add_argument("--max_steps", type=int, default=5000) + parser.add_argument("--device", type=str, default="auto") + parser.add_argument("--save_dir", type=str, default="checkpoints/chat") + parser.add_argument("--checkpoint", type=str, default=None, help="Fine-tune from existing checkpoint") + args = parser.parse_args() + + if args.device == "auto": + if torch.cuda.is_available(): args.device = "cuda" + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): args.device = "mps" + else: args.device = "cpu" + + # Config + config = PCSHOConfig( + vocab_size=257, max_seq_len=args.seq_len, + d_model=args.d_model, n_heads=args.n_heads, n_layers=args.n_layers, + d_ff=args.d_model * 4, n_diffusion_steps=64, n_settling_steps=6, + mask_token_id=0, dropout=0.1, feedback_rank=args.d_model // 4, + denoising_lambda=500.0, + homeostatic_target=0.0, lateral_inhibition=0.0, + ) + + # Load data + pairs = load_dialogue_data(args.data, args.max_samples) + n_val = max(1, len(pairs) // 10) + train_pairs = pairs[n_val:] + val_pairs = pairs[:n_val] + + train_ds = DialogueDataset(train_pairs, config.max_seq_len) + val_ds = DialogueDataset(val_pairs, config.max_seq_len) + + print(f"Train: {len(train_ds)}, Val: {len(val_ds)}") + + # Model + model = PCSHODLM(config).to(args.device) + + if args.checkpoint: + print(f"Loading checkpoint: {args.checkpoint}") + ckpt = torch.load(args.checkpoint, map_location=args.device, weights_only=False) + model.load_state_dict(ckpt["model_state_dict"], strict=False) + + model.train() + n_params = count_parameters(model) + print(f"Model: {n_params:,} params on {args.device}") + + # Training + updater = LocalParameterUpdater(model, lr_forward=args.lr, lr_feedback=args.lr, + lr_readout=args.lr, lr_precision=args.lr * 0.1) + + train_loader = DataLoader(train_ds, batch_size=args.batch_size, shuffle=True, drop_last=True) + val_loader = DataLoader(val_ds, batch_size=args.batch_size) + + os.makedirs(args.save_dir, exist_ok=True) + step = 0 + start = time.time() + K_max = config.n_settling_steps + + print(f"\n{'='*60}") + print(f"Chat Training | {n_params:,} params | {args.data} | {len(train_ds)} samples") + print(f"{'='*60}\n") + + while step < args.max_steps: + for batch in train_loader: + if step >= args.max_steps: + break + + x_0 = batch["input_ids"].to(args.device) + prompt_lens = batch["prompt_len"] + B, S = x_0.shape + + # Curriculum K + K_curr = max(3, int(K_max * min(1.0, step / 1000))) + model.config.n_settling_steps = K_curr + + # Sample timestep + t = torch.randint(1, config.n_diffusion_steps + 1, (B,), device=args.device) + + # Conditional corruption — only mask response + x_t, mask = conditional_corrupt(x_0, t, config.mask_token_id, model.schedule, prompt_lens) + + # HONEST SETTLE: use x_t (corrupted), NOT x_0 (answer) + # Settling minimizes entropy (push toward confident predictions) + # without peeking at the ground truth + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + + with torch.no_grad(): + h_settled, _, energies, _, _ = model.settle(h_init, x_t, mask, t) + + # Local updates (same as LocalParameterUpdater but with our custom mask) + L = config.n_layers + for l in range(L): + h_below = h_settled[l].detach() + h_current = h_settled[l + 1].detach() + updater.forward_optimizers[l].zero_grad() + mu_up = model.forward_blocks[l](h_below) + with torch.no_grad(): + tok_p, ch_p = model.precision_up[l](h_current, t) + eps = h_current - mu_up + loss_l = 0.5 * (eps * tok_p * ch_p * eps).sum() / B + loss_l.backward() + updater.forward_optimizers[l].step() + + for l in range(L - 1): + updater.feedback_optimizers[l].zero_grad() + h_above = h_settled[l + 2].detach() + h_current = h_settled[l + 1].detach() + mu_down = model.feedback_blocks[l](h_above) + with torch.no_grad(): + tok_p, ch_p = model.precision_down[l](h_current, t) + eps = h_current - mu_down + loss_l = 0.5 * (eps * tok_p * ch_p * eps).sum() / B + loss_l.backward() + updater.feedback_optimizers[l].step() + + # Readout + updater.readout_optimizer.zero_grad() + logits = model.readout(model.readout_norm(h_settled[L].detach())) + mask_logits = logits[mask] + mask_targets = x_0[mask] + if mask_logits.numel() > 0: + readout_loss = F.cross_entropy(mask_logits, mask_targets) + readout_loss.backward() + updater.readout_optimizer.step() + loss_val = readout_loss.item() + else: + loss_val = 0.0 + + # Embeddings + updater.embed_optimizer.zero_grad() + with torch.enable_grad(): + h_0_fresh = model.embed_input(x_t, t) + h_init_fresh = model.amortized_forward_pass(h_0_fresh) + logits_e = model.readout(model.readout_norm(h_init_fresh[L])) + ml_e, mt_e = logits_e[mask], x_0[mask] + if ml_e.numel() > 0: + embed_loss = F.cross_entropy(ml_e, mt_e) + embed_loss.backward() + torch.nn.utils.clip_grad_norm_( + list(model.token_embed.parameters()) + list(model.pos_embed.parameters()) + list(model.time_embed.parameters()), 1.0 + ) + updater.embed_optimizer.step() + + step += 1 + + if step % 50 == 0: + el = time.time() - start + e = f"{energies[-1]:.0f}" if energies else "N/A" + print(f"Step {step:5d} | Loss: {loss_val:.4f} | Energy: {e} | K={K_curr} | {el:.0f}s") + + if step % 500 == 0: + torch.save({ + "model_state_dict": model.state_dict(), + "config": config, + "step": step, + }, os.path.join(args.save_dir, f"chat_step{step}.pt")) + + # Final save + torch.save({ + "model_state_dict": model.state_dict(), + "config": config, + "step": step, + }, os.path.join(args.save_dir, "chat_final.pt")) + + print(f"\nDone! {step} steps in {time.time()-start:.0f}s") + print(f"Checkpoint: {args.save_dir}/chat_final.pt") + print(f"Run: python3 chat.py --checkpoint {args.save_dir}/chat_final.pt") + + +if __name__ == "__main__": + train() diff --git a/train_gpu.py b/train_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..18babaebb01340de877436c96a4fe17ded1aa3ea --- /dev/null +++ b/train_gpu.py @@ -0,0 +1,262 @@ +""" +PC-SHO-DLM GPU Training Script (A100 optimized) + +Trains a scaled-up PC-SHO-DLM on WikiText-103 using CUDA. +Designed for HuggingFace Spaces with A100 (80GB) GPU. + +Runs all 3 training modes sequentially and saves results. +""" + +import json +import os +import sys +import time + +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +sys.path.insert(0, "/app/src") +from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters + + +# ============================================================================= +# Dataset +# ============================================================================= + +class CharLevelDataset(Dataset): + def __init__(self, text: str, seq_len: int, vocab_size: int = 257): + self.seq_len = seq_len + self.data = torch.tensor( + [min(b + 1, vocab_size - 1) for b in text.encode("utf-8")], + dtype=torch.long, + ) + self.n_seqs = max(1, (len(self.data) - seq_len) // seq_len) + + def __len__(self): + return self.n_seqs + + def __getitem__(self, idx): + start = idx * self.seq_len + return {"input_ids": self.data[start : start + self.seq_len]} + + +def load_data(seq_len=512, max_chars=100_000_000): + """Load WikiText-103 from HuggingFace.""" + from datasets import load_dataset + + print("Loading WikiText-103...") + ds_train = load_dataset("wikitext", "wikitext-103-raw-v1", split="train") + ds_val = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation") + + train_text = "\n".join([r["text"] for r in ds_train if r["text"].strip()])[:max_chars] + val_text = "\n".join([r["text"] for r in ds_val if r["text"].strip()]) + + print(f"Train: {len(train_text):,} chars, Val: {len(val_text):,} chars") + return CharLevelDataset(train_text, seq_len), CharLevelDataset(val_text, seq_len) + + +# ============================================================================= +# Training +# ============================================================================= + +def train_model(model, train_ds, val_ds, mode, config, max_steps=10000, batch_size=64, lr=3e-4): + device = "cuda" + model = model.to(device) + model.train() + + train_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=4, pin_memory=True) + val_loader = DataLoader(val_ds, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=True) + + if mode == "backprop": + optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_steps, eta_min=lr * 0.1) + elif mode == "local": + updater = LocalParameterUpdater(model, lr_forward=lr, lr_feedback=lr, lr_readout=lr, lr_precision=lr * 0.1) + elif mode == "unified": + param_lr_scale = 0.005 + + log = {"step": [], "loss": [], "energy": [], "val_loss": [], "wall_time": []} + step = 0 + start = time.time() + + print(f"\n{'='*70}") + print(f"Training PC-SHO-DLM | Mode: {mode} | Params: {count_parameters(model):,}") + print(f"Device: {torch.cuda.get_device_name()} | Batch: {batch_size} | Steps: {max_steps}") + print(f"{'='*70}") + + while step < max_steps: + for batch in train_loader: + if step >= max_steps: + break + + x_0 = batch["input_ids"].to(device) + + if mode == "backprop": + optimizer.zero_grad() + output = model(x_0) + loss = output["loss"] + loss.backward() + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + optimizer.step() + scheduler.step() + loss_val = loss.item() + energies = output["energies"] + + elif mode == "local": + batch_d = {"input_ids": x_0} + result = updater.step(batch_d) + loss_val = result.get("loss", 0.0) + energies = result.get("energies", []) + + elif mode == "unified": + B, S = x_0.shape + t = torch.randint(1, config.n_diffusion_steps + 1, (B,), device=device) + x_t, mask = model.schedule.corrupt(x_0, t, config.mask_token_id) + h_0 = model.embed_input(x_t, t) + h_init = model.amortized_forward_pass(h_0) + h_settled, _, energies = model.unified_settle(h_init, x_0, mask, t, param_lr_scale=param_lr_scale) + with torch.no_grad(): + logits = model.readout(model.readout_norm(h_settled[-1])) + ml, mt = logits[mask], x_0[mask] + loss_val = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0.0 + + step += 1 + + if step % 100 == 0: + elapsed = time.time() - start + energy_str = f"{energies[-1]:.0f}" if energies else "N/A" + tps = (step * batch_size * config.max_seq_len) / elapsed + print(f"Step {step:6d} | Loss: {loss_val:.4f} | Energy: {energy_str} | Tok/s: {tps:.0f} | Time: {elapsed:.0f}s") + log["step"].append(step) + log["loss"].append(loss_val) + log["energy"].append(energies[-1] if energies else 0) + log["wall_time"].append(elapsed) + + if step % 2000 == 0: + # Validation + model.eval() + total_loss, total_tok = 0.0, 0 + with torch.no_grad(): + for vb in val_loader: + vx = vb["input_ids"].to(device) + vo = model(vx) + nm = vo["mask"].sum().item() + if nm > 0: + total_loss += vo["loss"].item() * nm + total_tok += nm + if total_tok > 100000: + break + val_loss = total_loss / max(1, total_tok) + print(f" --> Val loss: {val_loss:.4f}") + log["val_loss"].append((step, val_loss)) + model.train() + + elapsed = time.time() - start + print(f"Done. {step} steps in {elapsed:.0f}s ({step*batch_size*config.max_seq_len/elapsed:.0f} tok/s)") + + # Final validation + model.eval() + total_loss, total_tok = 0.0, 0 + with torch.no_grad(): + for vb in val_loader: + vx = vb["input_ids"].to(device) + vo = model(vx) + nm = vo["mask"].sum().item() + if nm > 0: + total_loss += vo["loss"].item() * nm + total_tok += nm + if total_tok > 200000: + break + final_val = total_loss / max(1, total_tok) + print(f"Final val loss: {final_val:.4f}") + log["final_val_loss"] = final_val + + return model, log + + +# ============================================================================= +# Main +# ============================================================================= + +def main(): + torch.backends.cudnn.benchmark = True + + # A100-optimized config: bigger model, bigger batch, longer sequences + config = PCSHOConfig( + vocab_size=257, + max_seq_len=512, + d_model=512, + n_heads=8, + n_layers=12, + d_ff=2048, + n_diffusion_steps=128, + n_settling_steps=6, + mask_token_id=0, + dropout=0.1, + feedback_rank=128, + ) + + # Load data + train_ds, val_ds = load_data(seq_len=config.max_seq_len, max_chars=100_000_000) + + results = {} + save_dir = "/app/results" + os.makedirs(save_dir, exist_ok=True) + + # 1. Backprop baseline + print("\n" + "=" * 70) + print("PHASE 1: Backprop Baseline") + print("=" * 70) + model_bp = PCSHODLM(config) + model_bp, log_bp = train_model(model_bp, train_ds, val_ds, "backprop", config, max_steps=10000, batch_size=64, lr=3e-4) + results["backprop"] = log_bp + torch.save({"model": model_bp.state_dict(), "config": config, "log": log_bp}, f"{save_dir}/backprop_10k.pt") + + # 2. Local PC + print("\n" + "=" * 70) + print("PHASE 2: Local PC (globally backprop-free)") + print("=" * 70) + model_pc = PCSHODLM(config) + model_pc, log_pc = train_model(model_pc, train_ds, val_ds, "local", config, max_steps=10000, batch_size=64, lr=3e-4) + results["local_pc"] = log_pc + torch.save({"model": model_pc.state_dict(), "config": config, "log": log_pc}, f"{save_dir}/local_pc_10k.pt") + + # 3. Unified (settling=learning) + print("\n" + "=" * 70) + print("PHASE 3: Unified (settling = learning)") + print("=" * 70) + model_uni = PCSHODLM(config) + model_uni, log_uni = train_model(model_uni, train_ds, val_ds, "unified", config, max_steps=10000, batch_size=64, lr=3e-4) + results["unified"] = log_uni + torch.save({"model": model_uni.state_dict(), "config": config, "log": log_uni}, f"{save_dir}/unified_10k.pt") + + # Save combined results + with open(f"{save_dir}/results.json", "w") as f: + json.dump(results, f, indent=2) + + # Print final comparison + print("\n" + "=" * 70) + print("FINAL RESULTS") + print("=" * 70) + for mode, log in results.items(): + final_loss = log.get("final_val_loss", log["loss"][-1] if log["loss"] else "N/A") + print(f"{mode:15s} | Final val loss: {final_loss}") + + # Push results to HF + try: + from huggingface_hub import HfApi + api = HfApi() + api.upload_folder( + folder_path=save_dir, + repo_id="zotowata/pc-sho-dlm-train", + repo_type="space", + path_in_repo="results", + ) + print("\nResults uploaded to HuggingFace!") + except Exception as e: + print(f"Upload failed: {e}") + + +if __name__ == "__main__": + main()