File size: 27,463 Bytes
2419253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
#!/usr/bin/env python3
"""12.0 Amendment 3, check L1: the ladder fed by the door, on dialogue.

The ladder's address for the next word of a reply, built from the door's own parts (no suffix guesses, no hash):
  role band   the dictionary's real part of speech for content words; a function word is its own band
  position    words since the sentence began (9D)
  context     the conversation: the concepts of the other speaker's turn and of the reply so far (the attention),
              each concept reaching the words that follow it in replies; an unseen concept reaches through its typed
              ConceptNet relations (IsA, AtLocation, UsedFor, ...) to concepts the ladder holds (meaning, not identity)
Readout per the probe: within an address the unbind reduces to the address's continuation distribution; orders are
z-interpolated (the ToL discipline). Ingest = binding counts, no gradient.
Measured on held-out DailyDialog validation replies (never ingested): next-word top1/top5 for
  ngram   word n-gram on the same ingest (the flat baseline)
  ladder  role-band routing x conversational context
  both    the two together (the deployable readout)
  mutant  the ladder with its address shuffled (context from another dialogue, role bands permuted): must fall
usage: ladder_dialog.py <tree> [n_eval=500]"""
import collections, json, math, random, re, sqlite3, sys, time
import numpy as np
T = sys.argv[1] if __name__ == "__main__" else __import__("os").path.abspath(__import__("os").path.join(__import__("os").path.dirname(__import__("os").path.abspath(__file__)), "..", ".."))
NEV = (int(sys.argv[2]) if len(sys.argv) > 2 else 500) if __name__ == "__main__" else 500
sys.path[:0] = [T + "/workbench/converse", T + "/workbench/swarm", T + "/workbench"]
import converse  # noqa: F401
from resonance import DD, clean
from turn_reader import Dict, open_dict

import threading as _threading
_tl = _threading.local()


class _PerThreadDict:
    """the dictionary store opened once per thread (sqlite connections stay in the thread that made them)"""
    def __getattr__(self, k):
        if not hasattr(_tl, "d"):
            _tl.d = Dict(open_dict())
        return getattr(_tl.d, k)


d = _PerThreadDict()
TOK = re.compile(r"[a-z']+|[.,;:!?]")
PUNC = set(".,;:!?")
FUNC = set("the a an this that these those my your his her its our their i you he she it we they him them me us who whom what "
           "which of in on at to for with by from as into over under about through and or but so because if then than while "
           "although though yet nor is are was were be been being have has had do does did will would shall should can could "
           "may might must not no yes oh well there here how why when where all some any very too just really please".split())
CN = sqlite3.connect("file:%s/root/fable-content/oracle-m-series-2026-08-15/m13e5_conceptnet_build_a_v1/"
                     "conceptnet_specialist.sqlite3?mode=ro" % T, uri=True, check_same_thread=False)  # read only: any thread
TYPED = {"IsA", "PartOf", "HasA", "UsedFor", "CapableOf", "AtLocation", "Causes", "HasSubevent", "HasPrerequisite",
         "MotivatedByGoal", "Desires", "MadeOf", "ReceivesAction", "HasProperty", "CausesDesire", "HasFirstSubevent",
         "HasLastSubevent", "MannerOf", "Entails"}
_pos, _lem, _nb = {}, {}, {}


def role(w):
    if w in PUNC or w in FUNC:
        return w
    if w not in _pos:
        p = d.pos(w)
        _pos[w] = next((x for x in ("verb", "noun", "adjective", "adj", "adverb") if x in p), "other")
    return _pos[w]


def lem(w):
    if w not in _lem:
        try:
            _lem[w] = d.lemma(w)
        except Exception:  # noqa: BLE001
            _lem[w] = w
    return _lem[w]


def concepts(toks):
    return [lem(w) for w in toks if w not in FUNC and w not in PUNC and len(w) > 2]


def neighbours(c):
    if c not in _nb:
        out = []
        for rel, a, b, wt in CN.execute("select rel,start,end,weight from edge where (start=? or end=?) and dataset in "
                                        "('/d/conceptnet/4/en','/d/wordnet/3.1','/d/verbosity','/d/opencyc','/d/wiktionary/en')",
                                        (c, c)):
            if rel in TYPED:
                o = b if a == c else a
                if " " not in o and o != c:
                    out.append((o, min(wt, 2.0)))
        _nb[c] = out
    return _nb[c]


