File size: 14,458 Bytes
04e89f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/env python3
"""turn_kernel - the head READS a conversation turn (PLAN_CONVERSATION_115 S1, constitution art. 1/7).



Language is a composition over a space of rules (Ben 11-05). The released kernel (K7b/K8) reads store sentences; it reads

6-13% of conversation turns (measure_turns_k8). The rest is residue, and residue grows constructions: this module runs the

M14 autonomous induction (wander-train/stage5m14_autonomous_induction_v1.py: g* = argmin L(g) + L(R | G+g), multi-donor >= 3,

held-out transfer >= 1, no human proposer) over the DIALOGUE corpus instead of store sentences, in passes, and installs the

admitted skeletons as rules the kernel tries after K8. A rule is a form with typed slots (NAME / NUM / WORD); realisation

refills the skeleton, so the second reading Parse(Realize(P)) = P holds by construction. Nothing about the data is written

by hand: case is learned from the corpus (a capitalised word is a NAME only where the corpus writes it lower-case less often).



  induce  <dd_full.json> <out dir> [passes]     -> conv_rules.json (ledger schema), scene_programs.json (every train turn as

                                                  programs: the scene index S3 reads), report

  measure <conv dir> <out dir>                  -> parse rates of K8 alone vs K8 + induced rules on Ben's turns, the general

                                                  openers and the validation scene turns

usage: PYTHONPATH=<wander-train>:<k8 dir> turn_kernel.py induce|measure ..."""
import collections
import json
import math
import os
import re
import sys
import time

TOK = re.compile(r"[A-Za-z][\w'-]*|\d+|[.?!]")
CLAUSE = re.compile(r"(?<=[.?!])\s+")
MAX_LEN, MIN_LEN, WINDOW = 14, 2, 80


def clean(u):
    return re.sub(r"\s+", " ", re.sub(r"\s+([.,?!'])", r"\1", u.strip()))


def clauses(text):
    return [c for c in CLAUSE.split(clean(text)) if TOK.findall(c)]


class Case:
    """learned from the corpus: a capitalised token is a NAME unless the corpus writes it lower-case at least as often

    (counted off non-initial positions: a clause-initial capital carries no case information), and only if it is rare

    (said in fewer than one clause in a hundred: a word said in every conversation is a form word, not a name)"""

    def __init__(self, texts=None, table=None):
        self.lower, self.upper, self.freq = collections.Counter(), collections.Counter(), collections.Counter()
        self.n_clauses = 0
        if table:
            self.lower.update(table["lower"])
            self.upper.update(table["upper"])
            self.freq.update(table["freq"])
            self.n_clauses = table["n_clauses"]
        for t in texts or []:
            for c in clauses(t):
                self.n_clauses += 1
                for i, w in enumerate(TOK.findall(c)):
                    if w[:1].isalpha():
                        self.freq[w.lower()] += 1
                        if i > 0:
                            (self.upper if w[0].isupper() else self.lower)[w.lower()] += 1

    def slot_type(self, tok):
        if tok.isdigit():
            return "NUM"
        lw = tok.lower()
        if tok[0].isupper() and self.lower[lw] < self.upper[lw] and self.freq[lw] < 0.01 * max(1, self.n_clauses):
            return "NAME"
        return "WORD"

    def dump(self):
        return {"lower": dict(self.lower), "upper": dict(self.upper), "freq": dict(self.freq), "n_clauses": self.n_clauses}


def toks(text):
    return TOK.findall(text)


def lgg(a, b, case):
    if len(a) != len(b):
        return None
    out, slots = [], 0
    for x, y in zip(a, b):
        if x.lower() == y.lower():
            out.append(x.lower())
        else:
            tx, ty = case.slot_type(x), case.slot_type(y)
            if tx != ty or x in ".?!" or y in ".?!":
                return None
            out.append("<" + tx + ">")
            slots += 1
    if slots == 0 or slots > len(a) // 2:
        return None
    return out


def matches(skel, ts, case):
    if len(skel) != len(ts):
        return None
    slots = {}
    for i, (s, t) in enumerate(zip(skel, ts)):
        if s.startswith("<"):
            if case.slot_type(t) != s[1:-1]:
                return None
            slots[i] = t
        elif s != t.lower():
            return None
    return slots


