eggfuse 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,97 @@
1
+ import json
2
+ import os
3
+ import subprocess
4
+ import tempfile
5
+ from contextlib import contextmanager
6
+ from pathlib import Path
7
+
8
+
9
+ @contextmanager
10
+ def receiver(worker, program):
11
+ with tempfile.TemporaryDirectory() as tmp:
12
+ frames = Path(tmp) / "frames"
13
+ proc = subprocess.Popen(
14
+ [worker, program, frames, "--propose"],
15
+ stdin=-1,
16
+ stdout=-1,
17
+ text=True,
18
+ env={**os.environ, "EGGFUSE_REPLAY_FIELD_VALUES": "1"},
19
+ )
20
+
21
+ def run(ir, requests, *, through=None, audit_next=False):
22
+ packet = {"initial": ir, "requests": requests}
23
+ if through is not None:
24
+ packet["through"] = through
25
+ if audit_next:
26
+ if through is None:
27
+ raise ValueError("audit requires explicit Run boundary")
28
+ packet["audit_next"] = True
29
+ proc.stdin.write(json.dumps(packet) + "\n")
30
+ proc.stdin.flush()
31
+ result = json.loads(proc.stdout.readline())
32
+ if through is not None and result.get("committed_runs") != through:
33
+ raise ValueError("receiver did not certify requested Run boundary")
34
+ return result
35
+
36
+ try:
37
+ yield run, frames
38
+ finally:
39
+ proc.stdin.close()
40
+ if proc.wait():
41
+ raise RuntimeError("receiver failed")
42
+
43
+
44
+ def resolve_worker(path=None):
45
+ """Use the named-request worker from this package or the selected build."""
46
+ import shutil
47
+
48
+ candidate = (
49
+ path or os.environ.get("RIPSAT_WORKER") or shutil.which("ripsat-window-worker")
50
+ )
51
+ if (
52
+ not candidate
53
+ or not Path(candidate).is_file()
54
+ or not os.access(candidate, os.X_OK)
55
+ ):
56
+ raise FileNotFoundError(
57
+ "Set RIPSAT_WORKER to the executable, or run ripsat build-worker."
58
+ )
59
+ return Path(candidate).resolve()
60
+
61
+
62
+ def build_worker(checkout, build):
63
+ """Compile the packaged worker against a compatible EggFuse research checkout."""
64
+ import shutil
65
+
66
+ build = Path(build).resolve()
67
+ checkout = Path(checkout).resolve()
68
+ source = Path(__file__).with_name("assets") / "corpus_worker.rs"
69
+ build.mkdir(parents=True, exist_ok=True)
70
+ project = build / "ripsat-worker"
71
+ project.mkdir(exist_ok=True)
72
+ runtime = checkout / "engine/cell-runtime"
73
+ if not (runtime / "Cargo.toml").is_file():
74
+ raise FileNotFoundError(f"Missing EggFuse runtime at {runtime}")
75
+ (project / "Cargo.toml").write_text(
76
+ '[package]\nname="ripsat-window-worker"\nversion="0.1.0"\nedition="2021"\n'
77
+ '[[bin]]\nname="ripsat-window-worker"\npath='
78
+ + json.dumps(str(source))
79
+ + "\n[dependencies]\neggfuse-cell-runtime={path="
80
+ + json.dumps(str(runtime))
81
+ + ',features=["cell-token-ept","cell-token-replay","slot-transfer-audit","spine-blocks","iterative-bake"]}\n'
82
+ 'serde_json={version="1",features=["float_roundtrip"]}\n'
83
+ )
84
+ shutil.copyfile(checkout / "Cargo.lock", project / "Cargo.lock")
85
+ subprocess.run(
86
+ [
87
+ "cargo",
88
+ "build",
89
+ "--release",
90
+ "--manifest-path",
91
+ project / "Cargo.toml",
92
+ "--target-dir",
93
+ build / "target",
94
+ ],
95
+ check=True,
96
+ )
97
+ return build / "target/release/ripsat-window-worker"
@@ -0,0 +1,133 @@
1
+ """Neural proposal from public state and its own draft history."""
2
+
3
+ import json
4
+ import operator
5
+ import time
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+ from .encoding import encode, public_frames
11
+ from .model import tensor_rows
12
+ from .sampling import draw, finish_without_replacement
13
+
14
+
15
+ def page(model, frame, policy, capacity, generator, stop_rng, rng, offset):
16
+ if policy == "factorized-random":
17
+ refs = [(a["token"], a["op"], v["version"]) for a, v in frame["updates"]]
18
+ rules = torch.randint(
19
+ model.role.num_embeddings, (capacity,), generator=generator
20
+ )
21
+ parents = torch.randint(len(refs), (capacity, 2), generator=generator)
22
+ proposals = [tuple(t) for t in torch.cat((rules[:, None], parents), 1).tolist()]
23
+ history = dict.fromkeys(proposals)
24
+ end_p = None
25
+ else:
26
+ rows, refs = encode(frame)
27
+ base = model.memory(tensor_rows([rows]))
28
+ end_p = base[-1][0].softmax(0)[-1].item() if model.use_end else None
29
+ # At a fresh publication: one categorical END/continue decision.
30
+ # Conditional on continue, sample from the exact remaining Rule marginal.
31
+ if policy == "autonomous" and torch.rand((), generator=stop_rng).item() < end_p:
32
+ return [], [], True, end_p
33
+ history = {}
34
+ proposals = []
35
+ sizes = [2] * model.role.num_embeddings
36
+ chunk = 4 if model.use_end else capacity
37
+ for start in range(0, capacity, chunk):
38
+ mem = model.read_draft(base, [list(history)]) if model.use_end else base
39
+ mem = (*mem[:-1], mem[-1][:, : len(sizes)])
40
+ raw = draw(
41
+ model, mem, torch.tensor(sizes), min(chunk, capacity - start), generator
42
+ )
43
+ proposals.extend(raw)
44
+ history.update(dict.fromkeys(raw))
45
+ if policy == "historical-wor":
46
+ extra, _ = finish_without_replacement(
47
+ model, mem, sizes, list(history), capacity, rng
48
+ )
49
+ history.update(dict.fromkeys(extra))
50
+ return sign_requests(history, refs, frame["run"], offset), proposals, False, end_p
51
+
52
+
53
+ def sign_requests(history, refs, run, offset):
54
+ """Resolve public port indices into named addresses; preserve variable parent arity."""
55
+ signed = []
56
+ for i, (rule, *parents) in enumerate(history, 1):
57
+ if any(p < 0 or p >= len(refs) for p in parents):
58
+ raise ValueError("Parent index outside the supplied public view")
59
+ named = []
60
+ for parent in parents:
61
+ owner, op, version = refs[parent]
62
+ named.append({"address": {"token": owner, "op": op}, "version": version})
63
+ signed.append({"token": offset + i, "rule": rule, "parents": named, "run": run})
64
+ return signed
65
+
66
+
67
+ def rollout(model, init, run, frames, policy, budget, seed, window_capacity=8):
68
+ generator = torch.Generator().manual_seed(seed)
69
+ stop_rng = torch.Generator().manual_seed(seed + 1000003)
70
+ rng = np.random.default_rng(seed)
71
+ tape = []
72
+ record = []
73
+ start = time.perf_counter()
74
+ state = run(init, [], through=0)
75
+ deltas = [json.loads(l) for l in frames.read_text().splitlines()]
76
+ run_id = 1
77
+ while len(tape) < budget:
78
+ if not deltas or deltas[-1]["run"] < run_id:
79
+ reason = "source_schedule"
80
+ break
81
+ current = list(public_frames(deltas[:run_id]))[-1]
82
+ if current["run"] != run_id:
83
+ raise ValueError("noncontiguous publication")
84
+ capacity = min(window_capacity, budget - len(tape))
85
+ if callable(policy):
86
+ # The custom decoder sees only published observations and its own RNG.
87
+ proposals = policy(model, current, capacity, generator)
88
+ end = proposals is None
89
+ prob = None
90
+ if isinstance(proposals, torch.Tensor):
91
+ proposals = proposals.tolist()
92
+ raw = [] if end else [tuple(map(operator.index, t)) for t in proposals]
93
+ if len(raw) > capacity:
94
+ raise ValueError("Policy exceeded its proposal budget")
95
+ refs = [(a["token"], a["op"], v["version"]) for a, v in current["updates"]]
96
+ req = sign_requests(dict.fromkeys(raw), refs, run_id, len(tape))
97
+ else:
98
+ req, raw, end, prob = page(
99
+ model, current, policy, capacity, generator, stop_rng, rng, len(tape)
100
+ )
101
+ record.append(
102
+ {
103
+ "run": run_id,
104
+ "raw": raw,
105
+ "paid": len(req),
106
+ "end": end,
107
+ "end_probability": prob,
108
+ "before": state["final"],
109
+ }
110
+ )
111
+ if end:
112
+ reason = "model_end"
113
+ break
114
+ if not req:
115
+ raise ValueError("unexpected empty batch")
116
+ tape.extend(req)
117
+ state = run(init, tape, through=run_id)
118
+ if state["unused"]:
119
+ raise ValueError("source window closed before issue")
120
+ deltas = [json.loads(l) for l in frames.read_text().splitlines()]
121
+ run_id += 1
122
+ else:
123
+ reason = "paid_cap"
124
+ elapsed = time.perf_counter() - start
125
+ return {
126
+ "reason": reason,
127
+ "windows": record,
128
+ "tape": tape,
129
+ "counts": state["counts"],
130
+ "credit": state["credit"],
131
+ "final": state["final"],
132
+ "seconds": elapsed,
133
+ }
@@ -0,0 +1,84 @@
1
+ import numpy as np
2
+ import torch
3
+
4
+
5
+ def pointer_macs(n, second=False, w=32):
6
+ return (2 if second else 1) * w * w + n * w
7
+
8
+
9
+ class Remaining:
10
+ """Conditional categorical node. Only prefixes already sampled acquire children."""
11
+
12
+ def __init__(self, probs):
13
+ self.probs = np.asarray(probs, dtype=np.float64)
14
+ self.probs = self.probs / self.probs.sum()
15
+ self.mass = self.probs.copy()
16
+ self.children = {}
17
+
18
+ def draw(self, rng):
19
+ return int(rng.choice(len(self.mass), p=self.mass / self.mass.sum()))
20
+
21
+ def update(self, i):
22
+ # Re-sum surviving leaves, avoiding 1 - removed_mass cancellation in tails.
23
+ self.mass[i] = (
24
+ self.probs[i] * self.children[i].mass.sum() if i in self.children else 0.0
25
+ )
26
+
27
+
28
+ def conditional_node(logits):
29
+ return Remaining(logits.reshape(-1).double().softmax(0).numpy())
30
+
31
+
32
+ def finish_without_replacement(model, memory, sizes, prior, count, rng):
33
+ h, k, m, p, logits = memory
34
+ n = h.shape[1]
35
+ root = conditional_node(logits)
36
+ macs = 0
37
+
38
+ def take(preset=None):
39
+ nonlocal macs
40
+ r = root.draw(rng) if preset is None else preset[0]
41
+ if r not in root.children:
42
+ q = model.first(p + model.role.weight[r]).tanh()
43
+ first = conditional_node(model.pointer(q, k, m))
44
+ first.query = q
45
+ root.children[r] = first
46
+ macs += pointer_macs(n)
47
+ first = root.children[r]
48
+ a = first.draw(rng) if preset is None else preset[1]
49
+ b = -1
50
+ if sizes[r] == 2:
51
+ if a not in first.children:
52
+ q = model.next(torch.cat((first.query, h[:, a]), 1)).tanh()
53
+ first.children[a] = conditional_node(model.pointer(q, k, m))
54
+ macs += pointer_macs(n, True)
55
+ second = first.children[a]
56
+ b = second.draw(rng) if preset is None else preset[2]
57
+ second.update(b)
58
+ first.update(a)
59
+ root.update(r)
60
+ return (r, a, b)
61
+
62
+ for item in prior:
63
+ take(item)
64
+ extra = []
65
+ while len(prior) + len(extra) < count and root.mass.any():
66
+ extra.append(take())
67
+ return extra, macs
68
+
69
+
70
+ def draw(model, mem, arities, count, gen):
71
+ h, k, v, p, rlog = mem
72
+ r = torch.multinomial(rlog[0].softmax(0), count, True, generator=gen)
73
+ q = model.first(p + model.role(r)).tanh()
74
+ a = torch.multinomial(
75
+ model.pointer(q, k, v).softmax(-1), 1, generator=gen
76
+ ).flatten()
77
+ b = torch.full_like(a, -1)
78
+ two = arities[r] == 2
79
+ if two.any():
80
+ q2 = model.next(torch.cat((q[two], h[0, a[two]]), -1)).tanh()
81
+ b[two] = torch.multinomial(
82
+ model.pointer(q2, k, v).softmax(-1), 1, generator=gen
83
+ ).flatten()
84
+ return list(zip(r.tolist(), a.tolist(), b.tolist()))
@@ -0,0 +1,265 @@
1
+ import json
2
+ import os
3
+ import random
4
+ import shutil
5
+ import subprocess
6
+ import time
7
+ from pathlib import Path
8
+ from types import SimpleNamespace
9
+
10
+ import numpy as np
11
+ import torch
12
+
13
+ from .batching import batch_tensors, prepare
14
+ from .batching import load_states as load
15
+ from .model import CalculusPointer
16
+
17
+ SHAPES = {"20k": (32, 1, 4), "100k": (64, 2, 4), "1m": (192, 3, 6), "10m": (512, 4, 8)}
18
+
19
+
20
+ def loss_for(model, packed, device):
21
+ batch = {k: v.to(device) for k, v in batch_tensors(packed).items()}
22
+ weights = batch.pop("weights")
23
+ log_p = model(**batch)
24
+ return -(log_p * weights).sum() / len(batch["rows"])
25
+
26
+
27
+ def fit(a):
28
+ w, layers, heads = SHAPES[a.size]
29
+ name = f"{a.size}-u{a.worlds}{'-historical' if a.historical else ''}{'-shallow' if a.shallow else ''}-s{a.seed}"
30
+ out = getattr(a, "output", None) or a.root / name
31
+ out.mkdir(parents=True, exist_ok=False)
32
+ torch.manual_seed(a.seed)
33
+ torch.set_num_threads(3)
34
+ rng = random.Random(a.seed)
35
+ program = json.loads((a.root / "data/program.json").read_bytes())["source_core"]
36
+ m = CalculusPointer(
37
+ len(program["tables"]),
38
+ len(program["rulesets"][0]["rules"]),
39
+ not a.historical,
40
+ width=w,
41
+ layers=layers,
42
+ heads=heads,
43
+ ).to(a.device)
44
+ opt = torch.optim.AdamW(m.parameters(), lr=0.0005)
45
+ total = sum(p.numel() for p in m.parameters())
46
+ weights = out / "weights.pt"
47
+ revision = (
48
+ subprocess.run(
49
+ ["git", "-C", str(Path(__file__).parent), "rev-parse", "HEAD"],
50
+ check=False,
51
+ capture_output=True,
52
+ text=True,
53
+ ).stdout.strip()
54
+ if shutil.which("git")
55
+ else None
56
+ )
57
+ conf = {
58
+ "model": name,
59
+ "registered": total,
60
+ "pid": os.getpid(),
61
+ "git": revision,
62
+ "data_version": a.root.name,
63
+ "training_seed": a.seed,
64
+ "checkpoint": str(weights),
65
+ "width": w,
66
+ "layers": layers,
67
+ "heads": heads,
68
+ "ffn": 2 * w,
69
+ "batch_states": a.batch,
70
+ "device": a.device,
71
+ "objective": "full Cell or verified END CE",
72
+ "lr": 0.0005,
73
+ "worlds": a.worlds,
74
+ "shallow": a.shallow,
75
+ "use_end": not a.historical,
76
+ "exposure_goal": a.exposure,
77
+ }
78
+ (out / "config.json").write_text(json.dumps(conf, indent=2))
79
+ with (out / "live.jsonl").open("w", buffering=1) as j:
80
+
81
+ def log(x):
82
+ print(json.dumps(x), file=j, flush=True)
83
+ if getattr(a, "logger", None):
84
+ a.logger(x)
85
+
86
+ log(dict(kind="config", **conf))
87
+ tracker = a.start_tracker(out) if getattr(a, "start_tracker", None) else None
88
+ data = load(a.root, "train", a.worlds, a.shallow)
89
+ val = load(a.root, "validation", getattr(a, "validation_worlds", 64))
90
+ if not any(y for _, y, _ in data):
91
+ raise ValueError("training partition has no complete Cell targets")
92
+ if a.historical:
93
+ data = [row for row in data if row[1]]
94
+ val = [row for row in val if row[1]]
95
+ vr = random.Random(433)
96
+ vb = [
97
+ prepare(
98
+ val, list(range(i, min(len(val), i + a.batch))), vr, not a.historical
99
+ )
100
+ for i in range(0, len(val), a.batch)
101
+ ]
102
+ seen = set()
103
+ seen_targets = set()
104
+ n = steps = ne = 0
105
+ ce = ns = fw = bw = op = 0
106
+ start = time.perf_counter()
107
+
108
+ def sync():
109
+ if a.device == "mps":
110
+ torch.mps.synchronize()
111
+ elif a.device == "cuda":
112
+ torch.cuda.synchronize()
113
+
114
+ while n < a.exposure:
115
+ order = list(range(len(data)))
116
+ rng.shuffle(order)
117
+ for start_i in range(0, len(order), a.batch * 12):
118
+ group = sorted(
119
+ order[start_i : start_i + 12 * a.batch],
120
+ key=lambda i: len(data[i][0]),
121
+ )
122
+ batches = [
123
+ group[i : i + a.batch] for i in range(0, len(group), a.batch)
124
+ ]
125
+ rng.shuffle(batches)
126
+ for indices in batches:
127
+ packed = prepare(data, indices, rng, not a.historical)
128
+ t = time.perf_counter()
129
+ opt.zero_grad(set_to_none=True)
130
+ loss = loss_for(m, packed, a.device)
131
+ sync()
132
+ fw += time.perf_counter() - t
133
+ t = time.perf_counter()
134
+ loss.backward()
135
+ norm = torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0)
136
+ sync()
137
+ bw += time.perf_counter() - t
138
+ t = time.perf_counter()
139
+ opt.step()
140
+ sync()
141
+ op += time.perf_counter() - t
142
+ ce += float(loss.detach()) * len(indices)
143
+ ns += len(indices)
144
+ prev = n
145
+ n += len(packed[-1])
146
+ ne += len(packed[3])
147
+ steps += 1
148
+ seen.update(indices)
149
+ seen_targets.update(packed[-1])
150
+ if not np.isfinite(ce):
151
+ raise ArithmeticError("nonfinite CE")
152
+ if prev // 10000 != n // 10000 or steps == 1 or n >= a.exposure:
153
+ with torch.no_grad():
154
+ v = sum(
155
+ float(loss_for(m, b, a.device)) * len(b[0]) for b in vb
156
+ ) / len(val)
157
+ elapsed = time.perf_counter() - start
158
+ con = sum(
159
+ p.numel() for p in m.parameters() if p.grad is not None
160
+ )
161
+ metrics = {
162
+ "train_ce": ce / ns,
163
+ "validation_ce": v,
164
+ "exposures": n,
165
+ "end_exposures": ne,
166
+ "optimizer_steps": steps,
167
+ "training_states": len(seen),
168
+ "unique_full_targets": len(seen_targets),
169
+ "parameters_connected": con,
170
+ "parameters_forward": con,
171
+ "gradient_norm": float(norm),
172
+ "lr": 0.0005,
173
+ "training_seconds": elapsed,
174
+ "tokens_per_second": n / elapsed,
175
+ "forward_seconds": fw,
176
+ "backward_seconds": bw,
177
+ "optimizer_seconds": op,
178
+ }
179
+ log({"kind": "metrics", "step": n, "metrics": metrics})
180
+ ce = ns = 0
181
+ if prev // 100000 != n // 100000 or n >= a.exposure:
182
+ staged = weights.with_suffix(".partial")
183
+ torch.save(m.state_dict(), staged)
184
+ staged.replace(weights)
185
+ if n >= a.exposure:
186
+ break
187
+ if n >= a.exposure:
188
+ break
189
+ (out / "training.json").write_text(
190
+ json.dumps(
191
+ dict(
192
+ parameters=total,
193
+ available_states=len(data),
194
+ available_targets=sum(len(y) for _, y, _ in data),
195
+ **metrics,
196
+ ),
197
+ indent=2,
198
+ )
199
+ )
200
+ log({"kind": "finish"})
201
+ if tracker is not None and tracker.wait(timeout=120):
202
+ raise RuntimeError("SwanLab failed")
203
+
204
+ return out
205
+
206
+
207
+ def train(
208
+ root,
209
+ output,
210
+ *,
211
+ worlds,
212
+ exposure=500000,
213
+ size="1m",
214
+ seed=71,
215
+ batch=128,
216
+ device="cpu",
217
+ swanlog=None,
218
+ ):
219
+ """Train with complete-Cell CE. The native runtime is offline during fitting."""
220
+ from .data import check_program
221
+
222
+ root = Path(root)
223
+ check_program(root)
224
+ if size not in SHAPES or min(worlds, exposure, batch) < 1:
225
+ raise ValueError("Invalid model size, training worlds, exposure or batch")
226
+ output = Path(output)
227
+ config = SimpleNamespace(
228
+ root=root,
229
+ output=output,
230
+ size=size,
231
+ worlds=worlds,
232
+ exposure=exposure,
233
+ seed=seed,
234
+ batch=batch,
235
+ device=device,
236
+ shallow=False,
237
+ historical=False,
238
+ validation_worlds=None,
239
+ logger=None,
240
+ )
241
+ if swanlog is None:
242
+ return fit(config)
243
+ import swanlab
244
+
245
+ tracker = swanlab.init(
246
+ project="ripsat",
247
+ name=output.name,
248
+ mode="local",
249
+ log_dir=str(swanlog),
250
+ config={
251
+ k: str(v) if isinstance(v, Path) else v for k, v in vars(config).items()
252
+ },
253
+ )
254
+
255
+ def log(row):
256
+ if row["kind"] == "metrics":
257
+ tracker.log(row["metrics"], step=row["step"])
258
+ elif row["kind"] == "config":
259
+ tracker.config.update(row)
260
+
261
+ config.logger = log
262
+ try:
263
+ return fit(config)
264
+ finally:
265
+ tracker.finish()