File size: 25,212 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""LOOPGUARD-1 (records/R5/LOOPGUARD/design.json): the reference-free line-loop guard of arm A2, its post-processing and its self-test.

The guard watches the TEXT tokens of the current output line (tokens since the last newline, before the line's first location
token). It FIRES when
  (a) the last K_REP x p text tokens are K_REP copies of one unit of p tokens, for the first p in 1..P_MAX that holds
      (counted as in records/R5/LOOPGUARD/analysis/lg_check_final_rule.py: runs[p] = consecutive text positions i with
      text[i] == text[i - p]; fire when runs[p] >= (K_REP - 1) x p), or
  (b) the line holds more than T_LINE text tokens (only if (a) did not fire on that token).
At most one fire per line. After a fire (enforced mode) only the 1,001 location tokens may follow until the line has 8 of
them, then only the newline or an end token; the next line is free again. Observe-only mode records the same events and never
changes a score. A row ends at its first stop token (end ids or pad); later tokens are ignored.

Post-processing (fixed before any run): a line closed by rule (a) keeps its text up to and including the first copy of the
unit (text[:onset + p]) and its location tokens; a line closed by rule (b) is dropped. Lines without an event are unchanged.

Self-test (CPU, no model): python om_guard.py --selftest --tokenizer-dir DIR --records-root DIR --preds-root DIR
  --final-rule lg_final_rule.json --out JSON
