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.
eggfuse/ripsat/data.py ADDED
@@ -0,0 +1,476 @@
1
+ """Collect native, replay-verified examples for the fixed eight-rule calculus recipe."""
2
+
3
+ import gzip
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import random
8
+ import shutil
9
+ import subprocess
10
+ import tempfile
11
+ from collections import Counter
12
+ from concurrent.futures import ProcessPoolExecutor
13
+ from pathlib import Path
14
+
15
+ from .encoding import encode, public_frames
16
+ from .graphs import canonical, depth, native_rows, runtime_rows
17
+ from .native import receiver
18
+
19
+ ASSETS = Path(__file__).with_name("assets")
20
+ CALCULUS = ASSETS / "calculus.egg"
21
+ SCHEDULE = "(run-schedule (saturate (run)))"
22
+
23
+
24
+ def term(node):
25
+ return (
26
+ "("
27
+ + " ".join(
28
+ [node[0], *(term(a) if isinstance(a, tuple) else str(a) for a in node[1:])]
29
+ )
30
+ + ")"
31
+ )
32
+
33
+
34
+ def initial_rows(roots):
35
+ nodes = {}
36
+ rows = []
37
+
38
+ def visit(n):
39
+ if n not in nodes:
40
+ fields = [
41
+ visit(a) if isinstance(a, tuple) else {"sort": "i64", "value": a}
42
+ for a in n[1:]
43
+ ]
44
+ nodes[n] = {"eq": f"Value({len(rows)})", "sort": "Math"}
45
+ rows.append(
46
+ {"table": n[0], "values": [*fields, nodes[n]], "subsumed": False}
47
+ )
48
+ return nodes[n]
49
+
50
+ for root in roots:
51
+ visit(root)
52
+ return rows
53
+
54
+
55
+ def candidates(rng):
56
+ while True:
57
+ x, y, z = [
58
+ ("RipenInput", rng.randrange(i * 100000, (i + 1) * 100000))
59
+ for i in range(3)
60
+ ]
61
+ order = rng.choice([3, 6, 10, 12])
62
+ integ = rng.randrange(2)
63
+ ops = ("Add", "Sub") if integ else ("Add", "Mul")
64
+ body = (rng.choice(("Sin", "Cos")), x)
65
+ for _ in range(rng.randint(1, order)):
66
+ leaf = rng.choice([x, y, z, ("Cos", y), ("Sin", x), ("Cos", x), body])
67
+ if rng.random() < 0.32:
68
+ leaf = (rng.choice(ops), leaf, rng.choice([y, z, ("Sin", x)]))
69
+ body = (
70
+ (rng.choice(ops), body, leaf)
71
+ if rng.randrange(2)
72
+ else (rng.choice(ops), leaf, body)
73
+ )
74
+ root = ("Integral", body, x) if integ else ("Diff", x, body)
75
+ if rng.random() < 0.10:
76
+ root = body if rng.randrange(2) else ("Diff", x, ("Div", body, y))
77
+ ir = initial_rows([root])
78
+ if len(ir) <= 32:
79
+ yield ir, term(root)
80
+
81
+
82
+ def composition_candidates(rng):
83
+ """Co-locate integration and differentiation; some derivatives consume an integral."""
84
+ while True:
85
+ x = ("RipenInput", rng.randrange(100000))
86
+ y = ("RipenInput", rng.randrange(100000, 200000))
87
+ choices = [x, y, ("Sin", x), ("Cos", x), ("Sin", y), ("Cos", y)]
88
+
89
+ def body(ops, choices=choices):
90
+ expr = rng.choice(choices)
91
+ for _ in range(rng.randint(1, 5)):
92
+ op = rng.choice(ops)
93
+ operand = rng.choice(choices)
94
+ expr = (op, expr, operand) if rng.randrange(2) else (op, operand, expr)
95
+ return expr
96
+
97
+ integral = ("Integral", body(["Add", "Sub"]), x)
98
+ derivand = body(["Add", "Mul"])
99
+ if rng.randrange(2):
100
+ root = ("Diff", x, (rng.choice(["Add", "Mul"]), derivand, integral))
101
+ else:
102
+ root = (rng.choice(["Add", "Sub", "Mul"]), ("Diff", x, derivand), integral)
103
+ ir = initial_rows([root])
104
+ if len(ir) <= 32:
105
+ yield ir, term(root)
106
+
107
+
108
+ def supervised_states(w, ir, run):
109
+ counts = dict(w["credit"]["origins"])
110
+ states = []
111
+ prefix = []
112
+ used = set()
113
+ frames = list(public_frames(w["frames"]))
114
+ for i, f in enumerate(frames):
115
+ tape = [t for t in w["requests"] if t["run"] == f["run"]]
116
+ x, refs = encode(f)
117
+ idx = {r: j for j, r in enumerate(refs)}
118
+ y = []
119
+ for t in tape:
120
+ if counts.get(t["token"], 0) <= 0:
121
+ continue
122
+ if len(tape) > 1:
123
+ q = run(ir, prefix + [t], through=f["run"])
124
+ if not dict(q["credit"]["origins"]).get(t["token"], 0):
125
+ continue
126
+ y.append(
127
+ [
128
+ t["rule"],
129
+ *[
130
+ idx[
131
+ p["address"]["token"],
132
+ p["address"]["op"],
133
+ p["version"],
134
+ ]
135
+ for p in t["parents"]
136
+ ],
137
+ ]
138
+ )
139
+ used.add(t["rule"])
140
+ end = i == len(frames) - 1
141
+ if end:
142
+ q = run(ir, prefix, through=i)
143
+ if q["final"] != w["final"] or w["changed"][-1] or y:
144
+ raise ValueError("uncertified END")
145
+ if end or y:
146
+ states.append([x, y, end])
147
+ prefix.extend(tape)
148
+ return states, used
149
+
150
+
151
+ def produce(args):
152
+ split, block, program, worker, *options = args
153
+ archive = bool(options and options[0])
154
+ rng = random.Random(f"reasoning-v1/{split}/{block}")
155
+ out = []
156
+ pre = CALCULUS.read_text().split("\n;; Local input\n")[0]
157
+ with tempfile.TemporaryDirectory() as td, receiver(worker, program) as (run, _):
158
+ tmp = Path(td)
159
+ capture = subprocess.Popen(
160
+ [worker, program, tmp / "frames"],
161
+ stdin=-1,
162
+ stdout=-1,
163
+ text=True,
164
+ env={**os.environ, "EGGFUSE_REPLAY_FIELD_VALUES": "1"},
165
+ )
166
+ paths = [tmp / "base.egg"]
167
+ paths[0].write_text(pre + "(push)\n")
168
+ try:
169
+ source = composition_candidates if split == "composition" else candidates
170
+ for ir, entry in source(rng):
171
+ capture.stdin.write(json.dumps(ir) + "\n")
172
+ capture.stdin.flush()
173
+ w = json.loads(capture.stdout.readline())
174
+ states, used = supervised_states(w, ir, run)
175
+ a = runtime_rows(w["initial"])
176
+ b = runtime_rows(w["final"])
177
+ uid = hashlib.sha256(canonical(a)).hexdigest()
178
+ oid = hashlib.sha256(canonical(b)).hexdigest()
179
+ row = {
180
+ "uid": uid,
181
+ "oid": oid,
182
+ "n": len(a),
183
+ "nf": len(b),
184
+ "depth": depth(w),
185
+ "rules": sorted(used),
186
+ "states": states,
187
+ }
188
+ if archive or split != "train":
189
+ row.update(initial=ir, final=w["final"], entry=entry)
190
+ if archive:
191
+ row["teacher_requests"] = w["requests"]
192
+ j = len(out)
193
+ pa, pb = tmp / f"i{j}.egg", tmp / f"o{j}.egg"
194
+ pa.write_text("(pop)\n(push)\n" + entry + "\n")
195
+ pb.write_text(SCHEDULE)
196
+ paths.extend((pa, pb))
197
+ out.append(
198
+ (
199
+ row,
200
+ canonical(a, pin_boundaries=True),
201
+ canonical(b, pin_boundaries=True),
202
+ )
203
+ )
204
+ if len(out) == 32:
205
+ break
206
+ finally:
207
+ capture.stdin.close()
208
+ if capture.wait():
209
+ raise RuntimeError("native capture failed")
210
+ subprocess.run(
211
+ ["egglog", "--to-json", *paths],
212
+ cwd=tmp,
213
+ stdout=subprocess.DEVNULL,
214
+ stderr=subprocess.PIPE,
215
+ check=True,
216
+ timeout=120,
217
+ )
218
+ verified = []
219
+ rejected = []
220
+ for j, (row, a, b) in enumerate(out):
221
+ for kind, expected in (("i", a), ("o", b)):
222
+ got = native_rows(json.loads((tmp / f"{kind}{j}.json").read_bytes()))
223
+ if canonical(got, pin_boundaries=True) != expected:
224
+ rejected.append(
225
+ {
226
+ "uid": row["uid"],
227
+ "graph": kind,
228
+ "entry": paths[1 + 2 * j].read_text(),
229
+ }
230
+ )
231
+ break
232
+ else:
233
+ verified.append(row)
234
+ if rejected:
235
+ diag = program.parent / "disagreements"
236
+ diag.mkdir(exist_ok=True)
237
+ (diag / f"{split}-{block}.json").write_text(json.dumps(rejected))
238
+ return verified
239
+
240
+
241
+ def build_split(
242
+ split,
243
+ limit,
244
+ dataset,
245
+ pool,
246
+ program,
247
+ worker,
248
+ jobs,
249
+ inputs,
250
+ owners,
251
+ card,
252
+ archive=False,
253
+ ):
254
+ count = 0
255
+ er = 0.0
256
+ ds = Counter()
257
+ sizes = Counter()
258
+ rules = Counter()
259
+ state_n = target_n = 0
260
+ outputs = set()
261
+
262
+ def accept(r):
263
+ nonlocal count, er, state_n, target_n
264
+ uid, oid = r["uid"], r["oid"]
265
+ if uid in inputs or owners.get(oid, split) != split:
266
+ return False
267
+ inputs.add(uid)
268
+ owners[oid] = split
269
+ outputs.add(oid)
270
+ count += 1
271
+ er += r["nf"] / r["n"]
272
+ ds[str(r["depth"])] += 1
273
+ sizes[r["n"]] += 1
274
+ rules[len(r["rules"])] += 1
275
+ state_n += len(r["states"])
276
+ target_n += sum(len(y) for _, y, _ in r["states"])
277
+ return True
278
+
279
+ def snapshot():
280
+ known = count - ds["None"]
281
+ card[f"{split}-{count}"] = {
282
+ "Uin": count,
283
+ "Uout": len(outputs),
284
+ "ER": er / count,
285
+ "DEPTH": sum(int(k) * v for k, v in ds.items() if k != "None") / known
286
+ if known
287
+ else None,
288
+ "depth_hist": dict(ds),
289
+ "initial_nodes": dict(sizes),
290
+ "distinct_rules_per_world": dict(rules),
291
+ "states": state_n,
292
+ "targets": target_n,
293
+ }
294
+ tmp = dataset / "card.tmp"
295
+ tmp.write_text(json.dumps(card, indent=2))
296
+ tmp.replace(dataset / "card.json")
297
+
298
+ block = 0
299
+ buf = []
300
+ # Completed shards are resumable. Uncommitted rows replay deterministically.
301
+ for path in sorted(dataset.glob(f"{split}-*.jsonl.gz")):
302
+ with gzip.open(path, "rt") as stream:
303
+ for line in stream:
304
+ if not accept(json.loads(line)):
305
+ raise ValueError("duplicate persisted world")
306
+ if count in (1000, 10000, limit):
307
+ snapshot()
308
+ while count < limit:
309
+ work = [
310
+ (split, k, program, worker, archive) for k in range(block, block + jobs)
311
+ ]
312
+ for pack in pool.map(produce, work):
313
+ for r in pack:
314
+ if count >= limit or not accept(r):
315
+ continue
316
+ buf.append(r)
317
+ if len(buf) == 500 or count == limit:
318
+ path = dataset / f"{split}-{count:06d}.jsonl.gz"
319
+ tmp = path.with_suffix(".partial")
320
+ with gzip.open(tmp, "wt", compresslevel=2) as f:
321
+ for item in buf:
322
+ print(json.dumps(item, separators=(",", ":")), file=f)
323
+ tmp.replace(path)
324
+ buf = []
325
+ if count in (1000, 10000, limit) or count % 5000 == 0:
326
+ snapshot()
327
+ print(split, count, flush=True)
328
+ block += jobs
329
+
330
+
331
+ def collect(output, *, train=10000, validation=64, test=160, jobs=1, worker=None):
332
+ """Generate disjoint native worlds, including original graphs and named Teacher tapes."""
333
+ from .native import resolve_worker
334
+
335
+ if min(train, validation, test, jobs) < 1:
336
+ raise ValueError("All split sizes and jobs must be positive")
337
+ worker = resolve_worker(worker)
338
+ if not shutil.which("egglog"):
339
+ raise FileNotFoundError(
340
+ "Place the egglog CLI on PATH for independent graph verification"
341
+ )
342
+ data = Path(output).resolve() / "data"
343
+ data.mkdir(parents=True, exist_ok=True)
344
+ program = data / "program.json"
345
+ config = {
346
+ "format": 1,
347
+ "ruleset": "calculus8",
348
+ "splits": {"validation": validation, "test": test, "train": train},
349
+ "program_sha256": hashlib.sha256(
350
+ (ASSETS / "calculus.json").read_bytes()
351
+ ).hexdigest(),
352
+ "worker_sha256": hashlib.sha256(worker.read_bytes()).hexdigest(),
353
+ "egglog_sha256": hashlib.sha256(
354
+ Path(shutil.which("egglog")).read_bytes()
355
+ ).hexdigest(),
356
+ }
357
+ manifest = data / "collection.json"
358
+ # Exclusive native collection. Advisory locks are released when a process exits.
359
+ import fcntl
360
+
361
+ with (data / ".collection.lock").open("a") as lock:
362
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
363
+ if manifest.exists():
364
+ if json.loads(manifest.read_text()) != config:
365
+ raise ValueError(
366
+ "Existing collection used different sizes, recipe or native tools"
367
+ )
368
+ elif any(p.name != Path(lock.name).name for p in data.iterdir()):
369
+ raise FileExistsError(f"Use a fresh collection directory: {data}")
370
+ else:
371
+ tmp = manifest.with_suffix(".tmp")
372
+ tmp.write_text(json.dumps(config, indent=2))
373
+ tmp.replace(manifest)
374
+ shutil.copyfile(ASSETS / "calculus.json", program)
375
+ inputs, owners, card = set(), {}, {}
376
+ with ProcessPoolExecutor(max_workers=jobs) as pool:
377
+ for split, limit in config["splits"].items():
378
+ build_split(
379
+ split,
380
+ limit,
381
+ data,
382
+ pool,
383
+ program,
384
+ worker,
385
+ jobs,
386
+ inputs,
387
+ owners,
388
+ card,
389
+ archive=True,
390
+ )
391
+ return data
392
+
393
+
394
+ def worlds(root, split="test"):
395
+ """Stream archived graph examples from packaged or historical scaling shards."""
396
+ if split not in ("train", "validation", "test"):
397
+ raise ValueError(f"Unknown split {split}")
398
+ paths = sorted((Path(root) / "data").glob(f"{split}-*.jsonl.gz"))
399
+ if not paths:
400
+ raise FileNotFoundError(f"No {split} shards in {root}/data")
401
+ for path in paths:
402
+ with gzip.open(path, "rt") as stream:
403
+ for line in stream:
404
+ yield json.loads(line)
405
+
406
+
407
+ def check_program(root):
408
+ program = Path(root) / "data/program.json"
409
+ if json.loads(program.read_bytes()) != json.loads(
410
+ (ASSETS / "calculus.json").read_bytes()
411
+ ):
412
+ raise ValueError(
413
+ "This release supports only the packaged eight-rule calculus Recipe"
414
+ )
415
+ return program
416
+
417
+
418
+ def verify(root, *, split="test", limit=None, worker=None):
419
+ """Independently recapture and replay archived inputs and rederive the CE targets."""
420
+ from itertools import islice
421
+
422
+ from .native import resolve_worker
423
+
424
+ if limit is not None and limit < 1:
425
+ raise ValueError("limit must be positive")
426
+ program = check_program(root)
427
+ worker = resolve_worker(worker)
428
+ counts = Counter()
429
+ with (
430
+ tempfile.TemporaryDirectory() as tmp,
431
+ receiver(worker, program) as (fork, _),
432
+ subprocess.Popen(
433
+ [worker, program, Path(tmp) / "frames"],
434
+ stdin=subprocess.PIPE,
435
+ stdout=subprocess.PIPE,
436
+ text=True,
437
+ env={**os.environ, "EGGFUSE_REPLAY_FIELD_VALUES": "1"},
438
+ ) as capture,
439
+ ):
440
+ try:
441
+ for world in islice(worlds(root, split), limit):
442
+ if "initial" not in world or "final" not in world:
443
+ raise ValueError(
444
+ "This shard lacks native snapshots; select an archived split"
445
+ )
446
+ capture.stdin.write(json.dumps(world["initial"]) + "\n")
447
+ capture.stdin.flush()
448
+ replay = json.loads(capture.stdout.readline())
449
+ for field, identifier in (("initial", "uid"), ("final", "oid")):
450
+ graph = runtime_rows(replay[field])
451
+ if hashlib.sha256(canonical(graph)).hexdigest() != world[
452
+ identifier
453
+ ] or canonical(graph, pin_boundaries=True) != canonical(
454
+ runtime_rows(world[field]), pin_boundaries=True
455
+ ):
456
+ raise ValueError(f"{world['uid']}: mismatched {field}")
457
+ if (
458
+ "teacher_requests" in world
459
+ and replay["requests"] != world["teacher_requests"]
460
+ ):
461
+ raise ValueError(f"{world['uid']}: mismatched Teacher tape")
462
+ states, _ = supervised_states(replay, world["initial"], fork)
463
+ if states != world["states"] or depth(replay) != world["depth"]:
464
+ raise ValueError(
465
+ f"{world['uid']}: mismatched states, complete targets, END or depth"
466
+ )
467
+ counts.update(
468
+ worlds=1,
469
+ states=len(states),
470
+ complete_targets=sum(len(y) for _, y, _ in states),
471
+ )
472
+ finally:
473
+ capture.stdin.close()
474
+ if capture.wait():
475
+ raise RuntimeError("Native recapture failed")
476
+ return dict(counts)
@@ -0,0 +1,35 @@
1
+ """Keep Metal's Darwin per-user temporary files alongside the experiment TMPDIR."""
2
+
3
+ import atexit
4
+ import ctypes
5
+ import os
6
+ import tempfile
7
+ from pathlib import Path
8
+
9
+
10
+ def redirect_metal_tmp():
11
+ # Apple's compiler uses confstr(_CS_DARWIN_USER_TEMP_DIR), ignoring TMPDIR.
12
+ # Only this process's private suffix points at the external temporary directory.
13
+ libc = ctypes.CDLL(None)
14
+ buf = ctypes.create_string_buffer(4096)
15
+ if not libc.confstr(65537, buf, len(buf)):
16
+ raise OSError("unavailable Darwin user temp directory")
17
+ system_tmp = Path(os.fsdecode(buf.value))
18
+ requested_tmp = Path(os.environ["TMPDIR"])
19
+ if system_tmp.stat().st_dev == requested_tmp.stat().st_dev:
20
+ return
21
+ directory = tempfile.TemporaryDirectory(prefix="ripsat-metal-", dir=requested_tmp)
22
+ path = Path(directory.name)
23
+ link = system_tmp / path.name
24
+ link.symlink_to(path.resolve(), target_is_directory=True)
25
+
26
+ def close():
27
+ link.unlink(missing_ok=True)
28
+ directory.cleanup()
29
+
30
+ atexit.register(close)
31
+ if not libc._set_user_dir_suffix(os.fsencode(link.name)):
32
+ raise OSError("cannot isolate Metal temp files")
33
+ libc.confstr(65537, buf, len(buf))
34
+ if Path(os.fsdecode(buf.value)).resolve() != path.resolve():
35
+ raise OSError("Metal temp directory mismatch")
@@ -0,0 +1,41 @@
1
+ import hashlib
2
+ import json
3
+
4
+
5
+ def encode(frame):
6
+ fields = {(p["token"], p["op"], v): vals for p, v, vals in frame["observed_fields"]}
7
+ rows, refs = [], []
8
+ for addr, port in frame["updates"]:
9
+ ref = (addr["token"], addr["op"], port["version"])
10
+ vals = fields[ref]
11
+ # Independent identity encoding per public field. No cross-Cell comparisons.
12
+ ids = [
13
+ int.from_bytes(
14
+ hashlib.blake2s(json.dumps(x).encode(), digest_size=4).digest(),
15
+ "little",
16
+ )
17
+ % 510
18
+ + 1
19
+ for x in vals
20
+ ]
21
+ rows.append([port["table"] + 1, *ids, *([0] * (3 - len(ids)))])
22
+ refs.append(ref)
23
+ return rows, refs
24
+
25
+
26
+ def public_frames(frames):
27
+ rows, fields = {}, {}
28
+ for f in frames:
29
+ for a in f["retired"]:
30
+ key = a["token"], a["op"]
31
+ rows.pop(key, None)
32
+ fields.pop(key, None)
33
+ for a, v in f["updates"]:
34
+ rows[a["token"], a["op"]] = [a, v]
35
+ for a, v, vs in f["observed_fields"]:
36
+ fields[a["token"], a["op"]] = [a, v, vs]
37
+ yield {
38
+ "run": f["run"],
39
+ "updates": list(rows.values()),
40
+ "observed_fields": list(fields.values()),
41
+ }