Zae commited on
Commit ·
c2d8a57
1
Parent(s): 24af195
PC-SHO-DLM: full architecture with MSA integration
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Dockerfile +11 -0
- README.md +107 -0
- app.py +265 -0
- app_backprop_wiki.py +120 -0
- app_chat_a100.py +192 -0
- app_fair_backprop.py +234 -0
- app_local.py +120 -0
- app_local_pc_wiki.py +115 -0
- app_mdlm_baseline.py +90 -0
- app_optimized.py +248 -0
- app_unified.py +130 -0
- app_unified_big.py +152 -0
- app_unified_wiki.py +121 -0
- app_v2_backprop.py +118 -0
- app_v2_unified.py +133 -0
- app_v2_unified_large.py +223 -0
- app_zerogpu.py +117 -0
- architecture_diagram.md +338 -0
- chat.py +231 -0
- checkpoints/backprop_1k/checkpoint_final.pt +3 -0
- checkpoints/backprop_1k/training_log.json +96 -0
- checkpoints/chat/chat_final.pt +3 -0
- checkpoints/chat/chat_step1000.pt +3 -0
- checkpoints/chat/chat_step1500.pt +3 -0
- checkpoints/chat/chat_step2000.pt +3 -0
- checkpoints/chat/chat_step500.pt +3 -0
- checkpoints/checkpoint_final.pt +3 -0
- checkpoints/local_pc_1k/checkpoint_final.pt +3 -0
- checkpoints/local_pc_1k/training_log.json +96 -0
- checkpoints/local_pc_wiki_lambda_fixed/checkpoint_final.pt +3 -0
- checkpoints/local_pc_wiki_lambda_fixed/checkpoint_step_2000.pt +3 -0
- checkpoints/local_pc_wiki_lambda_fixed/training_log.json +462 -0
- checkpoints/training_log.json +45 -0
- checkpoints/unified_wiki_lambda_fixed/checkpoint_step_2000.pt +3 -0
- data/ao3-metadata/fandoms.csv +3 -0
- data/ao3-metadata/random works - Oct 2024 - tag binary - 200.csv +3 -0
- data/ao3-metadata/random works - Oct 2024 - tag binary.csv +3 -0
- data/ao3-metadata/random works - Oct 2025 - fix indecies.csv +3 -0
- data/ao3-metadata/random works - Oct 2025 - top tags - 200.csv +3 -0
- data/ao3-metadata/random works - Oct 2025 - top tags.csv +3 -0
- data/ao3-metadata/random works - Oct 2025.csv +3 -0
- data/python_code.txt +3 -0
- data/tinystories_val.txt +3 -0
- data/wikitext-103/LICENSE.txt +3 -0
- data/wikitext-103/README.txt +3 -0
- data/wikitext-103/wiki.test.tokens +3 -0
- data/wikitext-103/wiki.train.tokens +3 -0
- data/wikitext-103/wiki.valid.tokens +3 -0
- diagnostics_output/diagnostics.json +130 -0
- experiments/ablation_runner.py +290 -0
Dockerfile
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM nvcr.io/nvidia/pytorch:24.01-py3
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
RUN pip install --no-cache-dir datasets huggingface_hub
|
| 6 |
+
|
| 7 |
+
COPY src/ /app/src/
|
| 8 |
+
COPY experiments/ /app/experiments/
|
| 9 |
+
COPY train_gpu.py /app/train_gpu.py
|
| 10 |
+
|
| 11 |
+
CMD ["python", "train_gpu.py"]
|
README.md
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PC-SHO-DLM
|
| 2 |
+
|
| 3 |
+
**Predictive-Coding Diffusion Language Models with Precision-Conditioned Second-Order Settling**
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
PC-SHO-DLM is a research architecture that unifies three individually mature research threads:
|
| 8 |
+
|
| 9 |
+
1. **Masked discrete diffusion** for iterative text denoising
|
| 10 |
+
2. **Predictive coding** for local error-driven inference and learning
|
| 11 |
+
3. **Second-order dynamical systems** for accelerated latent settling
|
| 12 |
+
|
| 13 |
+
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.
|
| 14 |
+
|
| 15 |
+
## Key Contributions
|
| 16 |
+
|
| 17 |
+
- **Bidirectional predictive transformer** with both bottom-up and top-down pathways
|
| 18 |
+
- **Precision-conditioned second-order settling** (damped inertial dynamics with learned uncertainty)
|
| 19 |
+
- **State continuation across diffusion steps** (warm-start from previous denoising step)
|
| 20 |
+
- **Tokenwise adaptive settling** (selective compute allocation to uncertain tokens)
|
| 21 |
+
- **Globally backpropagation-free training** via local prediction-error-driven updates
|
| 22 |
+
|
| 23 |
+
## Theoretical Results
|
| 24 |
+
|
| 25 |
+
| Theorem | Result |
|
| 26 |
+
|---------|--------|
|
| 27 |
+
| **A: Reduced-objective exactness** | Local post-settling updates = exact gradients via envelope theorem |
|
| 28 |
+
| **B: Accelerated settling** | O(sqrt(kappa)) vs O(kappa) microsteps over first-order PC |
|
| 29 |
+
| **C: Warm-start tracking** | Settling cost depends on inter-step drift, not full re-solve |
|
| 30 |
+
| **D: Precision optimality** | GLS-optimal under heteroscedastic prediction errors |
|
| 31 |
+
|
| 32 |
+
## Project Structure
|
| 33 |
+
|
| 34 |
+
```
|
| 35 |
+
pc-sho-dlm/
|
| 36 |
+
├── paper/
|
| 37 |
+
│ ├── main.tex # Full LaTeX manuscript
|
| 38 |
+
│ └── references.bib # Bibliography
|
| 39 |
+
├── src/
|
| 40 |
+
│ ├── model.py # Core PC-SHO-DLM architecture
|
| 41 |
+
│ └── train.py # Training loop (local + backprop modes)
|
| 42 |
+
├── experiments/
|
| 43 |
+
│ ├── ablation_runner.py # Ablation study runner
|
| 44 |
+
│ └── settling_analysis.py # Settling dynamics analysis
|
| 45 |
+
└── README.md
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
## Quick Start
|
| 49 |
+
|
| 50 |
+
### Sanity Check
|
| 51 |
+
```bash
|
| 52 |
+
cd src
|
| 53 |
+
python model.py
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
### Train (Local PC mode)
|
| 57 |
+
```bash
|
| 58 |
+
python src/train.py --mode local --device cpu --max_steps 5000
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
### Train (Backprop baseline)
|
| 62 |
+
```bash
|
| 63 |
+
python src/train.py --mode backprop --device cpu --max_steps 5000
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
### Run Ablations
|
| 67 |
+
```bash
|
| 68 |
+
python experiments/ablation_runner.py --device cpu
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
### Analyze Settling Dynamics
|
| 72 |
+
```bash
|
| 73 |
+
python experiments/settling_analysis.py --device cpu
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
## Experimental Program
|
| 77 |
+
|
| 78 |
+
### Stage 1: Proof of Mechanism (20M-100M params)
|
| 79 |
+
- Character/subword corpora (text8, enwik8, WikiText-103)
|
| 80 |
+
- Establish second-order PC is more compute-efficient than first-order PC
|
| 81 |
+
|
| 82 |
+
### Stage 2: Medium Scale (100M-1B params)
|
| 83 |
+
- Open web corpus subset
|
| 84 |
+
- Compare against backprop-trained masked diffusion
|
| 85 |
+
|
| 86 |
+
### Stage 3: Structured Generation
|
| 87 |
+
- Infilling, editing, code completion
|
| 88 |
+
- Test selective settling and state continuation
|
| 89 |
+
|
| 90 |
+
## Falsification Criteria
|
| 91 |
+
|
| 92 |
+
This proposal should be judged a failure if:
|
| 93 |
+
1. Second-order settling does not reduce required microsteps
|
| 94 |
+
2. Local learning creates an irrecoverable quality gap vs backprop
|
| 95 |
+
3. Precision heads fail to calibrate
|
| 96 |
+
4. Dynamics frequently enter limit cycles
|
| 97 |
+
5. State continuation does not materially reduce compute
|
| 98 |
+
|
| 99 |
+
## Citation
|
| 100 |
+
|
| 101 |
+
```bibtex
|
| 102 |
+
@article{pcshodlm2026,
|
| 103 |
+
title={PC-SHO-DLM: Predictive-Coding Diffusion Language Models
|
| 104 |
+
with Precision-Conditioned Second-Order Settling},
|
| 105 |
+
year={2026}
|
| 106 |
+
}
|
| 107 |
+
```
|
app.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PC-SHO-DLM A100 Training — HuggingFace Spaces
|
| 3 |
+
Runs all 3 training modes and displays results via Gradio.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
import gradio as gr
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch.utils.data import DataLoader, Dataset
|
| 16 |
+
|
| 17 |
+
# Import model
|
| 18 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 19 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# =============================================================================
|
| 23 |
+
# Dataset
|
| 24 |
+
# =============================================================================
|
| 25 |
+
|
| 26 |
+
class CharLevelDataset(Dataset):
|
| 27 |
+
def __init__(self, text, seq_len, vocab_size=257):
|
| 28 |
+
self.seq_len = seq_len
|
| 29 |
+
self.data = torch.tensor(
|
| 30 |
+
[min(b + 1, vocab_size - 1) for b in text.encode("utf-8")], dtype=torch.long
|
| 31 |
+
)
|
| 32 |
+
self.n_seqs = max(1, (len(self.data) - seq_len) // seq_len)
|
| 33 |
+
|
| 34 |
+
def __len__(self):
|
| 35 |
+
return self.n_seqs
|
| 36 |
+
|
| 37 |
+
def __getitem__(self, idx):
|
| 38 |
+
start = idx * self.seq_len
|
| 39 |
+
return {"input_ids": self.data[start : start + self.seq_len]}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# =============================================================================
|
| 43 |
+
# Training
|
| 44 |
+
# =============================================================================
|
| 45 |
+
|
| 46 |
+
TRAINING_LOG = []
|
| 47 |
+
CURRENT_STATUS = "Idle"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def train_one_mode(mode, config, train_ds, val_ds, max_steps=10000, batch_size=64, lr=3e-4):
|
| 51 |
+
global CURRENT_STATUS, TRAINING_LOG
|
| 52 |
+
|
| 53 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 54 |
+
CURRENT_STATUS = f"Training {mode} on {device}..."
|
| 55 |
+
TRAINING_LOG.append(f"\n{'='*60}")
|
| 56 |
+
TRAINING_LOG.append(f"Mode: {mode} | Params: {count_parameters(PCSHODLM(config)):,} | Device: {device}")
|
| 57 |
+
TRAINING_LOG.append(f"{'='*60}")
|
| 58 |
+
|
| 59 |
+
model = PCSHODLM(config).to(device)
|
| 60 |
+
model.train()
|
| 61 |
+
|
| 62 |
+
train_loader = DataLoader(train_ds, batch_size=batch_size, shuffle=True, drop_last=True,
|
| 63 |
+
num_workers=4 if device == "cuda" else 0, pin_memory=device == "cuda")
|
| 64 |
+
val_loader = DataLoader(val_ds, batch_size=batch_size, shuffle=False,
|
| 65 |
+
num_workers=2 if device == "cuda" else 0, pin_memory=device == "cuda")
|
| 66 |
+
|
| 67 |
+
if mode == "backprop":
|
| 68 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
|
| 69 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=max_steps, eta_min=lr * 0.1)
|
| 70 |
+
elif mode == "local":
|
| 71 |
+
updater = LocalParameterUpdater(model, lr_forward=lr, lr_feedback=lr, lr_readout=lr, lr_precision=lr * 0.1)
|
| 72 |
+
|
| 73 |
+
log = {"mode": mode, "steps": [], "losses": [], "energies": [], "val_losses": []}
|
| 74 |
+
step = 0
|
| 75 |
+
start = time.time()
|
| 76 |
+
|
| 77 |
+
while step < max_steps:
|
| 78 |
+
for batch in train_loader:
|
| 79 |
+
if step >= max_steps:
|
| 80 |
+
break
|
| 81 |
+
x_0 = batch["input_ids"].to(device)
|
| 82 |
+
|
| 83 |
+
if mode == "backprop":
|
| 84 |
+
optimizer.zero_grad()
|
| 85 |
+
out = model(x_0)
|
| 86 |
+
loss = out["loss"]
|
| 87 |
+
loss.backward()
|
| 88 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 89 |
+
optimizer.step()
|
| 90 |
+
scheduler.step()
|
| 91 |
+
loss_val = loss.item()
|
| 92 |
+
energies = out["energies"]
|
| 93 |
+
elif mode == "local":
|
| 94 |
+
result = updater.step({"input_ids": x_0})
|
| 95 |
+
loss_val = result.get("loss", 0.0)
|
| 96 |
+
energies = result.get("energies", [])
|
| 97 |
+
elif mode == "unified":
|
| 98 |
+
B, S = x_0.shape
|
| 99 |
+
t = torch.randint(1, config.n_diffusion_steps + 1, (B,), device=device)
|
| 100 |
+
x_t, mask = model.schedule.corrupt(x_0, t, config.mask_token_id)
|
| 101 |
+
h_0 = model.embed_input(x_t, t)
|
| 102 |
+
h_init = model.amortized_forward_pass(h_0)
|
| 103 |
+
h_s, _, energies = model.unified_settle(h_init, x_0, mask, t, param_lr_scale=0.005)
|
| 104 |
+
with torch.no_grad():
|
| 105 |
+
logits = model.readout(model.readout_norm(h_s[-1]))
|
| 106 |
+
ml, mt = logits[mask], x_0[mask]
|
| 107 |
+
loss_val = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0
|
| 108 |
+
|
| 109 |
+
step += 1
|
| 110 |
+
|
| 111 |
+
if step % 200 == 0:
|
| 112 |
+
elapsed = time.time() - start
|
| 113 |
+
tps = (step * batch_size * config.max_seq_len) / elapsed
|
| 114 |
+
energy_str = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 115 |
+
msg = f"[{mode}] Step {step:6d} | Loss: {loss_val:.4f} | Energy: {energy_str} | Tok/s: {tps:.0f} | {elapsed:.0f}s"
|
| 116 |
+
TRAINING_LOG.append(msg)
|
| 117 |
+
log["steps"].append(step)
|
| 118 |
+
log["losses"].append(loss_val)
|
| 119 |
+
log["energies"].append(energies[-1] if energies else 0)
|
| 120 |
+
|
| 121 |
+
if step % 2000 == 0:
|
| 122 |
+
model.eval()
|
| 123 |
+
tl, tt = 0.0, 0
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
for vb in val_loader:
|
| 126 |
+
vx = vb["input_ids"].to(device)
|
| 127 |
+
vo = model(vx)
|
| 128 |
+
nm = vo["mask"].sum().item()
|
| 129 |
+
if nm > 0:
|
| 130 |
+
tl += vo["loss"].item() * nm
|
| 131 |
+
tt += nm
|
| 132 |
+
if tt > 100000:
|
| 133 |
+
break
|
| 134 |
+
vl = tl / max(1, tt)
|
| 135 |
+
TRAINING_LOG.append(f" --> [{mode}] Val loss: {vl:.4f}")
|
| 136 |
+
log["val_losses"].append((step, vl))
|
| 137 |
+
model.train()
|
| 138 |
+
|
| 139 |
+
elapsed = time.time() - start
|
| 140 |
+
# Final val
|
| 141 |
+
model.eval()
|
| 142 |
+
tl, tt = 0.0, 0
|
| 143 |
+
with torch.no_grad():
|
| 144 |
+
for vb in val_loader:
|
| 145 |
+
vx = vb["input_ids"].to(device)
|
| 146 |
+
vo = model(vx)
|
| 147 |
+
nm = vo["mask"].sum().item()
|
| 148 |
+
if nm > 0:
|
| 149 |
+
tl += vo["loss"].item() * nm
|
| 150 |
+
tt += nm
|
| 151 |
+
if tt > 200000:
|
| 152 |
+
break
|
| 153 |
+
final_val = tl / max(1, tt)
|
| 154 |
+
log["final_val_loss"] = final_val
|
| 155 |
+
msg = f"[{mode}] DONE: {step} steps in {elapsed:.0f}s | Final val loss: {final_val:.4f}"
|
| 156 |
+
TRAINING_LOG.append(msg)
|
| 157 |
+
|
| 158 |
+
# Save checkpoint
|
| 159 |
+
os.makedirs("results", exist_ok=True)
|
| 160 |
+
torch.save({"model": model.state_dict(), "config": config, "log": log}, f"results/{mode}_10k.pt")
|
| 161 |
+
|
| 162 |
+
return log
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def run_all_training():
|
| 166 |
+
global CURRENT_STATUS, TRAINING_LOG
|
| 167 |
+
TRAINING_LOG = ["Starting PC-SHO-DLM A100 Training..."]
|
| 168 |
+
|
| 169 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 170 |
+
TRAINING_LOG.append(f"Device: {device}")
|
| 171 |
+
if device == "cuda":
|
| 172 |
+
TRAINING_LOG.append(f"GPU: {torch.cuda.get_device_name()}")
|
| 173 |
+
TRAINING_LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
|
| 174 |
+
|
| 175 |
+
# A100-optimized config
|
| 176 |
+
config = PCSHOConfig(
|
| 177 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8,
|
| 178 |
+
n_layers=12, d_ff=2048, n_diffusion_steps=128, n_settling_steps=6,
|
| 179 |
+
mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 180 |
+
)
|
| 181 |
+
TRAINING_LOG.append(f"Model: d={config.d_model}, L={config.n_layers}, ~{count_parameters(PCSHODLM(config)):,} params")
|
| 182 |
+
|
| 183 |
+
# Load data
|
| 184 |
+
CURRENT_STATUS = "Loading WikiText-103..."
|
| 185 |
+
from datasets import load_dataset
|
| 186 |
+
ds_train = load_dataset("wikitext", "wikitext-103-raw-v1", split="train")
|
| 187 |
+
ds_val = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 188 |
+
train_text = "\n".join([r["text"] for r in ds_train if r["text"].strip()])[:100_000_000]
|
| 189 |
+
val_text = "\n".join([r["text"] for r in ds_val if r["text"].strip()])
|
| 190 |
+
train_ds = CharLevelDataset(train_text, config.max_seq_len)
|
| 191 |
+
val_ds = CharLevelDataset(val_text, config.max_seq_len)
|
| 192 |
+
TRAINING_LOG.append(f"Data: {len(train_text):,} train chars, {len(val_text):,} val chars")
|
| 193 |
+
|
| 194 |
+
results = {}
|
| 195 |
+
for mode in ["backprop", "local", "unified"]:
|
| 196 |
+
results[mode] = train_one_mode(mode, config, train_ds, val_ds, max_steps=10000, batch_size=64)
|
| 197 |
+
|
| 198 |
+
# Final summary
|
| 199 |
+
TRAINING_LOG.append(f"\n{'='*60}")
|
| 200 |
+
TRAINING_LOG.append("FINAL RESULTS")
|
| 201 |
+
TRAINING_LOG.append(f"{'='*60}")
|
| 202 |
+
for mode, log in results.items():
|
| 203 |
+
TRAINING_LOG.append(f"{mode:15s} | Val loss: {log.get('final_val_loss', 'N/A')}")
|
| 204 |
+
|
| 205 |
+
CURRENT_STATUS = "Complete!"
|
| 206 |
+
|
| 207 |
+
# Upload results
|
| 208 |
+
try:
|
| 209 |
+
from huggingface_hub import HfApi
|
| 210 |
+
api = HfApi()
|
| 211 |
+
with open("results/results.json", "w") as f:
|
| 212 |
+
json.dump(results, f, indent=2)
|
| 213 |
+
api.upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-train",
|
| 214 |
+
repo_type="space", path_in_repo="results")
|
| 215 |
+
TRAINING_LOG.append("Results uploaded to HuggingFace!")
|
| 216 |
+
except Exception as e:
|
| 217 |
+
TRAINING_LOG.append(f"Upload error: {e}")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# =============================================================================
|
| 221 |
+
# Gradio UI
|
| 222 |
+
# =============================================================================
|
| 223 |
+
|
| 224 |
+
training_thread = None
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def start_training():
|
| 228 |
+
global training_thread
|
| 229 |
+
if training_thread and training_thread.is_alive():
|
| 230 |
+
return "Training already running!"
|
| 231 |
+
training_thread = threading.Thread(target=run_all_training, daemon=True)
|
| 232 |
+
training_thread.start()
|
| 233 |
+
return "Training started on A100!"
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def get_log():
|
| 237 |
+
return "\n".join(TRAINING_LOG[-50:])
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def get_status():
|
| 241 |
+
return CURRENT_STATUS
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
with gr.Blocks(title="PC-SHO-DLM Training") as demo:
|
| 245 |
+
gr.Markdown("# PC-SHO-DLM: Predictive-Coding Diffusion LM — A100 Training")
|
| 246 |
+
gr.Markdown("Trains 3 modes (backprop, local PC, unified) on WikiText-103 with ~50M params")
|
| 247 |
+
|
| 248 |
+
with gr.Row():
|
| 249 |
+
start_btn = gr.Button("Start Training", variant="primary")
|
| 250 |
+
status = gr.Textbox(label="Status", value="Idle")
|
| 251 |
+
|
| 252 |
+
log_box = gr.Textbox(label="Training Log", lines=25, max_lines=50)
|
| 253 |
+
|
| 254 |
+
refresh_btn = gr.Button("Refresh Log")
|
| 255 |
+
|
| 256 |
+
start_btn.click(start_training, outputs=status)
|
| 257 |
+
refresh_btn.click(get_log, outputs=log_box)
|
| 258 |
+
refresh_btn.click(get_status, outputs=status)
|
| 259 |
+
|
| 260 |
+
# Auto-refresh via Timer
|
| 261 |
+
timer = gr.Timer(5)
|
| 262 |
+
timer.tick(get_log, outputs=log_box)
|
| 263 |
+
timer.tick(get_status, outputs=status)
|
| 264 |
+
|
| 265 |
+
demo.launch()
|
app_backprop_wiki.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FAIR BACKPROP BASELINE — WikiText-103 in memory, standard masked diffusion LM."""
|
| 2 |
+
import json, os, sys, threading, time
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch, torch.nn as nn, torch.nn.functional as F
|
| 5 |
+
from torch.utils.data import DataLoader, Dataset
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 8 |
+
from model import PCSHOConfig, MaskDiffusionSchedule, BidirectionalTransformerBlock
|
| 9 |
+
|
| 10 |
+
class StandardMaskedDiffusionLM(nn.Module):
|
| 11 |
+
def __init__(self, config):
|
| 12 |
+
super().__init__()
|
| 13 |
+
self.config = config
|
| 14 |
+
self.token_embed = nn.Embedding(config.vocab_size, config.d_model)
|
| 15 |
+
self.pos_embed = nn.Embedding(config.max_seq_len, config.d_model)
|
| 16 |
+
self.time_embed = nn.Embedding(config.n_diffusion_steps + 1, config.d_model)
|
| 17 |
+
self.layers = nn.ModuleList([
|
| 18 |
+
BidirectionalTransformerBlock(config.d_model, config.n_heads, config.d_ff, config.dropout)
|
| 19 |
+
for _ in range(config.n_layers)
|
| 20 |
+
])
|
| 21 |
+
self.readout_norm = nn.LayerNorm(config.d_model)
|
| 22 |
+
self.readout = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 23 |
+
self.schedule = MaskDiffusionSchedule(config.n_diffusion_steps)
|
| 24 |
+
|
| 25 |
+
def forward(self, x_0, t=None):
|
| 26 |
+
B, S = x_0.shape; device = x_0.device
|
| 27 |
+
if t is None: t = torch.randint(1, self.config.n_diffusion_steps + 1, (B,), device=device)
|
| 28 |
+
x_t, mask = self.schedule.corrupt(x_0, t, self.config.mask_token_id)
|
| 29 |
+
positions = torch.arange(S, device=device).unsqueeze(0)
|
| 30 |
+
h = self.token_embed(x_t) + self.pos_embed(positions) + self.time_embed(t).unsqueeze(1)
|
| 31 |
+
for layer in self.layers: h = layer(h)
|
| 32 |
+
logits = self.readout(self.readout_norm(h))
|
| 33 |
+
ml, mt = logits[mask], x_0[mask]
|
| 34 |
+
loss = F.cross_entropy(ml, mt) if ml.numel() > 0 else torch.tensor(0.0, device=device)
|
| 35 |
+
return {"loss": loss, "mask": mask}
|
| 36 |
+
|
| 37 |
+
class CharDS(Dataset):
|
| 38 |
+
def __init__(self, text, sl):
|
| 39 |
+
self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 40 |
+
self.n = max(1,(len(self.data)-sl)//sl)
|
| 41 |
+
def __len__(self): return self.n
|
| 42 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 43 |
+
|
| 44 |
+
LOG, STATUS = [], "Idle"
|
| 45 |
+
|
| 46 |
+
def train():
|
| 47 |
+
global STATUS, LOG
|
| 48 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 49 |
+
LOG = [f"FAIR BACKPROP | Device: {dev}"]
|
| 50 |
+
if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 51 |
+
|
| 52 |
+
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)
|
| 53 |
+
|
| 54 |
+
STATUS = "Loading WikiText-103 into memory..."
|
| 55 |
+
from datasets import load_dataset
|
| 56 |
+
ds = load_dataset("wikitext", "wikitext-103-raw-v1", split="train")
|
| 57 |
+
dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 58 |
+
train_text = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000]
|
| 59 |
+
val_text = "\n".join([r["text"] for r in dv if r["text"].strip()])
|
| 60 |
+
train_ds = CharDS(train_text, cfg.max_seq_len); val_ds = CharDS(val_text, cfg.max_seq_len)
|
| 61 |
+
LOG.append(f"Data: {len(train_text):,} train chars, {len(val_text):,} val chars IN MEMORY")
|
| 62 |
+
|
| 63 |
+
model = StandardMaskedDiffusionLM(cfg).to(dev)
|
| 64 |
+
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 65 |
+
LOG.append(f"Model: {n_params:,} params | NO settling, NO PC, pure backprop")
|
| 66 |
+
model.train()
|
| 67 |
+
|
| 68 |
+
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
|
| 69 |
+
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10000, eta_min=3e-5)
|
| 70 |
+
tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True)
|
| 71 |
+
vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True)
|
| 72 |
+
|
| 73 |
+
STATUS = "Training..."
|
| 74 |
+
LOG.append(f"\n{'='*60}\nFAIR BACKPROP | {n_params:,} params\n{'='*60}")
|
| 75 |
+
step, start, mx = 0, time.time(), 10000
|
| 76 |
+
|
| 77 |
+
while step < mx:
|
| 78 |
+
for batch in tl:
|
| 79 |
+
if step >= mx: break
|
| 80 |
+
x0 = batch["input_ids"].to(dev)
|
| 81 |
+
opt.zero_grad(); out = model(x0); loss = out["loss"]; loss.backward()
|
| 82 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step(); sched.step()
|
| 83 |
+
step += 1; lv = loss.item()
|
| 84 |
+
if step % 100 == 0:
|
| 85 |
+
el = time.time()-start; tps = step*64*cfg.max_seq_len/el
|
| 86 |
+
LOG.append(f"[fair-bp] Step {step:6d} | Loss: {lv:.4f} | Tok/s: {tps:.0f} | {el:.0f}s")
|
| 87 |
+
if step % 2000 == 0:
|
| 88 |
+
model.eval(); tl2,tt2=0.,0
|
| 89 |
+
with torch.no_grad():
|
| 90 |
+
for vb in vl:
|
| 91 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 92 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 93 |
+
if tt2>100000: break
|
| 94 |
+
LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); model.train()
|
| 95 |
+
|
| 96 |
+
model.eval(); tl2,tt2=0.,0
|
| 97 |
+
with torch.no_grad():
|
| 98 |
+
for vb in vl:
|
| 99 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 100 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 101 |
+
if tt2>200000: break
|
| 102 |
+
LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s | Val: {tl2/max(1,tt2):.4f}")
|
| 103 |
+
STATUS = "Complete!"
|
| 104 |
+
os.makedirs("results",exist_ok=True)
|
| 105 |
+
torch.save({"model":model.state_dict(),"config":cfg},"results/fair_backprop.pt")
|
| 106 |
+
|
| 107 |
+
_t = None
|
| 108 |
+
def start():
|
| 109 |
+
global _t
|
| 110 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 111 |
+
_t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!"
|
| 112 |
+
|
| 113 |
+
with gr.Blocks(title="Fair Backprop") as demo:
|
| 114 |
+
gr.Markdown("# FAIR BACKPROP — WikiText-103 in memory")
|
| 115 |
+
with gr.Row():
|
| 116 |
+
btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle")
|
| 117 |
+
log=gr.Textbox(label="Log",lines=30); btn.click(start,outputs=st)
|
| 118 |
+
r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-60:]),outputs=log); r.click(lambda:STATUS,outputs=st)
|
| 119 |
+
t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-60:]),outputs=log); t.tick(lambda:STATUS,outputs=st)
|
| 120 |
+
demo.launch()
|
app_chat_a100.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM Chat Training on A100 — HONEST settling, large model, big dataset."""
|
| 2 |
+
import json, os, sys, threading, time, math, urllib.request
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch, torch.nn.functional as F
|
| 5 |
+
from torch.utils.data import DataLoader, Dataset
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 8 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters
|
| 9 |
+
|
| 10 |
+
class DialogueDataset(Dataset):
|
| 11 |
+
def __init__(self, pairs, max_seq_len, vocab_size=257):
|
| 12 |
+
self.samples = []
|
| 13 |
+
sep = [0x0A, 0x0A]
|
| 14 |
+
for prompt, response in pairs:
|
| 15 |
+
p = [min(b+1, vocab_size-1) for b in prompt.encode("utf-8")]
|
| 16 |
+
r = [min(b+1, vocab_size-1) for b in response.encode("utf-8")]
|
| 17 |
+
s = [min(b+1, vocab_size-1) for b in bytes(sep)]
|
| 18 |
+
max_p = int(max_seq_len * 0.4)
|
| 19 |
+
p = p[:max_p]; max_r = max_seq_len - len(p) - len(s); r = r[:max_r]
|
| 20 |
+
full = p + s + r
|
| 21 |
+
pl = len(p) + len(s)
|
| 22 |
+
if len(full) < max_seq_len: full += [0] * (max_seq_len - len(full))
|
| 23 |
+
self.samples.append({"input_ids": torch.tensor(full[:max_seq_len], dtype=torch.long), "prompt_len": pl, "response_len": len(r)})
|
| 24 |
+
def __len__(self): return len(self.samples)
|
| 25 |
+
def __getitem__(self, i): return self.samples[i]
|
| 26 |
+
|
| 27 |
+
def conditional_corrupt(x_0, t, mask_id, schedule, prompt_lens):
|
| 28 |
+
B, S = x_0.shape
|
| 29 |
+
mask_prob = schedule.mask_rate(t).unsqueeze(-1)
|
| 30 |
+
random_mask = torch.rand_like(x_0.float()) < mask_prob
|
| 31 |
+
response_mask = torch.zeros_like(x_0, dtype=torch.bool)
|
| 32 |
+
for b in range(B): response_mask[b, prompt_lens[b]:] = True
|
| 33 |
+
mask = random_mask & response_mask
|
| 34 |
+
x_t = x_0.clone(); x_t[mask] = mask_id
|
| 35 |
+
return x_t, mask
|
| 36 |
+
|
| 37 |
+
LOG, STATUS = [], "Idle"
|
| 38 |
+
|
| 39 |
+
def train():
|
| 40 |
+
global STATUS, LOG
|
| 41 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 42 |
+
LOG = [f"PC-SHO-DLM CHAT | HONEST SETTLING | {dev}"]
|
| 43 |
+
if dev == "cuda":
|
| 44 |
+
LOG.append(f"GPU: {torch.cuda.get_device_name()} | {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 45 |
+
|
| 46 |
+
# Bigger model for A100
|
| 47 |
+
cfg = PCSHOConfig(
|
| 48 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048,
|
| 49 |
+
n_diffusion_steps=64, n_settling_steps=6, mask_token_id=0, dropout=0.1,
|
| 50 |
+
feedback_rank=128, denoising_lambda=5.0,
|
| 51 |
+
homeostatic_target=0.0, lateral_inhibition=0.0,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
STATUS = "Loading Alpaca + Dolly datasets..."
|
| 55 |
+
pairs = []
|
| 56 |
+
|
| 57 |
+
# Alpaca
|
| 58 |
+
try:
|
| 59 |
+
url = "https://raw.githubusercontent.com/tatsu-lab/stanford_alpaca/main/alpaca_data.json"
|
| 60 |
+
LOG.append("Downloading Alpaca...")
|
| 61 |
+
with urllib.request.urlopen(url) as r:
|
| 62 |
+
data = json.loads(r.read())
|
| 63 |
+
for row in data:
|
| 64 |
+
inst = row.get("instruction",""); inp = row.get("input",""); out = row.get("output","")
|
| 65 |
+
p = f"{inst}\n{inp}".strip() if inp else inst
|
| 66 |
+
if p and out: pairs.append((p, out))
|
| 67 |
+
LOG.append(f"Alpaca: {len(pairs)} pairs")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
LOG.append(f"Alpaca failed: {e}")
|
| 70 |
+
|
| 71 |
+
# Dolly
|
| 72 |
+
try:
|
| 73 |
+
from datasets import load_dataset
|
| 74 |
+
ds = load_dataset("databricks/dolly-15k", split="train")
|
| 75 |
+
n_before = len(pairs)
|
| 76 |
+
for row in ds:
|
| 77 |
+
p = row.get("instruction","") or row.get("context","")
|
| 78 |
+
r = row.get("response","")
|
| 79 |
+
if p and r: pairs.append((p, r))
|
| 80 |
+
LOG.append(f"Dolly: {len(pairs) - n_before} pairs")
|
| 81 |
+
except Exception as e:
|
| 82 |
+
LOG.append(f"Dolly failed: {e}")
|
| 83 |
+
|
| 84 |
+
LOG.append(f"Total: {len(pairs)} dialogue pairs")
|
| 85 |
+
|
| 86 |
+
n_val = max(1, len(pairs) // 20)
|
| 87 |
+
train_ds = DialogueDataset(pairs[n_val:], cfg.max_seq_len)
|
| 88 |
+
val_ds = DialogueDataset(pairs[:n_val], cfg.max_seq_len)
|
| 89 |
+
LOG.append(f"Train: {len(train_ds)}, Val: {len(val_ds)}")
|
| 90 |
+
|
| 91 |
+
model = PCSHODLM(cfg).to(dev); model.train()
|
| 92 |
+
n_params = count_parameters(model)
|
| 93 |
+
LOG.append(f"Model: {n_params:,} params | HONEST settling (entropy, no peeking)")
|
| 94 |
+
|
| 95 |
+
updater = LocalParameterUpdater(model, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5)
|
| 96 |
+
tl = DataLoader(train_ds, batch_size=32, shuffle=True, drop_last=True, num_workers=4, pin_memory=True)
|
| 97 |
+
|
| 98 |
+
STATUS = "Training..."
|
| 99 |
+
LOG.append(f"\n{'='*60}\nCHAT TRAINING | {n_params:,} params | honest settling\n{'='*60}")
|
| 100 |
+
step, start, mx = 0, time.time(), 10000
|
| 101 |
+
K_max = cfg.n_settling_steps
|
| 102 |
+
|
| 103 |
+
while step < mx:
|
| 104 |
+
for batch in tl:
|
| 105 |
+
if step >= mx: break
|
| 106 |
+
x_0 = batch["input_ids"].to(dev)
|
| 107 |
+
prompt_lens = batch["prompt_len"]; B, S = x_0.shape
|
| 108 |
+
|
| 109 |
+
K_curr = max(3, int(K_max * min(1.0, step / 1000)))
|
| 110 |
+
model.config.n_settling_steps = K_curr
|
| 111 |
+
t = torch.randint(1, cfg.n_diffusion_steps+1, (B,), device=dev)
|
| 112 |
+
x_t, mask = conditional_corrupt(x_0, t, cfg.mask_token_id, model.schedule, prompt_lens)
|
| 113 |
+
|
| 114 |
+
# HONEST SETTLE: x_t not x_0
|
| 115 |
+
h_0 = model.embed_input(x_t, t)
|
| 116 |
+
h_init = model.amortized_forward_pass(h_0)
|
| 117 |
+
with torch.no_grad():
|
| 118 |
+
h_settled, _, energies, _, _ = model.settle(h_init, x_t, mask, t)
|
| 119 |
+
|
| 120 |
+
# Local updates
|
| 121 |
+
L = cfg.n_layers
|
| 122 |
+
for l in range(L):
|
| 123 |
+
updater.forward_optimizers[l].zero_grad()
|
| 124 |
+
mu_up = model.forward_blocks[l](h_settled[l].detach())
|
| 125 |
+
with torch.no_grad(): tok_p, ch_p = model.precision_up[l](h_settled[l+1].detach(), t)
|
| 126 |
+
eps = h_settled[l+1].detach() - mu_up
|
| 127 |
+
(0.5*(eps*tok_p*ch_p*eps).sum()/B).backward()
|
| 128 |
+
updater.forward_optimizers[l].step()
|
| 129 |
+
|
| 130 |
+
for l in range(L-1):
|
| 131 |
+
updater.feedback_optimizers[l].zero_grad()
|
| 132 |
+
mu_down = model.feedback_blocks[l](h_settled[l+2].detach())
|
| 133 |
+
with torch.no_grad(): tok_p, ch_p = model.precision_down[l](h_settled[l+1].detach(), t)
|
| 134 |
+
eps = h_settled[l+1].detach() - mu_down
|
| 135 |
+
(0.5*(eps*tok_p*ch_p*eps).sum()/B).backward()
|
| 136 |
+
updater.feedback_optimizers[l].step()
|
| 137 |
+
|
| 138 |
+
# Readout — this uses x_0 targets (learning signal)
|
| 139 |
+
updater.readout_optimizer.zero_grad()
|
| 140 |
+
logits = model.readout(model.readout_norm(h_settled[L].detach()))
|
| 141 |
+
ml, mt = logits[mask], x_0[mask]
|
| 142 |
+
if ml.numel() > 0:
|
| 143 |
+
loss = F.cross_entropy(ml, mt); loss.backward()
|
| 144 |
+
updater.readout_optimizer.step(); lv = loss.item()
|
| 145 |
+
else: lv = 0
|
| 146 |
+
|
| 147 |
+
# Embeddings
|
| 148 |
+
updater.embed_optimizer.zero_grad()
|
| 149 |
+
with torch.enable_grad():
|
| 150 |
+
h0f = model.embed_input(x_t, t); hif = model.amortized_forward_pass(h0f)
|
| 151 |
+
lf = model.readout(model.readout_norm(hif[L]))
|
| 152 |
+
mlf, mtf = lf[mask], x_0[mask]
|
| 153 |
+
if mlf.numel() > 0:
|
| 154 |
+
el = F.cross_entropy(mlf, mtf); el.backward()
|
| 155 |
+
torch.nn.utils.clip_grad_norm_(list(model.token_embed.parameters())+list(model.pos_embed.parameters())+list(model.time_embed.parameters()), 1.0)
|
| 156 |
+
updater.embed_optimizer.step()
|
| 157 |
+
|
| 158 |
+
step += 1
|
| 159 |
+
if step % 50 == 0:
|
| 160 |
+
el = time.time()-start; tps = step*32*cfg.max_seq_len/el
|
| 161 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 162 |
+
LOG.append(f"Step {step:5d} | Loss: {lv:.4f} | Energy: {e} | K={K_curr} | Tok/s: {tps:.0f} | {el:.0f}s")
|
| 163 |
+
if step % 1000 == 0:
|
| 164 |
+
os.makedirs("results", exist_ok=True)
|
| 165 |
+
torch.save({"model_state_dict": model.state_dict(), "config": cfg, "step": step}, f"results/chat_step{step}.pt")
|
| 166 |
+
|
| 167 |
+
os.makedirs("results", exist_ok=True)
|
| 168 |
+
torch.save({"model_state_dict": model.state_dict(), "config": cfg}, "results/chat_final.pt")
|
| 169 |
+
LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s")
|
| 170 |
+
STATUS = "Complete!"
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
from huggingface_hub import HfApi
|
| 174 |
+
HfApi().upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-local-pc-wiki", repo_type="space", path_in_repo="results")
|
| 175 |
+
LOG.append("Results uploaded!")
|
| 176 |
+
except: pass
|
| 177 |
+
|
| 178 |
+
_t = None
|
| 179 |
+
def start():
|
| 180 |
+
global _t
|
| 181 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 182 |
+
_t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!"
|
| 183 |
+
|
| 184 |
+
with gr.Blocks(title="PC-SHO-DLM Chat") as demo:
|
| 185 |
+
gr.Markdown("# PC-SHO-DLM Chat Training (A100) — HONEST Settling")
|
| 186 |
+
gr.Markdown("Entropy-based settling (no peeking at answers). Alpaca + Dolly data.")
|
| 187 |
+
with gr.Row():
|
| 188 |
+
btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle")
|
| 189 |
+
log=gr.Textbox(label="Log",lines=35); btn.click(start,outputs=st)
|
| 190 |
+
r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-70:]),outputs=log); r.click(lambda:STATUS,outputs=st)
|
| 191 |
+
t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-70:]),outputs=log); t.tick(lambda:STATUS,outputs=st)
|
| 192 |
+
demo.launch()
|
app_fair_backprop.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM: FAIR BACKPROP BASELINE
|
| 2 |
+
Standard masked diffusion LM — same architecture but NO settling loop.
|
| 3 |
+
Single forward pass through the transformer + backprop on masked token loss.
|
| 4 |
+
This is the proper baseline to compare against Local PC.
|
| 5 |
+
"""
|
| 6 |
+
import json, os, sys, threading, time, math
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import torch, torch.nn as nn, torch.nn.functional as F
|
| 9 |
+
from torch.utils.data import DataLoader, IterableDataset, Dataset
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 12 |
+
from model import PCSHOConfig, MaskDiffusionSchedule, BidirectionalTransformerBlock, count_parameters
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# =============================================================================
|
| 16 |
+
# Standard Masked Diffusion Transformer (NO predictive coding, NO settling)
|
| 17 |
+
# =============================================================================
|
| 18 |
+
|
| 19 |
+
class StandardMaskedDiffusionLM(nn.Module):
|
| 20 |
+
"""Standard masked diffusion LM baseline.
|
| 21 |
+
|
| 22 |
+
Same transformer architecture as PC-SHO-DLM but:
|
| 23 |
+
- Single forward pass (no settling loop)
|
| 24 |
+
- Standard backprop through all layers
|
| 25 |
+
- No predictive coding energy, no precision heads, no feedback blocks
|
| 26 |
+
- Same masked token denoising objective
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, config: PCSHOConfig):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.config = config
|
| 32 |
+
|
| 33 |
+
self.token_embed = nn.Embedding(config.vocab_size, config.d_model)
|
| 34 |
+
self.pos_embed = nn.Embedding(config.max_seq_len, config.d_model)
|
| 35 |
+
self.time_embed = nn.Embedding(config.n_diffusion_steps + 1, config.d_model)
|
| 36 |
+
|
| 37 |
+
# Same transformer blocks as PC-SHO-DLM forward path
|
| 38 |
+
self.layers = nn.ModuleList([
|
| 39 |
+
BidirectionalTransformerBlock(config.d_model, config.n_heads, config.d_ff, config.dropout)
|
| 40 |
+
for _ in range(config.n_layers)
|
| 41 |
+
])
|
| 42 |
+
|
| 43 |
+
self.readout_norm = nn.LayerNorm(config.d_model)
|
| 44 |
+
self.readout = nn.Linear(config.d_model, config.vocab_size, bias=False)
|
| 45 |
+
self.schedule = MaskDiffusionSchedule(config.n_diffusion_steps)
|
| 46 |
+
|
| 47 |
+
def forward(self, x_0, t=None):
|
| 48 |
+
B, S = x_0.shape
|
| 49 |
+
device = x_0.device
|
| 50 |
+
|
| 51 |
+
if t is None:
|
| 52 |
+
t = torch.randint(1, self.config.n_diffusion_steps + 1, (B,), device=device)
|
| 53 |
+
|
| 54 |
+
x_t, mask = self.schedule.corrupt(x_0, t, self.config.mask_token_id)
|
| 55 |
+
|
| 56 |
+
# Single forward pass — no settling
|
| 57 |
+
positions = torch.arange(S, device=device).unsqueeze(0)
|
| 58 |
+
h = self.token_embed(x_t) + self.pos_embed(positions) + self.time_embed(t).unsqueeze(1)
|
| 59 |
+
|
| 60 |
+
for layer in self.layers:
|
| 61 |
+
h = layer(h)
|
| 62 |
+
|
| 63 |
+
logits = self.readout(self.readout_norm(h))
|
| 64 |
+
mask_logits = logits[mask]
|
| 65 |
+
mask_targets = x_0[mask]
|
| 66 |
+
|
| 67 |
+
if mask_logits.numel() > 0:
|
| 68 |
+
loss = F.cross_entropy(mask_logits, mask_targets)
|
| 69 |
+
else:
|
| 70 |
+
loss = torch.tensor(0.0, device=device)
|
| 71 |
+
|
| 72 |
+
return {"loss": loss, "logits": logits, "mask": mask}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# =============================================================================
|
| 76 |
+
# Data
|
| 77 |
+
# =============================================================================
|
| 78 |
+
|
| 79 |
+
class StreamDS(IterableDataset):
|
| 80 |
+
def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None):
|
| 81 |
+
self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok
|
| 82 |
+
def __iter__(self):
|
| 83 |
+
from datasets import load_dataset
|
| 84 |
+
ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True, trust_remote_code=True)
|
| 85 |
+
buf, tot = [], 0
|
| 86 |
+
for item in ds:
|
| 87 |
+
t = item.get("text", "")
|
| 88 |
+
if not t or not t.strip(): continue
|
| 89 |
+
buf.extend([min(b+1, self.voc-1) for b in t.encode("utf-8")])
|
| 90 |
+
while len(buf) >= self.seq_len:
|
| 91 |
+
yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)}
|
| 92 |
+
buf = buf[self.seq_len:]; tot += self.seq_len
|
| 93 |
+
if self.max_tok and tot > self.max_tok: return
|
| 94 |
+
|
| 95 |
+
class CharDS(Dataset):
|
| 96 |
+
def __init__(self, text, sl):
|
| 97 |
+
self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 98 |
+
self.n = max(1,(len(self.data)-sl)//sl)
|
| 99 |
+
def __len__(self): return self.n
|
| 100 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# =============================================================================
|
| 104 |
+
# Training
|
| 105 |
+
# =============================================================================
|
| 106 |
+
|
| 107 |
+
LOG, STATUS = [], "Idle"
|
| 108 |
+
|
| 109 |
+
def train():
|
| 110 |
+
global STATUS, LOG
|
| 111 |
+
LOG = ["=" * 70]
|
| 112 |
+
LOG.append("FAIR BACKPROP BASELINE")
|
| 113 |
+
LOG.append("Standard masked diffusion LM — NO settling, NO PC, pure backprop")
|
| 114 |
+
LOG.append("Same transformer architecture, same data, same hyperparameters")
|
| 115 |
+
LOG.append("=" * 70)
|
| 116 |
+
|
| 117 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 118 |
+
LOG.append(f"Device: {dev}")
|
| 119 |
+
if dev == "cuda":
|
| 120 |
+
LOG.append(f"GPU: {torch.cuda.get_device_name()}")
|
| 121 |
+
LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 122 |
+
|
| 123 |
+
# Same architecture as PC-SHO-DLM but without PC overhead
|
| 124 |
+
cfg = PCSHOConfig(
|
| 125 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8,
|
| 126 |
+
n_layers=12, d_ff=2048, n_diffusion_steps=128,
|
| 127 |
+
mask_token_id=0, dropout=0.1,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
model = StandardMaskedDiffusionLM(cfg).to(dev)
|
| 131 |
+
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 132 |
+
LOG.append(f"Model: {n_params:,} params (d={cfg.d_model}, L={cfg.n_layers})")
|
| 133 |
+
LOG.append("NO settling loop, NO precision heads, NO feedback blocks")
|
| 134 |
+
LOG.append("Pure single-forward-pass + backprop")
|
| 135 |
+
|
| 136 |
+
STATUS = "Loading data..."
|
| 137 |
+
from datasets import load_dataset
|
| 138 |
+
dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 139 |
+
val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len)
|
| 140 |
+
train_ds = StreamDS("wikitext", "wikitext-103-raw-v1", "train", cfg.max_seq_len, max_tok=500_000_000)
|
| 141 |
+
LOG.append("Data: WikiText-103 streaming (500M tokens)")
|
| 142 |
+
|
| 143 |
+
model.train()
|
| 144 |
+
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
|
| 145 |
+
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10000, eta_min=3e-5)
|
| 146 |
+
tl = DataLoader(train_ds, batch_size=64, num_workers=4, pin_memory=True)
|
| 147 |
+
vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True)
|
| 148 |
+
|
| 149 |
+
STATUS = "Training FAIR BACKPROP..."
|
| 150 |
+
LOG.append(f"\n{'='*70}")
|
| 151 |
+
LOG.append(f"FAIR BACKPROP | {n_params:,} params | Single forward pass")
|
| 152 |
+
LOG.append(f"{'='*70}")
|
| 153 |
+
|
| 154 |
+
step, start, mx = 0, time.time(), 10000
|
| 155 |
+
log_d = {"steps": [], "losses": []}
|
| 156 |
+
|
| 157 |
+
for batch in tl:
|
| 158 |
+
if step >= mx: break
|
| 159 |
+
x0 = batch["input_ids"].to(dev)
|
| 160 |
+
|
| 161 |
+
opt.zero_grad()
|
| 162 |
+
out = model(x0)
|
| 163 |
+
loss = out["loss"]
|
| 164 |
+
loss.backward()
|
| 165 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 166 |
+
opt.step()
|
| 167 |
+
sched.step()
|
| 168 |
+
|
| 169 |
+
step += 1
|
| 170 |
+
lv = loss.item()
|
| 171 |
+
|
| 172 |
+
if step % 100 == 0:
|
| 173 |
+
el = time.time() - start
|
| 174 |
+
tps = step * 64 * cfg.max_seq_len / el
|
| 175 |
+
msg = f"[fair-bp] Step {step:6d} | Loss: {lv:.4f} | Tok/s: {tps:.0f} | {el:.0f}s"
|
| 176 |
+
LOG.append(msg)
|
| 177 |
+
log_d["steps"].append(step)
|
| 178 |
+
log_d["losses"].append(lv)
|
| 179 |
+
|
| 180 |
+
if step % 2000 == 0:
|
| 181 |
+
model.eval()
|
| 182 |
+
tl2, tt2 = 0., 0
|
| 183 |
+
with torch.no_grad():
|
| 184 |
+
for vb in vl:
|
| 185 |
+
vo = model(vb["input_ids"].to(dev))
|
| 186 |
+
nm = vo["mask"].sum().item()
|
| 187 |
+
if nm > 0: tl2 += vo["loss"].item() * nm; tt2 += nm
|
| 188 |
+
if tt2 > 100000: break
|
| 189 |
+
vl2 = tl2 / max(1, tt2)
|
| 190 |
+
LOG.append(f" --> Val: {vl2:.4f}")
|
| 191 |
+
log_d.setdefault("val", []).append((step, vl2))
|
| 192 |
+
model.train()
|
| 193 |
+
|
| 194 |
+
model.eval()
|
| 195 |
+
tl2, tt2 = 0., 0
|
| 196 |
+
with torch.no_grad():
|
| 197 |
+
for vb in vl:
|
| 198 |
+
vo = model(vb["input_ids"].to(dev))
|
| 199 |
+
nm = vo["mask"].sum().item()
|
| 200 |
+
if nm > 0: tl2 += vo["loss"].item() * nm; tt2 += nm
|
| 201 |
+
if tt2 > 200000: break
|
| 202 |
+
fv = tl2 / max(1, tt2)
|
| 203 |
+
log_d["final_val"] = fv
|
| 204 |
+
elapsed = time.time() - start
|
| 205 |
+
LOG.append(f"\nDONE: {step} steps in {elapsed:.0f}s | Final val: {fv:.4f}")
|
| 206 |
+
LOG.append(f"Tok/s: {step*64*cfg.max_seq_len/elapsed:.0f}")
|
| 207 |
+
STATUS = "Complete!"
|
| 208 |
+
|
| 209 |
+
os.makedirs("results", exist_ok=True)
|
| 210 |
+
torch.save({"model": model.state_dict(), "config": cfg, "log": log_d}, "results/fair_backprop.pt")
|
| 211 |
+
try:
|
| 212 |
+
from huggingface_hub import HfApi
|
| 213 |
+
HfApi().upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-fair-backprop",
|
| 214 |
+
repo_type="space", path_in_repo="results")
|
| 215 |
+
LOG.append("Uploaded!")
|
| 216 |
+
except: pass
|
| 217 |
+
|
| 218 |
+
_t = None
|
| 219 |
+
def start():
|
| 220 |
+
global _t
|
| 221 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 222 |
+
_t = threading.Thread(target=train, daemon=True); _t.start()
|
| 223 |
+
return "FAIR BACKPROP started on A100!"
|
| 224 |
+
|
| 225 |
+
with gr.Blocks(title="Fair Backprop") as demo:
|
| 226 |
+
gr.Markdown("# FAIR BACKPROP BASELINE (A100)")
|
| 227 |
+
gr.Markdown("Standard masked diffusion LM — NO settling, NO PC. Same arch, pure backprop.")
|
| 228 |
+
with gr.Row():
|
| 229 |
+
btn = gr.Button("Start", variant="primary"); st = gr.Textbox(label="Status", value="Idle")
|
| 230 |
+
log = gr.Textbox(label="Log", lines=30)
|
| 231 |
+
btn.click(start, outputs=st)
|
| 232 |
+
r = gr.Button("Refresh"); r.click(lambda: "\n".join(LOG[-60:]), outputs=log); r.click(lambda: STATUS, outputs=st)
|
| 233 |
+
t = gr.Timer(5); t.tick(lambda: "\n".join(LOG[-60:]), outputs=log); t.tick(lambda: STATUS, outputs=st)
|
| 234 |
+
demo.launch()
|
app_local.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM: LOCAL PC Training on A100 — Single mode, fast."""
|
| 2 |
+
import json, os, sys, threading, time
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch.utils.data import DataLoader, Dataset
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 9 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters
|
| 10 |
+
|
| 11 |
+
class CharDS(Dataset):
|
| 12 |
+
def __init__(self, text, seq_len):
|
| 13 |
+
self.seq_len = seq_len
|
| 14 |
+
self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 15 |
+
self.n = max(1, (len(self.data)-seq_len)//seq_len)
|
| 16 |
+
def __len__(self): return self.n
|
| 17 |
+
def __getitem__(self, i):
|
| 18 |
+
return {"input_ids": self.data[i*self.seq_len:(i+1)*self.seq_len]}
|
| 19 |
+
|
| 20 |
+
LOG = []
|
| 21 |
+
STATUS = "Idle"
|
| 22 |
+
|
| 23 |
+
def train():
|
| 24 |
+
global STATUS, LOG
|
| 25 |
+
LOG = ["Starting LOCAL PC training on A100..."]
|
| 26 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 27 |
+
LOG.append(f"Device: {device}")
|
| 28 |
+
if device == "cuda":
|
| 29 |
+
LOG.append(f"GPU: {torch.cuda.get_device_name()}")
|
| 30 |
+
LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 31 |
+
|
| 32 |
+
config = PCSHOConfig(
|
| 33 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8,
|
| 34 |
+
n_layers=12, d_ff=2048, n_diffusion_steps=128, n_settling_steps=6,
|
| 35 |
+
mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 36 |
+
)
|
| 37 |
+
LOG.append(f"Model: {count_parameters(PCSHODLM(config)):,} params")
|
| 38 |
+
|
| 39 |
+
STATUS = "Loading data..."
|
| 40 |
+
from datasets import load_dataset
|
| 41 |
+
ds = load_dataset("wikitext","wikitext-103-raw-v1",split="train")
|
| 42 |
+
dv = load_dataset("wikitext","wikitext-103-raw-v1",split="validation")
|
| 43 |
+
tt = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000]
|
| 44 |
+
vt = "\n".join([r["text"] for r in dv if r["text"].strip()])
|
| 45 |
+
train_ds, val_ds = CharDS(tt,config.max_seq_len), CharDS(vt,config.max_seq_len)
|
| 46 |
+
LOG.append(f"Data: {len(tt):,} train, {len(vt):,} val chars")
|
| 47 |
+
|
| 48 |
+
model = PCSHODLM(config).to(device)
|
| 49 |
+
model.train()
|
| 50 |
+
updater = LocalParameterUpdater(model, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5)
|
| 51 |
+
tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True)
|
| 52 |
+
vl = DataLoader(val_ds, batch_size=64, shuffle=False, num_workers=2, pin_memory=True)
|
| 53 |
+
|
| 54 |
+
STATUS = "Training LOCAL PC..."
|
| 55 |
+
LOG.append(f"\n{'='*60}\nMode: LOCAL PC | Params: {count_parameters(model):,}\n{'='*60}")
|
| 56 |
+
step, start, max_steps = 0, time.time(), 10000
|
| 57 |
+
log_data = {"steps":[],"losses":[],"energies":[]}
|
| 58 |
+
|
| 59 |
+
while step < max_steps:
|
| 60 |
+
for batch in tl:
|
| 61 |
+
if step >= max_steps: break
|
| 62 |
+
x_0 = batch["input_ids"].to(device)
|
| 63 |
+
result = updater.step({"input_ids": x_0})
|
| 64 |
+
step += 1
|
| 65 |
+
loss = result.get("loss",0); energies = result.get("energies",[])
|
| 66 |
+
if step % 100 == 0:
|
| 67 |
+
elapsed = time.time()-start
|
| 68 |
+
tps = step*64*config.max_seq_len/elapsed
|
| 69 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 70 |
+
msg = f"[local] Step {step:6d} | Loss: {loss:.4f} | Energy: {e} | Tok/s: {tps:.0f} | {elapsed:.0f}s"
|
| 71 |
+
LOG.append(msg); log_data["steps"].append(step); log_data["losses"].append(loss); log_data["energies"].append(energies[-1] if energies else 0)
|
| 72 |
+
if step % 2000 == 0:
|
| 73 |
+
model.eval()
|
| 74 |
+
tl2,tt2=0.0,0
|
| 75 |
+
with torch.no_grad():
|
| 76 |
+
for vb in vl:
|
| 77 |
+
vx=vb["input_ids"].to(device); vo=model(vx); nm=vo["mask"].sum().item()
|
| 78 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 79 |
+
if tt2>100000: break
|
| 80 |
+
vl2=tl2/max(1,tt2); LOG.append(f" --> [local] Val loss: {vl2:.4f}"); log_data.setdefault("val",[]).append((step,vl2))
|
| 81 |
+
model.train()
|
| 82 |
+
|
| 83 |
+
model.eval()
|
| 84 |
+
tl2,tt2=0.0,0
|
| 85 |
+
with torch.no_grad():
|
| 86 |
+
for vb in vl:
|
| 87 |
+
vx=vb["input_ids"].to(device); vo=model(vx); nm=vo["mask"].sum().item()
|
| 88 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 89 |
+
if tt2>200000: break
|
| 90 |
+
fv=tl2/max(1,tt2); log_data["final_val"]=fv
|
| 91 |
+
LOG.append(f"DONE: {step} steps in {time.time()-start:.0f}s | Final val: {fv:.4f}")
|
| 92 |
+
STATUS = "Complete!"
|
| 93 |
+
|
| 94 |
+
os.makedirs("results",exist_ok=True)
|
| 95 |
+
torch.save({"model":model.state_dict(),"config":config,"log":log_data},"results/local_pc_10k.pt")
|
| 96 |
+
with open("results/local_pc_log.json","w") as f: json.dump(log_data,f)
|
| 97 |
+
try:
|
| 98 |
+
from huggingface_hub import HfApi
|
| 99 |
+
HfApi().upload_folder(folder_path="results",repo_id="zotowata/pc-sho-dlm-local",repo_type="space",path_in_repo="results")
|
| 100 |
+
LOG.append("Results uploaded!")
|
| 101 |
+
except: pass
|
| 102 |
+
|
| 103 |
+
_thread = None
|
| 104 |
+
def start():
|
| 105 |
+
global _thread
|
| 106 |
+
if _thread and _thread.is_alive(): return "Already running!"
|
| 107 |
+
_thread = threading.Thread(target=train, daemon=True); _thread.start()
|
| 108 |
+
return "LOCAL PC training started on A100!"
|
| 109 |
+
|
| 110 |
+
with gr.Blocks(title="PC-SHO-DLM Local PC") as demo:
|
| 111 |
+
gr.Markdown("# PC-SHO-DLM: LOCAL PC Training (A100)")
|
| 112 |
+
with gr.Row():
|
| 113 |
+
btn = gr.Button("Start Training", variant="primary")
|
| 114 |
+
st = gr.Textbox(label="Status", value="Idle")
|
| 115 |
+
log = gr.Textbox(label="Log", lines=25, max_lines=50)
|
| 116 |
+
btn.click(start, outputs=st)
|
| 117 |
+
refresh = gr.Button("Refresh"); refresh.click(lambda: "\n".join(LOG[-50:]), outputs=log); refresh.click(lambda: STATUS, outputs=st)
|
| 118 |
+
timer = gr.Timer(5); timer.tick(lambda: "\n".join(LOG[-50:]), outputs=log); timer.tick(lambda: STATUS, outputs=st)
|
| 119 |
+
|
| 120 |
+
demo.launch()
|
app_local_pc_wiki.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM LOCAL PC — The mode that hit loss 1.146. WikiText-103 in memory.
|
| 2 |
+
Settle first, THEN update params from converged errors. Envelope theorem path."""
|
| 3 |
+
import json, os, sys, threading, time
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import torch, torch.nn.functional as F
|
| 6 |
+
from torch.utils.data import DataLoader, Dataset
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 9 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters
|
| 10 |
+
|
| 11 |
+
class CharDS(Dataset):
|
| 12 |
+
def __init__(self, text, sl):
|
| 13 |
+
self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 14 |
+
self.n = max(1,(len(self.data)-sl)//sl)
|
| 15 |
+
def __len__(self): return self.n
|
| 16 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 17 |
+
|
| 18 |
+
LOG, STATUS = [], "Idle"
|
| 19 |
+
|
| 20 |
+
def train():
|
| 21 |
+
global STATUS, LOG
|
| 22 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 23 |
+
LOG = [f"PC-SHO-DLM LOCAL PC | Device: {dev}"]
|
| 24 |
+
if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 25 |
+
|
| 26 |
+
cfg = PCSHOConfig(
|
| 27 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048,
|
| 28 |
+
n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 29 |
+
# v2 optimizations (tuned)
|
| 30 |
+
mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3,
|
| 31 |
+
homeostatic_target=1.0, homeostatic_rate=0.001, homeostatic_rho_max=0.03,
|
| 32 |
+
lateral_inhibition=0.001,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
STATUS = "Loading WikiText-103 into memory..."
|
| 36 |
+
from datasets import load_dataset
|
| 37 |
+
ds = load_dataset("wikitext", "wikitext-103-raw-v1", split="train")
|
| 38 |
+
dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 39 |
+
train_text = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000]
|
| 40 |
+
val_text = "\n".join([r["text"] for r in dv if r["text"].strip()])
|
| 41 |
+
train_ds = CharDS(train_text, cfg.max_seq_len); val_ds = CharDS(val_text, cfg.max_seq_len)
|
| 42 |
+
LOG.append(f"Data: {len(train_text):,} train, {len(val_text):,} val chars IN MEMORY")
|
| 43 |
+
|
| 44 |
+
model = PCSHODLM(cfg).to(dev); model.train()
|
| 45 |
+
n_params = count_parameters(model)
|
| 46 |
+
LOG.append(f"Model: {n_params:,} params")
|
| 47 |
+
LOG.append(f"Mode: LOCAL PC (settle THEN update — envelope theorem path)")
|
| 48 |
+
LOG.append(f"This is the mode that hit loss 1.146 on v1")
|
| 49 |
+
|
| 50 |
+
# LOCAL mode: settle first, then update params
|
| 51 |
+
updater = LocalParameterUpdater(model, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5)
|
| 52 |
+
tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True)
|
| 53 |
+
vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True)
|
| 54 |
+
|
| 55 |
+
STATUS = "Training LOCAL PC..."
|
| 56 |
+
LOG.append(f"\n{'='*60}\nLOCAL PC | {n_params:,} params | settle then update\n{'='*60}")
|
| 57 |
+
step, start, mx = 0, time.time(), 10000
|
| 58 |
+
K_max = cfg.n_settling_steps
|
| 59 |
+
|
| 60 |
+
while step < mx:
|
| 61 |
+
for batch in tl:
|
| 62 |
+
if step >= mx: break
|
| 63 |
+
x0 = batch["input_ids"].to(dev)
|
| 64 |
+
|
| 65 |
+
# Curriculum K
|
| 66 |
+
K_warmup = min(2000, mx // 3)
|
| 67 |
+
K_curr = max(1, int(K_max * min(1.0, step / K_warmup)))
|
| 68 |
+
model.config.n_settling_steps = K_curr
|
| 69 |
+
|
| 70 |
+
result = updater.step({"input_ids": x0})
|
| 71 |
+
step += 1
|
| 72 |
+
|
| 73 |
+
loss = result.get("loss", 0); energies = result.get("energies", [])
|
| 74 |
+
stat = result.get("stationarity", 0)
|
| 75 |
+
|
| 76 |
+
if step % 100 == 0:
|
| 77 |
+
el = time.time()-start; tps = step*64*cfg.max_seq_len/el
|
| 78 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 79 |
+
rho = f"[{model.layer_rho[0]:.4f}..{model.layer_rho[-1]:.4f}]"
|
| 80 |
+
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")
|
| 81 |
+
if step % 2000 == 0:
|
| 82 |
+
model.eval(); tl2,tt2=0.,0
|
| 83 |
+
with torch.no_grad():
|
| 84 |
+
for vb in vl:
|
| 85 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 86 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 87 |
+
if tt2>100000: break
|
| 88 |
+
LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); model.train()
|
| 89 |
+
|
| 90 |
+
model.config.n_settling_steps = K_max; model.eval(); tl2,tt2=0.,0
|
| 91 |
+
with torch.no_grad():
|
| 92 |
+
for vb in vl:
|
| 93 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 94 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 95 |
+
if tt2>200000: break
|
| 96 |
+
LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s | Val: {tl2/max(1,tt2):.4f}")
|
| 97 |
+
STATUS = "Complete!"
|
| 98 |
+
os.makedirs("results",exist_ok=True)
|
| 99 |
+
torch.save({"model":model.state_dict(),"config":cfg},"results/local_pc_wiki.pt")
|
| 100 |
+
|
| 101 |
+
_t = None
|
| 102 |
+
def start():
|
| 103 |
+
global _t
|
| 104 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 105 |
+
_t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!"
|
| 106 |
+
|
| 107 |
+
with gr.Blocks(title="Local PC Wiki") as demo:
|
| 108 |
+
gr.Markdown("# PC-SHO-DLM LOCAL PC — WikiText-103 in memory")
|
| 109 |
+
gr.Markdown("Settle THEN update (envelope theorem). The mode that hit loss 1.146.")
|
| 110 |
+
with gr.Row():
|
| 111 |
+
btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle")
|
| 112 |
+
log=gr.Textbox(label="Log",lines=35); btn.click(start,outputs=st)
|
| 113 |
+
r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-70:]),outputs=log); r.click(lambda:STATUS,outputs=st)
|
| 114 |
+
t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-70:]),outputs=log); t.tick(lambda:STATUS,outputs=st)
|
| 115 |
+
demo.launch()
|
app_mdlm_baseline.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MDLM BASELINE — Run the official MDLM code on text8 for reference numbers."""
|
| 2 |
+
import os, sys, subprocess, threading, time
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
LOG, STATUS = [], "Idle"
|
| 6 |
+
|
| 7 |
+
def train():
|
| 8 |
+
global STATUS, LOG
|
| 9 |
+
LOG = ["MDLM Official Baseline — text8"]
|
| 10 |
+
LOG.append("Setting up MDLM from kuleshov-group/mdlm...")
|
| 11 |
+
|
| 12 |
+
STATUS = "Installing dependencies..."
|
| 13 |
+
|
| 14 |
+
# Clone MDLM
|
| 15 |
+
if not os.path.exists("/home/user/mdlm"):
|
| 16 |
+
r = subprocess.run(["git", "clone", "https://github.com/kuleshov-group/mdlm.git", "/home/user/mdlm"],
|
| 17 |
+
capture_output=True, text=True)
|
| 18 |
+
LOG.append(f"Clone: {r.stdout[-200:] if r.stdout else r.stderr[-200:]}")
|
| 19 |
+
|
| 20 |
+
# Install deps
|
| 21 |
+
deps = ["hydra-core", "omegaconf", "lightning", "einops", "transformers", "datasets", "wandb", "rich", "timm"]
|
| 22 |
+
for dep in deps:
|
| 23 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "-q", dep], capture_output=True)
|
| 24 |
+
LOG.append("Dependencies installed")
|
| 25 |
+
|
| 26 |
+
# Check GPU
|
| 27 |
+
import torch
|
| 28 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 29 |
+
LOG.append(f"Device: {dev}")
|
| 30 |
+
if dev == "cuda":
|
| 31 |
+
LOG.append(f"GPU: {torch.cuda.get_device_name()}")
|
| 32 |
+
|
| 33 |
+
STATUS = "Training MDLM on text8..."
|
| 34 |
+
LOG.append("\nStarting MDLM training on text8 (character-level)...")
|
| 35 |
+
LOG.append("Config: small model (768d, 12 layers, 12 heads), seq_len=256")
|
| 36 |
+
|
| 37 |
+
# Run MDLM training
|
| 38 |
+
env = os.environ.copy()
|
| 39 |
+
env["WANDB_MODE"] = "disabled"
|
| 40 |
+
|
| 41 |
+
cmd = [
|
| 42 |
+
sys.executable, "-u", "-m", "main",
|
| 43 |
+
"loader.batch_size=64",
|
| 44 |
+
"loader.eval_batch_size=64",
|
| 45 |
+
"model=small",
|
| 46 |
+
"data=text8",
|
| 47 |
+
"parameterization=subs",
|
| 48 |
+
"model.length=256",
|
| 49 |
+
"trainer.max_steps=10000",
|
| 50 |
+
"wandb.name=mdlm-text8-baseline",
|
| 51 |
+
"eval.compute_generative_perplexity=False",
|
| 52 |
+
"checkpointing.save_dir=/home/user/mdlm/checkpoints",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
LOG.append(f"Command: {' '.join(cmd)}")
|
| 56 |
+
|
| 57 |
+
process = subprocess.Popen(
|
| 58 |
+
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
| 59 |
+
text=True, bufsize=1, cwd="/home/user/mdlm", env=env
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
for line in iter(process.stdout.readline, ''):
|
| 63 |
+
line = line.strip()
|
| 64 |
+
if line:
|
| 65 |
+
LOG.append(line)
|
| 66 |
+
# Extract loss from lightning output
|
| 67 |
+
if 'loss' in line.lower() or 'step' in line.lower() or 'epoch' in line.lower() or 'val' in line.lower():
|
| 68 |
+
pass # already appended
|
| 69 |
+
|
| 70 |
+
process.wait()
|
| 71 |
+
LOG.append(f"\nMDLM training finished with exit code {process.returncode}")
|
| 72 |
+
STATUS = "Complete!"
|
| 73 |
+
|
| 74 |
+
_t = None
|
| 75 |
+
def start():
|
| 76 |
+
global _t
|
| 77 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 78 |
+
_t = threading.Thread(target=train, daemon=True); _t.start()
|
| 79 |
+
return "MDLM baseline started!"
|
| 80 |
+
|
| 81 |
+
with gr.Blocks(title="MDLM Baseline") as demo:
|
| 82 |
+
gr.Markdown("# MDLM Official Baseline — text8 (A100)")
|
| 83 |
+
gr.Markdown("Running the official NeurIPS 2024 MDLM code for reference numbers")
|
| 84 |
+
with gr.Row():
|
| 85 |
+
btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle")
|
| 86 |
+
log=gr.Textbox(label="Log",lines=35)
|
| 87 |
+
btn.click(start, outputs=st)
|
| 88 |
+
r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-70:]),outputs=log); r.click(lambda:STATUS,outputs=st)
|
| 89 |
+
t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-70:]),outputs=log); t.tick(lambda:STATUS,outputs=st)
|
| 90 |
+
demo.launch()
|
app_optimized.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PC-SHO-DLM v2: OPTIMIZED Training on A100
|
| 3 |
+
All Tier 1+2 optimizations enabled:
|
| 4 |
+
- Spectral preconditioning (per-element precision dynamics)
|
| 5 |
+
- Curriculum over K (ramp settling steps)
|
| 6 |
+
- Temporal hierarchy (per-layer mass/damping)
|
| 7 |
+
- Homeostatic plasticity (adaptive anchoring)
|
| 8 |
+
- Linear attention in settling loop
|
| 9 |
+
- Lateral inhibition (competitive token settling)
|
| 10 |
+
- Adaptive two-timescale ratio (for unified mode)
|
| 11 |
+
|
| 12 |
+
Trains on massive streaming data from HuggingFace.
|
| 13 |
+
"""
|
| 14 |
+
import json, os, sys, threading, time, math
|
| 15 |
+
import gradio as gr
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from torch.utils.data import DataLoader, Dataset, IterableDataset
|
| 19 |
+
|
| 20 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 21 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters
|
| 22 |
+
|
| 23 |
+
# =============================================================================
|
| 24 |
+
# Streaming Dataset — handles terabytes via HF datasets streaming
|
| 25 |
+
# =============================================================================
|
| 26 |
+
|
| 27 |
+
class StreamingCharDataset(IterableDataset):
|
| 28 |
+
"""Streams text from HuggingFace datasets, encodes as bytes on the fly."""
|
| 29 |
+
def __init__(self, dataset_name, config_name, split, seq_len, vocab_size=257, max_tokens=None):
|
| 30 |
+
self.dataset_name = dataset_name
|
| 31 |
+
self.config_name = config_name
|
| 32 |
+
self.split = split
|
| 33 |
+
self.seq_len = seq_len
|
| 34 |
+
self.vocab_size = vocab_size
|
| 35 |
+
self.max_tokens = max_tokens
|
| 36 |
+
|
| 37 |
+
def __iter__(self):
|
| 38 |
+
from datasets import load_dataset
|
| 39 |
+
ds = load_dataset(self.dataset_name, self.config_name, split=self.split, streaming=True)
|
| 40 |
+
buffer = []
|
| 41 |
+
total = 0
|
| 42 |
+
for item in ds:
|
| 43 |
+
text = item.get("text", "")
|
| 44 |
+
if not text.strip():
|
| 45 |
+
continue
|
| 46 |
+
encoded = [min(b + 1, self.vocab_size - 1) for b in text.encode("utf-8")]
|
| 47 |
+
buffer.extend(encoded)
|
| 48 |
+
while len(buffer) >= self.seq_len:
|
| 49 |
+
chunk = buffer[:self.seq_len]
|
| 50 |
+
buffer = buffer[self.seq_len:]
|
| 51 |
+
total += self.seq_len
|
| 52 |
+
if self.max_tokens and total > self.max_tokens:
|
| 53 |
+
return
|
| 54 |
+
yield {"input_ids": torch.tensor(chunk, dtype=torch.long)}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class CharDS(Dataset):
|
| 58 |
+
def __init__(self, text, seq_len):
|
| 59 |
+
self.seq_len = seq_len
|
| 60 |
+
self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 61 |
+
self.n = max(1, (len(self.data)-seq_len)//seq_len)
|
| 62 |
+
def __len__(self): return self.n
|
| 63 |
+
def __getitem__(self, i):
|
| 64 |
+
return {"input_ids": self.data[i*self.seq_len:(i+1)*self.seq_len]}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# =============================================================================
|
| 68 |
+
# Training
|
| 69 |
+
# =============================================================================
|
| 70 |
+
|
| 71 |
+
LOG = []
|
| 72 |
+
STATUS = "Idle"
|
| 73 |
+
|
| 74 |
+
def train():
|
| 75 |
+
global STATUS, LOG
|
| 76 |
+
LOG = ["PC-SHO-DLM v2 — OPTIMIZED Training"]
|
| 77 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 78 |
+
LOG.append(f"Device: {device}")
|
| 79 |
+
if device == "cuda":
|
| 80 |
+
LOG.append(f"GPU: {torch.cuda.get_device_name()}")
|
| 81 |
+
LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 82 |
+
|
| 83 |
+
# Optimized config
|
| 84 |
+
config = PCSHOConfig(
|
| 85 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8,
|
| 86 |
+
n_layers=12, d_ff=2048, n_diffusion_steps=128, n_settling_steps=6,
|
| 87 |
+
mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 88 |
+
# Temporal hierarchy
|
| 89 |
+
mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3,
|
| 90 |
+
# Homeostatic
|
| 91 |
+
homeostatic_target=1.0, homeostatic_rate=0.001,
|
| 92 |
+
# Lateral inhibition
|
| 93 |
+
lateral_inhibition=0.01, settling_budget_fraction=0.5,
|
| 94 |
+
)
|
| 95 |
+
n_params = count_parameters(PCSHODLM(config))
|
| 96 |
+
LOG.append(f"Model: {n_params:,} params (d={config.d_model}, L={config.n_layers})")
|
| 97 |
+
LOG.append("Optimizations: spectral precond, curriculum-K, temporal hierarchy,")
|
| 98 |
+
LOG.append(" homeostatic plasticity, linear-attn settling, lateral inhibition")
|
| 99 |
+
|
| 100 |
+
# === DATA: Stream from multiple sources ===
|
| 101 |
+
STATUS = "Loading data (streaming)..."
|
| 102 |
+
LOG.append("\nData sources (streaming):")
|
| 103 |
+
|
| 104 |
+
# Use WikiText for validation (small, fixed)
|
| 105 |
+
from datasets import load_dataset
|
| 106 |
+
dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 107 |
+
val_text = "\n".join([r["text"] for r in dv if r["text"].strip()])
|
| 108 |
+
val_ds = CharDS(val_text, config.max_seq_len)
|
| 109 |
+
LOG.append(f" Val: WikiText-103 validation ({len(val_text):,} chars)")
|
| 110 |
+
|
| 111 |
+
# Stream from FineWeb-10BT (10 billion tokens) — ~50GB of high-quality web text
|
| 112 |
+
# Falls back to WikiText if FineWeb unavailable
|
| 113 |
+
try:
|
| 114 |
+
train_ds = StreamingCharDataset(
|
| 115 |
+
"HuggingFaceFW/fineweb", "sample-10BT", "train",
|
| 116 |
+
seq_len=config.max_seq_len, max_tokens=2_000_000_000 # 2B tokens
|
| 117 |
+
)
|
| 118 |
+
LOG.append(f" Train: FineWeb-10BT streaming (2B tokens)")
|
| 119 |
+
except Exception as e:
|
| 120 |
+
LOG.append(f" FineWeb failed ({e}), falling back to WikiText-103")
|
| 121 |
+
train_ds = StreamingCharDataset(
|
| 122 |
+
"wikitext", "wikitext-103-raw-v1", "train",
|
| 123 |
+
seq_len=config.max_seq_len, max_tokens=500_000_000
|
| 124 |
+
)
|
| 125 |
+
LOG.append(f" Train: WikiText-103 streaming (500M tokens)")
|
| 126 |
+
|
| 127 |
+
model = PCSHODLM(config).to(device)
|
| 128 |
+
model.train()
|
| 129 |
+
|
| 130 |
+
# Local PC training with all optimizations
|
| 131 |
+
updater = LocalParameterUpdater(model, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5)
|
| 132 |
+
tl = DataLoader(train_ds, batch_size=64, num_workers=4, pin_memory=True)
|
| 133 |
+
vl = DataLoader(val_ds, batch_size=64, shuffle=False, num_workers=2, pin_memory=True)
|
| 134 |
+
|
| 135 |
+
STATUS = "Training OPTIMIZED Local PC..."
|
| 136 |
+
LOG.append(f"\n{'='*60}")
|
| 137 |
+
LOG.append(f"Training: OPTIMIZED Local PC | {n_params:,} params")
|
| 138 |
+
LOG.append(f"{'='*60}")
|
| 139 |
+
|
| 140 |
+
step, start, max_steps = 0, time.time(), 10000
|
| 141 |
+
log_data = {"steps": [], "losses": [], "energies": [], "K_values": []}
|
| 142 |
+
K_max = config.n_settling_steps
|
| 143 |
+
|
| 144 |
+
for batch in tl:
|
| 145 |
+
if step >= max_steps:
|
| 146 |
+
break
|
| 147 |
+
x_0 = batch["input_ids"].to(device)
|
| 148 |
+
|
| 149 |
+
# CURRICULUM OVER K
|
| 150 |
+
K_warmup = min(2000, max_steps // 3)
|
| 151 |
+
K_curr = max(1, int(K_max * min(1.0, step / K_warmup)))
|
| 152 |
+
model.config.n_settling_steps = K_curr
|
| 153 |
+
|
| 154 |
+
result = updater.step({"input_ids": x_0})
|
| 155 |
+
step += 1
|
| 156 |
+
|
| 157 |
+
loss = result.get("loss", 0)
|
| 158 |
+
energies = result.get("energies", [])
|
| 159 |
+
|
| 160 |
+
if step % 100 == 0:
|
| 161 |
+
elapsed = time.time() - start
|
| 162 |
+
tps = step * 64 * config.max_seq_len / elapsed
|
| 163 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 164 |
+
rho_str = f"[{model.layer_rho[0]:.4f}..{model.layer_rho[-1]:.4f}]"
|
| 165 |
+
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"
|
| 166 |
+
LOG.append(msg)
|
| 167 |
+
log_data["steps"].append(step)
|
| 168 |
+
log_data["losses"].append(loss)
|
| 169 |
+
log_data["energies"].append(energies[-1] if energies else 0)
|
| 170 |
+
log_data["K_values"].append(K_curr)
|
| 171 |
+
|
| 172 |
+
if step % 2000 == 0:
|
| 173 |
+
model.eval()
|
| 174 |
+
tl2, tt2 = 0.0, 0
|
| 175 |
+
with torch.no_grad():
|
| 176 |
+
for vb in vl:
|
| 177 |
+
vx = vb["input_ids"].to(device)
|
| 178 |
+
vo = model(vx)
|
| 179 |
+
nm = vo["mask"].sum().item()
|
| 180 |
+
if nm > 0:
|
| 181 |
+
tl2 += vo["loss"].item() * nm
|
| 182 |
+
tt2 += nm
|
| 183 |
+
if tt2 > 100000:
|
| 184 |
+
break
|
| 185 |
+
vl2 = tl2 / max(1, tt2)
|
| 186 |
+
LOG.append(f" --> Val loss: {vl2:.4f}")
|
| 187 |
+
log_data.setdefault("val", []).append((step, vl2))
|
| 188 |
+
model.train()
|
| 189 |
+
|
| 190 |
+
# Restore full K for final eval
|
| 191 |
+
model.config.n_settling_steps = K_max
|
| 192 |
+
model.eval()
|
| 193 |
+
tl2, tt2 = 0.0, 0
|
| 194 |
+
with torch.no_grad():
|
| 195 |
+
for vb in vl:
|
| 196 |
+
vx = vb["input_ids"].to(device)
|
| 197 |
+
vo = model(vx)
|
| 198 |
+
nm = vo["mask"].sum().item()
|
| 199 |
+
if nm > 0:
|
| 200 |
+
tl2 += vo["loss"].item() * nm
|
| 201 |
+
tt2 += nm
|
| 202 |
+
if tt2 > 200000:
|
| 203 |
+
break
|
| 204 |
+
fv = tl2 / max(1, tt2)
|
| 205 |
+
log_data["final_val"] = fv
|
| 206 |
+
elapsed = time.time() - start
|
| 207 |
+
LOG.append(f"\nDONE: {step} steps in {elapsed:.0f}s | Final val: {fv:.4f}")
|
| 208 |
+
STATUS = "Complete!"
|
| 209 |
+
|
| 210 |
+
os.makedirs("results", exist_ok=True)
|
| 211 |
+
torch.save({"model": model.state_dict(), "config": config, "log": log_data}, "results/optimized_pc_10k.pt")
|
| 212 |
+
with open("results/optimized_log.json", "w") as f:
|
| 213 |
+
json.dump(log_data, f)
|
| 214 |
+
|
| 215 |
+
try:
|
| 216 |
+
from huggingface_hub import HfApi
|
| 217 |
+
HfApi().upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-optimized",
|
| 218 |
+
repo_type="space", path_in_repo="results")
|
| 219 |
+
LOG.append("Results uploaded!")
|
| 220 |
+
except Exception as e:
|
| 221 |
+
LOG.append(f"Upload: {e}")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
_thread = None
|
| 225 |
+
def start():
|
| 226 |
+
global _thread
|
| 227 |
+
if _thread and _thread.is_alive():
|
| 228 |
+
return "Already running!"
|
| 229 |
+
_thread = threading.Thread(target=train, daemon=True)
|
| 230 |
+
_thread.start()
|
| 231 |
+
return "OPTIMIZED training started on A100!"
|
| 232 |
+
|
| 233 |
+
with gr.Blocks(title="PC-SHO-DLM v2 Optimized") as demo:
|
| 234 |
+
gr.Markdown("# PC-SHO-DLM v2: OPTIMIZED Local PC Training (A100)")
|
| 235 |
+
gr.Markdown("All Tier 1+2 optimizations: spectral precond, curriculum-K, temporal hierarchy, homeostasis, linear-attn settling, lateral inhibition")
|
| 236 |
+
with gr.Row():
|
| 237 |
+
btn = gr.Button("Start Training", variant="primary")
|
| 238 |
+
st = gr.Textbox(label="Status", value="Idle")
|
| 239 |
+
log = gr.Textbox(label="Log", lines=30, max_lines=60)
|
| 240 |
+
btn.click(start, outputs=st)
|
| 241 |
+
refresh = gr.Button("Refresh")
|
| 242 |
+
refresh.click(lambda: "\n".join(LOG[-60:]), outputs=log)
|
| 243 |
+
refresh.click(lambda: STATUS, outputs=st)
|
| 244 |
+
timer = gr.Timer(5)
|
| 245 |
+
timer.tick(lambda: "\n".join(LOG[-60:]), outputs=log)
|
| 246 |
+
timer.tick(lambda: STATUS, outputs=st)
|
| 247 |
+
|
| 248 |
+
demo.launch()
|
app_unified.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM: UNIFIED Training on A100 — Settling IS Learning."""
|
| 2 |
+
import json, os, sys, threading, time
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch.utils.data import DataLoader, Dataset
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 9 |
+
from model import PCSHODLM, PCSHOConfig, count_parameters
|
| 10 |
+
|
| 11 |
+
class CharDS(Dataset):
|
| 12 |
+
def __init__(self, text, seq_len):
|
| 13 |
+
self.seq_len = seq_len
|
| 14 |
+
self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 15 |
+
self.n = max(1, (len(self.data)-seq_len)//seq_len)
|
| 16 |
+
def __len__(self): return self.n
|
| 17 |
+
def __getitem__(self, i):
|
| 18 |
+
return {"input_ids": self.data[i*self.seq_len:(i+1)*self.seq_len]}
|
| 19 |
+
|
| 20 |
+
LOG = []
|
| 21 |
+
STATUS = "Idle"
|
| 22 |
+
|
| 23 |
+
def train():
|
| 24 |
+
global STATUS, LOG
|
| 25 |
+
LOG = ["Starting UNIFIED training on A100..."]
|
| 26 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 27 |
+
LOG.append(f"Device: {device}")
|
| 28 |
+
if device == "cuda":
|
| 29 |
+
LOG.append(f"GPU: {torch.cuda.get_device_name()}")
|
| 30 |
+
LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 31 |
+
|
| 32 |
+
config = PCSHOConfig(
|
| 33 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8,
|
| 34 |
+
n_layers=12, d_ff=2048, n_diffusion_steps=128, n_settling_steps=6,
|
| 35 |
+
mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 36 |
+
)
|
| 37 |
+
LOG.append(f"Model: {count_parameters(PCSHODLM(config)):,} params")
|
| 38 |
+
|
| 39 |
+
STATUS = "Loading data..."
|
| 40 |
+
from datasets import load_dataset
|
| 41 |
+
ds = load_dataset("wikitext","wikitext-103-raw-v1",split="train")
|
| 42 |
+
dv = load_dataset("wikitext","wikitext-103-raw-v1",split="validation")
|
| 43 |
+
tt = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000]
|
| 44 |
+
vt = "\n".join([r["text"] for r in dv if r["text"].strip()])
|
| 45 |
+
train_ds, val_ds = CharDS(tt,config.max_seq_len), CharDS(vt,config.max_seq_len)
|
| 46 |
+
LOG.append(f"Data: {len(tt):,} train, {len(vt):,} val chars")
|
| 47 |
+
|
| 48 |
+
model = PCSHODLM(config).to(device)
|
| 49 |
+
model.train()
|
| 50 |
+
param_lr_scale = 0.005
|
| 51 |
+
|
| 52 |
+
tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True)
|
| 53 |
+
vl = DataLoader(val_ds, batch_size=64, shuffle=False, num_workers=2, pin_memory=True)
|
| 54 |
+
|
| 55 |
+
STATUS = "Training UNIFIED..."
|
| 56 |
+
LOG.append(f"\n{'='*60}\nMode: UNIFIED (settling=learning) | Params: {count_parameters(model):,}\n{'='*60}")
|
| 57 |
+
step, start, max_steps = 0, time.time(), 10000
|
| 58 |
+
log_data = {"steps":[],"losses":[],"energies":[]}
|
| 59 |
+
|
| 60 |
+
while step < max_steps:
|
| 61 |
+
for batch in tl:
|
| 62 |
+
if step >= max_steps: break
|
| 63 |
+
x_0 = batch["input_ids"].to(device)
|
| 64 |
+
B, S = x_0.shape
|
| 65 |
+
t = torch.randint(1, config.n_diffusion_steps+1, (B,), device=device)
|
| 66 |
+
x_t, mask = model.schedule.corrupt(x_0, t, config.mask_token_id)
|
| 67 |
+
h_0 = model.embed_input(x_t, t)
|
| 68 |
+
h_init = model.amortized_forward_pass(h_0)
|
| 69 |
+
h_s, _, energies = model.unified_settle(h_init, x_0, mask, t, param_lr_scale=param_lr_scale)
|
| 70 |
+
with torch.no_grad():
|
| 71 |
+
logits = model.readout(model.readout_norm(h_s[-1]))
|
| 72 |
+
ml, mt = logits[mask], x_0[mask]
|
| 73 |
+
loss = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0
|
| 74 |
+
|
| 75 |
+
step += 1
|
| 76 |
+
if step % 100 == 0:
|
| 77 |
+
elapsed = time.time()-start
|
| 78 |
+
tps = step*64*config.max_seq_len/elapsed
|
| 79 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 80 |
+
msg = f"[unified] Step {step:6d} | Loss: {loss:.4f} | Energy: {e} | Tok/s: {tps:.0f} | {elapsed:.0f}s"
|
| 81 |
+
LOG.append(msg); log_data["steps"].append(step); log_data["losses"].append(loss); log_data["energies"].append(energies[-1] if energies else 0)
|
| 82 |
+
if step % 2000 == 0:
|
| 83 |
+
model.eval()
|
| 84 |
+
tl2,tt2=0.0,0
|
| 85 |
+
with torch.no_grad():
|
| 86 |
+
for vb in vl:
|
| 87 |
+
vx=vb["input_ids"].to(device); vo=model(vx); nm=vo["mask"].sum().item()
|
| 88 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 89 |
+
if tt2>100000: break
|
| 90 |
+
vl2=tl2/max(1,tt2); LOG.append(f" --> [unified] Val loss: {vl2:.4f}"); log_data.setdefault("val",[]).append((step,vl2))
|
| 91 |
+
model.train()
|
| 92 |
+
|
| 93 |
+
model.eval()
|
| 94 |
+
tl2,tt2=0.0,0
|
| 95 |
+
with torch.no_grad():
|
| 96 |
+
for vb in vl:
|
| 97 |
+
vx=vb["input_ids"].to(device); vo=model(vx); nm=vo["mask"].sum().item()
|
| 98 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 99 |
+
if tt2>200000: break
|
| 100 |
+
fv=tl2/max(1,tt2); log_data["final_val"]=fv
|
| 101 |
+
LOG.append(f"DONE: {step} steps in {time.time()-start:.0f}s | Final val: {fv:.4f}")
|
| 102 |
+
STATUS = "Complete!"
|
| 103 |
+
|
| 104 |
+
os.makedirs("results",exist_ok=True)
|
| 105 |
+
torch.save({"model":model.state_dict(),"config":config,"log":log_data},"results/unified_10k.pt")
|
| 106 |
+
with open("results/unified_log.json","w") as f: json.dump(log_data,f)
|
| 107 |
+
try:
|
| 108 |
+
from huggingface_hub import HfApi
|
| 109 |
+
HfApi().upload_folder(folder_path="results",repo_id="zotowata/pc-sho-dlm-unified",repo_type="space",path_in_repo="results")
|
| 110 |
+
LOG.append("Results uploaded!")
|
| 111 |
+
except: pass
|
| 112 |
+
|
| 113 |
+
_thread = None
|
| 114 |
+
def start():
|
| 115 |
+
global _thread
|
| 116 |
+
if _thread and _thread.is_alive(): return "Already running!"
|
| 117 |
+
_thread = threading.Thread(target=train, daemon=True); _thread.start()
|
| 118 |
+
return "UNIFIED training started on A100!"
|
| 119 |
+
|
| 120 |
+
with gr.Blocks(title="PC-SHO-DLM Unified") as demo:
|
| 121 |
+
gr.Markdown("# PC-SHO-DLM: UNIFIED Training — Settling IS Learning (A100)")
|
| 122 |
+
with gr.Row():
|
| 123 |
+
btn = gr.Button("Start Training", variant="primary")
|
| 124 |
+
st = gr.Textbox(label="Status", value="Idle")
|
| 125 |
+
log = gr.Textbox(label="Log", lines=25, max_lines=50)
|
| 126 |
+
btn.click(start, outputs=st)
|
| 127 |
+
refresh = gr.Button("Refresh"); refresh.click(lambda: "\n".join(LOG[-50:]), outputs=log); refresh.click(lambda: STATUS, outputs=st)
|
| 128 |
+
timer = gr.Timer(5); timer.tick(lambda: "\n".join(LOG[-50:]), outputs=log); timer.tick(lambda: STATUS, outputs=st)
|
| 129 |
+
|
| 130 |
+
demo.launch()
|
app_unified_big.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM UNIFIED BIG — 350M params, FineWeb streaming, lambda=500, A100."""
|
| 2 |
+
import json, os, sys, threading, time, math
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch, torch.nn.functional as F
|
| 5 |
+
from torch.utils.data import DataLoader, IterableDataset, Dataset
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 8 |
+
from model import PCSHODLM, PCSHOConfig, count_parameters
|
| 9 |
+
|
| 10 |
+
class StreamDS(IterableDataset):
|
| 11 |
+
"""Streams from HuggingFace — handles billions of tokens without loading into memory."""
|
| 12 |
+
def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None):
|
| 13 |
+
self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok
|
| 14 |
+
def __iter__(self):
|
| 15 |
+
from datasets import load_dataset
|
| 16 |
+
ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True, trust_remote_code=True)
|
| 17 |
+
buf, tot = [], 0
|
| 18 |
+
for item in ds:
|
| 19 |
+
t = item.get("text", "")
|
| 20 |
+
if not t or not t.strip(): continue
|
| 21 |
+
buf.extend([min(b+1, self.voc-1) for b in t.encode("utf-8")])
|
| 22 |
+
while len(buf) >= self.seq_len:
|
| 23 |
+
yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)}
|
| 24 |
+
buf = buf[self.seq_len:]; tot += self.seq_len
|
| 25 |
+
if self.max_tok and tot > self.max_tok: return
|
| 26 |
+
|
| 27 |
+
class CharDS(Dataset):
|
| 28 |
+
def __init__(self, text, sl):
|
| 29 |
+
self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 30 |
+
self.n = max(1,(len(self.data)-sl)//sl)
|
| 31 |
+
def __len__(self): return self.n
|
| 32 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 33 |
+
|
| 34 |
+
LOG, STATUS = [], "Idle"
|
| 35 |
+
|
| 36 |
+
def train():
|
| 37 |
+
global STATUS, LOG
|
| 38 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 39 |
+
LOG = [f"PC-SHO-DLM UNIFIED BIG | {dev}"]
|
| 40 |
+
if dev == "cuda":
|
| 41 |
+
LOG.append(f"GPU: {torch.cuda.get_device_name()}")
|
| 42 |
+
LOG.append(f"VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 43 |
+
|
| 44 |
+
# 350M param model — biggest that fits on A100-80GB with batch 16
|
| 45 |
+
cfg = PCSHOConfig(
|
| 46 |
+
vocab_size=257, max_seq_len=512, d_model=1024, n_heads=16, n_layers=24, d_ff=4096,
|
| 47 |
+
n_diffusion_steps=128, n_settling_steps=4, mask_token_id=0, dropout=0.1,
|
| 48 |
+
feedback_rank=256, denoising_lambda=500.0,
|
| 49 |
+
mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3,
|
| 50 |
+
homeostatic_target=0.0, homeostatic_rate=0.0001,
|
| 51 |
+
homeostatic_rho_max=0.02, lateral_inhibition=0.0,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
model = PCSHODLM(cfg)
|
| 55 |
+
n_params = count_parameters(model)
|
| 56 |
+
LOG.append(f"Model: {n_params:,} params (d={cfg.d_model}, L={cfg.n_layers}, heads={cfg.n_heads})")
|
| 57 |
+
LOG.append(f"denoising_lambda={cfg.denoising_lambda}")
|
| 58 |
+
|
| 59 |
+
# Check if it fits
|
| 60 |
+
if n_params > 500_000_000:
|
| 61 |
+
LOG.append(f"WARNING: {n_params/1e6:.0f}M params may be tight on 80GB A100")
|
| 62 |
+
|
| 63 |
+
STATUS = "Loading data..."
|
| 64 |
+
|
| 65 |
+
# Validation: WikiText in memory
|
| 66 |
+
from datasets import load_dataset
|
| 67 |
+
dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 68 |
+
val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len)
|
| 69 |
+
LOG.append(f"Val: WikiText-103 ({len(val_ds)} samples)")
|
| 70 |
+
|
| 71 |
+
# Training: FineWeb-10BT streaming (billions of tokens)
|
| 72 |
+
train_ds = StreamDS("HuggingFaceFW/fineweb", "sample-10BT", "train",
|
| 73 |
+
cfg.max_seq_len, max_tok=10_000_000_000) # 10B tokens
|
| 74 |
+
LOG.append(f"Train: FineWeb-10BT streaming (10B tokens)")
|
| 75 |
+
|
| 76 |
+
model = model.to(dev)
|
| 77 |
+
model.train()
|
| 78 |
+
|
| 79 |
+
# Smaller batch for big model
|
| 80 |
+
batch_size = 16
|
| 81 |
+
tl = DataLoader(train_ds, batch_size=batch_size, num_workers=0)
|
| 82 |
+
vl = DataLoader(val_ds, batch_size=16, num_workers=0)
|
| 83 |
+
|
| 84 |
+
STATUS = "Training UNIFIED BIG..."
|
| 85 |
+
LOG.append(f"\n{'='*60}")
|
| 86 |
+
LOG.append(f"UNIFIED BIG | {n_params:,} params | FineWeb-10BT | lambda=500")
|
| 87 |
+
LOG.append(f"{'='*60}")
|
| 88 |
+
|
| 89 |
+
step, start, mx = 0, time.time(), 20000
|
| 90 |
+
K_max = cfg.n_settling_steps
|
| 91 |
+
param_lr_scale = 0.025
|
| 92 |
+
|
| 93 |
+
for batch in tl:
|
| 94 |
+
if step >= mx: break
|
| 95 |
+
x0 = batch["input_ids"].to(dev); B, S = x0.shape
|
| 96 |
+
|
| 97 |
+
# Curriculum K (start at 2 for big model)
|
| 98 |
+
K_curr = max(2, int(K_max * min(1.0, step / 1000)))
|
| 99 |
+
model.config.n_settling_steps = K_curr
|
| 100 |
+
|
| 101 |
+
t = torch.randint(1, cfg.n_diffusion_steps+1, (B,), device=dev)
|
| 102 |
+
x_t, mask = model.schedule.corrupt(x0, t, cfg.mask_token_id)
|
| 103 |
+
h0 = model.embed_input(x_t, t); h_init = model.amortized_forward_pass(h0)
|
| 104 |
+
h_s, _, energies = model.unified_settle(h_init, x0, mask, t, param_lr_scale=param_lr_scale)
|
| 105 |
+
|
| 106 |
+
# Adaptive two-timescale
|
| 107 |
+
if len(energies) >= 2 and energies[0] > 0:
|
| 108 |
+
e_ratio = energies[-1] / max(energies[0], 1e-8)
|
| 109 |
+
eff_rho_K = math.sqrt(max(e_ratio, 0.01))
|
| 110 |
+
param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - eff_rho_K) ** 2))
|
| 111 |
+
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
logits = model.readout(model.readout_norm(h_s[-1]))
|
| 114 |
+
ml, mt = logits[mask], x0[mask]
|
| 115 |
+
lv = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0
|
| 116 |
+
step += 1
|
| 117 |
+
|
| 118 |
+
if step % 50 == 0:
|
| 119 |
+
el = time.time()-start; tps = step*batch_size*cfg.max_seq_len/el
|
| 120 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 121 |
+
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")
|
| 122 |
+
if step % 2000 == 0:
|
| 123 |
+
model.eval(); tl2,tt2=0.,0
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
for vb in vl:
|
| 126 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 127 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 128 |
+
if tt2>50000: break
|
| 129 |
+
LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); model.train()
|
| 130 |
+
# Save checkpoint
|
| 131 |
+
os.makedirs("results",exist_ok=True)
|
| 132 |
+
torch.save({"model":model.state_dict(),"config":cfg,"step":step}, f"results/unified_big_step{step}.pt")
|
| 133 |
+
|
| 134 |
+
LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s")
|
| 135 |
+
STATUS = "Complete!"
|
| 136 |
+
os.makedirs("results",exist_ok=True)
|
| 137 |
+
torch.save({"model":model.state_dict(),"config":cfg}, "results/unified_big_final.pt")
|
| 138 |
+
|
| 139 |
+
_t = None
|
| 140 |
+
def start():
|
| 141 |
+
global _t
|
| 142 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 143 |
+
_t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!"
|
| 144 |
+
|
| 145 |
+
with gr.Blocks(title="Unified Big") as demo:
|
| 146 |
+
gr.Markdown("# PC-SHO-DLM UNIFIED BIG — 350M params, FineWeb-10BT (A100)")
|
| 147 |
+
with gr.Row():
|
| 148 |
+
btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle")
|
| 149 |
+
log=gr.Textbox(label="Log",lines=35); btn.click(start,outputs=st)
|
| 150 |
+
r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-70:]),outputs=log); r.click(lambda:STATUS,outputs=st)
|
| 151 |
+
t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-70:]),outputs=log); t.tick(lambda:STATUS,outputs=st)
|
| 152 |
+
demo.launch()
|
app_unified_wiki.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM UNIFIED — WikiText-103 in memory, all v2 optimizations, settling=learning."""
|
| 2 |
+
import json, os, sys, threading, time, math
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch, torch.nn.functional as F
|
| 5 |
+
from torch.utils.data import DataLoader, Dataset
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 8 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters
|
| 9 |
+
|
| 10 |
+
class CharDS(Dataset):
|
| 11 |
+
def __init__(self, text, sl):
|
| 12 |
+
self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 13 |
+
self.n = max(1,(len(self.data)-sl)//sl)
|
| 14 |
+
def __len__(self): return self.n
|
| 15 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 16 |
+
|
| 17 |
+
LOG, STATUS = [], "Idle"
|
| 18 |
+
|
| 19 |
+
def train():
|
| 20 |
+
global STATUS, LOG
|
| 21 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 22 |
+
LOG = [f"PC-SHO-DLM UNIFIED | Device: {dev}"]
|
| 23 |
+
if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 24 |
+
|
| 25 |
+
cfg = PCSHOConfig(
|
| 26 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048,
|
| 27 |
+
n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 28 |
+
mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3,
|
| 29 |
+
homeostatic_target=1.0, homeostatic_rate=0.001, homeostatic_rho_max=0.03,
|
| 30 |
+
lateral_inhibition=0.001, settling_budget_fraction=0.5,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
STATUS = "Loading WikiText-103 into memory..."
|
| 34 |
+
from datasets import load_dataset
|
| 35 |
+
ds = load_dataset("wikitext", "wikitext-103-raw-v1", split="train")
|
| 36 |
+
dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 37 |
+
train_text = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000]
|
| 38 |
+
val_text = "\n".join([r["text"] for r in dv if r["text"].strip()])
|
| 39 |
+
train_ds = CharDS(train_text, cfg.max_seq_len); val_ds = CharDS(val_text, cfg.max_seq_len)
|
| 40 |
+
LOG.append(f"Data: {len(train_text):,} train chars, {len(val_text):,} val chars IN MEMORY")
|
| 41 |
+
|
| 42 |
+
model = PCSHODLM(cfg).to(dev); model.train()
|
| 43 |
+
n_params = count_parameters(model)
|
| 44 |
+
LOG.append(f"Model: {n_params:,} params | Unified (settling=learning)")
|
| 45 |
+
LOG.append(f"Optimizations: spectral precond, curriculum-K, temporal hierarchy, homeostasis")
|
| 46 |
+
|
| 47 |
+
tl = DataLoader(train_ds, batch_size=64, shuffle=True, drop_last=True, num_workers=4, pin_memory=True)
|
| 48 |
+
vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True)
|
| 49 |
+
|
| 50 |
+
STATUS = "Training..."
|
| 51 |
+
LOG.append(f"\n{'='*60}\nUNIFIED | {n_params:,} params | settling=learning\n{'='*60}")
|
| 52 |
+
step, start, mx = 0, time.time(), 10000
|
| 53 |
+
K_max = cfg.n_settling_steps
|
| 54 |
+
param_lr_scale = 0.025 # theory-optimal starting value
|
| 55 |
+
|
| 56 |
+
while step < mx:
|
| 57 |
+
for batch in tl:
|
| 58 |
+
if step >= mx: break
|
| 59 |
+
x0 = batch["input_ids"].to(dev); B, S = x0.shape
|
| 60 |
+
|
| 61 |
+
# Curriculum K
|
| 62 |
+
K_warmup = min(2000, mx // 3)
|
| 63 |
+
K_curr = max(1, int(K_max * min(1.0, step / K_warmup)))
|
| 64 |
+
model.config.n_settling_steps = K_curr
|
| 65 |
+
|
| 66 |
+
t = torch.randint(1, cfg.n_diffusion_steps+1, (B,), device=dev)
|
| 67 |
+
x_t, mask = model.schedule.corrupt(x0, t, cfg.mask_token_id)
|
| 68 |
+
h0 = model.embed_input(x_t, t); h_init = model.amortized_forward_pass(h0)
|
| 69 |
+
h_s, _, energies = model.unified_settle(h_init, x0, mask, t, param_lr_scale=param_lr_scale)
|
| 70 |
+
|
| 71 |
+
# Adaptive two-timescale
|
| 72 |
+
if len(energies) >= 2 and energies[0] > 0:
|
| 73 |
+
e_ratio = energies[-1] / max(energies[0], 1e-8)
|
| 74 |
+
eff_rho_K = math.sqrt(max(e_ratio, 0.01))
|
| 75 |
+
param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - eff_rho_K) ** 2))
|
| 76 |
+
|
| 77 |
+
with torch.no_grad():
|
| 78 |
+
logits = model.readout(model.readout_norm(h_s[-1]))
|
| 79 |
+
ml, mt = logits[mask], x0[mask]
|
| 80 |
+
lv = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0
|
| 81 |
+
step += 1
|
| 82 |
+
|
| 83 |
+
if step % 100 == 0:
|
| 84 |
+
el = time.time()-start; tps = step*64*cfg.max_seq_len/el
|
| 85 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 86 |
+
rho = f"[{model.layer_rho[0]:.4f}..{model.layer_rho[-1]:.4f}]"
|
| 87 |
+
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")
|
| 88 |
+
if step % 2000 == 0:
|
| 89 |
+
model.eval(); tl2,tt2=0.,0
|
| 90 |
+
with torch.no_grad():
|
| 91 |
+
for vb in vl:
|
| 92 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 93 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 94 |
+
if tt2>100000: break
|
| 95 |
+
LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); model.train()
|
| 96 |
+
|
| 97 |
+
model.config.n_settling_steps = K_max; model.eval(); tl2,tt2=0.,0
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
for vb in vl:
|
| 100 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 101 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 102 |
+
if tt2>200000: break
|
| 103 |
+
LOG.append(f"\nDONE: {step} steps in {time.time()-start:.0f}s | Val: {tl2/max(1,tt2):.4f}")
|
| 104 |
+
STATUS = "Complete!"
|
| 105 |
+
os.makedirs("results",exist_ok=True)
|
| 106 |
+
torch.save({"model":model.state_dict(),"config":cfg},"results/unified_wiki.pt")
|
| 107 |
+
|
| 108 |
+
_t = None
|
| 109 |
+
def start():
|
| 110 |
+
global _t
|
| 111 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 112 |
+
_t = threading.Thread(target=train, daemon=True); _t.start(); return "Started!"
|
| 113 |
+
|
| 114 |
+
with gr.Blocks(title="Unified Wiki") as demo:
|
| 115 |
+
gr.Markdown("# PC-SHO-DLM UNIFIED — WikiText-103 in memory")
|
| 116 |
+
with gr.Row():
|
| 117 |
+
btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle")
|
| 118 |
+
log=gr.Textbox(label="Log",lines=30); btn.click(start,outputs=st)
|
| 119 |
+
r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-60:]),outputs=log); r.click(lambda:STATUS,outputs=st)
|
| 120 |
+
t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-60:]),outputs=log); t.tick(lambda:STATUS,outputs=st)
|
| 121 |
+
demo.launch()
|
app_v2_backprop.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM v2: BACKPROP BASELINE with all architectural optimizations.
|
| 2 |
+
Same optimized architecture (linear attn, temporal hierarchy, etc) but trained with standard backprop.
|
| 3 |
+
"""
|
| 4 |
+
import json, os, sys, threading, time
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import torch, torch.nn.functional as F
|
| 7 |
+
from torch.utils.data import DataLoader, IterableDataset, Dataset
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 10 |
+
from model import PCSHODLM, PCSHOConfig, count_parameters
|
| 11 |
+
|
| 12 |
+
class StreamDS(IterableDataset):
|
| 13 |
+
def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None):
|
| 14 |
+
self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok
|
| 15 |
+
def __iter__(self):
|
| 16 |
+
from datasets import load_dataset
|
| 17 |
+
ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True)
|
| 18 |
+
buf, tot = [], 0
|
| 19 |
+
for item in ds:
|
| 20 |
+
t = item.get("text","")
|
| 21 |
+
if not t.strip(): continue
|
| 22 |
+
buf.extend([min(b+1,self.voc-1) for b in t.encode("utf-8")])
|
| 23 |
+
while len(buf) >= self.seq_len:
|
| 24 |
+
yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)}
|
| 25 |
+
buf = buf[self.seq_len:]; tot += self.seq_len
|
| 26 |
+
if self.max_tok and tot > self.max_tok: return
|
| 27 |
+
|
| 28 |
+
class CharDS(Dataset):
|
| 29 |
+
def __init__(self, text, sl):
|
| 30 |
+
self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 31 |
+
self.n = max(1,(len(self.data)-sl)//sl)
|
| 32 |
+
def __len__(self): return self.n
|
| 33 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 34 |
+
|
| 35 |
+
LOG, STATUS = [], "Idle"
|
| 36 |
+
|
| 37 |
+
def train():
|
| 38 |
+
global STATUS, LOG
|
| 39 |
+
LOG = ["PC-SHO-DLM v2 BACKPROP — Optimized Architecture"]
|
| 40 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 41 |
+
LOG.append(f"Device: {dev}")
|
| 42 |
+
if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 43 |
+
|
| 44 |
+
cfg = PCSHOConfig(vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048,
|
| 45 |
+
n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 46 |
+
mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, homeostatic_target=1.0, homeostatic_rate=0.001,
|
| 47 |
+
lateral_inhibition=0.01, settling_budget_fraction=0.5)
|
| 48 |
+
LOG.append(f"Model: {count_parameters(PCSHODLM(cfg)):,} params")
|
| 49 |
+
|
| 50 |
+
STATUS = "Loading data..."
|
| 51 |
+
from datasets import load_dataset
|
| 52 |
+
dv = load_dataset("wikitext","wikitext-103-raw-v1",split="validation")
|
| 53 |
+
val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len)
|
| 54 |
+
try:
|
| 55 |
+
train_ds = StreamDS("HuggingFaceFW/fineweb","sample-10BT","train",cfg.max_seq_len,max_tok=2_000_000_000)
|
| 56 |
+
LOG.append("Train: FineWeb-10BT streaming (2B tokens)")
|
| 57 |
+
except:
|
| 58 |
+
train_ds = StreamDS("wikitext","wikitext-103-raw-v1","train",cfg.max_seq_len,max_tok=500_000_000)
|
| 59 |
+
LOG.append("Train: WikiText-103 fallback (500M tokens)")
|
| 60 |
+
LOG.append("Data: WikiText-103 streaming (500M tok/epoch)")
|
| 61 |
+
|
| 62 |
+
model = PCSHODLM(cfg).to(dev); model.train()
|
| 63 |
+
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.01)
|
| 64 |
+
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=10000, eta_min=3e-5)
|
| 65 |
+
tl = DataLoader(train_ds, batch_size=64, num_workers=4, pin_memory=True)
|
| 66 |
+
vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True)
|
| 67 |
+
|
| 68 |
+
STATUS = "Training v2 BACKPROP..."; LOG.append(f"\n{'='*60}\nv2 BACKPROP | {count_parameters(model):,} params\n{'='*60}")
|
| 69 |
+
step, start, mx = 0, time.time(), 10000; log_d = {"steps":[],"losses":[],"energies":[]}
|
| 70 |
+
K_max = cfg.n_settling_steps
|
| 71 |
+
|
| 72 |
+
for batch in tl:
|
| 73 |
+
if step >= mx: break
|
| 74 |
+
x0 = batch["input_ids"].to(dev)
|
| 75 |
+
K_curr = max(1, int(K_max * min(1.0, step / min(2000, mx//3)))); model.config.n_settling_steps = K_curr
|
| 76 |
+
opt.zero_grad(); out = model(x0); loss = out["loss"]; loss.backward()
|
| 77 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step(); sched.step()
|
| 78 |
+
step += 1; lv = loss.item(); es = out["energies"]
|
| 79 |
+
if step % 100 == 0:
|
| 80 |
+
el = time.time()-start; tps = step*64*cfg.max_seq_len/el; e = f"{es[-1]:.0f}" if es else "N/A"
|
| 81 |
+
msg = f"[v2-bp] Step {step:6d} | Loss: {lv:.4f} | Energy: {e} | K={K_curr} | Tok/s: {tps:.0f} | {el:.0f}s"
|
| 82 |
+
LOG.append(msg); log_d["steps"].append(step); log_d["losses"].append(lv); log_d["energies"].append(es[-1] if es else 0)
|
| 83 |
+
if step % 2000 == 0:
|
| 84 |
+
model.eval(); tl2,tt2=0.,0
|
| 85 |
+
with torch.no_grad():
|
| 86 |
+
for vb in vl:
|
| 87 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 88 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 89 |
+
if tt2>100000: break
|
| 90 |
+
LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); log_d.setdefault("val",[]).append((step,tl2/max(1,tt2))); model.train()
|
| 91 |
+
|
| 92 |
+
model.config.n_settling_steps = K_max; model.eval()
|
| 93 |
+
tl2,tt2=0.,0
|
| 94 |
+
with torch.no_grad():
|
| 95 |
+
for vb in vl:
|
| 96 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 97 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 98 |
+
if tt2>200000: break
|
| 99 |
+
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!"
|
| 100 |
+
os.makedirs("results",exist_ok=True); torch.save({"model":model.state_dict(),"config":cfg,"log":log_d},"results/v2_backprop.pt")
|
| 101 |
+
try:
|
| 102 |
+
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!")
|
| 103 |
+
except: pass
|
| 104 |
+
|
| 105 |
+
_t = None
|
| 106 |
+
def start():
|
| 107 |
+
global _t
|
| 108 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 109 |
+
_t = threading.Thread(target=train, daemon=True); _t.start(); return "v2 BACKPROP started on A100!"
|
| 110 |
+
|
| 111 |
+
with gr.Blocks(title="v2 Backprop") as demo:
|
| 112 |
+
gr.Markdown("# PC-SHO-DLM v2: BACKPROP Baseline (A100)\nOptimized arch: linear-attn settling, temporal hierarchy, homeostasis, curriculum-K")
|
| 113 |
+
with gr.Row():
|
| 114 |
+
btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle")
|
| 115 |
+
log=gr.Textbox(label="Log",lines=30); btn.click(start,outputs=st)
|
| 116 |
+
r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-60:]),outputs=log); r.click(lambda:STATUS,outputs=st)
|
| 117 |
+
t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-60:]),outputs=log); t.tick(lambda:STATUS,outputs=st)
|
| 118 |
+
demo.launch()
|
app_v2_unified.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM v2: UNIFIED (settling=learning) with all optimizations + adaptive two-timescale."""
|
| 2 |
+
import json, os, sys, threading, time, math
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch, torch.nn.functional as F
|
| 5 |
+
from torch.utils.data import DataLoader, IterableDataset, Dataset
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 8 |
+
from model import PCSHODLM, PCSHOConfig, count_parameters
|
| 9 |
+
|
| 10 |
+
class StreamDS(IterableDataset):
|
| 11 |
+
def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None):
|
| 12 |
+
self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok
|
| 13 |
+
def __iter__(self):
|
| 14 |
+
from datasets import load_dataset
|
| 15 |
+
ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True)
|
| 16 |
+
buf, tot = [], 0
|
| 17 |
+
for item in ds:
|
| 18 |
+
t = item.get("text","")
|
| 19 |
+
if not t.strip(): continue
|
| 20 |
+
buf.extend([min(b+1,self.voc-1) for b in t.encode("utf-8")])
|
| 21 |
+
while len(buf) >= self.seq_len:
|
| 22 |
+
yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)}
|
| 23 |
+
buf = buf[self.seq_len:]; tot += self.seq_len
|
| 24 |
+
if self.max_tok and tot > self.max_tok: return
|
| 25 |
+
|
| 26 |
+
class CharDS(Dataset):
|
| 27 |
+
def __init__(self, text, sl):
|
| 28 |
+
self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 29 |
+
self.n = max(1,(len(self.data)-sl)//sl)
|
| 30 |
+
def __len__(self): return self.n
|
| 31 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 32 |
+
|
| 33 |
+
LOG, STATUS = [], "Idle"
|
| 34 |
+
|
| 35 |
+
def train():
|
| 36 |
+
global STATUS, LOG
|
| 37 |
+
LOG = ["PC-SHO-DLM v2 UNIFIED — Settling IS Learning + Adaptive Ratio"]
|
| 38 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 39 |
+
LOG.append(f"Device: {dev}")
|
| 40 |
+
if dev == "cuda": LOG.append(f"GPU: {torch.cuda.get_device_name()} | VRAM: {torch.cuda.get_device_properties(0).total_memory/1e9:.1f} GB")
|
| 41 |
+
|
| 42 |
+
cfg = PCSHOConfig(vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048,
|
| 43 |
+
n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 44 |
+
mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3, homeostatic_target=1.0, homeostatic_rate=0.001,
|
| 45 |
+
lateral_inhibition=0.01, settling_budget_fraction=0.5)
|
| 46 |
+
LOG.append(f"Model: {count_parameters(PCSHODLM(cfg)):,} params")
|
| 47 |
+
LOG.append("Two-timescale: adaptive s* = (1 - rho^K)^2 / 2")
|
| 48 |
+
|
| 49 |
+
STATUS = "Loading data..."
|
| 50 |
+
from datasets import load_dataset
|
| 51 |
+
dv = load_dataset("wikitext","wikitext-103-raw-v1",split="validation")
|
| 52 |
+
val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len)
|
| 53 |
+
try:
|
| 54 |
+
train_ds = StreamDS("HuggingFaceFW/fineweb","sample-10BT","train",cfg.max_seq_len,max_tok=2_000_000_000)
|
| 55 |
+
LOG.append("Train: FineWeb-10BT streaming (2B tokens)")
|
| 56 |
+
except:
|
| 57 |
+
train_ds = StreamDS("wikitext","wikitext-103-raw-v1","train",cfg.max_seq_len,max_tok=500_000_000)
|
| 58 |
+
LOG.append("Train: WikiText-103 fallback (500M tokens)")
|
| 59 |
+
LOG.append("Data: WikiText-103 streaming (500M tok/epoch)")
|
| 60 |
+
|
| 61 |
+
model = PCSHODLM(cfg).to(dev); model.train()
|
| 62 |
+
tl = DataLoader(train_ds, batch_size=64, num_workers=4, pin_memory=True)
|
| 63 |
+
vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True)
|
| 64 |
+
|
| 65 |
+
STATUS = "Training v2 UNIFIED..."; LOG.append(f"\n{'='*60}\nv2 UNIFIED | {count_parameters(model):,} params\n{'='*60}")
|
| 66 |
+
step, start, mx = 0, time.time(), 10000; log_d = {"steps":[],"losses":[],"energies":[],"lr_scales":[]}
|
| 67 |
+
K_max = cfg.n_settling_steps
|
| 68 |
+
# Start with theoretically derived ratio, will adapt
|
| 69 |
+
param_lr_scale = 0.025
|
| 70 |
+
|
| 71 |
+
for batch in tl:
|
| 72 |
+
if step >= mx: break
|
| 73 |
+
x0 = batch["input_ids"].to(dev); B,S = x0.shape
|
| 74 |
+
K_curr = max(1, int(K_max * min(1.0, step / min(2000, mx//3)))); model.config.n_settling_steps = K_curr
|
| 75 |
+
|
| 76 |
+
t = torch.randint(1, cfg.n_diffusion_steps+1, (B,), device=dev)
|
| 77 |
+
x_t, mask = model.schedule.corrupt(x0, t, cfg.mask_token_id)
|
| 78 |
+
h0 = model.embed_input(x_t, t); h_init = model.amortized_forward_pass(h0)
|
| 79 |
+
h_s, _, energies = model.unified_settle(h_init, x0, mask, t, param_lr_scale=param_lr_scale)
|
| 80 |
+
|
| 81 |
+
# Adaptive two-timescale: s* = (1 - rho^K)^2 / 2
|
| 82 |
+
if len(energies) >= 2 and energies[0] > 0:
|
| 83 |
+
e_ratio = energies[-1] / max(energies[0], 1e-8)
|
| 84 |
+
eff_rho_K = math.sqrt(max(e_ratio, 0.01))
|
| 85 |
+
param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - eff_rho_K) ** 2))
|
| 86 |
+
|
| 87 |
+
with torch.no_grad():
|
| 88 |
+
logits = model.readout(model.readout_norm(h_s[-1]))
|
| 89 |
+
ml, mt = logits[mask], x0[mask]
|
| 90 |
+
lv = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0
|
| 91 |
+
step += 1
|
| 92 |
+
|
| 93 |
+
if step % 100 == 0:
|
| 94 |
+
el = time.time()-start; tps = step*64*cfg.max_seq_len/el; e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 95 |
+
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"
|
| 96 |
+
LOG.append(msg); log_d["steps"].append(step); log_d["losses"].append(lv)
|
| 97 |
+
log_d["energies"].append(energies[-1] if energies else 0); log_d["lr_scales"].append(param_lr_scale)
|
| 98 |
+
if step % 2000 == 0:
|
| 99 |
+
model.eval(); tl2,tt2=0.,0
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
for vb in vl:
|
| 102 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 103 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 104 |
+
if tt2>100000: break
|
| 105 |
+
LOG.append(f" --> Val: {tl2/max(1,tt2):.4f}"); log_d.setdefault("val",[]).append((step,tl2/max(1,tt2))); model.train()
|
| 106 |
+
|
| 107 |
+
model.config.n_settling_steps = K_max; model.eval()
|
| 108 |
+
tl2,tt2=0.,0
|
| 109 |
+
with torch.no_grad():
|
| 110 |
+
for vb in vl:
|
| 111 |
+
vo=model(vb["input_ids"].to(dev)); nm=vo["mask"].sum().item()
|
| 112 |
+
if nm>0: tl2+=vo["loss"].item()*nm; tt2+=nm
|
| 113 |
+
if tt2>200000: break
|
| 114 |
+
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!"
|
| 115 |
+
os.makedirs("results",exist_ok=True); torch.save({"model":model.state_dict(),"config":cfg,"log":log_d},"results/v2_unified.pt")
|
| 116 |
+
try:
|
| 117 |
+
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!")
|
| 118 |
+
except: pass
|
| 119 |
+
|
| 120 |
+
_t = None
|
| 121 |
+
def start():
|
| 122 |
+
global _t
|
| 123 |
+
if _t and _t.is_alive(): return "Already running!"
|
| 124 |
+
_t = threading.Thread(target=train, daemon=True); _t.start(); return "v2 UNIFIED started on A100!"
|
| 125 |
+
|
| 126 |
+
with gr.Blocks(title="v2 Unified") as demo:
|
| 127 |
+
gr.Markdown("# PC-SHO-DLM v2: UNIFIED (A100)\nSettling = Learning | Adaptive two-timescale ratio | All optimizations")
|
| 128 |
+
with gr.Row():
|
| 129 |
+
btn=gr.Button("Start",variant="primary"); st=gr.Textbox(label="Status",value="Idle")
|
| 130 |
+
log=gr.Textbox(label="Log",lines=30); btn.click(start,outputs=st)
|
| 131 |
+
r=gr.Button("Refresh"); r.click(lambda:"\n".join(LOG[-60:]),outputs=log); r.click(lambda:STATUS,outputs=st)
|
| 132 |
+
t=gr.Timer(5); t.tick(lambda:"\n".join(LOG[-60:]),outputs=log); t.tick(lambda:STATUS,outputs=st)
|
| 133 |
+
demo.launch()
|
app_v2_unified_large.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM v2: UNIFIED LARGE — 4xA100, FineWeb-10BT, all optimizations."""
|
| 2 |
+
import json, os, sys, threading, time, math
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch, torch.nn.functional as F
|
| 5 |
+
from torch.utils.data import DataLoader, IterableDataset, Dataset
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 8 |
+
from model import PCSHODLM, PCSHOConfig, count_parameters
|
| 9 |
+
|
| 10 |
+
class StreamDS(IterableDataset):
|
| 11 |
+
def __init__(self, name, cfg, split, seq_len, voc=257, max_tok=None):
|
| 12 |
+
self.name, self.cfg, self.split, self.seq_len, self.voc, self.max_tok = name, cfg, split, seq_len, voc, max_tok
|
| 13 |
+
def __iter__(self):
|
| 14 |
+
from datasets import load_dataset
|
| 15 |
+
ds = load_dataset(self.name, self.cfg, split=self.split, streaming=True, trust_remote_code=True)
|
| 16 |
+
buf, tot = [], 0
|
| 17 |
+
for item in ds:
|
| 18 |
+
t = item.get("text", "")
|
| 19 |
+
if not t or not t.strip():
|
| 20 |
+
continue
|
| 21 |
+
buf.extend([min(b+1, self.voc-1) for b in t.encode("utf-8")])
|
| 22 |
+
while len(buf) >= self.seq_len:
|
| 23 |
+
yield {"input_ids": torch.tensor(buf[:self.seq_len], dtype=torch.long)}
|
| 24 |
+
buf = buf[self.seq_len:]
|
| 25 |
+
tot += self.seq_len
|
| 26 |
+
if self.max_tok and tot > self.max_tok:
|
| 27 |
+
return
|
| 28 |
+
|
| 29 |
+
class CharDS(Dataset):
|
| 30 |
+
def __init__(self, text, sl):
|
| 31 |
+
self.sl = sl
|
| 32 |
+
self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 33 |
+
self.n = max(1, (len(self.data)-sl)//sl)
|
| 34 |
+
def __len__(self): return self.n
|
| 35 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 36 |
+
|
| 37 |
+
LOG, STATUS = [], "Idle"
|
| 38 |
+
|
| 39 |
+
def train():
|
| 40 |
+
global STATUS, LOG
|
| 41 |
+
LOG = ["=" * 70]
|
| 42 |
+
LOG.append("PC-SHO-DLM v2 UNIFIED LARGE")
|
| 43 |
+
LOG.append("4xA100 | FineWeb-10BT | Adaptive Two-Timescale | All Optimizations")
|
| 44 |
+
LOG.append("=" * 70)
|
| 45 |
+
|
| 46 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 47 |
+
n_gpu = torch.cuda.device_count() if dev == "cuda" else 0
|
| 48 |
+
LOG.append(f"Device: {dev} x {n_gpu}")
|
| 49 |
+
if dev == "cuda":
|
| 50 |
+
for i in range(n_gpu):
|
| 51 |
+
LOG.append(f" GPU {i}: {torch.cuda.get_device_name(i)} | {torch.cuda.get_device_properties(i).total_memory/1e9:.1f} GB")
|
| 52 |
+
|
| 53 |
+
# Large model sized for single A100-80GB
|
| 54 |
+
cfg = PCSHOConfig(
|
| 55 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048,
|
| 56 |
+
n_diffusion_steps=128, n_settling_steps=8, mask_token_id=0, dropout=0.1, feedback_rank=128,
|
| 57 |
+
mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3,
|
| 58 |
+
homeostatic_target=1.0, homeostatic_rate=0.001,
|
| 59 |
+
lateral_inhibition=0.01, settling_budget_fraction=0.5,
|
| 60 |
+
)
|
| 61 |
+
n_params = count_parameters(PCSHODLM(cfg))
|
| 62 |
+
LOG.append(f"\nModel: {n_params:,} params (d={cfg.d_model}, L={cfg.n_layers}, heads={cfg.n_heads})")
|
| 63 |
+
LOG.append("Optimizations: spectral precond, curriculum-K, temporal hierarchy,")
|
| 64 |
+
LOG.append(" homeostasis, linear-attn settling, lateral inhibition, adaptive s*")
|
| 65 |
+
|
| 66 |
+
# === DATA: FineWeb-10BT (10 billion tokens of curated web text) ===
|
| 67 |
+
STATUS = "Loading FineWeb-10BT..."
|
| 68 |
+
LOG.append("\nLoading FineWeb-10BT (10B tokens, streaming)...")
|
| 69 |
+
|
| 70 |
+
train_ds = StreamDS("HuggingFaceFW/fineweb", "sample-10BT", "train",
|
| 71 |
+
cfg.max_seq_len, max_tok=5_000_000_000) # 5B tokens
|
| 72 |
+
LOG.append("Train: FineWeb-10BT streaming (5B tokens)")
|
| 73 |
+
|
| 74 |
+
# Validation from WikiText
|
| 75 |
+
from datasets import load_dataset
|
| 76 |
+
dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 77 |
+
val_ds = CharDS("\n".join([r["text"] for r in dv if r["text"].strip()]), cfg.max_seq_len)
|
| 78 |
+
LOG.append(f"Val: WikiText-103 ({len(val_ds):,} samples)")
|
| 79 |
+
|
| 80 |
+
model = PCSHODLM(cfg).to(dev)
|
| 81 |
+
model.train()
|
| 82 |
+
|
| 83 |
+
batch_size = 64
|
| 84 |
+
tl = DataLoader(train_ds, batch_size=batch_size, num_workers=8, pin_memory=True, prefetch_factor=4)
|
| 85 |
+
vl = DataLoader(val_ds, batch_size=64, num_workers=2, pin_memory=True)
|
| 86 |
+
|
| 87 |
+
STATUS = "Training UNIFIED LARGE..."
|
| 88 |
+
LOG.append(f"\n{'='*70}")
|
| 89 |
+
LOG.append(f"UNIFIED LARGE | {n_params:,} params | batch={batch_size} | FineWeb-10BT")
|
| 90 |
+
LOG.append(f"{'='*70}")
|
| 91 |
+
|
| 92 |
+
step, start, mx = 0, time.time(), 20000
|
| 93 |
+
log_d = {"steps": [], "losses": [], "energies": [], "lr_scales": [], "K_values": []}
|
| 94 |
+
K_max = cfg.n_settling_steps
|
| 95 |
+
param_lr_scale = 0.025 # Start at theory-optimal value
|
| 96 |
+
|
| 97 |
+
for batch in tl:
|
| 98 |
+
if step >= mx:
|
| 99 |
+
break
|
| 100 |
+
x0 = batch["input_ids"].to(dev)
|
| 101 |
+
B, S = x0.shape
|
| 102 |
+
|
| 103 |
+
# Curriculum over K
|
| 104 |
+
K_curr = max(1, int(K_max * min(1.0, step / min(3000, mx // 3))))
|
| 105 |
+
model.config.n_settling_steps = K_curr
|
| 106 |
+
|
| 107 |
+
t = torch.randint(1, cfg.n_diffusion_steps + 1, (B,), device=dev)
|
| 108 |
+
x_t, mask = model.schedule.corrupt(x0, t, cfg.mask_token_id)
|
| 109 |
+
h0 = model.embed_input(x_t, t)
|
| 110 |
+
h_init = model.amortized_forward_pass(h0)
|
| 111 |
+
h_s, _, energies = model.unified_settle(h_init, x0, mask, t, param_lr_scale=param_lr_scale)
|
| 112 |
+
|
| 113 |
+
# Adaptive two-timescale: s* = (1 - rho^K)^2 / 2
|
| 114 |
+
if len(energies) >= 2 and energies[0] > 0:
|
| 115 |
+
e_ratio = energies[-1] / max(energies[0], 1e-8)
|
| 116 |
+
eff_rho_K = math.sqrt(max(e_ratio, 0.01))
|
| 117 |
+
param_lr_scale = max(0.001, min(0.1, 0.5 * (1.0 - eff_rho_K) ** 2))
|
| 118 |
+
|
| 119 |
+
with torch.no_grad():
|
| 120 |
+
logits = model.readout(model.readout_norm(h_s[-1]))
|
| 121 |
+
ml, mt = logits[mask], x0[mask]
|
| 122 |
+
lv = F.cross_entropy(ml, mt).item() if ml.numel() > 0 else 0
|
| 123 |
+
step += 1
|
| 124 |
+
|
| 125 |
+
if step % 100 == 0:
|
| 126 |
+
el = time.time() - start
|
| 127 |
+
tps = step * batch_size * cfg.max_seq_len / el
|
| 128 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 129 |
+
rho_str = f"[{model.layer_rho[0]:.3f}..{model.layer_rho[-1]:.3f}]"
|
| 130 |
+
msg = (f"[UNI-L] Step {step:6d} | Loss: {lv:.4f} | Energy: {e} | "
|
| 131 |
+
f"K={K_curr} | s={param_lr_scale:.4f} | rho={rho_str} | "
|
| 132 |
+
f"Tok/s: {tps:.0f} | {el:.0f}s")
|
| 133 |
+
LOG.append(msg)
|
| 134 |
+
log_d["steps"].append(step)
|
| 135 |
+
log_d["losses"].append(lv)
|
| 136 |
+
log_d["energies"].append(energies[-1] if energies else 0)
|
| 137 |
+
log_d["lr_scales"].append(param_lr_scale)
|
| 138 |
+
log_d["K_values"].append(K_curr)
|
| 139 |
+
|
| 140 |
+
if step % 2000 == 0:
|
| 141 |
+
model.eval()
|
| 142 |
+
tl2, tt2 = 0., 0
|
| 143 |
+
with torch.no_grad():
|
| 144 |
+
for vb in vl:
|
| 145 |
+
vo = model(vb["input_ids"].to(dev))
|
| 146 |
+
nm = vo["mask"].sum().item()
|
| 147 |
+
if nm > 0:
|
| 148 |
+
tl2 += vo["loss"].item() * nm
|
| 149 |
+
tt2 += nm
|
| 150 |
+
if tt2 > 100000:
|
| 151 |
+
break
|
| 152 |
+
vl2 = tl2 / max(1, tt2)
|
| 153 |
+
LOG.append(f" --> Val loss: {vl2:.4f}")
|
| 154 |
+
log_d.setdefault("val", []).append((step, vl2))
|
| 155 |
+
model.train()
|
| 156 |
+
|
| 157 |
+
# Save checkpoint
|
| 158 |
+
os.makedirs("results", exist_ok=True)
|
| 159 |
+
torch.save({
|
| 160 |
+
"model": model.state_dict(), "config": cfg, "log": log_d, "step": step
|
| 161 |
+
}, f"results/unified_large_step{step}.pt")
|
| 162 |
+
LOG.append(f" Checkpoint saved at step {step}")
|
| 163 |
+
|
| 164 |
+
# Final eval
|
| 165 |
+
model.config.n_settling_steps = K_max
|
| 166 |
+
model.eval()
|
| 167 |
+
tl2, tt2 = 0., 0
|
| 168 |
+
with torch.no_grad():
|
| 169 |
+
for vb in vl:
|
| 170 |
+
vo = model(vb["input_ids"].to(dev))
|
| 171 |
+
nm = vo["mask"].sum().item()
|
| 172 |
+
if nm > 0:
|
| 173 |
+
tl2 += vo["loss"].item() * nm
|
| 174 |
+
tt2 += nm
|
| 175 |
+
if tt2 > 200000:
|
| 176 |
+
break
|
| 177 |
+
fv = tl2 / max(1, tt2)
|
| 178 |
+
log_d["final_val"] = fv
|
| 179 |
+
elapsed = time.time() - start
|
| 180 |
+
LOG.append(f"\n{'='*70}")
|
| 181 |
+
LOG.append(f"DONE: {step} steps in {elapsed:.0f}s | Final val: {fv:.4f}")
|
| 182 |
+
LOG.append(f"Total tokens: {step * batch_size * cfg.max_seq_len:,}")
|
| 183 |
+
LOG.append(f"{'='*70}")
|
| 184 |
+
STATUS = "Complete!"
|
| 185 |
+
|
| 186 |
+
os.makedirs("results", exist_ok=True)
|
| 187 |
+
torch.save({"model": model.state_dict(), "config": cfg, "log": log_d}, "results/unified_large_final.pt")
|
| 188 |
+
with open("results/unified_large_log.json", "w") as f:
|
| 189 |
+
json.dump(log_d, f)
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
from huggingface_hub import HfApi
|
| 193 |
+
HfApi().upload_folder(folder_path="results", repo_id="zotowata/pc-sho-dlm-unified-large",
|
| 194 |
+
repo_type="space", path_in_repo="results")
|
| 195 |
+
LOG.append("Results uploaded!")
|
| 196 |
+
except Exception as e:
|
| 197 |
+
LOG.append(f"Upload: {e}")
|
| 198 |
+
|
| 199 |
+
_t = None
|
| 200 |
+
def start():
|
| 201 |
+
global _t
|
| 202 |
+
if _t and _t.is_alive():
|
| 203 |
+
return "Already running!"
|
| 204 |
+
_t = threading.Thread(target=train, daemon=True)
|
| 205 |
+
_t.start()
|
| 206 |
+
return "UNIFIED LARGE started!"
|
| 207 |
+
|
| 208 |
+
with gr.Blocks(title="v2 Unified Large") as demo:
|
| 209 |
+
gr.Markdown("# PC-SHO-DLM v2: UNIFIED LARGE (4xA100)")
|
| 210 |
+
gr.Markdown("~150M params | FineWeb-10BT (5B tokens) | Adaptive s* | 20k steps")
|
| 211 |
+
with gr.Row():
|
| 212 |
+
btn = gr.Button("Start Training", variant="primary")
|
| 213 |
+
st = gr.Textbox(label="Status", value="Idle")
|
| 214 |
+
log = gr.Textbox(label="Log", lines=35, max_lines=70)
|
| 215 |
+
btn.click(start, outputs=st)
|
| 216 |
+
r = gr.Button("Refresh")
|
| 217 |
+
r.click(lambda: "\n".join(LOG[-70:]), outputs=log)
|
| 218 |
+
r.click(lambda: STATUS, outputs=st)
|
| 219 |
+
t = gr.Timer(5)
|
| 220 |
+
t.tick(lambda: "\n".join(LOG[-70:]), outputs=log)
|
| 221 |
+
t.tick(lambda: STATUS, outputs=st)
|
| 222 |
+
|
| 223 |
+
demo.launch()
|
app_zerogpu.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PC-SHO-DLM on ZeroGPU — Large dataset training with lambda=500 fix."""
|
| 2 |
+
import json, os, sys, threading, time, math
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import spaces
|
| 5 |
+
import torch, torch.nn.functional as F
|
| 6 |
+
from torch.utils.data import DataLoader, Dataset
|
| 7 |
+
|
| 8 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 9 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters
|
| 10 |
+
|
| 11 |
+
class CharDS(Dataset):
|
| 12 |
+
def __init__(self, text, sl):
|
| 13 |
+
self.sl = sl; self.data = torch.tensor([min(b+1,256) for b in text.encode("utf-8")], dtype=torch.long)
|
| 14 |
+
self.n = max(1,(len(self.data)-sl)//sl)
|
| 15 |
+
def __len__(self): return self.n
|
| 16 |
+
def __getitem__(self, i): return {"input_ids": self.data[i*self.sl:(i+1)*self.sl]}
|
| 17 |
+
|
| 18 |
+
LOG, STATUS = [], "Idle"
|
| 19 |
+
MODEL, UPDATER, TRAIN_DS, VAL_DS, CFG = None, None, None, None, None
|
| 20 |
+
|
| 21 |
+
def setup():
|
| 22 |
+
"""Load data and create model (CPU, before GPU allocation)."""
|
| 23 |
+
global MODEL, UPDATER, TRAIN_DS, VAL_DS, CFG, LOG, STATUS
|
| 24 |
+
|
| 25 |
+
LOG = ["PC-SHO-DLM ZeroGPU — lambda=500 fix"]
|
| 26 |
+
|
| 27 |
+
CFG = PCSHOConfig(
|
| 28 |
+
vocab_size=257, max_seq_len=512, d_model=512, n_heads=8, n_layers=12, d_ff=2048,
|
| 29 |
+
n_diffusion_steps=128, n_settling_steps=6, mask_token_id=0, dropout=0.1,
|
| 30 |
+
feedback_rank=128, denoising_lambda=500.0,
|
| 31 |
+
mass_scale=0.5, gamma_scale=0.3, eta_scale=0.3,
|
| 32 |
+
homeostatic_target=0.0, homeostatic_rate=0.0001,
|
| 33 |
+
homeostatic_rho_max=0.02, lateral_inhibition=0.0,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
STATUS = "Loading WikiText-103..."
|
| 37 |
+
from datasets import load_dataset
|
| 38 |
+
ds = load_dataset("wikitext", "wikitext-103-raw-v1", split="train")
|
| 39 |
+
dv = load_dataset("wikitext", "wikitext-103-raw-v1", split="validation")
|
| 40 |
+
train_text = "\n".join([r["text"] for r in ds if r["text"].strip()])[:100_000_000]
|
| 41 |
+
val_text = "\n".join([r["text"] for r in dv if r["text"].strip()])
|
| 42 |
+
TRAIN_DS = CharDS(train_text, CFG.max_seq_len)
|
| 43 |
+
VAL_DS = CharDS(val_text, CFG.max_seq_len)
|
| 44 |
+
LOG.append(f"Data: {len(train_text):,} train, {len(val_text):,} val chars")
|
| 45 |
+
|
| 46 |
+
MODEL = PCSHODLM(CFG)
|
| 47 |
+
LOG.append(f"Model: {count_parameters(MODEL):,} params (d={CFG.d_model}, L={CFG.n_layers})")
|
| 48 |
+
LOG.append(f"denoising_lambda={CFG.denoising_lambda} (THE FIX)")
|
| 49 |
+
UPDATER = LocalParameterUpdater(MODEL, lr_forward=3e-4, lr_feedback=3e-4, lr_readout=3e-4, lr_precision=3e-5)
|
| 50 |
+
STATUS = "Ready — press Start"
|
| 51 |
+
|
| 52 |
+
@spaces.GPU(duration=300) # 5 min GPU sessions
|
| 53 |
+
def train_batch(step_start):
|
| 54 |
+
"""Run training steps on GPU. ZeroGPU gives us ~5 min per call."""
|
| 55 |
+
global MODEL, UPDATER, LOG, STATUS
|
| 56 |
+
|
| 57 |
+
device = "cuda"
|
| 58 |
+
MODEL = MODEL.to(device)
|
| 59 |
+
MODEL.train()
|
| 60 |
+
|
| 61 |
+
tl = DataLoader(TRAIN_DS, batch_size=32, shuffle=True, drop_last=True, num_workers=0)
|
| 62 |
+
|
| 63 |
+
STATUS = f"Training on GPU (steps {step_start}+)..."
|
| 64 |
+
K_max = CFG.n_settling_steps
|
| 65 |
+
step = step_start
|
| 66 |
+
start = time.time()
|
| 67 |
+
max_steps_this_session = 500 # fit within 5 min
|
| 68 |
+
|
| 69 |
+
for batch in tl:
|
| 70 |
+
if step - step_start >= max_steps_this_session:
|
| 71 |
+
break
|
| 72 |
+
x0 = batch["input_ids"].to(device)
|
| 73 |
+
|
| 74 |
+
K_curr = max(3, int(K_max * min(1.0, step / 1000)))
|
| 75 |
+
MODEL.config.n_settling_steps = K_curr
|
| 76 |
+
|
| 77 |
+
result = UPDATER.step({"input_ids": x0})
|
| 78 |
+
step += 1
|
| 79 |
+
|
| 80 |
+
loss = result.get("loss", 0)
|
| 81 |
+
energies = result.get("energies", [])
|
| 82 |
+
|
| 83 |
+
if step % 50 == 0:
|
| 84 |
+
el = time.time() - start
|
| 85 |
+
tps = (step - step_start) * 32 * CFG.max_seq_len / el
|
| 86 |
+
e = f"{energies[-1]:.0f}" if energies else "N/A"
|
| 87 |
+
LOG.append(f"[local] Step {step:6d} | Loss: {loss:.4f} | Energy: {e} | K={K_curr} | Tok/s: {tps:.0f} | {el:.0f}s")
|
| 88 |
+
|
| 89 |
+
MODEL = MODEL.to("cpu") # free GPU
|
| 90 |
+
STATUS = f"Session done. {step - step_start} steps. Press Start for more."
|
| 91 |
+
return step
|
| 92 |
+
|
| 93 |
+
CURRENT_STEP = 0
|
| 94 |
+
|
| 95 |
+
def start():
|
| 96 |
+
global CURRENT_STEP
|
| 97 |
+
if MODEL is None:
|
| 98 |
+
setup()
|
| 99 |
+
CURRENT_STEP = train_batch(CURRENT_STEP)
|
| 100 |
+
return f"Completed step {CURRENT_STEP}. Press Start for next GPU session."
|
| 101 |
+
|
| 102 |
+
with gr.Blocks(title="PC-SHO-DLM ZeroGPU") as demo:
|
| 103 |
+
gr.Markdown("# PC-SHO-DLM — ZeroGPU Training (lambda=500)")
|
| 104 |
+
gr.Markdown("Each 'Start' gives ~5 min on A100. Press repeatedly for more training.")
|
| 105 |
+
with gr.Row():
|
| 106 |
+
btn = gr.Button("Start / Continue Training", variant="primary")
|
| 107 |
+
st = gr.Textbox(label="Status", value="Idle")
|
| 108 |
+
log = gr.Textbox(label="Log", lines=30)
|
| 109 |
+
btn.click(start, outputs=st)
|
| 110 |
+
r = gr.Button("Refresh")
|
| 111 |
+
r.click(lambda: "\n".join(LOG[-60:]), outputs=log)
|
| 112 |
+
r.click(lambda: STATUS, outputs=st)
|
| 113 |
+
t = gr.Timer(5)
|
| 114 |
+
t.tick(lambda: "\n".join(LOG[-60:]), outputs=log)
|
| 115 |
+
t.tick(lambda: STATUS, outputs=st)
|
| 116 |
+
|
| 117 |
+
demo.launch()
|
architecture_diagram.md
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PC-SHO-DLM Architecture: Complete Technical Specification
|
| 2 |
+
|
| 3 |
+
## Architecture Diagram
|
| 4 |
+
|
| 5 |
+
```
|
| 6 |
+
PC-SHO-DLM: Predictive-Coding Diffusion Language Model
|
| 7 |
+
with Precision-Conditioned Second-Order Settling
|
| 8 |
+
|
| 9 |
+
============================================================================
|
| 10 |
+
OUTER LOOP: Masked Discrete Diffusion (T denoising steps)
|
| 11 |
+
============================================================================
|
| 12 |
+
|
| 13 |
+
t=T (fully masked) ──────────> t=T-1 ──────────> ... ──────────> t=0 (clean)
|
| 14 |
+
[MASK][MASK][MASK]... [MASK] the [MASK]... The cat sat...
|
| 15 |
+
|
| 16 |
+
Each step: unmask highest-confidence tokens via reverse diffusion
|
| 17 |
+
State continuation: h,v warm-started from previous step
|
| 18 |
+
|
| 19 |
+
============================================================================
|
| 20 |
+
INNER LOOP: Predictive-Coding Energy Minimization (K settling microsteps)
|
| 21 |
+
============================================================================
|
| 22 |
+
|
| 23 |
+
For each diffusion step t, run K microsteps of SHO settling:
|
| 24 |
+
|
| 25 |
+
┌─────────────────────────────────────────────────────────────────────────┐
|
| 26 |
+
│ │
|
| 27 |
+
│ x_t (corrupted tokens) │
|
| 28 |
+
│ │ │
|
| 29 |
+
│ ▼ │
|
| 30 |
+
│ ┌──────────────┐ │
|
| 31 |
+
│ │ Embeddings │ token + position + timestep │
|
| 32 |
+
│ │ h_0 │ │
|
| 33 |
+
│ └──────┬───────┘ │
|
| 34 |
+
│ │ │
|
| 35 |
+
│ ▼ │
|
| 36 |
+
│ ╔══════════════════════════════════════════════════════════╗ │
|
| 37 |
+
│ ║ BIDIRECTIONAL PREDICTIVE TRANSFORMER ║ │
|
| 38 |
+
│ ║ ║ │
|
| 39 |
+
│ ║ Layer 1: h_0 ──▶ f_1(h_0) = μ_1↑ ε_1↑ = h_1 - μ_1↑ ║ │
|
| 40 |
+
│ ║ g_1(h_2) = μ_1↓ ε_1↓ = h_1 - μ_1↓ ║ │
|
| 41 |
+
│ ║ Γ_1 = precision_up(h_1, t) ║ │
|
| 42 |
+
│ ║ Λ_1 = precision_down(h_1, t) ║ │
|
| 43 |
+
│ ║ ║ │
|
| 44 |
+
│ ║ Layer 2: h_1 ──▶ f_2(h_1) = μ_2↑ ε_2↑ = h_2 - μ_2↑ ║ │
|
| 45 |
+
│ ║ g_2(h_3) = μ_2↓ ε_2↓ = h_2 - μ_2↓ ║ │
|
| 46 |
+
│ ║ ... ║ │
|
| 47 |
+
│ ║ ║ │
|
| 48 |
+
│ ║ Layer L: h_{L-1} ──▶ f_L(h_{L-1}) = μ_L↑ ║ │
|
| 49 |
+
│ ║ ε_L↑ = h_L - μ_L↑ ║ │
|
| 50 |
+
│ ║ ║ │
|
| 51 |
+
│ ║ ┌─────────────────────────────────────────────────┐ ║ │
|
| 52 |
+
│ ║ │ BOTTOM-UP (f_l): Standard bidirectional │ ║ │
|
| 53 |
+
│ ║ │ transformer blocks with self-attention + FFN │ ║ │
|
| 54 |
+
│ ║ │ │ ║ │
|
| 55 |
+
│ ║ │ TOP-DOWN (g_l): Lightweight feedback predictors │ ║ │
|
| 56 |
+
│ ║ │ (low-rank projections from layer above) │ ║ │
|
| 57 |
+
│ ║ │ │ ║ │
|
| 58 |
+
│ ║ │ PRECISION (Γ_l, Λ_l): Learned uncertainty │ ║ │
|
| 59 |
+
│ ║ │ per token × channel, controls settling dynamics │ ║ │
|
| 60 |
+
│ ║ └─────────────────────────────────────────────────┘ ║ │
|
| 61 |
+
│ ╚══════════════════════════════════════════════════════════╝ │
|
| 62 |
+
│ │ │
|
| 63 |
+
│ ▼ │
|
| 64 |
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
| 65 |
+
│ │ ENERGY FUNCTION E_t(h) │ │
|
| 66 |
+
│ │ │ │
|
| 67 |
+
│ │ E = Σ_l ½||ε_l↑||²_Γ (bottom-up prediction errors) │ │
|
| 68 |
+
│ │ + Σ_l ½||ε_l↓||²_Λ (top-down prediction errors) │ │
|
| 69 |
+
│ │ + λ_t · H(softmax(W·h_L)) (entropy minimization) │ │
|
| 70 |
+
│ │ + ρ_l · ||h_l - h_l^init||² (anchoring) │ │
|
| 71 |
+
│ └──────────────────────────────────────────────────────────┘ │
|
| 72 |
+
│ │ │
|
| 73 |
+
│ ▼ │
|
| 74 |
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
| 75 |
+
│ │ SECOND-ORDER SETTLING (Damped SHO) │ │
|
| 76 |
+
│ │ │ │
|
| 77 |
+
│ │ For each layer l, for K microsteps: │ │
|
| 78 |
+
│ │ │ │
|
| 79 |
+
│ │ v_l^{k+1} = (1 - γ_l) · v_l^k - η_l · ∇_{h_l} E │ │
|
| 80 |
+
│ │ h_l^{k+1} = h_l^k + v_l^{k+1} │ │
|
| 81 |
+
│ │ │ │
|
| 82 |
+
│ │ where η_l, γ_l are precision-conditioned: │ │
|
| 83 |
+
│ │ η_l = η_base / (1 + c_η · prec_l) │ │
|
| 84 |
+
│ │ γ_l = clip(2√(m_l · prec_l), γ_min, γ_max) │ │
|
| 85 |
+
│ │ │ │
|
| 86 |
+
│ │ Temporal hierarchy: │ │
|
| 87 |
+
│ │ m_l = m · (1 + 0.5 · l/L) (heavier at top) │ │
|
| 88 |
+
│ │ η_l scaled by 1/(1 + 0.3·l/L) (slower at top) │ │
|
| 89 |
+
│ │ │ │
|
| 90 |
+
│ │ Soft-gate adaptive settling: │ │
|
| 91 |
+
│ │ w_i = σ((U_i - τ) / τ_temp) │ │
|
| 92 |
+
│ │ h_i^{k+1} = w_i · h_i^{new} + (1-w_i) · h_i^{old} │ │
|
| 93 |
+
│ └──────────────────────────────────────────────────────────┘ │
|
| 94 |
+
│ │ │
|
| 95 |
+
│ ▼ │
|
| 96 |
+
│ ┌──────────────────────────────────────────────────────────┐ │
|
| 97 |
+
│ │ LOCAL PARAMETER UPDATES │ │
|
| 98 |
+
│ │ (Globally Backpropagation-Free) │ │
|
| 99 |
+
│ │ │ │
|
| 100 |
+
│ │ After settling converges: │ │
|
| 101 |
+
│ │ │ │
|
| 102 |
+
│ │ Forward: Δθ_l ∝ -(Γ_l · ε_l↑) · ∂f_l/∂θ_l │ │
|
| 103 |
+
│ │ Feedback: Δφ_l ∝ -(Λ_l · ε_l↓) · ∂g_l/∂φ_l │ │
|
| 104 |
+
│ │ Readout: ΔW_o ∝ -∂L_mask/∂W_o (uses x_0 targets) │ │
|
| 105 |
+
│ │ Embeds: via readout loss backprop │ │
|
| 106 |
+
│ │ │ │
|
| 107 |
+
│ │ Each update is LAYER-LOCAL: no gradient crosses layers │ │
|
| 108 |
+
│ └──────────────────────────────────────────────────────────┘ │
|
| 109 |
+
│ │ │
|
| 110 |
+
│ ▼ │
|
| 111 |
+
│ ┌──────────────┐ │
|
| 112 |
+
│ │ Readout │ W_o · h_L → logits → softmax → token predictions │
|
| 113 |
+
│ │ (per token) │ │
|
| 114 |
+
│ └──────────────┘ │
|
| 115 |
+
│ │
|
| 116 |
+
└─────────────────────────────────────────────────────────────────────────┘
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
============================================================================
|
| 120 |
+
CONDITIONAL GENERATION (Chat Mode)
|
| 121 |
+
============================================================================
|
| 122 |
+
|
| 123 |
+
[prompt tokens (unmasked)] | [MASK MASK MASK ... (response region)]
|
| 124 |
+
↕ ↕
|
| 125 |
+
Never modified Iteratively unmasked via
|
| 126 |
+
by diffusion reverse diffusion + settling
|
| 127 |
+
↕ ↕
|
| 128 |
+
Provides context Response emerges from
|
| 129 |
+
through bidirectional energy minimization
|
| 130 |
+
attention at every conditioned on prompt
|
| 131 |
+
settling step
|
| 132 |
+
|
| 133 |
+
============================================================================
|
| 134 |
+
STATE CONTINUATION (Across Diffusion Steps)
|
| 135 |
+
============================================================================
|
| 136 |
+
|
| 137 |
+
Step t+1: settle → h*(t+1), v*(t+1)
|
| 138 |
+
│
|
| 139 |
+
warm-start ↓ (stop-gradient)
|
| 140 |
+
Step t: h^(0)(t) = h*(t+1)
|
| 141 |
+
v^(0)(t) = ρ_v · v*(t+1)
|
| 142 |
+
│
|
| 143 |
+
settle K steps → h*(t), v*(t)
|
| 144 |
+
│
|
| 145 |
+
warm-start ↓
|
| 146 |
+
Step t-1: ...continues...
|
| 147 |
+
|
| 148 |
+
Theorem C: ||h_t^(K) - h_t*|| ≤ ρ^K · (ε_{t+1} + Δ_t)
|
| 149 |
+
Settling cost depends on DRIFT, not full re-solve distance.
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
---
|
| 153 |
+
|
| 154 |
+
## Critical Derivations and Equations
|
| 155 |
+
|
| 156 |
+
### 1. The Per-Step Latent Energy
|
| 157 |
+
|
| 158 |
+
For diffusion timestep t, the energy over hidden states h = {h_0, ..., h_L}:
|
| 159 |
+
|
| 160 |
+
```
|
| 161 |
+
E_t(h, θ) = Σ_{l=1}^{L} ½ ||ε_l↑||²_{Γ_l} (bottom-up consistency)
|
| 162 |
+
+ Σ_{l=0}^{L-1} ½ ||ε_l↓||²_{Λ_l} (top-down consistency)
|
| 163 |
+
+ λ_t · Σ_{i ∈ M_t} H(p_θ(· | h_L^(i))) (entropy minimization — HONEST)
|
| 164 |
+
+ Σ_{l=1}^{L} ρ_l · ||h_l - h_l^{init}||² (anchoring)
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
where:
|
| 168 |
+
- `ε_l↑ = h_l - f_l(h_{l-1}; θ_l)` — bottom-up prediction error
|
| 169 |
+
- `ε_l↓ = h_l - g_l(h_{l+1}; φ_l)` — top-down prediction error
|
| 170 |
+
- `H(p) = -Σ_c p_c log p_c` — entropy of predicted token distribution
|
| 171 |
+
- `||x||²_Γ = x^T Γ x` — precision-weighted squared norm
|
| 172 |
+
- `M_t` — set of masked token positions
|
| 173 |
+
- `λ_t = λ_base · (1 + (1 - t/T))` — timestep-dependent weight
|
| 174 |
+
|
| 175 |
+
**CRITICAL: Honest Settling**
|
| 176 |
+
The entropy term `H(softmax(W·h_L))` does NOT use the ground truth x_0.
|
| 177 |
+
It pushes the model toward confident predictions without peeking at the answer.
|
| 178 |
+
The ground truth x_0 is used ONLY in the parameter update step (readout loss),
|
| 179 |
+
not during settling.
|
| 180 |
+
|
| 181 |
+
### 2. Second-Order Settling Dynamics (SHO)
|
| 182 |
+
|
| 183 |
+
Continuous time:
|
| 184 |
+
```
|
| 185 |
+
m_l · ḧ_l + γ_l · ḣ_l + ∇_{h_l} E_t(h) = 0
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
Discrete (symplectic Euler):
|
| 189 |
+
```
|
| 190 |
+
v_l^{k+1} = (1 - γ_l) · v_l^k - η_l · ∇_{h_l} E_t(h^k)
|
| 191 |
+
h_l^{k+1} = h_l^k + v_l^{k+1}
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
Precision-conditioned controller:
|
| 195 |
+
```
|
| 196 |
+
η_l = η_base · (1/(1 + 0.3·l/L)) / (1 + c_η · prec_l)
|
| 197 |
+
γ_l = clip(2√(m_l · prec_l), γ_min, γ_max)
|
| 198 |
+
m_l = m · (1 + 0.5 · l/L)
|
| 199 |
+
```
|
| 200 |
+
|
| 201 |
+
Interpretation:
|
| 202 |
+
- Low precision → flat energy → large steps, more momentum (exploration)
|
| 203 |
+
- High precision → sharp energy → small steps, high damping (exploitation)
|
| 204 |
+
- Lower layers settle fast (low mass, high damping)
|
| 205 |
+
- Higher layers settle slow (high mass, maintain context)
|
| 206 |
+
|
| 207 |
+
### 3. Theorem A: Reduced-Objective Exactness (Envelope Theorem)
|
| 208 |
+
|
| 209 |
+
Define the reduced objective:
|
| 210 |
+
```
|
| 211 |
+
Φ_t(θ) = min_h E_t(h, θ)
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
If h_t*(θ) is the unique minimizer, then:
|
| 215 |
+
```
|
| 216 |
+
∇_θ Φ_t(θ) = ∂E_t/∂θ |_{h=h_t*(θ)}
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
The implicit derivative through h_t*(θ) vanishes because ∇_h E_t(h_t*, θ) = 0.
|
| 220 |
+
|
| 221 |
+
**Consequence:** Local post-settling parameter updates are exact gradients of
|
| 222 |
+
the reduced objective. No backpropagation through the K settling steps needed.
|
| 223 |
+
|
| 224 |
+
Since E_t decomposes as E_t = Σ_l E_{t,l}(h_{l-1}, h_l, h_{l+1}, θ_l):
|
| 225 |
+
```
|
| 226 |
+
∂Φ_t/∂θ_l = ∂E_{t,l}/∂θ_l |_{h=h*}
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
Each layer's gradient depends only on its own settled states. Layer-local.
|
| 230 |
+
|
| 231 |
+
### 4. Theorem B: Accelerated Settling (O(√κ) vs O(κ))
|
| 232 |
+
|
| 233 |
+
For locally quadratic energy E(h) = ½(h-h*)^T H (h-h*), μI ≼ H ≼ LI, κ=L/μ:
|
| 234 |
+
|
| 235 |
+
**First-order PC:** h^{k+1} = h^k - α∇E(h^k)
|
| 236 |
+
```
|
| 237 |
+
K_FO = O(κ · log(1/ε)) with optimal α = 2/(L+μ)
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
**PC-SHO (heavy-ball):** v^{k+1} = β·v^k - η·∇E(h^k), h^{k+1} = h^k + v^{k+1}
|
| 241 |
+
```
|
| 242 |
+
K_SHO = O(√κ · log(1/ε)) with η = 4/(√L+√μ)², β = ((√κ-1)/(√κ+1))²
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
**Speedup:** K_SHO / K_FO = O(1/√κ)
|
| 246 |
+
|
| 247 |
+
Note: This holds for the local quadratic approximation near fixed points.
|
| 248 |
+
The anchoring term ρ||h-h^{init}||² ensures local strong convexity.
|
| 249 |
+
|
| 250 |
+
### 5. Theorem C: Warm-Start Tracking
|
| 251 |
+
|
| 252 |
+
If solver contracts by ρ_S < 1 and inter-step drift is Δ_t = ||h_t* - h_{t+1}*||:
|
| 253 |
+
|
| 254 |
+
Warm-start: `||h_t^(K) - h_t*|| ≤ ρ_S^K · (ε_{t+1} + Δ_t)`
|
| 255 |
+
Cold-start: `||h_t^(K) - h_t*|| ≤ ρ_S^K · D_t`
|
| 256 |
+
|
| 257 |
+
Warm-start wins when `Δ_t + ε_{t+1} < D_t` (adjacent steps are close).
|
| 258 |
+
|
| 259 |
+
**Total settling cost:**
|
| 260 |
+
- Warm-started SHO: `K_total = O(T · √κ̃ · log((Δ+ε)/ε))`
|
| 261 |
+
- Cold-started FO: `K_total = O(T · κ̃ · log(D/ε))`
|
| 262 |
+
|
| 263 |
+
Two advantages: √κ̃ instead of κ̃, AND Δ instead of D.
|
| 264 |
+
|
| 265 |
+
### 6. Theorem D: Precision Optimality (GLS)
|
| 266 |
+
|
| 267 |
+
If local errors are heteroscedastic: ε_l ~ N(0, Σ_l), Σ_l ≠ σ²I
|
| 268 |
+
|
| 269 |
+
The precision-weighted estimator (GLS):
|
| 270 |
+
```
|
| 271 |
+
θ̂_GLS = argmin_θ (y - Xθ)^T Σ^{-1} (y - Xθ)
|
| 272 |
+
Cov(θ̂_GLS) = (X^T Σ^{-1} X)^{-1}
|
| 273 |
+
```
|
| 274 |
+
|
| 275 |
+
This is BLUE (Best Linear Unbiased Estimator).
|
| 276 |
+
Precision heads learn Γ_l ≈ Σ_l^{-1}, making local updates statistically optimal.
|
| 277 |
+
|
| 278 |
+
### 7. Lyapunov Stability
|
| 279 |
+
|
| 280 |
+
For the continuous-time dynamics M·ḧ + Γ·ḣ + ∇E(h) = 0:
|
| 281 |
+
|
| 282 |
+
Define Lyapunov function: V(h, ḣ) = E(h) + ½ḣ^T M ḣ
|
| 283 |
+
|
| 284 |
+
Then: dV/dt = -ḣ^T Γ ḣ ≤ 0
|
| 285 |
+
|
| 286 |
+
**Extra settling time monotonically decreases total energy.**
|
| 287 |
+
|
| 288 |
+
### 8. Honest Training Loss vs Cheating Loss
|
| 289 |
+
|
| 290 |
+
**Cheating (old):** Settling uses x_0 in energy → model peeks at answer
|
| 291 |
+
```
|
| 292 |
+
Settling energy: E = ... + λ · CE(logits, x_0)
|
| 293 |
+
Reported loss: 0.001 (FAKE — model copies x_0 through energy)
|
| 294 |
+
Generation: garbage (no x_0 available at inference)
|
| 295 |
+
```
|
| 296 |
+
|
| 297 |
+
**Honest (current):** Settling uses entropy → model must find confident predictions alone
|
| 298 |
+
```
|
| 299 |
+
Settling energy: E = ... + λ · H(softmax(logits))
|
| 300 |
+
Reported loss: 1.5-2.0 (REAL — model actually predicts from context)
|
| 301 |
+
Generation: coherent (same mechanism at train and inference)
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
### 9. Optimal Denoising Lambda
|
| 305 |
+
|
| 306 |
+
At initialization, measure energy components:
|
| 307 |
+
```
|
| 308 |
+
E_pred = Σ_l ½||ε_l||² (prediction errors)
|
| 309 |
+
E_entropy = Σ_i H(p_i) (entropy at masked positions)
|
| 310 |
+
```
|
| 311 |
+
|
| 312 |
+
For entropy to be ~40% of total energy:
|
| 313 |
+
```
|
| 314 |
+
λ_opt = (E_pred · 0.4) / (E_entropy · 0.6)
|
| 315 |
+
```
|
| 316 |
+
|
| 317 |
+
Typical value: λ ≈ 5 for entropy-based settling (vs λ ≈ 500 for cheating mode).
|
| 318 |
+
|
| 319 |
+
### 10. Conditional Generation (Chat)
|
| 320 |
+
|
| 321 |
+
Training: mask only response, keep prompt visible
|
| 322 |
+
```
|
| 323 |
+
x = [prompt_tokens | SEP | MASK MASK ... MASK]
|
| 324 |
+
─────────────── ─────────────────
|
| 325 |
+
never masked masked by schedule
|
| 326 |
+
```
|
| 327 |
+
|
| 328 |
+
Inference: iteratively unmask response conditioned on prompt
|
| 329 |
+
```
|
| 330 |
+
For t = T down to 1:
|
| 331 |
+
mask = (x == MASK) & response_region
|
| 332 |
+
h_settled = PC_settle(embed(x, t), K steps)
|
| 333 |
+
logits = readout(h_settled)
|
| 334 |
+
unmask top-confidence response tokens
|
| 335 |
+
```
|
| 336 |
+
|
| 337 |
+
The bidirectional attention lets prompt tokens influence every settling step.
|
| 338 |
+
The prompt acts as a fixed boundary condition shaping the energy landscape.
|
chat.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
PC-SHO-DLM Chat — Conditional masked diffusion chatbot.
|
| 4 |
+
|
| 5 |
+
The prompt stays unmasked. The response region starts fully masked.
|
| 6 |
+
PC settling iteratively denoises the response conditioned on the prompt.
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
python3 train_chat.py --data alpaca # Train on dialogue data
|
| 10 |
+
python3 chat.py --checkpoint checkpoints/chat/chat_final.pt # Chat
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import argparse, glob, os, sys, torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 17 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def find_checkpoint():
|
| 21 |
+
for p in ["checkpoints/chat/chat_final.pt", "checkpoints/chat/*.pt",
|
| 22 |
+
"checkpoints/*/checkpoint_final.pt", "checkpoints/*/*.pt"]:
|
| 23 |
+
files = sorted(glob.glob(p), key=os.path.getmtime, reverse=True)
|
| 24 |
+
if files:
|
| 25 |
+
return files[0]
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def encode_text(text, vocab_size=257):
|
| 30 |
+
return [min(b + 1, vocab_size - 1) for b in text.encode("utf-8")]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def decode_tokens(tokens):
|
| 34 |
+
raw = tokens if isinstance(tokens, list) else tokens.squeeze().cpu().tolist()
|
| 35 |
+
# Filter out mask tokens (0) and padding
|
| 36 |
+
return bytes([max(0, t - 1) for t in raw if t > 0 and t < 257]).decode("utf-8", errors="replace")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def generate_response(model, prompt_text, response_len=256, device="cpu",
|
| 40 |
+
temperature=0.8, n_steps=None):
|
| 41 |
+
"""Generate a response conditioned on prompt via conditional masked diffusion.
|
| 42 |
+
|
| 43 |
+
1. Encode prompt as bytes
|
| 44 |
+
2. Create: [prompt_tokens | MASK * response_len]
|
| 45 |
+
3. Reverse diffusion: iteratively unmask response tokens
|
| 46 |
+
4. PC settling at each step refines predictions conditioned on prompt
|
| 47 |
+
"""
|
| 48 |
+
config = model.config
|
| 49 |
+
T = n_steps or config.n_diffusion_steps
|
| 50 |
+
mask_id = config.mask_token_id
|
| 51 |
+
|
| 52 |
+
prompt_tokens = encode_text(prompt_text)
|
| 53 |
+
prompt_len = len(prompt_tokens)
|
| 54 |
+
|
| 55 |
+
# Ensure we fit in max_seq_len
|
| 56 |
+
max_response = config.max_seq_len - prompt_len
|
| 57 |
+
if max_response <= 0:
|
| 58 |
+
prompt_tokens = prompt_tokens[:config.max_seq_len // 2]
|
| 59 |
+
prompt_len = len(prompt_tokens)
|
| 60 |
+
max_response = config.max_seq_len - prompt_len
|
| 61 |
+
response_len = min(response_len, max_response)
|
| 62 |
+
|
| 63 |
+
# Build initial sequence: [prompt | MASK...]
|
| 64 |
+
seq = prompt_tokens + [mask_id] * response_len
|
| 65 |
+
if len(seq) < config.max_seq_len:
|
| 66 |
+
seq = seq + [mask_id] * (config.max_seq_len - len(seq))
|
| 67 |
+
x = torch.tensor(seq[:config.max_seq_len], dtype=torch.long).unsqueeze(0).to(device)
|
| 68 |
+
|
| 69 |
+
# Response region mask (only unmask response, never touch prompt)
|
| 70 |
+
response_region = torch.zeros(1, config.max_seq_len, dtype=torch.bool, device=device)
|
| 71 |
+
response_region[0, prompt_len:prompt_len + response_len] = True
|
| 72 |
+
|
| 73 |
+
prev_h = None
|
| 74 |
+
prev_v = None
|
| 75 |
+
|
| 76 |
+
with torch.no_grad():
|
| 77 |
+
for t_val in range(T, 0, -1):
|
| 78 |
+
t = torch.full((1,), t_val, dtype=torch.long, device=device)
|
| 79 |
+
|
| 80 |
+
# Only consider masked tokens in response region
|
| 81 |
+
mask = (x == mask_id) & response_region
|
| 82 |
+
if not mask.any():
|
| 83 |
+
break
|
| 84 |
+
|
| 85 |
+
# Embed and settle
|
| 86 |
+
h_0 = model.embed_input(x, t)
|
| 87 |
+
h_init = model.amortized_forward_pass(h_0)
|
| 88 |
+
h_settled, v_final, _, _, _ = model.settle(
|
| 89 |
+
h_init, x, mask, t,
|
| 90 |
+
prev_h=prev_h, prev_v=prev_v,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# State continuation
|
| 94 |
+
prev_h = h_settled
|
| 95 |
+
prev_v = v_final
|
| 96 |
+
|
| 97 |
+
# Decode with temperature
|
| 98 |
+
logits = model.readout(model.readout_norm(h_settled[-1]))
|
| 99 |
+
|
| 100 |
+
if temperature > 0:
|
| 101 |
+
probs = F.softmax(logits / temperature, dim=-1)
|
| 102 |
+
else:
|
| 103 |
+
probs = F.softmax(logits, dim=-1)
|
| 104 |
+
|
| 105 |
+
# Determine how many tokens to unmask
|
| 106 |
+
t_prev = t_val - 1
|
| 107 |
+
target_mask_rate = model.schedule.mask_rate(
|
| 108 |
+
torch.tensor([t_prev], device=device)
|
| 109 |
+
).squeeze()
|
| 110 |
+
|
| 111 |
+
n_currently_masked = mask.sum().item()
|
| 112 |
+
n_to_keep_masked = int(target_mask_rate * response_len)
|
| 113 |
+
n_to_unmask = max(1, n_currently_masked - n_to_keep_masked)
|
| 114 |
+
|
| 115 |
+
# Score by confidence, only in response region
|
| 116 |
+
confidence = probs.max(dim=-1).values.squeeze() # (S,)
|
| 117 |
+
confidence[~mask.squeeze()] = float("inf")
|
| 118 |
+
|
| 119 |
+
# Unmask the most confident response tokens
|
| 120 |
+
masked_indices = mask.squeeze().nonzero(as_tuple=True)[0]
|
| 121 |
+
if len(masked_indices) > 0:
|
| 122 |
+
conf_at_masked = confidence[masked_indices]
|
| 123 |
+
n_to_unmask = min(n_to_unmask, len(masked_indices))
|
| 124 |
+
_, top_idx = conf_at_masked.topk(n_to_unmask)
|
| 125 |
+
unmask_pos = masked_indices[top_idx]
|
| 126 |
+
|
| 127 |
+
# Sample tokens
|
| 128 |
+
if temperature > 0:
|
| 129 |
+
for pos in unmask_pos:
|
| 130 |
+
token = torch.multinomial(probs[0, pos], 1).item()
|
| 131 |
+
x[0, pos] = token
|
| 132 |
+
else:
|
| 133 |
+
x[0, unmask_pos] = logits[0, unmask_pos].argmax(dim=-1)
|
| 134 |
+
|
| 135 |
+
# Final pass: unmask any remaining
|
| 136 |
+
remaining = (x == mask_id) & response_region
|
| 137 |
+
if remaining.any():
|
| 138 |
+
t_final = torch.ones(1, dtype=torch.long, device=device)
|
| 139 |
+
h_0 = model.embed_input(x, t_final)
|
| 140 |
+
h_init = model.amortized_forward_pass(h_0)
|
| 141 |
+
h_s, _, _, _, _ = model.settle(h_init, x, remaining, t_final, prev_h=prev_h, prev_v=prev_v)
|
| 142 |
+
logits = model.readout(model.readout_norm(h_s[-1]))
|
| 143 |
+
if temperature > 0:
|
| 144 |
+
for pos in remaining.squeeze().nonzero(as_tuple=True)[0]:
|
| 145 |
+
probs = F.softmax(logits[0, pos] / temperature, dim=-1)
|
| 146 |
+
x[0, pos] = torch.multinomial(probs, 1).item()
|
| 147 |
+
else:
|
| 148 |
+
x[0, remaining.squeeze()] = logits[0, remaining.squeeze()].argmax(dim=-1)
|
| 149 |
+
|
| 150 |
+
# Extract response
|
| 151 |
+
response_tokens = x[0, prompt_len:prompt_len + response_len].cpu().tolist()
|
| 152 |
+
return decode_tokens(response_tokens)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def main():
|
| 156 |
+
parser = argparse.ArgumentParser(description="PC-SHO-DLM Chat")
|
| 157 |
+
parser.add_argument("--checkpoint", type=str, default=None)
|
| 158 |
+
parser.add_argument("--device", type=str, default="auto")
|
| 159 |
+
parser.add_argument("--temperature", type=float, default=0.8)
|
| 160 |
+
parser.add_argument("--response_len", type=int, default=256)
|
| 161 |
+
args = parser.parse_args()
|
| 162 |
+
|
| 163 |
+
if args.device == "auto":
|
| 164 |
+
if torch.cuda.is_available(): args.device = "cuda"
|
| 165 |
+
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): args.device = "mps"
|
| 166 |
+
else: args.device = "cpu"
|
| 167 |
+
|
| 168 |
+
ckpt_path = args.checkpoint or find_checkpoint()
|
| 169 |
+
if not ckpt_path or not os.path.exists(ckpt_path):
|
| 170 |
+
print("No checkpoint found. Train first:")
|
| 171 |
+
print(" python3 train_chat.py --data alpaca")
|
| 172 |
+
sys.exit(1)
|
| 173 |
+
|
| 174 |
+
print(f"Loading {ckpt_path}...")
|
| 175 |
+
ckpt = torch.load(ckpt_path, map_location=args.device, weights_only=False)
|
| 176 |
+
config = ckpt["config"]
|
| 177 |
+
model = PCSHODLM(config).to(args.device)
|
| 178 |
+
model.load_state_dict(ckpt["model_state_dict"], strict=False)
|
| 179 |
+
model.eval()
|
| 180 |
+
print(f"Model: {sum(p.numel() for p in model.parameters()):,} params on {args.device}")
|
| 181 |
+
|
| 182 |
+
print()
|
| 183 |
+
print("=" * 60)
|
| 184 |
+
print(" PC-SHO-DLM Chat")
|
| 185 |
+
print(" Conditional Masked Diffusion Chatbot")
|
| 186 |
+
print("=" * 60)
|
| 187 |
+
print()
|
| 188 |
+
print(" Type a message and the model generates a response.")
|
| 189 |
+
print(" The prompt stays fixed; the response is iteratively")
|
| 190 |
+
print(" denoised via predictive-coding energy minimization.")
|
| 191 |
+
print()
|
| 192 |
+
print(" /temp 0.5 Set temperature (0=greedy, 1=creative)")
|
| 193 |
+
print(" /len 512 Set response length")
|
| 194 |
+
print(" /quit Exit")
|
| 195 |
+
print()
|
| 196 |
+
|
| 197 |
+
temp = args.temperature
|
| 198 |
+
resp_len = args.response_len
|
| 199 |
+
|
| 200 |
+
while True:
|
| 201 |
+
try:
|
| 202 |
+
user_input = input("You> ").strip()
|
| 203 |
+
except (EOFError, KeyboardInterrupt):
|
| 204 |
+
print("\nBye!")
|
| 205 |
+
break
|
| 206 |
+
|
| 207 |
+
if not user_input:
|
| 208 |
+
continue
|
| 209 |
+
if user_input.lower() in ["/quit", "/exit", "/q"]:
|
| 210 |
+
break
|
| 211 |
+
elif user_input.lower().startswith("/temp"):
|
| 212 |
+
try: temp = float(user_input.split()[1])
|
| 213 |
+
except: pass
|
| 214 |
+
print(f" Temperature: {temp}")
|
| 215 |
+
continue
|
| 216 |
+
elif user_input.lower().startswith("/len"):
|
| 217 |
+
try: resp_len = int(user_input.split()[1])
|
| 218 |
+
except: pass
|
| 219 |
+
print(f" Response length: {resp_len}")
|
| 220 |
+
continue
|
| 221 |
+
|
| 222 |
+
print(" [Generating...]")
|
| 223 |
+
response = generate_response(model, user_input, response_len=resp_len,
|
| 224 |
+
device=args.device, temperature=temp)
|
| 225 |
+
# Clean up: strip trailing nulls/garbage
|
| 226 |
+
response = response.rstrip('\x00').strip()
|
| 227 |
+
print(f"\nBot> {response}\n")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
if __name__ == "__main__":
|
| 231 |
+
main()
|
checkpoints/backprop_1k/checkpoint_final.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:38b8018dae08bfc9075d6bfac79667077d44cd644a46648349e6a85f38428b3e
|
| 3 |
+
size 23465759
|
checkpoints/backprop_1k/training_log.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"step": [
|
| 3 |
+
100,
|
| 4 |
+
200,
|
| 5 |
+
300,
|
| 6 |
+
400,
|
| 7 |
+
500,
|
| 8 |
+
600,
|
| 9 |
+
700,
|
| 10 |
+
800,
|
| 11 |
+
900,
|
| 12 |
+
1000
|
| 13 |
+
],
|
| 14 |
+
"loss": [
|
| 15 |
+
3.973542594909668,
|
| 16 |
+
3.2462473058700563,
|
| 17 |
+
3.20215793132782,
|
| 18 |
+
3.201729962825775,
|
| 19 |
+
3.1888448429107665,
|
| 20 |
+
3.1946746253967286,
|
| 21 |
+
3.1782461738586427,
|
| 22 |
+
3.180178542137146,
|
| 23 |
+
3.1794990515708923,
|
| 24 |
+
3.1801758503913877
|
| 25 |
+
],
|
| 26 |
+
"energy_initial": [
|
| 27 |
+
5270595.51,
|
| 28 |
+
5267421.675,
|
| 29 |
+
5297561.015,
|
| 30 |
+
5288095.895,
|
| 31 |
+
5311662.89,
|
| 32 |
+
5295208.57,
|
| 33 |
+
5298536.89,
|
| 34 |
+
5305402.28,
|
| 35 |
+
5263141.3,
|
| 36 |
+
5298722.35
|
| 37 |
+
],
|
| 38 |
+
"energy_final": [
|
| 39 |
+
2167628.65875,
|
| 40 |
+
2161769.35875,
|
| 41 |
+
2170405.285,
|
| 42 |
+
2168934.0225,
|
| 43 |
+
2171327.31375,
|
| 44 |
+
2167877.45375,
|
| 45 |
+
2166740.25375,
|
| 46 |
+
2171946.41875,
|
| 47 |
+
2158902.235,
|
| 48 |
+
2165013.49875
|
| 49 |
+
],
|
| 50 |
+
"stationarity_residual": [
|
| 51 |
+
3901.9395750427248,
|
| 52 |
+
3898.7040367126465,
|
| 53 |
+
3911.786459350586,
|
| 54 |
+
3908.9566624450686,
|
| 55 |
+
3914.174656524658,
|
| 56 |
+
3906.5373867797853,
|
| 57 |
+
3903.444817810059,
|
| 58 |
+
3914.3790266418455,
|
| 59 |
+
3894.4947831726076,
|
| 60 |
+
3903.315328826904
|
| 61 |
+
],
|
| 62 |
+
"wall_time": [
|
| 63 |
+
114.7592351436615,
|
| 64 |
+
234.22663807868958,
|
| 65 |
+
352.5620460510254,
|
| 66 |
+
485.0994050502777,
|
| 67 |
+
639.9822609424591,
|
| 68 |
+
1040.4187860488892,
|
| 69 |
+
1186.257786989212,
|
| 70 |
+
1349.9577169418335,
|
| 71 |
+
1505.554505109787,
|
| 72 |
+
1641.0701520442963
|
| 73 |
+
],
|
| 74 |
+
"val_loss": [
|
| 75 |
+
[
|
| 76 |
+
500,
|
| 77 |
+
3.194992378991592
|
| 78 |
+
],
|
| 79 |
+
[
|
| 80 |
+
1000,
|
| 81 |
+
3.1876371541706154
|
| 82 |
+
]
|
| 83 |
+
],
|
| 84 |
+
"tokens_per_sec": [
|
| 85 |
+
3569.2116585409594,
|
| 86 |
+
3497.467268111434,
|
| 87 |
+
3485.3439664408997,
|
| 88 |
+
3377.4520911444724,
|
| 89 |
+
3200.0886977461646,
|
| 90 |
+
2362.125744896457,
|
| 91 |
+
2417.012584825354,
|
| 92 |
+
2427.335285303006,
|
| 93 |
+
2448.5330736871483,
|
| 94 |
+
2495.932300576898
|
| 95 |
+
]
|
| 96 |
+
}
|
checkpoints/chat/chat_final.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6b5b607dfd71e7f0d24d645e3af48be34864e575b704b210f7c8ddb32a133a42
|
| 3 |
+
size 42769221
|
checkpoints/chat/chat_step1000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:502f6ca445444da9f9e1c88bbc5ebbf7cbdeff3aa36ba6f4c8f4874621d76ba8
|
| 3 |
+
size 42770163
|
checkpoints/chat/chat_step1500.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c41874a395fef739961bb65451f27508029b56bb47202e9a4db14c36c5d5de9
|
| 3 |
+
size 42770163
|
checkpoints/chat/chat_step2000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e245f4d24200074dd971e45355ee687343efe8ebaadcc55f7158ecf252e78be6
|
| 3 |
+
size 42770163
|
checkpoints/chat/chat_step500.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7517356a64c7e488f8268c09614b8f745cbbfde2135f561c562c09d756165da0
|
| 3 |
+
size 42769849
|
checkpoints/checkpoint_final.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0f131ad73eee730d001ca4b1059527b827cb2fdb8c9fa13be9f0495b7ecb60e6
|
| 3 |
+
size 16091587
|
checkpoints/local_pc_1k/checkpoint_final.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9a7f7e2003540fb4077812024540c36ddd3745ffaf318338e150948be51a8476
|
| 3 |
+
size 23465759
|
checkpoints/local_pc_1k/training_log.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"step": [
|
| 3 |
+
100,
|
| 4 |
+
200,
|
| 5 |
+
300,
|
| 6 |
+
400,
|
| 7 |
+
500,
|
| 8 |
+
600,
|
| 9 |
+
700,
|
| 10 |
+
800,
|
| 11 |
+
900,
|
| 12 |
+
1000
|
| 13 |
+
],
|
| 14 |
+
"loss": [
|
| 15 |
+
4.258981928825379,
|
| 16 |
+
3.336215796470642,
|
| 17 |
+
3.2282044744491576,
|
| 18 |
+
3.2040278053283693,
|
| 19 |
+
3.1845848608016967,
|
| 20 |
+
3.1786249399185182,
|
| 21 |
+
3.1659100317955016,
|
| 22 |
+
3.1637249565124512,
|
| 23 |
+
3.161261990070343,
|
| 24 |
+
3.167942237854004
|
| 25 |
+
],
|
| 26 |
+
"energy_initial": [
|
| 27 |
+
833023.37125,
|
| 28 |
+
341392.37125,
|
| 29 |
+
266566.16546875,
|
| 30 |
+
231912.27,
|
| 31 |
+
214780.41046875,
|
| 32 |
+
204189.7409375,
|
| 33 |
+
196751.30359375,
|
| 34 |
+
191164.40421875,
|
| 35 |
+
185644.6478125,
|
| 36 |
+
180652.7578125
|
| 37 |
+
],
|
| 38 |
+
"energy_final": [
|
| 39 |
+
554832.4546875,
|
| 40 |
+
269502.8328125,
|
| 41 |
+
210375.1321875,
|
| 42 |
+
184373.66765625,
|
| 43 |
+
172335.49625,
|
| 44 |
+
165377.38859375,
|
| 45 |
+
160904.538125,
|
| 46 |
+
157588.87328125,
|
| 47 |
+
154221.20390625,
|
| 48 |
+
151236.68453125
|
| 49 |
+
],
|
| 50 |
+
"stationarity_residual": [
|
| 51 |
+
1561.5680824279784,
|
| 52 |
+
929.1791234207153,
|
| 53 |
+
735.0096200180054,
|
| 54 |
+
647.4497012710572,
|
| 55 |
+
609.4694246673585,
|
| 56 |
+
590.0452673149109,
|
| 57 |
+
580.4542396354675,
|
| 58 |
+
576.9368585586548,
|
| 59 |
+
572.0829350090027,
|
| 60 |
+
569.5673301887513
|
| 61 |
+
],
|
| 62 |
+
"wall_time": [
|
| 63 |
+
147.88746404647827,
|
| 64 |
+
299.2261378765106,
|
| 65 |
+
460.55058312416077,
|
| 66 |
+
654.5177249908447,
|
| 67 |
+
825.0155017375946,
|
| 68 |
+
1292.595095872879,
|
| 69 |
+
1495.5974118709564,
|
| 70 |
+
1665.1974637508392,
|
| 71 |
+
1813.2391319274902,
|
| 72 |
+
1930.159700870514
|
| 73 |
+
],
|
| 74 |
+
"val_loss": [
|
| 75 |
+
[
|
| 76 |
+
500,
|
| 77 |
+
3.1764627510126946
|
| 78 |
+
],
|
| 79 |
+
[
|
| 80 |
+
1000,
|
| 81 |
+
3.165879757393407
|
| 82 |
+
]
|
| 83 |
+
],
|
| 84 |
+
"tokens_per_sec": [
|
| 85 |
+
2769.673566592976,
|
| 86 |
+
2737.7287486097903,
|
| 87 |
+
2668.1108330476814,
|
| 88 |
+
2503.2171588980536,
|
| 89 |
+
2482.3775985864922,
|
| 90 |
+
1901.2914468319273,
|
| 91 |
+
1917.0934485726355,
|
| 92 |
+
1967.8146714318455,
|
| 93 |
+
2033.0467918378324,
|
| 94 |
+
2122.10419591326
|
| 95 |
+
]
|
| 96 |
+
}
|
checkpoints/local_pc_wiki_lambda_fixed/checkpoint_final.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:baa12367a523e90ef8b743035b26749b1e0d174fad696669a8cb5a20b39f5cbd
|
| 3 |
+
size 42509025
|
checkpoints/local_pc_wiki_lambda_fixed/checkpoint_step_2000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a87fc58b9d7ae96bbd5471996db14370f09e43b86b6d823348d76e1af145f11d
|
| 3 |
+
size 42510281
|
checkpoints/local_pc_wiki_lambda_fixed/training_log.json
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"step": [
|
| 3 |
+
50,
|
| 4 |
+
100,
|
| 5 |
+
150,
|
| 6 |
+
200,
|
| 7 |
+
250,
|
| 8 |
+
300,
|
| 9 |
+
350,
|
| 10 |
+
400,
|
| 11 |
+
450,
|
| 12 |
+
500,
|
| 13 |
+
550,
|
| 14 |
+
600,
|
| 15 |
+
650,
|
| 16 |
+
700,
|
| 17 |
+
750,
|
| 18 |
+
800,
|
| 19 |
+
850,
|
| 20 |
+
900,
|
| 21 |
+
950,
|
| 22 |
+
1000,
|
| 23 |
+
1050,
|
| 24 |
+
1100,
|
| 25 |
+
1150,
|
| 26 |
+
1200,
|
| 27 |
+
1250,
|
| 28 |
+
1300,
|
| 29 |
+
1350,
|
| 30 |
+
1400,
|
| 31 |
+
1450,
|
| 32 |
+
1500,
|
| 33 |
+
1550,
|
| 34 |
+
1600,
|
| 35 |
+
1650,
|
| 36 |
+
1700,
|
| 37 |
+
1750,
|
| 38 |
+
1800,
|
| 39 |
+
1850,
|
| 40 |
+
1900,
|
| 41 |
+
1950,
|
| 42 |
+
2000,
|
| 43 |
+
2050,
|
| 44 |
+
2100,
|
| 45 |
+
2150,
|
| 46 |
+
2200,
|
| 47 |
+
2250,
|
| 48 |
+
2300,
|
| 49 |
+
2350,
|
| 50 |
+
2400,
|
| 51 |
+
2450,
|
| 52 |
+
2500,
|
| 53 |
+
2550,
|
| 54 |
+
2600,
|
| 55 |
+
2650,
|
| 56 |
+
2700,
|
| 57 |
+
2750,
|
| 58 |
+
2800,
|
| 59 |
+
2850,
|
| 60 |
+
2900,
|
| 61 |
+
2950,
|
| 62 |
+
3000
|
| 63 |
+
],
|
| 64 |
+
"loss": [
|
| 65 |
+
0.21437864273786544,
|
| 66 |
+
0.06857220411300659,
|
| 67 |
+
0.035148728638887405,
|
| 68 |
+
0.020972895678132774,
|
| 69 |
+
0.013533507781103253,
|
| 70 |
+
0.008646295601502062,
|
| 71 |
+
0.0061453641159459945,
|
| 72 |
+
0.004681998491287231,
|
| 73 |
+
0.0033234256599098443,
|
| 74 |
+
0.002539557530544698,
|
| 75 |
+
0.0020994919049553574,
|
| 76 |
+
0.0019077495508827268,
|
| 77 |
+
0.0015839052782393992,
|
| 78 |
+
0.0013997956831008195,
|
| 79 |
+
0.0012919189885724335,
|
| 80 |
+
0.0011379401991143824,
|
| 81 |
+
0.0010197754809632897,
|
| 82 |
+
0.0009524802933447063,
|
| 83 |
+
0.0009402855590451509,
|
| 84 |
+
0.000933931681793183,
|
| 85 |
+
0.0008880252955714241,
|
| 86 |
+
0.0007404407643480227,
|
| 87 |
+
0.0007191342004807666,
|
| 88 |
+
0.0006912627309793606,
|
| 89 |
+
0.0006465482013300061,
|
| 90 |
+
0.0006812598794931546,
|
| 91 |
+
0.0006511295342352242,
|
| 92 |
+
0.0006275616912171244,
|
| 93 |
+
0.0005930715601425618,
|
| 94 |
+
0.0005344201344996691,
|
| 95 |
+
0.0005560434464132413,
|
| 96 |
+
0.0005294423777377232,
|
| 97 |
+
0.0004877809778554365,
|
| 98 |
+
0.0004382653089123778,
|
| 99 |
+
0.0004203213079017587,
|
| 100 |
+
0.00039554817631142213,
|
| 101 |
+
0.00039055546949384734,
|
| 102 |
+
0.000328213750035502,
|
| 103 |
+
0.0003372134832898155,
|
| 104 |
+
0.0003075990959769115,
|
| 105 |
+
0.0003370191325666383,
|
| 106 |
+
0.00023736593255307525,
|
| 107 |
+
0.0002483331604162231,
|
| 108 |
+
0.00025497345719486473,
|
| 109 |
+
0.0001915762400312815,
|
| 110 |
+
0.00019251465288107285,
|
| 111 |
+
0.00019092288392130285,
|
| 112 |
+
0.00019388364802580327,
|
| 113 |
+
0.00016434719480457716,
|
| 114 |
+
0.0001352085336111486,
|
| 115 |
+
0.00011794728372478858,
|
| 116 |
+
0.00014831473417871167,
|
| 117 |
+
0.00011608733126195148,
|
| 118 |
+
8.511820582498331e-05,
|
| 119 |
+
8.775017347943503e-05,
|
| 120 |
+
0.00010035085459094262,
|
| 121 |
+
5.40398766315775e-05,
|
| 122 |
+
7.603460144309793e-05,
|
| 123 |
+
8.572758386435453e-05,
|
| 124 |
+
6.787052403524285e-05
|
| 125 |
+
],
|
| 126 |
+
"energy_initial": [
|
| 127 |
+
7698684.3,
|
| 128 |
+
6107091.13,
|
| 129 |
+
5852354.26,
|
| 130 |
+
5848288.87,
|
| 131 |
+
5937238.27,
|
| 132 |
+
5706541.045,
|
| 133 |
+
5813235.275,
|
| 134 |
+
6029184.51,
|
| 135 |
+
5949668.485,
|
| 136 |
+
5744343.065,
|
| 137 |
+
5896261.11,
|
| 138 |
+
6125549.59,
|
| 139 |
+
6070470.95,
|
| 140 |
+
6229371.64,
|
| 141 |
+
6058217.295,
|
| 142 |
+
6054126.04,
|
| 143 |
+
6039307.94,
|
| 144 |
+
5924170.35,
|
| 145 |
+
6017140.885,
|
| 146 |
+
5817855.76,
|
| 147 |
+
6018289.2,
|
| 148 |
+
5984032.64,
|
| 149 |
+
5971326.27,
|
| 150 |
+
6154519.66,
|
| 151 |
+
5873810.01,
|
| 152 |
+
5986345.085,
|
| 153 |
+
5936406.99,
|
| 154 |
+
6091542.26,
|
| 155 |
+
5925722.0,
|
| 156 |
+
5945736.025,
|
| 157 |
+
5962467.03,
|
| 158 |
+
5780643.0,
|
| 159 |
+
5900887.37,
|
| 160 |
+
6127922.5,
|
| 161 |
+
6164705.94,
|
| 162 |
+
5931382.21,
|
| 163 |
+
5883905.46,
|
| 164 |
+
5932295.24,
|
| 165 |
+
6094541.57,
|
| 166 |
+
6033401.53,
|
| 167 |
+
5720540.8,
|
| 168 |
+
5947334.405,
|
| 169 |
+
5955467.49,
|
| 170 |
+
6072561.455,
|
| 171 |
+
5809340.885,
|
| 172 |
+
6075700.67,
|
| 173 |
+
5956099.91,
|
| 174 |
+
6075797.79,
|
| 175 |
+
6242412.85,
|
| 176 |
+
6106390.29,
|
| 177 |
+
5953161.19,
|
| 178 |
+
6179365.98,
|
| 179 |
+
6157424.08,
|
| 180 |
+
6094414.41,
|
| 181 |
+
6175474.25,
|
| 182 |
+
6020570.29,
|
| 183 |
+
6047099.055,
|
| 184 |
+
6029787.67,
|
| 185 |
+
6218495.38,
|
| 186 |
+
6081523.8
|
| 187 |
+
],
|
| 188 |
+
"energy_final": [
|
| 189 |
+
1652554.96375,
|
| 190 |
+
705944.41125,
|
| 191 |
+
607953.49375,
|
| 192 |
+
572285.07875,
|
| 193 |
+
537746.90125,
|
| 194 |
+
494917.79125,
|
| 195 |
+
473506.921875,
|
| 196 |
+
457005.64875,
|
| 197 |
+
438494.308125,
|
| 198 |
+
416447.076875,
|
| 199 |
+
406914.03,
|
| 200 |
+
400999.99,
|
| 201 |
+
390525.980625,
|
| 202 |
+
384762.0225,
|
| 203 |
+
373795.095625,
|
| 204 |
+
368545.7475,
|
| 205 |
+
363369.811875,
|
| 206 |
+
357510.87875,
|
| 207 |
+
357484.321875,
|
| 208 |
+
353577.7525,
|
| 209 |
+
357915.508125,
|
| 210 |
+
362979.398125,
|
| 211 |
+
371097.1375,
|
| 212 |
+
380386.156875,
|
| 213 |
+
387829.081875,
|
| 214 |
+
399150.586875,
|
| 215 |
+
409923.39875,
|
| 216 |
+
416817.498125,
|
| 217 |
+
421484.156875,
|
| 218 |
+
427243.47125,
|
| 219 |
+
432332.433125,
|
| 220 |
+
435388.8875,
|
| 221 |
+
439161.039375,
|
| 222 |
+
438539.3175,
|
| 223 |
+
440151.813125,
|
| 224 |
+
443108.650625,
|
| 225 |
+
444380.25125,
|
| 226 |
+
443640.124375,
|
| 227 |
+
442540.393125,
|
| 228 |
+
444312.621875,
|
| 229 |
+
446053.64125,
|
| 230 |
+
444830.1425,
|
| 231 |
+
447178.676875,
|
| 232 |
+
447786.30125,
|
| 233 |
+
448424.36625,
|
| 234 |
+
450646.51125,
|
| 235 |
+
451476.01375,
|
| 236 |
+
453405.551875,
|
| 237 |
+
456309.660625,
|
| 238 |
+
459526.745,
|
| 239 |
+
461789.379375,
|
| 240 |
+
467258.625,
|
| 241 |
+
471400.43125,
|
| 242 |
+
476037.479375,
|
| 243 |
+
482717.544375,
|
| 244 |
+
489311.323125,
|
| 245 |
+
496543.541875,
|
| 246 |
+
504736.0525,
|
| 247 |
+
514683.98125,
|
| 248 |
+
522998.31875
|
| 249 |
+
],
|
| 250 |
+
"stationarity_residual": [
|
| 251 |
+
0.0,
|
| 252 |
+
0.0,
|
| 253 |
+
0.0,
|
| 254 |
+
0.0,
|
| 255 |
+
0.0,
|
| 256 |
+
0.0,
|
| 257 |
+
0.0,
|
| 258 |
+
0.0,
|
| 259 |
+
0.0,
|
| 260 |
+
0.0,
|
| 261 |
+
0.0,
|
| 262 |
+
0.0,
|
| 263 |
+
0.0,
|
| 264 |
+
0.0,
|
| 265 |
+
0.0,
|
| 266 |
+
0.0,
|
| 267 |
+
0.0,
|
| 268 |
+
0.0,
|
| 269 |
+
0.0,
|
| 270 |
+
0.0,
|
| 271 |
+
0.0,
|
| 272 |
+
0.0,
|
| 273 |
+
0.0,
|
| 274 |
+
0.0,
|
| 275 |
+
0.0,
|
| 276 |
+
0.0,
|
| 277 |
+
0.0,
|
| 278 |
+
0.0,
|
| 279 |
+
0.0,
|
| 280 |
+
0.0,
|
| 281 |
+
0.0,
|
| 282 |
+
0.0,
|
| 283 |
+
0.0,
|
| 284 |
+
0.0,
|
| 285 |
+
0.0,
|
| 286 |
+
0.0,
|
| 287 |
+
0.0,
|
| 288 |
+
0.0,
|
| 289 |
+
0.0,
|
| 290 |
+
0.0,
|
| 291 |
+
0.0,
|
| 292 |
+
0.0,
|
| 293 |
+
0.0,
|
| 294 |
+
0.0,
|
| 295 |
+
0.0,
|
| 296 |
+
0.0,
|
| 297 |
+
0.0,
|
| 298 |
+
0.0,
|
| 299 |
+
0.0,
|
| 300 |
+
0.0,
|
| 301 |
+
0.0,
|
| 302 |
+
0.0,
|
| 303 |
+
0.0,
|
| 304 |
+
0.0,
|
| 305 |
+
0.0,
|
| 306 |
+
0.0,
|
| 307 |
+
0.0,
|
| 308 |
+
0.0,
|
| 309 |
+
0.0,
|
| 310 |
+
0.0
|
| 311 |
+
],
|
| 312 |
+
"wall_time": [
|
| 313 |
+
46.83224701881409,
|
| 314 |
+
93.27795815467834,
|
| 315 |
+
144.22594499588013,
|
| 316 |
+
187.70664811134338,
|
| 317 |
+
223.2145059108734,
|
| 318 |
+
258.57073402404785,
|
| 319 |
+
305.0492169857025,
|
| 320 |
+
383.0472061634064,
|
| 321 |
+
451.9058039188385,
|
| 322 |
+
535.2478311061859,
|
| 323 |
+
1005.1899790763855,
|
| 324 |
+
1116.8730499744415,
|
| 325 |
+
1236.574786901474,
|
| 326 |
+
1339.8828241825104,
|
| 327 |
+
1423.296756029129,
|
| 328 |
+
1506.158792257309,
|
| 329 |
+
1577.9990320205688,
|
| 330 |
+
1657.4707880020142,
|
| 331 |
+
1743.5079112052917,
|
| 332 |
+
1819.936054944992,
|
| 333 |
+
2085.8407900333405,
|
| 334 |
+
2149.638072013855,
|
| 335 |
+
2208.5191662311554,
|
| 336 |
+
2267.8005650043488,
|
| 337 |
+
2329.4335021972656,
|
| 338 |
+
2393.2623631954193,
|
| 339 |
+
2461.015599966049,
|
| 340 |
+
2525.264710187912,
|
| 341 |
+
2585.4516730308533,
|
| 342 |
+
2651.2439770698547,
|
| 343 |
+
2901.422744035721,
|
| 344 |
+
2962.9505100250244,
|
| 345 |
+
3024.1742990016937,
|
| 346 |
+
3087.3891592025757,
|
| 347 |
+
3146.6180799007416,
|
| 348 |
+
3204.875967025757,
|
| 349 |
+
3270.302752017975,
|
| 350 |
+
3331.1951899528503,
|
| 351 |
+
3391.0012259483337,
|
| 352 |
+
3451.4704518318176,
|
| 353 |
+
3729.473039150238,
|
| 354 |
+
3795.7775888442993,
|
| 355 |
+
3854.923315048218,
|
| 356 |
+
3914.674096107483,
|
| 357 |
+
3973.7355649471283,
|
| 358 |
+
4033.9523270130157,
|
| 359 |
+
4101.106842041016,
|
| 360 |
+
4168.646975040436,
|
| 361 |
+
4235.202388286591,
|
| 362 |
+
4298.994647979736,
|
| 363 |
+
4530.3150498867035,
|
| 364 |
+
4593.397349119186,
|
| 365 |
+
4659.151156902313,
|
| 366 |
+
4729.11607003212,
|
| 367 |
+
4799.21485710144,
|
| 368 |
+
4870.703770160675,
|
| 369 |
+
4937.933058023453,
|
| 370 |
+
5006.13449215889,
|
| 371 |
+
5070.305644989014,
|
| 372 |
+
5133.637190103531
|
| 373 |
+
],
|
| 374 |
+
"val_loss": [
|
| 375 |
+
[
|
| 376 |
+
500,
|
| 377 |
+
0.0019980114247109305
|
| 378 |
+
],
|
| 379 |
+
[
|
| 380 |
+
1000,
|
| 381 |
+
0.0006265220506625516
|
| 382 |
+
],
|
| 383 |
+
[
|
| 384 |
+
1500,
|
| 385 |
+
0.0004066362535410008
|
| 386 |
+
],
|
| 387 |
+
[
|
| 388 |
+
2000,
|
| 389 |
+
0.00019371463765036995
|
| 390 |
+
],
|
| 391 |
+
[
|
| 392 |
+
2500,
|
| 393 |
+
8.949936562472213e-05
|
| 394 |
+
],
|
| 395 |
+
[
|
| 396 |
+
3000,
|
| 397 |
+
2.2330263250989578e-05
|
| 398 |
+
]
|
| 399 |
+
],
|
| 400 |
+
"tokens_per_sec": [
|
| 401 |
+
4373.055171103043,
|
| 402 |
+
4391.176737818168,
|
| 403 |
+
4259.982488015943,
|
| 404 |
+
4364.256717823169,
|
| 405 |
+
4587.515474504465,
|
| 406 |
+
4752.27795843948,
|
| 407 |
+
4699.569512637668,
|
| 408 |
+
4277.279598016609,
|
| 409 |
+
4078.7261062286234,
|
| 410 |
+
3826.264920620864,
|
| 411 |
+
2241.168382985648,
|
| 412 |
+
2200.4291356624994,
|
| 413 |
+
2153.0440602555573,
|
| 414 |
+
2139.8886143266573,
|
| 415 |
+
2158.369283838323,
|
| 416 |
+
2175.6006185038414,
|
| 417 |
+
2206.338489030593,
|
| 418 |
+
2224.1115962253207,
|
| 419 |
+
2231.82239380262,
|
| 420 |
+
2250.628525585094,
|
| 421 |
+
2061.9023372015154,
|
| 422 |
+
2095.9807414366264,
|
| 423 |
+
2132.831841363782,
|
| 424 |
+
2167.386354800813,
|
| 425 |
+
2197.95928717025,
|
| 426 |
+
2224.912772576455,
|
| 427 |
+
2246.8772648480094,
|
| 428 |
+
2270.8114428024805,
|
| 429 |
+
2297.1614832149003,
|
| 430 |
+
2317.4027185496248,
|
| 431 |
+
2188.1678611125676,
|
| 432 |
+
2211.84929610743,
|
| 433 |
+
2234.7918247407256,
|
| 434 |
+
2255.368416788276,
|
| 435 |
+
2278.0012756508763,
|
| 436 |
+
2300.494644990031,
|
| 437 |
+
2317.0943409823944,
|
| 438 |
+
2336.218551069099,
|
| 439 |
+
2355.410531521198,
|
| 440 |
+
2373.481133425962,
|
| 441 |
+
2251.47089464232,
|
| 442 |
+
2266.0969455322934,
|
| 443 |
+
2284.4553004784866,
|
| 444 |
+
2301.9029882871214,
|
| 445 |
+
2319.228305299329,
|
| 446 |
+
2335.3771280127485,
|
| 447 |
+
2347.073697599545,
|
| 448 |
+
2358.175220607316,
|
| 449 |
+
2369.4735410413005,
|
| 450 |
+
2381.95225593318,
|
| 451 |
+
2305.535020188322,
|
| 452 |
+
2318.4582544425707,
|
| 453 |
+
2329.6947522124747,
|
| 454 |
+
2338.5342707236377,
|
| 455 |
+
2347.0505771027442,
|
| 456 |
+
2354.6494595424074,
|
| 457 |
+
2364.0660703230933,
|
| 458 |
+
2372.768853614529,
|
| 459 |
+
2383.1304946954892,
|
| 460 |
+
2393.6245482420204
|
| 461 |
+
]
|
| 462 |
+
}
|
checkpoints/training_log.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"step": [
|
| 3 |
+
25,
|
| 4 |
+
50,
|
| 5 |
+
75,
|
| 6 |
+
100
|
| 7 |
+
],
|
| 8 |
+
"loss": [
|
| 9 |
+
4.83566909790039,
|
| 10 |
+
4.001754846572876,
|
| 11 |
+
3.6740700721740724,
|
| 12 |
+
3.5564898300170897
|
| 13 |
+
],
|
| 14 |
+
"energy_initial": [
|
| 15 |
+
1551801.665,
|
| 16 |
+
1532687.17,
|
| 17 |
+
1541912.385,
|
| 18 |
+
1559144.77
|
| 19 |
+
],
|
| 20 |
+
"energy_final": [
|
| 21 |
+
605239.6925,
|
| 22 |
+
603282.4875,
|
| 23 |
+
602236.6225,
|
| 24 |
+
604062.935
|
| 25 |
+
],
|
| 26 |
+
"stationarity_residual": [
|
| 27 |
+
1552.1239495849609,
|
| 28 |
+
1549.458076171875,
|
| 29 |
+
1548.9330493164061,
|
| 30 |
+
1552.3543615722656
|
| 31 |
+
],
|
| 32 |
+
"wall_time": [
|
| 33 |
+
15.414806127548218,
|
| 34 |
+
20.527431964874268,
|
| 35 |
+
25.813805103302002,
|
| 36 |
+
31.105968236923218
|
| 37 |
+
],
|
| 38 |
+
"val_loss": [],
|
| 39 |
+
"tokens_per_sec": [
|
| 40 |
+
3321.4819295391003,
|
| 41 |
+
4988.446688081726,
|
| 42 |
+
5950.304474110719,
|
| 43 |
+
6583.945512967493
|
| 44 |
+
]
|
| 45 |
+
}
|
checkpoints/unified_wiki_lambda_fixed/checkpoint_step_2000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:71cc3e02290be38b9f031d4bbe95b8858f07dbbd2cda48be0bef91df363fec0e
|
| 3 |
+
size 42510281
|
data/ao3-metadata/fandoms.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f200e02b76d0202264555fe51c6cc1e3442ed9fb0f88fa9e6db065ab8035d0d1
|
| 3 |
+
size 8647151
|
data/ao3-metadata/random works - Oct 2024 - tag binary - 200.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:12dafe2f91021e2d49527edd2240a5c2ab23c733b589cc1a197619fddfd21a02
|
| 3 |
+
size 174738654
|
data/ao3-metadata/random works - Oct 2024 - tag binary.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:84131d59bcee631bd06eb22ad5079f8fb1879234a697508d36940f1e13ca99fd
|
| 3 |
+
size 1221483677
|
data/ao3-metadata/random works - Oct 2025 - fix indecies.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:95e5f7c8415b24a05754433c419c8974f7480bd397a91a0a102c42e55180a009
|
| 3 |
+
size 63870415
|
data/ao3-metadata/random works - Oct 2025 - top tags - 200.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1dddee657a76495c1192250d6e1dceffeb674f8cfeb50ecefb95f8668147b897
|
| 3 |
+
size 26079
|
data/ao3-metadata/random works - Oct 2025 - top tags.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bc80d1b33d11ff974e765ff4b354b0098aa74b45d61005f1455cf5f54e726d7b
|
| 3 |
+
size 283715
|
data/ao3-metadata/random works - Oct 2025.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3a4ca256abca1dcaf0c237ff26498c9d2a6dd6a5124f059c087361e6400906a2
|
| 3 |
+
size 63687379
|
data/python_code.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:283ee7a13da2b086eebff5e80a1b1af07e1bcdfa946671729407e18019ad6196
|
| 3 |
+
size 10017726
|
data/tinystories_val.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:85b60248b6b837e31755e8992d9c926177f0bff65c55072bd33ff8cccf5a58cf
|
| 3 |
+
size 19240339
|
data/wikitext-103/LICENSE.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bb21dc59e69079967d10f54aaa408c2ba548210aea16babf57b4d5f2e8f169c5
|
| 3 |
+
size 22242
|
data/wikitext-103/README.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1b50ff59fefaf57b1af4cd875ef0fde65f9bbf8db7ffb5ad64e43084ef3f66bf
|
| 3 |
+
size 371
|
data/wikitext-103/wiki.test.tokens
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:56db52eb157b1ab5c89646eef70510c1eca6e12a3bfdb99f0d6b05b4eacb75b9
|
| 3 |
+
size 1281077
|
data/wikitext-103/wiki.train.tokens
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2082f99929dee10a3b96da7d6ef7ca4dbb4d7df9d51db264f14173a36989f826
|
| 3 |
+
size 539209157
|
data/wikitext-103/wiki.valid.tokens
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9aee9f52d6e77de6c7751fc5e7c44287db3ec0eaf15477098acc6b93c1c4250b
|
| 3 |
+
size 1142309
|
diagnostics_output/diagnostics.json
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"stationarity": {
|
| 3 |
+
"2": {
|
| 4 |
+
"stationarity_residual": 1200.3260688781738,
|
| 5 |
+
"energy": 176276.640625
|
| 6 |
+
},
|
| 7 |
+
"4": {
|
| 8 |
+
"stationarity_residual": 764.5930786132812,
|
| 9 |
+
"energy": 137036.515625
|
| 10 |
+
},
|
| 11 |
+
"8": {
|
| 12 |
+
"stationarity_residual": 476.9359664916992,
|
| 13 |
+
"energy": 110008.8125
|
| 14 |
+
},
|
| 15 |
+
"16": {
|
| 16 |
+
"stationarity_residual": 306.9395751953125,
|
| 17 |
+
"energy": 89895.734375
|
| 18 |
+
}
|
| 19 |
+
},
|
| 20 |
+
"hessian": {
|
| 21 |
+
"eigenvalues": [
|
| 22 |
+
0.24301810562610626,
|
| 23 |
+
0.41752108931541443,
|
| 24 |
+
1.0334908962249756,
|
| 25 |
+
1.3541364669799805,
|
| 26 |
+
2.169743776321411,
|
| 27 |
+
2.450981378555298,
|
| 28 |
+
3.0029847621917725,
|
| 29 |
+
3.4423043727874756,
|
| 30 |
+
4.003973007202148,
|
| 31 |
+
4.973252296447754
|
| 32 |
+
],
|
| 33 |
+
"lambda_min": 0.24301810562610626,
|
| 34 |
+
"lambda_max": 4.973252296447754,
|
| 35 |
+
"effective_kappa": 20.46453404627931
|
| 36 |
+
},
|
| 37 |
+
"monotonicity": {
|
| 38 |
+
"potential_energies": [
|
| 39 |
+
366367.34375,
|
| 40 |
+
225438.8125,
|
| 41 |
+
175794.296875,
|
| 42 |
+
151354.890625,
|
| 43 |
+
136789.5625,
|
| 44 |
+
127010.2890625,
|
| 45 |
+
119876.6328125,
|
| 46 |
+
114350.75,
|
| 47 |
+
109876.9140625,
|
| 48 |
+
106133.8046875,
|
| 49 |
+
102923.390625,
|
| 50 |
+
100117.0234375,
|
| 51 |
+
97627.109375,
|
| 52 |
+
95391.6015625,
|
| 53 |
+
93365.0234375,
|
| 54 |
+
91513.109375
|
| 55 |
+
],
|
| 56 |
+
"kinetic_energies": [
|
| 57 |
+
5606.288420778961,
|
| 58 |
+
1861.3425807472438,
|
| 59 |
+
876.1042447986551,
|
| 60 |
+
508.8102243544282,
|
| 61 |
+
336.10912394027946,
|
| 62 |
+
242.68130300539553,
|
| 63 |
+
186.8547363422431,
|
| 64 |
+
150.827149615861,
|
| 65 |
+
126.0891513161979,
|
| 66 |
+
108.22230372848355,
|
| 67 |
+
94.77399205873564,
|
| 68 |
+
84.30399400153124,
|
| 69 |
+
75.9253957528357,
|
| 70 |
+
69.06781523144457,
|
| 71 |
+
63.350062110544286,
|
| 72 |
+
58.50883019699609
|
| 73 |
+
],
|
| 74 |
+
"total_energies": [
|
| 75 |
+
371973.63217077893,
|
| 76 |
+
227300.15508074724,
|
| 77 |
+
176670.40111979865,
|
| 78 |
+
151863.70084935444,
|
| 79 |
+
137125.6716239403,
|
| 80 |
+
127252.97036550539,
|
| 81 |
+
120063.48754884224,
|
| 82 |
+
114501.57714961586,
|
| 83 |
+
110003.00321381619,
|
| 84 |
+
106242.02699122849,
|
| 85 |
+
103018.16461705873,
|
| 86 |
+
100201.32743150153,
|
| 87 |
+
97703.03477075284,
|
| 88 |
+
95460.66937773145,
|
| 89 |
+
93428.37349961055,
|
| 90 |
+
91571.618205197
|
| 91 |
+
],
|
| 92 |
+
"n_violations": 0,
|
| 93 |
+
"violation_rate": 0.0
|
| 94 |
+
},
|
| 95 |
+
"precision": {
|
| 96 |
+
"pearson_prec_inv_error": -0.14354610443115234,
|
| 97 |
+
"rank_correlation": 0.20927321910858154,
|
| 98 |
+
"mean_precision": 0.6959661245346069,
|
| 99 |
+
"mean_sq_error": 0.02698444202542305
|
| 100 |
+
},
|
| 101 |
+
"contraction": {
|
| 102 |
+
"distances": [
|
| 103 |
+
14.491872787475586,
|
| 104 |
+
13.412360668182373,
|
| 105 |
+
12.603797197341919,
|
| 106 |
+
11.945123672485352,
|
| 107 |
+
11.38826036453247,
|
| 108 |
+
10.908653974533081,
|
| 109 |
+
10.490684747695923,
|
| 110 |
+
10.123239278793335,
|
| 111 |
+
9.7978835105896
|
| 112 |
+
],
|
| 113 |
+
"contraction_factors": [
|
| 114 |
+
0.9255091363880749,
|
| 115 |
+
0.9397150515972496,
|
| 116 |
+
0.9477400727301866,
|
| 117 |
+
0.9533815368328441,
|
| 118 |
+
0.9578858952423434,
|
| 119 |
+
0.9616846195861622,
|
| 120 |
+
0.9649741196366338,
|
| 121 |
+
0.9678605079615863
|
| 122 |
+
],
|
| 123 |
+
"avg_contraction": 0.9523438674968852,
|
| 124 |
+
"is_contractive": true
|
| 125 |
+
},
|
| 126 |
+
"freeze_accuracy": {
|
| 127 |
+
"adaptive_vs_full_match": 0.9121338725090027,
|
| 128 |
+
"early_stable_rate": 1.0
|
| 129 |
+
}
|
| 130 |
+
}
|
experiments/ablation_runner.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PC-SHO-DLM Ablation Study Runner
|
| 3 |
+
|
| 4 |
+
Runs the critical ablations defined in the paper:
|
| 5 |
+
1. First-order vs second-order settling
|
| 6 |
+
2. Fixed vs learned precision
|
| 7 |
+
3. Cold-start vs warm-start (state continuation)
|
| 8 |
+
4. Uniform vs adaptive settling
|
| 9 |
+
5. Forward-only vs bidirectional PC
|
| 10 |
+
6. Tied vs learned feedback
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
from dataclasses import dataclass, field, asdict
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
| 24 |
+
from model import PCSHODLM, PCSHOConfig, LocalParameterUpdater, count_parameters
|
| 25 |
+
from train import CharLevelDataset, Trainer
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class AblationConfig:
|
| 30 |
+
"""Configuration for an ablation experiment."""
|
| 31 |
+
name: str
|
| 32 |
+
description: str
|
| 33 |
+
|
| 34 |
+
# Architecture overrides
|
| 35 |
+
use_second_order: bool = True
|
| 36 |
+
use_learned_precision: bool = True
|
| 37 |
+
use_state_continuation: bool = True
|
| 38 |
+
use_adaptive_settling: bool = True
|
| 39 |
+
use_feedback: bool = True
|
| 40 |
+
tied_feedback: bool = False
|
| 41 |
+
|
| 42 |
+
# Training
|
| 43 |
+
training_mode: str = "local"
|
| 44 |
+
max_steps: int = 2000
|
| 45 |
+
batch_size: int = 16
|
| 46 |
+
lr: float = 1e-4
|
| 47 |
+
seq_len: int = 128
|
| 48 |
+
n_settling: int = 8
|
| 49 |
+
|
| 50 |
+
# Model
|
| 51 |
+
d_model: int = 256
|
| 52 |
+
n_layers: int = 4
|
| 53 |
+
n_heads: int = 4
|
| 54 |
+
n_diffusion: int = 100
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# =============================================================================
|
| 58 |
+
# Define ablation experiments
|
| 59 |
+
# =============================================================================
|
| 60 |
+
|
| 61 |
+
ABLATIONS = [
|
| 62 |
+
# Full model (baseline)
|
| 63 |
+
AblationConfig(
|
| 64 |
+
name="full_model",
|
| 65 |
+
description="Full PC-SHO-DLM with all components",
|
| 66 |
+
),
|
| 67 |
+
|
| 68 |
+
# Ablation 1: First-order settling (no momentum)
|
| 69 |
+
AblationConfig(
|
| 70 |
+
name="first_order",
|
| 71 |
+
description="First-order settling (gamma=1, no velocity)",
|
| 72 |
+
use_second_order=False,
|
| 73 |
+
),
|
| 74 |
+
|
| 75 |
+
# Ablation 2: Fixed precision (no learned precision heads)
|
| 76 |
+
AblationConfig(
|
| 77 |
+
name="fixed_precision",
|
| 78 |
+
description="Fixed uniform precision (no learned heads)",
|
| 79 |
+
use_learned_precision=False,
|
| 80 |
+
),
|
| 81 |
+
|
| 82 |
+
# Ablation 3: No state continuation (cold restart each step)
|
| 83 |
+
AblationConfig(
|
| 84 |
+
name="no_continuation",
|
| 85 |
+
description="Cold restart at each diffusion step",
|
| 86 |
+
use_state_continuation=False,
|
| 87 |
+
),
|
| 88 |
+
|
| 89 |
+
# Ablation 4: No adaptive settling (all tokens always active)
|
| 90 |
+
AblationConfig(
|
| 91 |
+
name="no_adaptive",
|
| 92 |
+
description="Uniform settling (no token freezing)",
|
| 93 |
+
use_adaptive_settling=False,
|
| 94 |
+
),
|
| 95 |
+
|
| 96 |
+
# Ablation 5: No feedback (forward-only, no top-down)
|
| 97 |
+
AblationConfig(
|
| 98 |
+
name="no_feedback",
|
| 99 |
+
description="Forward-only stack (no top-down predictions)",
|
| 100 |
+
use_feedback=False,
|
| 101 |
+
),
|
| 102 |
+
|
| 103 |
+
# Ablation 6: Tied feedback (transpose of forward weights)
|
| 104 |
+
AblationConfig(
|
| 105 |
+
name="tied_feedback",
|
| 106 |
+
description="Tied feedback (weight transpose)",
|
| 107 |
+
tied_feedback=True,
|
| 108 |
+
),
|
| 109 |
+
|
| 110 |
+
# Ablation 7: Standard backprop training (for comparison)
|
| 111 |
+
AblationConfig(
|
| 112 |
+
name="backprop_baseline",
|
| 113 |
+
description="Standard backprop training (not local)",
|
| 114 |
+
training_mode="backprop",
|
| 115 |
+
),
|
| 116 |
+
|
| 117 |
+
# Ablation 8: Varying settling steps
|
| 118 |
+
AblationConfig(
|
| 119 |
+
name="settling_k2",
|
| 120 |
+
description="Only 2 settling steps",
|
| 121 |
+
n_settling=2,
|
| 122 |
+
),
|
| 123 |
+
AblationConfig(
|
| 124 |
+
name="settling_k16",
|
| 125 |
+
description="16 settling steps",
|
| 126 |
+
n_settling=16,
|
| 127 |
+
),
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def create_model_from_ablation(ablation: AblationConfig) -> PCSHODLM:
|
| 132 |
+
"""Create a model configured for a specific ablation."""
|
| 133 |
+
config = PCSHOConfig(
|
| 134 |
+
vocab_size=257,
|
| 135 |
+
max_seq_len=ablation.seq_len,
|
| 136 |
+
d_model=ablation.d_model,
|
| 137 |
+
n_heads=ablation.n_heads,
|
| 138 |
+
n_layers=ablation.n_layers,
|
| 139 |
+
d_ff=ablation.d_model * 4,
|
| 140 |
+
n_diffusion_steps=ablation.n_diffusion,
|
| 141 |
+
n_settling_steps=ablation.n_settling,
|
| 142 |
+
mask_token_id=0,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# Apply ablation modifications
|
| 146 |
+
if not ablation.use_second_order:
|
| 147 |
+
# Force first-order by setting gamma_min = gamma_max = 1
|
| 148 |
+
config.gamma_min = 1.0
|
| 149 |
+
config.gamma_max = 1.0
|
| 150 |
+
|
| 151 |
+
if not ablation.use_state_continuation:
|
| 152 |
+
config.velocity_decay = 0.0 # No velocity carry-over
|
| 153 |
+
|
| 154 |
+
if not ablation.use_adaptive_settling:
|
| 155 |
+
config.settling_threshold = float("inf") # Never freeze tokens
|
| 156 |
+
|
| 157 |
+
if not ablation.use_feedback:
|
| 158 |
+
config.feedback_rank = 0 # Will need model modification
|
| 159 |
+
|
| 160 |
+
model = PCSHODLM(config)
|
| 161 |
+
|
| 162 |
+
if not ablation.use_learned_precision:
|
| 163 |
+
# Replace precision heads with fixed uniform precision
|
| 164 |
+
for ph in list(model.precision_up) + list(model.precision_down):
|
| 165 |
+
for param in ph.parameters():
|
| 166 |
+
param.requires_grad = False
|
| 167 |
+
|
| 168 |
+
return model
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def run_ablation(
|
| 172 |
+
ablation: AblationConfig,
|
| 173 |
+
data_text: str,
|
| 174 |
+
output_dir: Path,
|
| 175 |
+
device: str = "cpu",
|
| 176 |
+
):
|
| 177 |
+
"""Run a single ablation experiment."""
|
| 178 |
+
print(f"\n{'='*60}")
|
| 179 |
+
print(f"Ablation: {ablation.name}")
|
| 180 |
+
print(f"Description: {ablation.description}")
|
| 181 |
+
print(f"{'='*60}")
|
| 182 |
+
|
| 183 |
+
# Create model
|
| 184 |
+
model = create_model_from_ablation(ablation)
|
| 185 |
+
print(f"Parameters: {count_parameters(model):,}")
|
| 186 |
+
|
| 187 |
+
# Create dataset
|
| 188 |
+
dataset = CharLevelDataset(data_text, ablation.seq_len, vocab_size=257)
|
| 189 |
+
n_val = max(1, len(dataset) // 10)
|
| 190 |
+
n_train = len(dataset) - n_val
|
| 191 |
+
train_dataset, val_dataset = torch.utils.data.random_split(
|
| 192 |
+
dataset, [n_train, n_val]
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Train
|
| 196 |
+
save_dir = output_dir / ablation.name
|
| 197 |
+
trainer = Trainer(
|
| 198 |
+
model=model,
|
| 199 |
+
train_dataset=train_dataset,
|
| 200 |
+
val_dataset=val_dataset,
|
| 201 |
+
training_mode=ablation.training_mode,
|
| 202 |
+
lr=ablation.lr,
|
| 203 |
+
batch_size=ablation.batch_size,
|
| 204 |
+
max_steps=ablation.max_steps,
|
| 205 |
+
log_interval=100,
|
| 206 |
+
eval_interval=500,
|
| 207 |
+
save_dir=str(save_dir),
|
| 208 |
+
device=device,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
start = time.time()
|
| 212 |
+
trainer.train()
|
| 213 |
+
elapsed = time.time() - start
|
| 214 |
+
|
| 215 |
+
# Save ablation config and results
|
| 216 |
+
results = {
|
| 217 |
+
"config": asdict(ablation),
|
| 218 |
+
"n_params": count_parameters(model),
|
| 219 |
+
"wall_time": elapsed,
|
| 220 |
+
"training_log": trainer.log,
|
| 221 |
+
}
|
| 222 |
+
with open(save_dir / "ablation_results.json", "w") as f:
|
| 223 |
+
json.dump(results, f, indent=2)
|
| 224 |
+
|
| 225 |
+
print(f"Completed in {elapsed:.1f}s")
|
| 226 |
+
return results
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def run_all_ablations(
|
| 230 |
+
data_path: Optional[str] = None,
|
| 231 |
+
output_dir: str = "ablation_results",
|
| 232 |
+
device: str = "cpu",
|
| 233 |
+
ablation_names: Optional[list] = None,
|
| 234 |
+
):
|
| 235 |
+
"""Run all ablation experiments."""
|
| 236 |
+
output_path = Path(output_dir)
|
| 237 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 238 |
+
|
| 239 |
+
# Load data
|
| 240 |
+
if data_path and os.path.exists(data_path):
|
| 241 |
+
with open(data_path, "r") as f:
|
| 242 |
+
text = f.read()
|
| 243 |
+
else:
|
| 244 |
+
print("Using synthetic data for ablation experiments.")
|
| 245 |
+
text = "The quick brown fox jumps over the lazy dog. " * 5000
|
| 246 |
+
|
| 247 |
+
# Filter ablations if specified
|
| 248 |
+
if ablation_names:
|
| 249 |
+
ablations = [a for a in ABLATIONS if a.name in ablation_names]
|
| 250 |
+
else:
|
| 251 |
+
ablations = ABLATIONS
|
| 252 |
+
|
| 253 |
+
all_results = {}
|
| 254 |
+
for ablation in ablations:
|
| 255 |
+
results = run_ablation(ablation, text, output_path, device)
|
| 256 |
+
all_results[ablation.name] = results
|
| 257 |
+
|
| 258 |
+
# Summary
|
| 259 |
+
print(f"\n{'='*60}")
|
| 260 |
+
print("ABLATION SUMMARY")
|
| 261 |
+
print(f"{'='*60}")
|
| 262 |
+
for name, results in all_results.items():
|
| 263 |
+
log = results["training_log"]
|
| 264 |
+
final_loss = log["loss"][-1] if log["loss"] else "N/A"
|
| 265 |
+
print(f"{name:25s} | Loss: {final_loss:>8} | Time: {results['wall_time']:.1f}s")
|
| 266 |
+
|
| 267 |
+
# Save summary
|
| 268 |
+
with open(output_path / "summary.json", "w") as f:
|
| 269 |
+
json.dump(
|
| 270 |
+
{name: {"final_loss": r["training_log"]["loss"][-1] if r["training_log"]["loss"] else None,
|
| 271 |
+
"wall_time": r["wall_time"]}
|
| 272 |
+
for name, r in all_results.items()},
|
| 273 |
+
f, indent=2,
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
return all_results
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
if __name__ == "__main__":
|
| 280 |
+
import argparse
|
| 281 |
+
|
| 282 |
+
parser = argparse.ArgumentParser()
|
| 283 |
+
parser.add_argument("--data", type=str, default=None)
|
| 284 |
+
parser.add_argument("--output", type=str, default="ablation_results")
|
| 285 |
+
parser.add_argument("--device", type=str, default="cpu")
|
| 286 |
+
parser.add_argument("--ablations", nargs="+", default=None,
|
| 287 |
+
help="Specific ablation names to run")
|
| 288 |
+
args = parser.parse_args()
|
| 289 |
+
|
| 290 |
+
run_all_ablations(args.data, args.output, args.device, args.ablations)
|