class Induced:
    def __init__(self, rules, case):
        self.rules = rules
        self.case = case
        self.by_len = collections.defaultdict(list)
        for r in rules:
            self.by_len[len(r["skeleton_tokens"])].append(r)
        for k in self.by_len:                                   # most specific first: fewest slots, then most literal mass
            self.by_len[k].sort(key=lambda r: (sum(1 for s in r["skeleton_tokens"] if s.startswith("<")), r["delta_bits"]))

    def read(self, text):
        ts = toks(text)
        for r in self.by_len.get(len(ts), ()):
            sl = matches(r["skeleton_tokens"], ts, self.case)
            if sl is not None:
                return {"rule": r["rule_id"], "slots": sl, "skeleton": r["skeleton_tokens"]}
        return None

    @staticmethod
    def realize(prog):
        out = [prog["slots"].get(i, s) for i, s in enumerate(prog["skeleton"])]
        s = " ".join(out)
        s = re.sub(r"\s+([.?!,])", r"\1", s)
        return s[:1].upper() + s[1:]


class TurnKernel:
    """K8 first (store sentences, named subjects), then the induced conversational rules; per clause."""

    def __init__(self, k8, conv_dir):
        self.k8 = k8
        d = json.load(open(os.path.join(conv_dir, "conv_rules.json")))
        self.case = Case(table=d["case"])
        self.ind = Induced(d["rules"], self.case)
        self.real = None

    def compile(self, text):
        out = []
        for c in clauses(text):
            p = None
            try:
                k = self.k8.compile_text(c)
            except Exception:  # noqa: BLE001
                k = None
            if k is not None:
                p = {"kind": "k8", "program": k, "text": c}
            else:
                r = self.ind.read(c)
                if r:
                    p = dict(kind="rule", text=c, **r)
            out.append(p)
        return out

    def read_all(self, text):
        ps = self.compile(text)
        return ps if ps and all(ps) else None

    def realize(self, prog, realizer=None):
        if prog["kind"] == "rule":
            return Induced.realize(prog)
        return realizer.realize2(prog["program"]) if realizer else prog["text"]

    def same(self, prog, text):
        """the second reading: the reply read back is the program it was said from"""
        ps = self.compile(text)
        if len(ps) != 1 or not ps[0] or ps[0]["kind"] != prog["kind"]:
            return False
        if prog["kind"] == "rule":
            return ps[0]["rule"] == prog["rule"] and ps[0]["slots"] == prog["slots"]
        return ps[0]["program"] == prog["program"]