raw = json.load(open(DD))
ORD = [3, 2, 1]
ZACC = 1.5


NTR = int(0.9 * len(raw["train"]))


def dialogues(split):
    src = raw["train"][:NTR] if split == "train" else raw["train"][NTR:] if split == "fit" else raw[split]
    for dl in src:
        yield [TOK.findall(clean(u).lower()) for u in dl["utterances"]]


# ---------------------------------------------------------------- ingest (binding counts)
t0 = time.time()
cnt = collections.Counter(w for dl in dialogues("train") for u in dl for w in u)
vocab = ["<s>"] + [w for w, _ in cnt.most_common(20000)]
wid = {w: i for i, w in enumerate(vocab)}
UNK = len(vocab)
V = UNK + 1
ngram = {o: collections.defaultdict(collections.Counter) for o in ORD}
band = {o: collections.defaultdict(collections.Counter) for o in ORD}
ngram_b = {o: collections.defaultdict(collections.Counter) for o in ORD}   # the same binding read backward
band_b = {o: collections.defaultdict(collections.Counter) for o in ORD}
ctxw = collections.defaultdict(collections.Counter)      # concept -> next word in the reply (conversational association)
cdf = collections.Counter()


def posn(toks, i):
    k = 0
    for j in range(i - 1, -1, -1):
        if toks[j] in ".!?":
            break
        k += 1
    return min(9, k)


for dl in dialogues("train"):
    for j in range(1, len(dl)):
        prev, r = dl[j - 1], ["<s>"] + dl[j]
        pc = set(concepts(prev))
        cdf.update(pc)
        ids = [wid.get(w, UNK) for w in r]
        rb = [role(w) for w in r]
        rr, rids, rrb = r[::-1], ids[::-1], rb[::-1]
        for i in range(1, len(rr)):
            if rids[i] == UNK:
                continue
            for o in ORD:
                if i - o >= 0:
                    ngram_b[o][tuple(rids[i - o:i])][rids[i]] += 1
                    band_b[o][tuple(rrb[i - o:i])][rids[i]] += 1
        seen = set(pc)
        for i in range(1, len(r)):
            nx = ids[i]
            if nx == UNK:
                if r[i] not in FUNC:
                    seen.add(lem(r[i]))
                continue
            for o in ORD:
                if i - o < 0:
                    continue
                ngram[o][tuple(ids[i - o:i])][nx] += 1
                band[o][(tuple(rb[i - o:i]), posn(r, i))][nx] += 1
            for c in seen:
                ctxw[c][nx] += 1
            if r[i] not in FUNC and r[i] not in PUNC:
                seen.add(lem(r[i]))
print("ingest %.0fs: vocab %d, ngram keys %s, band keys %s, context concepts %d" % (
    time.time() - t0, V, [len(ngram[o]) for o in ORD], [len(band[o]) for o in ORD], len(ctxw)), flush=True)
ND = sum(cdf.values()) or 1
# Ben (11-08): the distribution must account for how often a word shows up at all. A context counts a word by its LIFT over
# the word's base rate, shrunk for thin evidence: log P(w|c)/P(w) * n(c,w)/(n(c,w)+K), positive part only.
KSH, LAM = 5.0, 1.0
base = np.zeros(V)
for c_, dd_ in ctxw.items():
    for w_, n_ in dd_.items():
        base[w_] += n_
base = base / base.sum()
cnorm = {c: sum(v.values()) for c, v in ctxw.items()}


def zread(table, keyfn):
    s = np.zeros(V)
    for o in ORD:
        k = keyfn(o)
        if k is None:
            continue
        dd = table[o].get(k)
        if not dd:
            continue
        ks = np.fromiter(dd.keys(), int)
        cs = np.fromiter(dd.values(), float)
        z = (cs.max() - cs.mean()) / (cs.std() + 1e-9) if len(cs) > 1 else 3.0
        if z > ZACC:
            s[ks] += z * o * cs / cs.sum()
    return s