"""
import argparse
import json
import os
import sys
import time

DESIGN_ID = "LOOPGUARD-1"
K_REP = 12
P_MAX = 8
T_LINE = 96
NGRAM = 20
NL_ID = 23
LOC0 = 100297
LOC1 = 101297
N_LOC_LINE = 8


def token_ids(tok, stops, stop_set):
    """Ids the guard needs, asserted against the tokenizer (as build_report.json tokenizer block)."""
    nl = tok("\n", add_special_tokens=False).input_ids
    assert nl == [NL_ID], "newline ids %r != [%d]" % (nl, NL_ID)
    loc = tok.convert_tokens_to_ids(["<|LOC_%d|>" % n for n in range(1001)])
    assert loc == list(range(LOC0, LOC1 + 1)), "location ids are not the contiguous range %d..%d" % (LOC0, LOC1)
    ends = sorted(int(x) for x in stops)
    finish = sorted(int(x) for x in stop_set)
    assert ends and set(ends) <= set(finish), (ends, finish)
    assert NL_ID not in finish and not any(LOC0 <= t <= LOC1 for t in finish), "a stop id collides with newline/location ids"
    return {"newline": NL_ID, "loc0": LOC0, "loc1": LOC1, "end_ids": ends, "finish_ids": finish}


class LineState:
    """Incremental guard state of one row (pure Python; also used by the self-test on reference ids)."""

    def __init__(self, k=K_REP, p_max=P_MAX, t_line=T_LINE, nl=NL_ID, loc0=LOC0, loc1=LOC1, finish_ids=(2,)):
        self.k, self.p_max, self.t_line, self.nl, self.loc0, self.loc1 = k, p_max, t_line, nl, loc0, loc1
        self.finish = set(int(x) for x in finish_ids)
        self.line = 0
        self.finished = False
        self.events = []
        self._new_line()

    def _new_line(self):
        self.text = []
        self.n_loc = 0
        self.in_text = True
        self.runs = [0] * (self.p_max + 1)
        self.fired = False
        self.forced = False

    def push(self, t, step=None):
        if self.finished:
            return
        if t in self.finish:
            self.finished = True
            return
        if t == self.nl:
            self.line += 1
            self._new_line()
            return
        if self.loc0 <= t <= self.loc1:
            self.n_loc += 1
            self.in_text = False
            return
        if not self.in_text or self.fired:
            return
        self.text.append(t)
        i = len(self.text) - 1
        for p in range(1, self.p_max + 1):
            if i - p >= 0 and self.text[i - p] == t:
                self.runs[p] += 1
            else:
                self.runs[p] = 0
            if self.runs[p] >= (self.k - 1) * p:
                self._fire("period", p, len(self.text) - self.k * p, step)
                return
        if len(self.text) > self.t_line:
            self._fire("length", 0, None, step)

    def _fire(self, why, p, onset, step):
        self.fired = True
        self.forced = True
        self.events.append({"line": self.line, "why": why, "p": p, "onset_text_index": onset,
                            "n_text_tokens": len(self.text), "step": step})


def _transformers_base():
    from transformers import LogitsProcessor
    return LogitsProcessor


class LineLoopGuard(_transformers_base()):
    """transformers LogitsProcessor (5.23: called as processor(input_ids, scores); keep exactly two arguments, see
    LogitsProcessorList.__call__ in generation/logits_process.py). One instance per generate() call."""

    def __init__(self, prompt_len, batch, ids, k=K_REP, p_max=P_MAX, t_line=T_LINE, observe_only=False):
        self.prompt_len = int(prompt_len)
        self.batch = int(batch)
        self.ids = ids
        self.observe_only = bool(observe_only)
        self.cfg = {"k": k, "p_max": p_max, "t_line": t_line, "observe_only": self.observe_only}
        self.states = [LineState(k, p_max, t_line, ids["newline"], ids["loc0"], ids["loc1"], ids["finish_ids"]) for _ in range(batch)]
        self.last_step = None
        self.masked_steps = 0
        self.calls = 0
        self._end_allowed = sorted(set([ids["newline"]] + list(ids["end_ids"])))

    def __call__(self, input_ids, scores):
        import torch
        self.calls += 1
        cur = int(input_ids.shape[1])
        assert input_ids.shape[0] == self.batch, "batch %d != %d" % (input_ids.shape[0], self.batch)
        step = cur - self.prompt_len
        assert step >= 0, "input shorter than the prompt: guard built for another batch"
        if self.last_step is None:
            assert step == 0, "first call at step %d: a guard must be new for every generate() call" % step
        else:
            assert step == self.last_step + 1, "steps not consecutive (%s -> %d)" % (self.last_step, step)
        self.last_step = step
        if step > 0:
            last = input_ids[:, -1].tolist()          # one device-to-host copy per step
            for r, t in enumerate(last):
                self.states[r].push(int(t), step)
        if self.observe_only:
            return scores
        rows_loc, rows_end = [], []
        for r, s in enumerate(self.states):
            if s.forced and not s.finished:
                (rows_loc if s.n_loc < N_LOC_LINE else rows_end).append(r)
        if not rows_loc and not rows_end:
            return scores
        out = scores.clone()
        neg = -float("inf")
        for r in rows_loc:
            out[r, :self.ids["loc0"]] = neg
            out[r, self.ids["loc1"] + 1:] = neg
        if rows_end:
            keep_idx = torch.tensor(self._end_allowed, device=scores.device, dtype=torch.long)
            for r in rows_end:
                keep = scores[r, keep_idx]
                out[r, :] = neg
                out[r, keep_idx] = keep
        self.masked_steps += 1
        return out

    def events(self, r):
        return list(self.states[r].events)


def split_lines(ids, nl=NL_ID):
    lines = [[]]
    for t in ids:
        if t == nl:
            lines.append([])
        else:
            lines[-1].append(t)
    return lines


def clean_ids(new_ids, events, nl=NL_ID, loc0=LOC0, loc1=LOC1, end_ids=(2,)):
    """The fixed post-processing of arm A2. new_ids: generated ids up to and including the stop token (if any)."""
    ids = list(new_ids)
    tail = []
    if ids and ids[-1] in set(end_ids):
        tail = [ids[-1]]
        ids = ids[:-1]
    lines = split_lines(ids, nl)
    by_line = {}
    for e in events:
        by_line.setdefault(e["line"], e)          # first event of a line (at most one in enforced mode)
    kept = []
    for i, ln in enumerate(lines):
        e = by_line.get(i)
        if e is None:
            kept.append(ln)
            continue
        if e["why"] == "length":
            continue                                # rule (b): the line is dropped
        n_text = 0
        while n_text < len(ln) and not (loc0 <= ln[n_text] <= loc1):
            n_text += 1
        assert n_text == e["n_text_tokens"], "line %d: %d text tokens, event says %d" % (i, n_text, e["n_text_tokens"])
        cut = e["onset_text_index"] + e["p"]
        kept.append(ln[:cut] + ln[n_text:])        # rule (a): first copy of the unit, then the line's location tokens
    out = []
    for j, ln in enumerate(kept):
        if j:
            out.append(nl)
        out += ln
    return out + tail


# ------------------------------------------------------------------------------------------------------------ self-test
def _triggers_reference(ids, NL=NL_ID, EOS=2, LOC0_=LOC0, LOC1_=LOC1, K=K_REP, P=P_MAX, T=T_LINE):
    """verbatim logic of records/R5/LOOPGUARD/analysis/lg_check_final_rule.py triggers() (the design's rule check)"""
    out, line_start, in_text, runs, fired, line_no = [], 0, True, [0] * (P + 1), False, 0
    for i, t in enumerate(ids):
        if t == EOS:
            break
        if t == NL:
            line_start, in_text, runs, fired = i + 1, True, [0] * (P + 1), False
            line_no += 1
            continue
        if LOC0_ <= t <= LOC1_:
            in_text = False
            continue
        if not in_text or fired:
            continue
        for p in range(1, P + 1):
            if i - p >= line_start and ids[i - p] == t:
                runs[p] += 1
            else:
                runs[p] = 0
            if runs[p] >= (K - 1) * p:
                out.append({"line": line_no, "why": "period", "p": p, "text_tokens": i - line_start + 1})
                fired = True
                break
        if not fired and i - line_start + 1 > T:
            out.append({"line": line_no, "why": "length", "p": 0, "text_tokens": i - line_start + 1})
            fired = True
    return out


def _run_rows(rows, ids, observe_only, vocab, prompt_len=5, batch=64, check_scores=True):
    """Feed token rows through LineLoopGuard as generate() would (left prompt of pad ids, pads after the stop token).
    Returns per row (events, masked) and the number of calls whose returned scores differ from the input."""
    import torch
    res, changed_calls = [], 0
    pad = 0
    for b0 in range(0, len(rows), batch):
        chunk = rows[b0:b0 + batch]
        L = max(len(r) for r in chunk)
        full = torch.full((len(chunk), prompt_len + L), pad, dtype=torch.long)
        for i, r in enumerate(chunk):
            if r:
                full[i, prompt_len:prompt_len + len(r)] = torch.tensor(r, dtype=torch.long)
        g = LineLoopGuard(prompt_len, len(chunk), ids, observe_only=observe_only)
        scores = torch.zeros((len(chunk), vocab), dtype=torch.float32)
        for step in range(L + 1):
            out = g(full[:, :prompt_len + step], scores)
            if out is not scores:
                changed_calls += 1
                if check_scores and observe_only:
                    raise AssertionError("observe-only guard returned modified scores")
        for i in range(len(chunk)):
            res.append({"events": g.events(i), "masked_steps": g.masked_steps})
    return res, changed_calls


def selftest(a):
    import torch
    import transformers
    from transformers import AutoTokenizer, GenerationConfig, LogitsProcessor, LogitsProcessorList, NoRepeatNGramLogitsProcessor
    from transformers.generation.utils import GenerationMixin
    import inspect
    t0 = time.time()
    rep = {"design": DESIGN_ID, "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "checks": {}, "facts": {}}
    C = rep["checks"]
    # --- the installed transformers has what the arms use
    rep["facts"]["transformers"] = transformers.__version__
    rep["facts"]["torch"] = torch.__version__
    sig = inspect.signature(GenerationMixin.generate).parameters
    C["transformers_is_5.23.0"] = transformers.__version__ == "5.23.0"
    C["generate_has_logits_processor_arg"] = "logits_processor" in sig
    C["generationconfig_has_no_repeat_ngram_size"] = hasattr(GenerationConfig(), "no_repeat_ngram_size")
    C["norepeat_processor_exists"] = issubclass(NoRepeatNGramLogitsProcessor, LogitsProcessor)
    C["guard_is_logitsprocessor_with_2_args"] = (issubclass(LineLoopGuard, LogitsProcessor)
                                                 and list(inspect.signature(LineLoopGuard.__call__).parameters) == ["self", "input_ids", "scores"])
    tok = AutoTokenizer.from_pretrained(a.tokenizer_dir)
    stops, stop_set = [2], {0, 2}
    ids = token_ids(tok, stops, stop_set)
    rep["facts"]["ids"] = ids
    vocab = max(len(tok), LOC1 + 1)
    rep["facts"]["vocab_for_tests"] = vocab
    nl_like = [i for i in range(len(tok)) if i != NL_ID and "\n" in tok.decode([i], skip_special_tokens=False, clean_up_tokenization_spaces=False)]
    rep["facts"]["other_tokens_whose_text_contains_a_newline"] = {"count": len(nl_like), "first_ids": nl_like[:20]}
    # --- LogitsProcessorList calls the guard (2-argument signature) and leaves scores alone when nothing fires
    g = LineLoopGuard(3, 1, ids)
    sc = torch.zeros((1, vocab))
    out = LogitsProcessorList([g])(torch.zeros((1, 3), dtype=torch.long), sc)
    C["processor_list_calls_guard"] = out is sc and g.calls == 1

    # --- synthetic rows
    syn = {}
    A, B_, Cc, D, E = 1000, 1001, 1002, 1003, 1004
    base_unit = [500, 501, 502, 503, 504, 505, 506, 507]

    def fire_at(seq):
        st = LineState(finish_ids=ids["finish_ids"])
        for j, t in enumerate(seq):
            st.push(t, j + 1)
            if st.events:
                return j + 1, st.events[0]
        return None, None

    for p in range(1, P_MAX + 1):
        unit = base_unit[:p]
        # a 3-token prefix, except for p = 8: 12 x 8 = 96 tokens already fill the line limit (3 + 96 > 96 would fire the
        # length rule first, which is the rule's defined behaviour, checked below)
        prefix = [A, B_, Cc] if p < P_MAX else []
        seq12 = prefix + unit * 12
        seq11 = prefix + unit * 11 + [E]
        n12, e12 = fire_at(seq12)
        n11, _ = fire_at(seq11)
        syn["p%d" % p] = {"fires_at_token": n12, "expected": len(prefix) + 12 * p, "why": e12 and e12["why"], "p": e12 and e12["p"],
                          "onset": e12 and e12["onset_text_index"], "no_fire_at_11_copies": n11 is None}
        C["synthetic_p%d_fires_at_12_copies_not_11" % p] = (n12 == len(prefix) + 12 * p and e12["why"] == "period" and e12["p"] == p
                                                          and e12["onset_text_index"] == len(prefix) and n11 is None)
    n8, e8 = fire_at([A, B_, Cc] + base_unit * 12)
    syn["p8_after_3_text_tokens"] = {"fires_at_token": n8, "why": e8 and e8["why"]}
    C["synthetic_p8_after_prefix_fires_length_rule_at_97"] = n8 == 97 and e8["why"] == "length"
    prefix = [A, B_, Cc]
    seq = list(range(2000, 2000 + 97))
    n, e = fire_at(seq)
    C["synthetic_length_fires_at_97_text_tokens"] = n == 97 and e["why"] == "length" and e["n_text_tokens"] == 97
    n96, _ = fire_at(seq[:96] + [NL_ID] + seq[:96])
    C["synthetic_96_text_tokens_twice_no_fire"] = n96 is None
    # repeats split by a newline, repeats after a location token, a period-9 unit: no fire
    n_nl, _ = fire_at([A] * 6 + [NL_ID] + [A] * 6)
    n_loc, _ = fire_at([A, B_] + [LOC0 + 5] + [A] * 30)
    n_p9, _ = fire_at(list(range(3000, 3009)) * 10)
    C["synthetic_no_fire_across_newline_after_loc_or_period9"] = n_nl is None and n_loc is None and n_p9 is None
    # equivalence with the design's triggers() on these sequences
    eq = []
    for s in [prefix + base_unit[:p] * 12 for p in range(1, 9)] + [seq, seq[:96] + [NL_ID] + seq[:96]]:
        st = LineState(finish_ids=ids["finish_ids"])
        for t in s:
            st.push(t)
        tr = _triggers_reference(s)
        eq.append([(x["line"], x["why"], x["p"], x["n_text_tokens"]) for x in st.events] == [(x["line"], x["why"], x["p"], x["text_tokens"]) for x in tr])
    C["synthetic_equal_to_design_triggers"] = all(eq)
    rep["synthetic"] = syn

    # --- enforced mode: masks after a fire, location tokens untouched, then newline/end, then free; batch rows independent
    prompt = 4
    unit = [700, 701, 702]
    row0 = [A] + unit * 12                                         # fires at its last token
    row1 = [A, B_, Cc, D]                                          # a clean row
    g = LineLoopGuard(prompt, 2, ids)
    base = torch.arange(vocab, dtype=torch.float32).repeat(2, 1) * 1e-6
    hist = torch.zeros((2, prompt), dtype=torch.long)
    seqs = [list(row0), list(row1) + [2]]
    ok_loc = ok_end = ok_free = ok_row1 = True
    feed0 = list(row0)
    for step in range(len(row0) + 1 + 8 + 2):
        out = g(hist, base.clone())
        if step == len(row0):                                      # first step after the fire: only location ids, unchanged
            fin = torch.isfinite(out[0])
            ok_loc &= bool(fin[LOC0:LOC1 + 1].all()) and int(fin.sum()) == LOC1 - LOC0 + 1
            ok_loc &= bool(torch.equal(out[0, LOC0:LOC1 + 1], base[0, LOC0:LOC1 + 1]))
        if len(row0) <= step < len(row0) + 8:
            fin = torch.isfinite(out[0])
            ok_loc &= int(fin.sum()) == LOC1 - LOC0 + 1
        if step == len(row0) + 8:                                  # after 8 location ids: newline and end ids only
            fin = torch.isfinite(out[0])
            allowed = sorted(set([NL_ID] + ids["end_ids"]))
            ok_end &= sorted(torch.nonzero(fin).flatten().tolist()) == allowed
            ok_end &= bool(torch.equal(out[0, allowed], base[0, allowed]))
        if step == len(row0) + 9:                                  # next line is free again
            ok_free &= bool(torch.isfinite(out[0]).all())
        ok_row1 &= bool(torch.isfinite(out[1]).all())             # the other row is never masked
        # next tokens: row 0 follows row0, then 8 location tokens, then newline, then A; row 1 its sequence then end/pad
        if step < len(row0):
            n0 = row0[step]
        elif step < len(row0) + 8:
            n0 = LOC0 + 10 * (step - len(row0))
        elif step == len(row0) + 8:
            n0 = NL_ID
        else:
            n0 = A
        n1 = seqs[1][step] if step < len(seqs[1]) else 0
        hist = torch.cat([hist, torch.tensor([[n0], [n1]], dtype=torch.long)], 1)
        feed0.append(n0)
    C["enforced_only_location_ids_open_and_unchanged_after_fire"] = ok_loc
    C["enforced_then_only_newline_and_end_ids"] = ok_end
    C["enforced_next_line_free"] = ok_free
    C["enforced_other_row_untouched"] = ok_row1
    C["enforced_one_event"] = len(g.events(0)) == 1 and g.events(1) == []
    # observe-only never changes scores, same events
    g2 = LineLoopGuard(prompt, 2, ids, observe_only=True)
    same = True
    for step in range(hist.shape[1] - prompt + 1):
        sc = base.clone()
        out = g2(hist[:, :prompt + step], sc)
        same &= out is sc
    C["observe_only_never_changes_scores"] = same
    C["observe_only_same_events"] = [(e["line"], e["why"], e["p"], e["n_text_tokens"]) for e in g2.events(0)] == \
        [(e["line"], e["why"], e["p"], e["n_text_tokens"]) for e in g.events(0)]
    # finished rows: tokens after the end token are ignored
    st = LineState(finish_ids=ids["finish_ids"])
    for t in [A, 2] + [A] * 40:
        st.push(t)
    C["after_end_token_ignored"] = st.events == [] and st.finished
    # clean_ids
    locs = [LOC0 + 1, LOC0 + 2, LOC0 + 3, LOC0 + 2, LOC0 + 3, LOC0 + 4, LOC0 + 1, LOC0 + 4]
    l0 = [A, B_] + locs
    l1 = [Cc] + unit * 12 + locs                                     # period line
    l2 = list(range(2000, 2097)) + locs                              # length line
    l3 = [D, E] + locs
    gen = l0 + [NL_ID] + l1 + [NL_ID] + l2 + [NL_ID] + l3 + [2]
    st = LineState(finish_ids=ids["finish_ids"])
    for t in gen:
        st.push(t)
    cl = clean_ids(gen, st.events, end_ids=ids["end_ids"])
    want = l0 + [NL_ID] + ([Cc] + unit + locs) + [NL_ID] + l3 + [2]
    C["clean_ids_period_keeps_first_copy_and_locations_length_dropped"] = cl == want
    C["clean_ids_identity_without_events"] = clean_ids(gen, [], end_ids=ids["end_ids"]) == gen
    rep["clean_example"] = {"events": st.events, "in_len": len(gen), "out_len": len(cl)}

    # --- every reference target (train + val pages) through the guard: no event, no score change
    ref = {}
    rows_all = []
    for s in ("school_train", "gen_train", "school_val", "gen_val"):
        p = os.path.join(a.records_root, s + ".jsonl")
        rows = []
        with open(p, encoding="utf-8") as f:
            for line in f:
                r = json.loads(line)
                rows.append(list(r["target_ids"]))
        rows_all.append((s, rows))
    for s, rows in rows_all:
        res, changed = _run_rows(rows, ids, observe_only=False, vocab=vocab, check_scores=False)
        fired = sum(1 for x in res if x["events"])
        # the design's own counter on the same ids
        fired_ref = sum(1 for r in rows if _triggers_reference(r))
        ref[s] = {"pages": len(rows), "pages_fired": fired, "calls_with_changed_scores": changed, "pages_fired_design_triggers": fired_ref}
    rep["references"] = ref
    n_pages = sum(v["pages"] for v in ref.values())
    C["references_6006_pages"] = n_pages == 6006
    C["references_no_fire_no_score_change"] = all(v["pages_fired"] == 0 and v["calls_with_changed_scores"] == 0
                                                  and v["pages_fired_design_triggers"] == 0 for v in ref.values())

    # --- stored validation outputs (re-tokenised, as the design's check): observe mode fires on the predicted pages
    from tokenizers import Tokenizer
    fr = json.load(open(a.final_rule, encoding="utf-8"))
    tk = Tokenizer.from_file(os.path.join(a.tokenizer_dir, "tokenizer.json"))
    out_pages = {}
    for s in ("school_val", "gen_val"):
        P_ = []
        with open(os.path.join(a.preds_root, s + ".jsonl"), encoding="utf-8") as f:
            for line in f:
                r = json.loads(line)
                P_.append(r)
        rows = [tk.encode(r["raw"], add_special_tokens=False).ids for r in P_]
        res, changed = _run_rows(rows, ids, observe_only=True, vocab=vocab)
        fired = sorted(P_[i]["id"] for i, x in enumerate(res) if x["events"])
        capped = sorted(r["id"] for r in P_ if r["hit_cap"])
        first = [res[i]["events"][0] for i in range(len(res)) if res[i]["events"]]
        exp = fr["on_stored_outputs"][s]
        reasons = {}
        for e in first:
            reasons[e["why"]] = reasons.get(e["why"], 0) + 1
        out_pages[s] = {"pages": len(P_), "fired": fired, "capped": capped, "fire_reasons_first": reasons,
                        "text_tokens_in_line_at_first_fire": sorted(e["n_text_tokens"] for e in first)}
        C["stored_%s_fires_as_design" % s] = (len(fired) == exp["pages_fired"] and fired == capped and reasons == exp["fire_reasons_first"]
                                             and sorted(e["n_text_tokens"] for e in first) == exp["text_tokens_in_line_at_first_fire"]
                                             and changed == 0)
    rep["stored_outputs"] = out_pages

    # --- A1 sanity: NoRepeatNGramLogitsProcessor(20) bans the continuation of a repeated 20-gram, nothing on a fresh row
    nr = NoRepeatNGramLogitsProcessor(NGRAM)
    unit5 = [800, 801, 802, 803, 804]
    row = torch.tensor([[0] * 5 + unit5 * 5], dtype=torch.long)     # 25 generated tokens, period 5
    o = nr(row, torch.zeros((1, vocab)))
    banned = torch.nonzero(torch.isinf(o[0])).flatten().tolist()
    fresh = nr(torch.tensor([[0] * 5 + list(range(900, 925))], dtype=torch.long), torch.zeros((1, vocab)))
    C["ngram20_bans_next_unit_token_on_period5_row"] = banned == [unit5[0]]
    C["ngram20_bans_nothing_on_fresh_row"] = not bool(torch.isinf(fresh).any())

    rep["passed"] = all(bool(v) for v in C.values())
    rep["seconds"] = round(time.time() - t0, 1)
    rep["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    with open(a.out, "w", encoding="utf-8") as f:
        json.dump(rep, f, indent=1, ensure_ascii=False)
    print(json.dumps({"passed": rep["passed"], "failed": [k for k, v in C.items() if not v], "references": ref,
                      "stored": {s: {k: v for k, v in x.items() if k in ("fired", "fire_reasons_first")} for s, x in out_pages.items()},
                      "seconds": rep["seconds"]}, indent=1))
    return 0 if rep["passed"] else 2


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--tokenizer-dir", default="/path/to/TURKIC_OCR_DATA/checkpoints/r6_onemodel/seed1/final")
    ap.add_argument("--records-root", default="/path/to/TURKIC_OCR_DATA/data/processed/r6_onemodel/records")
    ap.add_argument("--preds-root", default="/path/to/TURKIC_OCR_DATA/outputs/r6_onemodel/page_preds/seed1_final")
    ap.add_argument("--final-rule", required=False, default="")
    ap.add_argument("--out", default="selftest.json")
    a = ap.parse_args()
    if not a.selftest:
        sys.exit("nothing to do (use --selftest)")
    sys.exit(selftest(a))