def induce(dd_path, out, passes=3, k8=None):
    t0 = time.time()
    dd = json.load(open(dd_path))
    turns = [clean(u) for dl in dd["train"] for u in dl["utterances"]]
    case = Case(turns)
    units = []                                                  # (clause text, tokens)
    for t in turns:
        for c in clauses(t):
            ts = toks(c)
            if MIN_LEN <= len(ts) <= MAX_LEN:
                units.append((c, ts))
    vocab = {w.lower() for _, ts in units for w in ts}
    LOG_V, LOG_T = math.log2(max(2, len(vocab))), math.log2(3)
    residue = []
    for c, ts in units:
        ok = False
        if k8 is not None:
            try:
                ok = k8.compile_text(c) is not None
            except Exception:  # noqa: BLE001
                ok = False
        if not ok:
            residue.append((c, ts))
    print("units", len(units), "residue after K8", len(residue), "vocab", len(vocab), flush=True)
    rules, rid = [], 0
    for ps in range(passes):
        cands = {}

        def propose(skel, donor):
            if not any(s.startswith("<") for s in skel):
                return
            e = cands.setdefault(" ".join(skel), {"skeleton": skel, "donors": set()})
            e["donors"].add(donor)
        for c, ts in residue:
            propose([("<" + case.slot_type(t) + ">") if case.slot_type(t) != "WORD" else t.lower() for t in ts], c)
        buckets = collections.defaultdict(list)
        for c, ts in residue:
            buckets[len(ts)].append((c, ts))
        for n, members in buckets.items():
            members.sort(key=lambda m: [w.lower() for w in m[1]])          # neighbours share prefixes: the window finds them
            for i in range(len(members)):
                for j in range(i + 1, min(i + WINDOW, len(members))):
                    sk = lgg(members[i][1], members[j][1], case)
                    if sk is not None:
                        propose(sk, members[i][0])
                        propose(sk, members[j][0])
        half = len(residue) // 2
        induct, held = residue[:half], residue[half:]
        by_len = collections.defaultdict(list)
        for c, ts in residue:
            by_len[len(ts)].append((c, ts))
        scored = []
        for key, cand in cands.items():
            sk = cand["skeleton"]
            if len(cand["donors"]) < 3:
                continue
            hits = [c for c, ts in by_len[len(sk)] if matches(sk, ts, case) is not None]
            if len(hits) < 3:
                continue
            hset = set(hits)
            ind = sum(1 for c, _ in induct if c in hset)
            tr = sum(1 for c, _ in held if c in hset)
            if ind < 3 or tr < 1:
                continue
            slots = sum(1 for s in sk if s.startswith("<"))
            saved = sum(len(sk) * LOG_V - slots * LOG_V for _ in hits)
            cost = (len(sk) - slots) * LOG_V + slots * LOG_T
            delta = cost - saved
            if delta < 0:
                scored.append({"skeleton_tokens": sk, "skeleton": key, "delta_bits": round(delta, 1), "induct_donors": ind,
                               "heldout_transfer": tr, "donor_examples": hits[:3]})
        scored.sort(key=lambda r: r["delta_bits"])
        # admit greedily; a later rule must still compress the residue the earlier ones left
        covered = set()
        admitted = []
        for r in scored:
            sk = r["skeleton_tokens"]
            hits = [c for c, ts in by_len[len(sk)] if c not in covered and matches(sk, ts, case) is not None]
            if len(hits) < 3:
                continue
            r["rule_id"] = "conv_r%04d" % rid
            r["pass"] = ps + 1
            r["provenance"] = "autonomous induction over DailyDialog train (M14 objective; no human proposer)"
            rid += 1
            admitted.append(r)
            covered.update(hits)
        rules += admitted
        residue = [(c, ts) for c, ts in residue if c not in covered]
        print("pass", ps + 1, "candidates", len(cands), "admitted", len(admitted), "residue left", len(residue),
              round(time.time() - t0), "s", flush=True)
        if not admitted:
            break
    os.makedirs(out, exist_ok=True)
    json.dump({"schema_version": "oracle-stage5m14-induced-rules-v1", "corpus": "DailyDialog train (clauses)", "rules": rules,
               "case": case.dump(), "units": len(units), "residue_left": len(residue)},
              open(os.path.join(out, "conv_rules.json"), "w"), ensure_ascii=False)
    # the scene index: every train turn as programs (the obligations S3 binds)
    ind = Induced(rules, case)
    scenes = []
    read = tot = 0
    for di, dl in enumerate(dd["train"]):
        d_ = []
        for u in dl["utterances"]:
            ps_ = []
            for c in clauses(clean(u)):
                r = ind.read(c)
                tot += 1
                read += bool(r)
                ps_.append({"rule": r["rule"], "slots": {str(k): v for k, v in r["slots"].items()}} if r else None)
            d_.append(ps_)
        scenes.append(d_)
    json.dump(scenes, open(os.path.join(out, "scene_programs.json"), "w"), ensure_ascii=False)
    print("rules", len(rules), "train clauses read by rules %d/%d = %.1f%%" % (read, tot, 100 * read / max(1, tot)))
    for r in rules[:12]:
        print("  %8.1f  %s   e.g. %s" % (r["delta_bits"], r["skeleton"], r["donor_examples"][0][:60]))


def measure(conv, out, k8):
    TK = TurnKernel(k8, out)
    sets = {}
    cs = json.load(open(os.path.join(conv, "conv_set_v1b.json")))
    sets["ben"] = [x["turn"] for x in cs if x["source"].startswith("ben")]
    sets["general"] = [p["text"] for p in json.load(open(os.path.join(conv, "conv_instrument_v1.json")))["dev"]]
    sets["scene"] = [x["turn"] for x in json.load(open(os.path.join(conv, "loop", "scene_v1.gen.json")))]
    rep = {}
    for name, texts in sets.items():
        c = collections.Counter()
        ex = []
        for t in texts:
            ps = TK.compile(t)
            c["n"] += 1
            c["clauses"] += len(ps)
            c["clauses_k8"] += sum(1 for p in ps if p and p["kind"] == "k8")
            c["clauses_rule"] += sum(1 for p in ps if p and p["kind"] == "rule")
            if ps and all(ps):
                c["turn_read"] += 1
                if all(p["kind"] == "rule" and TK.same(p, TK.realize(p)) for p in ps):
                    c["second_reading"] += 1
                if len(ex) < 8:
                    ex.append((t[:70], [(p["kind"], p.get("rule"), p.get("slots")) for p in ps]))
            elif ps and any(ps):
                c["turn_part"] += 1
        c["read_rate"] = round(c["turn_read"] / max(1, c["n"]), 4)
        rep[name] = dict(c)
        print(name, dict(c), flush=True)
        for e in ex[:5]:
            print("    ", e)
    json.dump(rep, open(os.path.join(out, "turns_read.json"), "w"), indent=1)


if __name__ == "__main__":
    a = sys.argv[1:]
    from stage5m13e9_kernel_k8 import ConstructionKernelK8  # noqa: E402
    K8 = ConstructionKernelK8(compositional=True)
    if a[0] == "induce":
        induce(a[1], a[2], int(a[3]) if len(a) > 3 else 3, K8)
    elif a[0] == "measure":
        measure(a[1], a[2], K8)