def context_read(cs):
    """one part of the conversation's context: each concept counts a word by its lift over the word's base rate (shrunk);
    returns (direct, through typed relations)"""
    dr, rc = np.zeros(V, np.float32), np.zeros(V, np.float32)
    for c in set(cs):
        src = [(c, 1.0, dr)] if c in ctxw else [(o, w, rc) for o, w in neighbours(c) if o in ctxw][:8]
        for k, w, tgt in src:
            dd = ctxw[k]
            ks = np.fromiter(dd.keys(), int)
            vs = np.fromiter(dd.values(), float)
            lift = np.log((vs / cnorm[k]) / (base[ks] + 1e-12)) * vs / (vs + KSH)
            tgt[ks] += w * np.clip(lift, 0, None)
    n = len(set(cs)) or 1
    return dr / n, rc / n


def norm(x):
    t = x.sum()
    return x / t if t > 0 else x


# ---------------------------------------------------------------- speaking (the fitted readout of run 4, fixed)
A_REC, L_TURN, L_REPLY, L_CONTENT = 30.0, 2.0, 2.0, 3.0
CONTENT_ROLES = {"noun", "verb", "adjective", "adj"}
idw = vocab


def content_of(turn_toks):
    """what the turn brings: words that follow this turn's concepts in replies far above their base rate (lift, shrunk), and
    words its concepts reach by typed relations; never a word of the turn itself"""
    own = set(concepts(turn_toks)) | set(turn_toks)
    dr, rc = context_read(concepts(turn_toks))
    sc = dr + 0.5 * rc
    for c in set(concepts(turn_toks)):
        for o, w in neighbours(c)[:40]:
            if o in wid:
                sc[wid[o]] += 0.3 * w
    out = []
    for k in np.argsort(-sc)[:400]:
        w = idw[k] if k < UNK else None
        if not w or sc[k] <= 0 or w in own or lem(w) in own or role(w) not in CONTENT_ROLES or len(w) < 3:
            continue
        out.append((w, float(sc[k])))
        if len(out) >= 6:
            break
    return out


def _forward(r, pd_, maxlen):
    out_lp = []
    for _ in range(maxlen):
        i = len(r)
        ids = [wid.get(w, UNK) for w in r]
        rb = [role(w) for w in r]
        ng = norm(zread(ngram, lambda o: tuple(ids[i - o:i]) if i - o >= 0 else None))
        bd = norm(zread(band, lambda o: (tuple(rb[i - o:i]), posn(r, i)) if i - o >= 0 else None))
        xd_, _ = context_read(concepts(r[1:]))
        s_ = (A_REC * ng + bd) * np.exp(L_TURN * pd_ + L_REPLY * xd_)
        s_[UNK] = 0; s_[0] = 0
        for t in ids[-6:]:
            if t < UNK and idw[t] not in PUNC:
                s_[t] *= 0.05
        if s_.sum() <= 0:
            break
        k = int(np.argmax(s_)); out_lp.append(math.log(s_[k] / s_.sum()))
        r.append(idw[k])
        if idw[k] in ".!?":
            break
    return r, out_lp


def _backward(c, pd_, maxlen=8):
    seq, lp = [c], []                                   # seq is the sentence read right to left, from the content word
    for _ in range(maxlen):
        i = len(seq)
        ids = [wid.get(w, UNK) for w in seq]
        rb = [role(w) for w in seq]
        ng = norm(zread(ngram_b, lambda o: tuple(ids[i - o:i]) if i - o >= 0 else None))
        bd = norm(zread(band_b, lambda o: tuple(rb[i - o:i]) if i - o >= 0 else None))
        s_ = (A_REC * ng + bd) * np.exp(L_TURN * pd_)
        s_[UNK] = 0
        for p in ".!?,":
            s_[wid[p]] = 0
        for t in ids:
            if 0 < t < UNK:
                s_[t] *= 0.05
        if s_.sum() <= 0:
            break
        k = int(np.argmax(s_)); lp.append(math.log(s_[k] / s_.sum()))
        if k == 0:
            return seq[::-1], lp
        seq.append(idw[k])
    return None, lp


def speak(turn_toks, maxlen=14):
    """the content is the address: for each word the turn brings, read the sentence backward to its start and forward to its
    end through the same readout; keep the reading the readout holds most surely (mean log score)"""
    cont = content_of(turn_toks)
    pd_, _ = context_read(concepts(turn_toks))
    best = None
    for c, _s in cont[:4]:
        left, lpb = _backward(c, pd_)
        if not left:
            continue
        r, lpf = _forward(["<s>"] + left, pd_, maxlen)
        if r[-1] not in ".!?":
            continue
        lp = lpb + lpf
        sc = sum(lp) / max(1, len(lp))
        if best is None or sc > best[0]:
            best = (sc, r)
    if best is None:
        r, _ = _forward(["<s>"], pd_, maxlen)
    else:
        r = best[1]
    txt = ""
    for t in r[1:]:
        txt += t if t in PUNC or t.startswith("'") else (" " + t if txt else t)
    return txt.strip(), cont


