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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, io, re, json, math, struct, tempfile, traceback
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import List, Tuple, Dict
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import gradio as gr
|
| 7 |
+
|
| 8 |
+
import matplotlib
|
| 9 |
+
matplotlib.use("Agg")
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
|
| 12 |
+
import imageio.v2 as imageio # GIF creation
|
| 13 |
+
|
| 14 |
+
# -----------------------------
|
| 15 |
+
# Optional DOCX support
|
| 16 |
+
# -----------------------------
|
| 17 |
+
_DOCX_OK = False
|
| 18 |
+
try:
|
| 19 |
+
from docx import Document
|
| 20 |
+
_DOCX_OK = True
|
| 21 |
+
except Exception:
|
| 22 |
+
_DOCX_OK = False
|
| 23 |
+
|
| 24 |
+
# -----------------------------
|
| 25 |
+
# Embeddings: sentence-transformers (preferred), fallback to hashing
|
| 26 |
+
# -----------------------------
|
| 27 |
+
from sklearn.feature_extraction.text import HashingVectorizer
|
| 28 |
+
from sklearn.decomposition import PCA
|
| 29 |
+
|
| 30 |
+
_ST_MODEL = None
|
| 31 |
+
def _load_st_model():
|
| 32 |
+
global _ST_MODEL
|
| 33 |
+
if _ST_MODEL is not None:
|
| 34 |
+
return _ST_MODEL
|
| 35 |
+
try:
|
| 36 |
+
from sentence_transformers import SentenceTransformer
|
| 37 |
+
_ST_MODEL = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 38 |
+
return _ST_MODEL
|
| 39 |
+
except Exception:
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
def embed_texts(texts: List[str], prefer_sentence_transformer: bool = True) -> Tuple[np.ndarray, str]:
|
| 43 |
+
texts = [t if isinstance(t, str) else str(t) for t in texts]
|
| 44 |
+
|
| 45 |
+
if prefer_sentence_transformer:
|
| 46 |
+
model = _load_st_model()
|
| 47 |
+
if model is not None:
|
| 48 |
+
try:
|
| 49 |
+
vecs = model.encode(
|
| 50 |
+
texts, batch_size=32, show_progress_bar=False,
|
| 51 |
+
convert_to_numpy=True, normalize_embeddings=True
|
| 52 |
+
)
|
| 53 |
+
return vecs.astype(np.float32), "sentence-transformers/all-MiniLM-L6-v2"
|
| 54 |
+
except Exception:
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
hv = HashingVectorizer(n_features=768, alternate_sign=False, norm=None)
|
| 58 |
+
X = hv.transform(texts)
|
| 59 |
+
vecs = X.toarray().astype(np.float32)
|
| 60 |
+
norms = np.linalg.norm(vecs, axis=1, keepdims=True) + 1e-9
|
| 61 |
+
vecs = vecs / norms
|
| 62 |
+
return vecs, "HashingVectorizer(768d) fallback"
|
| 63 |
+
|
| 64 |
+
# -----------------------------
|
| 65 |
+
# Text ingestion / splitting
|
| 66 |
+
# -----------------------------
|
| 67 |
+
def _basic_sentence_split(text: str) -> List[str]:
|
| 68 |
+
rough = re.split(r'[\n\r]+|(?<=[\.\!\?])\s+', text.strip())
|
| 69 |
+
out = []
|
| 70 |
+
for s in rough:
|
| 71 |
+
s = s.strip()
|
| 72 |
+
if s:
|
| 73 |
+
out.append(s)
|
| 74 |
+
return out
|
| 75 |
+
|
| 76 |
+
def read_txt_bytes(b: bytes) -> str:
|
| 77 |
+
try:
|
| 78 |
+
return b.decode("utf-8")
|
| 79 |
+
except Exception:
|
| 80 |
+
return b.decode("latin-1", errors="ignore")
|
| 81 |
+
|
| 82 |
+
def read_docx_bytes(b: bytes) -> List[str]:
|
| 83 |
+
if not _DOCX_OK:
|
| 84 |
+
raise RuntimeError("python-docx not installed in this Space.")
|
| 85 |
+
bio = io.BytesIO(b)
|
| 86 |
+
doc = Document(bio)
|
| 87 |
+
paras = [p.text.strip() for p in doc.paragraphs]
|
| 88 |
+
return [p for p in paras if p and not p.isspace()]
|
| 89 |
+
|
| 90 |
+
def to_units(raw_text: str, mode: str) -> List[str]:
|
| 91 |
+
raw_text = raw_text.strip()
|
| 92 |
+
if not raw_text:
|
| 93 |
+
return []
|
| 94 |
+
if mode == "sentences":
|
| 95 |
+
return _basic_sentence_split(raw_text)
|
| 96 |
+
paras = [p.strip() for p in re.split(r"\n\s*\n+", raw_text) if p.strip()]
|
| 97 |
+
return paras
|
| 98 |
+
|
| 99 |
+
# -----------------------------
|
| 100 |
+
# Demo corpus (for effortless investor demos)
|
| 101 |
+
# -----------------------------
|
| 102 |
+
DEMO_CORPUS = """
|
| 103 |
+
In the beginning, people stored knowledge in libraries, then in databases, and now in neural networks.
|
| 104 |
+
Compression isn’t just saving space — it’s choosing what matters.
|
| 105 |
+
A constellation is a pattern you can navigate.
|
| 106 |
+
Entropy is a measure of surprise, and learning is surprise turning into structure.
|
| 107 |
+
|
| 108 |
+
A system that learns from compressed data never needs the original.
|
| 109 |
+
It doesn’t memorize pixels; it memorizes geometry.
|
| 110 |
+
It doesn’t hoard text; it extracts signals.
|
| 111 |
+
The question isn’t “Can it compress?” but “Can it learn after compressing?”
|
| 112 |
+
|
| 113 |
+
Investors love seeing systems move.
|
| 114 |
+
They love curves that fall.
|
| 115 |
+
They love maps that cluster.
|
| 116 |
+
They love a demo that feels alive.
|
| 117 |
+
|
| 118 |
+
This demo builds a codec from your dataset,
|
| 119 |
+
then trains a model exclusively on the codec’s byte stream.
|
| 120 |
+
No raw text is used during training.
|
| 121 |
+
Only the compressed stream exists.
|
| 122 |
+
|
| 123 |
+
We call the clusters constellations.
|
| 124 |
+
We call the structure harvestable.
|
| 125 |
+
We call the drop in entropy visible proof.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
# -----------------------------
|
| 129 |
+
# CHR core
|
| 130 |
+
# -----------------------------
|
| 131 |
+
def softmax(x, axis=-1):
|
| 132 |
+
x = x - np.max(x, axis=axis, keepdims=True)
|
| 133 |
+
ex = np.exp(x)
|
| 134 |
+
return ex / (np.sum(ex, axis=axis, keepdims=True) + 1e-9)
|
| 135 |
+
|
| 136 |
+
def global_range_entropy(p: np.ndarray) -> float:
|
| 137 |
+
m = p.mean(axis=0)
|
| 138 |
+
m_safe = np.clip(m, 1e-12, None)
|
| 139 |
+
return float(-(m_safe * np.log(m_safe)).sum())
|
| 140 |
+
|
| 141 |
+
def soft_slab_entropy(z: np.ndarray, U: np.ndarray, bins: int = 8, tau: float = 5.0) -> float:
|
| 142 |
+
t = z @ U.T
|
| 143 |
+
K = U.shape[0]
|
| 144 |
+
Hs = []
|
| 145 |
+
for j in range(K):
|
| 146 |
+
tj = t[:, j]
|
| 147 |
+
tmin, tmax = float(tj.min()), float(tj.max())
|
| 148 |
+
if not np.isfinite(tmin) or not np.isfinite(tmax) or tmax - tmin < 1e-6:
|
| 149 |
+
Hs.append(0.0)
|
| 150 |
+
continue
|
| 151 |
+
centers = np.linspace(tmin, tmax, bins)
|
| 152 |
+
dist2 = (tj[:, None] - centers[None, :]) ** 2
|
| 153 |
+
weights = softmax(-tau * dist2, axis=1)
|
| 154 |
+
hist = weights.mean(axis=0)
|
| 155 |
+
hist = np.clip(hist, 1e-12, None)
|
| 156 |
+
H = float(-(hist * np.log(hist)).sum())
|
| 157 |
+
Hs.append(H)
|
| 158 |
+
return float(np.mean(Hs)) if Hs else 0.0
|
| 159 |
+
|
| 160 |
+
def kmeans_plus_plus_init(z: np.ndarray, K: int, rng: np.random.RandomState) -> np.ndarray:
|
| 161 |
+
N, d = z.shape
|
| 162 |
+
inds = [rng.randint(0, N)]
|
| 163 |
+
centers = [z[inds[0]]]
|
| 164 |
+
cos0 = np.clip(z @ centers[0], -1.0, 1.0)
|
| 165 |
+
d2 = np.clip(1.0 - cos0, 1e-12, None)
|
| 166 |
+
|
| 167 |
+
for _ in range(1, K):
|
| 168 |
+
s = d2.sum()
|
| 169 |
+
if not np.isfinite(s) or s <= 0:
|
| 170 |
+
probs = np.full(N, 1.0 / N)
|
| 171 |
+
else:
|
| 172 |
+
probs = np.clip(d2 / s, 0.0, None)
|
| 173 |
+
probs = probs / (probs.sum() + 1e-12)
|
| 174 |
+
next_idx = rng.choice(N, p=probs)
|
| 175 |
+
inds.append(next_idx)
|
| 176 |
+
centers.append(z[next_idx])
|
| 177 |
+
|
| 178 |
+
cos_new = np.clip(z @ z[next_idx], -1.0, 1.0)
|
| 179 |
+
d2 = np.minimum(d2, np.clip(1.0 - cos_new, 1e-12, None))
|
| 180 |
+
|
| 181 |
+
U = np.stack(centers, axis=0)
|
| 182 |
+
U = U / (np.linalg.norm(U, axis=1, keepdims=True) + 1e-9)
|
| 183 |
+
return U
|
| 184 |
+
|
| 185 |
+
def chr_optimize(z: np.ndarray, K: int = 8, iters: int = 30, beta: float = 12.0,
|
| 186 |
+
bins: int = 8, tau: float = 5.0, seed: int = 42):
|
| 187 |
+
rng = np.random.RandomState(seed)
|
| 188 |
+
N, d = z.shape
|
| 189 |
+
U = kmeans_plus_plus_init(z, K, rng) if N >= K else np.pad(z, ((0, max(0, K - N)), (0, 0)), mode="wrap")[:K]
|
| 190 |
+
U = U / (np.linalg.norm(U, axis=1, keepdims=True) + 1e-9)
|
| 191 |
+
|
| 192 |
+
logits0 = beta * (z @ U.T)
|
| 193 |
+
p0 = softmax(logits0, axis=1)
|
| 194 |
+
Hg_traj = [global_range_entropy(p0)]
|
| 195 |
+
Hs_traj = [soft_slab_entropy(z, U, bins=bins, tau=tau)]
|
| 196 |
+
|
| 197 |
+
for _ in range(iters):
|
| 198 |
+
logits = beta * (z @ U.T)
|
| 199 |
+
p = softmax(logits, axis=1)
|
| 200 |
+
numer = p.T @ z
|
| 201 |
+
denom = p.sum(axis=0)[:, None] + 1e-9
|
| 202 |
+
U = numer / denom
|
| 203 |
+
U = U / (np.linalg.norm(U, axis=1, keepdims=True) + 1e-9)
|
| 204 |
+
Hg_traj.append(global_range_entropy(p))
|
| 205 |
+
Hs_traj.append(soft_slab_entropy(z, U, bins=bins, tau=tau))
|
| 206 |
+
|
| 207 |
+
logits = beta * (z @ U.T)
|
| 208 |
+
p = softmax(logits, axis=1)
|
| 209 |
+
return U, p, np.array(Hg_traj), np.array(Hs_traj)
|
| 210 |
+
|
| 211 |
+
def compute_mhep(Hg_traj: np.ndarray, Hs_traj: np.ndarray, K: int, bins: int, w_g: float = 0.7, w_s: float = 0.3) -> float:
|
| 212 |
+
if len(Hg_traj) < 2 or len(Hs_traj) < 2:
|
| 213 |
+
return 0.0
|
| 214 |
+
maxHg = math.log(max(K, 2))
|
| 215 |
+
maxHs = math.log(max(bins, 2))
|
| 216 |
+
drop_g = max(0.0, float(Hg_traj[0] - Hg_traj[-1])) / (maxHg + 1e-9)
|
| 217 |
+
drop_s = max(0.0, float(Hs_traj[0] - Hs_traj[-1])) / (maxHs + 1e-9)
|
| 218 |
+
return float(np.clip(100.0 * (w_g * drop_g + w_s * drop_s), 0.0, 100.0))
|
| 219 |
+
|
| 220 |
+
# -----------------------------
|
| 221 |
+
# CHR → discrete "compressed" byte stream
|
| 222 |
+
# -----------------------------
|
| 223 |
+
def make_radial_bins(radials: np.ndarray, B: int = 64) -> np.ndarray:
|
| 224 |
+
edges = np.quantile(radials, np.linspace(0, 1, B + 1))
|
| 225 |
+
for i in range(1, len(edges)):
|
| 226 |
+
if edges[i] <= edges[i - 1]:
|
| 227 |
+
edges[i] = edges[i - 1] + 1e-6
|
| 228 |
+
return edges.astype(np.float32)
|
| 229 |
+
|
| 230 |
+
def quantize_radial(r: float, edges: np.ndarray) -> int:
|
| 231 |
+
b = np.searchsorted(edges, r, side="right") - 1
|
| 232 |
+
return int(np.clip(b, 0, len(edges) - 2))
|
| 233 |
+
|
| 234 |
+
def pack_codes_to_bytes(labels: np.ndarray, bins: np.ndarray) -> bytes:
|
| 235 |
+
out = bytearray()
|
| 236 |
+
for c, b in zip(labels.tolist(), bins.tolist()):
|
| 237 |
+
out.append(int(c) & 0xFF)
|
| 238 |
+
out.append(int(b) & 0xFF)
|
| 239 |
+
return bytes(out)
|
| 240 |
+
|
| 241 |
+
def save_codes_and_codec(code_bytes: bytes, codec: Dict, out_dir: str) -> Tuple[str, str]:
|
| 242 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 243 |
+
bin_path = os.path.join(out_dir, "codes.bin")
|
| 244 |
+
meta_path = os.path.join(out_dir, "codec.json")
|
| 245 |
+
with open(bin_path, "wb") as f:
|
| 246 |
+
f.write(b"CHRC")
|
| 247 |
+
f.write(struct.pack("<I", 1))
|
| 248 |
+
f.write(code_bytes)
|
| 249 |
+
with open(meta_path, "w", encoding="utf-8") as f:
|
| 250 |
+
json.dump(codec, f, indent=2)
|
| 251 |
+
return bin_path, meta_path
|
| 252 |
+
|
| 253 |
+
# -----------------------------
|
| 254 |
+
# Visuals
|
| 255 |
+
# -----------------------------
|
| 256 |
+
def plot_entropy(Hg, Hs, out_path):
|
| 257 |
+
plt.figure(figsize=(6,4))
|
| 258 |
+
plt.plot(Hg, label="Global range entropy")
|
| 259 |
+
plt.plot(Hs, label="Slab entropy")
|
| 260 |
+
plt.xlabel("Iteration"); plt.ylabel("Entropy")
|
| 261 |
+
plt.title("Entropy drops during CHR compression")
|
| 262 |
+
plt.legend()
|
| 263 |
+
plt.tight_layout()
|
| 264 |
+
plt.savefig(out_path, dpi=150)
|
| 265 |
+
plt.close()
|
| 266 |
+
|
| 267 |
+
def plot_constellation_map(z, U, labels, out_path):
|
| 268 |
+
if z.shape[1] > 2:
|
| 269 |
+
pca = PCA(n_components=2, random_state=0)
|
| 270 |
+
Z2 = pca.fit_transform(z)
|
| 271 |
+
U2 = pca.transform(U)
|
| 272 |
+
else:
|
| 273 |
+
Z2, U2 = z, U
|
| 274 |
+
plt.figure(figsize=(6,5))
|
| 275 |
+
plt.scatter(Z2[:,0], Z2[:,1], s=14, alpha=0.8, c=labels)
|
| 276 |
+
plt.scatter(U2[:,0], U2[:,1], marker="*", s=200)
|
| 277 |
+
plt.title("Constellation map (compressed geometry)")
|
| 278 |
+
plt.xlabel("PC1"); plt.ylabel("PC2")
|
| 279 |
+
plt.tight_layout()
|
| 280 |
+
plt.savefig(out_path, dpi=150)
|
| 281 |
+
plt.close()
|
| 282 |
+
|
| 283 |
+
def plot_training_curves(losses, ppls, out_path):
|
| 284 |
+
plt.figure(figsize=(6,4))
|
| 285 |
+
plt.plot(losses, label="Loss")
|
| 286 |
+
plt.plot(ppls, label="Perplexity")
|
| 287 |
+
plt.xlabel("Checkpoint")
|
| 288 |
+
plt.title("Learning on compressed stream")
|
| 289 |
+
plt.legend()
|
| 290 |
+
plt.tight_layout()
|
| 291 |
+
plt.savefig(out_path, dpi=150)
|
| 292 |
+
plt.close()
|
| 293 |
+
|
| 294 |
+
def plot_rollout_tracks(seq_bytes: List[int], out_path, title="Compressed rollout"):
|
| 295 |
+
cs = seq_bytes[0::2]
|
| 296 |
+
bs = seq_bytes[1::2]
|
| 297 |
+
plt.figure(figsize=(8,3.6))
|
| 298 |
+
plt.plot(cs, label="Constellation id")
|
| 299 |
+
plt.plot(bs, label="Radial bin")
|
| 300 |
+
plt.ylim(-2, 260)
|
| 301 |
+
plt.xlabel("Step"); plt.title(title)
|
| 302 |
+
plt.legend()
|
| 303 |
+
plt.tight_layout()
|
| 304 |
+
plt.savefig(out_path, dpi=150)
|
| 305 |
+
plt.close()
|
| 306 |
+
|
| 307 |
+
def plot_before_after_tracks(before_bytes: List[int], after_bytes: List[int], out_path):
|
| 308 |
+
b_c = before_bytes[0::2]; b_b = before_bytes[1::2]
|
| 309 |
+
a_c = after_bytes[0::2]; a_b = after_bytes[1::2]
|
| 310 |
+
plt.figure(figsize=(10,4))
|
| 311 |
+
plt.subplot(1,2,1)
|
| 312 |
+
plt.plot(b_c, label="Constellation")
|
| 313 |
+
plt.plot(b_b, label="Radial bin")
|
| 314 |
+
plt.title("BEFORE (untrained)")
|
| 315 |
+
plt.ylim(-2, 260)
|
| 316 |
+
plt.legend()
|
| 317 |
+
|
| 318 |
+
plt.subplot(1,2,2)
|
| 319 |
+
plt.plot(a_c, label="Constellation")
|
| 320 |
+
plt.plot(a_b, label="Radial bin")
|
| 321 |
+
plt.title("AFTER (trained)")
|
| 322 |
+
plt.ylim(-2, 260)
|
| 323 |
+
plt.legend()
|
| 324 |
+
|
| 325 |
+
plt.suptitle("Rollout comparison on compressed symbols")
|
| 326 |
+
plt.tight_layout()
|
| 327 |
+
plt.savefig(out_path, dpi=150)
|
| 328 |
+
plt.close()
|
| 329 |
+
|
| 330 |
+
def rollout_to_xy(seq_bytes: List[int], U: np.ndarray, radial_edges: np.ndarray) -> np.ndarray:
|
| 331 |
+
"""
|
| 332 |
+
Convert (constellation id, radial bin) stream into approximate vectors r*U[c],
|
| 333 |
+
then project to 2D using PCA fitted on U only (codec-only visualization).
|
| 334 |
+
"""
|
| 335 |
+
cs = np.array(seq_bytes[0::2], dtype=np.int32)
|
| 336 |
+
bs = np.array(seq_bytes[1::2], dtype=np.int32)
|
| 337 |
+
K, d = U.shape
|
| 338 |
+
B = len(radial_edges) - 1
|
| 339 |
+
|
| 340 |
+
cs = np.clip(cs, 0, K-1)
|
| 341 |
+
bs = np.clip(bs, 0, B-1)
|
| 342 |
+
|
| 343 |
+
# use bin midpoints as radius
|
| 344 |
+
mids = 0.5 * (radial_edges[bs] + radial_edges[bs + 1]) # [T]
|
| 345 |
+
V = U[cs] * mids[:, None] # [T, d]
|
| 346 |
+
|
| 347 |
+
pca = PCA(n_components=2, random_state=0)
|
| 348 |
+
U2 = pca.fit_transform(U)
|
| 349 |
+
V2 = pca.transform(V)
|
| 350 |
+
return V2, U2
|
| 351 |
+
|
| 352 |
+
def make_rollout_gif(seq_bytes: List[int], U: np.ndarray, radial_edges: np.ndarray,
|
| 353 |
+
out_path: str, title: str = "Compressed rollout (animated)",
|
| 354 |
+
stride: int = 2, fps: int = 12):
|
| 355 |
+
V2, U2 = rollout_to_xy(seq_bytes, U, radial_edges)
|
| 356 |
+
frames = []
|
| 357 |
+
# bounds for stable view
|
| 358 |
+
xmin = min(V2[:,0].min(), U2[:,0].min()) - 0.2
|
| 359 |
+
xmax = max(V2[:,0].max(), U2[:,0].max()) + 0.2
|
| 360 |
+
ymin = min(V2[:,1].min(), U2[:,1].min()) - 0.2
|
| 361 |
+
ymax = max(V2[:,1].max(), U2[:,1].max()) + 0.2
|
| 362 |
+
|
| 363 |
+
for t in range(1, len(V2), stride):
|
| 364 |
+
fig = plt.figure(figsize=(6,5))
|
| 365 |
+
plt.scatter(U2[:,0], U2[:,1], marker="*", s=180) # anchors
|
| 366 |
+
plt.plot(V2[:t,0], V2[:t,1], linewidth=2) # path so far
|
| 367 |
+
plt.scatter(V2[t-1,0], V2[t-1,1], s=80) # current point
|
| 368 |
+
plt.title(title)
|
| 369 |
+
plt.xlim(xmin, xmax); plt.ylim(ymin, ymax)
|
| 370 |
+
plt.xlabel("PC1 (codec space)"); plt.ylabel("PC2 (codec space)")
|
| 371 |
+
plt.tight_layout()
|
| 372 |
+
|
| 373 |
+
buf = io.BytesIO()
|
| 374 |
+
plt.savefig(buf, format="png", dpi=150)
|
| 375 |
+
plt.close(fig)
|
| 376 |
+
buf.seek(0)
|
| 377 |
+
frames.append(imageio.imread(buf))
|
| 378 |
+
|
| 379 |
+
imageio.mimsave(out_path, frames, fps=fps)
|
| 380 |
+
|
| 381 |
+
# -----------------------------
|
| 382 |
+
# Byte-level transformer (PyTorch)
|
| 383 |
+
# -----------------------------
|
| 384 |
+
import torch
|
| 385 |
+
import torch.nn as nn
|
| 386 |
+
from torch.utils.data import Dataset, DataLoader
|
| 387 |
+
|
| 388 |
+
class ByteStreamDataset(Dataset):
|
| 389 |
+
def __init__(self, bin_path: str, block_size: int = 256):
|
| 390 |
+
with open(bin_path, "rb") as f:
|
| 391 |
+
blob = f.read()
|
| 392 |
+
assert blob[:4] == b"CHRC"
|
| 393 |
+
ver = int.from_bytes(blob[4:8], "little")
|
| 394 |
+
assert ver == 1
|
| 395 |
+
data = blob[8:]
|
| 396 |
+
self.data = torch.tensor(list(data), dtype=torch.long)
|
| 397 |
+
self.block_size = int(block_size)
|
| 398 |
+
|
| 399 |
+
def __len__(self):
|
| 400 |
+
return max(0, len(self.data) - self.block_size - 1)
|
| 401 |
+
|
| 402 |
+
def __getitem__(self, idx):
|
| 403 |
+
x = self.data[idx:idx+self.block_size]
|
| 404 |
+
y = self.data[idx+1:idx+self.block_size+1]
|
| 405 |
+
return x, y
|
| 406 |
+
|
| 407 |
+
class TinyByteTransformer(nn.Module):
|
| 408 |
+
def __init__(self, vocab_size=256, d_model=192, n_layers=4, n_heads=6, block_size=256):
|
| 409 |
+
super().__init__()
|
| 410 |
+
self.tok = nn.Embedding(vocab_size, d_model)
|
| 411 |
+
self.pos = nn.Embedding(block_size, d_model)
|
| 412 |
+
enc_layer = nn.TransformerEncoderLayer(
|
| 413 |
+
d_model=d_model, nhead=n_heads, dim_feedforward=4*d_model,
|
| 414 |
+
dropout=0.1, batch_first=True
|
| 415 |
+
)
|
| 416 |
+
self.tr = nn.TransformerEncoder(enc_layer, num_layers=n_layers)
|
| 417 |
+
self.lm = nn.Linear(d_model, vocab_size)
|
| 418 |
+
self.block_size = block_size
|
| 419 |
+
|
| 420 |
+
def forward(self, x):
|
| 421 |
+
B, T = x.shape
|
| 422 |
+
pos = torch.arange(T, device=x.device).unsqueeze(0).expand(B, T)
|
| 423 |
+
h = self.tok(x) + self.pos(pos)
|
| 424 |
+
mask = torch.triu(torch.ones(T, T, device=x.device), diagonal=1).bool()
|
| 425 |
+
h = self.tr(h, mask=mask)
|
| 426 |
+
return self.lm(h)
|
| 427 |
+
|
| 428 |
+
@torch.no_grad()
|
| 429 |
+
def sample_bytes(model, start: List[int], steps: int, device: str = "cpu", temperature: float = 1.0) -> List[int]:
|
| 430 |
+
model.eval()
|
| 431 |
+
seq = start[:]
|
| 432 |
+
for _ in range(steps):
|
| 433 |
+
x = torch.tensor(seq[-model.block_size:], dtype=torch.long, device=device).unsqueeze(0)
|
| 434 |
+
logits = model(x)[0, -1] / max(1e-6, float(temperature))
|
| 435 |
+
probs = torch.softmax(logits, dim=-1)
|
| 436 |
+
nxt = int(torch.multinomial(probs, num_samples=1).item())
|
| 437 |
+
seq.append(nxt)
|
| 438 |
+
return seq
|
| 439 |
+
|
| 440 |
+
def train_on_compressed(bin_path: str,
|
| 441 |
+
steps: int = 800,
|
| 442 |
+
batch_size: int = 64,
|
| 443 |
+
block_size: int = 256,
|
| 444 |
+
lr: float = 3e-4,
|
| 445 |
+
device: str = "cpu",
|
| 446 |
+
log_every: int = 50):
|
| 447 |
+
ds = ByteStreamDataset(bin_path, block_size=block_size)
|
| 448 |
+
if len(ds) < 10:
|
| 449 |
+
raise RuntimeError("Not enough compressed data to train. Use more text or smaller block size.")
|
| 450 |
+
dl = DataLoader(ds, batch_size=batch_size, shuffle=True, drop_last=True)
|
| 451 |
+
it = iter(dl)
|
| 452 |
+
|
| 453 |
+
model = TinyByteTransformer(block_size=block_size).to(device)
|
| 454 |
+
opt = torch.optim.AdamW(model.parameters(), lr=lr)
|
| 455 |
+
loss_fn = nn.CrossEntropyLoss()
|
| 456 |
+
|
| 457 |
+
losses, ppls = [], []
|
| 458 |
+
model.train()
|
| 459 |
+
for step in range(1, steps+1):
|
| 460 |
+
try:
|
| 461 |
+
x, y = next(it)
|
| 462 |
+
except StopIteration:
|
| 463 |
+
it = iter(dl)
|
| 464 |
+
x, y = next(it)
|
| 465 |
+
|
| 466 |
+
x, y = x.to(device), y.to(device)
|
| 467 |
+
logits = model(x)
|
| 468 |
+
loss = loss_fn(logits.view(-1, 256), y.view(-1))
|
| 469 |
+
|
| 470 |
+
opt.zero_grad(set_to_none=True)
|
| 471 |
+
loss.backward()
|
| 472 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 473 |
+
opt.step()
|
| 474 |
+
|
| 475 |
+
if step % log_every == 0:
|
| 476 |
+
l = float(loss.detach().cpu().item())
|
| 477 |
+
ppl = float(torch.exp(loss.detach()).cpu().item())
|
| 478 |
+
losses.append(l)
|
| 479 |
+
ppls.append(ppl)
|
| 480 |
+
|
| 481 |
+
return model, losses, ppls
|
| 482 |
+
|
| 483 |
+
# -----------------------------
|
| 484 |
+
# Pipeline state
|
| 485 |
+
# -----------------------------
|
| 486 |
+
STATE = {
|
| 487 |
+
"units": None,
|
| 488 |
+
"Z": None,
|
| 489 |
+
"U": None,
|
| 490 |
+
"labels": None,
|
| 491 |
+
"bins": None,
|
| 492 |
+
"bin_path": None,
|
| 493 |
+
"meta_path": None,
|
| 494 |
+
"codec": None,
|
| 495 |
+
"model": None,
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
def _bytes_from_upload(file_obj) -> Tuple[bytes, str]:
|
| 499 |
+
if file_obj is None:
|
| 500 |
+
return b"", ""
|
| 501 |
+
if isinstance(file_obj, str) and os.path.exists(file_obj):
|
| 502 |
+
return Path(file_obj).read_bytes(), os.path.basename(file_obj)
|
| 503 |
+
if hasattr(file_obj, "name") and os.path.exists(file_obj.name):
|
| 504 |
+
return Path(file_obj.name).read_bytes(), os.path.basename(file_obj.name)
|
| 505 |
+
return b"", "upload"
|
| 506 |
+
|
| 507 |
+
# -----------------------------
|
| 508 |
+
# Gradio callbacks
|
| 509 |
+
# -----------------------------
|
| 510 |
+
def load_demo(units_mode: str):
|
| 511 |
+
units = to_units(DEMO_CORPUS, units_mode)
|
| 512 |
+
units = [u.strip() for u in units if u.strip()]
|
| 513 |
+
STATE["units"] = units
|
| 514 |
+
return f"Loaded **{len(units)}** demo units (built-in corpus)."
|
| 515 |
+
|
| 516 |
+
def ingest_file(file_obj, units_mode: str):
|
| 517 |
+
try:
|
| 518 |
+
b, name = _bytes_from_upload(file_obj)
|
| 519 |
+
if not b:
|
| 520 |
+
return "Upload a .txt or .docx file to begin."
|
| 521 |
+
|
| 522 |
+
if name.lower().endswith(".docx"):
|
| 523 |
+
paras = read_docx_bytes(b)
|
| 524 |
+
raw = "\n\n".join(paras)
|
| 525 |
+
else:
|
| 526 |
+
raw = read_txt_bytes(b)
|
| 527 |
+
|
| 528 |
+
units = to_units(raw, units_mode)
|
| 529 |
+
units = [u.strip() for u in units if u.strip()]
|
| 530 |
+
if len(units) > 3000:
|
| 531 |
+
units = units[:3000]
|
| 532 |
+
|
| 533 |
+
STATE["units"] = units
|
| 534 |
+
return f"Loaded **{len(units)}** units from **{name}**."
|
| 535 |
+
except Exception as e:
|
| 536 |
+
return f"Error ingesting file: {e}"
|
| 537 |
+
|
| 538 |
+
def compress_now(K, iters, beta, slab_bins, tau, seed, radial_bins):
|
| 539 |
+
try:
|
| 540 |
+
units = STATE.get("units")
|
| 541 |
+
if not units:
|
| 542 |
+
return "No units loaded. Upload a file or load the demo corpus.", None, None, None, None
|
| 543 |
+
|
| 544 |
+
Z, backend = embed_texts(units, prefer_sentence_transformer=True)
|
| 545 |
+
U, p, Hg, Hs = chr_optimize(Z, K=int(K), iters=int(iters), beta=float(beta),
|
| 546 |
+
bins=int(slab_bins), tau=float(tau), seed=int(seed))
|
| 547 |
+
labels = p.argmax(axis=1).astype(np.int32)
|
| 548 |
+
proj = Z @ U.T
|
| 549 |
+
radials = proj[np.arange(len(units)), labels].astype(np.float32)
|
| 550 |
+
|
| 551 |
+
edges = make_radial_bins(radials, B=int(radial_bins))
|
| 552 |
+
bins_q = np.array([quantize_radial(float(radials[i]), edges) for i in range(len(units))], dtype=np.int32)
|
| 553 |
+
|
| 554 |
+
code_bytes = pack_codes_to_bytes(labels, bins_q)
|
| 555 |
+
|
| 556 |
+
out_dir = tempfile.mkdtemp()
|
| 557 |
+
codec = {
|
| 558 |
+
"backend": backend,
|
| 559 |
+
"K": int(K),
|
| 560 |
+
"radial_bins": int(radial_bins),
|
| 561 |
+
"iters": int(iters),
|
| 562 |
+
"beta": float(beta),
|
| 563 |
+
"slab_bins": int(slab_bins),
|
| 564 |
+
"tau": float(tau),
|
| 565 |
+
"seed": int(seed),
|
| 566 |
+
"U": U.tolist(),
|
| 567 |
+
"radial_edges": edges.tolist(),
|
| 568 |
+
"units_count": int(len(units)),
|
| 569 |
+
"bytes_per_unit": 2.0,
|
| 570 |
+
"total_bytes": int(len(code_bytes) + 8),
|
| 571 |
+
}
|
| 572 |
+
bin_path, meta_path = save_codes_and_codec(code_bytes, codec, out_dir)
|
| 573 |
+
|
| 574 |
+
STATE.update({
|
| 575 |
+
"Z": Z, "U": U, "labels": labels, "bins": bins_q,
|
| 576 |
+
"bin_path": bin_path, "meta_path": meta_path, "codec": codec
|
| 577 |
+
})
|
| 578 |
+
|
| 579 |
+
ent_plot = os.path.join(out_dir, "entropy.png")
|
| 580 |
+
map_plot = os.path.join(out_dir, "map.png")
|
| 581 |
+
plot_entropy(Hg, Hs, ent_plot)
|
| 582 |
+
plot_constellation_map(Z, U, labels, map_plot)
|
| 583 |
+
|
| 584 |
+
mhep = compute_mhep(Hg, Hs, K=int(K), bins=int(slab_bins))
|
| 585 |
+
summary_md = (
|
| 586 |
+
f"## Compression Complete\n"
|
| 587 |
+
f"- **Embedding backend:** `{backend}`\n"
|
| 588 |
+
f"- **Units:** **{len(units)}**\n"
|
| 589 |
+
f"- **Constellations (K):** **{int(K)}**\n"
|
| 590 |
+
f"- **Radial bins:** **{int(radial_bins)}**\n"
|
| 591 |
+
f"- **Compressed stream size:** **{codec['total_bytes']} bytes**\n"
|
| 592 |
+
f"- **Bytes per unit:** **2.0** (constellation + radial bin)\n"
|
| 593 |
+
f"- **MHEP score:** **{mhep:.1f}%**\n"
|
| 594 |
+
f"\n### Investor-proof constraint\n"
|
| 595 |
+
f"Training input is **only** `codes.bin` (a byte stream)."
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
return summary_md, ent_plot, map_plot, bin_path, meta_path
|
| 599 |
+
except Exception as e:
|
| 600 |
+
return f"Compression error: {e}\n\n{traceback.format_exc()}", None, None, None, None
|
| 601 |
+
|
| 602 |
+
def train_now(train_steps, batch_size, block_size, lr, log_every, temperature, rollout_steps, gif_stride, gif_fps):
|
| 603 |
+
try:
|
| 604 |
+
bin_path = STATE.get("bin_path")
|
| 605 |
+
codec = STATE.get("codec")
|
| 606 |
+
U = STATE.get("U")
|
| 607 |
+
if not bin_path or not os.path.exists(bin_path) or codec is None or U is None:
|
| 608 |
+
return "No compressed stream found. Run compression first.", None, None, None, None
|
| 609 |
+
|
| 610 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 611 |
+
|
| 612 |
+
# Load stream bytes for starting context
|
| 613 |
+
with open(bin_path, "rb") as f:
|
| 614 |
+
blob = f.read()
|
| 615 |
+
stream = list(blob[8:])
|
| 616 |
+
start = stream[:min(len(stream), int(block_size))]
|
| 617 |
+
|
| 618 |
+
# ---- BEFORE: untrained (random) model rollout ----
|
| 619 |
+
untrained = TinyByteTransformer(block_size=int(block_size)).to(device)
|
| 620 |
+
before_seq = sample_bytes(
|
| 621 |
+
untrained, start=start, steps=int(rollout_steps),
|
| 622 |
+
device=device, temperature=float(temperature)
|
| 623 |
+
)
|
| 624 |
+
|
| 625 |
+
out_dir = os.path.dirname(bin_path)
|
| 626 |
+
before_plot = os.path.join(out_dir, "rollout_before.png")
|
| 627 |
+
plot_rollout_tracks(before_seq[-2*int(rollout_steps):], before_plot, title="BEFORE training (random)")
|
| 628 |
+
|
| 629 |
+
# ---- Train on compressed stream ----
|
| 630 |
+
model, losses, ppls = train_on_compressed(
|
| 631 |
+
bin_path=bin_path,
|
| 632 |
+
steps=int(train_steps),
|
| 633 |
+
batch_size=int(batch_size),
|
| 634 |
+
block_size=int(block_size),
|
| 635 |
+
lr=float(lr),
|
| 636 |
+
device=device,
|
| 637 |
+
log_every=int(log_every),
|
| 638 |
+
)
|
| 639 |
+
STATE["model"] = model
|
| 640 |
+
|
| 641 |
+
train_plot = os.path.join(out_dir, "training.png")
|
| 642 |
+
plot_training_curves(losses, ppls, train_plot)
|
| 643 |
+
|
| 644 |
+
# ---- AFTER: trained rollout ----
|
| 645 |
+
after_seq = sample_bytes(
|
| 646 |
+
model, start=start, steps=int(rollout_steps),
|
| 647 |
+
device=device, temperature=float(temperature)
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
after_plot = os.path.join(out_dir, "rollout_after.png")
|
| 651 |
+
plot_rollout_tracks(after_seq[-2*int(rollout_steps):], after_plot, title="AFTER training (trained model)")
|
| 652 |
+
|
| 653 |
+
# ---- Side-by-side comparison plot ----
|
| 654 |
+
compare_plot = os.path.join(out_dir, "rollout_compare.png")
|
| 655 |
+
plot_before_after_tracks(
|
| 656 |
+
before_seq[-2*int(rollout_steps):],
|
| 657 |
+
after_seq[-2*int(rollout_steps):],
|
| 658 |
+
compare_plot
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
# ---- Animated GIF (AFTER) in codec-only space ----
|
| 662 |
+
radial_edges = np.array(codec["radial_edges"], dtype=np.float32)
|
| 663 |
+
gif_path = os.path.join(out_dir, "rollout.gif")
|
| 664 |
+
make_rollout_gif(
|
| 665 |
+
after_seq[-2*int(rollout_steps):],
|
| 666 |
+
U=np.array(U, dtype=np.float32),
|
| 667 |
+
radial_edges=radial_edges,
|
| 668 |
+
out_path=gif_path,
|
| 669 |
+
title="AFTER training — animated traversal in codec space",
|
| 670 |
+
stride=int(gif_stride),
|
| 671 |
+
fps=int(gif_fps),
|
| 672 |
+
)
|
| 673 |
+
|
| 674 |
+
final_md = (
|
| 675 |
+
f"## Training Complete (compressed-only)\n"
|
| 676 |
+
f"- **Device:** `{device}`\n"
|
| 677 |
+
f"- **Steps:** **{int(train_steps)}** (logged every {int(log_every)})\n"
|
| 678 |
+
f"- **Final logged loss:** **{losses[-1]:.4f}**\n"
|
| 679 |
+
f"- **Final logged perplexity:** **{ppls[-1]:.2f}**\n"
|
| 680 |
+
f"\n### What investors should notice\n"
|
| 681 |
+
f"1) The **perplexity falls** (learning on compressed bytes).\n"
|
| 682 |
+
f"2) The **rollout changes** from noisy/random → structured.\n"
|
| 683 |
+
f"3) The GIF shows the model **navigating constellation space**."
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
metrics = {"loss": losses, "ppl": ppls}
|
| 687 |
+
return final_md, train_plot, compare_plot, gif_path, json.dumps(metrics, indent=2)
|
| 688 |
+
except Exception as e:
|
| 689 |
+
return f"Training error: {e}\n\n{traceback.format_exc()}", None, None, None, None
|
| 690 |
+
|
| 691 |
+
# -----------------------------
|
| 692 |
+
# Gradio UI
|
| 693 |
+
# -----------------------------
|
| 694 |
+
INTRO = """
|
| 695 |
+
# CHR Compressed-Only Learning (Investor Demo)
|
| 696 |
+
This Space compresses text into a **binary stream** (`codes.bin`) and trains a tiny transformer **only** on that byte stream.
|
| 697 |
+
|
| 698 |
+
**Investor wow features:**
|
| 699 |
+
- Entropy curves + constellation map during compression
|
| 700 |
+
- Training curves (loss + perplexity)
|
| 701 |
+
- **BEFORE vs AFTER** rollout comparison
|
| 702 |
+
- **Animated GIF** showing the model “moving” through codec space while generating compressed symbols
|
| 703 |
+
"""
|
| 704 |
+
|
| 705 |
+
with gr.Blocks(title="CHR Compressed-Only Learning (Investor Demo)") as demo:
|
| 706 |
+
gr.Markdown(INTRO)
|
| 707 |
+
|
| 708 |
+
with gr.Tab("1) Ingest"):
|
| 709 |
+
with gr.Row():
|
| 710 |
+
file_in = gr.File(label="Upload .txt or .docx", file_types=[".txt", ".docx"])
|
| 711 |
+
units_mode = gr.Radio(["paragraphs", "sentences"], value="sentences", label="Unit granularity")
|
| 712 |
+
with gr.Row():
|
| 713 |
+
ingest_btn = gr.Button("Load file", variant="primary")
|
| 714 |
+
demo_btn = gr.Button("Load built-in demo corpus", variant="secondary")
|
| 715 |
+
ingest_status = gr.Markdown("")
|
| 716 |
+
|
| 717 |
+
ingest_btn.click(ingest_file, inputs=[file_in, units_mode], outputs=[ingest_status])
|
| 718 |
+
demo_btn.click(load_demo, inputs=[units_mode], outputs=[ingest_status])
|
| 719 |
+
|
| 720 |
+
with gr.Tab("2) Compress (CHR → codes.bin)"):
|
| 721 |
+
with gr.Row():
|
| 722 |
+
K = gr.Slider(2, 48, value=16, step=1, label="K (constellations)")
|
| 723 |
+
iters = gr.Slider(5, 120, value=40, step=1, label="CHR iterations")
|
| 724 |
+
beta = gr.Slider(2, 30, value=16, step=1, label="beta (assignment sharpness)")
|
| 725 |
+
with gr.Row():
|
| 726 |
+
slab_bins = gr.Slider(3, 16, value=8, step=1, label="slab bins (entropy measure)")
|
| 727 |
+
tau = gr.Slider(1, 20, value=5, step=1, label="tau (slab softness)")
|
| 728 |
+
radial_bins = gr.Slider(8, 256, value=64, step=8, label="radial bins (compression alphabet)")
|
| 729 |
+
seed = gr.Slider(0, 9999, value=42, step=1, label="seed")
|
| 730 |
+
|
| 731 |
+
compress_btn = gr.Button("Compress → generate codes.bin", variant="primary")
|
| 732 |
+
compress_report = gr.Markdown("")
|
| 733 |
+
with gr.Row():
|
| 734 |
+
ent_img = gr.Image(label="Entropy during compression", type="filepath")
|
| 735 |
+
map_img = gr.Image(label="Constellation map (PCA)", type="filepath")
|
| 736 |
+
with gr.Row():
|
| 737 |
+
bin_file = gr.File(label="codes.bin (compressed stream)")
|
| 738 |
+
codec_file = gr.File(label="codec.json (metadata)")
|
| 739 |
+
|
| 740 |
+
compress_btn.click(
|
| 741 |
+
compress_now,
|
| 742 |
+
inputs=[K, iters, beta, slab_bins, tau, seed, radial_bins],
|
| 743 |
+
outputs=[compress_report, ent_img, map_img, bin_file, codec_file]
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
with gr.Tab("3) Train + Wow"):
|
| 747 |
+
with gr.Row():
|
| 748 |
+
train_steps = gr.Slider(100, 6000, value=900, step=50, label="training steps")
|
| 749 |
+
batch_size = gr.Slider(8, 256, value=64, step=8, label="batch size")
|
| 750 |
+
block_size = gr.Slider(64, 512, value=256, step=32, label="sequence length (bytes)")
|
| 751 |
+
with gr.Row():
|
| 752 |
+
lr = gr.Number(value=3e-4, label="learning rate")
|
| 753 |
+
log_every = gr.Slider(10, 200, value=50, step=10, label="log every (steps)")
|
| 754 |
+
temperature = gr.Slider(0.5, 2.0, value=1.0, step=0.05, label="rollout temperature")
|
| 755 |
+
rollout_steps = gr.Slider(60, 800, value=240, step=20, label="rollout steps (bytes)")
|
| 756 |
+
with gr.Row():
|
| 757 |
+
gif_stride = gr.Slider(1, 10, value=2, step=1, label="GIF stride (lower = smoother, heavier)")
|
| 758 |
+
gif_fps = gr.Slider(6, 24, value=12, step=1, label="GIF FPS")
|
| 759 |
+
|
| 760 |
+
train_btn = gr.Button("Train (compressed-only) + Generate visuals", variant="primary")
|
| 761 |
+
train_report = gr.Markdown("")
|
| 762 |
+
|
| 763 |
+
with gr.Row():
|
| 764 |
+
train_img = gr.Image(label="Loss + perplexity (compressed stream)", type="filepath")
|
| 765 |
+
compare_img = gr.Image(label="BEFORE vs AFTER rollout comparison", type="filepath")
|
| 766 |
+
with gr.Row():
|
| 767 |
+
gif_out = gr.Image(label="Animated rollout GIF (AFTER)", type="filepath")
|
| 768 |
+
|
| 769 |
+
metrics_json = gr.Code(label="Metrics (JSON)", language="json")
|
| 770 |
+
|
| 771 |
+
train_btn.click(
|
| 772 |
+
train_now,
|
| 773 |
+
inputs=[train_steps, batch_size, block_size, lr, log_every, temperature, rollout_steps, gif_stride, gif_fps],
|
| 774 |
+
outputs=[train_report, train_img, compare_img, gif_out, metrics_json]
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
if __name__ == "__main__":
|
| 778 |
+
demo.launch()
|