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/__init__.py +1 -0
- eggfuse/ripsat/__init__.py +1 -0
- eggfuse/ripsat/__main__.py +4 -0
- eggfuse/ripsat/assets/calculus.egg +31 -0
- eggfuse/ripsat/assets/calculus.json +1 -0
- eggfuse/ripsat/assets/comparison.html +12 -0
- eggfuse/ripsat/assets/corpus_worker.rs +122 -0
- eggfuse/ripsat/batching.py +91 -0
- eggfuse/ripsat/cli.py +120 -0
- eggfuse/ripsat/data.py +476 -0
- eggfuse/ripsat/device_tmp.py +35 -0
- eggfuse/ripsat/encoding.py +41 -0
- eggfuse/ripsat/evaluation.py +174 -0
- eggfuse/ripsat/graphs.py +210 -0
- eggfuse/ripsat/model.py +222 -0
- eggfuse/ripsat/native.py +97 -0
- eggfuse/ripsat/rollout.py +133 -0
- eggfuse/ripsat/sampling.py +84 -0
- eggfuse/ripsat/training.py +265 -0
- eggfuse/ripsat/viz.py +175 -0
- eggfuse-0.2.1.dist-info/METADATA +133 -0
- eggfuse-0.2.1.dist-info/RECORD +40 -0
- eggfuse-0.2.1.dist-info/WHEEL +5 -0
- eggfuse-0.2.1.dist-info/entry_points.txt +2 -0
- eggfuse-0.2.1.dist-info/top_level.txt +2 -0
- ripsat/__init__.py +1 -0
- ripsat/__main__.py +4 -0
- ripsat/batching.py +7 -0
- ripsat/cli.py +7 -0
- ripsat/data.py +7 -0
- ripsat/device_tmp.py +7 -0
- ripsat/encoding.py +7 -0
- ripsat/evaluation.py +7 -0
- ripsat/graphs.py +7 -0
- ripsat/model.py +7 -0
- ripsat/native.py +7 -0
- ripsat/rollout.py +7 -0
- ripsat/sampling.py +7 -0
- ripsat/training.py +7 -0
- ripsat/viz.py +7 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Native neural execution and separate offline reference scoring."""
|
|
2
|
+
|
|
3
|
+
import gzip
|
|
4
|
+
import json
|
|
5
|
+
from collections import Counter, defaultdict
|
|
6
|
+
from itertools import islice
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
from .data import check_program, worlds
|
|
12
|
+
from .graphs import canonical, matched_rows, runtime_rows, stats, trajectory_counts
|
|
13
|
+
from .model import CalculusPointer
|
|
14
|
+
from .native import receiver, resolve_worker
|
|
15
|
+
from .rollout import rollout
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def load_model(checkpoint, program):
|
|
19
|
+
checkpoint = Path(checkpoint)
|
|
20
|
+
conf = json.loads((checkpoint / "config.json").read_bytes())
|
|
21
|
+
core = json.loads(Path(program).read_bytes())["source_core"]
|
|
22
|
+
tables = len(core["tables"])
|
|
23
|
+
rules = len(core["rulesets"][0]["rules"])
|
|
24
|
+
dims = {k: conf[k] for k in ("width", "layers", "heads")}
|
|
25
|
+
model = CalculusPointer(tables, rules, conf.get("use_end", True), **dims)
|
|
26
|
+
model.load_state_dict(
|
|
27
|
+
torch.load(checkpoint / "weights.pt", map_location="cpu", weights_only=True)
|
|
28
|
+
)
|
|
29
|
+
return model.eval()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _execute(model, initial, run, frames, budget, seed, policy, capacity):
|
|
33
|
+
if budget < 1 or capacity < 1:
|
|
34
|
+
raise ValueError("Budget and window capacity must be positive")
|
|
35
|
+
if not callable(policy):
|
|
36
|
+
supported = {"fixed", "factorized-random"}
|
|
37
|
+
supported.update(
|
|
38
|
+
{"autonomous"} if model.use_end else {"historical-first", "historical-wor"}
|
|
39
|
+
)
|
|
40
|
+
if policy not in supported:
|
|
41
|
+
raise ValueError(f"Unsupported policy for this checkpoint: {policy}")
|
|
42
|
+
with torch.inference_mode():
|
|
43
|
+
result = rollout(model, initial, run, frames, policy, budget, seed, capacity)
|
|
44
|
+
result.update(
|
|
45
|
+
budget=budget,
|
|
46
|
+
policy=getattr(policy, "__name__", type(policy).__name__)
|
|
47
|
+
if callable(policy)
|
|
48
|
+
else policy,
|
|
49
|
+
generation_seed=seed,
|
|
50
|
+
)
|
|
51
|
+
return result
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def complete(
|
|
55
|
+
model,
|
|
56
|
+
initial,
|
|
57
|
+
*,
|
|
58
|
+
worker=None,
|
|
59
|
+
program=None,
|
|
60
|
+
budget=64,
|
|
61
|
+
seed=193,
|
|
62
|
+
policy="autonomous",
|
|
63
|
+
capacity=8,
|
|
64
|
+
):
|
|
65
|
+
"""Run one graph. Pass only the initial rows, never the reference closure."""
|
|
66
|
+
from .data import ASSETS
|
|
67
|
+
|
|
68
|
+
with receiver(resolve_worker(worker), program or ASSETS / "calculus.json") as (
|
|
69
|
+
run,
|
|
70
|
+
frames,
|
|
71
|
+
):
|
|
72
|
+
return _execute(model, initial, run, frames, budget, seed, policy, capacity)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _counts(world, result):
|
|
76
|
+
reference = runtime_rows(world["final"])
|
|
77
|
+
base = matched_rows(runtime_rows(world["initial"]), reference)
|
|
78
|
+
actual = runtime_rows(result["final"])
|
|
79
|
+
key = canonical(reference, pin_boundaries=True)
|
|
80
|
+
return trajectory_counts(
|
|
81
|
+
result,
|
|
82
|
+
canonical(actual, pin_boundaries=True) == key,
|
|
83
|
+
len(matched_rows(actual, reference) - base),
|
|
84
|
+
len(reference) - len(base),
|
|
85
|
+
lambda snapshot: canonical(runtime_rows(snapshot), pin_boundaries=True) == key,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def evaluate(
|
|
90
|
+
root,
|
|
91
|
+
checkpoint,
|
|
92
|
+
output,
|
|
93
|
+
*,
|
|
94
|
+
worker=None,
|
|
95
|
+
split="test",
|
|
96
|
+
limit=None,
|
|
97
|
+
budget=64,
|
|
98
|
+
seed=193,
|
|
99
|
+
policy="autonomous",
|
|
100
|
+
capacity=8,
|
|
101
|
+
):
|
|
102
|
+
"""Evaluate the split and save raw trajectories usable by the offline visualizer."""
|
|
103
|
+
if limit is not None and limit < 1:
|
|
104
|
+
raise ValueError("limit must be positive")
|
|
105
|
+
program = check_program(root)
|
|
106
|
+
model = (
|
|
107
|
+
checkpoint
|
|
108
|
+
if isinstance(checkpoint, torch.nn.Module)
|
|
109
|
+
else load_model(checkpoint, program)
|
|
110
|
+
)
|
|
111
|
+
worker = resolve_worker(worker)
|
|
112
|
+
output = Path(output)
|
|
113
|
+
output.mkdir(parents=True, exist_ok=False)
|
|
114
|
+
totals = Counter()
|
|
115
|
+
levels = defaultdict(Counter)
|
|
116
|
+
with (
|
|
117
|
+
receiver(worker, program) as (run, frames),
|
|
118
|
+
gzip.open(output / "comparisons.jsonl.gz", "wt") as dest,
|
|
119
|
+
):
|
|
120
|
+
for world in islice(worlds(root, split), limit):
|
|
121
|
+
if "initial" not in world or "final" not in world:
|
|
122
|
+
raise ValueError(
|
|
123
|
+
"This historical split contains training tensors only. Use a held-out split with native snapshots."
|
|
124
|
+
)
|
|
125
|
+
result = _execute(
|
|
126
|
+
model,
|
|
127
|
+
world["initial"],
|
|
128
|
+
run,
|
|
129
|
+
frames,
|
|
130
|
+
budget,
|
|
131
|
+
seed + int(world["uid"][:8], 16),
|
|
132
|
+
policy,
|
|
133
|
+
capacity,
|
|
134
|
+
)
|
|
135
|
+
c = _counts(world, result)
|
|
136
|
+
totals.update(c)
|
|
137
|
+
levels[
|
|
138
|
+
str(world["depth"]) if world["depth"] is not None else "Unknown"
|
|
139
|
+
].update(c)
|
|
140
|
+
original = {
|
|
141
|
+
k: world[k]
|
|
142
|
+
for k in (
|
|
143
|
+
"uid",
|
|
144
|
+
"depth",
|
|
145
|
+
"entry",
|
|
146
|
+
"initial",
|
|
147
|
+
"final",
|
|
148
|
+
"teacher_requests",
|
|
149
|
+
)
|
|
150
|
+
if k in world
|
|
151
|
+
}
|
|
152
|
+
print(
|
|
153
|
+
json.dumps(
|
|
154
|
+
{"world": original, "completion": result, "metrics": stats(c)},
|
|
155
|
+
separators=(",", ":"),
|
|
156
|
+
),
|
|
157
|
+
file=dest,
|
|
158
|
+
)
|
|
159
|
+
if not totals["worlds"]:
|
|
160
|
+
raise ValueError("No evaluation worlds found")
|
|
161
|
+
summary = {
|
|
162
|
+
"checkpoint": None
|
|
163
|
+
if isinstance(checkpoint, torch.nn.Module)
|
|
164
|
+
else str(checkpoint),
|
|
165
|
+
"model": type(model).__name__,
|
|
166
|
+
"seed": seed,
|
|
167
|
+
"budget": budget,
|
|
168
|
+
"policy": result["policy"],
|
|
169
|
+
"parameters": sum(p.numel() for p in model.parameters()),
|
|
170
|
+
"metrics": stats(totals),
|
|
171
|
+
"by_depth": {k: stats(c) for k, c in levels.items()},
|
|
172
|
+
}
|
|
173
|
+
(output / "metrics.json").write_text(json.dumps(summary, indent=2))
|
|
174
|
+
return summary
|
eggfuse/ripsat/graphs.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import zlib
|
|
3
|
+
from collections import Counter
|
|
4
|
+
|
|
5
|
+
import igraph
|
|
6
|
+
|
|
7
|
+
OPS = [
|
|
8
|
+
"Add",
|
|
9
|
+
"Mul",
|
|
10
|
+
"Sub",
|
|
11
|
+
"Div",
|
|
12
|
+
"Pow",
|
|
13
|
+
"Integral",
|
|
14
|
+
"Diff",
|
|
15
|
+
"Cos",
|
|
16
|
+
"Sin",
|
|
17
|
+
"Sqrt",
|
|
18
|
+
"Ln",
|
|
19
|
+
"Const",
|
|
20
|
+
"Var",
|
|
21
|
+
"RipenInput",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def native_rows(graph):
|
|
26
|
+
nodes = graph["nodes"]
|
|
27
|
+
rows = []
|
|
28
|
+
for v in nodes.values():
|
|
29
|
+
op = v["op"]
|
|
30
|
+
if op not in OPS or v.get("subsumed"):
|
|
31
|
+
continue
|
|
32
|
+
args = [nodes[k] for k in v["children"]]
|
|
33
|
+
args = tuple(
|
|
34
|
+
json.loads(x["op"]) if op in ("Var", "Const", "RipenInput") else x["eclass"]
|
|
35
|
+
for x in args
|
|
36
|
+
)
|
|
37
|
+
rows.append((op, args, v["eclass"]))
|
|
38
|
+
return rows
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def runtime_rows(rows):
|
|
42
|
+
def read(v):
|
|
43
|
+
return v["eq"] if "eq" in v else v["value"]
|
|
44
|
+
|
|
45
|
+
return [
|
|
46
|
+
(r["table"], tuple(map(read, r["values"][:-1])), read(r["values"][-1]))
|
|
47
|
+
for r in rows
|
|
48
|
+
if not r["subsumed"]
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def canonical(rows, *, pin_boundaries=False):
|
|
53
|
+
# BLISS individualization/refinement. Serialize the actual canonical labelled
|
|
54
|
+
# graph: hashes alone and a WL histogram cannot establish isomorphism.
|
|
55
|
+
labels, edges, classes = [], [], {}
|
|
56
|
+
|
|
57
|
+
def vertex(label):
|
|
58
|
+
labels.append(label)
|
|
59
|
+
return len(labels) - 1
|
|
60
|
+
|
|
61
|
+
def cls(c):
|
|
62
|
+
if c not in classes:
|
|
63
|
+
classes[c] = vertex("Math")
|
|
64
|
+
return classes[c]
|
|
65
|
+
|
|
66
|
+
bounds = {}
|
|
67
|
+
for op, args, result in rows:
|
|
68
|
+
en = vertex("op/" + op)
|
|
69
|
+
edges.append((en, cls(result)))
|
|
70
|
+
for j, v in enumerate(args):
|
|
71
|
+
port = vertex("arg/" + str(j))
|
|
72
|
+
if op == "RipenInput":
|
|
73
|
+
if v not in bounds:
|
|
74
|
+
bounds[v] = vertex(
|
|
75
|
+
f"boundary/i64/{v}" if pin_boundaries else "boundary/i64"
|
|
76
|
+
)
|
|
77
|
+
child = bounds[v]
|
|
78
|
+
elif op in ("Const", "Var"):
|
|
79
|
+
child = vertex("literal/" + json.dumps(v))
|
|
80
|
+
else:
|
|
81
|
+
child = cls(v)
|
|
82
|
+
edges.extend(((en, port), (port, child)))
|
|
83
|
+
colors = {v: i for i, v in enumerate(sorted(set(labels)))}
|
|
84
|
+
g = igraph.Graph(n=len(labels), edges=edges, directed=True)
|
|
85
|
+
g.vs["color"] = [colors[x] for x in labels]
|
|
86
|
+
perm = g.canonical_permutation(color=g.vs["color"])
|
|
87
|
+
cg = g.permute_vertices(perm)
|
|
88
|
+
key = sorted(colors), cg.vs["color"], sorted(cg.get_edgelist())
|
|
89
|
+
return zlib.compress(json.dumps(key, separators=(",", ":")).encode(), 1)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def depth(result):
|
|
93
|
+
# With changing class identity, the simple named-parent chain can omit an
|
|
94
|
+
# equality/enabling dependency. Do not silently give such cases depth one.
|
|
95
|
+
gains = dict(result["credit"]["origins"])
|
|
96
|
+
if not any(gains.values()):
|
|
97
|
+
return 0
|
|
98
|
+
if result["credit"]["signed_external"][2] or any(
|
|
99
|
+
p["version"] != 0 and p["address"]["token"] < 0
|
|
100
|
+
for t in result["requests"]
|
|
101
|
+
for p in t["parents"]
|
|
102
|
+
):
|
|
103
|
+
return None
|
|
104
|
+
if any(r["forwarded"] for f in result["frames"] for _, r in f["updates"]):
|
|
105
|
+
return None
|
|
106
|
+
chains, produced = {}, {}
|
|
107
|
+
for f in result["frames"]:
|
|
108
|
+
for a, row in f["updates"]:
|
|
109
|
+
k = (a["token"], a["op"])
|
|
110
|
+
if k in produced and produced[k] != row["version"]:
|
|
111
|
+
return None
|
|
112
|
+
produced[k] = row["version"]
|
|
113
|
+
for t in result["requests"]:
|
|
114
|
+
ds = []
|
|
115
|
+
for p in t["parents"]:
|
|
116
|
+
owner = p["address"]["token"]
|
|
117
|
+
if owner >= 0 and owner not in chains:
|
|
118
|
+
return None
|
|
119
|
+
ds.append(chains.get(owner, 0))
|
|
120
|
+
chains[t["token"]] = 1 + max(ds, default=0)
|
|
121
|
+
return max(chains[k] for k, v in gains.items() if v)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def matched_rows(rows, reference):
|
|
125
|
+
"""Map the generated ground e-classes into the reference quotient via constructors."""
|
|
126
|
+
index = {(op, args): cls for op, args, cls in reference}
|
|
127
|
+
mapping = {}
|
|
128
|
+
ready = set()
|
|
129
|
+
pending = list(rows)
|
|
130
|
+
while pending:
|
|
131
|
+
later = []
|
|
132
|
+
for op, args, cls in pending:
|
|
133
|
+
if op in ("RipenInput", "Const", "Var"):
|
|
134
|
+
key = (op, args)
|
|
135
|
+
elif all(c in mapping for c in args):
|
|
136
|
+
key = (op, tuple(mapping[c] for c in args))
|
|
137
|
+
else:
|
|
138
|
+
later.append((op, args, cls))
|
|
139
|
+
continue
|
|
140
|
+
if key not in index:
|
|
141
|
+
raise ValueError("native proposal outside reference closure")
|
|
142
|
+
dest = index[key]
|
|
143
|
+
if mapping.setdefault(cls, dest) != dest:
|
|
144
|
+
raise ValueError("inconsistent generated equality")
|
|
145
|
+
ready.add((key, dest))
|
|
146
|
+
if len(later) == len(pending):
|
|
147
|
+
raise ValueError("unsupported ungrounded class")
|
|
148
|
+
pending = later
|
|
149
|
+
return ready
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def stats(c):
|
|
153
|
+
def div(k, n):
|
|
154
|
+
return c[k] / c[n] if c[n] else None
|
|
155
|
+
|
|
156
|
+
return dict(
|
|
157
|
+
saturation=div("exact", "worlds"),
|
|
158
|
+
coverage=div("new_rows", "ref_new"),
|
|
159
|
+
early_stop=div("early", "worlds"),
|
|
160
|
+
early_among_end=div("early", "model_end"),
|
|
161
|
+
explicit_true_end=div("right_end", "worlds"),
|
|
162
|
+
post_sat_per_world=div("post_sat_paid", "worlds"),
|
|
163
|
+
repeat_rate=div("repeats", "raw"),
|
|
164
|
+
EPT=div("ops", "paid"),
|
|
165
|
+
EPS=div("ops", "seconds"),
|
|
166
|
+
avg_paid=div("paid", "worlds"),
|
|
167
|
+
**c,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def trajectory_counts(q, success, new_rows, ref_new, is_saturated):
|
|
172
|
+
c = Counter(
|
|
173
|
+
worlds=1,
|
|
174
|
+
exact=success,
|
|
175
|
+
new_rows=new_rows,
|
|
176
|
+
ref_new=ref_new,
|
|
177
|
+
model_end=0,
|
|
178
|
+
source_schedule=0,
|
|
179
|
+
paid_cap=0,
|
|
180
|
+
productive=0,
|
|
181
|
+
productive_later=0,
|
|
182
|
+
productive_new_ref=0,
|
|
183
|
+
)
|
|
184
|
+
c[q["reason"]] += 1
|
|
185
|
+
gains = dict(q["credit"]["origins"])
|
|
186
|
+
c.update(
|
|
187
|
+
paid=len(q["tape"]),
|
|
188
|
+
ops=sum(gains.values()),
|
|
189
|
+
seconds=q["seconds"],
|
|
190
|
+
early=q["reason"] == "model_end" and not success,
|
|
191
|
+
right_end=q["reason"] == "model_end" and success,
|
|
192
|
+
source_incomplete=q["reason"] == "source_schedule" and not success,
|
|
193
|
+
cap_incomplete=q["reason"] == "paid_cap" and not success,
|
|
194
|
+
met_budget=len(q["tape"]) == q["budget"],
|
|
195
|
+
)
|
|
196
|
+
for t in q["tape"]:
|
|
197
|
+
c["productive"] += gains.get(t["token"], 0) > 0
|
|
198
|
+
c["productive_later"] += t["run"] > 1 and gains.get(t["token"], 0) > 0
|
|
199
|
+
newref = any(
|
|
200
|
+
p["address"]["token"] > 0 or p["version"] > 0 for p in t["parents"]
|
|
201
|
+
)
|
|
202
|
+
c["productive_new_ref"] += newref and gains.get(t["token"], 0) > 0
|
|
203
|
+
for w in q["windows"]:
|
|
204
|
+
sat = is_saturated(w["before"])
|
|
205
|
+
c["pre_sat_windows"] += not sat
|
|
206
|
+
c["sat_windows"] += sat
|
|
207
|
+
c["post_sat_paid"] += sat * w["paid"]
|
|
208
|
+
c["raw"] += len(w["raw"])
|
|
209
|
+
c["repeats"] += len(w["raw"]) - len(set(map(tuple, w["raw"])))
|
|
210
|
+
return c
|
eggfuse/ripsat/model.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Transformer, complete-Cell dynamic pointer and draft-conditioned readout."""
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from torch import nn
|
|
5
|
+
from torch.nn import functional as F
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Pointer(nn.Module):
|
|
9
|
+
def __init__(self, tables, rules, *, width=32, layers=1, heads=4):
|
|
10
|
+
super().__init__()
|
|
11
|
+
field_width = width // 4
|
|
12
|
+
self.table = nn.Embedding(tables + 1, width, padding_idx=0)
|
|
13
|
+
self.field = nn.Embedding(512, field_width, padding_idx=0)
|
|
14
|
+
self.embed = nn.Linear(width + 3 * field_width, width)
|
|
15
|
+
|
|
16
|
+
def block():
|
|
17
|
+
return nn.TransformerEncoderLayer(
|
|
18
|
+
width, heads, 2 * width, dropout=0, batch_first=True
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
self.encoder = block()
|
|
22
|
+
if layers > 1:
|
|
23
|
+
self.encoder = nn.TransformerEncoder(
|
|
24
|
+
self.encoder, layers, enable_nested_tensor=False
|
|
25
|
+
)
|
|
26
|
+
for i in range(1, layers):
|
|
27
|
+
self.encoder.layers[i] = block()
|
|
28
|
+
self.choose = nn.Linear(width, rules)
|
|
29
|
+
self.role = nn.Embedding(rules, width)
|
|
30
|
+
self.first = nn.Linear(width, width)
|
|
31
|
+
self.next = nn.Linear(2 * width, width)
|
|
32
|
+
self.key = nn.Linear(width, width)
|
|
33
|
+
|
|
34
|
+
def memory(self, x, depth=1):
|
|
35
|
+
valid = x[:, :, 0] != 0
|
|
36
|
+
h = self.embed(
|
|
37
|
+
torch.cat((self.table(x[:, :, 0]), self.field(x[:, :, 1:]).flatten(2)), 2)
|
|
38
|
+
)
|
|
39
|
+
for _ in range(depth):
|
|
40
|
+
h = self.encoder(h, src_key_padding_mask=~valid)
|
|
41
|
+
pool = (h * valid[:, :, None]).sum(1) / valid.sum(1, keepdim=True)
|
|
42
|
+
return h, self.key(h), valid, pool, self.choose(pool)
|
|
43
|
+
|
|
44
|
+
def pointer(self, context, keys, valid):
|
|
45
|
+
return (
|
|
46
|
+
(keys * context[:, None])
|
|
47
|
+
.sum(-1)
|
|
48
|
+
.div(context.size(-1) ** 0.5)
|
|
49
|
+
.masked_fill(~valid, -torch.inf)
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
def loss(self, batch, depth=1):
|
|
53
|
+
rows, labels = zip(*batch)
|
|
54
|
+
x = tensor_rows(rows)
|
|
55
|
+
h, k, m, p, logits = self.memory(x, depth)
|
|
56
|
+
labels = torch.tensor([(i, *l) for i, ls in enumerate(labels) for l in ls])
|
|
57
|
+
i, r, a, b = labels.T
|
|
58
|
+
q = self.first(p[i] + self.role(r)).tanh()
|
|
59
|
+
value = F.cross_entropy(logits[i], r, reduction="sum")
|
|
60
|
+
value = value + F.cross_entropy(self.pointer(q, k[i], m[i]), a, reduction="sum")
|
|
61
|
+
active = b >= 0
|
|
62
|
+
q2 = self.next(torch.cat((q[active], h[i[active], a[active]]), 1)).tanh()
|
|
63
|
+
value = value + F.cross_entropy(
|
|
64
|
+
self.pointer(q2, k[i[active]], m[i[active]]), b[active], reduction="sum"
|
|
65
|
+
)
|
|
66
|
+
return value / len(i), len(i)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def tensor_rows(rows):
|
|
70
|
+
n = max(map(len, rows))
|
|
71
|
+
return torch.tensor([r + [[0] * 4] * (n - len(r)) for r in rows])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class SubsetPointer(Pointer):
|
|
75
|
+
def read_draft(self, memory, histories):
|
|
76
|
+
"""Write a full generated token's neural representation to its own parent slots.
|
|
77
|
+
|
|
78
|
+
The caller supplies ordered references from the actual draft, never a list
|
|
79
|
+
of valid partners. Nothing is removed from either pointer distribution.
|
|
80
|
+
"""
|
|
81
|
+
entries = [(i, *t) for i, history in enumerate(histories) for t in history]
|
|
82
|
+
if not entries:
|
|
83
|
+
return memory
|
|
84
|
+
return self._read_entries(
|
|
85
|
+
memory, torch.tensor(entries, device=memory[0].device)
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def _read_entries(self, memory, entries):
|
|
89
|
+
h, _, valid, _, _ = memory
|
|
90
|
+
i, rule, a, b = entries.T
|
|
91
|
+
second = b >= 0
|
|
92
|
+
first_repr = self.first(self.role(rule) + h[i, a]).tanh()
|
|
93
|
+
other = h[i, b.clamp_min(0)] * second[:, None]
|
|
94
|
+
token = self.next(torch.cat((first_repr, other), -1)).tanh()
|
|
95
|
+
n = h.size(1)
|
|
96
|
+
delta = torch.zeros_like(h).flatten(0, 1)
|
|
97
|
+
delta = delta.index_add(0, i * n + a, token)
|
|
98
|
+
delta = delta.index_add(0, i[second] * n + b[second], token[second])
|
|
99
|
+
present = torch.zeros_like(valid[:, 0]).index_fill(0, i, True)
|
|
100
|
+
revised = self.encoder(h + delta.view_as(h), src_key_padding_mask=~valid)
|
|
101
|
+
h = torch.where(present[:, None, None], revised, h)
|
|
102
|
+
pool = (h * valid[:, :, None]).sum(1) / valid.sum(1, keepdim=True)
|
|
103
|
+
return h, self.key(h), valid, pool, self.choose(pool)
|
|
104
|
+
|
|
105
|
+
def log_joint(self, memory, entries):
|
|
106
|
+
h, k, valid, p, logits = memory
|
|
107
|
+
i, r, a, b = entries.T
|
|
108
|
+
q = self.first(p[i] + self.role(r)).tanh()
|
|
109
|
+
result = (
|
|
110
|
+
logits.log_softmax(-1)[i, r]
|
|
111
|
+
+ self.pointer(q, k[i], valid[i])
|
|
112
|
+
.log_softmax(-1)
|
|
113
|
+
.gather(1, a[:, None])
|
|
114
|
+
.flatten()
|
|
115
|
+
)
|
|
116
|
+
two = b >= 0
|
|
117
|
+
q2 = self.next(torch.cat((q[two], h[i[two], a[two]]), -1)).tanh()
|
|
118
|
+
lp = (
|
|
119
|
+
self.pointer(q2, k[i[two]], valid[i[two]])
|
|
120
|
+
.log_softmax(-1)
|
|
121
|
+
.gather(1, b[two, None])
|
|
122
|
+
.flatten()
|
|
123
|
+
)
|
|
124
|
+
return result.index_add(0, torch.where(two)[0], lp)
|
|
125
|
+
|
|
126
|
+
def objective(self, rows, histories, remaining, strength=0.0):
|
|
127
|
+
if not all(remaining):
|
|
128
|
+
raise ValueError("no positive completion target; no END inferred")
|
|
129
|
+
mem = self.read_draft(self.memory(tensor_rows(rows)), histories)
|
|
130
|
+
|
|
131
|
+
def mean_per_state(groups, repeat=False):
|
|
132
|
+
entries = torch.tensor([(i, *t) for i, g in enumerate(groups) for t in g])
|
|
133
|
+
if not entries.numel():
|
|
134
|
+
return mem[-1].new_zeros(())
|
|
135
|
+
lp = self.log_joint(mem, entries)
|
|
136
|
+
loss = (
|
|
137
|
+
-torch.log(-torch.expm1(lp.clamp(max=-torch.finfo(lp.dtype).eps)))
|
|
138
|
+
if repeat
|
|
139
|
+
else -lp
|
|
140
|
+
)
|
|
141
|
+
counts = torch.tensor([len(g) for g in groups])
|
|
142
|
+
return (loss / counts[entries[:, 0]]).sum() / len(groups)
|
|
143
|
+
|
|
144
|
+
ce = mean_per_state(remaining)
|
|
145
|
+
ul = mean_per_state(histories, True) if strength else ce.new_zeros(())
|
|
146
|
+
return ce + strength * ul, ce
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class CalculusPointer(SubsetPointer):
|
|
150
|
+
def __init__(self, tables, rules, use_end, **dimensions):
|
|
151
|
+
super().__init__(tables, rules, **dimensions)
|
|
152
|
+
self.use_end = use_end
|
|
153
|
+
if use_end:
|
|
154
|
+
self.choose = nn.Linear(self.choose.in_features, rules + 1)
|
|
155
|
+
|
|
156
|
+
def forward(
|
|
157
|
+
self, rows, histories=None, *, draft=None, targets=None, end_states=None
|
|
158
|
+
):
|
|
159
|
+
"""Return encoded memory, or one teacher-forced joint log P per Cell then END."""
|
|
160
|
+
memory = self.memory(rows)
|
|
161
|
+
if histories is not None:
|
|
162
|
+
if draft is not None or targets is not None:
|
|
163
|
+
raise ValueError(
|
|
164
|
+
"Use histories for a memory read or draft for teacher forcing"
|
|
165
|
+
)
|
|
166
|
+
return self.read_draft(memory, histories)
|
|
167
|
+
if targets is None and draft is None and end_states is None:
|
|
168
|
+
return memory
|
|
169
|
+
if targets is None or draft is None or end_states is None:
|
|
170
|
+
raise ValueError("Teacher forcing requires draft, targets and end_states")
|
|
171
|
+
if any(t.numel() and t.shape[1] != 4 for t in (draft, targets)):
|
|
172
|
+
raise ValueError(
|
|
173
|
+
"The calculus preset expects rule and two parent references"
|
|
174
|
+
)
|
|
175
|
+
h, k, valid, p, logits = memory
|
|
176
|
+
if len(draft):
|
|
177
|
+
# Re-encode only states with pending requests, once per state.
|
|
178
|
+
active, local = draft[:, 0].unique(sorted=True, return_inverse=True)
|
|
179
|
+
entries = torch.cat((local[:, None], draft[:, 1:]), dim=1)
|
|
180
|
+
sub = tuple(v[active] for v in memory)
|
|
181
|
+
rh, rk, _, rp, rl = self._read_entries(sub, entries)
|
|
182
|
+
if self.use_end:
|
|
183
|
+
rl = torch.cat((rl[:, :-1], torch.full_like(rl[:, -1:], -torch.inf)), 1)
|
|
184
|
+
h, k, p, logits = (
|
|
185
|
+
v.index_copy(0, active, z)
|
|
186
|
+
for v, z in zip((h, k, p, logits), (rh, rk, rp, rl))
|
|
187
|
+
)
|
|
188
|
+
parts = []
|
|
189
|
+
if len(targets):
|
|
190
|
+
parts.append(self.log_joint((h, k, valid, p, logits), targets))
|
|
191
|
+
if len(end_states):
|
|
192
|
+
if not self.use_end:
|
|
193
|
+
raise ValueError("END targets require the END output")
|
|
194
|
+
parts.append(logits[end_states].log_softmax(-1)[:, -1])
|
|
195
|
+
return torch.cat(parts)
|
|
196
|
+
|
|
197
|
+
def completion_loss(self, xs, histories, labels, terminal):
|
|
198
|
+
device = self.table.weight.device
|
|
199
|
+
mem = self(tensor_rows(xs).to(device), histories)
|
|
200
|
+
logits = mem[-1]
|
|
201
|
+
if self.use_end:
|
|
202
|
+
# A pending draft must be submitted and published before a global END.
|
|
203
|
+
busy = torch.tensor([bool(h) for h in histories], device=device)
|
|
204
|
+
logits = torch.cat(
|
|
205
|
+
[logits[:, :-1], logits[:, -1:].masked_fill(busy[:, None], -torch.inf)],
|
|
206
|
+
1,
|
|
207
|
+
)
|
|
208
|
+
mem = (*mem[:-1], logits)
|
|
209
|
+
entries = [(i, *v) for i, y in enumerate(labels) for v in y]
|
|
210
|
+
counts = torch.tensor([len(y) for y in labels], device=device)
|
|
211
|
+
stops = torch.tensor(terminal, dtype=torch.bool, device=device)
|
|
212
|
+
if any(flag and h for flag, h in zip(terminal, histories, strict=True)):
|
|
213
|
+
raise ValueError("cannot end a view with pending requests")
|
|
214
|
+
if not torch.equal(stops, counts == 0) or (stops.any() and not self.use_end):
|
|
215
|
+
raise ValueError("unknown or unsupported label")
|
|
216
|
+
loss = logits.new_zeros(())
|
|
217
|
+
if entries:
|
|
218
|
+
ix = torch.tensor(entries, device=device)
|
|
219
|
+
loss = -(self.log_joint(mem, ix) / counts[ix[:, 0]]).sum()
|
|
220
|
+
if stops.any():
|
|
221
|
+
loss = loss - logits[stops].log_softmax(-1)[:, -1].sum()
|
|
222
|
+
return loss / len(xs)
|