def carries(turn_toks, reply):
    """L2: the reply carries at least one content word not in the turn that the turn brings (lift-associated with the turn's
    concepts, or reached from them by a typed relation)"""
    own = set(concepts(turn_toks)) | set(turn_toks)
    dr, rc = context_read(concepts(turn_toks))
    reach = {lem(o) for c in set(concepts(turn_toks)) for o, _w in neighbours(c)}
    for w in TOK.findall(reply.lower()):
        if w in own or lem(w) in own or w in FUNC or w in PUNC or role(w) not in CONTENT_ROLES or len(w) < 3:
            continue
        k = wid.get(w)
        if (k is not None and (dr[k] > 0.5 or rc[k] > 0.5)) or lem(w) in reach:
            return True
    return False


# ---------------------------------------------------------------- the order above the word: staged solving (Ben, 11-08:
# like the cube's staged algorithms — each stage fixes one property, later stages use only moves that keep it)
import os
from turn_kernel import TurnKernel, Induced
from stage5m13e9_kernel_k8 import ConstructionKernelK8
TKD = os.environ.get("ORACLE7_TK", T + "/workbench/converse/data/tk")
RULES = {r["rule_id"]: r for r in json.load(open(TKD + "/conv_rules.json"))["rules"]}
SP = json.load(open(TKD + "/scene_programs.json"))
TRN = raw["train"]
pvocab = collections.defaultdict(collections.Counter)
fsucc = collections.defaultdict(collections.Counter)
fact = collections.defaultdict(collections.Counter)
cform = collections.defaultdict(collections.Counter)    # concept of the speaker's turn -> reply form
fae = collections.defaultdict(collections.Counter)      # (act, feeling) of the speaker's turn -> reply form
fbase = collections.Counter()
for di, dlp in enumerate(SP[:NTR]):                      # the forms are read on the ingest part of train only
    acts = TRN[di].get("acts") or []
    for j in range(len(dlp)):
        for p in dlp[j] or []:
            if p:
                for k, v in p.get("slots", {}).items():
                    pvocab[(p["rule"], str(k))][str(v).lower()] += 1
        if j + 1 < len(dlp):
            for pb in dlp[j + 1] or []:
                if not pb:
                    continue
                if j < len(acts):
                    fact[acts[j]][pb["rule"]] += 1
                fbase[pb["rule"]] += 1
                emos = TRN[di].get("emotions") or []
                if j < len(acts) and j < len(emos):
                    fae[(acts[j], emos[j])][pb["rule"]] += 1
                if j < len(TRN[di]["utterances"]):
                    for c in set(concepts(TOK.findall(clean(TRN[di]["utterances"][j]).lower()))):
                        cform[c][pb["rule"]] += 1
                for pa in dlp[j] or []:
                    if pa:
                        fsucc[pa["rule"]][pb["rule"]] += 1
FB = sum(fbase.values()) or 1


def flift(cnt, rid, k=5.0):
    """the same correction one order up: a form counts by its lift over its base rate, shrunk for thin evidence"""
    n = cnt.get(rid, 0)
    if not n:
        return 0.0
    return max(0.0, math.log((n / sum(cnt.values())) / (fbase[rid] / FB))) * n / (n + k)


prole = {}
for key, cn in pvocab.items():
    rc = collections.Counter()
    for w, n in cn.items():
        for x in TOK.findall(w):
            rc[role(x)] += n
    prole[key] = rc
_wv = np.load(T + "/workbench/converse/data/ladder/wordvec.npz", allow_pickle=True)
WV, WVI = _wv["vec"], {w: i for i, w in enumerate(_wv["words"])}
PLACE = {}                                                # place -> (bundle of its fillers, its own resonance floor)
for key, cn in pvocab.items():
    ws = [(w, n) for w, n in cn.items() if w in WVI]
    if len(ws) < 3:
        continue
    vs = np.stack([WV[WVI[w]] for w, _ in ws]); ns = np.array([n for _, n in ws], np.float32)
    b = (vs * ns[:, None]).sum(0); b /= (np.linalg.norm(b) + 1e-9)
    cos = vs @ b
    PLACE[key] = (b, float(np.percentile(cos, 25)))
print("places with a meaning bundle:", len(PLACE), flush=True)


def resonates(key, w):
    """a word may enter a place if it resonates with the bundle of the words that filled it, at least as strongly as the
    place's own fillers do (their 25th percentile); places too thin for a bundle keep the part-of-speech rule"""
    if key not in PLACE:
        return None
    if w not in WVI:
        return False
    b, floor = PLACE[key]
    return float(WV[WVI[w]] @ b) >= floor


TKER = TurnKernel(ConstructionKernelK8(compositional=True), TKD)
print("forms", len(RULES), "typed places", len(pvocab), flush=True)


class Cells:
    """the whole saved corpus (59.6M words) as packed ladder cells: sorted uint64 address|next keys + counts"""
    def __init__(self, path):
        z = np.load(path, allow_pickle=True)
        self.vocab = list(z["vocab"]); self.wid = {w: i for i, w in enumerate(self.vocab)}
        self.roles = list(z["roles"]); self.rid = {r: i for i, r in enumerate(self.roles)}; self.vrole = z["vrole"]
        self.k = {n: z[n + "_k"] for n in ("w3", "w2", "w1", "b3", "b2", "b1")}
        self.c = {n: z[n + "_c"] for n in ("w3", "w2", "w1", "b3", "b2", "b1")}
        self.V = len(self.vocab)

    def _cell(self, n, prefix):
        k = self.k[n]
        lo = np.searchsorted(k, np.uint64(prefix << 16))
        hi = np.searchsorted(k, np.uint64((prefix << 16) | 0xFFFF), side="right")
        return (k[lo:hi] & np.uint64(0xFFFF)).astype(np.int64), self.c[n][lo:hi].astype(np.float64)

    def dist(self, prev):
        ids = [self.wid.get(w, 0) for w in prev[-3:]]
        while len(ids) < 3:
            ids.insert(0, 1)
        rl = [int(self.vrole[i]) for i in ids]
        p = 0
        for w in reversed(prev):
            if w == "<s>":
                break
            p += 1
        p = min(9, p)
        i1, i2, i3 = ids; r1, r2, r3 = rl
        wsc, bsc = np.zeros(self.V), np.zeros(self.V)
        for n, pre, o, tgt in (("w3", (i1 << 32) | (i2 << 16) | i3, 3, wsc), ("w2", (i2 << 16) | i3, 2, wsc), ("w1", i3, 1, wsc),
                               ("b3", (r1 << 32) | (r2 << 24) | (r3 << 16) | p, 3, bsc), ("b2", (r2 << 24) | (r3 << 16) | p, 2, bsc),
                               ("b1", (r3 << 16) | p, 1, bsc)):
            ks, cs = self._cell(n, pre)
            if len(cs) == 0:
                continue
            z = (cs.max() - cs.mean()) / (cs.std() + 1e-9) if len(cs) > 1 else 3.0
            if z > ZACC:
                tgt[ks] += z * o * cs / cs.sum()
        s_ = A_REC * norm(wsc) + norm(bsc)
        s_[0] = 0; s_[1] = 0
        return s_ / s_.sum() if s_.sum() > 0 else s_


CELLS = Cells(T + "/workbench/converse/data/ladder/cells.npz")
print("corpus cells loaded:", CELLS.V, "words", sum(len(v) for v in CELLS.k.values()), "cells", flush=True)
MU = 0.5


def p_dialog(r, pd_):
    i = len(r)
    ids = [wid.get(x, UNK) for x in r]
    rb = [role(x) for x in r]
    ng = norm(zread(ngram, lambda o: tuple(ids[i - o:i]) if i - o >= 0 else None))
    bd = norm(zread(band, lambda o: (tuple(rb[i - o:i]), posn(r, i)) if i - o >= 0 else None))
    s_ = (A_REC * ng + bd) * np.exp(L_TURN * pd_)
    return s_ / s_.sum() if s_.sum() > 0 else s_


def p_word(r, w, pd_, mu=None):
    mu = MU if mu is None else mu
    pdlg = p_dialog(r, pd_)
    k = wid.get(w, UNK)
    a = pdlg[k] if k != UNK else 0.0
    b = CELLS.dist(r)[CELLS.wid.get(w, 0)] if CELLS.wid.get(w, 0) > 1 else 0.0
    return mu * b + (1 - mu) * a


def sure(toks, pd_):
    r, lp = ["<s>"], []
    for w in toks:
        lp.append(math.log(p_word(r, w, pd_) + 1e-6))
        r.append(w)
    return sum(lp) / max(1, len(lp))


def fit_mu():
    """the blend of general English (whole corpus) and conversational register (dialogue), fitted on the held-back slice:
    the mean log score of the actual next word for each blend; the best is kept"""
    fd = list(dialogues("fit"))
    random.Random(5).shuffle(fd)
    pos_ = []
    for dl in fd[:120]:
        for j in range(1, len(dl)):
            pos_.append((dl[j - 1], dl[j]))
    pos_ = pos_[:300]
    res = {}
    cache = []
    for prev, rep_ in pos_:
        pd_, _ = context_read(concepts(prev))
        r = ["<s>"]
        for w in rep_:
            pdlg = p_dialog(r, pd_)
            k = wid.get(w, UNK)
            a = pdlg[k] if k != UNK else 0.0
            ck = CELLS.wid.get(w, 0)
            b = CELLS.dist(r)[ck] if ck > 1 else 0.0
            cache.append((a, b))
            r.append(w)
    for mu in (0.0, 0.1, 0.2, 0.3, 0.5, 0.7, 0.9, 1.0):
        res[mu] = sum(math.log(mu * b + (1 - mu) * a + 1e-6) for a, b in cache) / len(cache)
    print("blend fit (mean log score of the next word, %d words of the held-back slice):" % len(cache),
          "  ".join("mu=%.1f %.3f" % (m, v) for m, v in res.items()), flush=True)
    return max(res, key=res.get)


MU = fit_mu()
print("fitted blend: corpus share", MU, flush=True)


def _sure_unused(toks, pd_):
    """stage-3 judge: how surely the fitted readout reads the whole sentence (mean log score of its words)"""
    r = ["<s>"]
    lp = []
    for w in toks:
        i = len(r)
        ids = [wid.get(x, UNK) for x in r]
        rb = [role(x) for x in r]
        ng = norm(zread(ngram, lambda o: tuple(ids[i - o:i]) if i - o >= 0 else None))
        bd = norm(zread(band, lambda o: (tuple(rb[i - o:i]), posn(r, i)) if i - o >= 0 else None))
        s_ = (A_REC * ng + bd) * np.exp(L_TURN * pd_)
        k = wid.get(w, UNK)
        p = (s_[k] / s_.sum()) if s_.sum() > 0 and k != UNK else 0.0
        lp.append(math.log(p + 1e-6))
        r.append(w)
    return sum(lp) / max(1, len(lp))


def solve(turn_text):
    toks = TOK.findall(clean(turn_text).lower())
    cont = content_of(toks)
    pd_, _ = context_read(concepts(toks))
    # stage 1, SHAPE: the forms this turn calls (its act, and the forms that follow its own forms)
    act = 2 if turn_text.rstrip().endswith("?") else 1
    call = collections.Counter()
    for r_ in fact[act]:
        call[r_] += flift(fact[act], r_)
    for p in TKER.compile(turn_text) or []:
        if p and p.get("kind") == "rule":
            for r_ in fsucc[p["rule"]]:
                call[r_] += flift(fsucc[p["rule"]], r_)
    from relational_instrument_v1 import act_of, emotion_of, ACTS, EMOS
    an = {v: k for k, v in ACTS.items()}.get(act_of(turn_text), 1)
    en = {v: k for k, v in EMOS.items()}.get(emotion_of(turn_text), 0)
    for r_ in fae[(an, en)]:
        call[r_] += 2 * flift(fae[(an, en)], r_)          # what the turn does and how it feels decides the move first
    cs = set(concepts(toks))
    for c in cs:
        for r_ in cform.get(c, ()):
            call[r_] += flift(cform[c], r_) / len(cs)
    best = None
    for rid, a in call.most_common(120):
        rr = RULES.get(rid)
        if not rr:
            continue
        sk = rr["skeleton_tokens"]
        places = [i for i, x in enumerate(sk) if x.startswith("<")]
        if not places:
            continue
        # stage 2, CONTENT: a brought word only into a place that takes its kind of word; at least one must land
        slots, landed = {}, []
        for k in places:
            key = (rid, str(k))
            vb, rc = pvocab.get(key, collections.Counter()), prole.get(key, collections.Counter())
            tot = sum(rc.values()) or 1
            fit = []
            for w, s_ in cont:
                if w in landed:
                    continue
                rz = resonates(key, w)
                if vb.get(w) or rz or (rz is None and rc.get(role(w), 0) / tot >= 0.3):
                    fit.append((w, s_))
            if fit and sum(rc[x] for x in CONTENT_ROLES) / tot >= 0.3:
                slots[k] = fit[0][0]; landed.append(fit[0][0])
            elif vb:
                slots[k] = vb.most_common(1)[0][0]
            else:
                slots = None; break
        if not slots or not landed:
            continue
        # stage 3, AGREEMENT: one place at a time, try that place's own common fills and the other brought words; keep a
        # move only if the whole sentence reads more surely and the brought content stays in
        def realise(sl):
            return Induced.realize({"kind": "rule", "rule": rid, "slots": sl, "skeleton": sk})
        cur = sure(TOK.findall(realise(slots).lower()), pd_)
        for k in places:
            key = (rid, str(k))
            opts = [w for w, _n in pvocab.get(key, collections.Counter()).most_common(6)] +                    [w for w, _ in cont if resonates(key, w) is not False]
            for w in opts:
                if w == slots[k]:
                    continue
                trial = dict(slots); trial[k] = w
                if not any(x in trial.values() for x, _ in cont):
                    continue
                sc = sure(TOK.findall(realise(trial).lower()), pd_)
                if sc > cur:
                    slots, cur = trial, sc
        txt = realise(slots)
        prog = {"kind": "rule", "rule": rid, "slots": slots, "skeleton": sk}
        # stage 4, SOLVED: the second reading holds and the reply carries what the turn brings
        if not TKER.same(prog, txt) or not carries(toks, txt):
            continue
        total = cur + a
        if best is None or total > best[0]:
            best = (total, txt, rid)
    if best:
        return best[1], cont, best[2]
    txt, _ = speak(toks)
    return txt, cont, "word-order"


MODE = (sys.argv[3] if len(sys.argv) > 3 else "dev") if __name__ == "__main__" else "lib"
if MODE == "dev":
    for line in open(sys.argv[4], encoding="utf-8"):
        line = line.strip()
        if line:
            t = TOK.findall(clean(line).lower())
            rep, cont, how = solve(line)
            print("%-52s -> %s   [brings: %s] [%s] L2=%s" % (line[:52], rep, ", ".join(w for w, _ in cont[:4]), how, carries(t, rep)), flush=True)
elif MODE != "lib":                     # L2, run once: first statements of held-out validation dialogues
    vals = [dl for dl in dialogues("validation") if len(dl) > 1 and dl[0] and dl[0][-1] != "?"]
    random.Random(611).shuffle(vals)
    vals = vals[:100]
    common = collections.Counter(" ".join(dl[1]) for dl in dialogues("train") if len(dl) > 1).most_common(1)[0][0]
    res = collections.Counter()
    gen = []
    for k, dl in enumerate(vals):
        t = dl[0]
        rep, _ = speak(t)
        gen.append(rep)
        res["system"] += carries(t, rep)
        res["echo"] += carries(t, " ".join(t))
        res["generic"] += carries(t, common)
    for k, dl in enumerate(vals):
        res["other_turn"] += carries(dl[0], gen[(k + 1) % len(gen)])
        res["human"] += carries(dl[0], " ".join(dl[1]))
    print("L2 on 100 held-out first statements (validation), run once; share of replies carrying content the turn brings:")
    for k in ("system", "human", "echo", "generic", "other_turn"):
        print("  %-10s %d/100" % (k, res[k]))
    print("  generic line used:", common)
    ok = res["system"] >= 70 and all(res[m] <= 20 for m in ("echo", "generic", "other_turn"))
    print("L2 bar (system >= 70, every mutant <= 20) ->", "PASS" if ok else "FAIL")
    for k in range(12):
        print("   %-50s -> %s" % (" ".join(vals[k][0])[:50], gen[k]))